<commit_before>// 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
#include "wx/bookctrl.h"
////@end includes

#include "rowsselectiondialog.h"
#include "labelconstructor.h"
#include "gtimeline.h"
#include "window.h"

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

/*!
 * RowsSelectionDialog type definition
 */

IMPLEMENT_DYNAMIC_CLASS( RowsSelectionDialog, wxPropertySheetDialog )

/*!
 * RowsSelectionDialog event table definition
 */

BEGIN_EVENT_TABLE( RowsSelectionDialog, wxPropertySheetDialog )
EVT_BUTTON( wxID_OK, RowsSelectionDialog::OnOkClick )
END_EVENT_TABLE()

/*!
 * RowsSelectionDialog constructors
 */

RowsSelectionDialog::RowsSelectionDialog()
{
  Init();
}

void RowsSelectionDialog::OnSelectAllButtonClicked( wxCommandEvent& event )
{
  wxCheckListBox * myLevelCheckList = levelCheckList[ GetBookCtrl()->GetSelection() ];

  for ( unsigned int i = 0; i < myLevelCheckList->GetCount(); ++i )
    myLevelCheckList->Check( i );
}

void RowsSelectionDialog::OnUnselectAllButtonClicked( wxCommandEvent& event )
{
  wxCheckListBox * myLevelCheckList = levelCheckList[ GetBookCtrl()->GetSelection() ];

  for ( unsigned int i = 0; i < myLevelCheckList->GetCount(); ++i )
    myLevelCheckList->Check( i, false );
}

void RowsSelectionDialog::OnInvertButtonClicked( wxCommandEvent& event )
{
  wxCheckListBox * myLevelCheckList = levelCheckList[ GetBookCtrl()->GetSelection() ];

  for ( unsigned int i = 0; i < myLevelCheckList->GetCount(); ++i )
    myLevelCheckList->Check( i, !myLevelCheckList->IsChecked( i ) );
}

void RowsSelectionDialog::buildPanel( const wxString& title,
                                      TWindowLevel whichLevel )
{
  wxPanel *myPanel;

  myPanel = new wxPanel( GetBookCtrl(),
                         wxID_ANY,
                         wxDefaultPosition,
                         wxDefaultSize,
                         wxSUNKEN_BORDER | wxTAB_TRAVERSAL );

  GetBookCtrl()->AddPage( myPanel, title, whichLevel == myTimeline->getLevel() );

  wxBoxSizer *panelSizer = new wxBoxSizer( wxVERTICAL );
  wxBoxSizer *buttonsSizer = new wxBoxSizer( wxHORIZONTAL );

  myPanel->SetSizer( panelSizer );

  // Add Checklist lines
  wxArrayString choices;
  Trace *myTrace = myTimeline->getTrace();
  for ( size_t row = (size_t)0; row < myTrace->getLevelObjects( whichLevel ); ++row )
  {
    if( myTimeline->getLevel() == CPU )
      choices.Add( wxString::FromAscii( LabelConstructor::objectLabel( (TObjectOrder)row + 1,
                                                                       whichLevel,
                                                                       myTrace ).c_str() ) );
    else
      choices.Add( wxString::FromAscii( LabelConstructor::objectLabel( (TObjectOrder)row,
                                                                       whichLevel,
                                                                       myTrace ).c_str() ) );
  }

  vector< TObjectOrder > selectedIndex;
  mySelectedRows->getSelected( selectedIndex, whichLevel );
  wxCheckListBox * auxCheckList = new wxCheckListBox( myPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, choices );
  levelCheckList.push_back( auxCheckList );

  for ( unsigned int i = 0; i < (unsigned int)selectedIndex.size(); ++i )
    auxCheckList->Check( selectedIndex[ i ] );

  panelSizer->Add( auxCheckList, 3, wxALL | wxALIGN_CENTER | wxGROW, 5 );

  // Add Buttons
  wxButton *auxButton = new wxButton( myPanel, wxID_ANY, _("Select All") );
  selectionButtons.push_back( auxButton );
  auxButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED,
                      wxCommandEventHandler( RowsSelectionDialog:: OnSelectAllButtonClicked ),
                      NULL,
                      this );
  buttonsSizer->Add( auxButton, 1, wxGROW | wxALIGN_BOTTOM | wxALL, 5 );

  auxButton = new wxButton( myPanel, wxID_ANY, _("Unselect All") );
  selectionButtons.push_back( auxButton );
  auxButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED,
                      wxCommandEventHandler( RowsSelectionDialog::OnUnselectAllButtonClicked ),
                      NULL,
                      this );
  buttonsSizer->Add( auxButton, 1, wxGROW | wxALIGN_BOTTOM | wxALL, 5 );

  auxButton = new wxButton( myPanel, wxID_ANY, _("Invert") );
  selectionButtons.push_back( auxButton );
  auxButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED,
                      wxCommandEventHandler( RowsSelectionDialog::OnInvertButtonClicked ),
                      NULL,
                      this );
  buttonsSizer->Add( auxButton, 1, wxGROW | wxALIGN_BOTTOM | wxALL, 5 );

  // Build Panel
  panelSizer->Add( buttonsSizer, 0, wxALL | wxALIGN_BOTTOM, 5 );
}

RowsSelectionDialog::RowsSelectionDialog( wxWindow* parent,
                                          Window *whichTimeline,
                                          SelectionManagement< TObjectOrder, TWindowLevel > *whichSelectedRows,
                                          wxWindowID id,
                                          const wxString& caption,
                                          const wxPoint& pos,
                                          const wxSize& size,
                                          long style )
{
  myTimeline = whichTimeline;
  mySelectedRows = whichSelectedRows;

  Init();
  Create( parent, id, caption, pos, size, style );

  TWindowLevel level = myTimeline->getLevel();

  if (( level >= SYSTEM ) && ( level <= CPU ))
  {
    minLevel = NODE;
    buildPanel( _("Node"), NODE );
    buildPanel( _("CPU"), CPU );
  }
  else if (( level >= WORKLOAD ) && ( level <= THREAD ))
  {
    minLevel = APPLICATION;
    buildPanel( _("Application"), APPLICATION );
    buildPanel( _("Task"), TASK );
    buildPanel( _("Thread"), THREAD );
  }

  LayoutDialog();
  Centre();
}

/*!
 * RowsSelectionDialog creator
 */

bool RowsSelectionDialog::Create( wxWindow* parent,
                                  wxWindowID id,
                                  const wxString& caption,
                                  const wxPoint& pos,
                                  const wxSize& size,
                                  long style )
{
  SetExtraStyle( wxWS_EX_VALIDATE_RECURSIVELY | wxWS_EX_BLOCK_EVENTS );
  SetSheetStyle( wxPROPSHEET_DEFAULT );
  wxPropertySheetDialog::Create( parent, id, caption, pos, size, style );

  CreateButtons( wxOK | wxCANCEL );
  CreateControls();
  LayoutDialog();
  Centre();

  return true;
}

/*!
 * RowsSelectionDialog destructor
 */

RowsSelectionDialog::~RowsSelectionDialog()
{
  for ( vector< wxButton * >::iterator it = selectionButtons.begin(); it != selectionButtons.end(); ++it )
  {
    (*it)->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED,
                       wxCommandEventHandler( RowsSelectionDialog::OnSelectAllButtonClicked ));
    ++it;
    (*it)->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED,
                       wxCommandEventHandler( RowsSelectionDialog::OnUnselectAllButtonClicked ));
    ++it;
    (*it)->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED,
                       wxCommandEventHandler( RowsSelectionDialog::OnInvertButtonClicked ));
  }
}

/*!
 * Member initialisation
 */

void RowsSelectionDialog::Init()
{
}

/*!
 * Control creation for RowsSelectionDialog
 */

void RowsSelectionDialog::CreateControls()
{
}

/*!
 * Should we show tooltips?
 */

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

/*!
 * Get bitmap resources
 */

wxBitmap RowsSelectionDialog::GetBitmapResource( const wxString& name )
{
  // Bitmap retrieval
  wxUnusedVar(name);
  return wxNullBitmap;
}

/*!
 * Get icon resources
 */

wxIcon RowsSelectionDialog::GetIconResource( const wxString& name )
{
  // Icon retrieval
  wxUnusedVar(name);
  return wxNullIcon;
}

int RowsSelectionDialog::GetSelections( TWindowLevel whichLevel, wxArrayInt &selections )
{
  int selected = 0;

  for ( unsigned int i = 0; i < levelCheckList[ whichLevel - minLevel ]->GetCount(); ++i )
  {
    if ( levelCheckList[ whichLevel - minLevel ]->IsChecked( i ) )
    {
      ++selected;
      selections.Add( i );
    }
  }

  return selected;
}

void RowsSelectionDialog::OnOkClick( wxCommandEvent& event )
{
  TWindowLevel beginLevel;
  TWindowLevel endLevel;

  // Set range of levels for update loop
  if (( myTimeline->getLevel() >= WORKLOAD ) && ( myTimeline->getLevel() <= THREAD ))
  {
    beginLevel = APPLICATION;
    endLevel = THREAD;
  }
  else
  {
    beginLevel = NODE;
    endLevel = CPU;
  }

  // Loop through levels to update gTimeline
  for ( TWindowLevel whichLevel = beginLevel; whichLevel <= endLevel; whichLevel = TWindowLevel(whichLevel + 1) )
  {
    wxArrayInt selections;
    int numberSelected = GetSelections( whichLevel, selections );
    if ( numberSelected > 0 )
    {
      // Get new selections for that level
      vector< TObjectOrder > newSelection;
      for ( size_t row = (size_t)0; row < (size_t)numberSelected; row++ )
      {
        newSelection.push_back( (TObjectOrder)selections[ row ] );
      }
      mySelectedRows->setSelected( newSelection,
                                   myTimeline->getTrace()->getLevelObjects( whichLevel ),
                                   whichLevel );
    }
  }

  if ( TransferDataFromWindow() )
    EndModal( wxID_OK );
}
<commit_msg>*** empty log message ***<commit_after>// 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
#include "wx/bookctrl.h"
////@end includes

#include "rowsselectiondialog.h"
#include "labelconstructor.h"
#include "gtimeline.h"
#include "window.h"

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

/*!
 * RowsSelectionDialog type definition
 */

IMPLEMENT_DYNAMIC_CLASS( RowsSelectionDialog, wxPropertySheetDialog )

/*!
 * RowsSelectionDialog event table definition
 */

BEGIN_EVENT_TABLE( RowsSelectionDialog, wxPropertySheetDialog )
EVT_BUTTON( wxID_OK, RowsSelectionDialog::OnOkClick )
END_EVENT_TABLE()

/*!
 * RowsSelectionDialog constructors
 */

RowsSelectionDialog::RowsSelectionDialog()
{
  Init();
}

void RowsSelectionDialog::OnSelectAllButtonClicked( wxCommandEvent& event )
{
  wxCheckListBox * myLevelCheckList = levelCheckList[ GetBookCtrl()->GetSelection() ];

  for ( unsigned int i = 0; i < myLevelCheckList->GetCount(); ++i )
    myLevelCheckList->Check( i );
}

void RowsSelectionDialog::OnUnselectAllButtonClicked( wxCommandEvent& event )
{
  wxCheckListBox * myLevelCheckList = levelCheckList[ GetBookCtrl()->GetSelection() ];

  for ( unsigned int i = 0; i < myLevelCheckList->GetCount(); ++i )
    myLevelCheckList->Check( i, false );
}

void RowsSelectionDialog::OnInvertButtonClicked( wxCommandEvent& event )
{
  wxCheckListBox * myLevelCheckList = levelCheckList[ GetBookCtrl()->GetSelection() ];

  for ( unsigned int i = 0; i < myLevelCheckList->GetCount(); ++i )
    myLevelCheckList->Check( i, !myLevelCheckList->IsChecked( i ) );
}

void RowsSelectionDialog::buildPanel( const wxString& title,
                                      TWindowLevel whichLevel )
{
  wxPanel *myPanel;

  myPanel = new wxPanel( GetBookCtrl(),
                         wxID_ANY,
                         wxDefaultPosition,
                         wxDefaultSize,
                         wxSUNKEN_BORDER | wxTAB_TRAVERSAL );

  GetBookCtrl()->AddPage( myPanel, title, whichLevel == myTimeline->getLevel() );

  wxBoxSizer *panelSizer = new wxBoxSizer( wxVERTICAL );
  wxBoxSizer *buttonsSizer = new wxBoxSizer( wxHORIZONTAL );

  myPanel->SetSizer( panelSizer );

  // Add Checklist lines
  wxArrayString choices;
  Trace *myTrace = myTimeline->getTrace();
  for ( size_t row = (size_t)0; row < myTrace->getLevelObjects( whichLevel ); ++row )
  {
    if( whichLevel == CPU )
      choices.Add( wxString::FromAscii( LabelConstructor::objectLabel( (TObjectOrder)row + 1,
                                                                       whichLevel,
                                                                       myTrace ).c_str() ) );
    else
      choices.Add( wxString::FromAscii( LabelConstructor::objectLabel( (TObjectOrder)row,
                                                                       whichLevel,
                                                                       myTrace ).c_str() ) );
  }

  vector< TObjectOrder > selectedIndex;
  mySelectedRows->getSelected( selectedIndex, whichLevel );
  wxCheckListBox * auxCheckList = new wxCheckListBox( myPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, choices );
  levelCheckList.push_back( auxCheckList );

  for ( unsigned int i = 0; i < (unsigned int)selectedIndex.size(); ++i )
    auxCheckList->Check( selectedIndex[ i ] );

  panelSizer->Add( auxCheckList, 3, wxALL | wxALIGN_CENTER | wxGROW, 5 );

  // Add Buttons
  wxButton *auxButton = new wxButton( myPanel, wxID_ANY, _("Select All") );
  selectionButtons.push_back( auxButton );
  auxButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED,
                      wxCommandEventHandler( RowsSelectionDialog:: OnSelectAllButtonClicked ),
                      NULL,
                      this );
  buttonsSizer->Add( auxButton, 1, wxGROW | wxALIGN_BOTTOM | wxALL, 5 );

  auxButton = new wxButton( myPanel, wxID_ANY, _("Unselect All") );
  selectionButtons.push_back( auxButton );
  auxButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED,
                      wxCommandEventHandler( RowsSelectionDialog::OnUnselectAllButtonClicked ),
                      NULL,
                      this );
  buttonsSizer->Add( auxButton, 1, wxGROW | wxALIGN_BOTTOM | wxALL, 5 );

  auxButton = new wxButton( myPanel, wxID_ANY, _("Invert") );
  selectionButtons.push_back( auxButton );
  auxButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED,
                      wxCommandEventHandler( RowsSelectionDialog::OnInvertButtonClicked ),
                      NULL,
                      this );
  buttonsSizer->Add( auxButton, 1, wxGROW | wxALIGN_BOTTOM | wxALL, 5 );

  // Build Panel
  panelSizer->Add( buttonsSizer, 0, wxALL | wxALIGN_BOTTOM, 5 );
}

RowsSelectionDialog::RowsSelectionDialog( wxWindow* parent,
                                          Window *whichTimeline,
                                          SelectionManagement< TObjectOrder, TWindowLevel > *whichSelectedRows,
                                          wxWindowID id,
                                          const wxString& caption,
                                          const wxPoint& pos,
                                          const wxSize& size,
                                          long style )
{
  myTimeline = whichTimeline;
  mySelectedRows = whichSelectedRows;

  Init();
  Create( parent, id, caption, pos, size, style );

  TWindowLevel level = myTimeline->getLevel();

  if (( level >= SYSTEM ) && ( level <= CPU ))
  {
    minLevel = NODE;
    buildPanel( _("Node"), NODE );
    buildPanel( _("CPU"), CPU );
  }
  else if (( level >= WORKLOAD ) && ( level <= THREAD ))
  {
    minLevel = APPLICATION;
    buildPanel( _("Application"), APPLICATION );
    buildPanel( _("Task"), TASK );
    buildPanel( _("Thread"), THREAD );
  }

  LayoutDialog();
  Centre();
}

/*!
 * RowsSelectionDialog creator
 */

bool RowsSelectionDialog::Create( wxWindow* parent,
                                  wxWindowID id,
                                  const wxString& caption,
                                  const wxPoint& pos,
                                  const wxSize& size,
                                  long style )
{
  SetExtraStyle( wxWS_EX_VALIDATE_RECURSIVELY | wxWS_EX_BLOCK_EVENTS );
  SetSheetStyle( wxPROPSHEET_DEFAULT );
  wxPropertySheetDialog::Create( parent, id, caption, pos, size, style );

  CreateButtons( wxOK | wxCANCEL );
  CreateControls();
  LayoutDialog();
  Centre();

  return true;
}

/*!
 * RowsSelectionDialog destructor
 */

RowsSelectionDialog::~RowsSelectionDialog()
{
  for ( vector< wxButton * >::iterator it = selectionButtons.begin(); it != selectionButtons.end(); ++it )
  {
    (*it)->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED,
                       wxCommandEventHandler( RowsSelectionDialog::OnSelectAllButtonClicked ));
    ++it;
    (*it)->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED,
                       wxCommandEventHandler( RowsSelectionDialog::OnUnselectAllButtonClicked ));
    ++it;
    (*it)->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED,
                       wxCommandEventHandler( RowsSelectionDialog::OnInvertButtonClicked ));
  }
}

/*!
 * Member initialisation
 */

void RowsSelectionDialog::Init()
{
}

/*!
 * Control creation for RowsSelectionDialog
 */

void RowsSelectionDialog::CreateControls()
{
}

/*!
 * Should we show tooltips?
 */

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

/*!
 * Get bitmap resources
 */

wxBitmap RowsSelectionDialog::GetBitmapResource( const wxString& name )
{
  // Bitmap retrieval
  wxUnusedVar(name);
  return wxNullBitmap;
}

/*!
 * Get icon resources
 */

wxIcon RowsSelectionDialog::GetIconResource( const wxString& name )
{
  // Icon retrieval
  wxUnusedVar(name);
  return wxNullIcon;
}

int RowsSelectionDialog::GetSelections( TWindowLevel whichLevel, wxArrayInt &selections )
{
  int selected = 0;

  for ( unsigned int i = 0; i < levelCheckList[ whichLevel - minLevel ]->GetCount(); ++i )
  {
    if ( levelCheckList[ whichLevel - minLevel ]->IsChecked( i ) )
    {
      ++selected;
      selections.Add( i );
    }
  }

  return selected;
}

void RowsSelectionDialog::OnOkClick( wxCommandEvent& event )
{
  TWindowLevel beginLevel;
  TWindowLevel endLevel;

  // Set range of levels for update loop
  if (( myTimeline->getLevel() >= WORKLOAD ) && ( myTimeline->getLevel() <= THREAD ))
  {
    beginLevel = APPLICATION;
    endLevel = THREAD;
  }
  else
  {
    beginLevel = NODE;
    endLevel = CPU;
  }

  // Loop through levels to update gTimeline
  for ( TWindowLevel whichLevel = beginLevel; whichLevel <= endLevel; whichLevel = TWindowLevel(whichLevel + 1) )
  {
    wxArrayInt selections;
    int numberSelected = GetSelections( whichLevel, selections );
    if ( numberSelected > 0 )
    {
      // Get new selections for that level
      vector< TObjectOrder > newSelection;
      for ( size_t row = (size_t)0; row < (size_t)numberSelected; row++ )
      {
        newSelection.push_back( (TObjectOrder)selections[ row ] );
      }
      mySelectedRows->setSelected( newSelection,
                                   myTimeline->getTrace()->getLevelObjects( whichLevel ),
                                   whichLevel );
    }
  }

  if ( TransferDataFromWindow() )
    EndModal( wxID_OK );
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016, Ford Motor Company
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following
 * disclaimer in the documentation and/or other materials provided with the
 * distribution.
 *
 * Neither the name of the Ford Motor Company nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "gtest/gtest.h"
#include "application_manager/commands/hmi/activate_app_request.h"
#include "utils/shared_ptr.h"
#include "smart_objects/smart_object.h"
#include "application_manager/commands/command_impl.h"
#include "commands/commands_test.h"

namespace test {
namespace components {
namespace commands_test {
namespace hmi_commands_test {
namespace activate_app_request {

using ::testing::_;
namespace am = ::application_manager;
namespace strings = ::application_manager::strings;
using am::commands::MessageSharedPtr;
using am::commands::ActivateAppRequest;
using am::commands::CommandImpl;

typedef ::utils::SharedPtr<ActivateAppRequest> ActivateAppRequestPtr;

MATCHER_P(CheckMessage, level, "") {
  return level ==
         static_cast<mobile_apis::HMILevel::eType>(
             (*arg)[strings::msg_params][strings::activate_app_hmi_level]
                 .asInt());
}

namespace {
const uint32_t kAppId = 1u;
const uint32_t kCorrelationId = 2u;
}  // namespace

class ActivateAppRequestTest : public CommandsTest<CommandsTestMocks::kIsNice> {
 public:
  MessageSharedPtr CreateMsgParams() {
    MessageSharedPtr msg = CreateMessage(smart_objects::SmartType_Map);
    smart_objects::SmartObject msg_params =
        smart_objects::SmartObject(smart_objects::SmartType_Map);
    msg_params[strings::app_id] = kAppId;
    msg_params[strings::correlation_id] = kCorrelationId;
    (*msg)[strings::msg_params] = msg_params;
    (*msg)[strings::params][strings::app_id] = kAppId;
    (*msg)[strings::params][strings::correlation_id] = kCorrelationId;
    (*msg)[strings::app_id] = kAppId;
    return msg;
  }
};

TEST_F(ActivateAppRequestTest, Run_SUCCESS) {
  MessageSharedPtr msg = CreateMsgParams();

// TODO(OKozlov) Invastigate and fix issue with using log
#ifdef ENABLE_LOG
  (*msg)[strings::msg_params][strings::activate_app_hmi_level] =
      mobile_apis::HMILevel::HMI_FULL;
#endif
  ActivateAppRequestPtr command(CreateCommand<ActivateAppRequest>(msg));

  EXPECT_CALL(app_mngr_, set_application_id(kCorrelationId, kAppId));
#ifdef ENABLE_LOG
  EXPECT_CALL(app_mngr_,
              SendMessageToHMI(CheckMessage(mobile_apis::HMILevel::HMI_FULL)));
#else
  EXPECT_CALL(app_mngr_,
              SendMessageToHMI(msg)));
#endif
  command->Run();

#ifndef ENABLE_LOG
  EXPECT_EQ(CommandImpl::hmi_protocol_type_,
            (*msg)[strings::params][strings::protocol_type].asInt());
  EXPECT_EQ(CommandImpl::protocol_version_,
            (*msg)[strings::params][strings::protocol_version].asInt());
#endif
}

}  // namespace activate_app_request
}  // namespace hmi_commands_test
}  // namespace commands_test
}  // namespace components
}  // namespace test
<commit_msg>Fix UT for activate_app_request<commit_after>/*
 * Copyright (c) 2016, Ford Motor Company
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following
 * disclaimer in the documentation and/or other materials provided with the
 * distribution.
 *
 * Neither the name of the Ford Motor Company nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "gtest/gtest.h"
#include "application_manager/commands/hmi/activate_app_request.h"
#include "utils/shared_ptr.h"
#include "smart_objects/smart_object.h"
#include "application_manager/commands/command_impl.h"
#include "commands/commands_test.h"
#include "application_manager/mock_application.h"

namespace test {
namespace components {
namespace commands_test {
namespace hmi_commands_test {
namespace activate_app_request {

using ::testing::_;
using ::utils::SharedPtr;
namespace am = ::application_manager;
namespace strings = ::application_manager::strings;
using am::commands::MessageSharedPtr;
using am::commands::ActivateAppRequest;
using am::commands::CommandImpl;

using ::test::components::application_manager_test::MockApplication;

typedef SharedPtr<MockApplication> MockAppPtr;
typedef ::utils::SharedPtr<ActivateAppRequest> ActivateAppRequestPtr;

MATCHER_P(CheckMessage, level, "") {
  return level ==
         static_cast<mobile_apis::HMILevel::eType>(
             (*arg)[strings::msg_params][strings::activate_app_hmi_level]
                 .asInt());
}

namespace {
const uint32_t kAppId = 1u;
const uint32_t kCorrelationId = 2u;
}  // namespace

class ActivateAppRequestTest : public CommandsTest<CommandsTestMocks::kIsNice> {
 public:
  MessageSharedPtr CreateMsgParams() {
    MessageSharedPtr msg = CreateMessage(smart_objects::SmartType_Map);
    smart_objects::SmartObject msg_params =
        smart_objects::SmartObject(smart_objects::SmartType_Map);
    msg_params[strings::app_id] = kAppId;
    msg_params[strings::correlation_id] = kCorrelationId;
    (*msg)[strings::msg_params] = msg_params;
    (*msg)[strings::params][strings::app_id] = kAppId;
    (*msg)[strings::params][strings::correlation_id] = kCorrelationId;
    (*msg)[strings::app_id] = kAppId;
    return msg;
  }
};

TEST_F(ActivateAppRequestTest, Run_SUCCESS) {
  MessageSharedPtr msg = CreateMsgParams();
  MockAppPtr app = CreateMockApp();

  EXPECT_CALL(app_mngr_, application(_)).WillRepeatedly(Return(app));

  ON_CALL(*app, hmi_app_id()).WillByDefault(Return(kAppId));

// TODO(OKozlov) Investigate and fix issue with using log
#ifdef ENABLE_LOG
  (*msg)[strings::msg_params][strings::activate_app_hmi_level] =
      mobile_apis::HMILevel::HMI_FULL;
#endif
  ActivateAppRequestPtr command(CreateCommand<ActivateAppRequest>(msg));

  EXPECT_CALL(app_mngr_, set_application_id(kCorrelationId, kAppId));
#ifdef ENABLE_LOG
  EXPECT_CALL(app_mngr_,
              SendMessageToHMI(CheckMessage(mobile_apis::HMILevel::HMI_FULL)));
#else
  EXPECT_CALL(app_mngr_,
              SendMessageToHMI(msg)));
#endif
  command->Run();

#ifndef ENABLE_LOG
  EXPECT_EQ(CommandImpl::hmi_protocol_type_,
            (*msg)[strings::params][strings::protocol_type].asInt());
  EXPECT_EQ(CommandImpl::protocol_version_,
            (*msg)[strings::params][strings::protocol_version].asInt());
#endif
}

}  // namespace activate_app_request
}  // namespace hmi_commands_test
}  // namespace commands_test
}  // namespace components
}  // namespace test
<|endoftext|>


<commit_before>/*!
    \class QGraphicsSceneLinearIndex
    \brief The QGraphicsSceneLinearIndex class provides an implementation of
    a linear indexing algorithm for discovering items in QGraphicsScene.
    \since 4.6
    \ingroup multimedia
    \ingroup graphicsview-api
    \mainclass
    \internal

    QGraphicsSceneLinearIndex index is default linear implementation to discover items.
    It basically store all items in a list and return them to the scene.

    \sa QGraphicsScene, QGraphicsView, QGraphicsSceneIndex, QGraphicsSceneBspTreeIndex
*/

#include <private/qgraphicsscenelinearindex_p.h>

/*!
    \fn QGraphicsSceneLinearIndex::QGraphicsSceneLinearIndex(QGraphicsScene *scene = 0):

    Construct a linear index for the given \a scene.
*/

/*!
    \fn QList<QGraphicsItem *> QGraphicsSceneLinearIndex::items(Qt::SortOrder order = Qt::AscendingOrder) const;

    Return all items in the index and sort them using \a order.
*/

/*!
    \fn virtual QList<QGraphicsItem *> QGraphicsSceneLinearIndex::estimateItems(const QRectF &rect, Qt::SortOrder order) const;

    Returns an estimation visible items that are either inside or
    intersect with the specified \a rect and return a list sorted using \a order.
*/

/*!
    \fn QRectF QGraphicsSceneLinearIndex::indexedRect() const;
    \reimp
    Return the rect indexed by the the index.
*/

/*!
    \fn void QGraphicsSceneLinearIndex::clear();
    \reimp
    Clear the all the BSP index.
*/

/*!
    \fn virtual void QGraphicsSceneLinearIndex::addItem(QGraphicsItem *item);

    Add the \a item into the index.
*/

/*!
    \fn virtual void QGraphicsSceneLinearIndex::removeItem(QGraphicsItem *item);

    Add the \a item from the index.
*/

<commit_msg>With license it's better.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/

/*!
    \class QGraphicsSceneLinearIndex
    \brief The QGraphicsSceneLinearIndex class provides an implementation of
    a linear indexing algorithm for discovering items in QGraphicsScene.
    \since 4.6
    \ingroup multimedia
    \ingroup graphicsview-api
    \mainclass
    \internal

    QGraphicsSceneLinearIndex index is default linear implementation to discover items.
    It basically store all items in a list and return them to the scene.

    \sa QGraphicsScene, QGraphicsView, QGraphicsSceneIndex, QGraphicsSceneBspTreeIndex
*/

#include <private/qgraphicsscenelinearindex_p.h>

/*!
    \fn QGraphicsSceneLinearIndex::QGraphicsSceneLinearIndex(QGraphicsScene *scene = 0):

    Construct a linear index for the given \a scene.
*/

/*!
    \fn QList<QGraphicsItem *> QGraphicsSceneLinearIndex::items(Qt::SortOrder order = Qt::AscendingOrder) const;

    Return all items in the index and sort them using \a order.
*/

/*!
    \fn virtual QList<QGraphicsItem *> QGraphicsSceneLinearIndex::estimateItems(const QRectF &rect, Qt::SortOrder order) const;

    Returns an estimation visible items that are either inside or
    intersect with the specified \a rect and return a list sorted using \a order.
*/

/*!
    \fn QRectF QGraphicsSceneLinearIndex::indexedRect() const;
    \reimp
    Return the rect indexed by the the index.
*/

/*!
    \fn void QGraphicsSceneLinearIndex::clear();
    \reimp
    Clear the all the BSP index.
*/

/*!
    \fn virtual void QGraphicsSceneLinearIndex::addItem(QGraphicsItem *item);

    Add the \a item into the index.
*/

/*!
    \fn virtual void QGraphicsSceneLinearIndex::removeItem(QGraphicsItem *item);

    Add the \a item from the index.
*/

<|endoftext|>


<commit_before>#include "master.hpp"

namespace factor
{

THREADHANDLE start_thread(void *(*start_routine)(void *),void *args)
{
	pthread_attr_t attr;
	pthread_t thread;
	if (pthread_attr_init (&attr) != 0)
		fatal_error("pthread_attr_init() failed",0);
	if (pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_JOINABLE) != 0)
		fatal_error("pthread_attr_setdetachstate() failed",0);
	if (pthread_create (&thread, &attr, start_routine, args) != 0)
		fatal_error("pthread_create() failed",0);
	pthread_attr_destroy(&attr);
	return thread;
}

static void *null_dll;

void sleep_nanos(u64 nsec)
{
	timespec ts;
	timespec ts_rem;
	int ret;
	ts.tv_sec = nsec / 1000000000;
	ts.tv_nsec = nsec % 1000000000;
	ret = nanosleep(&ts,&ts_rem);
	while(ret == -1 && errno == EINTR)
	{
		memcpy(&ts, &ts_rem, sizeof(ts));
		ret = nanosleep(&ts, &ts_rem);
	}

	if(ret == -1)
		fatal_error("nanosleep failed", 0);
}

void factor_vm::init_ffi()
{
	null_dll = dlopen(NULL,RTLD_LAZY);
}

void factor_vm::ffi_dlopen(dll *dll)
{
	dll->handle = dlopen(alien_offset(dll->path), RTLD_LAZY);
}

void *factor_vm::ffi_dlsym(dll *dll, symbol_char *symbol)
{
	void *handle = (dll == NULL ? null_dll : dll->handle);
	return dlsym(handle,symbol);
}

void factor_vm::ffi_dlclose(dll *dll)
{
	if(dlclose(dll->handle))
		general_error(ERROR_FFI,false_object,false_object);
	dll->handle = NULL;
}

void factor_vm::primitive_existsp()
{
	struct stat sb;
	char *path = (char *)(untag_check<byte_array>(ctx->pop()) + 1);
	ctx->push(tag_boolean(stat(path,&sb) >= 0));
}

void factor_vm::move_file(const vm_char *path1, const vm_char *path2)
{
	int ret = 0;
	do
	{
		ret = rename((path1),(path2));
	}
	while(ret < 0 && errno == EINTR);

	if(ret < 0)
		general_error(ERROR_IO,tag_fixnum(errno),false_object);
}

segment::segment(cell size_, bool executable_p)
{
	size = size_;

	int pagesize = getpagesize();

	int prot;
	if(executable_p)
		prot = (PROT_READ | PROT_WRITE | PROT_EXEC);
	else
		prot = (PROT_READ | PROT_WRITE);

	char *array = (char *)mmap(NULL,pagesize + size + pagesize,prot,MAP_ANON | MAP_PRIVATE,-1,0);
	if(array == (char*)-1) out_of_memory();

	if(mprotect(array,pagesize,PROT_NONE) == -1)
		fatal_error("Cannot protect low guard page",(cell)array);

	if(mprotect(array + pagesize + size,pagesize,PROT_NONE) == -1)
		fatal_error("Cannot protect high guard page",(cell)array);

	start = (cell)(array + pagesize);
	end = start + size;
}

segment::~segment()
{
	int pagesize = getpagesize();
	int retval = munmap((void*)(start - pagesize),pagesize + size + pagesize);
	if(retval)
		fatal_error("Segment deallocation failed",0);
}

void factor_vm::dispatch_signal(void *uap, void (handler)())
{
	UAP_STACK_POINTER(uap) = (UAP_STACK_POINTER_TYPE)fix_callstack_top((stack_frame *)UAP_STACK_POINTER(uap));
	UAP_PROGRAM_COUNTER(uap) = (cell)handler;

	ctx->callstack_top = (stack_frame *)UAP_STACK_POINTER(uap);
}

void memory_signal_handler(int signal, siginfo_t *siginfo, void *uap)
{
	factor_vm *vm = current_vm();
	vm->signal_fault_addr = (cell)siginfo->si_addr;
	vm->dispatch_signal(uap,factor::memory_signal_handler_impl);
}

void misc_signal_handler(int signal, siginfo_t *siginfo, void *uap)
{
	factor_vm *vm = current_vm();
	vm->signal_number = signal;
	vm->dispatch_signal(uap,factor::misc_signal_handler_impl);
}

void ignore_signal_handler(int signal, siginfo_t *siginfo, void *uap)
{
}

void fpe_signal_handler(int signal, siginfo_t *siginfo, void *uap)
{
	factor_vm *vm = current_vm();
	vm->signal_number = signal;
	vm->signal_fpu_status = fpu_status(uap_fpu_status(uap));
	uap_clear_fpu_status(uap);

	vm->dispatch_signal(uap,
		(siginfo->si_code == FPE_INTDIV || siginfo->si_code == FPE_INTOVF)
		? factor::misc_signal_handler_impl
		: factor::fp_signal_handler_impl);
}

static void sigaction_safe(int signum, const struct sigaction *act, struct sigaction *oldact)
{
	int ret;
	do
	{
		ret = sigaction(signum, act, oldact);
	}
	while(ret == -1 && errno == EINTR);

	if(ret == -1)
		fatal_error("sigaction failed", 0);
}

void factor_vm::unix_init_signals()
{
	/* OpenBSD doesn't support sigaltstack() if we link against
	libpthread. See http://redmine.ruby-lang.org/issues/show/1239 */

#ifndef __OpenBSD__
	signal_callstack_seg = new segment(callstack_size,false);

	stack_t signal_callstack;
	signal_callstack.ss_sp = (char *)signal_callstack_seg->start;
	signal_callstack.ss_size = signal_callstack_seg->size;
	signal_callstack.ss_flags = 0;

	if(sigaltstack(&signal_callstack,(stack_t *)NULL) < 0)
		fatal_error("sigaltstack() failed",0);
#endif

	struct sigaction memory_sigaction;
	struct sigaction misc_sigaction;
	struct sigaction fpe_sigaction;
	struct sigaction ignore_sigaction;

	memset(&memory_sigaction,0,sizeof(struct sigaction));
	sigemptyset(&memory_sigaction.sa_mask);
	memory_sigaction.sa_sigaction = memory_signal_handler;
	memory_sigaction.sa_flags = SA_SIGINFO | SA_ONSTACK;

	sigaction_safe(SIGBUS,&memory_sigaction,NULL);
	sigaction_safe(SIGSEGV,&memory_sigaction,NULL);

	memset(&fpe_sigaction,0,sizeof(struct sigaction));
	sigemptyset(&fpe_sigaction.sa_mask);
	fpe_sigaction.sa_sigaction = fpe_signal_handler;
	fpe_sigaction.sa_flags = SA_SIGINFO | SA_ONSTACK;

	sigaction_safe(SIGFPE,&fpe_sigaction,NULL);

	memset(&misc_sigaction,0,sizeof(struct sigaction));
	sigemptyset(&misc_sigaction.sa_mask);
	misc_sigaction.sa_sigaction = misc_signal_handler;
	misc_sigaction.sa_flags = SA_SIGINFO | SA_ONSTACK;

	sigaction_safe(SIGQUIT,&misc_sigaction,NULL);
	sigaction_safe(SIGILL,&misc_sigaction,NULL);

	/* We don't use SA_IGN here because then the ignore action is inherited
	by subprocesses, which we don't want. There is a unit test in
	io.launcher.unix for this. */
	memset(&ignore_sigaction,0,sizeof(struct sigaction));
	sigemptyset(&ignore_sigaction.sa_mask);
	ignore_sigaction.sa_sigaction = ignore_signal_handler;
	ignore_sigaction.sa_flags = SA_SIGINFO | SA_ONSTACK;
	sigaction_safe(SIGPIPE,&ignore_sigaction,NULL);
}

/* On Unix, shared fds such as stdin cannot be set to non-blocking mode
(http://homepages.tesco.net/J.deBoynePollard/FGA/dont-set-shared-file-descriptors-to-non-blocking-mode.html)
so we kludge around this by spawning a thread, which waits on a control pipe
for a signal, upon receiving this signal it reads one block of data from stdin
and writes it to a data pipe. Upon completion, it writes a 4-byte integer to
the size pipe, indicating how much data was written to the data pipe.

The read end of the size pipe can be set to non-blocking. */
extern "C" {
	int stdin_read;
	int stdin_write;

	int control_read;
	int control_write;

	int size_read;
	int size_write;
}

void safe_close(int fd)
{
	if(close(fd) < 0)
		fatal_error("error closing fd",errno);
}

bool check_write(int fd, void *data, ssize_t size)
{
	if(write(fd,data,size) == size)
		return true;
	else
	{
		if(errno == EINTR)
			return check_write(fd,data,size);
		else
			return false;
	}
}

void safe_write(int fd, void *data, ssize_t size)
{
	if(!check_write(fd,data,size))
		fatal_error("error writing fd",errno);
}

bool safe_read(int fd, void *data, ssize_t size)
{
	ssize_t bytes = read(fd,data,size);
	if(bytes < 0)
	{
		if(errno == EINTR)
			return safe_read(fd,data,size);
		else
		{
			fatal_error("error reading fd",errno);
			return false;
		}
	}
	else
		return (bytes == size);
}

void *stdin_loop(void *arg)
{
	unsigned char buf[4096];
	bool loop_running = true;

	while(loop_running)
	{
		if(!safe_read(control_read,buf,1))
			break;

		if(buf[0] != 'X')
			fatal_error("stdin_loop: bad data on control fd",buf[0]);

		for(;;)
		{
			ssize_t bytes = read(0,buf,sizeof(buf));
			if(bytes < 0)
			{
				if(errno == EINTR)
					continue;
				else
				{
					loop_running = false;
					break;
				}
			}
			else if(bytes >= 0)
			{
				safe_write(size_write,&bytes,sizeof(bytes));

				if(!check_write(stdin_write,buf,bytes))
					loop_running = false;
				break;
			}
		}
	}

	safe_close(stdin_write);
	safe_close(control_read);

	return NULL;
}

void safe_pipe(int *in, int *out)
{
	int filedes[2];

	if(pipe(filedes) < 0)
		fatal_error("Error opening pipe",errno);

	*in = filedes[0];
	*out = filedes[1];

	if(fcntl(*in,F_SETFD,FD_CLOEXEC) < 0)
		fatal_error("Error with fcntl",errno);

	if(fcntl(*out,F_SETFD,FD_CLOEXEC) < 0)
		fatal_error("Error with fcntl",errno);
}

void open_console()
{
	safe_pipe(&control_read,&control_write);
	safe_pipe(&size_read,&size_write);
	safe_pipe(&stdin_read,&stdin_write);
	start_thread(stdin_loop,NULL);
}

VM_C_API void wait_for_stdin()
{
	if(write(control_write,"X",1) != 1)
	{
		if(errno == EINTR)
			wait_for_stdin();
		else
			fatal_error("Error writing control fd",errno);
	}
}

}
<commit_msg>vm/os-unix.cpp: remove dead code<commit_after>#include "master.hpp"

namespace factor
{

THREADHANDLE start_thread(void *(*start_routine)(void *),void *args)
{
	pthread_attr_t attr;
	pthread_t thread;
	if (pthread_attr_init (&attr) != 0)
		fatal_error("pthread_attr_init() failed",0);
	if (pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_JOINABLE) != 0)
		fatal_error("pthread_attr_setdetachstate() failed",0);
	if (pthread_create (&thread, &attr, start_routine, args) != 0)
		fatal_error("pthread_create() failed",0);
	pthread_attr_destroy(&attr);
	return thread;
}

static void *null_dll;

void sleep_nanos(u64 nsec)
{
	timespec ts;
	timespec ts_rem;
	int ret;
	ts.tv_sec = nsec / 1000000000;
	ts.tv_nsec = nsec % 1000000000;
	ret = nanosleep(&ts,&ts_rem);
	while(ret == -1 && errno == EINTR)
	{
		memcpy(&ts, &ts_rem, sizeof(ts));
		ret = nanosleep(&ts, &ts_rem);
	}

	if(ret == -1)
		fatal_error("nanosleep failed", 0);
}

void factor_vm::init_ffi()
{
	null_dll = dlopen(NULL,RTLD_LAZY);
}

void factor_vm::ffi_dlopen(dll *dll)
{
	dll->handle = dlopen(alien_offset(dll->path), RTLD_LAZY);
}

void *factor_vm::ffi_dlsym(dll *dll, symbol_char *symbol)
{
	void *handle = (dll == NULL ? null_dll : dll->handle);
	return dlsym(handle,symbol);
}

void factor_vm::ffi_dlclose(dll *dll)
{
	if(dlclose(dll->handle))
		general_error(ERROR_FFI,false_object,false_object);
	dll->handle = NULL;
}

void factor_vm::primitive_existsp()
{
	struct stat sb;
	char *path = (char *)(untag_check<byte_array>(ctx->pop()) + 1);
	ctx->push(tag_boolean(stat(path,&sb) >= 0));
}

void factor_vm::move_file(const vm_char *path1, const vm_char *path2)
{
	int ret = 0;
	do
	{
		ret = rename((path1),(path2));
	}
	while(ret < 0 && errno == EINTR);

	if(ret < 0)
		general_error(ERROR_IO,tag_fixnum(errno),false_object);
}

segment::segment(cell size_, bool executable_p)
{
	size = size_;

	int pagesize = getpagesize();

	int prot;
	if(executable_p)
		prot = (PROT_READ | PROT_WRITE | PROT_EXEC);
	else
		prot = (PROT_READ | PROT_WRITE);

	char *array = (char *)mmap(NULL,pagesize + size + pagesize,prot,MAP_ANON | MAP_PRIVATE,-1,0);
	if(array == (char*)-1) out_of_memory();

	if(mprotect(array,pagesize,PROT_NONE) == -1)
		fatal_error("Cannot protect low guard page",(cell)array);

	if(mprotect(array + pagesize + size,pagesize,PROT_NONE) == -1)
		fatal_error("Cannot protect high guard page",(cell)array);

	start = (cell)(array + pagesize);
	end = start + size;
}

segment::~segment()
{
	int pagesize = getpagesize();
	int retval = munmap((void*)(start - pagesize),pagesize + size + pagesize);
	if(retval)
		fatal_error("Segment deallocation failed",0);
}

void factor_vm::dispatch_signal(void *uap, void (handler)())
{
	UAP_STACK_POINTER(uap) = (UAP_STACK_POINTER_TYPE)fix_callstack_top((stack_frame *)UAP_STACK_POINTER(uap));
	UAP_PROGRAM_COUNTER(uap) = (cell)handler;

	ctx->callstack_top = (stack_frame *)UAP_STACK_POINTER(uap);
}

void memory_signal_handler(int signal, siginfo_t *siginfo, void *uap)
{
	factor_vm *vm = current_vm();
	vm->signal_fault_addr = (cell)siginfo->si_addr;
	vm->dispatch_signal(uap,factor::memory_signal_handler_impl);
}

void misc_signal_handler(int signal, siginfo_t *siginfo, void *uap)
{
	factor_vm *vm = current_vm();
	vm->signal_number = signal;
	vm->dispatch_signal(uap,factor::misc_signal_handler_impl);
}

void ignore_signal_handler(int signal, siginfo_t *siginfo, void *uap)
{
}

void fpe_signal_handler(int signal, siginfo_t *siginfo, void *uap)
{
	factor_vm *vm = current_vm();
	vm->signal_number = signal;
	vm->signal_fpu_status = fpu_status(uap_fpu_status(uap));
	uap_clear_fpu_status(uap);

	vm->dispatch_signal(uap,
		(siginfo->si_code == FPE_INTDIV || siginfo->si_code == FPE_INTOVF)
		? factor::misc_signal_handler_impl
		: factor::fp_signal_handler_impl);
}

static void sigaction_safe(int signum, const struct sigaction *act, struct sigaction *oldact)
{
	int ret;
	do
	{
		ret = sigaction(signum, act, oldact);
	}
	while(ret == -1 && errno == EINTR);

	if(ret == -1)
		fatal_error("sigaction failed", 0);
}

void factor_vm::unix_init_signals()
{
	/* OpenBSD doesn't support sigaltstack() if we link against
	libpthread. See http://redmine.ruby-lang.org/issues/show/1239 */

#ifndef __OpenBSD__
	signal_callstack_seg = new segment(callstack_size,false);

	stack_t signal_callstack;
	signal_callstack.ss_sp = (char *)signal_callstack_seg->start;
	signal_callstack.ss_size = signal_callstack_seg->size;
	signal_callstack.ss_flags = 0;

	if(sigaltstack(&signal_callstack,(stack_t *)NULL) < 0)
		fatal_error("sigaltstack() failed",0);
#endif

	struct sigaction memory_sigaction;
	struct sigaction misc_sigaction;
	struct sigaction fpe_sigaction;
	struct sigaction ignore_sigaction;

	memset(&memory_sigaction,0,sizeof(struct sigaction));
	sigemptyset(&memory_sigaction.sa_mask);
	memory_sigaction.sa_sigaction = memory_signal_handler;
	memory_sigaction.sa_flags = SA_SIGINFO | SA_ONSTACK;

	sigaction_safe(SIGBUS,&memory_sigaction,NULL);
	sigaction_safe(SIGSEGV,&memory_sigaction,NULL);

	memset(&fpe_sigaction,0,sizeof(struct sigaction));
	sigemptyset(&fpe_sigaction.sa_mask);
	fpe_sigaction.sa_sigaction = fpe_signal_handler;
	fpe_sigaction.sa_flags = SA_SIGINFO | SA_ONSTACK;

	sigaction_safe(SIGFPE,&fpe_sigaction,NULL);

	memset(&misc_sigaction,0,sizeof(struct sigaction));
	sigemptyset(&misc_sigaction.sa_mask);
	misc_sigaction.sa_sigaction = misc_signal_handler;
	misc_sigaction.sa_flags = SA_SIGINFO | SA_ONSTACK;

	sigaction_safe(SIGQUIT,&misc_sigaction,NULL);
	sigaction_safe(SIGILL,&misc_sigaction,NULL);

	/* We don't use SA_IGN here because then the ignore action is inherited
	by subprocesses, which we don't want. There is a unit test in
	io.launcher.unix for this. */
	memset(&ignore_sigaction,0,sizeof(struct sigaction));
	sigemptyset(&ignore_sigaction.sa_mask);
	ignore_sigaction.sa_sigaction = ignore_signal_handler;
	ignore_sigaction.sa_flags = SA_SIGINFO | SA_ONSTACK;
	sigaction_safe(SIGPIPE,&ignore_sigaction,NULL);
}

/* On Unix, shared fds such as stdin cannot be set to non-blocking mode
(http://homepages.tesco.net/J.deBoynePollard/FGA/dont-set-shared-file-descriptors-to-non-blocking-mode.html)
so we kludge around this by spawning a thread, which waits on a control pipe
for a signal, upon receiving this signal it reads one block of data from stdin
and writes it to a data pipe. Upon completion, it writes a 4-byte integer to
the size pipe, indicating how much data was written to the data pipe.

The read end of the size pipe can be set to non-blocking. */
extern "C" {
	int stdin_read;
	int stdin_write;

	int control_read;
	int control_write;

	int size_read;
	int size_write;
}

void safe_close(int fd)
{
	if(close(fd) < 0)
		fatal_error("error closing fd",errno);
}

bool check_write(int fd, void *data, ssize_t size)
{
	if(write(fd,data,size) == size)
		return true;
	else
	{
		if(errno == EINTR)
			return check_write(fd,data,size);
		else
			return false;
	}
}

void safe_write(int fd, void *data, ssize_t size)
{
	if(!check_write(fd,data,size))
		fatal_error("error writing fd",errno);
}

bool safe_read(int fd, void *data, ssize_t size)
{
	ssize_t bytes = read(fd,data,size);
	if(bytes < 0)
	{
		if(errno == EINTR)
			return safe_read(fd,data,size);
		else
		{
			fatal_error("error reading fd",errno);
			return false;
		}
	}
	else
		return (bytes == size);
}

void *stdin_loop(void *arg)
{
	unsigned char buf[4096];
	bool loop_running = true;

	while(loop_running)
	{
		if(!safe_read(control_read,buf,1))
			break;

		if(buf[0] != 'X')
			fatal_error("stdin_loop: bad data on control fd",buf[0]);

		for(;;)
		{
			ssize_t bytes = read(0,buf,sizeof(buf));
			if(bytes < 0)
			{
				if(errno == EINTR)
					continue;
				else
				{
					loop_running = false;
					break;
				}
			}
			else if(bytes >= 0)
			{
				safe_write(size_write,&bytes,sizeof(bytes));

				if(!check_write(stdin_write,buf,bytes))
					loop_running = false;
				break;
			}
		}
	}

	safe_close(stdin_write);
	safe_close(control_read);

	return NULL;
}

void safe_pipe(int *in, int *out)
{
	int filedes[2];

	if(pipe(filedes) < 0)
		fatal_error("Error opening pipe",errno);

	*in = filedes[0];
	*out = filedes[1];

	if(fcntl(*in,F_SETFD,FD_CLOEXEC) < 0)
		fatal_error("Error with fcntl",errno);

	if(fcntl(*out,F_SETFD,FD_CLOEXEC) < 0)
		fatal_error("Error with fcntl",errno);
}

void open_console()
{
	safe_pipe(&control_read,&control_write);
	safe_pipe(&size_read,&size_write);
	safe_pipe(&stdin_read,&stdin_write);
	start_thread(stdin_loop,NULL);
}

}
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#include "ElemMessage.hpp"

#include <xercesc/sax/AttributeList.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>

#include "Constants.hpp"
#include "StylesheetConstructionContext.hpp"
#include "StylesheetExecutionContext.hpp"

ElemMessage::ElemMessage(
			StylesheetConstructionContext&	constructionContext,
			Stylesheet&						stylesheetTree,
			const AttributeList&			atts,
			int								lineNumber,
			int								columnNumber) :
	ElemTemplateElement(constructionContext,
						stylesheetTree,
						lineNumber,
						columnNumber,
						Constants::ELEMNAME_MESSAGE),
	m_terminate(false)
{
	const unsigned int	nAttrs = atts.getLength();

	for(unsigned int i = 0; i < nAttrs; i++)
	{
		const XalanDOMChar*	const	aname = atts.getName(i);

		if (equals(aname, Constants::ATTRNAME_TERMINATE) == true)
		{
			const XalanDOMChar*	const	avalue = atts.getValue(i);

			if (equals(avalue, Constants::ATTRVAL_YES) == true)
			{
				m_terminate = true;
			}
			else if (equals(avalue, Constants::ATTRVAL_NO) == false)
			{
				constructionContext.error(
					"The attribute 'terminate' has an illegal value",
					0,
					this);
			}
		}
		else if(isAttrOK(aname, atts, i, constructionContext) == false ||
				processSpaceAttr(aname, atts, i, constructionContext))
		{
			constructionContext.error(
				"xsl:message has an illegal attribute",
				0,
				this);
		}
	}
}

const XalanDOMString&
ElemMessage::getElementName() const
{
	return Constants::ELEMNAME_MESSAGE_WITH_PREFIX_STRING;
}

void
ElemMessage::execute(StylesheetExecutionContext&		executionContext) const
{
	ElemTemplateElement::execute(executionContext);

	StylesheetExecutionContext::GetAndReleaseCachedString	theResult(executionContext);

    executionContext.message(
		childrenToString(executionContext,theResult.get()),
		executionContext.getCurrentNode(),
		this);

	if (m_terminate == true)
	{
		throw ElemMessageTerminateException(theResult.get());
	}
}

ElemMessage::ElemMessageTerminateException::ElemMessageTerminateException(const XalanDOMString&		theMessage) :
	XSLTProcessorException(theMessage,
						   TranscodeFromLocalCodePage("ElemMessageTerminateException"))
{
}

ElemMessage::ElemMessageTerminateException::~ElemMessageTerminateException()
{
}
<commit_msg>Use Locator for messages.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#include "ElemMessage.hpp"

#include <xercesc/sax/AttributeList.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>

#include "Constants.hpp"
#include "StylesheetConstructionContext.hpp"
#include "StylesheetExecutionContext.hpp"

ElemMessage::ElemMessage(
			StylesheetConstructionContext&	constructionContext,
			Stylesheet&						stylesheetTree,
			const AttributeList&			atts,
			int								lineNumber,
			int								columnNumber) :
	ElemTemplateElement(constructionContext,
						stylesheetTree,
						lineNumber,
						columnNumber,
						Constants::ELEMNAME_MESSAGE),
	m_terminate(false)
{
	const unsigned int	nAttrs = atts.getLength();

	for(unsigned int i = 0; i < nAttrs; i++)
	{
		const XalanDOMChar*	const	aname = atts.getName(i);

		if (equals(aname, Constants::ATTRNAME_TERMINATE) == true)
		{
			const XalanDOMChar*	const	avalue = atts.getValue(i);

			if (equals(avalue, Constants::ATTRVAL_YES) == true)
			{
				m_terminate = true;
			}
			else if (equals(avalue, Constants::ATTRVAL_NO) == false)
			{
				constructionContext.error(
					"The attribute 'terminate' has an illegal value",
					0,
					this);
			}
		}
		else if(isAttrOK(aname, atts, i, constructionContext) == false ||
				processSpaceAttr(aname, atts, i, constructionContext))
		{
			constructionContext.error(
				"xsl:message has an illegal attribute",
				0,
				this);
		}
	}
}

const XalanDOMString&
ElemMessage::getElementName() const
{
	return Constants::ELEMNAME_MESSAGE_WITH_PREFIX_STRING;
}

void
ElemMessage::execute(StylesheetExecutionContext&		executionContext) const
{
	ElemTemplateElement::execute(executionContext);

	StylesheetExecutionContext::GetAndReleaseCachedString	theResult(executionContext);

    executionContext.message(
		childrenToString(executionContext,theResult.get()),
		executionContext.getCurrentNode(),
		getLocator());

	if (m_terminate == true)
	{
		throw ElemMessageTerminateException(theResult.get());
	}
}

ElemMessage::ElemMessageTerminateException::ElemMessageTerminateException(const XalanDOMString&		theMessage) :
	XSLTProcessorException(theMessage,
						   TranscodeFromLocalCodePage("ElemMessageTerminateException"))
{
}

ElemMessage::ElemMessageTerminateException::~ElemMessageTerminateException()
{
}
<|endoftext|>


<commit_before>/*
 * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Affero 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 Affero 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 "blackrock_spire.h"
#include "ScriptedCreature.h"
#include "ScriptMgr.h"

enum Spells
{
    SPELL_FLAMESTRIKE               = 16419,
    SPELL_CLEAVE                    = 15284,
    SPELL_CONFLAGRATION             = 16805,
    SPELL_THUNDERCLAP               = 15548, //Not sure if right ID. 23931 would be a harder possibility.
    SPELL_RAGE                      = 16789,
    SPELL_PIERCE_ARMOR              = 12097
};

enum Events
{
    EVENT_FLAMESTRIKE               = 1,
    EVENT_CLEAVE,
    EVENT_CONFLAGRATION,
    EVENT_THUNDERCLAP,
    EVENT_PIERCE_ARMOR,
    EVENT_RAGE
};

enum ChromaticEliteGuardEvents
{
    EVENT_MORTAL_STRIKE = 1,
    EVENT_KNOCKDOWN     = 2,
    EVENT_STRIKE        = 3
};

enum ChromaticEliteGuardSpells
{
    SPELL_MORTAL_STRIKE = 15708,
    SPELL_KNOCKDOWN     = 16790,
    SPELL_STRIKE        = 15580
};

constexpr uint32 ChromaticEliteGuardEntry  = 10814;
constexpr uint32 GeneralDrakkisathEntry    = 10814;

class boss_drakkisath : public CreatureScript
{
public:
    boss_drakkisath() : CreatureScript("boss_drakkisath") { }

    struct boss_drakkisathAI : public BossAI
    {
        boss_drakkisathAI(Creature* creature) : BossAI(creature, DATA_GENERAL_DRAKKISATH) { }

        void Reset() override
        {
            _Reset();
        }

        void EnterCombat(Unit* /*who*/) override
        {
            _EnterCombat();
            CallForHelp();
            events.ScheduleEvent(EVENT_FLAMESTRIKE, 6000);
            events.ScheduleEvent(EVENT_CLEAVE,    8000);
            events.ScheduleEvent(EVENT_CONFLAGRATION, 15000);
            events.ScheduleEvent(EVENT_THUNDERCLAP,    17000);
            events.ScheduleEvent(EVENT_PIERCE_ARMOR, 5000);
            events.ScheduleEvent(EVENT_RAGE, 1000);
        }

        // Will make his two adds engage combat
        void CallForHelp()
        {
            std::list<Creature*> ChromaticEliteGuards;
            me->GetCreaturesWithEntryInRange(ChromaticEliteGuards, 15.0f, ChromaticEliteGuardEntry);
            for (std::list<Creature*>::const_iterator itr = ChromaticEliteGuards.begin(); itr != ChromaticEliteGuards.end(); ++itr)
            {
                (*itr)->ToCreature()->AI()->AttackStart(me->GetVictim());
            }
        }

        void JustDied(Unit* /*killer*/) override
        {
            _JustDied();
        }

        void UpdateAI(uint32 diff) override
        {
            if (!UpdateVictim())
                return;

            events.Update(diff);

            if (me->HasUnitState(UNIT_STATE_CASTING))
                return;

            while (uint32 eventId = events.ExecuteEvent())
            {
                switch (eventId)
                {
                    case EVENT_FLAMESTRIKE:
                        DoCastAOE(SPELL_FLAMESTRIKE);
                        events.ScheduleEvent(EVENT_FLAMESTRIKE, 10000);
                        break;
                    case EVENT_CLEAVE:
                        DoCastVictim(SPELL_CLEAVE);
                        events.ScheduleEvent(EVENT_CLEAVE, 8000);
                        break;
                    case EVENT_CONFLAGRATION:
                        if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 50.0f, true))
                        {
                            DoCast(target, SPELL_CONFLAGRATION);
                        }
                        events.ScheduleEvent(EVENT_CONFLAGRATION, 18000);
                        break;
                    case EVENT_THUNDERCLAP:
                        DoCastVictim(SPELL_THUNDERCLAP);
                        events.ScheduleEvent(EVENT_THUNDERCLAP, 20000);
                        break;
                    case EVENT_PIERCE_ARMOR:
                        DoCastVictim(SPELL_PIERCE_ARMOR);
                        events.ScheduleEvent(EVENT_PIERCE_ARMOR, 40000);
                        break;
                    case EVENT_RAGE:
                        DoCastSelf(SPELL_RAGE);
                        events.ScheduleEvent(EVENT_RAGE, 35000);
                        break;
                }
            }
            DoMeleeAttackIfReady();
        }
    };

    CreatureAI* GetAI(Creature* creature) const override
    {
        return GetBlackrockSpireAI<boss_drakkisathAI>(creature);
    }
};

class chromatic_elite_guard : public CreatureScript
{
public:
    chromatic_elite_guard() : CreatureScript("chromatic_elite_guard") { }

    struct chromatic_elite_guardAI : public ScriptedAI
    {
        chromatic_elite_guardAI(Creature* creature) : ScriptedAI(creature) { }

        EventMap _events;

        void EnterCombat(Unit* who) override
        {
            _events.ScheduleEvent(EVENT_MORTAL_STRIKE, urand(5000, 12800));
            _events.ScheduleEvent(EVENT_KNOCKDOWN, urand(5600, 15400));
            _events.ScheduleEvent(EVENT_STRIKE, urand(12000, 20800));

            std::list<Creature*> GeneralDrakkisath;
            me->GetCreaturesWithEntryInRange(GeneralDrakkisath, 15.0f, GeneralDrakkisathEntry);
            for (std::list<Creature*>::const_iterator itr = GeneralDrakkisath.begin(); itr != GeneralDrakkisath.end(); ++itr)
            {
                (*itr)->ToCreature()->AI()->AttackStart(who);
            }

            std::list<Creature*> ChromaticEliteGuards;
            me->GetCreaturesWithEntryInRange(ChromaticEliteGuards, 15.0f, ChromaticEliteGuardEntry);
            for (std::list<Creature*>::const_iterator itr = ChromaticEliteGuards.begin(); itr != ChromaticEliteGuards.end(); ++itr)
            {
                (*itr)->ToCreature()->AI()->AttackStart(who);
            }
        }

        void UpdateAI(uint32 diff) override
        {
            if (!UpdateVictim())
                return;

            _events.Update(diff);

            switch (_events.ExecuteEvent())
            {
                case EVENT_MORTAL_STRIKE:
                    DoCastVictim(SPELL_MORTAL_STRIKE);
                    _events.ScheduleEvent(EVENT_MORTAL_STRIKE, 13000);
                    break;
                case EVENT_KNOCKDOWN:
                    DoCastVictim(SPELL_KNOCKDOWN);
                    _events.ScheduleEvent(EVENT_MORTAL_STRIKE, urand(11200, 25700));
                    break;
                case EVENT_STRIKE:
                    DoCastVictim(SPELL_STRIKE);
                    _events.ScheduleEvent(EVENT_MORTAL_STRIKE, 9000);
                    break;
            }

            DoMeleeAttackIfReady();
        }
    };

    CreatureAI* GetAI(Creature* creature) const override
    {
        return new chromatic_elite_guardAI(creature);
    }
};

void AddSC_boss_drakkisath()
{
    new boss_drakkisath();
    new chromatic_elite_guard();
}
<commit_msg>fix(Scripts/UBRS): Correct Drakkisath's guard abilities not being cast (#8957)<commit_after>/*
 * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Affero 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 Affero 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 "blackrock_spire.h"
#include "ScriptedCreature.h"
#include "ScriptMgr.h"

enum Spells
{
    SPELL_FLAMESTRIKE               = 16419,
    SPELL_CLEAVE                    = 15284,
    SPELL_CONFLAGRATION             = 16805,
    SPELL_THUNDERCLAP               = 15548, //Not sure if right ID. 23931 would be a harder possibility.
    SPELL_RAGE                      = 16789,
    SPELL_PIERCE_ARMOR              = 12097
};

enum Events
{
    EVENT_FLAMESTRIKE               = 1,
    EVENT_CLEAVE,
    EVENT_CONFLAGRATION,
    EVENT_THUNDERCLAP,
    EVENT_PIERCE_ARMOR,
    EVENT_RAGE
};

enum ChromaticEliteGuardEvents
{
    EVENT_MORTAL_STRIKE = 1,
    EVENT_KNOCKDOWN     = 2,
    EVENT_STRIKE        = 3
};

enum ChromaticEliteGuardSpells
{
    SPELL_MORTAL_STRIKE = 15708,
    SPELL_KNOCKDOWN     = 16790,
    SPELL_STRIKE        = 15580
};

constexpr uint32 ChromaticEliteGuardEntry  = 10814;
constexpr uint32 GeneralDrakkisathEntry    = 10814;

class boss_drakkisath : public CreatureScript
{
public:
    boss_drakkisath() : CreatureScript("boss_drakkisath") { }

    struct boss_drakkisathAI : public BossAI
    {
        boss_drakkisathAI(Creature* creature) : BossAI(creature, DATA_GENERAL_DRAKKISATH) { }

        void Reset() override
        {
            _Reset();
        }

        void EnterCombat(Unit* /*who*/) override
        {
            _EnterCombat();
            CallForHelp();
            events.ScheduleEvent(EVENT_FLAMESTRIKE, 6000);
            events.ScheduleEvent(EVENT_CLEAVE,    8000);
            events.ScheduleEvent(EVENT_CONFLAGRATION, 15000);
            events.ScheduleEvent(EVENT_THUNDERCLAP,    17000);
            events.ScheduleEvent(EVENT_PIERCE_ARMOR, 5000);
            events.ScheduleEvent(EVENT_RAGE, 1000);
        }

        // Will make his two adds engage combat
        void CallForHelp()
        {
            std::list<Creature*> ChromaticEliteGuards;
            me->GetCreaturesWithEntryInRange(ChromaticEliteGuards, 15.0f, ChromaticEliteGuardEntry);
            for (std::list<Creature*>::const_iterator itr = ChromaticEliteGuards.begin(); itr != ChromaticEliteGuards.end(); ++itr)
            {
                (*itr)->ToCreature()->AI()->AttackStart(me->GetVictim());
            }
        }

        void JustDied(Unit* /*killer*/) override
        {
            _JustDied();
        }

        void UpdateAI(uint32 diff) override
        {
            if (!UpdateVictim())
                return;

            events.Update(diff);

            if (me->HasUnitState(UNIT_STATE_CASTING))
                return;

            while (uint32 eventId = events.ExecuteEvent())
            {
                switch (eventId)
                {
                    case EVENT_FLAMESTRIKE:
                        DoCastAOE(SPELL_FLAMESTRIKE);
                        events.ScheduleEvent(EVENT_FLAMESTRIKE, 10000);
                        break;
                    case EVENT_CLEAVE:
                        DoCastVictim(SPELL_CLEAVE);
                        events.ScheduleEvent(EVENT_CLEAVE, 8000);
                        break;
                    case EVENT_CONFLAGRATION:
                        if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 50.0f, true))
                        {
                            DoCast(target, SPELL_CONFLAGRATION);
                        }
                        events.ScheduleEvent(EVENT_CONFLAGRATION, 18000);
                        break;
                    case EVENT_THUNDERCLAP:
                        DoCastVictim(SPELL_THUNDERCLAP);
                        events.ScheduleEvent(EVENT_THUNDERCLAP, 20000);
                        break;
                    case EVENT_PIERCE_ARMOR:
                        DoCastVictim(SPELL_PIERCE_ARMOR);
                        events.ScheduleEvent(EVENT_PIERCE_ARMOR, 40000);
                        break;
                    case EVENT_RAGE:
                        DoCastSelf(SPELL_RAGE);
                        events.ScheduleEvent(EVENT_RAGE, 35000);
                        break;
                }
            }
            DoMeleeAttackIfReady();
        }
    };

    CreatureAI* GetAI(Creature* creature) const override
    {
        return GetBlackrockSpireAI<boss_drakkisathAI>(creature);
    }
};

class chromatic_elite_guard : public CreatureScript
{
public:
    chromatic_elite_guard() : CreatureScript("chromatic_elite_guard") { }

    struct chromatic_elite_guardAI : public ScriptedAI
    {
        chromatic_elite_guardAI(Creature* creature) : ScriptedAI(creature) { }

        EventMap _events;

        void EnterCombat(Unit* who) override
        {
            _events.ScheduleEvent(EVENT_MORTAL_STRIKE, urand(5000, 12800));
            _events.ScheduleEvent(EVENT_KNOCKDOWN, urand(5600, 15400));
            _events.ScheduleEvent(EVENT_STRIKE, urand(12000, 20800));

            std::list<Creature*> GeneralDrakkisath;
            me->GetCreaturesWithEntryInRange(GeneralDrakkisath, 15.0f, GeneralDrakkisathEntry);
            for (std::list<Creature*>::const_iterator itr = GeneralDrakkisath.begin(); itr != GeneralDrakkisath.end(); ++itr)
            {
                (*itr)->ToCreature()->AI()->AttackStart(who);
            }

            std::list<Creature*> ChromaticEliteGuards;
            me->GetCreaturesWithEntryInRange(ChromaticEliteGuards, 15.0f, ChromaticEliteGuardEntry);
            for (std::list<Creature*>::const_iterator itr = ChromaticEliteGuards.begin(); itr != ChromaticEliteGuards.end(); ++itr)
            {
                (*itr)->ToCreature()->AI()->AttackStart(who);
            }
        }

        void UpdateAI(uint32 diff) override
        {
            if (!UpdateVictim())
                return;

            _events.Update(diff);

            switch (_events.ExecuteEvent())
            {
                case EVENT_MORTAL_STRIKE:
                    DoCastVictim(SPELL_MORTAL_STRIKE);
                    _events.ScheduleEvent(EVENT_MORTAL_STRIKE, 13000);
                    break;
                case EVENT_KNOCKDOWN:
                    DoCastVictim(SPELL_KNOCKDOWN);
                    _events.ScheduleEvent(EVENT_KNOCKDOWN, urand(11200, 25700));
                    break;
                case EVENT_STRIKE:
                    DoCastVictim(SPELL_STRIKE);
                    _events.ScheduleEvent(EVENT_STRIKE, 9000);
                    break;
            }

            DoMeleeAttackIfReady();
        }
    };

    CreatureAI* GetAI(Creature* creature) const override
    {
        return new chromatic_elite_guardAI(creature);
    }
};

void AddSC_boss_drakkisath()
{
    new boss_drakkisath();
    new chromatic_elite_guard();
}
<|endoftext|>


<commit_before>//
// Copyright (C) 2005 Stefan Seefeld
// All rights reserved.
// Licensed to the public under the terms of the GNU LGPL (>= 2),
// see the file COPYING for details.
//

#include "ASGTranslator.hh"
#include "SXRGenerator.hh"
#include <Support/Timer.hh>
#include <Support/path.hh>
#include <boost/filesystem/convenience.hpp>
#include <clang-c/Index.h>
#include <fstream>
#include <cstring>
#include <unistd.h>

using namespace Synopsis;
namespace fs = boost::filesystem;

namespace
{
bpl::object error_type;

//. Override unexpected() to print a message before we abort
void unexpected()
{
  std::cout << "Warning: Aborting due to unexpected exception." << std::endl;
  throw std::bad_exception();
}

bpl::dict annotations(bpl::object o)
{ return bpl::extract<bpl::dict>(o.attr("annotations"));}

//. Merge new files to files already present in the IR.
//. If a file doesn't exist yet, add it. If it does,
//. upgrade the 'primary' flag if it is set now.
void merge_files(bpl::dict ir_files, bpl::dict new_files)
{
  bpl::list keys = new_files.keys();
  for (unsigned i = 0; i != bpl::len(keys); ++i)
  {
    bpl::object filename = keys[i];
    bpl::object file = new_files[filename];
    if (ir_files.has_key(filename))
    {
      if (bpl::extract<bool>(annotations(file)["primary"]))
       	annotations(ir_files[filename])["primary"] = true;
    }
    else
      ir_files[filename] = file;
  }
}

bpl::object parse(bpl::object ir,
                  char const *cpp_file, char const *input_file, char const *base_path,
                  bool primary_file_only, char const *sxr_prefix,
		  bpl::list cpp_flags,
                  bool verbose, bool debug, bool profile)
{
  std::set_unexpected(unexpected);

  // if (debug) Synopsis::Trace::enable(Trace::TRANSLATION);

  if (!input_file || *input_file == '\0') throw std::runtime_error("no input file");

  char const **args = new char const*[bpl::len(cpp_flags) + 2];
  args[0] = "-x";
  args[1] = "c";
  for (size_t i = 0; i != bpl::len(cpp_flags); ++i)
    args[i + 2] = bpl::extract<char const *>(cpp_flags[i]);

  Timer timer;
  // first arg: exclude declarations from PCH
  // second arg: display diagnostics
  CXIndex idx = clang_createIndex(0, 1);
  CXTranslationUnit_Flags flags = CXTranslationUnit_DetailedPreprocessingRecord;
  CXTranslationUnit tu =
    clang_parseTranslationUnit(idx, input_file,
			       args,
			       bpl::len(cpp_flags) + 2,
			       0,  // unsaved_files
			       0,  // num_unsaved_files
			       flags);
  delete [] args;
  if (!tu)
  {
    std::cerr << "unable to parse input\n";
    return ir;
  }

  if (profile)
    std::cout << "C++ parser took " << timer.elapsed()
              << " seconds" << std::endl;
  unsigned diagnostics = clang_getNumDiagnostics(tu);
  if (diagnostics)
  {
    for (unsigned i = 0; i != diagnostics; ++i)
    {
      CXDiagnostic d = clang_getDiagnostic(tu, i);
      CXString diagnostic = clang_formatDiagnostic(d, flags);
      std::cerr << clang_getCString(diagnostic) << std::endl;
      clang_disposeString(diagnostic);
      clang_disposeDiagnostic(d);
    }
    throw std::runtime_error("The input contains errors.");
  }
  bpl::object asg = ir.attr("asg");
  bpl::dict files;
  timer.reset();
  ASGTranslator translator(input_file, base_path, primary_file_only, asg, files, verbose, debug);
  translator.translate(tu);

  if (profile)
    std::cout << "ASG translation took " << timer.elapsed()
	      << " seconds" << std::endl;
  if (sxr_prefix)
  {
    timer.reset();
    SXRGenerator generator(translator, verbose, debug);
    for (size_t i = 0; i != bpl::len(files); ++i)
    {
      bpl::object sf = files.attr("values")()[i];
      if (!bpl::extract<bpl::dict>(sf.attr("annotations"))().get("primary", false)) continue;
      std::string abs_name = bpl::extract<char const *>(sf.attr("abs_name"))();
      std::string name = bpl::extract<char const *>(sf.attr("name"))();
      std::string sxr = std::string(sxr_prefix) + "/" + name + ".sxr";
      create_directories(fs::path(sxr).branch_path());
      generator.generate(tu, sxr, abs_name, name);
    }
    if (profile)
      std::cout << "SXR generation took " << timer.elapsed()
  		<< " seconds" << std::endl;
  }
  merge_files(bpl::extract<bpl::dict>(ir.attr("files")), files);

  clang_disposeTranslationUnit(tu);
  clang_disposeIndex(idx);
  return ir;
}

}

BOOST_PYTHON_MODULE(ParserImpl)
{
  bpl::scope scope;
  scope.attr("version") = "0.2";
  bpl::def("parse", parse);
  bpl::object module = bpl::import("Synopsis.Processor");
  bpl::object error_base = module.attr("Error");
  error_type = bpl::object(bpl::handle<>(PyErr_NewException("ParserImpl.ParseError",
                                                            error_base.ptr(), 0)));
  scope.attr("ParseError") = error_type;
}
<commit_msg>Work around clang bug.<commit_after>//
// Copyright (C) 2005 Stefan Seefeld
// All rights reserved.
// Licensed to the public under the terms of the GNU LGPL (>= 2),
// see the file COPYING for details.
//

#include "ASGTranslator.hh"
#include "SXRGenerator.hh"
#include <Support/Timer.hh>
#include <Support/path.hh>
#include <boost/filesystem/convenience.hpp>
#include <clang-c/Index.h>
#include <fstream>
#include <cstring>
#include <unistd.h>

using namespace Synopsis;
namespace fs = boost::filesystem;

namespace
{
bpl::object error_type;

//. Override unexpected() to print a message before we abort
void unexpected()
{
  std::cout << "Warning: Aborting due to unexpected exception." << std::endl;
  throw std::bad_exception();
}

bpl::dict annotations(bpl::object o)
{ return bpl::extract<bpl::dict>(o.attr("annotations"));}

//. Merge new files to files already present in the IR.
//. If a file doesn't exist yet, add it. If it does,
//. upgrade the 'primary' flag if it is set now.
void merge_files(bpl::dict ir_files, bpl::dict new_files)
{
  bpl::list keys = new_files.keys();
  for (unsigned i = 0; i != bpl::len(keys); ++i)
  {
    bpl::object filename = keys[i];
    bpl::object file = new_files[filename];
    if (ir_files.has_key(filename))
    {
      if (bpl::extract<bool>(annotations(file)["primary"]))
       	annotations(ir_files[filename])["primary"] = true;
    }
    else
      ir_files[filename] = file;
  }
}

bpl::object parse(bpl::object ir,
                  char const *cpp_file, char const *input_file, char const *base_path,
                  bool primary_file_only, char const *sxr_prefix,
		  bpl::list cpp_flags,
                  bool verbose, bool debug, bool profile)
{
  std::set_unexpected(unexpected);

  // if (debug) Synopsis::Trace::enable(Trace::TRANSLATION);

  if (!input_file || *input_file == '\0') throw std::runtime_error("no input file");

  char const **args = new char const*[bpl::len(cpp_flags) + 3];
  args[0] = "-x";
  args[1] = "c";
  for (size_t i = 0; i != bpl::len(cpp_flags); ++i)
    args[i + 2] = bpl::extract<char const *>(cpp_flags[i]);
  // Due to a bug in clang 2.9, the '-x c' option above only
  // works if the input argument is passed in args, instead of
  // the below 'input_file'. (Fixed in trunk)
  args[bpl::len(cpp_flags) + 2] = input_file;

  Timer timer;
  // first arg: exclude declarations from PCH
  // second arg: display diagnostics
  CXIndex idx = clang_createIndex(0, 1);
  CXTranslationUnit_Flags flags = CXTranslationUnit_DetailedPreprocessingRecord;
  CXTranslationUnit tu =
    clang_parseTranslationUnit(idx, 0,//input_file,
			       args,
			       bpl::len(cpp_flags) + 2,
			       0,  // unsaved_files
			       0,  // num_unsaved_files
			       flags);
  delete [] args;
  if (!tu)
  {
    std::cerr << "unable to parse input\n";
    return ir;
  }

  if (profile)
    std::cout << "C++ parser took " << timer.elapsed()
              << " seconds" << std::endl;
  unsigned diagnostics = clang_getNumDiagnostics(tu);
  if (diagnostics)
  {
    for (unsigned i = 0; i != diagnostics; ++i)
    {
      CXDiagnostic d = clang_getDiagnostic(tu, i);
      CXString diagnostic = clang_formatDiagnostic(d, flags);
      std::cerr << clang_getCString(diagnostic) << std::endl;
      clang_disposeString(diagnostic);
      clang_disposeDiagnostic(d);
    }
    throw std::runtime_error("The input contains errors.");
  }
  bpl::object asg = ir.attr("asg");
  bpl::dict files;
  timer.reset();
  ASGTranslator translator(input_file, base_path, primary_file_only, asg, files, verbose, debug);
  translator.translate(tu);

  if (profile)
    std::cout << "ASG translation took " << timer.elapsed()
	      << " seconds" << std::endl;
  if (sxr_prefix)
  {
    timer.reset();
    SXRGenerator generator(translator, verbose, debug);
    for (size_t i = 0; i != bpl::len(files); ++i)
    {
      bpl::object sf = files.attr("values")()[i];
      if (!bpl::extract<bpl::dict>(sf.attr("annotations"))().get("primary", false)) continue;
      std::string abs_name = bpl::extract<char const *>(sf.attr("abs_name"))();
      std::string name = bpl::extract<char const *>(sf.attr("name"))();
      std::string sxr = std::string(sxr_prefix) + "/" + name + ".sxr";
      create_directories(fs::path(sxr).branch_path());
      generator.generate(tu, sxr, abs_name, name);
    }
    if (profile)
      std::cout << "SXR generation took " << timer.elapsed()
  		<< " seconds" << std::endl;
  }
  merge_files(bpl::extract<bpl::dict>(ir.attr("files")), files);

  clang_disposeTranslationUnit(tu);
  clang_disposeIndex(idx);
  return ir;
}

}

BOOST_PYTHON_MODULE(ParserImpl)
{
  bpl::scope scope;
  scope.attr("version") = "0.2";
  bpl::def("parse", parse);
  bpl::object module = bpl::import("Synopsis.Processor");
  bpl::object error_base = module.attr("Error");
  error_type = bpl::object(bpl::handle<>(PyErr_NewException("ParserImpl.ParseError",
                                                            error_base.ptr(), 0)));
  scope.attr("ParseError") = error_type;
}
<|endoftext|>


<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2012 Francois Beaune, Jupiter Jazz Limited
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// Interface header.
#include "sceneitem.h"

// appleseed.studio headers.
#include "mainwindow/project/assemblycollectionitem.h"
#include "mainwindow/project/multimodelcollectionitem.h"
#include "mainwindow/project/singlemodelcollectionitem.h"
#include "mainwindow/project/texturecollectionitem.h"

// appleseed.renderer headers.
#include "renderer/api/entity.h"
#include "renderer/api/environmentedf.h"
#include "renderer/api/environmentshader.h"
#include "renderer/api/scene.h"

// appleseed.foundation headers.
#include "foundation/utility/uid.h"

// Qt headers.
#include <QMenu>

using namespace foundation;
using namespace renderer;

namespace appleseed {
namespace studio {

namespace
{
    const UniqueID g_class_uid = new_guid();
}

SceneItem::SceneItem(
    Scene&          scene,
    ProjectBuilder& project_builder,
    ParamArray&     settings)
  : BaseGroupItem(g_class_uid, "Scene", scene, project_builder, settings)
{
    set_allow_deletion(false);
    set_allow_edition(false);

    insertChild(
        0,
        m_camera_item =
            new CameraItem(
                scene.get_camera(),
                scene,
                this,
                project_builder));
    m_camera_item->set_allow_deletion(false);
    m_camera_item->set_fixed_position(true);

    insertChild(
        1,
        m_environment_item =
            new EnvironmentItem(
                scene.get_environment(),
                scene,
                this,
                project_builder));
    m_environment_item->set_allow_deletion(false);
    m_environment_item->set_fixed_position(true);

    insertChild(
        2,
        m_environment_edf_collection_item =
            new MultiModelCollectionItem<EnvironmentEDF, Scene, SceneItem>(
                new_guid(),
                EntityTraits<EnvironmentEDF>::get_human_readable_collection_type_name(),
                scene,
                this,
                project_builder));
    m_environment_edf_collection_item->add_items(scene.environment_edfs());

    insertChild(
        3,
        m_environment_shader_collection_item =
            new MultiModelCollectionItem<EnvironmentShader, Scene, SceneItem>(
                new_guid(),
                EntityTraits<EnvironmentShader>::get_human_readable_collection_type_name(),
                scene,
                this,
                project_builder));
    m_environment_shader_collection_item->add_items(scene.environment_shaders());
}

QMenu* SceneItem::get_single_item_context_menu() const
{
    QMenu* menu = ItemBase::get_single_item_context_menu();

    menu->addSeparator();
    menu->addAction("Import Textures...", &get_texture_collection_item(), SLOT(slot_import_textures()));

    menu->addSeparator();
    menu->addAction("Create Assembly...", &get_assembly_collection_item(), SLOT(slot_create()));
    menu->addAction("Create Color...", &get_color_collection_item(), SLOT(slot_create()));
    menu->addAction("Create Environment EDF...", m_environment_edf_collection_item, SLOT(slot_create()));
    menu->addAction("Create Environment Shader...", m_environment_shader_collection_item, SLOT(slot_create()));

    return menu;
}

void SceneItem::add_item(EnvironmentEDF* environment_edf)
{
    m_environment_edf_collection_item->add_item(environment_edf);
}

void SceneItem::add_item(EnvironmentShader* environment_shader)
{
    m_environment_shader_collection_item->add_item(environment_shader);
}

}   // namespace studio
}   // namespace appleseed
<commit_msg>the Scene item is a kind of collection item, display it in bold.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2012 Francois Beaune, Jupiter Jazz Limited
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// Interface header.
#include "sceneitem.h"

// appleseed.studio headers.
#include "mainwindow/project/assemblycollectionitem.h"
#include "mainwindow/project/multimodelcollectionitem.h"
#include "mainwindow/project/singlemodelcollectionitem.h"
#include "mainwindow/project/texturecollectionitem.h"

// appleseed.renderer headers.
#include "renderer/api/entity.h"
#include "renderer/api/environmentedf.h"
#include "renderer/api/environmentshader.h"
#include "renderer/api/scene.h"

// appleseed.foundation headers.
#include "foundation/utility/uid.h"

// Qt headers.
#include <QFont>
#include <QMenu>

using namespace foundation;
using namespace renderer;

namespace appleseed {
namespace studio {

namespace
{
    const UniqueID g_class_uid = new_guid();
}

SceneItem::SceneItem(
    Scene&          scene,
    ProjectBuilder& project_builder,
    ParamArray&     settings)
  : BaseGroupItem(g_class_uid, "Scene", scene, project_builder, settings)
{
    set_allow_deletion(false);
    set_allow_edition(false);

    QFont font;
    font.setBold(true);
    setFont(0, font);

    insertChild(
        0,
        m_camera_item =
            new CameraItem(
                scene.get_camera(),
                scene,
                this,
                project_builder));
    m_camera_item->set_allow_deletion(false);
    m_camera_item->set_fixed_position(true);

    insertChild(
        1,
        m_environment_item =
            new EnvironmentItem(
                scene.get_environment(),
                scene,
                this,
                project_builder));
    m_environment_item->set_allow_deletion(false);
    m_environment_item->set_fixed_position(true);

    insertChild(
        2,
        m_environment_edf_collection_item =
            new MultiModelCollectionItem<EnvironmentEDF, Scene, SceneItem>(
                new_guid(),
                EntityTraits<EnvironmentEDF>::get_human_readable_collection_type_name(),
                scene,
                this,
                project_builder));
    m_environment_edf_collection_item->add_items(scene.environment_edfs());

    insertChild(
        3,
        m_environment_shader_collection_item =
            new MultiModelCollectionItem<EnvironmentShader, Scene, SceneItem>(
                new_guid(),
                EntityTraits<EnvironmentShader>::get_human_readable_collection_type_name(),
                scene,
                this,
                project_builder));
    m_environment_shader_collection_item->add_items(scene.environment_shaders());
}

QMenu* SceneItem::get_single_item_context_menu() const
{
    QMenu* menu = ItemBase::get_single_item_context_menu();

    menu->addSeparator();
    menu->addAction("Import Textures...", &get_texture_collection_item(), SLOT(slot_import_textures()));

    menu->addSeparator();
    menu->addAction("Create Assembly...", &get_assembly_collection_item(), SLOT(slot_create()));
    menu->addAction("Create Color...", &get_color_collection_item(), SLOT(slot_create()));
    menu->addAction("Create Environment EDF...", m_environment_edf_collection_item, SLOT(slot_create()));
    menu->addAction("Create Environment Shader...", m_environment_shader_collection_item, SLOT(slot_create()));

    return menu;
}

void SceneItem::add_item(EnvironmentEDF* environment_edf)
{
    m_environment_edf_collection_item->add_item(environment_edf);
}

void SceneItem::add_item(EnvironmentShader* environment_shader)
{
    m_environment_shader_collection_item->add_item(environment_shader);
}

}   // namespace studio
}   // namespace appleseed
<|endoftext|>


<commit_before>/**
 * @file
 */
#include "libbirch/SharedPointer.hpp"

#include "libbirch/World.hpp"
#include "libbirch/WeakPointer.hpp"
#include "libbirch/Any.hpp"

bi::SharedPointer<bi::Any>::SharedPointer() :
    SharedPointer(std::make_shared<Any>()) {
  //
}

bi::SharedPointer<bi::Any>::SharedPointer(const std::nullptr_t& o) {
  //
}

bi::SharedPointer<bi::Any>::SharedPointer(const std::shared_ptr<Any>& ptr) :
    ptr(ptr) {
  //
}

bi::SharedPointer<bi::Any>& bi::SharedPointer<bi::Any>::operator=(
    const std::nullptr_t& o) {
  ptr = o;
  return *this;
}

bool bi::SharedPointer<bi::Any>::query() const {
  return static_cast<bool>(ptr);
}

bi::Any* bi::SharedPointer<bi::Any>::get() {
  return fiberWorld->get(ptr).get();
}

bi::Any* bi::SharedPointer<bi::Any>::get() const {
  return fiberWorld->get(ptr).get();
}
<commit_msg>Pointers now updated after mapping, ~15% performance gain (anecdotal).<commit_after>/**
 * @file
 */
#include "libbirch/SharedPointer.hpp"

#include "libbirch/World.hpp"
#include "libbirch/WeakPointer.hpp"
#include "libbirch/Any.hpp"

bi::SharedPointer<bi::Any>::SharedPointer() :
    SharedPointer(std::make_shared<Any>()) {
  //
}

bi::SharedPointer<bi::Any>::SharedPointer(const std::nullptr_t& o) {
  //
}

bi::SharedPointer<bi::Any>::SharedPointer(const std::shared_ptr<Any>& ptr) :
    ptr(ptr) {
  //
}

bi::SharedPointer<bi::Any>& bi::SharedPointer<bi::Any>::operator=(
    const std::nullptr_t& o) {
  ptr = o;
  return *this;
}

bool bi::SharedPointer<bi::Any>::query() const {
  return static_cast<bool>(ptr);
}

bi::Any* bi::SharedPointer<bi::Any>::get() {
  ptr = fiberWorld->get(ptr);
  return ptr.get();
}

bi::Any* bi::SharedPointer<bi::Any>::get() const {
  const_cast<std::shared_ptr<bi::Any>&>(ptr) = fiberWorld->get(ptr);
  return ptr.get();
}
<|endoftext|>