text
stringlengths 54
60.6k
|
---|
<commit_before>/**
* @file src/wrapper_unix_sockets.h
* @author Scott L. Price <[email protected]>
* @note (C) 2015 Scott L. Price
* @brief A small http server for embedded systems
* @details
*
* The MIT License (MIT)
*
* Copyright (c) 2015 Scott Price
*
* 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.
*/
#include <stdint.h>
#include <inttypes.h>
#include "application.h"
#include "attohttp.h"
// Done include this bit until the attohttp.h file has been included
/** This is our unix socket */
TCPServer *w_server;
/**
* @brief The init function for the wrapper
*
* This function creates the server socket, and sets everything up
*
* @param port The port to open
*
* @return None
*/
void
attoHTTPWrapperInit(uint16_t port)
{
attoHTTPInit();
w_server = new TCPServer(port);
w_server->begin();
}
/**
* @brief The main function for the wrapper
*
* This runs everything. It returns after servicing one socket (or none if
* there are no requests). It must be called in a loop
*
* @param setup This may or may not be used in the future.
*
* @return None
*/
void
attoHTTPWrapperMain(uint8_t setup)
{
TCPClient client = w_server->available();
if (client) {
attoHTTPExecute((void *)&client, (void *)&client);
}
}
/**
* @brief The end function for the wrapper
*
* This function closes all of the open sockets, and closes other stuff down.
*
* @return None
*/
void
attoHTTPWrapperEnd(void)
{
delete w_server;
}
/**
* @brief User function to get a byte
*
* This function must be defined by the user. It will allow this software to
* get bytes from any source.
*
* @param read This is whatever it needs to be. Could be a socket, or an object,
* or something totally different. It will be called with whatever
* extra argument was given to the execute routine.
* @param byte A pointer to the byte we need to put the next character in.
*
* @return 1 if a character was read, 0 otherwise.
*/
uint16_t
attoHTTPGetByte(void *read, uint8_t *byte) {
uint16_t ret = 0;
TCPClient *client = (TCPClient *)read;
int c;
if (client->available() > 0) {
c = client->read();
if (c >= 0) {
*byte = (c & 0xFF);
Serial.println(c);
ret = 1;
}
}
return ret;
}
/**
* @brief User function to set a byte
*
* This function must be defined by the user. It will allow this software to
* set bytes to any destination.
*
* @param write This is whatever it needs to be. Could be a socket, or an object,
* or something totally different. It will be called with whatever
* extra argument was given to the execute routine.
* @param byte A pointer to the byte we need to put the next character in.
*
* @return 1 if a character was read, 0 otherwise.
*/
uint16_t
attoHTTPSetByte(void *write, uint8_t byte) {
TCPClient *client = (TCPClient *)write;
return client->write((const uint8_t *)&byte, 1);
}
<commit_msg>It now flushes the client buffer and properly disconnects from the client. I also removed some test code.<commit_after>/**
* @file src/wrapper_unix_sockets.h
* @author Scott L. Price <[email protected]>
* @note (C) 2015 Scott L. Price
* @brief A small http server for embedded systems
* @details
*
* The MIT License (MIT)
*
* Copyright (c) 2015 Scott Price
*
* 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.
*/
#include <stdint.h>
#include <inttypes.h>
#include "application.h"
#include "attohttp.h"
// Done include this bit until the attohttp.h file has been included
/** This is our unix socket */
TCPServer *w_server;
/**
* @brief The init function for the wrapper
*
* This function creates the server socket, and sets everything up
*
* @param port The port to open
*
* @return None
*/
void
attoHTTPWrapperInit(uint16_t port)
{
attoHTTPInit();
w_server = new TCPServer(port);
w_server->begin();
}
/**
* @brief The main function for the wrapper
*
* This runs everything. It returns after servicing one socket (or none if
* there are no requests). It must be called in a loop
*
* @param setup This may or may not be used in the future.
*
* @return None
*/
void
attoHTTPWrapperMain(uint8_t setup)
{
TCPClient client = w_server->available();
if (client) {
attoHTTPExecute((void *)&client, (void *)&client);
client.flush();
}
client.stop();
}
/**
* @brief The end function for the wrapper
*
* This function closes all of the open sockets, and closes other stuff down.
*
* @return None
*/
void
attoHTTPWrapperEnd(void)
{
delete w_server;
}
/**
* @brief User function to get a byte
*
* This function must be defined by the user. It will allow this software to
* get bytes from any source.
*
* @param read This is whatever it needs to be. Could be a socket, or an object,
* or something totally different. It will be called with whatever
* extra argument was given to the execute routine.
* @param byte A pointer to the byte we need to put the next character in.
*
* @return 1 if a character was read, 0 otherwise.
*/
uint16_t
attoHTTPGetByte(void *read, uint8_t *byte) {
uint16_t ret = 0;
TCPClient *client = (TCPClient *)read;
int c;
if (client->available() > 0) {
c = client->read();
if (c >= 0) {
*byte = (c & 0xFF);
ret = 1;
}
}
return ret;
}
/**
* @brief User function to set a byte
*
* This function must be defined by the user. It will allow this software to
* set bytes to any destination.
*
* @param write This is whatever it needs to be. Could be a socket, or an object,
* or something totally different. It will be called with whatever
* extra argument was given to the execute routine.
* @param byte A pointer to the byte we need to put the next character in.
*
* @return 1 if a character was read, 0 otherwise.
*/
uint16_t
attoHTTPSetByte(void *write, uint8_t byte) {
TCPClient *client = (TCPClient *)write;
return client->write((const uint8_t *)&byte, 1);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2022 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_HOOFS_PLATFORM_LOG_LOGGER_HPP
#define IOX_HOOFS_PLATFORM_LOG_LOGGER_HPP
#include "iceoryx_hoofs/log/platform_building_blocks/console_logger.hpp"
#include "iceoryx_hoofs/log/platform_building_blocks/logger.hpp"
namespace iox
{
namespace platform
{
using LogLevel = pbb::LogLevel;
using pbb::asStringLiteral;
using pbb::logLevelFromEnvOr;
using Logger = pbb::Logger<pbb::ConsoleLogger>;
using TestingLoggerBase = pbb::Logger<pbb::ConsoleLogger>;
/// @todo iox-#1345 make this a compile time option since if will reduce performance but some logger might want
/// to do the filtering by themselves
static constexpr bool IGNORE_ACTIVE_LOG_LEVEL{false};
/// @todo iox-#1345 compile time option for minimal compiled log level, i.e. all lower log level should be
/// optimized out; this is different than IGNORE_ACTIVE_LOG_LEVEL since the active log level could still be set to off
static constexpr LogLevel MINIMAL_LOG_LEVEL{LogLevel::TRACE};
} // namespace platform
} // namespace iox
#endif // IOX_HOOFS_PLATFORM_LOG_LOGGER_HPP
<commit_msg>iox-#1345 Add doxygen documentation to platform/logger.hpp<commit_after>// Copyright (c) 2022 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_HOOFS_PLATFORM_LOG_LOGGER_HPP
#define IOX_HOOFS_PLATFORM_LOG_LOGGER_HPP
#include "iceoryx_hoofs/log/platform_building_blocks/console_logger.hpp"
#include "iceoryx_hoofs/log/platform_building_blocks/logger.hpp"
namespace iox
{
namespace platform
{
using LogLevel = pbb::LogLevel;
using pbb::asStringLiteral;
using pbb::logLevelFromEnvOr;
using Logger = pbb::Logger<pbb::ConsoleLogger>;
using TestingLoggerBase = pbb::Logger<pbb::ConsoleLogger>;
/// @todo iox-#1345 make this a compile time option
/// @brief If set to true, the IOX_LOG macro will ignore the the configured log level and forward all messages to the
/// logger. This is useful in cases the default ConsoleLogger is replaced by a custom logger which does the filtering by
/// itself
/// @note This has an performance impact if set to true since the lazy evaluation of the logged data will be jimmied.
static constexpr bool IGNORE_ACTIVE_LOG_LEVEL{false};
/// @todo iox-#1345 make this a compile time option
/// @brief The minimal log level which will be compiled into the application. All log levels below this will be
/// optimized out at compile time
/// @note This is different than IGNORE_ACTIVE_LOG_LEVEL since the active log level could still be set to off at runtime
static constexpr LogLevel MINIMAL_LOG_LEVEL{LogLevel::TRACE};
} // namespace platform
} // namespace iox
#endif // IOX_HOOFS_PLATFORM_LOG_LOGGER_HPP
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: TestCellDistanceSelector.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .SECTION Thanks
// This test was written by Philippe Pebay, Kitware SAS 2012
#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkExtractSelection.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkCellDistanceSelector.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkPointData.h"
#include "vtkSelection.h"
#include "vtkSelectionNode.h"
#include "vtkSmartPointer.h"
#include "vtkTestUtilities.h"
#include "vtkUnstructuredGrid.h"
#include "vtkUnstructuredGridReader.h"
#include "vtkUnstructuredGridWriter.h"
#include <vtksys/ios/sstream>
// Reference values
vtkIdType cardCellDistanceSelection[] =
{
125,
16,
19,
73,
};
// ------------------------------------------------------------------------------------------------
static int CheckExtractedUGrid( vtkExtractSelection* extract,
const char* tag,
int testIdx,
bool writeGrid )
{
// Output must be a multiblock dataset
vtkMultiBlockDataSet* outputMB = vtkMultiBlockDataSet::SafeDownCast( extract->GetOutput() );
if ( ! outputMB )
{
vtkGenericWarningMacro("Cannot downcast extracted selection to multiblock dataset.");
return 1;
}
// First block must be an unstructured grid
vtkUnstructuredGrid* ugrid = vtkUnstructuredGrid::SafeDownCast( outputMB->GetBlock( 0 ) );
if ( ! ugrid )
{
vtkGenericWarningMacro("Cannot downcast extracted selection to unstructured grid.");
return 1;
}
// Initialize test status
int testStatus = 0;
cerr << endl;
// Verify selection cardinality
vtkIdType nCells = ugrid->GetNumberOfCells();
cout << tag
<< " contains "
<< nCells
<< " cells."
<< endl;
if ( nCells != cardCellDistanceSelection[testIdx] )
{
vtkGenericWarningMacro( "Incorrect cardinality: "
<< nCells
<< " != "
<< cardCellDistanceSelection[testIdx] );
testStatus = 1;
}
// Verify selection cells
cerr << "Original cell Ids: ";
ugrid->GetCellData()->SetActiveScalars( "vtkOriginalCellIds" );
vtkDataArray* oCellIds = ugrid->GetCellData()->GetScalars();
for ( vtkIdType i = 0; i < oCellIds->GetNumberOfTuples(); ++ i )
{
cerr << oCellIds->GetTuple1( i )
<< " ";
}
cerr << endl;
// If requested, write mesh
if ( writeGrid )
{
vtksys_ios::ostringstream fileNameSS;
fileNameSS << "./CellDistanceExtraction-"
<< testIdx
<< ".vtk";
vtkSmartPointer<vtkUnstructuredGridWriter> writer = vtkSmartPointer<vtkUnstructuredGridWriter>::New();
writer->SetFileName( fileNameSS.str().c_str() );
writer->SetInputData( ugrid );
writer->Write();
cerr << "Wrote file "
<< fileNameSS.str()
<< endl;
}
return testStatus;
}
//----------------------------------------------------------------------------
int TestCellDistanceSelector( int argc, char * argv [] )
{
// Initialize test value
int testIntValue = 0;
// Read 3D unstructured input mesh
char* fileName = vtkTestUtilities::ExpandDataFileName( argc, argv, "Data/AngularSector.vtk");
vtkSmartPointer<vtkUnstructuredGridReader> reader = vtkSmartPointer<vtkUnstructuredGridReader>::New();
reader->SetFileName( fileName );
reader->Update();
delete [] fileName;
// Create multi-block mesh for linear selector
vtkSmartPointer<vtkMultiBlockDataSet> mesh = vtkSmartPointer<vtkMultiBlockDataSet>::New();
mesh->SetNumberOfBlocks( 1 );
mesh->GetMetaData( static_cast<unsigned>( 0 ) )->Set( vtkCompositeDataSet::NAME(), "Mesh" );
mesh->SetBlock( 0, reader->GetOutput() );
// *****************************************************************************
// 0. Selection within distance of 2 from cell 7010
// *****************************************************************************
// Create a selection, sel0, of cell with index 7010
vtkSmartPointer<vtkIdTypeArray> selArr0 = vtkSmartPointer<vtkIdTypeArray>::New();
selArr0->InsertNextValue( 7010 );
vtkSmartPointer<vtkSelectionNode> selNode0 = vtkSmartPointer<vtkSelectionNode>::New();
selNode0->SetContentType( vtkSelectionNode::INDICES );
selNode0->SetFieldType( vtkSelectionNode::CELL );
selNode0->GetProperties()->Set( vtkSelectionNode::COMPOSITE_INDEX(), 1 );
selNode0->SetSelectionList( selArr0 );
vtkSmartPointer<vtkSelection> sel0 = vtkSmartPointer<vtkSelection>::New();
sel0->AddNode( selNode0 );
// Create selection up to topological distance of 2
vtkSmartPointer<vtkCellDistanceSelector> ls0 = vtkSmartPointer<vtkCellDistanceSelector>::New();
ls0->SetInputMesh( mesh );
ls0->SetInputSelection( sel0 );
ls0->SetDistance( 2 );
// Extract selection from mesh
vtkSmartPointer<vtkExtractSelection> es0 = vtkSmartPointer<vtkExtractSelection>::New();
es0->SetInputData( 0, mesh );
es0->SetInputConnection( 1, ls0->GetOutputPort() );
es0->Update();
testIntValue += CheckExtractedUGrid( es0, "Selection d({7010})<3", 0, true );
// *****************************************************************************
// 1. Selection at distance of 1 from ridge 7643-7499-7355-7211, excluding it
// *****************************************************************************
// Create a selection, sel1, of cells with indices 7643-7499-7355-7211
vtkSmartPointer<vtkIdTypeArray> selArr1 = vtkSmartPointer<vtkIdTypeArray>::New();
selArr1->InsertNextValue( 7643 );
selArr1->InsertNextValue( 7499 );
selArr1->InsertNextValue( 7355 );
selArr1->InsertNextValue( 7211 );
vtkSmartPointer<vtkSelectionNode> selNode1 = vtkSmartPointer<vtkSelectionNode>::New();
selNode1->SetContentType( vtkSelectionNode::INDICES );
selNode1->SetFieldType( vtkSelectionNode::CELL );
selNode1->GetProperties()->Set( vtkSelectionNode::COMPOSITE_INDEX(), 1 );
selNode1->SetSelectionList( selArr1 );
vtkSmartPointer<vtkSelection> sel1 = vtkSmartPointer<vtkSelection>::New();
sel1->AddNode( selNode1 );
// Create selection at distance of 1
vtkSmartPointer<vtkCellDistanceSelector> ls1 = vtkSmartPointer<vtkCellDistanceSelector>::New();
ls1->SetInputMesh( mesh );
ls1->SetInputSelection( sel1 );
ls1->SetDistance( 1 );
ls1->IncludeSeedOff();
// Extract selection from mesh
vtkSmartPointer<vtkExtractSelection> es1 = vtkSmartPointer<vtkExtractSelection>::New();
es1->SetInputData( 0, mesh );
es1->SetInputConnection( 1, ls1->GetOutputPort() );
es1->Update();
testIntValue += CheckExtractedUGrid( es1, "Selection d({7643-7499-7355-7211})=1", 1, true );
// *****************************************************************************
// 2. Selection at distance of 2 from corner 7632
// *****************************************************************************
// Create a selection, sel2, of cell with index 7632
vtkSmartPointer<vtkIdTypeArray> selArr2 = vtkSmartPointer<vtkIdTypeArray>::New();
selArr2->InsertNextValue( 7632 );
vtkSmartPointer<vtkSelectionNode> selNode2 = vtkSmartPointer<vtkSelectionNode>::New();
selNode2->SetContentType( vtkSelectionNode::INDICES );
selNode2->SetFieldType( vtkSelectionNode::CELL );
selNode2->GetProperties()->Set( vtkSelectionNode::COMPOSITE_INDEX(), 1 );
selNode2->SetSelectionList( selArr2 );
vtkSmartPointer<vtkSelection> sel2 = vtkSmartPointer<vtkSelection>::New();
sel2->AddNode( selNode2 );
// Create selection at distance of 2
vtkSmartPointer<vtkCellDistanceSelector> ls2 = vtkSmartPointer<vtkCellDistanceSelector>::New();
ls2->SetInputMesh( mesh );
ls2->SetInputSelection( sel2 );
ls2->SetDistance( 2 );
ls2->IncludeSeedOff();
ls2->AddIntermediateOff();
// Extract selection from mesh
vtkSmartPointer<vtkExtractSelection> es2 = vtkSmartPointer<vtkExtractSelection>::New();
es2->SetInputData( 0, mesh );
es2->SetInputConnection( 1, ls2->GetOutputPort() );
es2->Update();
testIntValue += CheckExtractedUGrid( es2, "Selection d({7632})=2", 2, true );
// *****************************************************************************
// 3. Selection within distance of 1 from cells 6413, 7268, and 7399
// *****************************************************************************
// Create a selection, sel3, of cells with indices 6413, 7268, and 7399
vtkSmartPointer<vtkIdTypeArray> selArr3 = vtkSmartPointer<vtkIdTypeArray>::New();
selArr3->InsertNextValue( 6413 );
selArr3->InsertNextValue( 7268 );
selArr3->InsertNextValue( 7399 );
vtkSmartPointer<vtkSelectionNode> selNode3 = vtkSmartPointer<vtkSelectionNode>::New();
selNode3->SetContentType( vtkSelectionNode::INDICES );
selNode3->SetFieldType( vtkSelectionNode::CELL );
selNode3->GetProperties()->Set( vtkSelectionNode::COMPOSITE_INDEX(), 1 );
selNode3->SetSelectionList( selArr3 );
vtkSmartPointer<vtkSelection> sel3 = vtkSmartPointer<vtkSelection>::New();
sel3->AddNode( selNode3 );
// Create selection within distance of 1
vtkSmartPointer<vtkCellDistanceSelector> ls3 = vtkSmartPointer<vtkCellDistanceSelector>::New();
ls3->SetInputMesh( mesh );
ls3->SetInputSelection( sel3 );
ls3->SetDistance( 1 );
// Extract selection from mesh
vtkSmartPointer<vtkExtractSelection> es3 = vtkSmartPointer<vtkExtractSelection>::New();
es3->SetInputData( 0, mesh );
es3->SetInputConnection( 1, ls3->GetOutputPort() );
es3->Update();
testIntValue += CheckExtractedUGrid( es3, "Selection d({6413,7268,7399})=1", 3, true );
return testIntValue;
}
<commit_msg>Added a test for the IncludeSeed option when the seed is visible<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: TestCellDistanceSelector.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .SECTION Thanks
// This test was written by Philippe Pebay, Kitware SAS 2012
#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkExtractSelection.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkCellDistanceSelector.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkPointData.h"
#include "vtkSelection.h"
#include "vtkSelectionNode.h"
#include "vtkSmartPointer.h"
#include "vtkTestUtilities.h"
#include "vtkUnstructuredGrid.h"
#include "vtkUnstructuredGridReader.h"
#include "vtkUnstructuredGridWriter.h"
#include <vtksys/ios/sstream>
// Reference values
vtkIdType cardCellDistanceSelection[] =
{
125,
16,
20,
73,
};
// ------------------------------------------------------------------------------------------------
static int CheckExtractedUGrid( vtkExtractSelection* extract,
const char* tag,
int testIdx,
bool writeGrid )
{
// Output must be a multiblock dataset
vtkMultiBlockDataSet* outputMB = vtkMultiBlockDataSet::SafeDownCast( extract->GetOutput() );
if ( ! outputMB )
{
vtkGenericWarningMacro("Cannot downcast extracted selection to multiblock dataset.");
return 1;
}
// First block must be an unstructured grid
vtkUnstructuredGrid* ugrid = vtkUnstructuredGrid::SafeDownCast( outputMB->GetBlock( 0 ) );
if ( ! ugrid )
{
vtkGenericWarningMacro("Cannot downcast extracted selection to unstructured grid.");
return 1;
}
// Initialize test status
int testStatus = 0;
cerr << endl;
// Verify selection cardinality
vtkIdType nCells = ugrid->GetNumberOfCells();
cout << tag
<< " contains "
<< nCells
<< " cells."
<< endl;
if ( nCells != cardCellDistanceSelection[testIdx] )
{
vtkGenericWarningMacro( "Incorrect cardinality: "
<< nCells
<< " != "
<< cardCellDistanceSelection[testIdx] );
testStatus = 1;
}
// Verify selection cells
cerr << "Original cell Ids: ";
ugrid->GetCellData()->SetActiveScalars( "vtkOriginalCellIds" );
vtkDataArray* oCellIds = ugrid->GetCellData()->GetScalars();
for ( vtkIdType i = 0; i < oCellIds->GetNumberOfTuples(); ++ i )
{
cerr << oCellIds->GetTuple1( i )
<< " ";
}
cerr << endl;
// If requested, write mesh
if ( writeGrid )
{
vtksys_ios::ostringstream fileNameSS;
fileNameSS << "./CellDistanceExtraction-"
<< testIdx
<< ".vtk";
vtkSmartPointer<vtkUnstructuredGridWriter> writer = vtkSmartPointer<vtkUnstructuredGridWriter>::New();
writer->SetFileName( fileNameSS.str().c_str() );
writer->SetInputData( ugrid );
writer->Write();
cerr << "Wrote file "
<< fileNameSS.str()
<< endl;
}
return testStatus;
}
//----------------------------------------------------------------------------
int TestCellDistanceSelector( int argc, char * argv [] )
{
// Initialize test value
int testIntValue = 0;
// Read 3D unstructured input mesh
char* fileName = vtkTestUtilities::ExpandDataFileName( argc, argv, "Data/AngularSector.vtk");
vtkSmartPointer<vtkUnstructuredGridReader> reader = vtkSmartPointer<vtkUnstructuredGridReader>::New();
reader->SetFileName( fileName );
reader->Update();
delete [] fileName;
// Create multi-block mesh for linear selector
vtkSmartPointer<vtkMultiBlockDataSet> mesh = vtkSmartPointer<vtkMultiBlockDataSet>::New();
mesh->SetNumberOfBlocks( 1 );
mesh->GetMetaData( static_cast<unsigned>( 0 ) )->Set( vtkCompositeDataSet::NAME(), "Mesh" );
mesh->SetBlock( 0, reader->GetOutput() );
// *****************************************************************************
// 0. Selection within distance of 2 from cell 7010
// *****************************************************************************
// Create a selection, sel0, of cell with index 7010
vtkSmartPointer<vtkIdTypeArray> selArr0 = vtkSmartPointer<vtkIdTypeArray>::New();
selArr0->InsertNextValue( 7010 );
vtkSmartPointer<vtkSelectionNode> selNode0 = vtkSmartPointer<vtkSelectionNode>::New();
selNode0->SetContentType( vtkSelectionNode::INDICES );
selNode0->SetFieldType( vtkSelectionNode::CELL );
selNode0->GetProperties()->Set( vtkSelectionNode::COMPOSITE_INDEX(), 1 );
selNode0->SetSelectionList( selArr0 );
vtkSmartPointer<vtkSelection> sel0 = vtkSmartPointer<vtkSelection>::New();
sel0->AddNode( selNode0 );
// Create selection up to topological distance of 2
vtkSmartPointer<vtkCellDistanceSelector> ls0 = vtkSmartPointer<vtkCellDistanceSelector>::New();
ls0->SetInputMesh( mesh );
ls0->SetInputSelection( sel0 );
ls0->SetDistance( 2 );
// Extract selection from mesh
vtkSmartPointer<vtkExtractSelection> es0 = vtkSmartPointer<vtkExtractSelection>::New();
es0->SetInputData( 0, mesh );
es0->SetInputConnection( 1, ls0->GetOutputPort() );
es0->Update();
testIntValue += CheckExtractedUGrid( es0, "Selection d({7010})<3", 0, true );
// *****************************************************************************
// 1. Selection at distance of 1 from ridge 7643-7499-7355-7211, excluding it
// *****************************************************************************
// Create a selection, sel1, of cells with indices 7643-7499-7355-7211
vtkSmartPointer<vtkIdTypeArray> selArr1 = vtkSmartPointer<vtkIdTypeArray>::New();
selArr1->InsertNextValue( 7643 );
selArr1->InsertNextValue( 7499 );
selArr1->InsertNextValue( 7355 );
selArr1->InsertNextValue( 7211 );
vtkSmartPointer<vtkSelectionNode> selNode1 = vtkSmartPointer<vtkSelectionNode>::New();
selNode1->SetContentType( vtkSelectionNode::INDICES );
selNode1->SetFieldType( vtkSelectionNode::CELL );
selNode1->GetProperties()->Set( vtkSelectionNode::COMPOSITE_INDEX(), 1 );
selNode1->SetSelectionList( selArr1 );
vtkSmartPointer<vtkSelection> sel1 = vtkSmartPointer<vtkSelection>::New();
sel1->AddNode( selNode1 );
// Create selection at distance of 1
vtkSmartPointer<vtkCellDistanceSelector> ls1 = vtkSmartPointer<vtkCellDistanceSelector>::New();
ls1->SetInputMesh( mesh );
ls1->SetInputSelection( sel1 );
ls1->SetDistance( 1 );
ls1->IncludeSeedOff();
// Extract selection from mesh
vtkSmartPointer<vtkExtractSelection> es1 = vtkSmartPointer<vtkExtractSelection>::New();
es1->SetInputData( 0, mesh );
es1->SetInputConnection( 1, ls1->GetOutputPort() );
es1->Update();
testIntValue += CheckExtractedUGrid( es1, "Selection d({7643-7499-7355-7211})=1", 1, true );
// *****************************************************************************
// 2. Selection at distance of 2 from corner 7632, retaining seed
// *****************************************************************************
// Create a selection, sel2, of cell with index 7632
vtkSmartPointer<vtkIdTypeArray> selArr2 = vtkSmartPointer<vtkIdTypeArray>::New();
selArr2->InsertNextValue( 7632 );
vtkSmartPointer<vtkSelectionNode> selNode2 = vtkSmartPointer<vtkSelectionNode>::New();
selNode2->SetContentType( vtkSelectionNode::INDICES );
selNode2->SetFieldType( vtkSelectionNode::CELL );
selNode2->GetProperties()->Set( vtkSelectionNode::COMPOSITE_INDEX(), 1 );
selNode2->SetSelectionList( selArr2 );
vtkSmartPointer<vtkSelection> sel2 = vtkSmartPointer<vtkSelection>::New();
sel2->AddNode( selNode2 );
// Create selection at distance of 2
vtkSmartPointer<vtkCellDistanceSelector> ls2 = vtkSmartPointer<vtkCellDistanceSelector>::New();
ls2->SetInputMesh( mesh );
ls2->SetInputSelection( sel2 );
ls2->SetDistance( 2 );
ls2->AddIntermediateOff();
// Extract selection from mesh
vtkSmartPointer<vtkExtractSelection> es2 = vtkSmartPointer<vtkExtractSelection>::New();
es2->SetInputData( 0, mesh );
es2->SetInputConnection( 1, ls2->GetOutputPort() );
es2->Update();
testIntValue += CheckExtractedUGrid( es2, "Selection d({7632})=0|2", 2, true );
// *****************************************************************************
// 3. Selection within distance of 1 from cells 6413, 7268, and 7399
// *****************************************************************************
// Create a selection, sel3, of cells with indices 6413, 7268, and 7399
vtkSmartPointer<vtkIdTypeArray> selArr3 = vtkSmartPointer<vtkIdTypeArray>::New();
selArr3->InsertNextValue( 6413 );
selArr3->InsertNextValue( 7268 );
selArr3->InsertNextValue( 7399 );
vtkSmartPointer<vtkSelectionNode> selNode3 = vtkSmartPointer<vtkSelectionNode>::New();
selNode3->SetContentType( vtkSelectionNode::INDICES );
selNode3->SetFieldType( vtkSelectionNode::CELL );
selNode3->GetProperties()->Set( vtkSelectionNode::COMPOSITE_INDEX(), 1 );
selNode3->SetSelectionList( selArr3 );
vtkSmartPointer<vtkSelection> sel3 = vtkSmartPointer<vtkSelection>::New();
sel3->AddNode( selNode3 );
// Create selection within distance of 1
vtkSmartPointer<vtkCellDistanceSelector> ls3 = vtkSmartPointer<vtkCellDistanceSelector>::New();
ls3->SetInputMesh( mesh );
ls3->SetInputSelection( sel3 );
ls3->SetDistance( 1 );
// Extract selection from mesh
vtkSmartPointer<vtkExtractSelection> es3 = vtkSmartPointer<vtkExtractSelection>::New();
es3->SetInputData( 0, mesh );
es3->SetInputConnection( 1, ls3->GetOutputPort() );
es3->Update();
testIntValue += CheckExtractedUGrid( es3, "Selection d({6413,7268,7399})=1", 3, true );
return testIntValue;
}
<|endoftext|> |
<commit_before>//===-- AuxVector.cpp -------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "AuxVector.h"
#include "lldb/Target/Process.h"
#include "lldb/Utility/DataBufferHeap.h"
#include "lldb/Utility/DataExtractor.h"
#include "lldb/Utility/Log.h"
using namespace lldb;
using namespace lldb_private;
static bool GetMaxU64(DataExtractor &data, lldb::offset_t *offset_ptr,
uint64_t *value, unsigned int byte_size) {
lldb::offset_t saved_offset = *offset_ptr;
*value = data.GetMaxU64(offset_ptr, byte_size);
return *offset_ptr != saved_offset;
}
static bool ParseAuxvEntry(DataExtractor &data, AuxVector::Entry &entry,
lldb::offset_t *offset_ptr, unsigned int byte_size) {
if (!GetMaxU64(data, offset_ptr, &entry.type, byte_size))
return false;
if (!GetMaxU64(data, offset_ptr, &entry.value, byte_size))
return false;
return true;
}
DataBufferSP AuxVector::GetAuxvData() {
if (m_process)
return m_process->GetAuxvData();
else
return DataBufferSP();
}
void AuxVector::ParseAuxv(DataExtractor &data) {
const unsigned int byte_size = m_process->GetAddressByteSize();
lldb::offset_t offset = 0;
for (;;) {
Entry entry;
if (!ParseAuxvEntry(data, entry, &offset, byte_size))
break;
if (entry.type == AUXV_AT_NULL)
break;
if (entry.type == AUXV_AT_IGNORE)
continue;
m_auxv.push_back(entry);
}
}
AuxVector::AuxVector(Process *process) : m_process(process) {
DataExtractor data;
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
data.SetData(GetAuxvData());
data.SetByteOrder(m_process->GetByteOrder());
data.SetAddressByteSize(m_process->GetAddressByteSize());
ParseAuxv(data);
if (log)
DumpToLog(log);
}
AuxVector::iterator AuxVector::FindEntry(EntryType type) const {
for (iterator I = begin(); I != end(); ++I) {
if (I->type == static_cast<uint64_t>(type))
return I;
}
return end();
}
void AuxVector::DumpToLog(Log *log) const {
if (!log)
return;
log->PutCString("AuxVector: ");
for (iterator I = begin(); I != end(); ++I) {
log->Printf(" %s [%" PRIu64 "]: %" PRIx64, GetEntryName(*I), I->type,
I->value);
}
}
const char *AuxVector::GetEntryName(EntryType type) {
const char *name = "AT_???";
#define ENTRY_NAME(_type) \
_type: \
name = #_type + 5
switch (type) {
case ENTRY_NAME(AUXV_AT_NULL); break;
case ENTRY_NAME(AUXV_AT_IGNORE); break;
case ENTRY_NAME(AUXV_AT_EXECFD); break;
case ENTRY_NAME(AUXV_AT_PHDR); break;
case ENTRY_NAME(AUXV_AT_PHENT); break;
case ENTRY_NAME(AUXV_AT_PHNUM); break;
case ENTRY_NAME(AUXV_AT_PAGESZ); break;
case ENTRY_NAME(AUXV_AT_BASE); break;
case ENTRY_NAME(AUXV_AT_FLAGS); break;
case ENTRY_NAME(AUXV_AT_ENTRY); break;
case ENTRY_NAME(AUXV_AT_NOTELF); break;
case ENTRY_NAME(AUXV_AT_UID); break;
case ENTRY_NAME(AUXV_AT_EUID); break;
case ENTRY_NAME(AUXV_AT_GID); break;
case ENTRY_NAME(AUXV_AT_EGID); break;
case ENTRY_NAME(AUXV_AT_CLKTCK); break;
case ENTRY_NAME(AUXV_AT_PLATFORM); break;
case ENTRY_NAME(AUXV_AT_HWCAP); break;
case ENTRY_NAME(AUXV_AT_FPUCW); break;
case ENTRY_NAME(AUXV_AT_DCACHEBSIZE); break;
case ENTRY_NAME(AUXV_AT_ICACHEBSIZE); break;
case ENTRY_NAME(AUXV_AT_UCACHEBSIZE); break;
case ENTRY_NAME(AUXV_AT_IGNOREPPC); break;
case ENTRY_NAME(AUXV_AT_SECURE); break;
case ENTRY_NAME(AUXV_AT_BASE_PLATFORM); break;
case ENTRY_NAME(AUXV_AT_RANDOM); break;
case ENTRY_NAME(AUXV_AT_EXECFN); break;
case ENTRY_NAME(AUXV_AT_SYSINFO); break;
case ENTRY_NAME(AUXV_AT_SYSINFO_EHDR); break;
case ENTRY_NAME(AUXV_AT_L1I_CACHESHAPE); break;
case ENTRY_NAME(AUXV_AT_L1D_CACHESHAPE); break;
case ENTRY_NAME(AUXV_AT_L2_CACHESHAPE); break;
case ENTRY_NAME(AUXV_AT_L3_CACHESHAPE); break;
}
#undef ENTRY_NAME
return name;
}
<commit_msg>[lldb] Fix -Wstring-plus-int warning in POSIX-DYLD/AuxVector.cpp<commit_after>//===-- AuxVector.cpp -------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "AuxVector.h"
#include "lldb/Target/Process.h"
#include "lldb/Utility/DataBufferHeap.h"
#include "lldb/Utility/DataExtractor.h"
#include "lldb/Utility/Log.h"
using namespace lldb;
using namespace lldb_private;
static bool GetMaxU64(DataExtractor &data, lldb::offset_t *offset_ptr,
uint64_t *value, unsigned int byte_size) {
lldb::offset_t saved_offset = *offset_ptr;
*value = data.GetMaxU64(offset_ptr, byte_size);
return *offset_ptr != saved_offset;
}
static bool ParseAuxvEntry(DataExtractor &data, AuxVector::Entry &entry,
lldb::offset_t *offset_ptr, unsigned int byte_size) {
if (!GetMaxU64(data, offset_ptr, &entry.type, byte_size))
return false;
if (!GetMaxU64(data, offset_ptr, &entry.value, byte_size))
return false;
return true;
}
DataBufferSP AuxVector::GetAuxvData() {
if (m_process)
return m_process->GetAuxvData();
else
return DataBufferSP();
}
void AuxVector::ParseAuxv(DataExtractor &data) {
const unsigned int byte_size = m_process->GetAddressByteSize();
lldb::offset_t offset = 0;
for (;;) {
Entry entry;
if (!ParseAuxvEntry(data, entry, &offset, byte_size))
break;
if (entry.type == AUXV_AT_NULL)
break;
if (entry.type == AUXV_AT_IGNORE)
continue;
m_auxv.push_back(entry);
}
}
AuxVector::AuxVector(Process *process) : m_process(process) {
DataExtractor data;
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
data.SetData(GetAuxvData());
data.SetByteOrder(m_process->GetByteOrder());
data.SetAddressByteSize(m_process->GetAddressByteSize());
ParseAuxv(data);
if (log)
DumpToLog(log);
}
AuxVector::iterator AuxVector::FindEntry(EntryType type) const {
for (iterator I = begin(); I != end(); ++I) {
if (I->type == static_cast<uint64_t>(type))
return I;
}
return end();
}
void AuxVector::DumpToLog(Log *log) const {
if (!log)
return;
log->PutCString("AuxVector: ");
for (iterator I = begin(); I != end(); ++I) {
log->Printf(" %s [%" PRIu64 "]: %" PRIx64, GetEntryName(*I), I->type,
I->value);
}
}
const char *AuxVector::GetEntryName(EntryType type) {
const char *name = "AT_???";
#define ENTRY_NAME(_type) \
_type: \
name = &#_type[5]
switch (type) {
case ENTRY_NAME(AUXV_AT_NULL); break;
case ENTRY_NAME(AUXV_AT_IGNORE); break;
case ENTRY_NAME(AUXV_AT_EXECFD); break;
case ENTRY_NAME(AUXV_AT_PHDR); break;
case ENTRY_NAME(AUXV_AT_PHENT); break;
case ENTRY_NAME(AUXV_AT_PHNUM); break;
case ENTRY_NAME(AUXV_AT_PAGESZ); break;
case ENTRY_NAME(AUXV_AT_BASE); break;
case ENTRY_NAME(AUXV_AT_FLAGS); break;
case ENTRY_NAME(AUXV_AT_ENTRY); break;
case ENTRY_NAME(AUXV_AT_NOTELF); break;
case ENTRY_NAME(AUXV_AT_UID); break;
case ENTRY_NAME(AUXV_AT_EUID); break;
case ENTRY_NAME(AUXV_AT_GID); break;
case ENTRY_NAME(AUXV_AT_EGID); break;
case ENTRY_NAME(AUXV_AT_CLKTCK); break;
case ENTRY_NAME(AUXV_AT_PLATFORM); break;
case ENTRY_NAME(AUXV_AT_HWCAP); break;
case ENTRY_NAME(AUXV_AT_FPUCW); break;
case ENTRY_NAME(AUXV_AT_DCACHEBSIZE); break;
case ENTRY_NAME(AUXV_AT_ICACHEBSIZE); break;
case ENTRY_NAME(AUXV_AT_UCACHEBSIZE); break;
case ENTRY_NAME(AUXV_AT_IGNOREPPC); break;
case ENTRY_NAME(AUXV_AT_SECURE); break;
case ENTRY_NAME(AUXV_AT_BASE_PLATFORM); break;
case ENTRY_NAME(AUXV_AT_RANDOM); break;
case ENTRY_NAME(AUXV_AT_EXECFN); break;
case ENTRY_NAME(AUXV_AT_SYSINFO); break;
case ENTRY_NAME(AUXV_AT_SYSINFO_EHDR); break;
case ENTRY_NAME(AUXV_AT_L1I_CACHESHAPE); break;
case ENTRY_NAME(AUXV_AT_L1D_CACHESHAPE); break;
case ENTRY_NAME(AUXV_AT_L2_CACHESHAPE); break;
case ENTRY_NAME(AUXV_AT_L3_CACHESHAPE); break;
}
#undef ENTRY_NAME
return name;
}
<|endoftext|> |
<commit_before>#pragma once
#include "depthai-shared/common/CameraBoardSocket.hpp"
#include "depthai-shared/common/CameraImageOrientation.hpp"
#include "depthai-shared/datatype/RawCameraControl.hpp"
#include "depthai-shared/properties/Properties.hpp"
namespace dai {
/**
* Specify properties for ColorCamera such as camera ID, ...
*/
struct ColorCameraProperties : PropertiesSerializable<Properties, ColorCameraProperties> {
static constexpr int AUTO = -1;
struct IspScale {
int32_t horizNumerator = 0;
int32_t horizDenominator = 0;
int32_t vertNumerator = 0;
int32_t vertDenominator = 0;
DEPTHAI_SERIALIZE(IspScale, horizNumerator, horizDenominator, vertNumerator, vertDenominator);
};
/**
* Select the camera sensor resolution
*/
enum class SensorResolution : int32_t { THE_1080_P, THE_1200_P, THE_4_K, THE_5_MP, THE_12_MP, THE_12P0_MP, THE_13_MP, THE_5312X6000, THE_48_MP, THE_720_P, THE_800_P };
/**
* For 24 bit color these can be either RGB or BGR
*/
enum class ColorOrder : int32_t { BGR, RGB };
/*
* Initial controls applied to ColorCamera node
*/
RawCameraControl initialControl;
/**
* Which socket will color camera use
*/
CameraBoardSocket boardSocket = CameraBoardSocket::AUTO;
/**
* Camera sensor image orientation / pixel readout
*/
CameraImageOrientation imageOrientation = CameraImageOrientation::AUTO;
/**
* For 24 bit color these can be either RGB or BGR
*/
ColorOrder colorOrder = ColorOrder::BGR;
/**
* Are colors interleaved (R1G1B1, R2G2B2, ...) or planar (R1R2..., G1G2..., B1B2)
*/
bool interleaved = true;
/**
* Are values FP16 type (0.0 - 255.0)
*/
bool fp16 = false;
/**
* Preview frame output height
*/
uint32_t previewHeight = 300;
/**
* Preview frame output width
*/
uint32_t previewWidth = 300;
/**
* Preview frame output width
*/
int32_t videoWidth = AUTO;
/**
* Preview frame output height
*/
int32_t videoHeight = AUTO;
/**
* Preview frame output width
*/
int32_t stillWidth = AUTO;
/**
* Preview frame output height
*/
int32_t stillHeight = AUTO;
/**
* Select the camera sensor resolution
*/
SensorResolution resolution = SensorResolution::THE_1080_P;
/**
* Camera sensor FPS
*/
float fps = 30.0;
/**
* Initial sensor crop, -1 signifies center crop
*/
float sensorCropX = AUTO;
float sensorCropY = AUTO;
/**
* Whether to keep aspect ratio of input (video size) or not
*/
bool previewKeepAspectRatio = true;
/**
* Configure scaling for `isp` output.
*/
IspScale ispScale;
/**
* Pool sizes
*/
int numFramesPoolRaw = 3;
int numFramesPoolIsp = 3;
int numFramesPoolVideo = 4;
int numFramesPoolPreview = 4;
int numFramesPoolStill = 4;
};
DEPTHAI_SERIALIZE_EXT(ColorCameraProperties,
initialControl,
boardSocket,
imageOrientation,
colorOrder,
interleaved,
fp16,
previewHeight,
previewWidth,
videoWidth,
videoHeight,
stillWidth,
stillHeight,
resolution,
fps,
sensorCropX,
sensorCropY,
previewKeepAspectRatio,
ispScale,
numFramesPoolRaw,
numFramesPoolIsp,
numFramesPoolVideo,
numFramesPoolPreview,
numFramesPoolStill);
} // namespace dai
<commit_msg>`make clangformat`<commit_after>#pragma once
#include "depthai-shared/common/CameraBoardSocket.hpp"
#include "depthai-shared/common/CameraImageOrientation.hpp"
#include "depthai-shared/datatype/RawCameraControl.hpp"
#include "depthai-shared/properties/Properties.hpp"
namespace dai {
/**
* Specify properties for ColorCamera such as camera ID, ...
*/
struct ColorCameraProperties : PropertiesSerializable<Properties, ColorCameraProperties> {
static constexpr int AUTO = -1;
struct IspScale {
int32_t horizNumerator = 0;
int32_t horizDenominator = 0;
int32_t vertNumerator = 0;
int32_t vertDenominator = 0;
DEPTHAI_SERIALIZE(IspScale, horizNumerator, horizDenominator, vertNumerator, vertDenominator);
};
/**
* Select the camera sensor resolution
*/
enum class SensorResolution : int32_t {
THE_1080_P,
THE_1200_P,
THE_4_K,
THE_5_MP,
THE_12_MP,
THE_12P0_MP,
THE_13_MP,
THE_5312X6000,
THE_48_MP,
THE_720_P,
THE_800_P
};
/**
* For 24 bit color these can be either RGB or BGR
*/
enum class ColorOrder : int32_t { BGR, RGB };
/*
* Initial controls applied to ColorCamera node
*/
RawCameraControl initialControl;
/**
* Which socket will color camera use
*/
CameraBoardSocket boardSocket = CameraBoardSocket::AUTO;
/**
* Camera sensor image orientation / pixel readout
*/
CameraImageOrientation imageOrientation = CameraImageOrientation::AUTO;
/**
* For 24 bit color these can be either RGB or BGR
*/
ColorOrder colorOrder = ColorOrder::BGR;
/**
* Are colors interleaved (R1G1B1, R2G2B2, ...) or planar (R1R2..., G1G2..., B1B2)
*/
bool interleaved = true;
/**
* Are values FP16 type (0.0 - 255.0)
*/
bool fp16 = false;
/**
* Preview frame output height
*/
uint32_t previewHeight = 300;
/**
* Preview frame output width
*/
uint32_t previewWidth = 300;
/**
* Preview frame output width
*/
int32_t videoWidth = AUTO;
/**
* Preview frame output height
*/
int32_t videoHeight = AUTO;
/**
* Preview frame output width
*/
int32_t stillWidth = AUTO;
/**
* Preview frame output height
*/
int32_t stillHeight = AUTO;
/**
* Select the camera sensor resolution
*/
SensorResolution resolution = SensorResolution::THE_1080_P;
/**
* Camera sensor FPS
*/
float fps = 30.0;
/**
* Initial sensor crop, -1 signifies center crop
*/
float sensorCropX = AUTO;
float sensorCropY = AUTO;
/**
* Whether to keep aspect ratio of input (video size) or not
*/
bool previewKeepAspectRatio = true;
/**
* Configure scaling for `isp` output.
*/
IspScale ispScale;
/**
* Pool sizes
*/
int numFramesPoolRaw = 3;
int numFramesPoolIsp = 3;
int numFramesPoolVideo = 4;
int numFramesPoolPreview = 4;
int numFramesPoolStill = 4;
};
DEPTHAI_SERIALIZE_EXT(ColorCameraProperties,
initialControl,
boardSocket,
imageOrientation,
colorOrder,
interleaved,
fp16,
previewHeight,
previewWidth,
videoWidth,
videoHeight,
stillWidth,
stillHeight,
resolution,
fps,
sensorCropX,
sensorCropY,
previewKeepAspectRatio,
ispScale,
numFramesPoolRaw,
numFramesPoolIsp,
numFramesPoolVideo,
numFramesPoolPreview,
numFramesPoolStill);
} // namespace dai
<|endoftext|> |
<commit_before>#include "MeshRenderer.hh"
#include "ResourceManager/Texture.hh"
#include "Core/Engine.hh"
namespace Components
{
MeshRenderer::MeshRenderer(std::string const &name, std::string const &resource) :
AComponent(name),
_mesh(GameEngine::instance()->resources().getResource(resource)),
_next(NULL)
{
}
MeshRenderer::~MeshRenderer(void)
{
}
void MeshRenderer::start()
{
}
void MeshRenderer::update()
{
GameEngine::instance()->renderer().addToRenderQueue(this);
}
void MeshRenderer::stop()
{
}
bool MeshRenderer::setShader(std::string const &name)
{
_shader = name;
return (true);
}
std::string const &MeshRenderer::getShader() const
{
return (_shader);
}
SmartPointer<Resources::SharedMesh> const &MeshRenderer::getMesh() const
{
return (_mesh);
}
void MeshRenderer::addTexture(const std::string &textureName, const std::string &name, unsigned int priority)
{
SmartPointer<Resources::Texture> texture = GameEngine::instance()->resources().getResource(textureName);
for (textureMapIt it = _textures.begin(); it != _textures.end(); ++it)
{
if (it->second.first == name)
return;
}
_textures.insert(std::make_pair(priority, std::make_pair(name, texture)));
}
void MeshRenderer::removeTexture(const std::string &name)
{
for (textureMapIt it = _textures.begin(); it != _textures.end(); ++it)
{
if (it->second.first == name)
{
_textures.erase(it);
return;
}
}
}
void MeshRenderer::bindTextures() const
{
unsigned int c = 0;
for (textureMap::const_iterator it = _textures.begin(); it != _textures.end(); ++it)
{
glActiveTexture(GL_TEXTURE0 + c);
glBindTexture(GL_TEXTURE_2D, it->second.second->getId());
++c;
}
}
void MeshRenderer::unbindTextures() const
{
//unsigned int c = 0;
//for (textureMap::const_iterator it = _textures.begin(); it != _textures.end(); ++it)
//{
// glActiveTexture(GL_TEXTURE0 + c);
// glBindTexture(GL_TEXTURE_2D, 0);
// ++c;
//}
//glActiveTexture(GL_TEXTURE0);
}
void MeshRenderer::setNext(MeshRenderer *next)
{
_next = next;
}
MeshRenderer *MeshRenderer::getNext() const
{
return (_next);
}
void MeshRenderer::addMaterial(SmartPointer<Material> material)
{
material->addObject(this);
_materials.insert(material->getName());
}
void MeshRenderer::removeMaterial(SmartPointer<Material> material)
{
// be carefull when iterating on it
material->removeObject(this);
_materials.erase(material->getName());
}
void MeshRenderer::addMaterial(const std::string &material)
{
SmartPointer<Material> m = GameEngine::instance()->renderer().getMaterialManager().getMaterial(material);
if (!m.get())
return;
m->addObject(this);
_materials.insert(m->getName());
}
void MeshRenderer::removeMaterial(const std::string &material)
{
SmartPointer<Material> m = GameEngine::instance()->renderer().getMaterialManager().getMaterial(material);
if (!m.get())
return;
m->removeObject(this);
_materials.erase(m->getName());
}
}<commit_msg>Some comments<commit_after>#include "MeshRenderer.hh"
#include "ResourceManager/Texture.hh"
#include "Core/Engine.hh"
namespace Components
{
MeshRenderer::MeshRenderer(std::string const &name, std::string const &resource) :
AComponent(name),
_mesh(GameEngine::instance()->resources().getResource(resource)),
_next(NULL)
{
}
MeshRenderer::~MeshRenderer(void)
{
}
void MeshRenderer::start()
{
}
void MeshRenderer::update()
{
GameEngine::instance()->renderer().addToRenderQueue(this);
}
void MeshRenderer::stop()
{
}
bool MeshRenderer::setShader(std::string const &name)
{
_shader = name;
return (true);
}
std::string const &MeshRenderer::getShader() const
{
return (_shader);
}
SmartPointer<Resources::SharedMesh> const &MeshRenderer::getMesh() const
{
return (_mesh);
}
void MeshRenderer::addTexture(const std::string &textureName, const std::string &name, unsigned int priority)
{
SmartPointer<Resources::Texture> texture = GameEngine::instance()->resources().getResource(textureName);
for (textureMapIt it = _textures.begin(); it != _textures.end(); ++it)
{
if (it->second.first == name)
return;
}
_textures.insert(std::make_pair(priority, std::make_pair(name, texture)));
}
void MeshRenderer::removeTexture(const std::string &name)
{
for (textureMapIt it = _textures.begin(); it != _textures.end(); ++it)
{
if (it->second.first == name)
{
_textures.erase(it);
return;
}
}
}
void MeshRenderer::bindTextures() const
{
//
// a little bit hardcodeded -> to clean
//
unsigned int c = 0;
for (textureMap::const_iterator it = _textures.begin(); it != _textures.end(); ++it)
{
glActiveTexture(GL_TEXTURE0 + c);
glBindTexture(GL_TEXTURE_2D, it->second.second->getId());
++c;
}
}
void MeshRenderer::unbindTextures() const
{
//unsigned int c = 0;
//for (textureMap::const_iterator it = _textures.begin(); it != _textures.end(); ++it)
//{
// glActiveTexture(GL_TEXTURE0 + c);
// glBindTexture(GL_TEXTURE_2D, 0);
// ++c;
//}
//glActiveTexture(GL_TEXTURE0);
}
void MeshRenderer::setNext(MeshRenderer *next)
{
_next = next;
}
MeshRenderer *MeshRenderer::getNext() const
{
return (_next);
}
void MeshRenderer::addMaterial(SmartPointer<Material> material)
{
material->addObject(this);
_materials.insert(material->getName());
}
void MeshRenderer::removeMaterial(SmartPointer<Material> material)
{
// be carefull when iterating on it
material->removeObject(this);
_materials.erase(material->getName());
}
void MeshRenderer::addMaterial(const std::string &material)
{
SmartPointer<Material> m = GameEngine::instance()->renderer().getMaterialManager().getMaterial(material);
if (!m.get())
return;
m->addObject(this);
_materials.insert(m->getName());
}
void MeshRenderer::removeMaterial(const std::string &material)
{
SmartPointer<Material> m = GameEngine::instance()->renderer().getMaterialManager().getMaterial(material);
if (!m.get())
return;
m->removeObject(this);
_materials.erase(m->getName());
}
}<|endoftext|> |
<commit_before>/*
* Copyright (c) 2019-2020 Fastly, Inc., Toru Maesaka, Goro Fuji
*
* 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.
*/
#include <vector>
#include <unistd.h>
#include "h2olog.h"
using namespace std;
#define VERSION "0.1.0"
#define POLL_TIMEOUT (1000)
static void usage(void)
{
printf(R"(h2olog (v%s)
Usage: h2olog -p PID
h2olog quic -p PID
h2olog quic -t event_type -p PID
h2olog quic -v -s response_header_name -p PID
Other options:
-h Shows this help and exit.
-d Shows debugging information.
)",
VERSION);
return;
}
static void show_event_per_sec(h2o_tracer_t *tracer, time_t *t0)
{
time_t t1 = time(NULL);
int64_t d = t1 - *t0;
if (d > 10) {
uint64_t c = tracer->count / d;
if (c > 0) {
struct tm t;
localtime_r(&t1, &t);
char s[100];
const char *iso8601format = "%FT%TZ";
strftime(s, sizeof(s), iso8601format, &t);
fprintf(stderr, "%s %20lu events/s\n", s, c);
tracer->count = 0;
}
*t0 = t1;
}
}
static void show_process(pid_t pid)
{
char cmdline[256];
char proc_file[256];
snprintf(proc_file, sizeof(proc_file), "/proc/%d/cmdline", pid);
FILE *f = fopen(proc_file, "r");
if (f == nullptr) {
fprintf(stderr, "Failed to open %s: %s\n", proc_file, strerror(errno));
exit(EXIT_FAILURE);
}
size_t nread = fread(cmdline, 1, sizeof(cmdline), f);
fclose(f);
for (size_t i = 0; i < nread; i++) {
if (cmdline[i] == '\0') {
cmdline[i] = ' ';
}
}
fprintf(stderr, "Attaching pid=%d (%s)\n", pid, cmdline);
}
static std::string join_str(const std::string &sep, const std::vector<std::string> &strs)
{
std::string s;
for (auto iter = strs.cbegin(); iter != strs.cend(); ++iter) {
if (iter != strs.cbegin()) {
s += sep;
}
s += *iter;
}
return s;
}
static std::string generate_header_filter_cflag(const std::vector<std::string> &tokens)
{
std::vector<std::string> conditions;
for (auto &token : tokens) {
char buf[256];
snprintf(buf, sizeof(buf), "/* %s */ (slen) == %lu", token.c_str(), token.size());
std::vector<std::string> exprs = {buf};
for (size_t i = 0; i < token.size(); ++i) {
snprintf(buf, sizeof(buf), "(s)[%lu] == '%c'", i, token[i]);
exprs.push_back(buf);
}
conditions.push_back("(" + join_str(" && ", exprs) + ")");
}
std::string cflag("-DCHECK_ALLOWED_RES_HEADER_NAME(s,slen)=(");
cflag += join_str(" || ", conditions);
cflag += ")";
return cflag;
}
int main(int argc, char **argv)
{
h2o_tracer_t tracer = {};
if (argc > 1 && strcmp(argv[1], "quic") == 0) {
init_quic_tracer(&tracer);
--argc;
++argv;
} else {
init_http_tracer(&tracer);
}
bool debug = false;
const char *out_file = nullptr;
std::vector<std::string> event_type_filters;
std::vector<std::string> response_header_filters;
int c;
pid_t h2o_pid = -1;
while ((c = getopt(argc, argv, "hdp:t:s:o:")) != -1) {
switch (c) {
case 'p':
h2o_pid = atoi(optarg);
break;
case 't':
event_type_filters.push_back(optarg);
break;
case 's':
response_header_filters.push_back(optarg);
break;
case 'o':
out_file = optarg;
break;
case 'd':
debug = true;
break;
case 'h':
usage();
exit(EXIT_SUCCESS);
default:
usage();
exit(EXIT_FAILURE);
}
}
if (argc > optind) {
fprintf(stderr, "Error: too many aruments\n");
usage();
exit(EXIT_FAILURE);
}
if (h2o_pid == -1) {
fprintf(stderr, "Error: -p option is missing\n");
usage();
exit(EXIT_FAILURE);
}
if (geteuid() != 0) {
fprintf(stderr, "Error: root privilege is required\n");
exit(EXIT_FAILURE);
}
if (out_file != nullptr) {
FILE *out = fopen(out_file, "w");
if (out == nullptr) {
fprintf(stderr, "Error: failed to open %s: %s", out_file, strerror(errno));
exit(EXIT_FAILURE);
}
tracer.out = out;
} else {
tracer.out = stdout;
}
std::vector<std::string> cflags;
if (!response_header_filters.empty()) {
cflags.push_back(generate_header_filter_cflag(response_header_filters));
}
ebpf::BPF *bpf = new ebpf::BPF();
std::vector<ebpf::USDT> probes = tracer.init_usdt_probes(h2o_pid);
ebpf::StatusTuple ret = bpf->init(tracer.bpf_text(), cflags, probes);
if (ret.code() != 0) {
fprintf(stderr, "init: %s\n", ret.msg().c_str());
return EXIT_FAILURE;
}
for (auto &probe : probes) {
ret = bpf->attach_usdt(probe);
if (ret.code() != 0) {
fprintf(stderr, "attach_usdt: %s\n", ret.msg().c_str());
return EXIT_FAILURE;
}
}
ret = bpf->open_perf_buffer("events", tracer.handle_event, nullptr, &tracer, 64);
if (ret.code() != 0) {
fprintf(stderr, "open_perf_buffer: %s\n", ret.msg().c_str());
return EXIT_FAILURE;
}
if (debug) {
show_process(h2o_pid);
}
ebpf::BPFPerfBuffer *perf_buffer = bpf->get_perf_buffer("events");
if (perf_buffer) {
time_t t0 = time(NULL);
while (true) {
perf_buffer->poll(POLL_TIMEOUT);
fflush(tracer.out);
if (debug) {
show_event_per_sec(&tracer, &t0);
}
}
}
fprintf(stderr, "Error: failed to get_perf_buffer()\n");
return EXIT_FAILURE;
}
<commit_msg>use "%zu" for size_t value (thanks to @syohex for review)<commit_after>/*
* Copyright (c) 2019-2020 Fastly, Inc., Toru Maesaka, Goro Fuji
*
* 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.
*/
#include <vector>
#include <unistd.h>
#include "h2olog.h"
using namespace std;
#define VERSION "0.1.0"
#define POLL_TIMEOUT (1000)
static void usage(void)
{
printf(R"(h2olog (v%s)
Usage: h2olog -p PID
h2olog quic -p PID
h2olog quic -t event_type -p PID
h2olog quic -v -s response_header_name -p PID
Other options:
-h Shows this help and exit.
-d Shows debugging information.
)",
VERSION);
return;
}
static void show_event_per_sec(h2o_tracer_t *tracer, time_t *t0)
{
time_t t1 = time(NULL);
int64_t d = t1 - *t0;
if (d > 10) {
uint64_t c = tracer->count / d;
if (c > 0) {
struct tm t;
localtime_r(&t1, &t);
char s[100];
const char *iso8601format = "%FT%TZ";
strftime(s, sizeof(s), iso8601format, &t);
fprintf(stderr, "%s %20lu events/s\n", s, c);
tracer->count = 0;
}
*t0 = t1;
}
}
static void show_process(pid_t pid)
{
char cmdline[256];
char proc_file[256];
snprintf(proc_file, sizeof(proc_file), "/proc/%d/cmdline", pid);
FILE *f = fopen(proc_file, "r");
if (f == nullptr) {
fprintf(stderr, "Failed to open %s: %s\n", proc_file, strerror(errno));
exit(EXIT_FAILURE);
}
size_t nread = fread(cmdline, 1, sizeof(cmdline), f);
fclose(f);
for (size_t i = 0; i < nread; i++) {
if (cmdline[i] == '\0') {
cmdline[i] = ' ';
}
}
fprintf(stderr, "Attaching pid=%d (%s)\n", pid, cmdline);
}
static std::string join_str(const std::string &sep, const std::vector<std::string> &strs)
{
std::string s;
for (auto iter = strs.cbegin(); iter != strs.cend(); ++iter) {
if (iter != strs.cbegin()) {
s += sep;
}
s += *iter;
}
return s;
}
static std::string generate_header_filter_cflag(const std::vector<std::string> &tokens)
{
std::vector<std::string> conditions;
for (auto &token : tokens) {
char buf[256];
snprintf(buf, sizeof(buf), "/* %s */ (slen) == %zu", token.c_str(), token.size());
std::vector<std::string> exprs = {buf};
for (size_t i = 0; i < token.size(); ++i) {
snprintf(buf, sizeof(buf), "(s)[%zu] == '%c'", i, token[i]);
exprs.push_back(buf);
}
conditions.push_back("(" + join_str(" && ", exprs) + ")");
}
std::string cflag("-DCHECK_ALLOWED_RES_HEADER_NAME(s,slen)=(");
cflag += join_str(" || ", conditions);
cflag += ")";
return cflag;
}
int main(int argc, char **argv)
{
h2o_tracer_t tracer = {};
if (argc > 1 && strcmp(argv[1], "quic") == 0) {
init_quic_tracer(&tracer);
--argc;
++argv;
} else {
init_http_tracer(&tracer);
}
bool debug = false;
const char *out_file = nullptr;
std::vector<std::string> event_type_filters;
std::vector<std::string> response_header_filters;
int c;
pid_t h2o_pid = -1;
while ((c = getopt(argc, argv, "hdp:t:s:o:")) != -1) {
switch (c) {
case 'p':
h2o_pid = atoi(optarg);
break;
case 't':
event_type_filters.push_back(optarg);
break;
case 's':
response_header_filters.push_back(optarg);
break;
case 'o':
out_file = optarg;
break;
case 'd':
debug = true;
break;
case 'h':
usage();
exit(EXIT_SUCCESS);
default:
usage();
exit(EXIT_FAILURE);
}
}
if (argc > optind) {
fprintf(stderr, "Error: too many aruments\n");
usage();
exit(EXIT_FAILURE);
}
if (h2o_pid == -1) {
fprintf(stderr, "Error: -p option is missing\n");
usage();
exit(EXIT_FAILURE);
}
if (geteuid() != 0) {
fprintf(stderr, "Error: root privilege is required\n");
exit(EXIT_FAILURE);
}
if (out_file != nullptr) {
FILE *out = fopen(out_file, "w");
if (out == nullptr) {
fprintf(stderr, "Error: failed to open %s: %s", out_file, strerror(errno));
exit(EXIT_FAILURE);
}
tracer.out = out;
} else {
tracer.out = stdout;
}
std::vector<std::string> cflags;
if (!response_header_filters.empty()) {
cflags.push_back(generate_header_filter_cflag(response_header_filters));
}
ebpf::BPF *bpf = new ebpf::BPF();
std::vector<ebpf::USDT> probes = tracer.init_usdt_probes(h2o_pid);
ebpf::StatusTuple ret = bpf->init(tracer.bpf_text(), cflags, probes);
if (ret.code() != 0) {
fprintf(stderr, "init: %s\n", ret.msg().c_str());
return EXIT_FAILURE;
}
for (auto &probe : probes) {
ret = bpf->attach_usdt(probe);
if (ret.code() != 0) {
fprintf(stderr, "attach_usdt: %s\n", ret.msg().c_str());
return EXIT_FAILURE;
}
}
ret = bpf->open_perf_buffer("events", tracer.handle_event, nullptr, &tracer, 64);
if (ret.code() != 0) {
fprintf(stderr, "open_perf_buffer: %s\n", ret.msg().c_str());
return EXIT_FAILURE;
}
if (debug) {
show_process(h2o_pid);
}
ebpf::BPFPerfBuffer *perf_buffer = bpf->get_perf_buffer("events");
if (perf_buffer) {
time_t t0 = time(NULL);
while (true) {
perf_buffer->poll(POLL_TIMEOUT);
fflush(tracer.out);
if (debug) {
show_event_per_sec(&tracer, &t0);
}
}
}
fprintf(stderr, "Error: failed to get_perf_buffer()\n");
return EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>
#include <gloperate-osg/OsgFboRenderStage.h>
#include <osgViewer/Viewer>
#include <osgViewer/Renderer>
#include <osg/Camera>
#include <osg/Texture2D>
namespace gloperate_osg
{
void OsgFboRenderStage::updateFbo_osg()
{
// Get OSG camera
osg::Camera * camera = (viewer() ? viewer()->getCamera() : nullptr);
if (camera && m_viewportW > 0 && m_viewportH > 0) {
// (Re)create color texture
osg::Texture2D * colorTextureOsg = new osg::Texture2D;
colorTextureOsg->setTextureSize(m_viewportW, m_viewportH);
colorTextureOsg->setInternalFormat(GL_RGBA);
colorTextureOsg->setFilter(osg::Texture::MIN_FILTER, osg::Texture::NEAREST);
colorTextureOsg->setFilter(osg::Texture::MAG_FILTER, osg::Texture::NEAREST);
colorTextureOsg->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
colorTextureOsg->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
m_colorTextureOsg = colorTextureOsg;
// (Re)create depth texture
osg::Texture2D * depthTextureOsg = new osg::Texture2D;
depthTextureOsg->setTextureSize(m_viewportW, m_viewportH);
depthTextureOsg->setSourceFormat(GL_DEPTH_COMPONENT);
depthTextureOsg->setInternalFormat(GL_DEPTH_COMPONENT24);
depthTextureOsg->setFilter(osg::Texture::MIN_FILTER, osg::Texture::NEAREST);
depthTextureOsg->setFilter(osg::Texture::MAG_FILTER, osg::Texture::NEAREST);
depthTextureOsg->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
depthTextureOsg->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
m_depthTextureOsg = depthTextureOsg;
// Create FBO for camera
camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
camera->detach(osg::Camera::COLOR_BUFFER0);
camera->attach(osg::Camera::COLOR_BUFFER0, m_colorTextureOsg);
camera->detach(osg::Camera::DEPTH_BUFFER);
camera->attach(osg::Camera::DEPTH_BUFFER, m_depthTextureOsg);
camera->setViewport(0, 0, m_viewportW, m_viewportH);
// Update projection matrix to preserve the aspect ratio
camera->setProjectionMatrixAsPerspective(30.0f, camera->getViewport()->aspectRatio(), 1.0f, 10000.0f);
// Make sure the camera FBO is rebuilt
osgViewer::Renderer * renderer = (osgViewer::Renderer*)camera->getRenderer();
renderer->getSceneView(0)->getRenderStage()->setCameraRequiresSetUp(true);
renderer->getSceneView(0)->getRenderStage()->setFrameBufferObject(nullptr);
}
}
unsigned int OsgFboRenderStage::getOsgTextureId(const osg::Texture * texture) const
{
// Check if everything is setup correctly
if (m_embedded && texture) {
// Get texture ID
unsigned int contextID = m_embedded->getState()->getContextID();
return texture->getTextureObject(contextID)->id();
} else {
// Return invalid ID on error
return 0;
}
}
} // namespace gloperate_osg
<commit_msg>Fix compilation for glbinding 2.0<commit_after>
#include <gloperate-osg/OsgFboRenderStage.h>
#undef __gl_h_ // dirtiest hack imaginale
// TODO: find a solution for GL/gl.h and glbinding/gl/gl.h
#include <osgViewer/Viewer>
#include <osgViewer/Renderer>
#include <osg/Camera>
#include <osg/Texture2D>
namespace gloperate_osg
{
void OsgFboRenderStage::updateFbo_osg()
{
// Get OSG camera
osg::Camera * camera = (viewer() ? viewer()->getCamera() : nullptr);
if (camera && m_viewportW > 0 && m_viewportH > 0) {
// (Re)create color texture
osg::Texture2D * colorTextureOsg = new osg::Texture2D;
colorTextureOsg->setTextureSize(m_viewportW, m_viewportH);
colorTextureOsg->setInternalFormat(GL_RGBA);
colorTextureOsg->setFilter(osg::Texture::MIN_FILTER, osg::Texture::NEAREST);
colorTextureOsg->setFilter(osg::Texture::MAG_FILTER, osg::Texture::NEAREST);
colorTextureOsg->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
colorTextureOsg->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
m_colorTextureOsg = colorTextureOsg;
// (Re)create depth texture
osg::Texture2D * depthTextureOsg = new osg::Texture2D;
depthTextureOsg->setTextureSize(m_viewportW, m_viewportH);
depthTextureOsg->setSourceFormat(GL_DEPTH_COMPONENT);
depthTextureOsg->setInternalFormat(GL_DEPTH_COMPONENT24);
depthTextureOsg->setFilter(osg::Texture::MIN_FILTER, osg::Texture::NEAREST);
depthTextureOsg->setFilter(osg::Texture::MAG_FILTER, osg::Texture::NEAREST);
depthTextureOsg->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
depthTextureOsg->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
m_depthTextureOsg = depthTextureOsg;
// Create FBO for camera
camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
camera->detach(osg::Camera::COLOR_BUFFER0);
camera->attach(osg::Camera::COLOR_BUFFER0, m_colorTextureOsg);
camera->detach(osg::Camera::DEPTH_BUFFER);
camera->attach(osg::Camera::DEPTH_BUFFER, m_depthTextureOsg);
camera->setViewport(0, 0, m_viewportW, m_viewportH);
// Update projection matrix to preserve the aspect ratio
camera->setProjectionMatrixAsPerspective(30.0f, camera->getViewport()->aspectRatio(), 1.0f, 10000.0f);
// Make sure the camera FBO is rebuilt
osgViewer::Renderer * renderer = (osgViewer::Renderer*)camera->getRenderer();
renderer->getSceneView(0)->getRenderStage()->setCameraRequiresSetUp(true);
renderer->getSceneView(0)->getRenderStage()->setFrameBufferObject(nullptr);
}
}
unsigned int OsgFboRenderStage::getOsgTextureId(const osg::Texture * texture) const
{
// Check if everything is setup correctly
if (m_embedded && texture) {
// Get texture ID
unsigned int contextID = m_embedded->getState()->getContextID();
return texture->getTextureObject(contextID)->id();
} else {
// Return invalid ID on error
return 0;
}
}
} // namespace gloperate_osg
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: NeonPropFindRequest.cxx,v $
*
* $Revision: 1.21 $
*
* last change: $Author: obo $ $Date: 2008-01-04 14:35:30 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_ucb.hxx"
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _NEONTYPES_HXX_
#include "NeonTypes.hxx"
#endif
#ifndef _DAVEXCEPTION_HXX_
#include "DAVException.hxx"
#endif
#ifndef _DAVPROPERTIES_HXX_
#include "DAVProperties.hxx"
#endif
#ifndef _NEONPROPFINDREQUEST_HXX_
#include "NeonPropFindRequest.hxx"
#endif
#ifndef _LINKSEQUENCE_HXX_
#include "LinkSequence.hxx"
#endif
#ifndef _LOCKSEQUENCE_HXX_
#include "LockSequence.hxx"
#endif
#ifndef _LOCKENTRYSEQUENCE_HXX_
#include "LockEntrySequence.hxx"
#endif
#ifndef _UCBDEADPROPERTYVALUE_HXX_
#include "UCBDeadPropertyValue.hxx"
#endif
using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::ucb;
using namespace std;
using namespace webdav_ucp;
// -------------------------------------------------------------------
extern "C" int NPFR_propfind_iter( void* userdata,
const NeonPropName* pname,
const char* value,
const HttpStatus* status )
{
/*
HTTP Response Status Classes:
- 1: Informational - Request received, continuing process
- 2: Success - The action was successfully received,
understood, and accepted
- 3: Redirection - Further action must be taken in order to
complete the request
- 4: Client Error - The request contains bad syntax or cannot
be fulfilled
- 5: Server Error - The server failed to fulfill an apparently
valid request
*/
if ( status->klass > 2 )
return 0; // Error getting this property. Go on.
// Create & set the PropertyValue
DAVPropertyValue thePropertyValue;
thePropertyValue.IsCaseSensitive = true;
DAVProperties::createUCBPropName( pname->nspace,
pname->name,
thePropertyValue.Name );
bool bHasValue = false;
if ( DAVProperties::isUCBDeadProperty( *pname ) )
{
// DAV dead property added by WebDAV UCP?
if ( UCBDeadPropertyValue::createFromXML(
value, thePropertyValue.Value ) )
OSL_ENSURE( thePropertyValue.Value.hasValue(),
"NeonPropFindRequest::propfind_iter - No value!" );
bHasValue = true;
}
if ( !bHasValue )
{
if ( rtl_str_compareIgnoreAsciiCase(
pname->name, "resourcetype" ) == 0 )
{
OString aValue( value );
aValue = aValue.trim(); // #107358# remove leading/trailing spaces
if ( aValue.getLength() )
{
aValue = aValue.toAsciiLowerCase();
if ( aValue.compareTo(
RTL_CONSTASCII_STRINGPARAM( "<collection" ) ) == 0 )
{
thePropertyValue.Value
<<= OUString::createFromAscii( "collection" );
}
}
if ( !thePropertyValue.Value.hasValue() )
{
// Take over the value exactly as supplied by the server.
thePropertyValue.Value <<= OUString::createFromAscii( value );
}
}
else if ( rtl_str_compareIgnoreAsciiCase(
pname->name, "supportedlock" ) == 0 )
{
Sequence< LockEntry > aEntries;
LockEntrySequence::createFromXML( value, aEntries );
thePropertyValue.Value <<= aEntries;
}
else if ( rtl_str_compareIgnoreAsciiCase(
pname->name, "lockdiscovery" ) == 0 )
{
Sequence< Lock > aLocks;
LockSequence::createFromXML( value, aLocks );
thePropertyValue.Value <<= aLocks;
}
else if ( rtl_str_compareIgnoreAsciiCase( pname->name, "source" ) == 0 )
{
Sequence< Link > aLinks;
LinkSequence::createFromXML( value, aLinks );
thePropertyValue.Value <<= aLinks;
}
else
{
thePropertyValue.Value
<<= OStringToOUString( value, RTL_TEXTENCODING_UTF8 );
}
}
// Add the newly created PropertyValue
DAVResource* theResource = static_cast< DAVResource * >( userdata );
theResource->properties.push_back( thePropertyValue );
return 0; // Go on.
}
// -------------------------------------------------------------------
extern "C" void NPFR_propfind_results( void* userdata,
const ne_uri* uri,
const NeonPropFindResultSet* set )
{
DAVResource theResource(
OStringToOUString( uri->path, RTL_TEXTENCODING_UTF8 ) );
ne_propset_iterate( set, NPFR_propfind_iter, &theResource );
// Add entry to resources list.
vector< DAVResource > * theResources
= static_cast< vector< DAVResource > * >( userdata );
theResources->push_back( theResource );
}
// -------------------------------------------------------------------
extern "C" int NPFR_propnames_iter( void* userdata,
const NeonPropName* pname,
const char* /*value*/,
const HttpStatus* /*status*/ )
{
OUString aFullName;
DAVProperties::createUCBPropName( pname->nspace,
pname->name,
aFullName );
DAVResourceInfo* theResource = static_cast< DAVResourceInfo * >( userdata );
theResource->properties.push_back( aFullName );
return 0;
}
// -------------------------------------------------------------------
extern "C" void NPFR_propnames_results( void* userdata,
const ne_uri* uri,
const NeonPropFindResultSet* results )
{
// @@@ href is not the uri! DAVResourceInfo ctor wants uri!
// Create entry for the resource.
DAVResourceInfo theResource(
OStringToOUString( uri->path, RTL_TEXTENCODING_UTF8 ) );
// Fill entry.
ne_propset_iterate( results, NPFR_propnames_iter, &theResource );
// Add entry to resources list.
vector< DAVResourceInfo > * theResources
= static_cast< vector< DAVResourceInfo > * >( userdata );
theResources->push_back( theResource );
}
// -------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------
NeonPropFindRequest::NeonPropFindRequest( HttpSession* inSession,
const char* inPath,
const Depth inDepth,
const vector< OUString >& inPropNames,
vector< DAVResource >& ioResources,
int & nError )
{
// Generate the list of properties we're looking for
int thePropCount = inPropNames.size();
if ( thePropCount > 0 )
{
NeonPropName* thePropNames = new NeonPropName[ thePropCount + 1 ];
int theIndex;
for ( theIndex = 0; theIndex < thePropCount; theIndex ++ )
{
// Split fullname into namespace and name!
DAVProperties::createNeonPropName(
inPropNames[ theIndex ], thePropNames[ theIndex ] );
}
thePropNames[ theIndex ].nspace = NULL;
thePropNames[ theIndex ].name = NULL;
nError = ne_simple_propfind( inSession,
inPath,
inDepth,
thePropNames,
NPFR_propfind_results,
&ioResources );
for ( theIndex = 0; theIndex < thePropCount; theIndex ++ )
free( (void *)thePropNames[ theIndex ].name );
delete [] thePropNames;
}
else
{
// ALLPROP
nError = ne_simple_propfind( inSession,
inPath,
inDepth,
NULL, // 0 == allprop
NPFR_propfind_results,
&ioResources );
}
// #87585# - Sometimes neon lies (because some servers lie).
if ( ( nError == NE_OK ) && ioResources.empty() )
nError = NE_ERROR;
}
// -------------------------------------------------------------------
// Constructor
// - obtains property names
// -------------------------------------------------------------------
NeonPropFindRequest::NeonPropFindRequest(
HttpSession* inSession,
const char* inPath,
const Depth inDepth,
std::vector< DAVResourceInfo > & ioResInfo,
int & nError )
{
nError = ne_propnames( inSession,
inPath,
inDepth,
NPFR_propnames_results,
&ioResInfo );
// #87585# - Sometimes neon lies (because some servers lie).
if ( ( nError == NE_OK ) && ioResInfo.empty() )
nError = NE_ERROR;
}
// -------------------------------------------------------------------
// Destructor
// -------------------------------------------------------------------
NeonPropFindRequest::~NeonPropFindRequest( )
{
}
<commit_msg>#i10000# fix by TKR, NEON_VERSION missing<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: NeonPropFindRequest.cxx,v $
*
* $Revision: 1.22 $
*
* last change: $Author: obo $ $Date: 2008-01-07 12:58:15 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_ucb.hxx"
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _NEONTYPES_HXX_
#include "NeonTypes.hxx"
#endif
#ifndef _DAVEXCEPTION_HXX_
#include "DAVException.hxx"
#endif
#ifndef _DAVPROPERTIES_HXX_
#include "DAVProperties.hxx"
#endif
#ifndef _NEONPROPFINDREQUEST_HXX_
#include "NeonPropFindRequest.hxx"
#endif
#ifndef _LINKSEQUENCE_HXX_
#include "LinkSequence.hxx"
#endif
#ifndef _LOCKSEQUENCE_HXX_
#include "LockSequence.hxx"
#endif
#ifndef _LOCKENTRYSEQUENCE_HXX_
#include "LockEntrySequence.hxx"
#endif
#ifndef _UCBDEADPROPERTYVALUE_HXX_
#include "UCBDeadPropertyValue.hxx"
#endif
using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::ucb;
using namespace std;
using namespace webdav_ucp;
// -------------------------------------------------------------------
extern "C" int NPFR_propfind_iter( void* userdata,
const NeonPropName* pname,
const char* value,
const HttpStatus* status )
{
/*
HTTP Response Status Classes:
- 1: Informational - Request received, continuing process
- 2: Success - The action was successfully received,
understood, and accepted
- 3: Redirection - Further action must be taken in order to
complete the request
- 4: Client Error - The request contains bad syntax or cannot
be fulfilled
- 5: Server Error - The server failed to fulfill an apparently
valid request
*/
if ( status->klass > 2 )
return 0; // Error getting this property. Go on.
// Create & set the PropertyValue
DAVPropertyValue thePropertyValue;
thePropertyValue.IsCaseSensitive = true;
DAVProperties::createUCBPropName( pname->nspace,
pname->name,
thePropertyValue.Name );
bool bHasValue = false;
if ( DAVProperties::isUCBDeadProperty( *pname ) )
{
// DAV dead property added by WebDAV UCP?
if ( UCBDeadPropertyValue::createFromXML(
value, thePropertyValue.Value ) )
OSL_ENSURE( thePropertyValue.Value.hasValue(),
"NeonPropFindRequest::propfind_iter - No value!" );
bHasValue = true;
}
if ( !bHasValue )
{
if ( rtl_str_compareIgnoreAsciiCase(
pname->name, "resourcetype" ) == 0 )
{
OString aValue( value );
aValue = aValue.trim(); // #107358# remove leading/trailing spaces
if ( aValue.getLength() )
{
aValue = aValue.toAsciiLowerCase();
if ( aValue.compareTo(
RTL_CONSTASCII_STRINGPARAM( "<collection" ) ) == 0 )
{
thePropertyValue.Value
<<= OUString::createFromAscii( "collection" );
}
}
if ( !thePropertyValue.Value.hasValue() )
{
// Take over the value exactly as supplied by the server.
thePropertyValue.Value <<= OUString::createFromAscii( value );
}
}
else if ( rtl_str_compareIgnoreAsciiCase(
pname->name, "supportedlock" ) == 0 )
{
Sequence< LockEntry > aEntries;
LockEntrySequence::createFromXML( value, aEntries );
thePropertyValue.Value <<= aEntries;
}
else if ( rtl_str_compareIgnoreAsciiCase(
pname->name, "lockdiscovery" ) == 0 )
{
Sequence< Lock > aLocks;
LockSequence::createFromXML( value, aLocks );
thePropertyValue.Value <<= aLocks;
}
else if ( rtl_str_compareIgnoreAsciiCase( pname->name, "source" ) == 0 )
{
Sequence< Link > aLinks;
LinkSequence::createFromXML( value, aLinks );
thePropertyValue.Value <<= aLinks;
}
else
{
thePropertyValue.Value
<<= OStringToOUString( value, RTL_TEXTENCODING_UTF8 );
}
}
// Add the newly created PropertyValue
DAVResource* theResource = static_cast< DAVResource * >( userdata );
theResource->properties.push_back( thePropertyValue );
return 0; // Go on.
}
// -------------------------------------------------------------------
extern "C" void NPFR_propfind_results( void* userdata,
#if NEON_VERSION >= 0260
const ne_uri* uri,
#else
const char* href,
#endif
const NeonPropFindResultSet* set )
{
// @@@ href is not the uri! DAVResource ctor wants uri!
#if NEON_VERSION >= 0260
DAVResource theResource(
OStringToOUString( uri->path, RTL_TEXTENCODING_UTF8 ) );
#else
DAVResource theResource(
OStringToOUString( href, RTL_TEXTENCODING_UTF8 ) );
#endif
ne_propset_iterate( set, NPFR_propfind_iter, &theResource );
// Add entry to resources list.
vector< DAVResource > * theResources
= static_cast< vector< DAVResource > * >( userdata );
theResources->push_back( theResource );
}
// -------------------------------------------------------------------
extern "C" int NPFR_propnames_iter( void* userdata,
const NeonPropName* pname,
const char* /*value*/,
const HttpStatus* /*status*/ )
{
OUString aFullName;
DAVProperties::createUCBPropName( pname->nspace,
pname->name,
aFullName );
DAVResourceInfo* theResource = static_cast< DAVResourceInfo * >( userdata );
theResource->properties.push_back( aFullName );
return 0;
}
// -------------------------------------------------------------------
extern "C" void NPFR_propnames_results( void* userdata,
#if NEON_VERSION >= 0260
const ne_uri* uri,
#else
const char* href,
#endif
const NeonPropFindResultSet* results )
{
// @@@ href is not the uri! DAVResourceInfo ctor wants uri!
// Create entry for the resource.
#if NEON_VERSION >= 0260
DAVResourceInfo theResource(
OStringToOUString( uri->path, RTL_TEXTENCODING_UTF8 ) );
#else
DAVResourceInfo theResource(
OStringToOUString( href, RTL_TEXTENCODING_UTF8 ) );
#endif
// Fill entry.
ne_propset_iterate( results, NPFR_propnames_iter, &theResource );
// Add entry to resources list.
vector< DAVResourceInfo > * theResources
= static_cast< vector< DAVResourceInfo > * >( userdata );
theResources->push_back( theResource );
}
// -------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------
NeonPropFindRequest::NeonPropFindRequest( HttpSession* inSession,
const char* inPath,
const Depth inDepth,
const vector< OUString >& inPropNames,
vector< DAVResource >& ioResources,
int & nError )
{
// Generate the list of properties we're looking for
int thePropCount = inPropNames.size();
if ( thePropCount > 0 )
{
NeonPropName* thePropNames = new NeonPropName[ thePropCount + 1 ];
int theIndex;
for ( theIndex = 0; theIndex < thePropCount; theIndex ++ )
{
// Split fullname into namespace and name!
DAVProperties::createNeonPropName(
inPropNames[ theIndex ], thePropNames[ theIndex ] );
}
thePropNames[ theIndex ].nspace = NULL;
thePropNames[ theIndex ].name = NULL;
nError = ne_simple_propfind( inSession,
inPath,
inDepth,
thePropNames,
NPFR_propfind_results,
&ioResources );
for ( theIndex = 0; theIndex < thePropCount; theIndex ++ )
free( (void *)thePropNames[ theIndex ].name );
delete [] thePropNames;
}
else
{
// ALLPROP
nError = ne_simple_propfind( inSession,
inPath,
inDepth,
NULL, // 0 == allprop
NPFR_propfind_results,
&ioResources );
}
// #87585# - Sometimes neon lies (because some servers lie).
if ( ( nError == NE_OK ) && ioResources.empty() )
nError = NE_ERROR;
}
// -------------------------------------------------------------------
// Constructor
// - obtains property names
// -------------------------------------------------------------------
NeonPropFindRequest::NeonPropFindRequest(
HttpSession* inSession,
const char* inPath,
const Depth inDepth,
std::vector< DAVResourceInfo > & ioResInfo,
int & nError )
{
nError = ne_propnames( inSession,
inPath,
inDepth,
NPFR_propnames_results,
&ioResInfo );
// #87585# - Sometimes neon lies (because some servers lie).
if ( ( nError == NE_OK ) && ioResInfo.empty() )
nError = NE_ERROR;
}
// -------------------------------------------------------------------
// Destructor
// -------------------------------------------------------------------
NeonPropFindRequest::~NeonPropFindRequest( )
{
}
<|endoftext|> |
<commit_before>// CSV or DSV format (comma- or more generally delimiter-separated values)
// Licence: Lesser GNU Public License 2.1 (LGPL)
// $Id: $
#define BUILDING_XYLIB
#include "csv.h"
#include "util.h"
#include <limits>
#include <boost/tokenizer.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
using namespace std;
using namespace xylib::util;
namespace xylib {
typedef boost::tokenizer< boost::escaped_list_separator<char> > Tokenizer;
const FormatInfo CsvDataSet::fmt_info(
"csv",
"comma-separated values",
"csv tsv tab",
false, // whether binary
false, // whether has multi-blocks
&CsvDataSet::ctor,
&CsvDataSet::check
);
static
double read_field(const char* field)
{
char* endptr;
double d = strtod(field, &endptr);
if (endptr != field && *endptr == '\0')
return d;
else
return numeric_limits<double>::quiet_NaN();
}
static
int count_numbers(const string& line, char sep, int *number_count)
{
int field_count = 0;
*number_count = 0;
Tokenizer t(line, boost::escaped_list_separator<char>('\\', sep, '"'));
for (Tokenizer::iterator i = t.begin(); i != t.end(); ++i) {
double d = read_field(i->c_str());
++field_count;
if (!boost::math::isnan(d))
++(*number_count);
}
return field_count;
}
static
void read_numbers_from_line(const string& line, char sep, vector<double> *out)
{
Tokenizer t(line, boost::escaped_list_separator<char>('\\', sep, '"'));
for (Tokenizer::iterator i = t.begin(); i != t.end(); ++i)
out->push_back(read_field(i->c_str()));
}
static
bool is_space(const char* str)
{
while (*str) {
if (!isspace(*str))
return false;
++str;
}
return true;
}
static
char read_4lines(istream &f, bool decimal_comma,
vector<vector<double> > *out,
vector<string> *column_names)
{
char buffer[1600]; // more than enough for one line
string lines[4];
buffer[1600-1]=0;
for (int all_lines = 0, nonempty_lines=0;
nonempty_lines < 4; ++all_lines) {
// it can be a large file without new lines, limit line length
f.getline(buffer, 1600);
if (!f || buffer[1600-1] != 0)
throw FormatError("reading line " + S(all_lines) + " failed.");
if (!is_space(buffer)) {
if (decimal_comma)
for (char* p = buffer; *p != '\0'; ++p)
if (*p == ',')
*p = '.';
lines[nonempty_lines] = buffer;
++nonempty_lines;
}
}
// The first line can be header. Second line should not be a header,
// but just in case, let's check lines 3 and 4.
int max_number_count = 0;
int max_field_count = 0;
char sep = 0;
const char* separators = "\t,;|:/ ";
for (const char* isep = separators; *isep != '\0'; ++isep) {
int num2;
int fields1 = count_numbers(lines[2], *isep, &num2);
int num3;
int fields2 = count_numbers(lines[3], *isep, &num3);
if (fields1 == 0 || fields2 != fields1)
continue;
int num = min(num2, num3);
if (num > max_number_count || (num == max_number_count &&
fields1 > max_field_count)) {
max_number_count = num;
max_field_count = fields1;
sep = *isep;
}
}
int num0;
int fields0 = count_numbers(lines[0], sep, &num0);
if (fields0 != max_field_count)
throw FormatError("different field count (`" + S(sep) +
"'-separated) in lines 1 and 3.");
bool has_header = (num0 < max_number_count);
if (has_header && column_names) {
Tokenizer t(lines[0],
boost::escaped_list_separator<char>('\\', sep, '"'));
for (Tokenizer::iterator i = t.begin(); i != t.end(); ++i)
column_names->push_back(*i);
}
if (out != NULL) {
if (!has_header) {
out->resize(out->size() + 1);
read_numbers_from_line(lines[0], sep, &out->back());
}
for (int i = 1; i != 4; ++i) {
out->resize(out->size() + 1);
read_numbers_from_line(lines[i], sep, &out->back());
}
}
return sep;
}
bool CsvDataSet::check(istream &f)
{
try {
return read_4lines(f, false, NULL, NULL) != 0;
}
catch (FormatError &) {
return false;
}
}
void CsvDataSet::load_data(istream &f)
{
bool decimal_comma = has_option("decimal_comma");
vector<vector<double> > data;
vector<string> column_names;
string line;
line.reserve(100);
char sep = read_4lines(f, decimal_comma, &data, &column_names);
size_t n_col = data[0].size();
while (getline(f, line)) {
if (is_space(line.c_str()))
continue;
if (decimal_comma)
for (string::iterator p = line.begin(); p != line.end(); ++p)
if (*p == ',')
*p = '.';
data.resize(data.size() + 1);
data.back().reserve(n_col);
read_numbers_from_line(line, sep, &data.back());
}
Block* blk = new Block;
for (size_t i = 0; i != n_col; ++i) {
VecColumn *col = new VecColumn;
if (column_names.size() > i)
col->set_name(column_names[i]);
col->reserve(data.size());
for (size_t j = 0; j != data.size(); ++j)
col->add_val(data[j].size() > i ? data[j][i]
: numeric_limits<double>::quiet_NaN());
blk->add_column(col);
}
add_block(blk);
}
} // namespace xylib
<commit_msg>workaround for compiling with Boost < 1.35<commit_after>// CSV or DSV format (comma- or more generally delimiter-separated values)
// Licence: Lesser GNU Public License 2.1 (LGPL)
// $Id: $
#define BUILDING_XYLIB
#include "csv.h"
#include "util.h"
#include <limits>
#include <boost/tokenizer.hpp>
#include <boost/version.hpp>
#if BOOST_VERSION >= 103500
#include <boost/math/special_functions/fpclassify.hpp>
#else
namespace boost { namespace math { bool isnan(double f) { return f != f; } }}
#endif
using namespace std;
using namespace xylib::util;
namespace xylib {
typedef boost::tokenizer< boost::escaped_list_separator<char> > Tokenizer;
const FormatInfo CsvDataSet::fmt_info(
"csv",
"comma-separated values",
"csv tsv tab",
false, // whether binary
false, // whether has multi-blocks
&CsvDataSet::ctor,
&CsvDataSet::check
);
static
double read_field(const char* field)
{
char* endptr;
double d = strtod(field, &endptr);
if (endptr != field && *endptr == '\0')
return d;
else
return numeric_limits<double>::quiet_NaN();
}
static
int count_numbers(const string& line, char sep, int *number_count)
{
int field_count = 0;
*number_count = 0;
Tokenizer t(line, boost::escaped_list_separator<char>('\\', sep, '"'));
for (Tokenizer::iterator i = t.begin(); i != t.end(); ++i) {
double d = read_field(i->c_str());
++field_count;
if (!boost::math::isnan(d))
++(*number_count);
}
return field_count;
}
static
void read_numbers_from_line(const string& line, char sep, vector<double> *out)
{
Tokenizer t(line, boost::escaped_list_separator<char>('\\', sep, '"'));
for (Tokenizer::iterator i = t.begin(); i != t.end(); ++i)
out->push_back(read_field(i->c_str()));
}
static
bool is_space(const char* str)
{
while (*str) {
if (!isspace(*str))
return false;
++str;
}
return true;
}
static
char read_4lines(istream &f, bool decimal_comma,
vector<vector<double> > *out,
vector<string> *column_names)
{
char buffer[1600]; // more than enough for one line
string lines[4];
buffer[1600-1]=0;
for (int all_lines = 0, nonempty_lines=0;
nonempty_lines < 4; ++all_lines) {
// it can be a large file without new lines, limit line length
f.getline(buffer, 1600);
if (!f || buffer[1600-1] != 0)
throw FormatError("reading line " + S(all_lines) + " failed.");
if (!is_space(buffer)) {
if (decimal_comma)
for (char* p = buffer; *p != '\0'; ++p)
if (*p == ',')
*p = '.';
lines[nonempty_lines] = buffer;
++nonempty_lines;
}
}
// The first line can be header. Second line should not be a header,
// but just in case, let's check lines 3 and 4.
int max_number_count = 0;
int max_field_count = 0;
char sep = 0;
const char* separators = "\t,;|:/ ";
for (const char* isep = separators; *isep != '\0'; ++isep) {
int num2;
int fields1 = count_numbers(lines[2], *isep, &num2);
int num3;
int fields2 = count_numbers(lines[3], *isep, &num3);
if (fields1 == 0 || fields2 != fields1)
continue;
int num = min(num2, num3);
if (num > max_number_count || (num == max_number_count &&
fields1 > max_field_count)) {
max_number_count = num;
max_field_count = fields1;
sep = *isep;
}
}
int num0;
int fields0 = count_numbers(lines[0], sep, &num0);
if (fields0 != max_field_count)
throw FormatError("different field count (`" + S(sep) +
"'-separated) in lines 1 and 3.");
bool has_header = (num0 < max_number_count);
if (has_header && column_names) {
Tokenizer t(lines[0],
boost::escaped_list_separator<char>('\\', sep, '"'));
for (Tokenizer::iterator i = t.begin(); i != t.end(); ++i)
column_names->push_back(*i);
}
if (out != NULL) {
if (!has_header) {
out->resize(out->size() + 1);
read_numbers_from_line(lines[0], sep, &out->back());
}
for (int i = 1; i != 4; ++i) {
out->resize(out->size() + 1);
read_numbers_from_line(lines[i], sep, &out->back());
}
}
return sep;
}
bool CsvDataSet::check(istream &f)
{
try {
return read_4lines(f, false, NULL, NULL) != 0;
}
catch (FormatError &) {
return false;
}
}
void CsvDataSet::load_data(istream &f)
{
bool decimal_comma = has_option("decimal_comma");
vector<vector<double> > data;
vector<string> column_names;
string line;
line.reserve(100);
char sep = read_4lines(f, decimal_comma, &data, &column_names);
size_t n_col = data[0].size();
while (getline(f, line)) {
if (is_space(line.c_str()))
continue;
if (decimal_comma)
for (string::iterator p = line.begin(); p != line.end(); ++p)
if (*p == ',')
*p = '.';
data.resize(data.size() + 1);
data.back().reserve(n_col);
read_numbers_from_line(line, sep, &data.back());
}
Block* blk = new Block;
for (size_t i = 0; i != n_col; ++i) {
VecColumn *col = new VecColumn;
if (column_names.size() > i)
col->set_name(column_names[i]);
col->reserve(data.size());
for (size_t j = 0; j != data.size(); ++j)
col->add_val(data[j].size() > i ? data[j][i]
: numeric_limits<double>::quiet_NaN());
blk->add_column(col);
}
add_block(blk);
}
} // namespace xylib
<|endoftext|> |
<commit_before>#include "zcm.h"
#include <zmq.h>
#include <unistd.h>
#include <dirent.h>
#include <cstring>
#include <cassert>
#include <cctype>
#include <cstdio>
#include <vector>
using std::vector;
#include <unordered_map>
using std::unordered_map;
#include <string>
using std::string;
#include <mutex>
#include <thread>
#include <iostream>
#define METADATA_PUB_ADDR "ipc:///tmp/zcm-metadata-pub"
#define METADATA_SUB_ADDR "ipc:///tmp/zcm-metadata-sub"
#define ZMQ_IO_THREADS 1
struct Sub
{
zcm_callback_t *cb;
void *usr;
void *sock;
};
struct SubRegex
{
string channelRegex;
zcm_callback_t *cb;
void *usr;
};
struct Pub
{
void *sock;
};
struct zcm_t
{
std::thread recvThread;
// The mutex protects all data below it
std::mutex mut;
bool recvThreadStarted = false;
bool running = true;
void *ctx;
unordered_map<string, Sub> subs;
unordered_map<string, Pub> pubs;
vector<SubRegex> subRegex;
zcm_t()
{
ctx = zmq_init(ZMQ_IO_THREADS);
}
string getIPCAddress(const string& channel)
{
return "ipc:///tmp/zmq-channel-"+channel;
}
Sub *findSub(const string& channel)
{
auto it = subs.find(channel);
if (it != subs.end())
return &it->second;
else
return nullptr;
}
Pub *findPub(const string& channel)
{
auto it = pubs.find(channel);
if (it != pubs.end())
return &it->second;
else
return nullptr;
}
int publish(const string& channel, const char *data, size_t len)
{
std::unique_lock<std::mutex> lk(mut);
Pub *pub = findPub(channel);
if (!pub) {
void *sock = zmq_socket(ctx, ZMQ_PUB);
string address = getIPCAddress(channel);
zmq_bind(sock, address.c_str());
pubs.emplace(channel, Pub{sock});
pub = findPub(channel);
assert(pub);
}
int rc = zmq_send(pub->sock, data, len, 0);
assert(rc == (int)len);
return 0;
}
void searchForRegexSubs()
{
std::unique_lock<std::mutex> lk(mut);
// TODO: actually implement regex, or remove it
if (subRegex.size() == 0)
return;
for (auto& r : subRegex) {
if (r.channelRegex != ".*") {
static bool warned = false;
if (!warned) {
fprintf(stderr, "Er: only .* (aka subscribe-all) is implemented\n");
warned = true;
}
}
}
SubRegex& srex = subRegex[0];
const char *prefix = "zmq-channel-";
size_t prefixLen = strlen(prefix);
DIR *d;
dirent *ent;
if (!(d=opendir("/tmp/")))
return;
while ((ent=readdir(d)) != nullptr) {
if (strncmp(ent->d_name, prefix, prefixLen) == 0) {
string channel(ent->d_name + prefixLen);
if (!findSub(channel))
subOneInternal(channel, srex.cb, srex.usr);
}
}
closedir(d);
}
void recvMsgFromSock(const string& channel, void *sock)
{
const int BUFSZ = 1 << 20;
char *buf = (char *) malloc(BUFSZ);
int rc = zmq_recv(sock, buf, BUFSZ, 0);
assert(0 < rc && rc < BUFSZ);
// Dispatch
{
std::unique_lock<std::mutex> lk(mut);
if (Sub *sub = findSub(channel)) {
zcm_recv_buf_t rbuf;
rbuf.data = buf;
rbuf.len = rc;
rbuf.utime = 0;
rbuf.zcm = this;
sub->cb(&rbuf, channel.c_str(), sub->usr);
}
}
}
void recvThreadFunc()
{
while (1) {
searchForRegexSubs();
// Build up a list of poll items
vector<zmq_pollitem_t> pitems;
vector<string> pchannels;
{
std::unique_lock<std::mutex> lk(mut);
pitems.resize(subs.size());
int i = 0;
for (auto& elt : subs) {
auto& channel = elt.first;
auto& sub = elt.second;
auto *p = &pitems[i];
memset(p, 0, sizeof(*p));
p->socket = sub.sock;
p->events = ZMQ_POLLIN;
pchannels.emplace_back(channel);
i++;
}
}
int rc = zmq_poll(pitems.data(), pitems.size(), 100);
if (!running)
break;
if (rc >= 0) {
for (size_t i = 0; i < pitems.size(); i++) {
auto& p = pitems[i];
if (p.revents != 0)
recvMsgFromSock(pchannels[i], p.socket);
}
}
}
}
static bool isRegexChannel(const string& channel)
{
// These chars are considered regex
auto isRegexChar = [](char c) {
return c == '(' || c == ')' || c == '|' ||
c == '.' || c == '*' || c == '+';
};
for (auto& c : channel)
if (isRegexChar(c))
return true;
return false;
}
void subOneInternal(const string& channel, zcm_callback_t *cb, void *usr)
{
assert(!findSub(channel));
void *sock = zmq_socket(ctx, ZMQ_SUB);
string address = getIPCAddress(channel);
zmq_connect(sock, address.c_str());
zmq_setsockopt(sock, ZMQ_SUBSCRIBE, "", 0);
subs.emplace(channel, Sub{cb, usr, sock});
}
int subscribe(const string& channel, zcm_callback_t *cb, void *usr)
{
std::unique_lock<std::mutex> lk(mut);
if (isRegexChannel(channel)) {
subRegex.emplace_back(SubRegex{channel, cb, usr});
} else {
subOneInternal(channel, cb, usr);
}
if (!recvThreadStarted) {
recvThread = std::thread{&zcm_t::recvThreadFunc, this};
recvThreadStarted = true;
}
return 0;
}
};
static void printBytes(const char *buf, size_t len)
{
printf("printBytes:");
for (size_t i = 0; i < len; i++) {
char c = buf[i];
printf(" 0x%02x", c&0xff);
if (isalpha(c))
printf("(%c)", c);
}
printf("\n");
}
zcm_t *zcm_create(void)
{
return new zcm_t();
}
void zcm_destroy(zcm_t *zcm)
{
// TODO: What is the "correct" method to shut-down ZMQ?
}
int zcm_publish(zcm_t *zcm, const char *channel, char *data, size_t len)
{
return zcm->publish(channel, data, len);
}
int zcm_subscribe(zcm_t *zcm, const char *channel, zcm_callback_t *cb, void *usr)
{
return zcm->subscribe(channel, cb, usr);
}
<commit_msg>fixed leak<commit_after>#include "zcm.h"
#include <zmq.h>
#include <unistd.h>
#include <dirent.h>
#include <cstring>
#include <cassert>
#include <cctype>
#include <cstdio>
#include <vector>
using std::vector;
#include <unordered_map>
using std::unordered_map;
#include <string>
using std::string;
#include <mutex>
#include <thread>
#include <iostream>
#define METADATA_PUB_ADDR "ipc:///tmp/zcm-metadata-pub"
#define METADATA_SUB_ADDR "ipc:///tmp/zcm-metadata-sub"
#define ZMQ_IO_THREADS 1
struct Sub
{
zcm_callback_t *cb;
void *usr;
void *sock;
};
struct SubRegex
{
string channelRegex;
zcm_callback_t *cb;
void *usr;
};
struct Pub
{
void *sock;
};
struct zcm_t
{
std::thread recvThread;
// The mutex protects all data below it
std::mutex mut;
bool recvThreadStarted = false;
static constexpr int RECVBUFSZ = 1 << 20;
char recvbuf[RECVBUFSZ];
bool running = true;
void *ctx;
unordered_map<string, Sub> subs;
unordered_map<string, Pub> pubs;
vector<SubRegex> subRegex;
zcm_t()
{
ctx = zmq_init(ZMQ_IO_THREADS);
}
string getIPCAddress(const string& channel)
{
return "ipc:///tmp/zmq-channel-"+channel;
}
Sub *findSub(const string& channel)
{
auto it = subs.find(channel);
if (it != subs.end())
return &it->second;
else
return nullptr;
}
Pub *findPub(const string& channel)
{
auto it = pubs.find(channel);
if (it != pubs.end())
return &it->second;
else
return nullptr;
}
int publish(const string& channel, const char *data, size_t len)
{
std::unique_lock<std::mutex> lk(mut);
Pub *pub = findPub(channel);
if (!pub) {
void *sock = zmq_socket(ctx, ZMQ_PUB);
string address = getIPCAddress(channel);
zmq_bind(sock, address.c_str());
pubs.emplace(channel, Pub{sock});
pub = findPub(channel);
assert(pub);
}
int rc = zmq_send(pub->sock, data, len, 0);
assert(rc == (int)len);
return 0;
}
void searchForRegexSubs()
{
std::unique_lock<std::mutex> lk(mut);
// TODO: actually implement regex, or remove it
if (subRegex.size() == 0)
return;
for (auto& r : subRegex) {
if (r.channelRegex != ".*") {
static bool warned = false;
if (!warned) {
fprintf(stderr, "Er: only .* (aka subscribe-all) is implemented\n");
warned = true;
}
}
}
SubRegex& srex = subRegex[0];
const char *prefix = "zmq-channel-";
size_t prefixLen = strlen(prefix);
DIR *d;
dirent *ent;
if (!(d=opendir("/tmp/")))
return;
while ((ent=readdir(d)) != nullptr) {
if (strncmp(ent->d_name, prefix, prefixLen) == 0) {
string channel(ent->d_name + prefixLen);
if (!findSub(channel))
subOneInternal(channel, srex.cb, srex.usr);
}
}
closedir(d);
}
void recvMsgFromSock(const string& channel, void *sock)
{
int rc = zmq_recv(sock, recvbuf, RECVBUFSZ, 0);
assert(0 < rc && rc < RECVBUFSZ);
// Dispatch
{
std::unique_lock<std::mutex> lk(mut);
if (Sub *sub = findSub(channel)) {
zcm_recv_buf_t rbuf;
rbuf.data = recvbuf;
rbuf.len = rc;
rbuf.utime = 0;
rbuf.zcm = this;
sub->cb(&rbuf, channel.c_str(), sub->usr);
}
}
}
void recvThreadFunc()
{
while (1) {
searchForRegexSubs();
// Build up a list of poll items
vector<zmq_pollitem_t> pitems;
vector<string> pchannels;
{
std::unique_lock<std::mutex> lk(mut);
pitems.resize(subs.size());
int i = 0;
for (auto& elt : subs) {
auto& channel = elt.first;
auto& sub = elt.second;
auto *p = &pitems[i];
memset(p, 0, sizeof(*p));
p->socket = sub.sock;
p->events = ZMQ_POLLIN;
pchannels.emplace_back(channel);
i++;
}
}
int rc = zmq_poll(pitems.data(), pitems.size(), 100);
if (!running)
break;
if (rc >= 0) {
for (size_t i = 0; i < pitems.size(); i++) {
auto& p = pitems[i];
if (p.revents != 0)
recvMsgFromSock(pchannels[i], p.socket);
}
}
}
}
static bool isRegexChannel(const string& channel)
{
// These chars are considered regex
auto isRegexChar = [](char c) {
return c == '(' || c == ')' || c == '|' ||
c == '.' || c == '*' || c == '+';
};
for (auto& c : channel)
if (isRegexChar(c))
return true;
return false;
}
void subOneInternal(const string& channel, zcm_callback_t *cb, void *usr)
{
assert(!findSub(channel));
void *sock = zmq_socket(ctx, ZMQ_SUB);
string address = getIPCAddress(channel);
zmq_connect(sock, address.c_str());
zmq_setsockopt(sock, ZMQ_SUBSCRIBE, "", 0);
subs.emplace(channel, Sub{cb, usr, sock});
}
int subscribe(const string& channel, zcm_callback_t *cb, void *usr)
{
std::unique_lock<std::mutex> lk(mut);
if (isRegexChannel(channel)) {
subRegex.emplace_back(SubRegex{channel, cb, usr});
} else {
subOneInternal(channel, cb, usr);
}
if (!recvThreadStarted) {
recvThread = std::thread{&zcm_t::recvThreadFunc, this};
recvThreadStarted = true;
}
return 0;
}
};
static void printBytes(const char *buf, size_t len)
{
printf("printBytes:");
for (size_t i = 0; i < len; i++) {
char c = buf[i];
printf(" 0x%02x", c&0xff);
if (isalpha(c))
printf("(%c)", c);
}
printf("\n");
}
zcm_t *zcm_create(void)
{
return new zcm_t();
}
void zcm_destroy(zcm_t *zcm)
{
// TODO: What is the "correct" method to shut-down ZMQ?
}
int zcm_publish(zcm_t *zcm, const char *channel, char *data, size_t len)
{
return zcm->publish(channel, data, len);
}
int zcm_subscribe(zcm_t *zcm, const char *channel, zcm_callback_t *cb, void *usr)
{
return zcm->subscribe(channel, cb, usr);
}
<|endoftext|> |
<commit_before>/* predictionResultDialog.C
*
* Copyright (C) 2009 Marcel Schumann
*
* This file is part of QuEasy -- A Toolbox for Automated QSAR Model
* Construction and Validation.
* QuEasy is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* QuEasy is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#include <predictionResultDialog.h>
#include <mainWindow.h>
#include <QtGui/QDialogButtonBox>
#include <QtGui/QFileDialog>
#include <QtGui/QLabel>
#include <QtGui/QGroupBox>
#include <QtGui/QHBoxLayout>
#include <QtGui/QVBoxLayout>
#include <QtGui/QPushButton>
#include <QtCore/QFile>
#include <QtCore/QTextStream>
#include <QtGui/QScrollArea>
#include <QtGui/QHeaderView>
using namespace BALL::QSAR;
namespace BALL
{
namespace VIEW
{
PredictionResultDialog::PredictionResultDialog(PredictionItem* item)
{
//return if there's no parent
if (item == NULL)
{
return;
}
pred_item_ = item;
QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok,Qt::Horizontal, this);
QPushButton* print_button = new QPushButton("Save to File", buttons);
QVBoxLayout* mainLayout = new QVBoxLayout();
QVBoxLayout* resultGroupLayout = new QVBoxLayout();
QGroupBox* resultGroup = new QGroupBox(tr("Predicted Activity Values"),this);
file_name_ = item->name();
results_ = item->results();
QStringList labels;
labels << "Compound";
bool show_expected=0;
const QSARData* test_data = 0;
uint no_y=0;
if(item->getTestData()!=0) no_y=item->getTestData()->getNoResponseVariables();
else if(results_->size()==0) return; // no prediction=>nothing to be displayed
if(no_y>=1)
{
show_expected=1;
test_data = item->getTestData();
if(no_y==1) labels<<"Prediction"<<"Expected";
else
{
for(uint i=0; i<no_y;i++)
{
String p = "Prediction"+String(i);
String e = "Expected"+String(i);
labels<<p.c_str()<<e.c_str();
}
}
}
else
{
labels<<"Prediction";
}
compound_names_ = test_data->getSubstanceNames();
table_ = new QTableWidget(results_->size(), 1+no_y*(1+show_expected), this);
table_->verticalHeader()->hide();
table_->setHorizontalHeaderLabels (labels);
table_->setAlternatingRowColors(true);
table_->setDragDropMode(QAbstractItemView::NoDragDrop);
table_->setEditTriggers(QAbstractItemView::NoEditTriggers);
table_->horizontalHeader()->setResizeMode(QHeaderView::Custom);
if(((uint)results_->size()) == compound_names_->size())
{
int i = 0;
for (list<Vector<double> >::const_iterator it = results_->begin(); it != results_->end(); it++)
{
QTableWidgetItem* name = new QTableWidgetItem(QString(compound_names_->at(i).c_str()));
table_->setItem(i, 0, name);
vector<double>* e = 0;
if(show_expected) e = test_data->getActivity(i);
for(uint act=0; act<e->size(); act++)
{
QTableWidgetItem* pred = new QTableWidgetItem(QString((((String)(*it)(1+act)).c_str())));
table_->setItem(i, 1+2*act, pred);
if(show_expected)
{
QTableWidgetItem* expected = new QTableWidgetItem(QString(((String((*e)[act])).c_str())));
table_->setItem(i, 2+2*act, expected);
}
}
delete e;
i++;
}
}
QScrollArea* scrollArea = new QScrollArea(this);
scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
scrollArea->setFrameShape(QFrame::NoFrame);
scrollArea->setWidget(table_);
scrollArea->setWidgetResizable(true);
resultGroupLayout->addWidget(scrollArea);
resultGroup->setLayout(resultGroupLayout);
mainLayout->addWidget(resultGroup);
mainLayout->addWidget(buttons);
setLayout(mainLayout);
setWindowTitle("Predicted Activity Values for " + item->name());
uint width = 0;
for(int i=0; i<table_->columnCount();i++)
{
width+=table_->columnWidth(i);
}
width+=65;
uint mainWindow_width = item->view()->data_scene->main_window->size().width();
if(width<mainWindow_width) resize(width,450);
else resize(mainWindow_width,450);
table_->setSortingEnabled(1);
connect(buttons, SIGNAL(accepted()), this, SLOT(accept()));
connect(print_button, SIGNAL(clicked()), this, SLOT(saveToFile()));
}
PredictionResultDialog::~PredictionResultDialog()
{
}
void PredictionResultDialog::saveToFile()
{
QString filename = QFileDialog::getSaveFileName(this, tr("Save File as"),file_name_ +"_prediction_results.txt",tr("text (*.txt)"));
QFile file(filename);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
{
return;
}
ofstream out(file.fileName().toStdString().c_str());
uint no_rows=table_->rowCount();
uint no_cols=table_->columnCount();
bool use_selection = (table_->selectedItems().size()>1);
list<int> selected_columns;
list<int> selected_rows;
list<int>::iterator col_it;
list<int>::iterator row_it;
if(use_selection)
{
// find selected columns
QList<QTableWidgetSelectionRange> ranges = table_->selectedRanges();
for(int i=0; i<(int)no_cols; i++)
{
for(QList<QTableWidgetSelectionRange>::iterator it=ranges.begin();it!=ranges.end();it++)
{
if(i<=it->rightColumn() && i>=it->leftColumn())
{
selected_columns.push_back(i);
break;
}
}
}
col_it=selected_columns.begin();
// find selected rows
for(int i=0; i<(int)no_rows; i++)
{
for(QList<QTableWidgetSelectionRange>::iterator it=ranges.begin();it!=ranges.end();it++)
{
if(i<=it->bottomRow() && i>=it->topRow())
{
selected_rows.push_back(i);
break;
}
}
}
row_it=selected_rows.begin();
}
// print table-header
for(int i=0; i<(int)no_cols; i++)
{
bool write=0;
if(use_selection)
{
if(col_it!=selected_columns.end() && *col_it==i)
{
write=1;
col_it++;
}
}
if(!use_selection || write) out<<table_->horizontalHeaderItem(i)->text().toStdString()<<"\t";
}
out<<endl;
if(use_selection) col_it=selected_columns.begin();
// print data
for(int i=0; i<(int)no_rows; i++)
{
bool wrote_item=0;
for(int j=0; j<(int)no_cols; j++)
{
if(!use_selection || table_->item(i,j)->isSelected())
{
out<<table_->item(i,j)->text().toStdString()<<"\t";
wrote_item=1;
}
else if(col_it!=selected_columns.end() && *col_it==j && row_it!=selected_rows.end() && *row_it==i)
{
out<<"\t";
col_it++;
}
}
if(wrote_item)
{
out<<endl;
if(use_selection)
{
row_it++;
col_it=selected_columns.begin();
}
}
}
}
}
}<commit_msg>Fixed displaying predictions without available expected values in PredictionResultDialog.<commit_after>/* predictionResultDialog.C
*
* Copyright (C) 2009 Marcel Schumann
*
* This file is part of QuEasy -- A Toolbox for Automated QSAR Model
* Construction and Validation.
* QuEasy is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* QuEasy is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#include <predictionResultDialog.h>
#include <mainWindow.h>
#include <QtGui/QDialogButtonBox>
#include <QtGui/QFileDialog>
#include <QtGui/QLabel>
#include <QtGui/QGroupBox>
#include <QtGui/QHBoxLayout>
#include <QtGui/QVBoxLayout>
#include <QtGui/QPushButton>
#include <QtCore/QFile>
#include <QtCore/QTextStream>
#include <QtGui/QScrollArea>
#include <QtGui/QHeaderView>
using namespace BALL::QSAR;
namespace BALL
{
namespace VIEW
{
PredictionResultDialog::PredictionResultDialog(PredictionItem* item)
{
//return if there's no parent
if (item == NULL)
{
return;
}
pred_item_ = item;
QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok,Qt::Horizontal, this);
QPushButton* print_button = new QPushButton("Save to File", buttons);
QVBoxLayout* mainLayout = new QVBoxLayout();
QVBoxLayout* resultGroupLayout = new QVBoxLayout();
QGroupBox* resultGroup = new QGroupBox(tr("Predicted Activity Values"),this);
file_name_ = item->name();
results_ = item->results();
QStringList labels;
labels << "Compound";
bool show_expected=0;
const QSARData* test_data = 0;
if(item->getTestData()==0 || results_->size()==0) return; // no prediction=>nothing to be displayed
test_data = item->getTestData();
Size no_y=test_data->getNoResponseVariables();
if(no_y>=1)
{
show_expected=1;
if(no_y==1) labels<<"Prediction"<<"Expected";
else
{
for(uint i=0; i<no_y;i++)
{
String p = "Prediction"+String(i);
String e = "Expected"+String(i);
labels<<p.c_str()<<e.c_str();
}
}
}
else
{
for(Size act=0; act<results_->front().getSize(); act++)
{
String p = "Prediction"+String(act);
labels<<p.c_str();
}
}
compound_names_ = test_data->getSubstanceNames();
Size no_columns = 1;
if(no_y>=1) no_columns+=2*no_y;
else no_columns+=results_->front().getSize();
table_ = new QTableWidget(results_->size(), no_columns, this);
table_->verticalHeader()->hide();
table_->setHorizontalHeaderLabels (labels);
table_->setAlternatingRowColors(true);
table_->setDragDropMode(QAbstractItemView::NoDragDrop);
table_->setEditTriggers(QAbstractItemView::NoEditTriggers);
if(results_->size()==compound_names_->size())
{
int i = 0;
for (list<Vector<double> >::const_iterator it = results_->begin(); it != results_->end(); it++)
{
QTableWidgetItem* name = new QTableWidgetItem(QString(compound_names_->at(i).c_str()));
table_->setItem(i, 0, name);
vector<double>* e = 0;
if(show_expected) e = test_data->getActivity(i);
for(uint act=0; act<it->getSize(); act++)
{
QTableWidgetItem* pred = new QTableWidgetItem(QString((((String)(*it)(1+act)).c_str())));
table_->setItem(i, 1+(1+show_expected)*act, pred);
if(show_expected)
{
QTableWidgetItem* expected = new QTableWidgetItem(QString(((String((*e)[act])).c_str())));
table_->setItem(i, 2+2*act, expected);
}
}
delete e;
i++;
}
}
QScrollArea* scrollArea = new QScrollArea(this);
scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
scrollArea->setFrameShape(QFrame::NoFrame);
scrollArea->setWidget(table_);
scrollArea->setWidgetResizable(true);
resultGroupLayout->addWidget(scrollArea);
resultGroup->setLayout(resultGroupLayout);
mainLayout->addWidget(resultGroup);
mainLayout->addWidget(buttons);
setLayout(mainLayout);
setWindowTitle("Predicted Activity Values for " + item->name());
table_->horizontalHeader()->resizeSections(QHeaderView::ResizeToContents);
uint width = 0;
for(int i=0; i<table_->columnCount();i++)
{
width+=table_->columnWidth(i);
}
width+=65;
uint mainWindow_width = item->view()->data_scene->main_window->size().width();
if(width<mainWindow_width) resize(width,450);
else resize(mainWindow_width,450);
table_->setSortingEnabled(1);
connect(buttons, SIGNAL(accepted()), this, SLOT(accept()));
connect(print_button, SIGNAL(clicked()), this, SLOT(saveToFile()));
}
PredictionResultDialog::~PredictionResultDialog()
{
}
void PredictionResultDialog::saveToFile()
{
QString filename = QFileDialog::getSaveFileName(this, tr("Save File as"),file_name_ +"_prediction_results.txt",tr("text (*.txt)"));
QFile file(filename);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
{
return;
}
ofstream out(file.fileName().toStdString().c_str());
uint no_rows=table_->rowCount();
uint no_cols=table_->columnCount();
bool use_selection = (table_->selectedItems().size()>1);
list<int> selected_columns;
list<int> selected_rows;
list<int>::iterator col_it;
list<int>::iterator row_it;
if(use_selection)
{
// find selected columns
QList<QTableWidgetSelectionRange> ranges = table_->selectedRanges();
for(int i=0; i<(int)no_cols; i++)
{
for(QList<QTableWidgetSelectionRange>::iterator it=ranges.begin();it!=ranges.end();it++)
{
if(i<=it->rightColumn() && i>=it->leftColumn())
{
selected_columns.push_back(i);
break;
}
}
}
col_it=selected_columns.begin();
// find selected rows
for(int i=0; i<(int)no_rows; i++)
{
for(QList<QTableWidgetSelectionRange>::iterator it=ranges.begin();it!=ranges.end();it++)
{
if(i<=it->bottomRow() && i>=it->topRow())
{
selected_rows.push_back(i);
break;
}
}
}
row_it=selected_rows.begin();
}
// print table-header
for(int i=0; i<(int)no_cols; i++)
{
bool write=0;
if(use_selection)
{
if(col_it!=selected_columns.end() && *col_it==i)
{
write=1;
col_it++;
}
}
if(!use_selection || write) out<<table_->horizontalHeaderItem(i)->text().toStdString()<<"\t";
}
out<<endl;
if(use_selection) col_it=selected_columns.begin();
// print data
for(int i=0; i<(int)no_rows; i++)
{
bool wrote_item=0;
for(int j=0; j<(int)no_cols; j++)
{
if(!use_selection || table_->item(i,j)->isSelected())
{
out<<table_->item(i,j)->text().toStdString()<<"\t";
wrote_item=1;
}
else if(col_it!=selected_columns.end() && *col_it==j && row_it!=selected_rows.end() && *row_it==i)
{
out<<"\t";
col_it++;
}
}
if(wrote_item)
{
out<<endl;
if(use_selection)
{
row_it++;
col_it=selected_columns.begin();
}
}
}
}
}
}<|endoftext|> |
<commit_before>#include <Accelerometer_GY_521_mock.h>
int Accelerometer_GY_521_mock::_init_accelerometer_sensor(){
size_t len = 0;
char *update_string = NULL;
logger.log(LOG_DEBUG, "Opening the file for Accelerometer values");
//Opening the file (
save_file = fopen(SAVE_ACCELEROMETER_FILENAME, "r");
//Registering the update frequency
if(save_file == NULL){
logger.log(LOG_ERROR, "Failing to open %s", SAVE_ACCELEROMETER_FILENAME);
return -1;
}
// If the first line is empty
if(getline(&update_string, &len, save_file) == -1){
logger.log(LOG_ERROR, "Gyroscope save file is empty");
return -1;
}
// We test if the save file has been save with the same update frequency
if(atoi(update_string) != update_frequency_ms){
logger.log(LOG_ERROR, "Error the file has been recorded at %ims, expecting %ims", atoi(update_string), update_frequency_ms);
return -1;
}
logger.log(LOG_DEBUG, "Accelerometer successfully mocked");
free(update_string);
return 0;
}
int Accelerometer_GY_521_mock::_teardown_accelerometer_sensor(){
int error_code = 0;
if(fclose(save_file))
error_code = -1;
return error_code;
}
double Accelerometer_GY_521_mock::_get_x_acceleration(){
double value = 0.0;
load_from_file(&value, AXIS_X);
return value;
}
double Accelerometer_GY_521_mock::_get_y_acceleration(){
double value = 0.0;
load_from_file(&value, AXIS_Y);
return value;
}
double Accelerometer_GY_521_mock::_get_z_acceleration(){
double value = 0.0;
load_from_file(&value, AXIS_Z);
return value;
}
/**
* Allow to load the values directly from a file
* It can manage values refreshment when needed
* this function can't be common between gyroscope and accelerometer values because of static values
*/
int Accelerometer_GY_521_mock::load_from_file(double *buffer, axis axis_desired){
static bool x_new = true;
static bool y_new = true;
static bool z_new = true;
static double x_value = 0.0;
static double y_value = 0.0;
static double z_value = 0.0;
double values_array[3];
char *values = NULL;
size_t len;
// If the value has already been fetched, we must triger a new line reading
if( (axis_desired == AXIS_X && !x_new) || (axis_desired == AXIS_Y && !y_new) || (axis_desired == AXIS_Z && !z_new)){
if(getline(&values, &len, save_file) == -1){
free(values);
logger.log(LOG_ERROR, "File %s empty", SAVE_ACCELEROMETER_FILENAME);
return -1;
}
// We then get extract decimal values separated by space from the string
int j=0;
int previous_index = 0;
for(int i=0; values[i] != '\0'; i++){
// if we have found a separator;
if(values[i] == ' '){
values[i] = '\0';
values_array[j] = atof(&values[previous_index]);
j++;
//The begining of the next value in the string
previous_index = i+1;
}
}
values_array[j] = atof(&values[previous_index]);
x_value = values_array[0];
y_value = values_array[1];
z_value = values_array[2];
x_new = true;
y_new = true;
z_new = true;
}
// We return the value demanded and turn the associated new flag to false
switch (axis_desired){
case AXIS_X:
*buffer = x_value;
x_new = false;
break;
case AXIS_Y:
*buffer = y_value;
y_new = false;
break;
case AXIS_Z:
*buffer = z_value;
z_new = false;
break;
}
free(values);
return 0;
}
<commit_msg>Modify error message when mocking is not at the right frequency<commit_after>#include <Accelerometer_GY_521_mock.h>
int Accelerometer_GY_521_mock::_init_accelerometer_sensor(){
size_t len = 0;
char *update_string = NULL;
logger.log(LOG_DEBUG, "Opening the file for Accelerometer values");
//Opening the file (
save_file = fopen(SAVE_ACCELEROMETER_FILENAME, "r");
//Registering the update frequency
if(save_file == NULL){
logger.log(LOG_ERROR, "Failing to open %s", SAVE_ACCELEROMETER_FILENAME);
return -1;
}
// If the first line is empty
if(getline(&update_string, &len, save_file) == -1){
logger.log(LOG_ERROR, "Gyroscope save file is empty");
return -1;
}
// We test if the save file has been save with the same update frequency
if(atoi(update_string) != update_frequency_ms){
logger.log(LOG_ERROR, "Error the file has been recorded at %ims, %ims is not a correct update value", atoi(update_string), update_frequency_ms);
return -1;
}
logger.log(LOG_DEBUG, "Accelerometer successfully mocked");
free(update_string);
return 0;
}
int Accelerometer_GY_521_mock::_teardown_accelerometer_sensor(){
int error_code = 0;
if(fclose(save_file))
error_code = -1;
return error_code;
}
double Accelerometer_GY_521_mock::_get_x_acceleration(){
double value = 0.0;
load_from_file(&value, AXIS_X);
return value;
}
double Accelerometer_GY_521_mock::_get_y_acceleration(){
double value = 0.0;
load_from_file(&value, AXIS_Y);
return value;
}
double Accelerometer_GY_521_mock::_get_z_acceleration(){
double value = 0.0;
load_from_file(&value, AXIS_Z);
return value;
}
/**
* Allow to load the values directly from a file
* It can manage values refreshment when needed
* this function can't be common between gyroscope and accelerometer values because of static values
*/
int Accelerometer_GY_521_mock::load_from_file(double *buffer, axis axis_desired){
static bool x_new = true;
static bool y_new = true;
static bool z_new = true;
static double x_value = 0.0;
static double y_value = 0.0;
static double z_value = 0.0;
double values_array[3];
char *values = NULL;
size_t len;
// If the value has already been fetched, we must triger a new line reading
if( (axis_desired == AXIS_X && !x_new) || (axis_desired == AXIS_Y && !y_new) || (axis_desired == AXIS_Z && !z_new)){
if(getline(&values, &len, save_file) == -1){
free(values);
logger.log(LOG_ERROR, "File %s empty", SAVE_ACCELEROMETER_FILENAME);
return -1;
}
// We then get extract decimal values separated by space from the string
int j=0;
int previous_index = 0;
for(int i=0; values[i] != '\0'; i++){
// if we have found a separator;
if(values[i] == ' '){
values[i] = '\0';
values_array[j] = atof(&values[previous_index]);
j++;
//The begining of the next value in the string
previous_index = i+1;
}
}
values_array[j] = atof(&values[previous_index]);
x_value = values_array[0];
y_value = values_array[1];
z_value = values_array[2];
x_new = true;
y_new = true;
z_new = true;
}
// We return the value demanded and turn the associated new flag to false
switch (axis_desired){
case AXIS_X:
*buffer = x_value;
x_new = false;
break;
case AXIS_Y:
*buffer = y_value;
y_new = false;
break;
case AXIS_Z:
*buffer = z_value;
z_new = false;
break;
}
free(values);
return 0;
}
<|endoftext|> |
<commit_before>#include <yafraycore/ccthreads.h>
#include <iostream>
#include <stdexcept>
#ifdef __APPLE__
#include <AvailabilityMacros.h>
#endif
using namespace std;
namespace yafthreads {
mutex_t::mutex_t()
{
#if HAVE_PTHREAD
int error=pthread_mutex_init(&m, NULL);
switch(error)
{
case EINVAL: throw std::runtime_error("pthread_mutex_init error EINVAL"); break;
case ENOMEM: throw std::runtime_error("pthread_mutex_init error ENOMEM"); break;
case EAGAIN: throw std::runtime_error("pthread_mutex_init error EAGAIN"); break;
default: break;
}
#elif defined( WIN32_THREADS )
winMutex = CreateMutex(0, FALSE, 0);
#endif
}
void mutex_t::lock()
{
#if HAVE_PTHREAD
if(pthread_mutex_lock(&m))
{
throw std::runtime_error("Error mutex lock");
}
#elif defined( WIN32_THREADS )
WaitForSingleObject(winMutex, INFINITE);
#endif
}
void mutex_t::unlock()
{
#if HAVE_PTHREAD
if(pthread_mutex_unlock(&m))
{
throw std::runtime_error("Error mutex lock");
}
#elif defined( WIN32_THREADS )
ReleaseMutex(winMutex);
#endif
}
mutex_t::~mutex_t()
{
#if HAVE_PTHREAD
pthread_mutex_destroy(&m);
#elif defined( WIN32_THREADS )
CloseHandle(winMutex);
#endif
}
/* condition object */
conditionVar_t::conditionVar_t()
{
#if HAVE_PTHREAD
int error=pthread_mutex_init(&m, NULL);
switch(error)
{
case EINVAL: throw std::runtime_error("pthread_mutex_init error EINVAL"); break;
case ENOMEM: throw std::runtime_error("pthread_mutex_init error ENOMEM"); break;
case EAGAIN: throw std::runtime_error("pthread_mutex_init error EAGAIN"); break;
default: break;
}
error = pthread_cond_init (&c, NULL);
if(error != 0)
{
throw std::runtime_error("pthread_cond_init error\n");
}
#elif defined( WIN32_THREADS )
condHandle = CreateEvent(0, FALSE, FALSE, "yafConditionSignal");
winMutex = CreateMutex(0, FALSE, 0);
#endif
}
void conditionVar_t::lock()
{
#if HAVE_PTHREAD
if(pthread_mutex_lock(&m))
{
throw std::runtime_error("Error mutex lock");
}
#elif defined( WIN32_THREADS )
WaitForSingleObject(winMutex, INFINITE);
#endif
}
void conditionVar_t::unlock()
{
#if HAVE_PTHREAD
if(pthread_mutex_unlock(&m))
{
throw std::runtime_error("Error mutex lock");
}
#elif defined( WIN32_THREADS )
ReleaseMutex(winMutex);
#endif
}
void conditionVar_t::signal()
{
#if HAVE_PTHREAD
if(pthread_cond_signal(&c))
{
throw std::runtime_error("Error condition signal");
}
#elif defined( WIN32_THREADS )
SetEvent(condHandle);
#endif
}
void conditionVar_t::wait()
{
#if HAVE_PTHREAD
if(pthread_cond_wait(&c, &m))
{
throw std::runtime_error("Error condition wait");
}
#elif defined( WIN32_THREADS )
unlock();
SignalObjectAndWait(condHandle, winMutex, INFINITE, FALSE);
#endif
}
conditionVar_t::~conditionVar_t()
{
#if HAVE_PTHREAD
pthread_mutex_destroy(&m);
pthread_cond_destroy(&c);
#elif defined( WIN32_THREADS )
CloseHandle(condHandle);
CloseHandle(winMutex);
#endif
}
#if HAVE_PTHREAD
void * wrapper(void *data)
{
thread_t *obj=(thread_t *)data;
obj->lock.lock();
try{ obj->body(); }
catch(std::exception &e)
{
std::cout << "exception occured: " << e.what() << std::endl;
}
obj->running=false;
obj->lock.unlock();
pthread_exit(0);
return NULL;
}
void thread_t::run()
{
lock.lock();
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE);
pthread_create(&id,&attr,wrapper,this);
running=true;
lock.unlock();
}
void thread_t::wait()
{
if(running)
pthread_join(id,NULL);
running=false;
}
thread_t::~thread_t()
{
wait();
}
#elif defined( WIN32_THREADS )
DWORD WINAPI wrapper (void *data)
{
thread_t *obj=(thread_t *)data;
//obj->lock.lock();
obj->body();
//obj->lock.unlock();
return 0;
}
void thread_t::run()
{
//lock.lock();
winThread = CreateThread(0, 0, wrapper, this, 0, &id);
running = true;
//lock.unlock();
}
void thread_t::wait()
{
WaitForSingleObject(winThread, INFINITE);
running = false;
}
thread_t::~thread_t()
{
if(running) wait();
CloseHandle(winThread);
}
#endif
} // yafthreads
<commit_msg>- Small fix on threading code: Unnecesary mutex locks slow thread creation on fast systems<commit_after>#include <yafraycore/ccthreads.h>
#include <iostream>
#include <stdexcept>
#ifdef __APPLE__
#include <AvailabilityMacros.h>
#endif
using namespace std;
namespace yafthreads {
mutex_t::mutex_t()
{
#if HAVE_PTHREAD
int error=pthread_mutex_init(&m, NULL);
switch(error)
{
case EINVAL: throw std::runtime_error("pthread_mutex_init error EINVAL"); break;
case ENOMEM: throw std::runtime_error("pthread_mutex_init error ENOMEM"); break;
case EAGAIN: throw std::runtime_error("pthread_mutex_init error EAGAIN"); break;
default: break;
}
#elif defined( WIN32_THREADS )
winMutex = CreateMutex(0, FALSE, 0);
#endif
}
void mutex_t::lock()
{
#if HAVE_PTHREAD
if(pthread_mutex_lock(&m))
{
throw std::runtime_error("Error mutex lock");
}
#elif defined( WIN32_THREADS )
WaitForSingleObject(winMutex, INFINITE);
#endif
}
void mutex_t::unlock()
{
#if HAVE_PTHREAD
if(pthread_mutex_unlock(&m))
{
throw std::runtime_error("Error mutex lock");
}
#elif defined( WIN32_THREADS )
ReleaseMutex(winMutex);
#endif
}
mutex_t::~mutex_t()
{
#if HAVE_PTHREAD
pthread_mutex_destroy(&m);
#elif defined( WIN32_THREADS )
CloseHandle(winMutex);
#endif
}
/* condition object */
conditionVar_t::conditionVar_t()
{
#if HAVE_PTHREAD
int error=pthread_mutex_init(&m, NULL);
switch(error)
{
case EINVAL: throw std::runtime_error("pthread_mutex_init error EINVAL"); break;
case ENOMEM: throw std::runtime_error("pthread_mutex_init error ENOMEM"); break;
case EAGAIN: throw std::runtime_error("pthread_mutex_init error EAGAIN"); break;
default: break;
}
error = pthread_cond_init (&c, NULL);
if(error != 0)
{
throw std::runtime_error("pthread_cond_init error\n");
}
#elif defined( WIN32_THREADS )
condHandle = CreateEvent(0, FALSE, FALSE, "yafConditionSignal");
winMutex = CreateMutex(0, FALSE, 0);
#endif
}
void conditionVar_t::lock()
{
#if HAVE_PTHREAD
if(pthread_mutex_lock(&m))
{
throw std::runtime_error("Error mutex lock");
}
#elif defined( WIN32_THREADS )
WaitForSingleObject(winMutex, INFINITE);
#endif
}
void conditionVar_t::unlock()
{
#if HAVE_PTHREAD
if(pthread_mutex_unlock(&m))
{
throw std::runtime_error("Error mutex lock");
}
#elif defined( WIN32_THREADS )
ReleaseMutex(winMutex);
#endif
}
void conditionVar_t::signal()
{
#if HAVE_PTHREAD
if(pthread_cond_signal(&c))
{
throw std::runtime_error("Error condition signal");
}
#elif defined( WIN32_THREADS )
SetEvent(condHandle);
#endif
}
void conditionVar_t::wait()
{
#if HAVE_PTHREAD
if(pthread_cond_wait(&c, &m))
{
throw std::runtime_error("Error condition wait");
}
#elif defined( WIN32_THREADS )
unlock();
SignalObjectAndWait(condHandle, winMutex, INFINITE, FALSE);
#endif
}
conditionVar_t::~conditionVar_t()
{
#if HAVE_PTHREAD
pthread_mutex_destroy(&m);
pthread_cond_destroy(&c);
#elif defined( WIN32_THREADS )
CloseHandle(condHandle);
CloseHandle(winMutex);
#endif
}
#if HAVE_PTHREAD
void * wrapper(void *data)
{
thread_t *obj=(thread_t *)data;
//obj->lock.lock();
try{ obj->body(); }
catch(std::exception &e)
{
std::cout << "exception occured: " << e.what() << std::endl;
}
obj->running=false;
//obj->lock.unlock();
pthread_exit(0);
return NULL;
}
void thread_t::run()
{
//lock.lock();
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE);
pthread_create(&id,&attr,wrapper,this);
running=true;
//lock.unlock();
}
void thread_t::wait()
{
//if(running)
pthread_join(id,NULL);
running=false;
}
thread_t::~thread_t()
{
wait();
}
#elif defined( WIN32_THREADS )
DWORD WINAPI wrapper (void *data)
{
thread_t *obj=(thread_t *)data;
//obj->lock.lock();
obj->body();
//obj->lock.unlock();
return 0;
}
void thread_t::run()
{
//lock.lock();
winThread = CreateThread(0, 0, wrapper, this, 0, &id);
running = true;
//lock.unlock();
}
void thread_t::wait()
{
WaitForSingleObject(winThread, INFINITE);
running = false;
}
thread_t::~thread_t()
{
if(running) wait();
CloseHandle(winThread);
}
#endif
} // yafthreads
<|endoftext|> |
<commit_before>/*------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2021 Google LLC.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief Tests that compute shaders have a subgroup size that is uniform in
* command scope.
*//*--------------------------------------------------------------------*/
#include "deUniquePtr.hpp"
#include "vkRef.hpp"
#include "vkRefUtil.hpp"
#include "vkPrograms.hpp"
#include "vkMemUtil.hpp"
#include "vkBuilderUtil.hpp"
#include "vkCmdUtil.hpp"
#include "vkObjUtil.hpp"
#include "vkTypeUtil.hpp"
#include "vkImageWithMemory.hpp"
#include "vkBarrierUtil.hpp"
#include "vktTestCaseUtil.hpp"
using namespace vk;
namespace vkt
{
namespace subgroups
{
namespace
{
using std::vector;
using de::MovePtr;
class MultipleDispatchesUniformSubgroupSizeInstance : public TestInstance
{
public:
MultipleDispatchesUniformSubgroupSizeInstance (Context& context);
tcu::TestStatus iterate (void);
};
MultipleDispatchesUniformSubgroupSizeInstance::MultipleDispatchesUniformSubgroupSizeInstance (Context& context)
:TestInstance (context)
{
}
tcu::TestStatus MultipleDispatchesUniformSubgroupSizeInstance::iterate (void)
{
const DeviceInterface& vk = m_context.getDeviceInterface();
const VkDevice device = m_context.getDevice();
Allocator& allocator = m_context.getDefaultAllocator();
const VkQueue queue = m_context.getUniversalQueue();
const deUint32 queueFamilyIndex = m_context.getUniversalQueueFamilyIndex();
const Move<VkCommandPool> cmdPool = createCommandPool(vk, device, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, queueFamilyIndex);
const Move<VkCommandBuffer> cmdBuffer = allocateCommandBuffer(vk, device, *cmdPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY);
Move<VkShaderModule> computeShader = createShaderModule (vk, device, m_context.getBinaryCollection().get("comp"), 0u);
// The number of invocations in a workgroup.
const deUint32 maxLocalSize = m_context.getDeviceProperties().limits.maxComputeWorkGroupSize[0];
// Create a storage buffer to hold the sizes of subgroups.
const VkDeviceSize bufferSize = maxLocalSize * 2 * sizeof(deUint32);
const VkBufferCreateInfo resultBufferCreateInfo = makeBufferCreateInfo(bufferSize, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
Move<VkBuffer> resultBuffer = createBuffer(vk, device, &resultBufferCreateInfo);
MovePtr<Allocation> resultBufferMemory = allocator.allocate(getBufferMemoryRequirements(vk, device, *resultBuffer), MemoryRequirement::HostVisible);
VK_CHECK(vk.bindBufferMemory(device, *resultBuffer, resultBufferMemory->getMemory(), resultBufferMemory->getOffset()));
// Build descriptors for the storage buffer
const Unique<VkDescriptorPool> descriptorPool (DescriptorPoolBuilder().addType(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC)
.build(vk, device, VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, 1u));
const auto descriptorSetLayout1 (DescriptorSetLayoutBuilder().addSingleBinding(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, VK_SHADER_STAGE_COMPUTE_BIT)
.build(vk, device));
const VkDescriptorBufferInfo resultInfo = makeDescriptorBufferInfo(*resultBuffer, 0u,
(VkDeviceSize) bufferSize - maxLocalSize * sizeof(deUint32));
const VkDescriptorSetAllocateInfo allocInfo =
{
VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, // sType
DE_NULL, // pNext
*descriptorPool, // descriptorPool
1u, // descriptorSetCount
&(*descriptorSetLayout1) // pSetLayouts
};
Move<VkDescriptorSet> descriptorSet = allocateDescriptorSet(vk, device, &allocInfo);
DescriptorSetUpdateBuilder builder;
builder.writeSingle(*descriptorSet, DescriptorSetUpdateBuilder::Location::binding(0u), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, &resultInfo);
builder.update(vk, device);
// Compute pipeline
const Move<VkPipelineLayout> computePipelineLayout = makePipelineLayout (vk, device, *descriptorSetLayout1);
for (deUint32 localSize1 = 8; localSize1 < maxLocalSize + 1; localSize1 *= 2)
{
for (deUint32 localSize2 = 8; localSize2 < maxLocalSize + 1; localSize2 *= 2)
{
// On each iteration, change the number of invocations which might affect
// the subgroup size if the driver doesn't behave as expected.
const VkSpecializationMapEntry entries =
{
0u, // deUint32 constantID;
0u, // deUint32 offset;
sizeof(localSize1) // size_t size;
};
const VkSpecializationInfo specInfo =
{
1, // mapEntryCount
&entries, // pMapEntries
sizeof(localSize1), // dataSize
&localSize1 // pData
};
const VkSpecializationInfo specInfo2 =
{
1, // mapEntryCount
&entries, // pMapEntries
sizeof(localSize2), // dataSize
&localSize2 // pData
};
const VkPipelineShaderStageCreateInfo shaderStageCreateInfo =
{
VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, // sType
DE_NULL, // pNext
VK_PIPELINE_SHADER_STAGE_CREATE_ALLOW_VARYING_SUBGROUP_SIZE_BIT_EXT, // flags
VK_SHADER_STAGE_COMPUTE_BIT, // stage
*computeShader, // module
"main", // pName
&specInfo, // pSpecializationInfo
};
const VkPipelineShaderStageCreateInfo shaderStageCreateInfo2 =
{
VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, // sType
DE_NULL, // pNext
VK_PIPELINE_SHADER_STAGE_CREATE_ALLOW_VARYING_SUBGROUP_SIZE_BIT_EXT, // flags
VK_SHADER_STAGE_COMPUTE_BIT, // stage
*computeShader, // module
"main", // pName
&specInfo2, // pSpecializationInfo
};
const VkComputePipelineCreateInfo pipelineCreateInfo =
{
VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, // sType
DE_NULL, // pNext
0u, // flags
shaderStageCreateInfo, // stage
*computePipelineLayout, // layout
(VkPipeline) 0, // basePipelineHandle
0u, // basePipelineIndex
};
const VkComputePipelineCreateInfo pipelineCreateInfo2 =
{
VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, // sType
DE_NULL, // pNext
0u, // flags
shaderStageCreateInfo2, // stage
*computePipelineLayout, // layout
(VkPipeline) 0, // basePipelineHandle
0u, // basePipelineIndex
};
Move<VkPipeline> computePipeline = createComputePipeline(vk, device, (VkPipelineCache) 0u, &pipelineCreateInfo);
Move<VkPipeline> computePipeline2 = createComputePipeline(vk, device, (VkPipelineCache) 0u, &pipelineCreateInfo2);
beginCommandBuffer(vk, *cmdBuffer);
// Clears the values written on the previous iteration.
vk.cmdFillBuffer(*cmdBuffer, *resultBuffer, 0u, VK_WHOLE_SIZE, 0);
const deUint32 zero = 0u;
vk.cmdBindDescriptorSets(*cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, *computePipelineLayout, 0u, 1u, &descriptorSet.get(), 1, &zero);
vk.cmdBindPipeline(*cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, *computePipeline);
vk.cmdDispatch(*cmdBuffer, 1, 1, 1);
const auto barrier = makeBufferMemoryBarrier(VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_WRITE_BIT, *resultBuffer, 0ull, bufferSize);
vk.cmdPipelineBarrier(*cmdBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, (VkDependencyFlags) 0,
0, (const VkMemoryBarrier *) DE_NULL, 1, &barrier, 0, (const VkImageMemoryBarrier *) DE_NULL);
const deUint32 offset = static_cast<deUint32>(maxLocalSize * sizeof(deUint32));
vk.cmdBindDescriptorSets(*cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, *computePipelineLayout, 0u, 1u, &descriptorSet.get(), 1u, &offset);
vk.cmdBindPipeline(*cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, *computePipeline2);
vk.cmdDispatch(*cmdBuffer, 1, 1, 1);
endCommandBuffer(vk, *cmdBuffer);
submitCommandsAndWait(vk, device, queue, *cmdBuffer);
invalidateAlloc(vk, device, *resultBufferMemory);
const deUint32 *res = static_cast<const deUint32 *>(resultBufferMemory->getHostPtr());
deUint32 size = 0;
// Search for the first nonzero size. Then go through the data of both pipelines and check that
// the first nonzero size matches with other nonzero values.
for (deUint32 i = 0; i < maxLocalSize; i++)
{
if (res[i] != 0)
{
size = res[i];
break;
}
}
// Subgroup size is guaranteed to be at least 1.
DE_ASSERT(size > 0);
for (deUint32 i = 0; i < maxLocalSize * 2; i++)
{
if (size != res[i] && res[i] != 0)
return tcu::TestStatus::fail("Subgroup size not uniform in command scope. " + std::to_string(res[i]) + " != " + std::to_string(size));
}
}
}
return tcu::TestStatus::pass("pass");
}
class MultipleDispatchesUniformSubgroupSize : public TestCase
{
public:
MultipleDispatchesUniformSubgroupSize (tcu::TestContext& testCtx,
const std::string& name,
const std::string& description);
void initPrograms (SourceCollections& programCollection) const;
TestInstance* createInstance (Context& context) const;
virtual void checkSupport (Context& context) const;
};
MultipleDispatchesUniformSubgroupSize::MultipleDispatchesUniformSubgroupSize (tcu::TestContext& testCtx,
const std::string& name,
const std::string& description)
: TestCase (testCtx, name, description)
{
}
void MultipleDispatchesUniformSubgroupSize::checkSupport (Context& context) const
{
const VkPhysicalDeviceSubgroupSizeControlFeaturesEXT& subgroupSizeControlFeatures = context.getSubgroupSizeControlFeatures();
if (subgroupSizeControlFeatures.subgroupSizeControl == DE_FALSE)
TCU_THROW(NotSupportedError, "Device does not support varying subgroup sizes");
}
void MultipleDispatchesUniformSubgroupSize::initPrograms (SourceCollections& programCollection) const
{
std::ostringstream computeSrc;
computeSrc
<< glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_450) << "\n"
<< "#extension GL_KHR_shader_subgroup_basic : enable\n"
<< "#extension GL_KHR_shader_subgroup_vote : enable\n"
<< "#extension GL_KHR_shader_subgroup_ballot : enable\n"
<< "layout(std430, binding = 0) buffer Outputs { uint sizes[]; };\n"
<< "layout(local_size_x_id = 0) in;\n"
<< "void main()\n"
<< "{\n"
<< " if (subgroupElect())\n"
<< " {\n"
<< " sizes[gl_WorkGroupID.x * gl_NumSubgroups + gl_SubgroupID] = gl_SubgroupSize;\n"
<< " }\n"
<< "}\n";
programCollection.glslSources.add("comp") << glu::ComputeSource(computeSrc.str())
<< ShaderBuildOptions(programCollection.usedVulkanVersion, SPIRV_VERSION_1_3, 0u);
}
TestInstance* MultipleDispatchesUniformSubgroupSize::createInstance (Context& context) const
{
return new MultipleDispatchesUniformSubgroupSizeInstance(context);
}
} // anonymous ns
tcu::TestCaseGroup* createMultipleDispatchesUniformSubgroupSizeTests (tcu::TestContext& testCtx)
{
de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "multiple_dispatches", "Multiple dispatches uniform subgroup size tests"));
testGroup->addChild(new MultipleDispatchesUniformSubgroupSize(testCtx, "uniform_subgroup_size", ""));
return testGroup.release();
}
} // compute
} // vkt
<commit_msg>Add missing barrier to fix multi-core issue<commit_after>/*------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2021 Google LLC.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief Tests that compute shaders have a subgroup size that is uniform in
* command scope.
*//*--------------------------------------------------------------------*/
#include "deUniquePtr.hpp"
#include "vkRef.hpp"
#include "vkRefUtil.hpp"
#include "vkPrograms.hpp"
#include "vkMemUtil.hpp"
#include "vkBuilderUtil.hpp"
#include "vkCmdUtil.hpp"
#include "vkObjUtil.hpp"
#include "vkTypeUtil.hpp"
#include "vkImageWithMemory.hpp"
#include "vkBarrierUtil.hpp"
#include "vktTestCaseUtil.hpp"
using namespace vk;
namespace vkt
{
namespace subgroups
{
namespace
{
using std::vector;
using de::MovePtr;
class MultipleDispatchesUniformSubgroupSizeInstance : public TestInstance
{
public:
MultipleDispatchesUniformSubgroupSizeInstance (Context& context);
tcu::TestStatus iterate (void);
};
MultipleDispatchesUniformSubgroupSizeInstance::MultipleDispatchesUniformSubgroupSizeInstance (Context& context)
:TestInstance (context)
{
}
tcu::TestStatus MultipleDispatchesUniformSubgroupSizeInstance::iterate (void)
{
const DeviceInterface& vk = m_context.getDeviceInterface();
const VkDevice device = m_context.getDevice();
Allocator& allocator = m_context.getDefaultAllocator();
const VkQueue queue = m_context.getUniversalQueue();
const deUint32 queueFamilyIndex = m_context.getUniversalQueueFamilyIndex();
const Move<VkCommandPool> cmdPool = createCommandPool(vk, device, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, queueFamilyIndex);
const Move<VkCommandBuffer> cmdBuffer = allocateCommandBuffer(vk, device, *cmdPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY);
Move<VkShaderModule> computeShader = createShaderModule (vk, device, m_context.getBinaryCollection().get("comp"), 0u);
// The number of invocations in a workgroup.
const deUint32 maxLocalSize = m_context.getDeviceProperties().limits.maxComputeWorkGroupSize[0];
// Create a storage buffer to hold the sizes of subgroups.
const VkDeviceSize bufferSize = maxLocalSize * 2 * sizeof(deUint32);
const VkBufferCreateInfo resultBufferCreateInfo = makeBufferCreateInfo(bufferSize, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
Move<VkBuffer> resultBuffer = createBuffer(vk, device, &resultBufferCreateInfo);
MovePtr<Allocation> resultBufferMemory = allocator.allocate(getBufferMemoryRequirements(vk, device, *resultBuffer), MemoryRequirement::HostVisible);
VK_CHECK(vk.bindBufferMemory(device, *resultBuffer, resultBufferMemory->getMemory(), resultBufferMemory->getOffset()));
// Build descriptors for the storage buffer
const Unique<VkDescriptorPool> descriptorPool (DescriptorPoolBuilder().addType(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC)
.build(vk, device, VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, 1u));
const auto descriptorSetLayout1 (DescriptorSetLayoutBuilder().addSingleBinding(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, VK_SHADER_STAGE_COMPUTE_BIT)
.build(vk, device));
const VkDescriptorBufferInfo resultInfo = makeDescriptorBufferInfo(*resultBuffer, 0u,
(VkDeviceSize) bufferSize - maxLocalSize * sizeof(deUint32));
const VkDescriptorSetAllocateInfo allocInfo =
{
VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, // sType
DE_NULL, // pNext
*descriptorPool, // descriptorPool
1u, // descriptorSetCount
&(*descriptorSetLayout1) // pSetLayouts
};
Move<VkDescriptorSet> descriptorSet = allocateDescriptorSet(vk, device, &allocInfo);
DescriptorSetUpdateBuilder builder;
builder.writeSingle(*descriptorSet, DescriptorSetUpdateBuilder::Location::binding(0u), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, &resultInfo);
builder.update(vk, device);
// Compute pipeline
const Move<VkPipelineLayout> computePipelineLayout = makePipelineLayout (vk, device, *descriptorSetLayout1);
for (deUint32 localSize1 = 8; localSize1 < maxLocalSize + 1; localSize1 *= 2)
{
for (deUint32 localSize2 = 8; localSize2 < maxLocalSize + 1; localSize2 *= 2)
{
// On each iteration, change the number of invocations which might affect
// the subgroup size if the driver doesn't behave as expected.
const VkSpecializationMapEntry entries =
{
0u, // deUint32 constantID;
0u, // deUint32 offset;
sizeof(localSize1) // size_t size;
};
const VkSpecializationInfo specInfo =
{
1, // mapEntryCount
&entries, // pMapEntries
sizeof(localSize1), // dataSize
&localSize1 // pData
};
const VkSpecializationInfo specInfo2 =
{
1, // mapEntryCount
&entries, // pMapEntries
sizeof(localSize2), // dataSize
&localSize2 // pData
};
const VkPipelineShaderStageCreateInfo shaderStageCreateInfo =
{
VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, // sType
DE_NULL, // pNext
VK_PIPELINE_SHADER_STAGE_CREATE_ALLOW_VARYING_SUBGROUP_SIZE_BIT_EXT, // flags
VK_SHADER_STAGE_COMPUTE_BIT, // stage
*computeShader, // module
"main", // pName
&specInfo, // pSpecializationInfo
};
const VkPipelineShaderStageCreateInfo shaderStageCreateInfo2 =
{
VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, // sType
DE_NULL, // pNext
VK_PIPELINE_SHADER_STAGE_CREATE_ALLOW_VARYING_SUBGROUP_SIZE_BIT_EXT, // flags
VK_SHADER_STAGE_COMPUTE_BIT, // stage
*computeShader, // module
"main", // pName
&specInfo2, // pSpecializationInfo
};
const VkComputePipelineCreateInfo pipelineCreateInfo =
{
VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, // sType
DE_NULL, // pNext
0u, // flags
shaderStageCreateInfo, // stage
*computePipelineLayout, // layout
(VkPipeline) 0, // basePipelineHandle
0u, // basePipelineIndex
};
const VkComputePipelineCreateInfo pipelineCreateInfo2 =
{
VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, // sType
DE_NULL, // pNext
0u, // flags
shaderStageCreateInfo2, // stage
*computePipelineLayout, // layout
(VkPipeline) 0, // basePipelineHandle
0u, // basePipelineIndex
};
Move<VkPipeline> computePipeline = createComputePipeline(vk, device, (VkPipelineCache) 0u, &pipelineCreateInfo);
Move<VkPipeline> computePipeline2 = createComputePipeline(vk, device, (VkPipelineCache) 0u, &pipelineCreateInfo2);
beginCommandBuffer(vk, *cmdBuffer);
// Clears the values written on the previous iteration.
vk.cmdFillBuffer(*cmdBuffer, *resultBuffer, 0u, VK_WHOLE_SIZE, 0);
const auto fillBarrier = makeBufferMemoryBarrier(VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_WRITE_BIT, *resultBuffer, 0ull, bufferSize);
vk.cmdPipelineBarrier(*cmdBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, (VkDependencyFlags) 0,
0, (const VkMemoryBarrier *) DE_NULL, 1, &fillBarrier, 0, (const VkImageMemoryBarrier *) DE_NULL);
const deUint32 zero = 0u;
vk.cmdBindDescriptorSets(*cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, *computePipelineLayout, 0u, 1u, &descriptorSet.get(), 1, &zero);
vk.cmdBindPipeline(*cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, *computePipeline);
vk.cmdDispatch(*cmdBuffer, 1, 1, 1);
const auto barrier = makeBufferMemoryBarrier(VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_WRITE_BIT, *resultBuffer, 0ull, bufferSize);
vk.cmdPipelineBarrier(*cmdBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, (VkDependencyFlags) 0,
0, (const VkMemoryBarrier *) DE_NULL, 1, &barrier, 0, (const VkImageMemoryBarrier *) DE_NULL);
const deUint32 offset = static_cast<deUint32>(maxLocalSize * sizeof(deUint32));
vk.cmdBindDescriptorSets(*cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, *computePipelineLayout, 0u, 1u, &descriptorSet.get(), 1u, &offset);
vk.cmdBindPipeline(*cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, *computePipeline2);
vk.cmdDispatch(*cmdBuffer, 1, 1, 1);
endCommandBuffer(vk, *cmdBuffer);
submitCommandsAndWait(vk, device, queue, *cmdBuffer);
invalidateAlloc(vk, device, *resultBufferMemory);
const deUint32 *res = static_cast<const deUint32 *>(resultBufferMemory->getHostPtr());
deUint32 size = 0;
// Search for the first nonzero size. Then go through the data of both pipelines and check that
// the first nonzero size matches with other nonzero values.
for (deUint32 i = 0; i < maxLocalSize; i++)
{
if (res[i] != 0)
{
size = res[i];
break;
}
}
// Subgroup size is guaranteed to be at least 1.
DE_ASSERT(size > 0);
for (deUint32 i = 0; i < maxLocalSize * 2; i++)
{
if (size != res[i] && res[i] != 0)
return tcu::TestStatus::fail("Subgroup size not uniform in command scope. " + std::to_string(res[i]) + " != " + std::to_string(size));
}
}
}
return tcu::TestStatus::pass("pass");
}
class MultipleDispatchesUniformSubgroupSize : public TestCase
{
public:
MultipleDispatchesUniformSubgroupSize (tcu::TestContext& testCtx,
const std::string& name,
const std::string& description);
void initPrograms (SourceCollections& programCollection) const;
TestInstance* createInstance (Context& context) const;
virtual void checkSupport (Context& context) const;
};
MultipleDispatchesUniformSubgroupSize::MultipleDispatchesUniformSubgroupSize (tcu::TestContext& testCtx,
const std::string& name,
const std::string& description)
: TestCase (testCtx, name, description)
{
}
void MultipleDispatchesUniformSubgroupSize::checkSupport (Context& context) const
{
const VkPhysicalDeviceSubgroupSizeControlFeaturesEXT& subgroupSizeControlFeatures = context.getSubgroupSizeControlFeatures();
if (subgroupSizeControlFeatures.subgroupSizeControl == DE_FALSE)
TCU_THROW(NotSupportedError, "Device does not support varying subgroup sizes");
}
void MultipleDispatchesUniformSubgroupSize::initPrograms (SourceCollections& programCollection) const
{
std::ostringstream computeSrc;
computeSrc
<< glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_450) << "\n"
<< "#extension GL_KHR_shader_subgroup_basic : enable\n"
<< "#extension GL_KHR_shader_subgroup_vote : enable\n"
<< "#extension GL_KHR_shader_subgroup_ballot : enable\n"
<< "layout(std430, binding = 0) buffer Outputs { uint sizes[]; };\n"
<< "layout(local_size_x_id = 0) in;\n"
<< "void main()\n"
<< "{\n"
<< " if (subgroupElect())\n"
<< " {\n"
<< " sizes[gl_WorkGroupID.x * gl_NumSubgroups + gl_SubgroupID] = gl_SubgroupSize;\n"
<< " }\n"
<< "}\n";
programCollection.glslSources.add("comp") << glu::ComputeSource(computeSrc.str())
<< ShaderBuildOptions(programCollection.usedVulkanVersion, SPIRV_VERSION_1_3, 0u);
}
TestInstance* MultipleDispatchesUniformSubgroupSize::createInstance (Context& context) const
{
return new MultipleDispatchesUniformSubgroupSizeInstance(context);
}
} // anonymous ns
tcu::TestCaseGroup* createMultipleDispatchesUniformSubgroupSizeTests (tcu::TestContext& testCtx)
{
de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "multiple_dispatches", "Multiple dispatches uniform subgroup size tests"));
testGroup->addChild(new MultipleDispatchesUniformSubgroupSize(testCtx, "uniform_subgroup_size", ""));
return testGroup.release();
}
} // compute
} // vkt
<|endoftext|> |
<commit_before>/**
* @file linear_regression.cpp
* @author James Cline
*
* Implementation of simple linear regression.
*/
#include "linear_regression.hpp"
using namespace mlpack;
using namespace mlpack::regression;
LinearRegression::LinearRegression(arma::mat& predictors,
const arma::colvec& responses)
{
/*
* We want to calculate the a_i coefficients of:
* \sum_{i=0}^n (a_i * x_i^i)
* In order to get the intercept value, we will add a row of ones.
*/
// We store the number of rows of the predictors.
// Reminder: Armadillo stores the data transposed from how we think of it,
// that is, columns are actually rows (see: column major order).
size_t nCols = predictors.n_cols;
// Here we add the row of ones to the predictors.
arma::rowvec ones;
ones.ones(nCols);
predictors.insert_rows(0, ones);
// We set the parameters to the correct size and initialize them to zero.
parameters.zeros(nCols);
// We compute the QR decomposition of the predictors.
// We transpose the predictors because they are in column major order.
arma::mat Q, R;
arma::qr(Q, R, arma::trans(predictors));
// We compute the parameters, B, like so:
// R * B = Q^T * responses
// B = Q^T * responses * R^-1
arma::solve(parameters, R, arma::trans(Q) * responses);
// We now remove the row of ones we added so the user's data is unmodified.
predictors.shed_row(0);
}
LinearRegression::LinearRegression(const std::string& filename)
{
data::Load(filename, parameters, true);
}
LinearRegression::LinearRegression(const LinearRegression& linearRegression)
{
parameters = linearRegression.parameters;
}
void LinearRegression::Predict(const arma::mat& points, arma::vec& predictions)
{
// We get the number of columns and rows of the dataset.
const size_t nCols = points.n_cols;
const size_t nRows = points.n_rows;
// We want to be sure we have the correct number of dimensions in the dataset.
Log::Assert(points.n_rows == parameters.n_rows - 1);
// Get the predictions, but this ignores the intercept value (parameters[0]).
predictions = arma::trans(arma::trans(
parameters.subvec(1, parameters.n_elem - 1)) * points);
// Now add the intercept.
predictions += parameters(0);
}
//! Compute the L2 squared error on the given predictors and responses.
double LinearRegression::ComputeError(const arma::mat& predictors,
const arma::vec& responses) const
{
// Get the number of columns and rows of the dataset.
const size_t nCols = predictors.n_cols;
const size_t nRows = predictors.n_rows;
// Ensure that we have the correct number of dimensions in the dataset.
if (nRows != parameters.n_rows - 1)
{
Log::Fatal << "The test data must have the same number of columns as the "
"training file." << std::endl;
}
// Calculate the differences between actual responses and predicted responses.
// We must also add the intercept (parameters(0)) to the predictions.
arma::vec temp = responses - arma::trans(
(arma::trans(parameters.subvec(1, parameters.n_elem - 1)) * predictors) +
parameters(0));
const double cost = arma::dot(temp, temp) / nCols;
return cost;
}
<commit_msg>Fix warning, add const.<commit_after>/**
* @file linear_regression.cpp
* @author James Cline
*
* Implementation of simple linear regression.
*/
#include "linear_regression.hpp"
using namespace mlpack;
using namespace mlpack::regression;
LinearRegression::LinearRegression(arma::mat& predictors,
const arma::colvec& responses)
{
/*
* We want to calculate the a_i coefficients of:
* \sum_{i=0}^n (a_i * x_i^i)
* In order to get the intercept value, we will add a row of ones.
*/
// We store the number of rows of the predictors.
// Reminder: Armadillo stores the data transposed from how we think of it,
// that is, columns are actually rows (see: column major order).
const size_t nCols = predictors.n_cols;
// Here we add the row of ones to the predictors.
arma::rowvec ones;
ones.ones(nCols);
predictors.insert_rows(0, ones);
// We set the parameters to the correct size and initialize them to zero.
parameters.zeros(nCols);
// We compute the QR decomposition of the predictors.
// We transpose the predictors because they are in column major order.
arma::mat Q, R;
arma::qr(Q, R, arma::trans(predictors));
// We compute the parameters, B, like so:
// R * B = Q^T * responses
// B = Q^T * responses * R^-1
arma::solve(parameters, R, arma::trans(Q) * responses);
// We now remove the row of ones we added so the user's data is unmodified.
predictors.shed_row(0);
}
LinearRegression::LinearRegression(const std::string& filename)
{
data::Load(filename, parameters, true);
}
LinearRegression::LinearRegression(const LinearRegression& linearRegression)
{
parameters = linearRegression.parameters;
}
void LinearRegression::Predict(const arma::mat& points, arma::vec& predictions)
{
// We want to be sure we have the correct number of dimensions in the dataset.
Log::Assert(points.n_rows == parameters.n_rows - 1);
// Get the predictions, but this ignores the intercept value (parameters[0]).
predictions = arma::trans(arma::trans(
parameters.subvec(1, parameters.n_elem - 1)) * points);
// Now add the intercept.
predictions += parameters(0);
}
//! Compute the L2 squared error on the given predictors and responses.
double LinearRegression::ComputeError(const arma::mat& predictors,
const arma::vec& responses) const
{
// Get the number of columns and rows of the dataset.
const size_t nCols = predictors.n_cols;
const size_t nRows = predictors.n_rows;
// Ensure that we have the correct number of dimensions in the dataset.
if (nRows != parameters.n_rows - 1)
{
Log::Fatal << "The test data must have the same number of columns as the "
"training file." << std::endl;
}
// Calculate the differences between actual responses and predicted responses.
// We must also add the intercept (parameters(0)) to the predictions.
arma::vec temp = responses - arma::trans(
(arma::trans(parameters.subvec(1, parameters.n_elem - 1)) * predictors) +
parameters(0));
const double cost = arma::dot(temp, temp) / nCols;
return cost;
}
<|endoftext|> |
<commit_before>/*
irccontact.cpp - IRC Contact
Copyright (c) 2002 by Nick Betcher <[email protected]>
Kopete (c) 2002 by the Kopete developers <[email protected]>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <kdebug.h>
#include <klocale.h>
#include <qregexp.h>
#include <qtimer.h>
#include <qtextcodec.h>
#include "ircaccount.h"
#include "kopetemetacontact.h"
#include "kopeteview.h"
#include "ircusercontact.h"
#include "irccontact.h"
#include "ircprotocol.h"
#include "ircservercontact.h"
#include "irccontactmanager.h"
#include "ksparser.h"
IRCContact::IRCContact(IRCContactManager *contactManager, const QString &nick, KopeteMetaContact *metac, const QString& icon)
: KopeteContact(contactManager->account(), nick, metac, icon),
m_protocol(static_cast<IRCProtocol *>(protocol())),
m_account(contactManager->account()),
m_engine(contactManager->engine()),
m_metaContact(metac),
m_nickName(nick),
m_msgManager(0L),
m_isConnected(false)
{
// Contact list display name
setDisplayName(m_nickName);
// IRCContactManager stuff
QObject::connect(contactManager, SIGNAL(privateMessage(IRCContact *, IRCContact *, const QString &)),
this, SLOT(privateMessage(IRCContact *, IRCContact *, const QString &)));
QObject::connect(contactManager, SIGNAL(action(IRCContact *, IRCContact *, const QString &)),
this, SLOT(action(IRCContact *, IRCContact *, const QString &)));
// KopeteMessageManagerFactory stuff
mMyself.append( static_cast<KopeteContact*>( this ) );
// KIRC stuff
QObject::connect(m_engine, SIGNAL(incomingNickChange(const QString &, const QString &)),
this, SLOT( slotNewNickChange(const QString&, const QString&)));
QObject::connect(m_engine, SIGNAL(successfullyChangedNick(const QString &, const QString &)),
this, SLOT(slotNewNickChange(const QString &, const QString &)));
QObject::connect(m_engine, SIGNAL(incomingQuitIRC(const QString &, const QString &)),
this, SLOT( slotUserDisconnected(const QString&, const QString&)));
QObject::connect(m_engine, SIGNAL(statusChanged(KIRC::EngineStatus)),
this, SLOT(updateStatus()));
m_engine->setCodec( m_nickName, codec() );
}
IRCContact::~IRCContact()
{
// kdDebug(14120) << k_funcinfo << mNickName << endl;
if(metaContact() && metaContact()->isTemporary() && !isChatting())
metaContact()->deleteLater();
}
bool IRCContact::isReachable()
{
if ( onlineStatus().status() != KopeteOnlineStatus::Offline && onlineStatus().status() != KopeteOnlineStatus::Unknown )
return true;
return false;
}
void IRCContact::privateMessage(IRCContact *, IRCContact *, const QString &)
{
}
void IRCContact::action(IRCContact *, IRCContact *, const QString &)
{
}
void IRCContact::setCodec( const QTextCodec *codec )
{
m_engine->setCodec( m_nickName, codec );
metaContact()->setPluginData( m_protocol, QString::fromLatin1("Codec"), QString::number(codec->mibEnum()) );
}
const QTextCodec *IRCContact::codec()
{
QString codecId = metaContact()->pluginData( m_protocol, QString::fromLatin1("Codec") );
QTextCodec *codec = m_account->codec();
if( !codecId.isEmpty() )
{
bool test = true;
uint mib = codecId.toInt(&test);
if( test )
codec = QTextCodec::codecForMib( mib );
else
codec = QTextCodec::codecForName( codecId.latin1() );
}
if( !codec )
return m_engine->codec();
return codec;
}
KopeteMessageManager *IRCContact::manager(bool canCreate)
{
if( canCreate && !m_msgManager )
{
if(m_engine->status() == KIRC::Disconnected)
m_account->connect();
m_msgManager = KopeteMessageManagerFactory::factory()->create( m_account->myself(), mMyself, m_account->protocol());
m_msgManager->setDisplayName(caption());
m_isConnected = true;
QObject::connect( m_msgManager, SIGNAL(messageSent(KopeteMessage&, KopeteMessageManager *)),
this, SLOT(slotSendMsg(KopeteMessage&, KopeteMessageManager *)));
QObject::connect( m_msgManager, SIGNAL(closing(KopeteMessageManager*)),
this, SLOT(messageManagerDestroyed()));
QTimer::singleShot( 0, this, SLOT( initConversation() ) );
}
return m_msgManager;
}
void IRCContact::messageManagerDestroyed()
{
m_msgManager = 0L;
m_isConnected = false;
if( metaContact()->isTemporary() && !isChatting() )
deleteLater();
}
void IRCContact::slotUserDisconnected(const QString &user, const QString &reason)
{
if( m_isConnected )
{
QString nickname = user.section('!', 0, 0);
KopeteContact *c = locateUser( nickname );
if ( c )
{
manager()->removeContact( c, i18n("Quit: \"%1\" ").arg(reason) );
c->setOnlineStatus( m_protocol->m_UserStatusOffline );
}
}
}
void IRCContact::slotNewNickChange(const QString &oldnickname, const QString &newnickname)
{
//kdDebug(14120) << k_funcinfo << oldnickname << " >> " << newnickname << ", " << m_nickName << endl;
IRCContact *user = static_cast<IRCContact*>( locateUser(oldnickname) );
if( user )
{
user->setNickName( newnickname );
//If tracking name changes....
user->setDisplayName( newnickname );
//If the user is in our contact list, then change the notify list nickname
if( !user->metaContact()->isTemporary() )
{
m_account->contactManager()->removeFromNotifyList( oldnickname );
m_account->contactManager()->addToNotifyList( newnickname );
}
}
}
void IRCContact::slotSendMsg(KopeteMessage &message, KopeteMessageManager *)
{
QString htmlString = message.escapedBody();
if( htmlString.find( QString::fromLatin1("</span") ) > -1 )
{
QRegExp findTags( QString::fromLatin1("<span style=\"(.*)\">(.*)</span>") );
findTags.setMinimal( true );
int pos = 0;
while ( pos >= 0 )
{
pos = findTags.search( htmlString );
if ( pos > -1 )
{
QString styleHTML = findTags.cap(1);
QString replacement = findTags.cap(2);
QStringList styleAttrs = QStringList::split( ';', styleHTML );
for( QStringList::Iterator attrPair = styleAttrs.begin(); attrPair != styleAttrs.end(); ++attrPair )
{
QString attribute = (*attrPair).section(':',0,0);
QString value = (*attrPair).section(':',1);
if( attribute == QString::fromLatin1("color") )
{
int ircColor = KSParser::colorForHTML( value );
if( ircColor > -1 )
replacement.prepend( QString( QChar(0x03) ).append( QString::number(ircColor) ) ).append( QChar( 0x03 ) );
}
else if( attribute == QString::fromLatin1("font-weight") && value == QString::fromLatin1("600") )
replacement.prepend( QChar(0x02) ).append( QChar(0x02) );
else if( attribute == QString::fromLatin1("text-decoration") && value == QString::fromLatin1("underline") )
replacement.prepend( QChar(31) ).append( QChar(31) );
}
QRegExp rx( QString::fromLatin1("<span style=\"%1\">.*</span>" ).arg( styleHTML ) );
rx.setMinimal( true );
htmlString.replace( rx, replacement );
}
}
}
htmlString = KopeteMessage::unescape( htmlString );
if( htmlString.find( '\n' ) > -1 )
{
QStringList messages = QStringList::split( '\n', htmlString );
for( QStringList::Iterator it = messages.begin(); it != messages.end(); ++it )
{
KopeteMessage msg(message.from(), message.to(), *it, message.direction(),
KopeteMessage::RichText, message.type() );
m_engine->messageContact(m_nickName, *it );
msg.setBg( QColor() );
msg.setFg( QColor() );
appendMessage(msg);
manager()->messageSucceeded();
}
}
else
{
m_engine->messageContact(m_nickName, htmlString );
message.setBg( QColor() );
message.setFg( QColor() );
appendMessage(message);
manager()->messageSucceeded();
}
}
KopeteContact *IRCContact::locateUser( const QString &nick )
{
//kdDebug(14120) << k_funcinfo << "Find nick " << nick << endl;
if( m_isConnected )
{
if( nick == m_account->mySelf()->nickName() )
return m_account->mySelf();
else
{
KopeteContactPtrList mMembers = manager()->members();
for( KopeteContact *it = mMembers.first(); it; it = mMembers.next() )
{
if( static_cast<IRCContact*>(it)->nickName() == nick )
return it;
}
}
}
return 0L;
}
bool IRCContact::isChatting( KopeteMessageManager *avoid ) const
{
QIntDict<KopeteMessageManager> sessions = KopeteMessageManagerFactory::factory()->sessions();
for ( QIntDictIterator<KopeteMessageManager> it( sessions ); it.current() ; ++it )
{
if( it.current() != avoid && it.current()->account() == m_account &&
it.current()->members().contains(this) )
{
return true;
}
}
return false;
}
void IRCContact::slotDeleteContact()
{
kdDebug(14120) << k_funcinfo << m_nickName << endl;
if( !isChatting() )
{
kdDebug(14120) << k_funcinfo << "will delete " << m_nickName << endl;
KopeteContact::slotDeleteContact();
}
}
void IRCContact::appendMessage( KopeteMessage &msg )
{
manager()->appendMessage(msg);
}
KopeteView *IRCContact::view()
{
if( m_msgManager )
return manager()->view(false);
return 0L;
}
#include "irccontact.moc"
<commit_msg>Fix crash bug when deleting a user you're chatting with<commit_after>/*
irccontact.cpp - IRC Contact
Copyright (c) 2002 by Nick Betcher <[email protected]>
Kopete (c) 2002 by the Kopete developers <[email protected]>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <kdebug.h>
#include <klocale.h>
#include <qregexp.h>
#include <qtimer.h>
#include <qtextcodec.h>
#include "ircaccount.h"
#include "kopetemetacontact.h"
#include "kopeteview.h"
#include "ircusercontact.h"
#include "irccontact.h"
#include "ircprotocol.h"
#include "ircservercontact.h"
#include "irccontactmanager.h"
#include "ksparser.h"
IRCContact::IRCContact(IRCContactManager *contactManager, const QString &nick, KopeteMetaContact *metac, const QString& icon)
: KopeteContact(contactManager->account(), nick, metac, icon),
m_protocol(static_cast<IRCProtocol *>(protocol())),
m_account(contactManager->account()),
m_engine(contactManager->engine()),
m_metaContact(metac),
m_nickName(nick),
m_msgManager(0L),
m_isConnected(false)
{
// Contact list display name
setDisplayName(m_nickName);
// IRCContactManager stuff
QObject::connect(contactManager, SIGNAL(privateMessage(IRCContact *, IRCContact *, const QString &)),
this, SLOT(privateMessage(IRCContact *, IRCContact *, const QString &)));
QObject::connect(contactManager, SIGNAL(action(IRCContact *, IRCContact *, const QString &)),
this, SLOT(action(IRCContact *, IRCContact *, const QString &)));
// KopeteMessageManagerFactory stuff
mMyself.append( static_cast<KopeteContact*>( this ) );
// KIRC stuff
QObject::connect(m_engine, SIGNAL(incomingNickChange(const QString &, const QString &)),
this, SLOT( slotNewNickChange(const QString&, const QString&)));
QObject::connect(m_engine, SIGNAL(successfullyChangedNick(const QString &, const QString &)),
this, SLOT(slotNewNickChange(const QString &, const QString &)));
QObject::connect(m_engine, SIGNAL(incomingQuitIRC(const QString &, const QString &)),
this, SLOT( slotUserDisconnected(const QString&, const QString&)));
QObject::connect(m_engine, SIGNAL(statusChanged(KIRC::EngineStatus)),
this, SLOT(updateStatus()));
m_engine->setCodec( m_nickName, codec() );
}
IRCContact::~IRCContact()
{
// kdDebug(14120) << k_funcinfo << mNickName << endl;
if(metaContact() && metaContact()->isTemporary() && !isChatting())
metaContact()->deleteLater();
}
bool IRCContact::isReachable()
{
if ( onlineStatus().status() != KopeteOnlineStatus::Offline && onlineStatus().status() != KopeteOnlineStatus::Unknown )
return true;
return false;
}
void IRCContact::privateMessage(IRCContact *, IRCContact *, const QString &)
{
}
void IRCContact::action(IRCContact *, IRCContact *, const QString &)
{
}
void IRCContact::setCodec( const QTextCodec *codec )
{
m_engine->setCodec( m_nickName, codec );
metaContact()->setPluginData( m_protocol, QString::fromLatin1("Codec"), QString::number(codec->mibEnum()) );
}
const QTextCodec *IRCContact::codec()
{
QString codecId = metaContact()->pluginData( m_protocol, QString::fromLatin1("Codec") );
QTextCodec *codec = m_account->codec();
if( !codecId.isEmpty() )
{
bool test = true;
uint mib = codecId.toInt(&test);
if( test )
codec = QTextCodec::codecForMib( mib );
else
codec = QTextCodec::codecForName( codecId.latin1() );
}
if( !codec )
return m_engine->codec();
return codec;
}
KopeteMessageManager *IRCContact::manager(bool canCreate)
{
if( canCreate && !m_msgManager )
{
if(m_engine->status() == KIRC::Disconnected)
m_account->connect();
m_msgManager = KopeteMessageManagerFactory::factory()->create( m_account->myself(), mMyself, m_account->protocol());
m_msgManager->setDisplayName(caption());
m_isConnected = true;
QObject::connect( m_msgManager, SIGNAL(messageSent(KopeteMessage&, KopeteMessageManager *)),
this, SLOT(slotSendMsg(KopeteMessage&, KopeteMessageManager *)));
QObject::connect( m_msgManager, SIGNAL(closing(KopeteMessageManager*)),
this, SLOT(messageManagerDestroyed()));
QTimer::singleShot( 0, this, SLOT( initConversation() ) );
}
return m_msgManager;
}
void IRCContact::messageManagerDestroyed()
{
m_msgManager = 0L;
m_isConnected = false;
if( metaContact()->isTemporary() && !isChatting() )
deleteLater();
}
void IRCContact::slotUserDisconnected(const QString &user, const QString &reason)
{
if( m_isConnected )
{
QString nickname = user.section('!', 0, 0);
KopeteContact *c = locateUser( nickname );
if ( c )
{
manager()->removeContact( c, i18n("Quit: \"%1\" ").arg(reason) );
c->setOnlineStatus( m_protocol->m_UserStatusOffline );
}
}
}
void IRCContact::slotNewNickChange(const QString &oldnickname, const QString &newnickname)
{
//kdDebug(14120) << k_funcinfo << oldnickname << " >> " << newnickname << ", " << m_nickName << endl;
IRCContact *user = static_cast<IRCContact*>( locateUser(oldnickname) );
if( user )
{
user->setNickName( newnickname );
//If tracking name changes....
user->setDisplayName( newnickname );
//If the user is in our contact list, then change the notify list nickname
if( !user->metaContact()->isTemporary() )
{
m_account->contactManager()->removeFromNotifyList( oldnickname );
m_account->contactManager()->addToNotifyList( newnickname );
}
}
}
void IRCContact::slotSendMsg(KopeteMessage &message, KopeteMessageManager *)
{
QString htmlString = message.escapedBody();
if( htmlString.find( QString::fromLatin1("</span") ) > -1 )
{
QRegExp findTags( QString::fromLatin1("<span style=\"(.*)\">(.*)</span>") );
findTags.setMinimal( true );
int pos = 0;
while ( pos >= 0 )
{
pos = findTags.search( htmlString );
if ( pos > -1 )
{
QString styleHTML = findTags.cap(1);
QString replacement = findTags.cap(2);
QStringList styleAttrs = QStringList::split( ';', styleHTML );
for( QStringList::Iterator attrPair = styleAttrs.begin(); attrPair != styleAttrs.end(); ++attrPair )
{
QString attribute = (*attrPair).section(':',0,0);
QString value = (*attrPair).section(':',1);
if( attribute == QString::fromLatin1("color") )
{
int ircColor = KSParser::colorForHTML( value );
if( ircColor > -1 )
replacement.prepend( QString( QChar(0x03) ).append( QString::number(ircColor) ) ).append( QChar( 0x03 ) );
}
else if( attribute == QString::fromLatin1("font-weight") && value == QString::fromLatin1("600") )
replacement.prepend( QChar(0x02) ).append( QChar(0x02) );
else if( attribute == QString::fromLatin1("text-decoration") && value == QString::fromLatin1("underline") )
replacement.prepend( QChar(31) ).append( QChar(31) );
}
QRegExp rx( QString::fromLatin1("<span style=\"%1\">.*</span>" ).arg( styleHTML ) );
rx.setMinimal( true );
htmlString.replace( rx, replacement );
}
}
}
htmlString = KopeteMessage::unescape( htmlString );
if( htmlString.find( '\n' ) > -1 )
{
QStringList messages = QStringList::split( '\n', htmlString );
for( QStringList::Iterator it = messages.begin(); it != messages.end(); ++it )
{
KopeteMessage msg(message.from(), message.to(), *it, message.direction(),
KopeteMessage::RichText, message.type() );
m_engine->messageContact(m_nickName, *it );
msg.setBg( QColor() );
msg.setFg( QColor() );
appendMessage(msg);
manager()->messageSucceeded();
}
}
else
{
m_engine->messageContact(m_nickName, htmlString );
message.setBg( QColor() );
message.setFg( QColor() );
appendMessage(message);
manager()->messageSucceeded();
}
}
KopeteContact *IRCContact::locateUser( const QString &nick )
{
//kdDebug(14120) << k_funcinfo << "Find nick " << nick << endl;
if( m_isConnected )
{
if( nick == m_account->mySelf()->nickName() )
return m_account->mySelf();
else
{
KopeteContactPtrList mMembers = manager()->members();
for( KopeteContact *it = mMembers.first(); it; it = mMembers.next() )
{
if( static_cast<IRCContact*>(it)->nickName() == nick )
return it;
}
}
}
return 0L;
}
bool IRCContact::isChatting( KopeteMessageManager *avoid ) const
{
QIntDict<KopeteMessageManager> sessions = KopeteMessageManagerFactory::factory()->sessions();
for ( QIntDictIterator<KopeteMessageManager> it( sessions ); it.current() ; ++it )
{
if( it.current() != avoid && it.current()->account() == m_account &&
it.current()->members().contains(this) )
{
return true;
}
}
return false;
}
void IRCContact::slotDeleteContact()
{
kdDebug(14120) << k_funcinfo << m_nickName << endl;
if( manager(false) )
delete manager();
if( !isChatting() )
{
kdDebug(14120) << k_funcinfo << "will delete " << m_nickName << endl;
KopeteContact::slotDeleteContact();
}
else
{
metaContact()->removeContact( this );
KopeteMetaContact *m = new KopeteMetaContact();
m->setTemporary( true );
setMetaContact( m );
}
}
void IRCContact::appendMessage( KopeteMessage &msg )
{
manager()->appendMessage(msg);
}
KopeteView *IRCContact::view()
{
if( m_msgManager )
return manager()->view(false);
return 0L;
}
#include "irccontact.moc"
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved
*/
#ifndef _Stroika_Foundation_Cache_BloomFilter_inl_
#define _Stroika_Foundation_Cache_BloomFilter_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include <cmath>
#include "../Characters/StringBuilder.h"
#include "../Debug/Assertions.h"
#include "../Execution/Exceptions.h"
#include "../Math/Common.h"
namespace Stroika::Foundation::Cache {
/*
********************************************************************************
********************** Cache::BloomFilter<T>::Statistics ***********************
********************************************************************************
*/
template <typename T>
nonvirtual double BloomFilter<T>::Statistics::GetFractionFull () const
{
return static_cast<double> (fBitsSet) / static_cast<double> (fBitCount);
}
template <typename T>
Characters::String BloomFilter<T>::Statistics::ToString () const
{
Characters::StringBuilder sb;
sb += L"{";
sb += L"fHashFunctions: " + Characters::ToString (fHashFunctions) + L", ";
sb += L"fBitCount: " + Characters::ToString (fBitCount) + L", ";
sb += L"fBitsSet: " + Characters::ToString (fBitsSet);
sb += L"}";
return sb.str ();
}
/*
********************************************************************************
****************************** Cache::BloomFilter ******************************
********************************************************************************
*/
template <typename T>
inline BloomFilter<T>::BloomFilter (const Containers::Sequence<HashFunctionType>& hashFunctions, size_t bitCount)
: fHashFunctions_{hashFunctions.template As<vector<HashFunctionType>> ()}
{
Require (fHashFunctions_.size () >= 1);
Require (bitCount >= 1);
fBits_.resize (bitCount, false);
}
template <typename T>
BloomFilter<T>::BloomFilter (size_t expectedMaxSetSize, const HashFunctionType& defaultHashFunction, double desiredFalsePositivityRate)
{
size_t bitCount = OptimizeBitSize (expectedMaxSetSize, desiredFalsePositivityRate);
size_t hashFunctionCnt = OptimizeNumberOfHashFunctions (expectedMaxSetSize, bitCount);
fBits_.resize (bitCount, false);
fHashFunctions_ = DeriveIndependentHashFunctions (defaultHashFunction, hashFunctionCnt).template As<vector<HashFunctionType>> ();
}
template <typename T>
inline unsigned int BloomFilter<T>::OptimizeBitSize (size_t nElements, double desiredFalsePositiveProbability)
{
// based on https://en.wikipedia.org/wiki/Bloom_filter (approximate)
return static_cast<unsigned int> (::ceil (-static_cast<double> (nElements) * log (desiredFalsePositiveProbability) / log (2) * log (2)));
}
template <typename T>
inline unsigned int BloomFilter<T>::OptimizeNumberOfHashFunctions (size_t setSize, size_t bitSize)
{
// based on https://en.wikipedia.org/wiki/Bloom_filter - (m/n)*ln(2)
return static_cast<unsigned int> (::ceil ((double (bitSize) / setSize) * log (2)));
}
template <typename T>
inline double BloomFilter<T>::ProbabilityOfFalsePositive (size_t hashFunctionCount, size_t bitCount, size_t nElementsInsertedSoFar)
{
// From https://en.wikipedia.org/wiki/Bloom_filter
return ::pow (1 - ::exp (-static_cast<double> (hashFunctionCount * nElementsInsertedSoFar) / bitCount), hashFunctionCount);
}
template <typename T>
inline double BloomFilter<T>::ProbabilityOfFalsePositive (size_t nElementsInsertedSoFar) const
{
return ProbabilityOfFalsePositive (fHashFunctions_.size (), fBits_.size (), nElementsInsertedSoFar);
}
template <typename T>
auto BloomFilter<T>::DeriveIndependentHashFunctions (const HashFunctionType& h, size_t repeatCount) -> Containers::Sequence<HashFunctionType>
{
Require (repeatCount >= 1);
/**
* From https://en.wikipedia.org/wiki/Bloom_filter
*
* The requirement of designing k different independent hash functions can be prohibitive
* for large k. For a good hash function with a wide output, there should be little if any
* correlation between different bit-fields of such a hash, so this type of hash can be
* used to generate multiple "different" hash functions by slicing its output into multiple
* bit fields. Alternatively, one can pass k different initial values (such as 0, 1, ..., k − 1)
* to a hash function that takes an initial value; or add (or append) these values to the key
*
* This trick here - is something similar to the suggestions in the wiki article - deriving
* a hash function by combining a unique seed (by hashing a constant) and combining that with the
* has result of the original function.
*/
Containers::Sequence<HashFunctionType> result{h};
for (size_t i = 1; i < repeatCount; ++i) {
HashResultType seed = Cryptography::Digest::Hash<HashResultType>{}(i);
result += [=] (const T& t) { return Cryptography::Digest::HashValueCombine (h (t), seed); };
}
return result;
}
template <typename T>
void BloomFilter<T>::Add (Configuration::ArgByValueType<T> elt)
{
size_t sz{fBits_.size ()};
for (const HashFunctionType& f : fHashFunctions_) {
auto v = f (elt);
fBits_[v % sz] = true;
}
}
template <typename T>
inline void BloomFilter<T>::clear ()
{
fBits_.clear ();
}
template <typename T>
bool BloomFilter<T>::Contains (Configuration::ArgByValueType<T> elt) const
{
size_t sz{fBits_.size ()};
for (const HashFunctionType& f : fHashFunctions_) {
if (not fBits_[f (elt) % sz]) {
return false;
}
}
return true;
}
template <typename T>
auto BloomFilter<T>::GetStatistics () const -> Statistics
{
size_t nTrue{};
for (bool i : fBits_) {
if (i) {
nTrue++;
}
}
return Statistics{fHashFunctions_.size (), fBits_.size (), nTrue};
}
}
#endif /*_Stroika_Foundation_Cache_BloomFilter_inl_*/
<commit_msg>bloomfilter code cleanup<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved
*/
#ifndef _Stroika_Foundation_Cache_BloomFilter_inl_
#define _Stroika_Foundation_Cache_BloomFilter_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include <cmath>
#include "../Characters/StringBuilder.h"
#include "../Debug/Assertions.h"
#include "../Execution/Exceptions.h"
#include "../Math/Common.h"
namespace Stroika::Foundation::Cache {
/*
********************************************************************************
********************** Cache::BloomFilter<T>::Statistics ***********************
********************************************************************************
*/
template <typename T>
nonvirtual double BloomFilter<T>::Statistics::GetFractionFull () const
{
return static_cast<double> (fBitsSet) / static_cast<double> (fBitCount);
}
template <typename T>
Characters::String BloomFilter<T>::Statistics::ToString () const
{
Characters::StringBuilder sb;
sb += L"{";
sb += L"fHashFunctions: " + Characters::ToString (fHashFunctions) + L", ";
sb += L"fBitCount: " + Characters::ToString (fBitCount) + L", ";
sb += L"fBitsSet: " + Characters::ToString (fBitsSet);
sb += L"}";
return sb.str ();
}
/*
********************************************************************************
****************************** Cache::BloomFilter ******************************
********************************************************************************
*/
template <typename T>
inline BloomFilter<T>::BloomFilter (const Containers::Sequence<HashFunctionType>& hashFunctions, size_t bitCount)
: fHashFunctions_{hashFunctions.template As<vector<HashFunctionType>> ()}
{
Require (fHashFunctions_.size () >= 1);
Require (bitCount >= 1);
fBits_.resize (bitCount, false);
}
template <typename T>
BloomFilter<T>::BloomFilter (size_t expectedMaxSetSize, const HashFunctionType& defaultHashFunction, double desiredFalsePositivityRate)
{
size_t bitCount = OptimizeBitSize (expectedMaxSetSize, desiredFalsePositivityRate);
size_t hashFunctionCnt = OptimizeNumberOfHashFunctions (expectedMaxSetSize, bitCount);
fBits_.resize (bitCount, false);
fHashFunctions_ = DeriveIndependentHashFunctions (defaultHashFunction, hashFunctionCnt).template As<vector<HashFunctionType>> ();
}
template <typename T>
inline unsigned int BloomFilter<T>::OptimizeBitSize (size_t nElements, double desiredFalsePositiveProbability)
{
// based on https://en.wikipedia.org/wiki/Bloom_filter (approximate)
return static_cast<unsigned int> (::ceil (-static_cast<double> (nElements) * log (desiredFalsePositiveProbability) / log (2) * log (2)));
}
template <typename T>
inline unsigned int BloomFilter<T>::OptimizeNumberOfHashFunctions (size_t setSize, size_t bitSize)
{
// based on https://en.wikipedia.org/wiki/Bloom_filter - (m/n)*ln(2)
return static_cast<unsigned int> (::ceil ((double (bitSize) / setSize) * log (2)));
}
template <typename T>
inline double BloomFilter<T>::ProbabilityOfFalsePositive (size_t hashFunctionCount, size_t bitCount, size_t nElementsInsertedSoFar)
{
// From https://en.wikipedia.org/wiki/Bloom_filter
return ::pow (1 - ::exp (-static_cast<double> (hashFunctionCount * nElementsInsertedSoFar) / bitCount), hashFunctionCount);
}
template <typename T>
inline double BloomFilter<T>::ProbabilityOfFalsePositive (size_t nElementsInsertedSoFar) const
{
return ProbabilityOfFalsePositive (fHashFunctions_.size (), fBits_.size (), nElementsInsertedSoFar);
}
template <typename T>
auto BloomFilter<T>::DeriveIndependentHashFunctions (const HashFunctionType& h, size_t repeatCount) -> Containers::Sequence<HashFunctionType>
{
Require (repeatCount >= 1);
/**
* From https://en.wikipedia.org/wiki/Bloom_filter
*
* The requirement of designing k different independent hash functions can be prohibitive
* for large k. For a good hash function with a wide output, there should be little if any
* correlation between different bit-fields of such a hash, so this type of hash can be
* used to generate multiple "different" hash functions by slicing its output into multiple
* bit fields. Alternatively, one can pass k different initial values (such as 0, 1, ..., k − 1)
* to a hash function that takes an initial value; or add (or append) these values to the key
*
* This trick here - is something similar to the suggestions in the wiki article - deriving
* a hash function by combining a unique seed (by hashing a constant) and combining that with the
* has result of the original function.
*/
Containers::Sequence<HashFunctionType> result{h};
for (size_t i = 1; i < repeatCount; ++i) {
HashResultType seed = Cryptography::Digest::Hash<HashResultType>{}(i);
result += [=] (const T& t) { return Cryptography::Digest::HashValueCombine (h (t), seed); };
}
return result;
}
template <typename T>
void BloomFilter<T>::Add (Configuration::ArgByValueType<T> elt)
{
size_t sz{fBits_.size ()};
for (const HashFunctionType& f : fHashFunctions_) {
fBits_[f (elt) % sz] = true;
}
}
template <typename T>
inline void BloomFilter<T>::clear ()
{
fBits_.clear ();
}
template <typename T>
bool BloomFilter<T>::Contains (Configuration::ArgByValueType<T> elt) const
{
size_t sz{fBits_.size ()};
for (const HashFunctionType& f : fHashFunctions_) {
if (not fBits_[f (elt) % sz]) {
return false;
}
}
return true;
}
template <typename T>
auto BloomFilter<T>::GetStatistics () const -> Statistics
{
size_t nTrue{};
for (bool i : fBits_) {
if (i) {
nTrue++;
}
}
return Statistics{fHashFunctions_.size (), fBits_.size (), nTrue};
}
}
#endif /*_Stroika_Foundation_Cache_BloomFilter_inl_*/
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved
*/
#include "../StroikaPreComp.h"
#if qPlatform_AIX
#include <sys/stat.h>
#endif
#include "Process.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Configuration;
using namespace Stroika::Foundation::Execution;
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
/*
********************************************************************************
********************** Execution::IsProcessRunning *****************************
********************************************************************************
*/
bool Execution::IsProcessRunning (pid_t pid)
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper traceCtx ("Stroika::Foundation::Execution::IsProcessRunning");
DbgTrace (L"(pid=%d)", pid);
#endif
#if qPlatform_AIX
// sadly getpgid doesnt appear to work on AIX --LGP 2015-11-13
// From http://stackoverflow.com/questions/9152979/check-if-process-exists-given-its-pid
struct stat sts;
char buf[1024];
snprintf (buf, NEltsOf(buf), "/proc/%d", pid);
if (::stat (buf, &sts) == -1 && errno == ENOENT) {
// process doesn't exist
return true;
}
else {
return true;
}
#elif qPlatform_POSIX
// http://stackoverflow.com/questions/9152979/check-if-process-exists-given-its-pid
// http://linux.die.net/man/2/getpgid
// if not owner, trick of kill (pid, 0) returns error EPERM
pid_t tmp { ::getpgid (pid) };
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace (L"getpgid (pid=%d) -> %d, with ernno=%d", pid, tmp, errno);
#endif
return tmp > 0;
#else
AssertNotImplemented ();
return false;
#endif
}
<commit_msg>probably fixed Execution::IsProcessRunning() for AIX<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved
*/
#include "../StroikaPreComp.h"
#if qPlatform_AIX
#include <sys/stat.h>
#endif
#include "Process.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Configuration;
using namespace Stroika::Foundation::Execution;
// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
/*
********************************************************************************
********************** Execution::IsProcessRunning *****************************
********************************************************************************
*/
bool Execution::IsProcessRunning (pid_t pid)
{
#if USE_NOISY_TRACE_IN_THIS_MODULE_
Debug::TraceContextBumper traceCtx ("Stroika::Foundation::Execution::IsProcessRunning");
DbgTrace (L"(pid=%d)", pid);
#endif
#if qPlatform_AIX
// sadly getpgid doesnt appear to work on AIX --LGP 2015-11-13
// From http://stackoverflow.com/questions/9152979/check-if-process-exists-given-its-pid
struct stat sts;
char buf[1024];
snprintf (buf, NEltsOf(buf), "/proc/%d", pid);
if (::stat (buf, &sts) == -1 && errno == ENOENT) {
// process doesn't exist
return false;
}
else {
return true;
}
#elif qPlatform_POSIX
// http://stackoverflow.com/questions/9152979/check-if-process-exists-given-its-pid
// http://linux.die.net/man/2/getpgid
// if not owner, trick of kill (pid, 0) returns error EPERM
pid_t tmp { ::getpgid (pid) };
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace (L"getpgid (pid=%d) -> %d, with ernno=%d", pid, tmp, errno);
#endif
return tmp > 0;
#else
AssertNotImplemented ();
return false;
#endif
}
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved
*/
#include "../StroikaPreComp.h"
#include <map>
#include "../Debug/Trace.h"
#include "CriticalSection.h"
#include "Signals.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Execution;
namespace {
CriticalSection sCritSection_;
map<SignalIDType,set<SignalHandlerType>> sHandlers_;
bool IsSigIgnore_ (const set<SignalHandlerType>& sigSet)
{
return sigSet.size () == 1 and *sigSet.begin () == SignalHandlerRegistry::kIGNORED;
}
void MyHandler_ (int signal)
{
Debug::TraceContextBumper trcCtx (TSTR ("Stroika::Foundation::Execution::Signals::{}::MyHandler_"));
DbgTrace ("(signal = %d)", signal);
set<SignalHandlerType> handlers;
{
AutoCriticalSection critSec (sCritSection_);
map<SignalIDType,set<SignalHandlerType>>::const_iterator i = sHandlers_.find (signal);
Assert (i != sHandlers_.end ());
handlers = i->second;
}
for (set<SignalHandlerType>::const_iterator i = handlers.begin (); i != handlers.end (); ++i) {
if (*i != SignalHandlerRegistry::kIGNORED) {
(*i) (signal);
}
}
}
}
/*
********************************************************************************
******************** Execution::SignalHandlerRegistry **************************
********************************************************************************
*/
const SignalHandlerType SignalHandlerRegistry::kIGNORED = SIG_IGN;
SignalHandlerRegistry& SignalHandlerRegistry::Get ()
{
static SignalHandlerRegistry sThe_;
return sThe_;
}
SignalHandlerRegistry::SignalHandlerRegistry ()
{
}
set<SignalIDType> SignalHandlerRegistry::GetHandledSignals () const
{
set<SignalIDType> result;
{
AutoCriticalSection critSec (sCritSection_);
for (map<SignalIDType,set<SignalHandlerType>>::const_iterator i = sHandlers_.begin (); i != sHandlers_.end (); ++i) {
result.insert (i->first);
}
}
return result;
}
set<SignalHandlerType> SignalHandlerRegistry::GetSignalHandlers (SignalIDType signal) const
{
AutoCriticalSection critSec (sCritSection_);
map<SignalIDType,set<SignalHandlerType>>::const_iterator i = sHandlers_.find (signal);
if (i == sHandlers_.end ()) {
return set<SignalHandlerType> ();
}
else {
return i->second;
}
}
void SignalHandlerRegistry::SetSignalHandlers (SignalIDType signal)
{
SetSignalHandlers (signal, set<SignalHandlerType> ());
}
void SignalHandlerRegistry::SetSignalHandlers (SignalIDType signal, SignalHandlerType handler)
{
SetSignalHandlers (signal, set<SignalHandlerType> (&handler, &handler + 1));
}
void SignalHandlerRegistry::SetSignalHandlers (SignalIDType signal, const set<SignalHandlerType>& handlers)
{
Debug::TraceContextBumper trcCtx (TSTR ("Stroika::Foundation::Execution::Signals::{}::SetSignalHandlers"));
DbgTrace ("(signal = %d, handlers.size (), ....)", signal, handlers.size ());
AutoCriticalSection critSec (sCritSection_);
map<SignalIDType,set<SignalHandlerType>>::iterator i = sHandlers_.find (signal);
if (i == sHandlers_.end ()) {
if (not handlers.empty ()) {
sHandlers_.insert (map<SignalIDType,set<SignalHandlerType>>::value_type (signal, handlers));
}
}
else {
i->second = handlers;
}
if (handlers.empty ()) {
// nothing todo - empty list treated as not in sHandlers_ list
(void)::signal (signal, SIG_DFL);
}
else if (IsSigIgnore_ (handlers)) {
(void)::signal (signal, SIG_IGN);
}
else {
(void)::signal (signal, MyHandler_);
}
}
void SignalHandlerRegistry::AddSignalHandler (SignalIDType signal, SignalHandlerType handler)
{
set<SignalHandlerType> s = GetSignalHandlers (signal);
s.insert (handler);
SetSignalHandlers (signal, s);
}
void SignalHandlerRegistry::RemoveSignalHandler (SignalIDType signal, SignalHandlerType handler)
{
set<SignalHandlerType> s = GetSignalHandlers (signal);
Require (s.find (handler) != s.end ());
s.erase (handler);
SetSignalHandlers (signal, s);
}
/*
********************************************************************************
**************************** Execution::SendSignal *****************************
********************************************************************************
*/
void Execution::SendSignal (Thread::NativeHandleType h, SignalIDType signal)
{
Debug::TraceContextBumper trcCtx (TSTR ("Stroika::Foundation::Execution::Signals::Execution::SendSignal"));
DbgTrace ("(signal = %d)", signal);
#if qPlatform_POSIX
Verify (pthread_kill (h, signal));
#else
AssertNotImplemented ();
#endif
}
<commit_msg>fixed POSIX signal debugmessage and assertion<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved
*/
#include "../StroikaPreComp.h"
#include <map>
#include "../Debug/Trace.h"
#include "CriticalSection.h"
#include "Signals.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Execution;
namespace {
CriticalSection sCritSection_;
map<SignalIDType,set<SignalHandlerType>> sHandlers_;
bool IsSigIgnore_ (const set<SignalHandlerType>& sigSet)
{
return sigSet.size () == 1 and *sigSet.begin () == SignalHandlerRegistry::kIGNORED;
}
void MyHandler_ (int signal)
{
Debug::TraceContextBumper trcCtx (TSTR ("Stroika::Foundation::Execution::Signals::{}::MyHandler_"));
DbgTrace ("(signal = %d)", signal);
set<SignalHandlerType> handlers;
{
AutoCriticalSection critSec (sCritSection_);
map<SignalIDType,set<SignalHandlerType>>::const_iterator i = sHandlers_.find (signal);
Assert (i != sHandlers_.end ());
handlers = i->second;
}
for (set<SignalHandlerType>::const_iterator i = handlers.begin (); i != handlers.end (); ++i) {
if (*i != SignalHandlerRegistry::kIGNORED) {
(*i) (signal);
}
}
}
}
/*
********************************************************************************
******************** Execution::SignalHandlerRegistry **************************
********************************************************************************
*/
const SignalHandlerType SignalHandlerRegistry::kIGNORED = SIG_IGN;
SignalHandlerRegistry& SignalHandlerRegistry::Get ()
{
static SignalHandlerRegistry sThe_;
return sThe_;
}
SignalHandlerRegistry::SignalHandlerRegistry ()
{
}
set<SignalIDType> SignalHandlerRegistry::GetHandledSignals () const
{
set<SignalIDType> result;
{
AutoCriticalSection critSec (sCritSection_);
for (map<SignalIDType,set<SignalHandlerType>>::const_iterator i = sHandlers_.begin (); i != sHandlers_.end (); ++i) {
result.insert (i->first);
}
}
return result;
}
set<SignalHandlerType> SignalHandlerRegistry::GetSignalHandlers (SignalIDType signal) const
{
AutoCriticalSection critSec (sCritSection_);
map<SignalIDType,set<SignalHandlerType>>::const_iterator i = sHandlers_.find (signal);
if (i == sHandlers_.end ()) {
return set<SignalHandlerType> ();
}
else {
return i->second;
}
}
void SignalHandlerRegistry::SetSignalHandlers (SignalIDType signal)
{
SetSignalHandlers (signal, set<SignalHandlerType> ());
}
void SignalHandlerRegistry::SetSignalHandlers (SignalIDType signal, SignalHandlerType handler)
{
SetSignalHandlers (signal, set<SignalHandlerType> (&handler, &handler + 1));
}
void SignalHandlerRegistry::SetSignalHandlers (SignalIDType signal, const set<SignalHandlerType>& handlers)
{
Debug::TraceContextBumper trcCtx (TSTR ("Stroika::Foundation::Execution::Signals::{}::SetSignalHandlers"));
DbgTrace ("(signal = %d, handlers.size () = %d, ....)", signal, handlers.size ());
AutoCriticalSection critSec (sCritSection_);
map<SignalIDType,set<SignalHandlerType>>::iterator i = sHandlers_.find (signal);
if (i == sHandlers_.end ()) {
if (not handlers.empty ()) {
sHandlers_.insert (map<SignalIDType,set<SignalHandlerType>>::value_type (signal, handlers));
}
}
else {
i->second = handlers;
}
if (handlers.empty ()) {
// nothing todo - empty list treated as not in sHandlers_ list
(void)::signal (signal, SIG_DFL);
}
else if (IsSigIgnore_ (handlers)) {
(void)::signal (signal, SIG_IGN);
}
else {
(void)::signal (signal, MyHandler_);
}
}
void SignalHandlerRegistry::AddSignalHandler (SignalIDType signal, SignalHandlerType handler)
{
set<SignalHandlerType> s = GetSignalHandlers (signal);
s.insert (handler);
SetSignalHandlers (signal, s);
}
void SignalHandlerRegistry::RemoveSignalHandler (SignalIDType signal, SignalHandlerType handler)
{
set<SignalHandlerType> s = GetSignalHandlers (signal);
Require (s.find (handler) != s.end ());
s.erase (handler);
SetSignalHandlers (signal, s);
}
/*
********************************************************************************
**************************** Execution::SendSignal *****************************
********************************************************************************
*/
void Execution::SendSignal (Thread::NativeHandleType h, SignalIDType signal)
{
Debug::TraceContextBumper trcCtx (TSTR ("Stroika::Foundation::Execution::Signals::Execution::SendSignal"));
DbgTrace ("(signal = %d)", signal);
#if qPlatform_POSIX
Verify (pthread_kill (h, signal) == 0);
#else
AssertNotImplemented ();
#endif
}
<|endoftext|> |
<commit_before>#include "openrasp_file.h"
static const char* mode_to_type(char *mode)
{
if (strchr(mode, '+') > mode)
{
return "writeFile";
}
else if (strchr(mode, 'r') != nullptr)
{
return "readFile";
}
else
{
return "writeFile";
}
}
static void check_file_operation(const char* type, char *filename, int filename_len, zend_bool use_include_path TSRMLS_DC)
{
char resolved_path_buff[MAXPATHLEN];
char *real_path = nullptr;
real_path = php_resolve_path(filename, filename_len, use_include_path ? PG(include_path) : NULL TSRMLS_CC);
if (real_path)
{
zval *params;
MAKE_STD_ZVAL(params);
array_init(params);
zval *path = NULL;
MAKE_STD_ZVAL(path);
ZVAL_STRING(path, filename, 1);
zval *realpath = NULL;
MAKE_STD_ZVAL(realpath);
ZVAL_STRING(realpath, real_path, 1);
add_assoc_zval(params, "path", path);
add_assoc_zval(params, "realpath", realpath);
check(type, params TSRMLS_CC);
}
}
void hook_file(INTERNAL_FUNCTION_PARAMETERS)
{
char *filename;
int filename_len;
long flags = 0;
zend_bool use_include_path;
zval *zcontext = NULL;
if (openrasp_check_type_ignored(ZEND_STRL("readFile") TSRMLS_CC)
|| zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|lr!", &filename, &filename_len, &flags, &zcontext) == FAILURE) {
return;
}
use_include_path = flags & PHP_FILE_USE_INCLUDE_PATH;
check_file_operation("readFile", filename, filename_len, use_include_path TSRMLS_CC);
}
void hook_readfile(INTERNAL_FUNCTION_PARAMETERS)
{
char *filename;
int filename_len;
zend_bool use_include_path = 0;
zval *zcontext = NULL;
if (openrasp_check_type_ignored(ZEND_STRL("readFile") TSRMLS_CC)
|| zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|br!", &filename, &filename_len, &use_include_path, &zcontext) == FAILURE) {
return;
}
check_file_operation("readFile", filename, filename_len, use_include_path TSRMLS_CC);
}
void hook_file_get_contents(INTERNAL_FUNCTION_PARAMETERS)
{
char *filename;
int filename_len;
zend_bool use_include_path = 0;
long offset = -1;
long maxlen = PHP_STREAM_COPY_ALL;
zval *zcontext = NULL;
if (openrasp_check_type_ignored(ZEND_STRL("readFile") TSRMLS_CC)
|| zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|br!ll", &filename, &filename_len, &use_include_path, &zcontext, &offset, &maxlen) == FAILURE) {
return;
}
check_file_operation("readFile", filename, filename_len, use_include_path TSRMLS_CC);
}
void hook_file_put_contents(INTERNAL_FUNCTION_PARAMETERS)
{
zval **path, **data, **flags;
char resolved_path_buff[MAXPATHLEN];
int argc = MIN(3, ZEND_NUM_ARGS());
if (!openrasp_check_type_ignored(ZEND_STRL("writeFile") TSRMLS_CC) &&
argc > 1 &&
zend_get_parameters_ex(argc, &path, &data, &flags) == SUCCESS &&
Z_TYPE_PP(path) == IS_STRING)
{
if (!openrasp_check_type_ignored(ZEND_STRL("webshell") TSRMLS_CC)
&& openrasp_zval_in_request(*path TSRMLS_CC)
&& openrasp_zval_in_request(*data TSRMLS_CC))
{
zval *attack_params = NULL;
MAKE_STD_ZVAL(attack_params);
ZVAL_STRING(attack_params, "", 1);
zval *plugin_message = NULL;
MAKE_STD_ZVAL(plugin_message);
ZVAL_STRING(plugin_message, _("File dropper backdoor"), 1);
openrasp_buildin_php_risk_handle(1, "webshell", 100, attack_params, plugin_message TSRMLS_CC);
}
char *real_path = nullptr;
char *include_path = nullptr;
if (argc == 3 && Z_TYPE_PP(flags) == IS_LONG && (Z_LVAL_PP(flags) & PHP_FILE_USE_INCLUDE_PATH))
{
include_path = PG(include_path);
}
else
{
include_path = NULL;
}
real_path = php_resolve_path(Z_STRVAL_PP(path), Z_STRLEN_PP(path), include_path TSRMLS_CC);
zval *params;
MAKE_STD_ZVAL(params);
array_init(params);
add_assoc_zval(params, "path", *path);
Z_ADDREF_P(*path);
if (real_path)
{
add_assoc_string(params, "realpath", real_path, 1);
}
else
{
zval *realpath;
MAKE_STD_ZVAL(realpath);
ZVAL_STRING(realpath, Z_STRVAL_PP(path), 1);
add_assoc_zval(params, "realpath", realpath);
}
check("writeFile", params TSRMLS_CC);
}
}
void hook_fopen(INTERNAL_FUNCTION_PARAMETERS)
{
char *filename, *mode;
int filename_len, mode_len;
zend_bool use_include_path = 0;
zval *zcontext = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ps|br", &filename, &filename_len, &mode, &mode_len, &use_include_path, &zcontext) == FAILURE) {
return;
}
const char *type = mode_to_type(mode);
if (!openrasp_check_type_ignored(type, strlen(type) TSRMLS_CC))
{
check_file_operation(type, filename, filename_len, use_include_path TSRMLS_CC);
}
}
void hook_splfileobject___construct_ex(INTERNAL_FUNCTION_PARAMETERS)
{
char *filename, *mode;
int filename_len, mode_len;
zend_bool use_include_path = 0;
zval *zcontext = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|sbr", &filename, &filename_len, &mode, &mode_len, &use_include_path, &zcontext) == FAILURE) {
return;
}
const char *type = mode_to_type(mode);
if (!openrasp_check_type_ignored(type, strlen(type) TSRMLS_CC))
{
check_file_operation(type, filename, filename_len, use_include_path TSRMLS_CC);
}
}
void hook_copy(INTERNAL_FUNCTION_PARAMETERS)
{
zval **source, **dest;
int argc = MIN(2, ZEND_NUM_ARGS());
if (!openrasp_check_type_ignored(ZEND_STRL("writeFile") TSRMLS_CC) &&
argc > 1 &&
zend_get_parameters_ex(argc, &source, &dest) == SUCCESS &&
Z_TYPE_PP(source) == IS_STRING &&
Z_TYPE_PP(dest) == IS_STRING)
{
zval *params;
MAKE_STD_ZVAL(params);
array_init(params);
add_assoc_zval(params, "path", *dest);
Z_ADDREF_P(*dest);
add_assoc_zval(params, "realpath", *dest);
Z_ADDREF_P(*dest);
check("writeFile", params TSRMLS_CC);
}
}<commit_msg>openrasp_file.cc zend_parse_params p->s<commit_after>#include "openrasp_file.h"
static const char* mode_to_type(char *mode)
{
if (strchr(mode, '+') > mode)
{
return "writeFile";
}
else if (strchr(mode, 'r') != nullptr)
{
return "readFile";
}
else
{
return "writeFile";
}
}
static void check_file_operation(const char* type, char *filename, int filename_len, zend_bool use_include_path TSRMLS_DC)
{
char resolved_path_buff[MAXPATHLEN];
char *real_path = nullptr;
real_path = php_resolve_path(filename, filename_len, use_include_path ? PG(include_path) : NULL TSRMLS_CC);
if (real_path)
{
zval *params;
MAKE_STD_ZVAL(params);
array_init(params);
zval *path = NULL;
MAKE_STD_ZVAL(path);
ZVAL_STRING(path, filename, 1);
zval *realpath = NULL;
MAKE_STD_ZVAL(realpath);
ZVAL_STRING(realpath, real_path, 1);
add_assoc_zval(params, "path", path);
add_assoc_zval(params, "realpath", realpath);
check(type, params TSRMLS_CC);
}
}
void hook_file(INTERNAL_FUNCTION_PARAMETERS)
{
char *filename;
int filename_len;
long flags = 0;
zend_bool use_include_path;
zval *zcontext = NULL;
if (openrasp_check_type_ignored(ZEND_STRL("readFile") TSRMLS_CC)
|| zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|lr!", &filename, &filename_len, &flags, &zcontext) == FAILURE) {
return;
}
use_include_path = flags & PHP_FILE_USE_INCLUDE_PATH;
check_file_operation("readFile", filename, filename_len, use_include_path TSRMLS_CC);
}
void hook_readfile(INTERNAL_FUNCTION_PARAMETERS)
{
char *filename;
int filename_len;
zend_bool use_include_path = 0;
zval *zcontext = NULL;
if (openrasp_check_type_ignored(ZEND_STRL("readFile") TSRMLS_CC)
|| zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|br!", &filename, &filename_len, &use_include_path, &zcontext) == FAILURE) {
return;
}
check_file_operation("readFile", filename, filename_len, use_include_path TSRMLS_CC);
}
void hook_file_get_contents(INTERNAL_FUNCTION_PARAMETERS)
{
char *filename;
int filename_len;
zend_bool use_include_path = 0;
long offset = -1;
long maxlen = PHP_STREAM_COPY_ALL;
zval *zcontext = NULL;
if (openrasp_check_type_ignored(ZEND_STRL("readFile") TSRMLS_CC)
|| zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|br!ll", &filename, &filename_len, &use_include_path, &zcontext, &offset, &maxlen) == FAILURE) {
return;
}
check_file_operation("readFile", filename, filename_len, use_include_path TSRMLS_CC);
}
void hook_file_put_contents(INTERNAL_FUNCTION_PARAMETERS)
{
zval **path, **data, **flags;
char resolved_path_buff[MAXPATHLEN];
int argc = MIN(3, ZEND_NUM_ARGS());
if (!openrasp_check_type_ignored(ZEND_STRL("writeFile") TSRMLS_CC) &&
argc > 1 &&
zend_get_parameters_ex(argc, &path, &data, &flags) == SUCCESS &&
Z_TYPE_PP(path) == IS_STRING)
{
if (!openrasp_check_type_ignored(ZEND_STRL("webshell") TSRMLS_CC)
&& openrasp_zval_in_request(*path TSRMLS_CC)
&& openrasp_zval_in_request(*data TSRMLS_CC))
{
zval *attack_params = NULL;
MAKE_STD_ZVAL(attack_params);
ZVAL_STRING(attack_params, "", 1);
zval *plugin_message = NULL;
MAKE_STD_ZVAL(plugin_message);
ZVAL_STRING(plugin_message, _("File dropper backdoor"), 1);
openrasp_buildin_php_risk_handle(1, "webshell", 100, attack_params, plugin_message TSRMLS_CC);
}
char *real_path = nullptr;
char *include_path = nullptr;
if (argc == 3 && Z_TYPE_PP(flags) == IS_LONG && (Z_LVAL_PP(flags) & PHP_FILE_USE_INCLUDE_PATH))
{
include_path = PG(include_path);
}
else
{
include_path = NULL;
}
real_path = php_resolve_path(Z_STRVAL_PP(path), Z_STRLEN_PP(path), include_path TSRMLS_CC);
zval *params;
MAKE_STD_ZVAL(params);
array_init(params);
add_assoc_zval(params, "path", *path);
Z_ADDREF_P(*path);
if (real_path)
{
add_assoc_string(params, "realpath", real_path, 1);
}
else
{
zval *realpath;
MAKE_STD_ZVAL(realpath);
ZVAL_STRING(realpath, Z_STRVAL_PP(path), 1);
add_assoc_zval(params, "realpath", realpath);
}
check("writeFile", params TSRMLS_CC);
}
}
void hook_fopen(INTERNAL_FUNCTION_PARAMETERS)
{
char *filename, *mode;
int filename_len, mode_len;
zend_bool use_include_path = 0;
zval *zcontext = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|br", &filename, &filename_len, &mode, &mode_len, &use_include_path, &zcontext) == FAILURE) {
return;
}
const char *type = mode_to_type(mode);
if (!openrasp_check_type_ignored(type, strlen(type) TSRMLS_CC))
{
check_file_operation(type, filename, filename_len, use_include_path TSRMLS_CC);
}
}
void hook_splfileobject___construct_ex(INTERNAL_FUNCTION_PARAMETERS)
{
char *filename, *mode;
int filename_len, mode_len;
zend_bool use_include_path = 0;
zval *zcontext = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|sbr", &filename, &filename_len, &mode, &mode_len, &use_include_path, &zcontext) == FAILURE) {
return;
}
const char *type = mode_to_type(mode);
if (!openrasp_check_type_ignored(type, strlen(type) TSRMLS_CC))
{
check_file_operation(type, filename, filename_len, use_include_path TSRMLS_CC);
}
}
void hook_copy(INTERNAL_FUNCTION_PARAMETERS)
{
zval **source, **dest;
int argc = MIN(2, ZEND_NUM_ARGS());
if (!openrasp_check_type_ignored(ZEND_STRL("writeFile") TSRMLS_CC) &&
argc > 1 &&
zend_get_parameters_ex(argc, &source, &dest) == SUCCESS &&
Z_TYPE_PP(source) == IS_STRING &&
Z_TYPE_PP(dest) == IS_STRING)
{
zval *params;
MAKE_STD_ZVAL(params);
array_init(params);
add_assoc_zval(params, "path", *dest);
Z_ADDREF_P(*dest);
add_assoc_zval(params, "realpath", *dest);
Z_ADDREF_P(*dest);
check("writeFile", params TSRMLS_CC);
}
}<|endoftext|> |
<commit_before>//===- unittest/AST/RecursiveASTMatcherTest.cpp ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Tooling/Tooling.h"
#include "gtest/gtest.h"
namespace clang {
/// \brief Base class for sipmle RecursiveASTVisitor based tests.
///
/// This is a drop-in replacement for RecursiveASTVisitor itself, with the
/// additional capability of running it over a snippet of code.
///
/// Visits template instantiations by default.
///
/// FIXME: Put into a common location.
template <typename T>
class TestVisitor : public clang::RecursiveASTVisitor<T> {
public:
/// \brief Runs the current AST visitor over the given code.
bool runOver(StringRef Code) {
return tooling::runToolOnCode(new TestAction(this), Code);
}
bool shouldVisitTemplateInstantiations() const {
return true;
}
protected:
clang::ASTContext *Context;
clang::SourceManager *SM;
private:
class FindConsumer : public clang::ASTConsumer {
public:
FindConsumer(TestVisitor *Visitor) : Visitor(Visitor) {}
virtual void HandleTranslationUnit(clang::ASTContext &Context) {
Visitor->TraverseDecl(Context.getTranslationUnitDecl());
}
private:
TestVisitor *Visitor;
};
class TestAction : public clang::ASTFrontendAction {
public:
TestAction(TestVisitor *Visitor) : Visitor(Visitor) {}
virtual clang::ASTConsumer* CreateASTConsumer(
clang::CompilerInstance& compiler, llvm::StringRef dummy) {
Visitor->SM = &compiler.getSourceManager();
Visitor->Context = &compiler.getASTContext();
/// TestConsumer will be deleted by the framework calling us.
return new FindConsumer(Visitor);
}
private:
TestVisitor *Visitor;
};
};
/// \brief A RecursiveASTVisitor for testing the RecursiveASTVisitor itself.
///
/// Allows simple creation of test visitors running matches on only a small
/// subset of the Visit* methods.
template <typename T>
class ExpectedLocationVisitor : public TestVisitor<T> {
public:
ExpectedLocationVisitor()
: ExpectedLine(0), ExpectedColumn(0), Found(false) {}
~ExpectedLocationVisitor() {
EXPECT_TRUE(Found)
<< "Expected \"" << ExpectedMatch << "\" at " << ExpectedLine
<< ":" << ExpectedColumn << PartialMatches;
}
/// \brief Expect 'Match' to occur at the given 'Line' and 'Column'.
void ExpectMatch(Twine Match, unsigned Line, unsigned Column) {
ExpectedMatch = Match.str();
ExpectedLine = Line;
ExpectedColumn = Column;
}
protected:
/// \brief Convenience method to simplify writing test visitors.
///
/// Sets 'Found' to true if 'Name' and 'Location' match the expected
/// values. If only a partial match is found, record the information
/// to produce nice error output when a test fails.
///
/// Implementations are required to call this with appropriate values
/// for 'Name' during visitation.
void Match(StringRef Name, SourceLocation Location) {
FullSourceLoc FullLocation = this->Context->getFullLoc(Location);
if (Name == ExpectedMatch &&
FullLocation.isValid() &&
FullLocation.getSpellingLineNumber() == ExpectedLine &&
FullLocation.getSpellingColumnNumber() == ExpectedColumn) {
Found = true;
} else if (Name == ExpectedMatch ||
(FullLocation.isValid() &&
FullLocation.getSpellingLineNumber() == ExpectedLine &&
FullLocation.getSpellingColumnNumber() == ExpectedColumn)) {
// If we did not match, record information about partial matches.
llvm::raw_string_ostream Stream(PartialMatches);
Stream << ", partial match: \"" << Name << "\" at ";
Location.print(Stream, *this->SM);
}
}
std::string ExpectedMatch;
unsigned ExpectedLine;
unsigned ExpectedColumn;
std::string PartialMatches;
bool Found;
};
class TypeLocVisitor : public ExpectedLocationVisitor<TypeLocVisitor> {
public:
bool VisitTypeLoc(TypeLoc TypeLocation) {
Match(TypeLocation.getType().getAsString(), TypeLocation.getBeginLoc());
return true;
}
};
class DeclRefExprVisitor : public ExpectedLocationVisitor<DeclRefExprVisitor> {
public:
bool VisitDeclRefExpr(DeclRefExpr *Reference) {
Match(Reference->getNameInfo().getAsString(), Reference->getLocation());
return true;
}
};
class CXXMemberCallVisitor
: public ExpectedLocationVisitor<CXXMemberCallVisitor> {
public:
bool VisitCXXMemberCallExpr(CXXMemberCallExpr *Call) {
Match(Call->getMethodDecl()->getQualifiedNameAsString(),
Call->getLocStart());
return true;
}
};
TEST(RecursiveASTVisitor, VisitsBaseClassDeclarations) {
TypeLocVisitor Visitor;
Visitor.ExpectMatch("class X", 1, 30);
EXPECT_TRUE(Visitor.runOver("class X {}; class Y : public X {};"));
}
TEST(RecursiveASTVisitor, VisitsBaseClassTemplateArguments) {
DeclRefExprVisitor Visitor;
Visitor.ExpectMatch("x", 2, 3);
EXPECT_TRUE(Visitor.runOver(
"void x(); template <void (*T)()> class X {};\nX<x> y;"));
}
TEST(RecursiveASTVisitor, VisitsCallExpr) {
DeclRefExprVisitor Visitor;
Visitor.ExpectMatch("x", 1, 22);
EXPECT_TRUE(Visitor.runOver(
"void x(); void y() { x(); }"));
}
TEST(RecursiveASTVisitor, VisitsCallInTemplateInstantiation) {
CXXMemberCallVisitor Visitor;
Visitor.ExpectMatch("Y::x", 3, 3);
EXPECT_TRUE(Visitor.runOver(
"struct Y { void x(); };\n"
"template<typename T> void y(T t) {\n"
" t.x();\n"
"}\n"
"void foo() { y<Y>(Y()); }"));
}
/* FIXME:
TEST(RecursiveASTVisitor, VisitsCallInNestedTemplateInstantiation) {
CXXMemberCallVisitor Visitor;
Visitor.ExpectMatch("Y::x", 4, 5);
EXPECT_TRUE(Visitor.runOver(
"struct Y { void x(); };\n"
"template<typename T> struct Z {\n"
" template<typename U> static void f() {\n"
" T().x();\n"
" }\n"
"};\n"
"void foo() { Z<Y>::f<int>(); }"));
}
*/
/* FIXME: According to Richard Smith this is a bug in the AST.
TEST(RecursiveASTVisitor, VisitsBaseClassTemplateArgumentsInInstantiation) {
DeclRefExprVisitor Visitor;
Visitor.ExpectMatch("x", 3, 43);
EXPECT_TRUE(Visitor.runOver(
"template <typename T> void x();\n"
"template <void (*T)()> class X {};\n"
"template <typename T> class Y : public X< x<T> > {};\n"
"Y<int> y;"));
}
*/
} // end namespace clang
<commit_msg>No need to put the SourceManager in with the ASTContext, as the ASTContext already contains the SourceManager.<commit_after>//===- unittest/AST/RecursiveASTMatcherTest.cpp ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Tooling/Tooling.h"
#include "gtest/gtest.h"
namespace clang {
/// \brief Base class for sipmle RecursiveASTVisitor based tests.
///
/// This is a drop-in replacement for RecursiveASTVisitor itself, with the
/// additional capability of running it over a snippet of code.
///
/// Visits template instantiations by default.
///
/// FIXME: Put into a common location.
template <typename T>
class TestVisitor : public clang::RecursiveASTVisitor<T> {
public:
/// \brief Runs the current AST visitor over the given code.
bool runOver(StringRef Code) {
return tooling::runToolOnCode(new TestAction(this), Code);
}
bool shouldVisitTemplateInstantiations() const {
return true;
}
protected:
clang::ASTContext *Context;
private:
class FindConsumer : public clang::ASTConsumer {
public:
FindConsumer(TestVisitor *Visitor) : Visitor(Visitor) {}
virtual void HandleTranslationUnit(clang::ASTContext &Context) {
Visitor->TraverseDecl(Context.getTranslationUnitDecl());
}
private:
TestVisitor *Visitor;
};
class TestAction : public clang::ASTFrontendAction {
public:
TestAction(TestVisitor *Visitor) : Visitor(Visitor) {}
virtual clang::ASTConsumer* CreateASTConsumer(
clang::CompilerInstance& compiler, llvm::StringRef dummy) {
Visitor->Context = &compiler.getASTContext();
/// TestConsumer will be deleted by the framework calling us.
return new FindConsumer(Visitor);
}
private:
TestVisitor *Visitor;
};
};
/// \brief A RecursiveASTVisitor for testing the RecursiveASTVisitor itself.
///
/// Allows simple creation of test visitors running matches on only a small
/// subset of the Visit* methods.
template <typename T>
class ExpectedLocationVisitor : public TestVisitor<T> {
public:
ExpectedLocationVisitor()
: ExpectedLine(0), ExpectedColumn(0), Found(false) {}
~ExpectedLocationVisitor() {
EXPECT_TRUE(Found)
<< "Expected \"" << ExpectedMatch << "\" at " << ExpectedLine
<< ":" << ExpectedColumn << PartialMatches;
}
/// \brief Expect 'Match' to occur at the given 'Line' and 'Column'.
void ExpectMatch(Twine Match, unsigned Line, unsigned Column) {
ExpectedMatch = Match.str();
ExpectedLine = Line;
ExpectedColumn = Column;
}
protected:
/// \brief Convenience method to simplify writing test visitors.
///
/// Sets 'Found' to true if 'Name' and 'Location' match the expected
/// values. If only a partial match is found, record the information
/// to produce nice error output when a test fails.
///
/// Implementations are required to call this with appropriate values
/// for 'Name' during visitation.
void Match(StringRef Name, SourceLocation Location) {
FullSourceLoc FullLocation = this->Context->getFullLoc(Location);
if (Name == ExpectedMatch &&
FullLocation.isValid() &&
FullLocation.getSpellingLineNumber() == ExpectedLine &&
FullLocation.getSpellingColumnNumber() == ExpectedColumn) {
Found = true;
} else if (Name == ExpectedMatch ||
(FullLocation.isValid() &&
FullLocation.getSpellingLineNumber() == ExpectedLine &&
FullLocation.getSpellingColumnNumber() == ExpectedColumn)) {
// If we did not match, record information about partial matches.
llvm::raw_string_ostream Stream(PartialMatches);
Stream << ", partial match: \"" << Name << "\" at ";
Location.print(Stream, this->Context->getSourceManager());
}
}
std::string ExpectedMatch;
unsigned ExpectedLine;
unsigned ExpectedColumn;
std::string PartialMatches;
bool Found;
};
class TypeLocVisitor : public ExpectedLocationVisitor<TypeLocVisitor> {
public:
bool VisitTypeLoc(TypeLoc TypeLocation) {
Match(TypeLocation.getType().getAsString(), TypeLocation.getBeginLoc());
return true;
}
};
class DeclRefExprVisitor : public ExpectedLocationVisitor<DeclRefExprVisitor> {
public:
bool VisitDeclRefExpr(DeclRefExpr *Reference) {
Match(Reference->getNameInfo().getAsString(), Reference->getLocation());
return true;
}
};
class CXXMemberCallVisitor
: public ExpectedLocationVisitor<CXXMemberCallVisitor> {
public:
bool VisitCXXMemberCallExpr(CXXMemberCallExpr *Call) {
Match(Call->getMethodDecl()->getQualifiedNameAsString(),
Call->getLocStart());
return true;
}
};
TEST(RecursiveASTVisitor, VisitsBaseClassDeclarations) {
TypeLocVisitor Visitor;
Visitor.ExpectMatch("class X", 1, 30);
EXPECT_TRUE(Visitor.runOver("class X {}; class Y : public X {};"));
}
TEST(RecursiveASTVisitor, VisitsBaseClassTemplateArguments) {
DeclRefExprVisitor Visitor;
Visitor.ExpectMatch("x", 2, 3);
EXPECT_TRUE(Visitor.runOver(
"void x(); template <void (*T)()> class X {};\nX<x> y;"));
}
TEST(RecursiveASTVisitor, VisitsCallExpr) {
DeclRefExprVisitor Visitor;
Visitor.ExpectMatch("x", 1, 22);
EXPECT_TRUE(Visitor.runOver(
"void x(); void y() { x(); }"));
}
TEST(RecursiveASTVisitor, VisitsCallInTemplateInstantiation) {
CXXMemberCallVisitor Visitor;
Visitor.ExpectMatch("Y::x", 3, 3);
EXPECT_TRUE(Visitor.runOver(
"struct Y { void x(); };\n"
"template<typename T> void y(T t) {\n"
" t.x();\n"
"}\n"
"void foo() { y<Y>(Y()); }"));
}
/* FIXME:
TEST(RecursiveASTVisitor, VisitsCallInNestedTemplateInstantiation) {
CXXMemberCallVisitor Visitor;
Visitor.ExpectMatch("Y::x", 4, 5);
EXPECT_TRUE(Visitor.runOver(
"struct Y { void x(); };\n"
"template<typename T> struct Z {\n"
" template<typename U> static void f() {\n"
" T().x();\n"
" }\n"
"};\n"
"void foo() { Z<Y>::f<int>(); }"));
}
*/
/* FIXME: According to Richard Smith this is a bug in the AST.
TEST(RecursiveASTVisitor, VisitsBaseClassTemplateArgumentsInInstantiation) {
DeclRefExprVisitor Visitor;
Visitor.ExpectMatch("x", 3, 43);
EXPECT_TRUE(Visitor.runOver(
"template <typename T> void x();\n"
"template <void (*T)()> class X {};\n"
"template <typename T> class Y : public X< x<T> > {};\n"
"Y<int> y;"));
}
*/
} // end namespace clang
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkMultiThreaderBase.h"
#include "itkMedianImageFilter.h"
int
main(int argc, char * argv[])
{
if (argc != 2)
{
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0];
std::cerr << " <NumberOfThreads>";
std::cerr << std::endl;
return EXIT_FAILURE;
}
const auto numberOfThreads = std::atoi(argv[1]);
itk::MultiThreaderBase::SetGlobalDefaultNumberOfThreads(numberOfThreads);
constexpr unsigned int Dimension = 2;
using PixelType = float;
using ImageType = itk::Image<PixelType, Dimension>;
using FilterType = itk::MedianImageFilter<ImageType, ImageType>;
FilterType::Pointer filter = FilterType::New();
const auto filterDefaultThreads = filter->GetMultiThreader()->GetGlobalDefaultNumberOfThreads();
std::cout << "Filter's default number of threads: " << filterDefaultThreads << std::endl;
if (filterDefaultThreads != numberOfThreads)
{
std::cerr << "Filter does not have expected default number of threads." << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>ENH: Make type sign match for comparison<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkMultiThreaderBase.h"
#include "itkMedianImageFilter.h"
int
main(int argc, char * argv[])
{
if (argc != 2)
{
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0];
std::cerr << " <NumberOfThreads>";
std::cerr << std::endl;
return EXIT_FAILURE;
}
const auto numberOfThreads = static_cast<unsigned int>(std::atoi(argv[1]));
itk::MultiThreaderBase::SetGlobalDefaultNumberOfThreads(numberOfThreads);
constexpr unsigned int Dimension = 2;
using PixelType = float;
using ImageType = itk::Image<PixelType, Dimension>;
using FilterType = itk::MedianImageFilter<ImageType, ImageType>;
FilterType::Pointer filter = FilterType::New();
const auto filterDefaultThreads = filter->GetMultiThreader()->GetGlobalDefaultNumberOfThreads();
std::cout << "Filter's default number of threads: " << filterDefaultThreads << std::endl;
if (filterDefaultThreads != numberOfThreads)
{
std::cerr << "Filter does not have expected default number of threads." << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
**
** GNU Lesser General Public License Usage
**
** 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.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "profilemanagerconfigwidget.h"
#include "profile.h"
#include <utils/detailswidget.h>
#include <QHBoxLayout>
#include <QFileDialog>
#include <QGridLayout>
#include <QLabel>
#include <QToolButton>
#include <QScrollArea>
#include <QSizePolicy>
#include <QStyle>
namespace ProjectExplorer {
namespace Internal {
ProfileManagerConfigWidget::ProfileManagerConfigWidget(Profile *p, QWidget *parent) :
ProfileConfigWidget(parent),
m_layout(new QGridLayout),
m_iconButton(new QToolButton),
m_profile(p)
{
m_layout->setMargin(0);
m_layout->setSpacing(6);
QVBoxLayout *top = new QVBoxLayout(this);
top->setMargin(0);
QScrollArea *scroll = new QScrollArea;
scroll->setFrameShape(QFrame::NoFrame);
scroll->setWidgetResizable(true);
scroll->setFocusPolicy(Qt::NoFocus);
top->addWidget(scroll);
Utils::DetailsWidget *details = new Utils::DetailsWidget;
details->setState(Utils::DetailsWidget::NoSummary);
scroll->setWidget(details);
QWidget *widget = new QWidget;
details->setWidget(widget);
QHBoxLayout *masterLayout = new QHBoxLayout(widget);
masterLayout->setSpacing(12);
QVBoxLayout *iconLayout = new QVBoxLayout;
iconLayout->addWidget(m_iconButton);
iconLayout->addStretch();
masterLayout->addLayout(iconLayout);
masterLayout->addLayout(m_layout);
discard();
connect(m_iconButton, SIGNAL(clicked()), this, SLOT(setIcon()));
}
QString ProfileManagerConfigWidget::displayName() const
{
return tr("Profiles");
}
void ProfileManagerConfigWidget::apply()
{
foreach (ProfileConfigWidget *w, m_widgets)
w->apply();
m_profile->setIconPath(m_iconPath);
}
void ProfileManagerConfigWidget::discard()
{
foreach (ProfileConfigWidget *w, m_widgets)
w->discard();
m_iconButton->setIcon(m_profile->icon());
m_iconPath = m_profile->iconPath();
}
bool ProfileManagerConfigWidget::isDirty() const
{
foreach (ProfileConfigWidget *w, m_widgets)
if (w->isDirty())
return true;
return m_profile->iconPath() != m_iconPath;
}
void ProfileManagerConfigWidget::addConfigWidget(ProjectExplorer::ProfileConfigWidget *widget)
{
Q_ASSERT(widget);
Q_ASSERT(!m_widgets.contains(widget));
connect(widget, SIGNAL(dirty()), this, SIGNAL(dirty()));
int row = m_layout->rowCount();
m_layout->addWidget(new QLabel(widget->displayName()), row, 0,
Qt::Alignment(style()->styleHint(QStyle::SH_FormLayoutLabelAlignment)));
m_layout->addWidget(widget, row, 1);
if (widget->buttonWidget())
m_layout->addWidget(widget->buttonWidget(), row, 2);
m_widgets.append(widget);
}
void ProfileManagerConfigWidget::makeReadOnly()
{
foreach (ProfileConfigWidget *w, m_widgets)
w->makeReadOnly();
m_iconButton->setEnabled(false);
}
void ProfileManagerConfigWidget::setIcon()
{
const QString path = QFileDialog::getOpenFileName(0, tr("Select Icon"), m_iconPath, tr("Images (*.png *.xpm *.jpg)"));
if (path.isEmpty())
return;
const QIcon icon = QIcon(path);
if (icon.isNull())
return;
m_iconButton->setIcon(icon);
m_iconPath = path;
emit dirty();
}
} // namespace Internal
} // namespace ProjectExplorer
<commit_msg>projectexplorer: improve spacing in profile selection dialog<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
**
** GNU Lesser General Public License Usage
**
** 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.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "profilemanagerconfigwidget.h"
#include "profile.h"
#include <utils/detailswidget.h>
#include <QHBoxLayout>
#include <QFileDialog>
#include <QGridLayout>
#include <QLabel>
#include <QToolButton>
#include <QScrollArea>
#include <QSizePolicy>
#include <QStyle>
namespace ProjectExplorer {
namespace Internal {
ProfileManagerConfigWidget::ProfileManagerConfigWidget(Profile *p, QWidget *parent) :
ProfileConfigWidget(parent),
m_layout(new QGridLayout),
m_iconButton(new QToolButton),
m_profile(p)
{
m_layout->setMargin(0);
m_layout->setSpacing(6);
m_layout->setContentsMargins(0, 0, 0, 0);
QVBoxLayout *top = new QVBoxLayout(this);
top->setMargin(0);
QScrollArea *scroll = new QScrollArea;
scroll->setFrameShape(QFrame::NoFrame);
scroll->setWidgetResizable(true);
scroll->setFocusPolicy(Qt::NoFocus);
top->addWidget(scroll);
Utils::DetailsWidget *details = new Utils::DetailsWidget;
details->setState(Utils::DetailsWidget::NoSummary);
scroll->setWidget(details);
QWidget *widget = new QWidget;
details->setWidget(widget);
QVBoxLayout *iconLayout = new QVBoxLayout;
iconLayout->addWidget(m_iconButton);
iconLayout->addStretch();
QHBoxLayout *spacer = new QHBoxLayout;
spacer->addItem(new QSpacerItem(1, 1, QSizePolicy::Fixed, QSizePolicy::MinimumExpanding));
QGridLayout *masterLayout = new QGridLayout(widget);
masterLayout->setMargin(0);
masterLayout->setContentsMargins(6, 0, 6, 0);
masterLayout->addLayout(iconLayout, 0, 0);
masterLayout->addLayout(m_layout, 0, 1);
masterLayout->addLayout(spacer, 1, 0);
discard();
connect(m_iconButton, SIGNAL(clicked()), this, SLOT(setIcon()));
}
QString ProfileManagerConfigWidget::displayName() const
{
return tr("Profiles");
}
void ProfileManagerConfigWidget::apply()
{
foreach (ProfileConfigWidget *w, m_widgets)
w->apply();
m_profile->setIconPath(m_iconPath);
}
void ProfileManagerConfigWidget::discard()
{
foreach (ProfileConfigWidget *w, m_widgets)
w->discard();
m_iconButton->setIcon(m_profile->icon());
m_iconPath = m_profile->iconPath();
}
bool ProfileManagerConfigWidget::isDirty() const
{
foreach (ProfileConfigWidget *w, m_widgets)
if (w->isDirty())
return true;
return m_profile->iconPath() != m_iconPath;
}
void ProfileManagerConfigWidget::addConfigWidget(ProjectExplorer::ProfileConfigWidget *widget)
{
Q_ASSERT(widget);
Q_ASSERT(!m_widgets.contains(widget));
connect(widget, SIGNAL(dirty()), this, SIGNAL(dirty()));
int row = m_layout->rowCount();
m_layout->addWidget(new QLabel(widget->displayName()), row, 0,
Qt::Alignment(style()->styleHint(QStyle::SH_FormLayoutLabelAlignment)));
m_layout->addWidget(widget, row, 1);
if (widget->buttonWidget())
m_layout->addWidget(widget->buttonWidget(), row, 2);
m_widgets.append(widget);
}
void ProfileManagerConfigWidget::makeReadOnly()
{
foreach (ProfileConfigWidget *w, m_widgets)
w->makeReadOnly();
m_iconButton->setEnabled(false);
}
void ProfileManagerConfigWidget::setIcon()
{
const QString path = QFileDialog::getOpenFileName(0, tr("Select Icon"), m_iconPath, tr("Images (*.png *.xpm *.jpg)"));
if (path.isEmpty())
return;
const QIcon icon = QIcon(path);
if (icon.isNull())
return;
m_iconButton->setIcon(icon);
m_iconPath = path;
emit dirty();
}
} // namespace Internal
} // namespace ProjectExplorer
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "debugview.h"
#include "debugviewwidget.h"
#include <qmldesignerplugin.h>
#include <designersettings.h>
#include <bindingproperty.h>
#include <nodeabstractproperty.h>
#include <variantproperty.h>
namespace {
const QLatin1String lineBreak = QLatin1String("<br>");
bool isDebugViewEnabled()
{
return (QmlDesigner::QmlDesignerPlugin::instance()->settings().enableDebugView);
}
bool isDebugViewShown()
{
return (QmlDesigner::QmlDesignerPlugin::instance()->settings().showDebugView);
}
}
namespace QmlDesigner {
namespace Internal {
DebugView::DebugView(QObject *parent) : QmlModelView(parent),
m_debugViewWidget(new DebugViewWidget)
{
}
DebugView::~DebugView()
{
}
void DebugView::modelAttached(Model *model)
{
log(tr("Model attached"), tr("FileName %1").arg(model->fileUrl().toLocalFile()));
m_debugViewWidget->setDebugViewEnabled(isDebugViewEnabled());
qDebug() << "enabled: " << isDebugViewEnabled();
QmlModelView::modelAttached(model);
}
void DebugView::modelAboutToBeDetached(Model *model)
{
log(tr("Model detached"), tr("FileName %1").arg(model->fileUrl().toLocalFile()));
QmlModelView::modelAboutToBeDetached(model);
}
void DebugView::importsChanged(const QList<Import> &addedImports, const QList<Import> &removedImports)
{
if (isDebugViewEnabled()) {
QString message;
message += tr("Added imports:") += lineBreak;
foreach (const Import &import, addedImports) {
message += import.toString() += lineBreak;
}
message += tr("Removed imports:") += lineBreak;
foreach (const Import &import, removedImports) {
message += import.toString() += lineBreak;
}
log(tr("Imports changed:"), message);
}
}
void DebugView::nodeCreated(const ModelNode &createdNode)
{
if (isDebugViewEnabled()) {
QTextStream message;
QString string;
message.setString(&string);
message << createdNode;
log(tr("Node created:"), message.readAll());
}
}
void DebugView::nodeAboutToBeRemoved(const ModelNode &removedNode)
{
if (isDebugViewEnabled()) {
QTextStream message;
QString string;
message.setString(&string);
message << removedNode;
log(tr("Node removed:"), message.readAll());
}
}
void DebugView::nodeReparented(const ModelNode &node, const NodeAbstractProperty &newPropertyParent,
const NodeAbstractProperty &oldPropertyParent, AbstractView::PropertyChangeFlags propertyChange)
{
if (isDebugViewEnabled()) {
QTextStream message;
QString string;
message.setString(&string);
message << node;
message << tr("New parent property:");
message << lineBreak;
message << newPropertyParent;
message << tr("Old parent property:");
message << lineBreak;
message << oldPropertyParent;
message << tr("PropertyChangeFlag");
message << lineBreak;
message << propertyChange;
log(tr("Node reparanted:"), message.readAll());
}
}
void DebugView::nodeIdChanged(const ModelNode &node, const QString &newId, const QString &oldId)
{
if (isDebugViewEnabled()) {
QTextStream message;
QString string;
message.setString(&string);
message << node;
message << tr("New Id: ") << newId << lineBreak;
message << tr("Old Id: ") << oldId << lineBreak;
log(tr("Node id changed:"), string);
}
}
void DebugView::propertiesAboutToBeRemoved(const QList<AbstractProperty> & /*propertyList*/)
{
}
void DebugView::variantPropertiesChanged(const QList<VariantProperty> &propertyList,
AbstractView::PropertyChangeFlags /*propertyChange*/)
{
if (isDebugViewEnabled()) {
QTextStream message;
QString string;
message.setString(&string);
foreach (const VariantProperty &property, propertyList) {
message << property;
}
log(tr("VariantProperties changed:"), string);
}
}
void DebugView::bindingPropertiesChanged(const QList<BindingProperty> &propertyList,
AbstractView::PropertyChangeFlags /*propertyChange*/)
{
if (isDebugViewEnabled()) {
QTextStream message;
QString string;
message.setString(&string);
foreach (const BindingProperty &property, propertyList) {
message << property;
}
log(tr("BindingProperties changed:"), string);
}
}
void DebugView::rootNodeTypeChanged(const QString &type, int majorVersion, int minorVersion)
{
if (isDebugViewEnabled()) {
QString message;
message += type;
message += QLatin1String(" ");
message += QString::number(majorVersion);
message += QLatin1String(" ");
message += QString::number(minorVersion);
log(tr("Node id changed:"), message);
}
}
void DebugView::selectedNodesChanged(const QList<ModelNode> & /*selectedNodeList*/,
const QList<ModelNode> & /*lastSelectedNodeList*/)
{
}
void DebugView::scriptFunctionsChanged(const ModelNode & /*node*/, const QStringList & /*scriptFunctionList*/)
{
}
void DebugView::propertiesRemoved(const QList<AbstractProperty> &propertyList)
{
if (isDebugViewEnabled()) {
QTextStream message;
QString string;
message.setString(&string);
foreach (const AbstractProperty &property, propertyList) {
message << property;
}
log(tr("Properties removed:"), string);
}
}
void DebugView::auxiliaryDataChanged(const ModelNode &node, const PropertyName &name, const QVariant &data)
{
if (isDebugViewEnabled()) {
QTextStream message;
QString string;
message.setString(&string);
message << node;
message << name;
message << data.toString();
log(tr("Auxiliary Data Changed:"), string);
}
}
void DebugView::rewriterBeginTransaction()
{
if (isDebugViewEnabled())
log(tr("Begin rewriter transaction"), QString(), true);
}
void DebugView::rewriterEndTransaction()
{
if (isDebugViewEnabled())
log(tr("End rewriter transaction"), QString(), true);
}
WidgetInfo DebugView::widgetInfo()
{
return createWidgetInfo(m_debugViewWidget.data(), "DebugView", WidgetInfo::LeftPane, 0, tr("Debug View"));
}
bool DebugView::hasWidget() const
{
if (isDebugViewShown())
return true;
return false;
}
void DebugView::instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > &propertyList)
{
if (isDebugViewEnabled()) {
QTextStream message;
QString string;
message.setString(&string);
typedef QPair<ModelNode, PropertyName> Pair;
foreach (const Pair &pair, propertyList) {
message << pair.first;
message << lineBreak;
message << pair.second;
}
logInstance(tr("Instance property change"), string);
}
}
void DebugView::instancesCompleted(const QVector<ModelNode> &completedNodeList)
{
if (isDebugViewEnabled()) {
QTextStream message;
QString string;
message.setString(&string);
foreach (const ModelNode &modelNode, completedNodeList) {
message << modelNode;
}
logInstance(tr("Instance Completed"), string);
}
}
void DebugView::instanceInformationsChange(const QMultiHash<ModelNode, InformationName> &informationChangeHash)
{
if (isDebugViewEnabled()) {
QTextStream message;
QString string;
message.setString(&string);
foreach (const ModelNode &modelNode, informationChangeHash.keys()) {
message << modelNode;
message << informationChangeHash.value(modelNode);
}
logInstance(tr("Instance Completed"), string);
}
}
void DebugView::instancesRenderImageChanged(const QVector<ModelNode> & /*nodeList*/)
{
}
void DebugView::instancesPreviewImageChanged(const QVector<ModelNode> & /*nodeList*/)
{
}
void DebugView::instancesChildrenChanged(const QVector<ModelNode> & /*nodeList*/)
{
}
void DebugView::customNotification(const AbstractView *view, const QString &identifier, const QList<ModelNode> &nodeList, const QList<QVariant> &data)
{
if (isDebugViewEnabled()) {
QTextStream message;
QString string;
message.setString(&string);
message << view;
message << identifier;
foreach (const ModelNode &node, nodeList) {
message << node;
}
foreach (const QVariant &variant, data) {
message << variant.toString();
}
log(tr("Custom Notification:"), string);
}
}
void DebugView::nodeSourceChanged(const ModelNode &modelNode, const QString &newNodeSource)
{
if (isDebugViewEnabled()) {
QTextStream message;
QString string;
message.setString(&string);
message << modelNode;
message << newNodeSource;
log(tr("Node Source Changed:"), string);
}
}
void DebugView::log(const QString &title, const QString &message, bool highlight)
{
m_debugViewWidget->addLogMessage(title, message, highlight);
}
void DebugView::logInstance(const QString &title, const QString &message, bool highlight)
{
m_debugViewWidget->addLogInstanceMessage(title, message, highlight);
}
} // namesapce Internal
} // namespace QmlDesigner
<commit_msg>QmlDesigner: QLatin1Fix<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "debugview.h"
#include "debugviewwidget.h"
#include <qmldesignerplugin.h>
#include <designersettings.h>
#include <bindingproperty.h>
#include <nodeabstractproperty.h>
#include <variantproperty.h>
namespace {
const QLatin1String lineBreak = QLatin1String("<br>");
bool isDebugViewEnabled()
{
return (QmlDesigner::QmlDesignerPlugin::instance()->settings().enableDebugView);
}
bool isDebugViewShown()
{
return (QmlDesigner::QmlDesignerPlugin::instance()->settings().showDebugView);
}
}
namespace QmlDesigner {
namespace Internal {
DebugView::DebugView(QObject *parent) : QmlModelView(parent),
m_debugViewWidget(new DebugViewWidget)
{
}
DebugView::~DebugView()
{
}
void DebugView::modelAttached(Model *model)
{
log(tr("Model attached"), tr("FileName %1").arg(model->fileUrl().toLocalFile()));
m_debugViewWidget->setDebugViewEnabled(isDebugViewEnabled());
qDebug() << "enabled: " << isDebugViewEnabled();
QmlModelView::modelAttached(model);
}
void DebugView::modelAboutToBeDetached(Model *model)
{
log(tr("Model detached"), tr("FileName %1").arg(model->fileUrl().toLocalFile()));
QmlModelView::modelAboutToBeDetached(model);
}
void DebugView::importsChanged(const QList<Import> &addedImports, const QList<Import> &removedImports)
{
if (isDebugViewEnabled()) {
QString message;
message += tr("Added imports:") += lineBreak;
foreach (const Import &import, addedImports) {
message += import.toString() += lineBreak;
}
message += tr("Removed imports:") += lineBreak;
foreach (const Import &import, removedImports) {
message += import.toString() += lineBreak;
}
log(tr("Imports changed:"), message);
}
}
void DebugView::nodeCreated(const ModelNode &createdNode)
{
if (isDebugViewEnabled()) {
QTextStream message;
QString string;
message.setString(&string);
message << createdNode;
log(tr("Node created:"), message.readAll());
}
}
void DebugView::nodeAboutToBeRemoved(const ModelNode &removedNode)
{
if (isDebugViewEnabled()) {
QTextStream message;
QString string;
message.setString(&string);
message << removedNode;
log(tr("Node removed:"), message.readAll());
}
}
void DebugView::nodeReparented(const ModelNode &node, const NodeAbstractProperty &newPropertyParent,
const NodeAbstractProperty &oldPropertyParent, AbstractView::PropertyChangeFlags propertyChange)
{
if (isDebugViewEnabled()) {
QTextStream message;
QString string;
message.setString(&string);
message << node;
message << tr("New parent property:");
message << lineBreak;
message << newPropertyParent;
message << tr("Old parent property:");
message << lineBreak;
message << oldPropertyParent;
message << tr("PropertyChangeFlag");
message << lineBreak;
message << propertyChange;
log(tr("Node reparanted:"), message.readAll());
}
}
void DebugView::nodeIdChanged(const ModelNode &node, const QString &newId, const QString &oldId)
{
if (isDebugViewEnabled()) {
QTextStream message;
QString string;
message.setString(&string);
message << node;
message << tr("New Id: ") << newId << lineBreak;
message << tr("Old Id: ") << oldId << lineBreak;
log(tr("Node id changed:"), string);
}
}
void DebugView::propertiesAboutToBeRemoved(const QList<AbstractProperty> & /*propertyList*/)
{
}
void DebugView::variantPropertiesChanged(const QList<VariantProperty> &propertyList,
AbstractView::PropertyChangeFlags /*propertyChange*/)
{
if (isDebugViewEnabled()) {
QTextStream message;
QString string;
message.setString(&string);
foreach (const VariantProperty &property, propertyList) {
message << property;
}
log(tr("VariantProperties changed:"), string);
}
}
void DebugView::bindingPropertiesChanged(const QList<BindingProperty> &propertyList,
AbstractView::PropertyChangeFlags /*propertyChange*/)
{
if (isDebugViewEnabled()) {
QTextStream message;
QString string;
message.setString(&string);
foreach (const BindingProperty &property, propertyList) {
message << property;
}
log(tr("BindingProperties changed:"), string);
}
}
void DebugView::rootNodeTypeChanged(const QString &type, int majorVersion, int minorVersion)
{
if (isDebugViewEnabled()) {
QString message;
message += type;
message += QLatin1String(" ");
message += QString::number(majorVersion);
message += QLatin1String(" ");
message += QString::number(minorVersion);
log(tr("Node id changed:"), message);
}
}
void DebugView::selectedNodesChanged(const QList<ModelNode> & /*selectedNodeList*/,
const QList<ModelNode> & /*lastSelectedNodeList*/)
{
}
void DebugView::scriptFunctionsChanged(const ModelNode & /*node*/, const QStringList & /*scriptFunctionList*/)
{
}
void DebugView::propertiesRemoved(const QList<AbstractProperty> &propertyList)
{
if (isDebugViewEnabled()) {
QTextStream message;
QString string;
message.setString(&string);
foreach (const AbstractProperty &property, propertyList) {
message << property;
}
log(tr("Properties removed:"), string);
}
}
void DebugView::auxiliaryDataChanged(const ModelNode &node, const PropertyName &name, const QVariant &data)
{
if (isDebugViewEnabled()) {
QTextStream message;
QString string;
message.setString(&string);
message << node;
message << name;
message << data.toString();
log(tr("Auxiliary Data Changed:"), string);
}
}
void DebugView::rewriterBeginTransaction()
{
if (isDebugViewEnabled())
log(tr("Begin rewriter transaction"), QString(), true);
}
void DebugView::rewriterEndTransaction()
{
if (isDebugViewEnabled())
log(tr("End rewriter transaction"), QString(), true);
}
WidgetInfo DebugView::widgetInfo()
{
return createWidgetInfo(m_debugViewWidget.data(), QLatin1String("DebugView"), WidgetInfo::LeftPane, 0, tr("Debug View"));
}
bool DebugView::hasWidget() const
{
if (isDebugViewShown())
return true;
return false;
}
void DebugView::instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > &propertyList)
{
if (isDebugViewEnabled()) {
QTextStream message;
QString string;
message.setString(&string);
typedef QPair<ModelNode, PropertyName> Pair;
foreach (const Pair &pair, propertyList) {
message << pair.first;
message << lineBreak;
message << pair.second;
}
logInstance(tr("Instance property change"), string);
}
}
void DebugView::instancesCompleted(const QVector<ModelNode> &completedNodeList)
{
if (isDebugViewEnabled()) {
QTextStream message;
QString string;
message.setString(&string);
foreach (const ModelNode &modelNode, completedNodeList) {
message << modelNode;
}
logInstance(tr("Instance Completed"), string);
}
}
void DebugView::instanceInformationsChange(const QMultiHash<ModelNode, InformationName> &informationChangeHash)
{
if (isDebugViewEnabled()) {
QTextStream message;
QString string;
message.setString(&string);
foreach (const ModelNode &modelNode, informationChangeHash.keys()) {
message << modelNode;
message << informationChangeHash.value(modelNode);
}
logInstance(tr("Instance Completed"), string);
}
}
void DebugView::instancesRenderImageChanged(const QVector<ModelNode> & /*nodeList*/)
{
}
void DebugView::instancesPreviewImageChanged(const QVector<ModelNode> & /*nodeList*/)
{
}
void DebugView::instancesChildrenChanged(const QVector<ModelNode> & /*nodeList*/)
{
}
void DebugView::customNotification(const AbstractView *view, const QString &identifier, const QList<ModelNode> &nodeList, const QList<QVariant> &data)
{
if (isDebugViewEnabled()) {
QTextStream message;
QString string;
message.setString(&string);
message << view;
message << identifier;
foreach (const ModelNode &node, nodeList) {
message << node;
}
foreach (const QVariant &variant, data) {
message << variant.toString();
}
log(tr("Custom Notification:"), string);
}
}
void DebugView::nodeSourceChanged(const ModelNode &modelNode, const QString &newNodeSource)
{
if (isDebugViewEnabled()) {
QTextStream message;
QString string;
message.setString(&string);
message << modelNode;
message << newNodeSource;
log(tr("Node Source Changed:"), string);
}
}
void DebugView::log(const QString &title, const QString &message, bool highlight)
{
m_debugViewWidget->addLogMessage(title, message, highlight);
}
void DebugView::logInstance(const QString &title, const QString &message, bool highlight)
{
m_debugViewWidget->addLogInstanceMessage(title, message, highlight);
}
} // namesapce Internal
} // namespace QmlDesigner
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Creator.
**
** $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 Technology Preview License Agreement accompanying
** this package.
**
** 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.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "maemoruncontrol.h"
#include "maemopackagecreationstep.h"
#include "maemosshthread.h"
#include "maemorunconfiguration.h"
#include <coreplugin/icore.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <debugger/debuggermanager.h>
#include <extensionsystem/pluginmanager.h>
#include <projectexplorer/toolchain.h>
#include <utils/qtcassert.h>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QFuture>
#include <QtCore/QProcess>
#include <QtCore/QStringBuilder>
#include <QtGui/QMessageBox>
namespace Qt4ProjectManager {
namespace Internal {
using ProjectExplorer::RunConfiguration;
using ProjectExplorer::ToolChain;
AbstractMaemoRunControl::AbstractMaemoRunControl(RunConfiguration *rc)
: RunControl(rc)
, m_runConfig(qobject_cast<MaemoRunConfiguration *>(rc))
, m_devConfig(m_runConfig ? m_runConfig->deviceConfig() : MaemoDeviceConfig())
{
}
AbstractMaemoRunControl::~AbstractMaemoRunControl()
{
}
void AbstractMaemoRunControl::start()
{
m_stoppedByUser = false;
if (!m_devConfig.isValid()) {
handleError(tr("No device configuration set for run configuration."));
} else {
emit started();
startInitialCleanup();
}
}
void AbstractMaemoRunControl::startInitialCleanup()
{
emit appendMessage(this, tr("Cleaning up remote leftovers first ..."), false);
const QStringList appsToKill
= QStringList() << executableFileName() << QLatin1String("gdbserver");
killRemoteProcesses(appsToKill, true);
}
void AbstractMaemoRunControl::stop()
{
m_stoppedByUser = true;
if (isCleaning())
m_initialCleaner->stop();
else if (isDeploying())
m_sshDeployer->stop();
else
stopInternal();
}
void AbstractMaemoRunControl::handleInitialCleanupFinished()
{
if (m_stoppedByUser) {
emit appendMessage(this, tr("Initial cleanup canceled by user."), false);
emit finished();
} else if (m_initialCleaner->hasError()) {
handleError(tr("Error running initial cleanup: %1.")
.arg(m_initialCleaner->error()));
emit finished();
} else {
emit appendMessage(this, tr("Initial cleanup done."), false);
startInternal();
}
}
void AbstractMaemoRunControl::startDeployment(bool forDebugging)
{
QTC_ASSERT(m_runConfig, return);
if (m_stoppedByUser) {
emit finished();
} else {
m_deployables.clear();
if (m_runConfig->currentlyNeedsDeployment(m_devConfig.server.host)) {
m_deployables.append(Deployable(packageFileName(),
QFileInfo(executableOnHost()).canonicalPath(),
&MaemoRunConfiguration::wasDeployed));
m_needsInstall = true;
} else {
m_needsInstall = false;
}
if (forDebugging
&& m_runConfig->debuggingHelpersNeedDeployment(m_devConfig.server.host)) {
const QFileInfo &info(m_runConfig->dumperLib());
m_deployables.append(Deployable(info.fileName(), info.canonicalPath(),
&MaemoRunConfiguration::debuggingHelpersDeployed));
}
deploy();
}
}
void AbstractMaemoRunControl::deploy()
{
Core::ICore::instance()->progressManager()
->addTask(m_progress.future(), tr("Deploying"),
QLatin1String("Maemo.Deploy"));
if (!m_deployables.isEmpty()) {
QList<Core::SftpTransferInfo> deploySpecs;
QStringList files;
foreach (const Deployable &deployable, m_deployables) {
const QString srcFilePath
= deployable.dir % QDir::separator() % deployable.fileName;
const QString tgtFilePath
= remoteDir() % QDir::separator() % deployable.fileName;
files << srcFilePath;
deploySpecs << Core::SftpTransferInfo(srcFilePath,
tgtFilePath.toUtf8(), Core::SftpTransferInfo::Upload);
}
emit appendMessage(this, tr("Files to deploy: %1.").arg(files.join(" ")), false);
m_sshDeployer.reset(new MaemoSshDeployer(m_devConfig.server, deploySpecs));
connect(m_sshDeployer.data(), SIGNAL(finished()),
this, SLOT(handleDeployThreadFinished()));
connect(m_sshDeployer.data(), SIGNAL(fileCopied(QString)),
this, SLOT(handleFileCopied()));
m_progress.setProgressRange(0, m_deployables.count());
m_progress.setProgressValue(0);
m_progress.reportStarted();
m_sshDeployer->start();
} else {
m_progress.reportFinished();
startExecution();
}
}
void AbstractMaemoRunControl::handleFileCopied()
{
Deployable deployable = m_deployables.takeFirst();
(m_runConfig->*deployable.updateTimestamp)(m_devConfig.server.host);
m_progress.setProgressValue(m_progress.progressValue() + 1);
}
bool AbstractMaemoRunControl::isDeploying() const
{
return m_sshDeployer && m_sshDeployer->isRunning();
}
QString AbstractMaemoRunControl::packageFileName() const
{
return QFileInfo(packageFilePath()).fileName();
}
QString AbstractMaemoRunControl::packageFilePath() const
{
return m_runConfig->packageStep()->packageFilePath();
}
QString AbstractMaemoRunControl::executableFilePathOnTarget() const
{
return m_runConfig->packageStep()->remoteExecutableFilePath();
}
bool AbstractMaemoRunControl::isCleaning() const
{
return m_initialCleaner && m_initialCleaner->isRunning();
}
void AbstractMaemoRunControl::startExecution()
{
m_sshRunner.reset(new MaemoSshRunner(m_devConfig.server, remoteCall()));
connect(m_sshRunner.data(), SIGNAL(finished()),
this, SLOT(handleRunThreadFinished()));
connect(m_sshRunner.data(), SIGNAL(remoteOutput(QString)),
this, SLOT(handleRemoteOutput(QString)));
emit appendMessage(this, tr("Starting remote application."), false);
m_sshRunner->start();
}
bool AbstractMaemoRunControl::isRunning() const
{
return isDeploying() || (m_sshRunner && m_sshRunner->isRunning());
}
void AbstractMaemoRunControl::stopRunning(bool forDebugging)
{
if (m_sshRunner && m_sshRunner->isRunning()) {
m_sshRunner->stop();
QStringList apps(executableFileName());
if (forDebugging)
apps << QLatin1String("gdbserver");
killRemoteProcesses(apps, false);
}
}
void AbstractMaemoRunControl::killRemoteProcesses(const QStringList &apps,
bool initialCleanup)
{
QString niceKill;
QString brutalKill;
foreach (const QString &app, apps) {
niceKill += QString::fromLocal8Bit("pkill -x %1;").arg(app);
brutalKill += QString::fromLocal8Bit("pkill -x -9 %1;").arg(app);
}
QString remoteCall = niceKill + QLatin1String("sleep 1; ") + brutalKill;
remoteCall.remove(remoteCall.count() - 1, 1); // Get rid of trailing semicolon.
QScopedPointer<MaemoSshRunner> &runner
= initialCleanup ? m_initialCleaner : m_sshStopper;
runner.reset(new MaemoSshRunner(m_devConfig.server, remoteCall));
if (initialCleanup)
connect(runner.data(), SIGNAL(finished()),
this, SLOT(handleInitialCleanupFinished()));
runner->start();
}
void AbstractMaemoRunControl::handleDeployThreadFinished()
{
bool cancel;
if (m_stoppedByUser) {
emit appendMessage(this, tr("Deployment canceled by user."), false);
cancel = true;
} else if (m_sshDeployer->hasError()) {
handleError(tr("Deployment failed: %1").arg(m_sshDeployer->error()));
cancel = true;
} else {
emit appendMessage(this, tr("Deployment finished."), false);
cancel = false;
}
if (cancel) {
m_progress.reportCanceled();
m_progress.reportFinished();
emit finished();
} else {
m_progress.reportFinished();
startExecution();
}
}
void AbstractMaemoRunControl::handleRunThreadFinished()
{
if (m_stoppedByUser) {
emit appendMessage(this,
tr("Remote execution canceled due to user request."),
false);
} else if (m_sshRunner->hasError()) {
emit appendMessage(this, tr("Error running remote process: %1")
.arg(m_sshRunner->error()),
true);
} else {
emit appendMessage(this, tr("Finished running remote process."),
false);
}
emit finished();
}
const QString AbstractMaemoRunControl::executableOnHost() const
{
return m_runConfig->executable();
}
const QString AbstractMaemoRunControl::executableFileName() const
{
return QFileInfo(executableOnHost()).fileName();
}
const QString AbstractMaemoRunControl::remoteDir() const
{
return homeDirOnDevice(m_devConfig.server.uname);
}
QString AbstractMaemoRunControl::remoteSudo() const
{
return QLatin1String("/usr/lib/mad-developer/devrootsh");
}
QString AbstractMaemoRunControl::remoteInstallCommand() const
{
return QString::fromLocal8Bit("%1 dpkg -i %2").arg(remoteSudo())
.arg(packageFileName());
}
const QString AbstractMaemoRunControl::targetCmdLinePrefix() const
{
const QString &installPrefix = m_needsInstall
? remoteInstallCommand() + QLatin1String(" && ")
: QString();
return QString::fromLocal8Bit("%1%2 chmod u+x %3 && source /etc/profile && ")
.arg(installPrefix).arg(remoteSudo()).arg(executableFilePathOnTarget());
}
QString AbstractMaemoRunControl::targetCmdLineSuffix() const
{
return m_runConfig->arguments().join(" ");
}
void AbstractMaemoRunControl::handleError(const QString &errString)
{
QMessageBox::critical(0, tr("Remote Execution Failure"), errString);
emit appendMessage(this, errString, true);
}
MaemoRunControl::MaemoRunControl(RunConfiguration *runConfiguration)
: AbstractMaemoRunControl(runConfiguration)
{
}
MaemoRunControl::~MaemoRunControl()
{
stop();
}
void MaemoRunControl::startInternal()
{
startDeployment(false);
}
QString MaemoRunControl::remoteCall() const
{
return QString::fromLocal8Bit("%1 %2 %3").arg(targetCmdLinePrefix())
.arg(executableFilePathOnTarget()).arg(targetCmdLineSuffix());
}
void MaemoRunControl::stopInternal()
{
AbstractMaemoRunControl::stopRunning(false);
}
void MaemoRunControl::handleRemoteOutput(const QString &output)
{
emit addToOutputWindowInline(this, output, false);
}
MaemoDebugRunControl::MaemoDebugRunControl(RunConfiguration *runConfiguration)
: AbstractMaemoRunControl(runConfiguration)
, m_debuggerManager(ExtensionSystem::PluginManager::instance()
->getObject<Debugger::DebuggerManager>())
, m_startParams(new Debugger::DebuggerStartParameters)
{
QTC_ASSERT(m_debuggerManager != 0, return);
m_startParams->startMode = Debugger::StartRemote;
m_startParams->executable = executableOnHost();
m_startParams->remoteChannel
= m_devConfig.server.host % QLatin1Char(':') % gdbServerPort();
m_startParams->remoteArchitecture = QLatin1String("arm");
m_startParams->sysRoot = m_runConfig->sysRoot();
m_startParams->toolChainType = ToolChain::GCC_MAEMO;
m_startParams->debuggerCommand = m_runConfig->gdbCmd();
m_startParams->dumperLibrary = m_runConfig->dumperLib();
m_startParams->remoteDumperLib = QString::fromLocal8Bit("%1/%2")
.arg(remoteDir()).arg(QFileInfo(m_runConfig->dumperLib()).fileName());
connect(m_debuggerManager, SIGNAL(debuggingFinished()), this,
SLOT(debuggingFinished()), Qt::QueuedConnection);
connect(m_debuggerManager, SIGNAL(applicationOutputAvailable(QString, bool)),
this, SLOT(debuggerOutput(QString)), Qt::QueuedConnection);
}
MaemoDebugRunControl::~MaemoDebugRunControl()
{
disconnect(SIGNAL(addToOutputWindow(RunControl*,QString, bool)));
disconnect(SIGNAL(addToOutputWindowInline(RunControl*,QString, bool)));
stop();
debuggingFinished();
}
void MaemoDebugRunControl::startInternal()
{
m_debuggingStarted = false;
startDeployment(true);
}
QString MaemoDebugRunControl::remoteCall() const
{
return QString::fromLocal8Bit("%1 gdbserver :%2 %3 %4")
.arg(targetCmdLinePrefix()).arg(gdbServerPort())
.arg(executableFilePathOnTarget()).arg(targetCmdLineSuffix());
}
void MaemoDebugRunControl::handleRemoteOutput(const QString &output)
{
if (!m_debuggingStarted) {
m_debuggingStarted = true;
startDebugging();
}
emit addToOutputWindowInline(this, output, false);
}
void MaemoDebugRunControl::startDebugging()
{
m_debuggerManager->startNewDebugger(m_startParams);
}
void MaemoDebugRunControl::stopInternal()
{
m_debuggerManager->exitDebugger();
}
bool MaemoDebugRunControl::isRunning() const
{
return AbstractMaemoRunControl::isRunning()
|| m_debuggerManager->state() != Debugger::DebuggerNotReady;
}
void MaemoDebugRunControl::debuggingFinished()
{
AbstractMaemoRunControl::stopRunning(true);
}
void MaemoDebugRunControl::debuggerOutput(const QString &output)
{
emit appendMessage(this, QLatin1String("[gdb says:] ") + output, true);
}
QString MaemoDebugRunControl::gdbServerPort() const
{
return m_devConfig.type == MaemoDeviceConfig::Physical
? QString::number(m_devConfig.gdbServerPort)
: m_runConfig->simulatorGdbServerPort();
}
} // namespace Internal
} // namespace Qt4ProjectManager
<commit_msg>Maemo: Set DISPLAY variable before running remote executable.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Creator.
**
** $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 Technology Preview License Agreement accompanying
** this package.
**
** 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.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "maemoruncontrol.h"
#include "maemopackagecreationstep.h"
#include "maemosshthread.h"
#include "maemorunconfiguration.h"
#include <coreplugin/icore.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <debugger/debuggermanager.h>
#include <extensionsystem/pluginmanager.h>
#include <projectexplorer/toolchain.h>
#include <utils/qtcassert.h>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QFuture>
#include <QtCore/QProcess>
#include <QtCore/QStringBuilder>
#include <QtGui/QMessageBox>
namespace Qt4ProjectManager {
namespace Internal {
using ProjectExplorer::RunConfiguration;
using ProjectExplorer::ToolChain;
AbstractMaemoRunControl::AbstractMaemoRunControl(RunConfiguration *rc)
: RunControl(rc)
, m_runConfig(qobject_cast<MaemoRunConfiguration *>(rc))
, m_devConfig(m_runConfig ? m_runConfig->deviceConfig() : MaemoDeviceConfig())
{
}
AbstractMaemoRunControl::~AbstractMaemoRunControl()
{
}
void AbstractMaemoRunControl::start()
{
m_stoppedByUser = false;
if (!m_devConfig.isValid()) {
handleError(tr("No device configuration set for run configuration."));
} else {
emit started();
startInitialCleanup();
}
}
void AbstractMaemoRunControl::startInitialCleanup()
{
emit appendMessage(this, tr("Cleaning up remote leftovers first ..."), false);
const QStringList appsToKill
= QStringList() << executableFileName() << QLatin1String("gdbserver");
killRemoteProcesses(appsToKill, true);
}
void AbstractMaemoRunControl::stop()
{
m_stoppedByUser = true;
if (isCleaning())
m_initialCleaner->stop();
else if (isDeploying())
m_sshDeployer->stop();
else
stopInternal();
}
void AbstractMaemoRunControl::handleInitialCleanupFinished()
{
if (m_stoppedByUser) {
emit appendMessage(this, tr("Initial cleanup canceled by user."), false);
emit finished();
} else if (m_initialCleaner->hasError()) {
handleError(tr("Error running initial cleanup: %1.")
.arg(m_initialCleaner->error()));
emit finished();
} else {
emit appendMessage(this, tr("Initial cleanup done."), false);
startInternal();
}
}
void AbstractMaemoRunControl::startDeployment(bool forDebugging)
{
QTC_ASSERT(m_runConfig, return);
if (m_stoppedByUser) {
emit finished();
} else {
m_deployables.clear();
if (m_runConfig->currentlyNeedsDeployment(m_devConfig.server.host)) {
m_deployables.append(Deployable(packageFileName(),
QFileInfo(executableOnHost()).canonicalPath(),
&MaemoRunConfiguration::wasDeployed));
m_needsInstall = true;
} else {
m_needsInstall = false;
}
if (forDebugging
&& m_runConfig->debuggingHelpersNeedDeployment(m_devConfig.server.host)) {
const QFileInfo &info(m_runConfig->dumperLib());
m_deployables.append(Deployable(info.fileName(), info.canonicalPath(),
&MaemoRunConfiguration::debuggingHelpersDeployed));
}
deploy();
}
}
void AbstractMaemoRunControl::deploy()
{
Core::ICore::instance()->progressManager()
->addTask(m_progress.future(), tr("Deploying"),
QLatin1String("Maemo.Deploy"));
if (!m_deployables.isEmpty()) {
QList<Core::SftpTransferInfo> deploySpecs;
QStringList files;
foreach (const Deployable &deployable, m_deployables) {
const QString srcFilePath
= deployable.dir % QDir::separator() % deployable.fileName;
const QString tgtFilePath
= remoteDir() % QDir::separator() % deployable.fileName;
files << srcFilePath;
deploySpecs << Core::SftpTransferInfo(srcFilePath,
tgtFilePath.toUtf8(), Core::SftpTransferInfo::Upload);
}
emit appendMessage(this, tr("Files to deploy: %1.").arg(files.join(" ")), false);
m_sshDeployer.reset(new MaemoSshDeployer(m_devConfig.server, deploySpecs));
connect(m_sshDeployer.data(), SIGNAL(finished()),
this, SLOT(handleDeployThreadFinished()));
connect(m_sshDeployer.data(), SIGNAL(fileCopied(QString)),
this, SLOT(handleFileCopied()));
m_progress.setProgressRange(0, m_deployables.count());
m_progress.setProgressValue(0);
m_progress.reportStarted();
m_sshDeployer->start();
} else {
m_progress.reportFinished();
startExecution();
}
}
void AbstractMaemoRunControl::handleFileCopied()
{
Deployable deployable = m_deployables.takeFirst();
(m_runConfig->*deployable.updateTimestamp)(m_devConfig.server.host);
m_progress.setProgressValue(m_progress.progressValue() + 1);
}
bool AbstractMaemoRunControl::isDeploying() const
{
return m_sshDeployer && m_sshDeployer->isRunning();
}
QString AbstractMaemoRunControl::packageFileName() const
{
return QFileInfo(packageFilePath()).fileName();
}
QString AbstractMaemoRunControl::packageFilePath() const
{
return m_runConfig->packageStep()->packageFilePath();
}
QString AbstractMaemoRunControl::executableFilePathOnTarget() const
{
return m_runConfig->packageStep()->remoteExecutableFilePath();
}
bool AbstractMaemoRunControl::isCleaning() const
{
return m_initialCleaner && m_initialCleaner->isRunning();
}
void AbstractMaemoRunControl::startExecution()
{
m_sshRunner.reset(new MaemoSshRunner(m_devConfig.server, remoteCall()));
connect(m_sshRunner.data(), SIGNAL(finished()),
this, SLOT(handleRunThreadFinished()));
connect(m_sshRunner.data(), SIGNAL(remoteOutput(QString)),
this, SLOT(handleRemoteOutput(QString)));
emit appendMessage(this, tr("Starting remote application."), false);
m_sshRunner->start();
}
bool AbstractMaemoRunControl::isRunning() const
{
return isDeploying() || (m_sshRunner && m_sshRunner->isRunning());
}
void AbstractMaemoRunControl::stopRunning(bool forDebugging)
{
if (m_sshRunner && m_sshRunner->isRunning()) {
m_sshRunner->stop();
QStringList apps(executableFileName());
if (forDebugging)
apps << QLatin1String("gdbserver");
killRemoteProcesses(apps, false);
}
}
void AbstractMaemoRunControl::killRemoteProcesses(const QStringList &apps,
bool initialCleanup)
{
QString niceKill;
QString brutalKill;
foreach (const QString &app, apps) {
niceKill += QString::fromLocal8Bit("pkill -x %1;").arg(app);
brutalKill += QString::fromLocal8Bit("pkill -x -9 %1;").arg(app);
}
QString remoteCall = niceKill + QLatin1String("sleep 1; ") + brutalKill;
remoteCall.remove(remoteCall.count() - 1, 1); // Get rid of trailing semicolon.
QScopedPointer<MaemoSshRunner> &runner
= initialCleanup ? m_initialCleaner : m_sshStopper;
runner.reset(new MaemoSshRunner(m_devConfig.server, remoteCall));
if (initialCleanup)
connect(runner.data(), SIGNAL(finished()),
this, SLOT(handleInitialCleanupFinished()));
runner->start();
}
void AbstractMaemoRunControl::handleDeployThreadFinished()
{
bool cancel;
if (m_stoppedByUser) {
emit appendMessage(this, tr("Deployment canceled by user."), false);
cancel = true;
} else if (m_sshDeployer->hasError()) {
handleError(tr("Deployment failed: %1").arg(m_sshDeployer->error()));
cancel = true;
} else {
emit appendMessage(this, tr("Deployment finished."), false);
cancel = false;
}
if (cancel) {
m_progress.reportCanceled();
m_progress.reportFinished();
emit finished();
} else {
m_progress.reportFinished();
startExecution();
}
}
void AbstractMaemoRunControl::handleRunThreadFinished()
{
if (m_stoppedByUser) {
emit appendMessage(this,
tr("Remote execution canceled due to user request."),
false);
} else if (m_sshRunner->hasError()) {
emit appendMessage(this, tr("Error running remote process: %1")
.arg(m_sshRunner->error()),
true);
} else {
emit appendMessage(this, tr("Finished running remote process."),
false);
}
emit finished();
}
const QString AbstractMaemoRunControl::executableOnHost() const
{
return m_runConfig->executable();
}
const QString AbstractMaemoRunControl::executableFileName() const
{
return QFileInfo(executableOnHost()).fileName();
}
const QString AbstractMaemoRunControl::remoteDir() const
{
return homeDirOnDevice(m_devConfig.server.uname);
}
QString AbstractMaemoRunControl::remoteSudo() const
{
return QLatin1String("/usr/lib/mad-developer/devrootsh");
}
QString AbstractMaemoRunControl::remoteInstallCommand() const
{
return QString::fromLocal8Bit("%1 dpkg -i %2").arg(remoteSudo())
.arg(packageFileName());
}
const QString AbstractMaemoRunControl::targetCmdLinePrefix() const
{
const QString &installPrefix = m_needsInstall
? remoteInstallCommand() + QLatin1String(" && ")
: QString();
return QString::fromLocal8Bit("%1%2 chmod a+x %3 && source /etc/profile && DISPLAY=:0.0 ")
.arg(installPrefix).arg(remoteSudo()).arg(executableFilePathOnTarget());
}
QString AbstractMaemoRunControl::targetCmdLineSuffix() const
{
return m_runConfig->arguments().join(" ");
}
void AbstractMaemoRunControl::handleError(const QString &errString)
{
QMessageBox::critical(0, tr("Remote Execution Failure"), errString);
emit appendMessage(this, errString, true);
}
MaemoRunControl::MaemoRunControl(RunConfiguration *runConfiguration)
: AbstractMaemoRunControl(runConfiguration)
{
}
MaemoRunControl::~MaemoRunControl()
{
stop();
}
void MaemoRunControl::startInternal()
{
startDeployment(false);
}
QString MaemoRunControl::remoteCall() const
{
return QString::fromLocal8Bit("%1 %2 %3").arg(targetCmdLinePrefix())
.arg(executableFilePathOnTarget()).arg(targetCmdLineSuffix());
}
void MaemoRunControl::stopInternal()
{
AbstractMaemoRunControl::stopRunning(false);
}
void MaemoRunControl::handleRemoteOutput(const QString &output)
{
emit addToOutputWindowInline(this, output, false);
}
MaemoDebugRunControl::MaemoDebugRunControl(RunConfiguration *runConfiguration)
: AbstractMaemoRunControl(runConfiguration)
, m_debuggerManager(ExtensionSystem::PluginManager::instance()
->getObject<Debugger::DebuggerManager>())
, m_startParams(new Debugger::DebuggerStartParameters)
{
QTC_ASSERT(m_debuggerManager != 0, return);
m_startParams->startMode = Debugger::StartRemote;
m_startParams->executable = executableOnHost();
m_startParams->remoteChannel
= m_devConfig.server.host % QLatin1Char(':') % gdbServerPort();
m_startParams->remoteArchitecture = QLatin1String("arm");
m_startParams->sysRoot = m_runConfig->sysRoot();
m_startParams->toolChainType = ToolChain::GCC_MAEMO;
m_startParams->debuggerCommand = m_runConfig->gdbCmd();
m_startParams->dumperLibrary = m_runConfig->dumperLib();
m_startParams->remoteDumperLib = QString::fromLocal8Bit("%1/%2")
.arg(remoteDir()).arg(QFileInfo(m_runConfig->dumperLib()).fileName());
connect(m_debuggerManager, SIGNAL(debuggingFinished()), this,
SLOT(debuggingFinished()), Qt::QueuedConnection);
connect(m_debuggerManager, SIGNAL(applicationOutputAvailable(QString, bool)),
this, SLOT(debuggerOutput(QString)), Qt::QueuedConnection);
}
MaemoDebugRunControl::~MaemoDebugRunControl()
{
disconnect(SIGNAL(addToOutputWindow(RunControl*,QString, bool)));
disconnect(SIGNAL(addToOutputWindowInline(RunControl*,QString, bool)));
stop();
debuggingFinished();
}
void MaemoDebugRunControl::startInternal()
{
m_debuggingStarted = false;
startDeployment(true);
}
QString MaemoDebugRunControl::remoteCall() const
{
return QString::fromLocal8Bit("%1 gdbserver :%2 %3 %4")
.arg(targetCmdLinePrefix()).arg(gdbServerPort())
.arg(executableFilePathOnTarget()).arg(targetCmdLineSuffix());
}
void MaemoDebugRunControl::handleRemoteOutput(const QString &output)
{
if (!m_debuggingStarted) {
m_debuggingStarted = true;
startDebugging();
}
emit addToOutputWindowInline(this, output, false);
}
void MaemoDebugRunControl::startDebugging()
{
m_debuggerManager->startNewDebugger(m_startParams);
}
void MaemoDebugRunControl::stopInternal()
{
m_debuggerManager->exitDebugger();
}
bool MaemoDebugRunControl::isRunning() const
{
return AbstractMaemoRunControl::isRunning()
|| m_debuggerManager->state() != Debugger::DebuggerNotReady;
}
void MaemoDebugRunControl::debuggingFinished()
{
AbstractMaemoRunControl::stopRunning(true);
}
void MaemoDebugRunControl::debuggerOutput(const QString &output)
{
emit appendMessage(this, QLatin1String("[gdb says:] ") + output, true);
}
QString MaemoDebugRunControl::gdbServerPort() const
{
return m_devConfig.type == MaemoDeviceConfig::Physical
? QString::number(m_devConfig.gdbServerPort)
: m_runConfig->simulatorGdbServerPort();
}
} // namespace Internal
} // namespace Qt4ProjectManager
<|endoftext|> |
<commit_before>/* This file is part of the KDE project.
Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
This library is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 2.1 or 3 of the License.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "utils.h"
#include <e32std.h>
QT_BEGIN_NAMESPACE
using namespace Phonon;
using namespace Phonon::MMF;
/*! \class MMF::Utils
\internal
*/
/*! \class MMF::TTraceContext
\internal
*/
/*! \class MMF::Utils
\internal
*/
_LIT(PanicCategory, "Phonon::MMF");
void MMF::Utils::panic(PanicCode code)
{
User::Panic(PanicCategory, code);
}
static const TInt KMimePrefixLength = 6; // either "audio/" or "video/"
_LIT(KMimePrefixAudio, "audio/");
_LIT(KMimePrefixVideo, "video/");
MMF::MediaType MMF::Utils::mimeTypeToMediaType(const TDesC& mimeType)
{
MediaType result = MediaTypeUnknown;
if (mimeType.Left(KMimePrefixLength).Compare(KMimePrefixAudio) == 0) {
result = MediaTypeAudio;
} else if (mimeType.Left(KMimePrefixLength).Compare(KMimePrefixVideo) == 0) {
result = MediaTypeVideo;
}
return result;
}
#ifdef _DEBUG
#include <hal.h>
#include <hal_data.h>
#include <gdi.h>
#include <eikenv.h>
struct TScreenInfo
{
int width;
int height;
int bpp;
const char* address;
int initialOffset;
int lineOffset;
TDisplayMode displayMode;
};
static void getScreenInfoL(TScreenInfo& info)
{
info.displayMode = CEikonEnv::Static()->ScreenDevice()->DisplayMode();
// Then we must set these as the input parameter
info.width = info.displayMode;
info.height = info.displayMode;
info.initialOffset = info.displayMode;
info.lineOffset = info.displayMode;
info.bpp = info.displayMode;
User::LeaveIfError( HAL::Get(HALData::EDisplayXPixels, info.width) );
User::LeaveIfError( HAL::Get(HALData::EDisplayYPixels, info.width) );
int address;
User::LeaveIfError( HAL::Get(HALData::EDisplayMemoryAddress, address) );
info.address = reinterpret_cast<const char*>(address);
User::LeaveIfError( HAL::Get(HALData::EDisplayOffsetToFirstPixel, info.initialOffset) );
User::LeaveIfError( HAL::Get(HALData::EDisplayOffsetBetweenLines, info.lineOffset) );
User::LeaveIfError( HAL::Get(HALData::EDisplayBitsPerPixel, info.bpp) );
}
QColor MMF::Utils::getScreenPixel(const QPoint& pos)
{
TScreenInfo info;
TRAPD(err, getScreenInfoL(info));
QColor pixel;
if(err == KErrNone and pos.x() < info.width and pos.y() < info.height)
{
const int bytesPerPixel = info.bpp / 8;
Q_ASSERT(bytesPerPixel >= 3);
const int stride = (info.width * bytesPerPixel) + info.lineOffset;
const char* ptr =
info.address
+ info.initialOffset
+ pos.y() * stride
+ pos.x() * bytesPerPixel;
// BGRA
pixel.setBlue(*ptr++);
pixel.setGreen(*ptr++);
pixel.setRed(*ptr++);
if(bytesPerPixel == 4)
pixel.setAlpha(*ptr++);
}
return pixel;
}
// Debugging: for debugging video visibility
void MMF::Utils::dumpScreenPixelSample()
{
for(int i=0; i<20; ++i) {
const QPoint pos(i*10, i*10);
const QColor pixel = Utils::getScreenPixel(pos);
RDebug::Printf(
"Phonon::MMF::Utils::dumpScreenPixelSample %d %d = %d %d %d %d",
pos.x(), pos.y(), pixel.red(), pixel.green(), pixel.blue(), pixel.alpha()
);
}
}
#endif // _DEBUG
QT_END_NAMESPACE
<commit_msg>qdoc: Marked some undocumented Phonon classes internal<commit_after>/* This file is part of the KDE project.
Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
This library is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 2.1 or 3 of the License.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "utils.h"
#include <e32std.h>
QT_BEGIN_NAMESPACE
using namespace Phonon;
using namespace Phonon::MMF;
/*! \namespace MMF::Utils
\internal
*/
/*! \class MMF::TTraceContext
\internal
*/
/*! \class MMF::Utils
\internal
*/
_LIT(PanicCategory, "Phonon::MMF");
void MMF::Utils::panic(PanicCode code)
{
User::Panic(PanicCategory, code);
}
static const TInt KMimePrefixLength = 6; // either "audio/" or "video/"
_LIT(KMimePrefixAudio, "audio/");
_LIT(KMimePrefixVideo, "video/");
MMF::MediaType MMF::Utils::mimeTypeToMediaType(const TDesC& mimeType)
{
MediaType result = MediaTypeUnknown;
if (mimeType.Left(KMimePrefixLength).Compare(KMimePrefixAudio) == 0) {
result = MediaTypeAudio;
} else if (mimeType.Left(KMimePrefixLength).Compare(KMimePrefixVideo) == 0) {
result = MediaTypeVideo;
}
return result;
}
#ifdef _DEBUG
#include <hal.h>
#include <hal_data.h>
#include <gdi.h>
#include <eikenv.h>
struct TScreenInfo
{
int width;
int height;
int bpp;
const char* address;
int initialOffset;
int lineOffset;
TDisplayMode displayMode;
};
static void getScreenInfoL(TScreenInfo& info)
{
info.displayMode = CEikonEnv::Static()->ScreenDevice()->DisplayMode();
// Then we must set these as the input parameter
info.width = info.displayMode;
info.height = info.displayMode;
info.initialOffset = info.displayMode;
info.lineOffset = info.displayMode;
info.bpp = info.displayMode;
User::LeaveIfError( HAL::Get(HALData::EDisplayXPixels, info.width) );
User::LeaveIfError( HAL::Get(HALData::EDisplayYPixels, info.width) );
int address;
User::LeaveIfError( HAL::Get(HALData::EDisplayMemoryAddress, address) );
info.address = reinterpret_cast<const char*>(address);
User::LeaveIfError( HAL::Get(HALData::EDisplayOffsetToFirstPixel, info.initialOffset) );
User::LeaveIfError( HAL::Get(HALData::EDisplayOffsetBetweenLines, info.lineOffset) );
User::LeaveIfError( HAL::Get(HALData::EDisplayBitsPerPixel, info.bpp) );
}
QColor MMF::Utils::getScreenPixel(const QPoint& pos)
{
TScreenInfo info;
TRAPD(err, getScreenInfoL(info));
QColor pixel;
if(err == KErrNone and pos.x() < info.width and pos.y() < info.height)
{
const int bytesPerPixel = info.bpp / 8;
Q_ASSERT(bytesPerPixel >= 3);
const int stride = (info.width * bytesPerPixel) + info.lineOffset;
const char* ptr =
info.address
+ info.initialOffset
+ pos.y() * stride
+ pos.x() * bytesPerPixel;
// BGRA
pixel.setBlue(*ptr++);
pixel.setGreen(*ptr++);
pixel.setRed(*ptr++);
if(bytesPerPixel == 4)
pixel.setAlpha(*ptr++);
}
return pixel;
}
// Debugging: for debugging video visibility
void MMF::Utils::dumpScreenPixelSample()
{
for(int i=0; i<20; ++i) {
const QPoint pos(i*10, i*10);
const QColor pixel = Utils::getScreenPixel(pos);
RDebug::Printf(
"Phonon::MMF::Utils::dumpScreenPixelSample %d %d = %d %d %d %d",
pos.x(), pos.y(), pixel.red(), pixel.green(), pixel.blue(), pixel.alpha()
);
}
}
#endif // _DEBUG
QT_END_NAMESPACE
<|endoftext|> |
<commit_before>#ifndef __ACTION_HLS_NVME_MEMCOPY_H__
#define __ACTION_HLS_NVME_MEMCOPY_H__
/*
* Copyright 2017 International Business Machines
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdint.h>
#include <string.h>
#include <ap_int.h>
#include "hls_snap.H"
#include <action_nvme_memcopy.h> /* Memcopy Job definition */
#define RELEASE_LEVEL 0x00000001
#define MAX_NB_OF_BYTES_READ (256 * 1024)
#define SSD_BLOCK_SIZE 512
#define SSD_BLOCK_SIZE_SHIFT 9
#define MAX_SSD_BLOCK_XFER 128
//The NVMe subsystem can handle up to 218 read or write requests per drive.
#define CARD_DRAM_SIZE (1 * 1024 *1024 * 1024)
#define MAX_NB_OF_WORDS_READ (MAX_NB_OF_BYTES_READ/BPERDW)
#define DRAM_ADDR_TO_SSD 0x00000000
#define DRAM_ADDR_FROM_SSD 0x80000000
//---------------------------------------------------------------------
typedef struct {
CONTROL Control; /* 16 bytes */
nvme_memcopy_job_t Data; /* 108 bytes */
uint8_t padding[SNAP_HLS_JOBSIZE - sizeof(nvme_memcopy_job_t)];
} action_reg;
#endif /* __ACTION_HLS_NVME_MEMCOPY_H__ */
<commit_msg>Delete action_nvme_memcopy.H (#702)<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// 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.
#include "ez-rpc.h"
#include "rpc-twoparty.h"
#include <capnp/rpc.capnp.h>
#include <kj/async-io.h>
#include <kj/debug.h>
#include <kj/threadlocal.h>
#include <map>
namespace capnp {
KJ_THREADLOCAL_PTR(EzRpcContext) threadEzContext = nullptr;
class EzRpcContext: public kj::Refcounted {
public:
EzRpcContext(): ioContext(kj::setupAsyncIo()) {
threadEzContext = this;
}
~EzRpcContext() noexcept(false) {
KJ_REQUIRE(threadEzContext == this,
"EzRpcContext destroyed from different thread than it was created.") {
return;
}
threadEzContext = nullptr;
}
kj::WaitScope& getWaitScope() {
return ioContext.waitScope;
}
kj::AsyncIoProvider& getIoProvider() {
return *ioContext.provider;
}
kj::LowLevelAsyncIoProvider& getLowLevelIoProvider() {
return *ioContext.lowLevelProvider;
}
static kj::Own<EzRpcContext> getThreadLocal() {
EzRpcContext* existing = threadEzContext;
if (existing != nullptr) {
return kj::addRef(*existing);
} else {
return kj::refcounted<EzRpcContext>();
}
}
private:
kj::AsyncIoContext ioContext;
};
// =======================================================================================
struct EzRpcClient::Impl {
kj::Own<EzRpcContext> context;
struct ClientContext {
kj::Own<kj::AsyncIoStream> stream;
TwoPartyVatNetwork network;
RpcSystem<rpc::twoparty::VatId> rpcSystem;
ClientContext(kj::Own<kj::AsyncIoStream>&& stream, ReaderOptions readerOpts)
: stream(kj::mv(stream)),
network(*this->stream, rpc::twoparty::Side::CLIENT, readerOpts),
rpcSystem(makeRpcClient(network)) {}
Capability::Client getMain() {
word scratch[4];
memset(scratch, 0, sizeof(scratch));
MallocMessageBuilder message(scratch);
auto hostId = message.getRoot<rpc::twoparty::VatId>();
hostId.setSide(rpc::twoparty::Side::SERVER);
return rpcSystem.bootstrap(hostId);
}
Capability::Client restore(kj::StringPtr name) {
word scratch[64];
memset(scratch, 0, sizeof(scratch));
MallocMessageBuilder message(scratch);
auto hostIdOrphan = message.getOrphanage().newOrphan<rpc::twoparty::VatId>();
auto hostId = hostIdOrphan.get();
hostId.setSide(rpc::twoparty::Side::SERVER);
auto objectId = message.getRoot<AnyPointer>();
objectId.setAs<Text>(name);
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
return rpcSystem.restore(hostId, objectId);
#pragma GCC diagnostic pop
}
};
kj::ForkedPromise<void> setupPromise;
kj::Maybe<kj::Own<ClientContext>> clientContext;
// Filled in before `setupPromise` resolves.
Impl(kj::StringPtr serverAddress, uint defaultPort,
ReaderOptions readerOpts)
: context(EzRpcContext::getThreadLocal()),
setupPromise(context->getIoProvider().getNetwork()
.parseAddress(serverAddress, defaultPort)
.then([readerOpts](kj::Own<kj::NetworkAddress>&& addr) {
return addr->connect();
}).then([this, readerOpts](kj::Own<kj::AsyncIoStream>&& stream) {
clientContext = kj::heap<ClientContext>(kj::mv(stream),
readerOpts);
}).fork()) {}
Impl(const struct sockaddr* serverAddress, uint addrSize,
ReaderOptions readerOpts)
: context(EzRpcContext::getThreadLocal()),
setupPromise(context->getIoProvider().getNetwork()
.getSockaddr(serverAddress, addrSize)->connect()
.then([this, readerOpts](kj::Own<kj::AsyncIoStream>&& stream) {
clientContext = kj::heap<ClientContext>(kj::mv(stream),
readerOpts);
}).fork()) {}
Impl(int socketFd, ReaderOptions readerOpts)
: context(EzRpcContext::getThreadLocal()),
setupPromise(kj::Promise<void>(kj::READY_NOW).fork()),
clientContext(kj::heap<ClientContext>(
context->getLowLevelIoProvider().wrapSocketFd(socketFd),
readerOpts)) {}
};
EzRpcClient::EzRpcClient(kj::StringPtr serverAddress, uint defaultPort, ReaderOptions readerOpts)
: impl(kj::heap<Impl>(serverAddress, defaultPort, readerOpts)) {}
EzRpcClient::EzRpcClient(const struct sockaddr* serverAddress, uint addrSize, ReaderOptions readerOpts)
: impl(kj::heap<Impl>(serverAddress, addrSize, readerOpts)) {}
EzRpcClient::EzRpcClient(int socketFd, ReaderOptions readerOpts)
: impl(kj::heap<Impl>(socketFd, readerOpts)) {}
EzRpcClient::~EzRpcClient() noexcept(false) {}
Capability::Client EzRpcClient::getMain() {
KJ_IF_MAYBE(client, impl->clientContext) {
return client->get()->getMain();
} else {
return impl->setupPromise.addBranch().then([this]() {
return KJ_ASSERT_NONNULL(impl->clientContext)->getMain();
});
}
}
Capability::Client EzRpcClient::importCap(kj::StringPtr name) {
KJ_IF_MAYBE(client, impl->clientContext) {
return client->get()->restore(name);
} else {
return impl->setupPromise.addBranch().then(kj::mvCapture(kj::heapString(name),
[this](kj::String&& name) {
return KJ_ASSERT_NONNULL(impl->clientContext)->restore(name);
}));
}
}
kj::WaitScope& EzRpcClient::getWaitScope() {
return impl->context->getWaitScope();
}
kj::AsyncIoProvider& EzRpcClient::getIoProvider() {
return impl->context->getIoProvider();
}
kj::LowLevelAsyncIoProvider& EzRpcClient::getLowLevelIoProvider() {
return impl->context->getLowLevelIoProvider();
}
// =======================================================================================
struct EzRpcServer::Impl final: public SturdyRefRestorer<AnyPointer>,
public kj::TaskSet::ErrorHandler {
Capability::Client mainInterface;
kj::Own<EzRpcContext> context;
struct ExportedCap {
kj::String name;
Capability::Client cap = nullptr;
ExportedCap(kj::StringPtr name, Capability::Client cap)
: name(kj::heapString(name)), cap(cap) {}
ExportedCap() = default;
ExportedCap(const ExportedCap&) = delete;
ExportedCap(ExportedCap&&) = default;
ExportedCap& operator=(const ExportedCap&) = delete;
ExportedCap& operator=(ExportedCap&&) = default;
// Make std::map happy...
};
std::map<kj::StringPtr, ExportedCap> exportMap;
kj::ForkedPromise<uint> portPromise;
kj::TaskSet tasks;
struct ServerContext {
kj::Own<kj::AsyncIoStream> stream;
TwoPartyVatNetwork network;
RpcSystem<rpc::twoparty::VatId> rpcSystem;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
ServerContext(kj::Own<kj::AsyncIoStream>&& stream, SturdyRefRestorer<AnyPointer>& restorer,
ReaderOptions readerOpts)
: stream(kj::mv(stream)),
network(*this->stream, rpc::twoparty::Side::SERVER, readerOpts),
rpcSystem(makeRpcServer(network, restorer)) {}
#pragma GCC diagnostic pop
};
Impl(Capability::Client mainInterface, kj::StringPtr bindAddress, uint defaultPort,
ReaderOptions readerOpts)
: mainInterface(kj::mv(mainInterface)),
context(EzRpcContext::getThreadLocal()), portPromise(nullptr), tasks(*this) {
auto paf = kj::newPromiseAndFulfiller<uint>();
portPromise = paf.promise.fork();
tasks.add(context->getIoProvider().getNetwork().parseAddress(bindAddress, defaultPort)
.then(kj::mvCapture(paf.fulfiller,
[this, readerOpts](kj::Own<kj::PromiseFulfiller<uint>>&& portFulfiller,
kj::Own<kj::NetworkAddress>&& addr) {
auto listener = addr->listen();
portFulfiller->fulfill(listener->getPort());
acceptLoop(kj::mv(listener), readerOpts);
})));
}
Impl(Capability::Client mainInterface, struct sockaddr* bindAddress, uint addrSize,
ReaderOptions readerOpts)
: mainInterface(kj::mv(mainInterface)),
context(EzRpcContext::getThreadLocal()), portPromise(nullptr), tasks(*this) {
auto listener = context->getIoProvider().getNetwork()
.getSockaddr(bindAddress, addrSize)->listen();
portPromise = kj::Promise<uint>(listener->getPort()).fork();
acceptLoop(kj::mv(listener), readerOpts);
}
Impl(Capability::Client mainInterface, int socketFd, uint port, ReaderOptions readerOpts)
: mainInterface(kj::mv(mainInterface)),
context(EzRpcContext::getThreadLocal()),
portPromise(kj::Promise<uint>(port).fork()),
tasks(*this) {
acceptLoop(context->getLowLevelIoProvider().wrapListenSocketFd(socketFd), readerOpts);
}
void acceptLoop(kj::Own<kj::ConnectionReceiver>&& listener, ReaderOptions readerOpts) {
auto ptr = listener.get();
tasks.add(ptr->accept().then(kj::mvCapture(kj::mv(listener),
[this, readerOpts](kj::Own<kj::ConnectionReceiver>&& listener,
kj::Own<kj::AsyncIoStream>&& connection) {
acceptLoop(kj::mv(listener), readerOpts);
auto server = kj::heap<ServerContext>(kj::mv(connection), *this, readerOpts);
// Arrange to destroy the server context when all references are gone, or when the
// EzRpcServer is destroyed (which will destroy the TaskSet).
tasks.add(server->network.onDisconnect().attach(kj::mv(server)));
})));
}
Capability::Client restore(AnyPointer::Reader objectId) override {
if (objectId.isNull()) {
return mainInterface;
} else {
auto name = objectId.getAs<Text>();
auto iter = exportMap.find(name);
if (iter == exportMap.end()) {
KJ_FAIL_REQUIRE("Server exports no such capability.", name) { break; }
return nullptr;
} else {
return iter->second.cap;
}
}
}
void taskFailed(kj::Exception&& exception) override {
kj::throwFatalException(kj::mv(exception));
}
};
EzRpcServer::EzRpcServer(Capability::Client mainInterface, kj::StringPtr bindAddress,
uint defaultPort, ReaderOptions readerOpts)
: impl(kj::heap<Impl>(kj::mv(mainInterface), bindAddress, defaultPort, readerOpts)) {}
EzRpcServer::EzRpcServer(Capability::Client mainInterface, struct sockaddr* bindAddress,
uint addrSize, ReaderOptions readerOpts)
: impl(kj::heap<Impl>(kj::mv(mainInterface), bindAddress, addrSize, readerOpts)) {}
EzRpcServer::EzRpcServer(Capability::Client mainInterface, int socketFd, uint port,
ReaderOptions readerOpts)
: impl(kj::heap<Impl>(kj::mv(mainInterface), socketFd, port, readerOpts)) {}
EzRpcServer::EzRpcServer(kj::StringPtr bindAddress, uint defaultPort,
ReaderOptions readerOpts)
: EzRpcServer(nullptr, bindAddress, defaultPort, readerOpts) {}
EzRpcServer::EzRpcServer(struct sockaddr* bindAddress, uint addrSize,
ReaderOptions readerOpts)
: EzRpcServer(nullptr, bindAddress, addrSize, readerOpts) {}
EzRpcServer::EzRpcServer(int socketFd, uint port, ReaderOptions readerOpts)
: EzRpcServer(nullptr, socketFd, port, readerOpts) {}
EzRpcServer::~EzRpcServer() noexcept(false) {}
void EzRpcServer::exportCap(kj::StringPtr name, Capability::Client cap) {
Impl::ExportedCap entry(kj::heapString(name), cap);
impl->exportMap[entry.name] = kj::mv(entry);
}
kj::Promise<uint> EzRpcServer::getPort() {
return impl->portPromise.addBranch();
}
kj::WaitScope& EzRpcServer::getWaitScope() {
return impl->context->getWaitScope();
}
kj::AsyncIoProvider& EzRpcServer::getIoProvider() {
return impl->context->getIoProvider();
}
kj::LowLevelAsyncIoProvider& EzRpcServer::getLowLevelIoProvider() {
return impl->context->getLowLevelIoProvider();
}
} // namespace capnp
<commit_msg>Fix bug where EzRpcClient would segfault if the target host resolved to multiple addresses and the connection to the first of those failed.<commit_after>// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// 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.
#include "ez-rpc.h"
#include "rpc-twoparty.h"
#include <capnp/rpc.capnp.h>
#include <kj/async-io.h>
#include <kj/debug.h>
#include <kj/threadlocal.h>
#include <map>
namespace capnp {
KJ_THREADLOCAL_PTR(EzRpcContext) threadEzContext = nullptr;
class EzRpcContext: public kj::Refcounted {
public:
EzRpcContext(): ioContext(kj::setupAsyncIo()) {
threadEzContext = this;
}
~EzRpcContext() noexcept(false) {
KJ_REQUIRE(threadEzContext == this,
"EzRpcContext destroyed from different thread than it was created.") {
return;
}
threadEzContext = nullptr;
}
kj::WaitScope& getWaitScope() {
return ioContext.waitScope;
}
kj::AsyncIoProvider& getIoProvider() {
return *ioContext.provider;
}
kj::LowLevelAsyncIoProvider& getLowLevelIoProvider() {
return *ioContext.lowLevelProvider;
}
static kj::Own<EzRpcContext> getThreadLocal() {
EzRpcContext* existing = threadEzContext;
if (existing != nullptr) {
return kj::addRef(*existing);
} else {
return kj::refcounted<EzRpcContext>();
}
}
private:
kj::AsyncIoContext ioContext;
};
// =======================================================================================
kj::Promise<kj::Own<kj::AsyncIoStream>> connectAttach(kj::Own<kj::NetworkAddress>&& addr) {
return addr->connect().attach(kj::mv(addr));
}
struct EzRpcClient::Impl {
kj::Own<EzRpcContext> context;
struct ClientContext {
kj::Own<kj::AsyncIoStream> stream;
TwoPartyVatNetwork network;
RpcSystem<rpc::twoparty::VatId> rpcSystem;
ClientContext(kj::Own<kj::AsyncIoStream>&& stream, ReaderOptions readerOpts)
: stream(kj::mv(stream)),
network(*this->stream, rpc::twoparty::Side::CLIENT, readerOpts),
rpcSystem(makeRpcClient(network)) {}
Capability::Client getMain() {
word scratch[4];
memset(scratch, 0, sizeof(scratch));
MallocMessageBuilder message(scratch);
auto hostId = message.getRoot<rpc::twoparty::VatId>();
hostId.setSide(rpc::twoparty::Side::SERVER);
return rpcSystem.bootstrap(hostId);
}
Capability::Client restore(kj::StringPtr name) {
word scratch[64];
memset(scratch, 0, sizeof(scratch));
MallocMessageBuilder message(scratch);
auto hostIdOrphan = message.getOrphanage().newOrphan<rpc::twoparty::VatId>();
auto hostId = hostIdOrphan.get();
hostId.setSide(rpc::twoparty::Side::SERVER);
auto objectId = message.getRoot<AnyPointer>();
objectId.setAs<Text>(name);
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
return rpcSystem.restore(hostId, objectId);
#pragma GCC diagnostic pop
}
};
kj::ForkedPromise<void> setupPromise;
kj::Maybe<kj::Own<ClientContext>> clientContext;
// Filled in before `setupPromise` resolves.
Impl(kj::StringPtr serverAddress, uint defaultPort,
ReaderOptions readerOpts)
: context(EzRpcContext::getThreadLocal()),
setupPromise(context->getIoProvider().getNetwork()
.parseAddress(serverAddress, defaultPort)
.then([readerOpts](kj::Own<kj::NetworkAddress>&& addr) {
return connectAttach(kj::mv(addr));
}).then([this, readerOpts](kj::Own<kj::AsyncIoStream>&& stream) {
clientContext = kj::heap<ClientContext>(kj::mv(stream),
readerOpts);
}).fork()) {}
Impl(const struct sockaddr* serverAddress, uint addrSize,
ReaderOptions readerOpts)
: context(EzRpcContext::getThreadLocal()),
setupPromise(
connectAttach(context->getIoProvider().getNetwork()
.getSockaddr(serverAddress, addrSize))
.then([this, readerOpts](kj::Own<kj::AsyncIoStream>&& stream) {
clientContext = kj::heap<ClientContext>(kj::mv(stream),
readerOpts);
}).fork()) {}
Impl(int socketFd, ReaderOptions readerOpts)
: context(EzRpcContext::getThreadLocal()),
setupPromise(kj::Promise<void>(kj::READY_NOW).fork()),
clientContext(kj::heap<ClientContext>(
context->getLowLevelIoProvider().wrapSocketFd(socketFd),
readerOpts)) {}
};
EzRpcClient::EzRpcClient(kj::StringPtr serverAddress, uint defaultPort, ReaderOptions readerOpts)
: impl(kj::heap<Impl>(serverAddress, defaultPort, readerOpts)) {}
EzRpcClient::EzRpcClient(const struct sockaddr* serverAddress, uint addrSize, ReaderOptions readerOpts)
: impl(kj::heap<Impl>(serverAddress, addrSize, readerOpts)) {}
EzRpcClient::EzRpcClient(int socketFd, ReaderOptions readerOpts)
: impl(kj::heap<Impl>(socketFd, readerOpts)) {}
EzRpcClient::~EzRpcClient() noexcept(false) {}
Capability::Client EzRpcClient::getMain() {
KJ_IF_MAYBE(client, impl->clientContext) {
return client->get()->getMain();
} else {
return impl->setupPromise.addBranch().then([this]() {
return KJ_ASSERT_NONNULL(impl->clientContext)->getMain();
});
}
}
Capability::Client EzRpcClient::importCap(kj::StringPtr name) {
KJ_IF_MAYBE(client, impl->clientContext) {
return client->get()->restore(name);
} else {
return impl->setupPromise.addBranch().then(kj::mvCapture(kj::heapString(name),
[this](kj::String&& name) {
return KJ_ASSERT_NONNULL(impl->clientContext)->restore(name);
}));
}
}
kj::WaitScope& EzRpcClient::getWaitScope() {
return impl->context->getWaitScope();
}
kj::AsyncIoProvider& EzRpcClient::getIoProvider() {
return impl->context->getIoProvider();
}
kj::LowLevelAsyncIoProvider& EzRpcClient::getLowLevelIoProvider() {
return impl->context->getLowLevelIoProvider();
}
// =======================================================================================
struct EzRpcServer::Impl final: public SturdyRefRestorer<AnyPointer>,
public kj::TaskSet::ErrorHandler {
Capability::Client mainInterface;
kj::Own<EzRpcContext> context;
struct ExportedCap {
kj::String name;
Capability::Client cap = nullptr;
ExportedCap(kj::StringPtr name, Capability::Client cap)
: name(kj::heapString(name)), cap(cap) {}
ExportedCap() = default;
ExportedCap(const ExportedCap&) = delete;
ExportedCap(ExportedCap&&) = default;
ExportedCap& operator=(const ExportedCap&) = delete;
ExportedCap& operator=(ExportedCap&&) = default;
// Make std::map happy...
};
std::map<kj::StringPtr, ExportedCap> exportMap;
kj::ForkedPromise<uint> portPromise;
kj::TaskSet tasks;
struct ServerContext {
kj::Own<kj::AsyncIoStream> stream;
TwoPartyVatNetwork network;
RpcSystem<rpc::twoparty::VatId> rpcSystem;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
ServerContext(kj::Own<kj::AsyncIoStream>&& stream, SturdyRefRestorer<AnyPointer>& restorer,
ReaderOptions readerOpts)
: stream(kj::mv(stream)),
network(*this->stream, rpc::twoparty::Side::SERVER, readerOpts),
rpcSystem(makeRpcServer(network, restorer)) {}
#pragma GCC diagnostic pop
};
Impl(Capability::Client mainInterface, kj::StringPtr bindAddress, uint defaultPort,
ReaderOptions readerOpts)
: mainInterface(kj::mv(mainInterface)),
context(EzRpcContext::getThreadLocal()), portPromise(nullptr), tasks(*this) {
auto paf = kj::newPromiseAndFulfiller<uint>();
portPromise = paf.promise.fork();
tasks.add(context->getIoProvider().getNetwork().parseAddress(bindAddress, defaultPort)
.then(kj::mvCapture(paf.fulfiller,
[this, readerOpts](kj::Own<kj::PromiseFulfiller<uint>>&& portFulfiller,
kj::Own<kj::NetworkAddress>&& addr) {
auto listener = addr->listen();
portFulfiller->fulfill(listener->getPort());
acceptLoop(kj::mv(listener), readerOpts);
})));
}
Impl(Capability::Client mainInterface, struct sockaddr* bindAddress, uint addrSize,
ReaderOptions readerOpts)
: mainInterface(kj::mv(mainInterface)),
context(EzRpcContext::getThreadLocal()), portPromise(nullptr), tasks(*this) {
auto listener = context->getIoProvider().getNetwork()
.getSockaddr(bindAddress, addrSize)->listen();
portPromise = kj::Promise<uint>(listener->getPort()).fork();
acceptLoop(kj::mv(listener), readerOpts);
}
Impl(Capability::Client mainInterface, int socketFd, uint port, ReaderOptions readerOpts)
: mainInterface(kj::mv(mainInterface)),
context(EzRpcContext::getThreadLocal()),
portPromise(kj::Promise<uint>(port).fork()),
tasks(*this) {
acceptLoop(context->getLowLevelIoProvider().wrapListenSocketFd(socketFd), readerOpts);
}
void acceptLoop(kj::Own<kj::ConnectionReceiver>&& listener, ReaderOptions readerOpts) {
auto ptr = listener.get();
tasks.add(ptr->accept().then(kj::mvCapture(kj::mv(listener),
[this, readerOpts](kj::Own<kj::ConnectionReceiver>&& listener,
kj::Own<kj::AsyncIoStream>&& connection) {
acceptLoop(kj::mv(listener), readerOpts);
auto server = kj::heap<ServerContext>(kj::mv(connection), *this, readerOpts);
// Arrange to destroy the server context when all references are gone, or when the
// EzRpcServer is destroyed (which will destroy the TaskSet).
tasks.add(server->network.onDisconnect().attach(kj::mv(server)));
})));
}
Capability::Client restore(AnyPointer::Reader objectId) override {
if (objectId.isNull()) {
return mainInterface;
} else {
auto name = objectId.getAs<Text>();
auto iter = exportMap.find(name);
if (iter == exportMap.end()) {
KJ_FAIL_REQUIRE("Server exports no such capability.", name) { break; }
return nullptr;
} else {
return iter->second.cap;
}
}
}
void taskFailed(kj::Exception&& exception) override {
kj::throwFatalException(kj::mv(exception));
}
};
EzRpcServer::EzRpcServer(Capability::Client mainInterface, kj::StringPtr bindAddress,
uint defaultPort, ReaderOptions readerOpts)
: impl(kj::heap<Impl>(kj::mv(mainInterface), bindAddress, defaultPort, readerOpts)) {}
EzRpcServer::EzRpcServer(Capability::Client mainInterface, struct sockaddr* bindAddress,
uint addrSize, ReaderOptions readerOpts)
: impl(kj::heap<Impl>(kj::mv(mainInterface), bindAddress, addrSize, readerOpts)) {}
EzRpcServer::EzRpcServer(Capability::Client mainInterface, int socketFd, uint port,
ReaderOptions readerOpts)
: impl(kj::heap<Impl>(kj::mv(mainInterface), socketFd, port, readerOpts)) {}
EzRpcServer::EzRpcServer(kj::StringPtr bindAddress, uint defaultPort,
ReaderOptions readerOpts)
: EzRpcServer(nullptr, bindAddress, defaultPort, readerOpts) {}
EzRpcServer::EzRpcServer(struct sockaddr* bindAddress, uint addrSize,
ReaderOptions readerOpts)
: EzRpcServer(nullptr, bindAddress, addrSize, readerOpts) {}
EzRpcServer::EzRpcServer(int socketFd, uint port, ReaderOptions readerOpts)
: EzRpcServer(nullptr, socketFd, port, readerOpts) {}
EzRpcServer::~EzRpcServer() noexcept(false) {}
void EzRpcServer::exportCap(kj::StringPtr name, Capability::Client cap) {
Impl::ExportedCap entry(kj::heapString(name), cap);
impl->exportMap[entry.name] = kj::mv(entry);
}
kj::Promise<uint> EzRpcServer::getPort() {
return impl->portPromise.addBranch();
}
kj::WaitScope& EzRpcServer::getWaitScope() {
return impl->context->getWaitScope();
}
kj::AsyncIoProvider& EzRpcServer::getIoProvider() {
return impl->context->getIoProvider();
}
kj::LowLevelAsyncIoProvider& EzRpcServer::getLowLevelIoProvider() {
return impl->context->getLowLevelIoProvider();
}
} // namespace capnp
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include <mitkContourModel.h>
mitk::ContourModel::ContourModel()
{
this->m_Contour = mitk::ContourModelElement::New();
m_SelectedVertex = NULL;
}
mitk::ContourModel::ContourModel(const mitk::ContourModel &other) :
m_Contour(other.m_Contour)
{
m_SelectedVertex = NULL;
}
mitk::ContourModel::~ContourModel()
{
m_SelectedVertex = NULL;
this->m_Contour = NULL;
}
bool mitk::ContourModel::SelectVertexAt(int index)
{
if(index < 0 || index > this->m_Contour->GetSize())
return false;
this->m_SelectedVertex = this->m_Contour->GetVertexAt(index);
return true;
}
bool mitk::ContourModel::SelectVertexAt(mitk::Point3D &point, float eps)
{
this->m_SelectedVertex = this->m_Contour->GetVertexAt(point, eps);
return this->m_SelectedVertex != NULL;
}
bool mitk::ContourModel::RemoveVertexAt(int index)
{
if(index < 0 || index > this->m_Contour->GetSize())
return false;
this->m_Contour->RemoveVertexAt(index);
return true;
}
bool mitk::ContourModel::RemoveVertexAt(mitk::Point3D &point, float eps)
{
return this->m_Contour->RemoveVertexAt(point, eps);
}
void mitk::ContourModel::MoveSelectedVertex(mitk::Vector3D &translate)
{
if(this->m_SelectedVertex)
{
this->MoveVertex(this->m_SelectedVertex,translate);
}
}
void mitk::ContourModel::MoveContour(mitk::Vector3D &translate)
{
VertexListType* vList = this->m_Contour->GetVertexList();
VertexIterator it = vList->begin();
VertexIterator end = vList->end();
while(it != end)
{
this->MoveVertex((*it),translate);
it++;
}
}
void mitk::ContourModel::MoveVertex(VertexType* vertex, mitk::Vector3D &vector)
{
vertex->Coordinates[0] += vector[0];
vertex->Coordinates[1] += vector[1];
vertex->Coordinates[2] += vector[2];
}
void mitk::ContourModel::SetRequestedRegionToLargestPossibleRegion ()
{
}
bool mitk::ContourModel::RequestedRegionIsOutsideOfTheBufferedRegion ()
{
return NULL;
}
bool mitk::ContourModel::VerifyRequestedRegion ()
{
return NULL;
}
const mitk::Geometry3D * mitk::ContourModel::GetUpdatedGeometry (int t)
{
return NULL;
}
mitk::Geometry3D* mitk::ContourModel::GetGeometry (int t)const
{
return NULL;
}
void mitk::ContourModel::SetRequestedRegion (itk::DataObject *data)
{
}<commit_msg>init timestep<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include <mitkContourModel.h>
mitk::ContourModel::ContourModel()
{
this->m_Contour = mitk::ContourModelElement::New();
Superclass::InitializeTimeSlicedGeometry(1);
m_SelectedVertex = NULL;
}
mitk::ContourModel::ContourModel(const mitk::ContourModel &other) :
m_Contour(other.m_Contour)
{
m_SelectedVertex = NULL;
}
mitk::ContourModel::~ContourModel()
{
m_SelectedVertex = NULL;
this->m_Contour = NULL;
}
bool mitk::ContourModel::SelectVertexAt(int index)
{
if(index < 0 || index > this->m_Contour->GetSize())
return false;
this->m_SelectedVertex = this->m_Contour->GetVertexAt(index);
return true;
}
bool mitk::ContourModel::SelectVertexAt(mitk::Point3D &point, float eps)
{
this->m_SelectedVertex = this->m_Contour->GetVertexAt(point, eps);
return this->m_SelectedVertex != NULL;
}
bool mitk::ContourModel::RemoveVertexAt(int index)
{
if(index < 0 || index > this->m_Contour->GetSize())
return false;
this->m_Contour->RemoveVertexAt(index);
return true;
}
bool mitk::ContourModel::RemoveVertexAt(mitk::Point3D &point, float eps)
{
return this->m_Contour->RemoveVertexAt(point, eps);
}
void mitk::ContourModel::MoveSelectedVertex(mitk::Vector3D &translate)
{
if(this->m_SelectedVertex)
{
this->MoveVertex(this->m_SelectedVertex,translate);
}
}
void mitk::ContourModel::MoveContour(mitk::Vector3D &translate)
{
VertexListType* vList = this->m_Contour->GetVertexList();
VertexIterator it = vList->begin();
VertexIterator end = vList->end();
while(it != end)
{
this->MoveVertex((*it),translate);
it++;
}
}
void mitk::ContourModel::MoveVertex(VertexType* vertex, mitk::Vector3D &vector)
{
vertex->Coordinates[0] += vector[0];
vertex->Coordinates[1] += vector[1];
vertex->Coordinates[2] += vector[2];
}
void mitk::ContourModel::SetRequestedRegionToLargestPossibleRegion ()
{
}
bool mitk::ContourModel::RequestedRegionIsOutsideOfTheBufferedRegion ()
{
return false;
}
bool mitk::ContourModel::VerifyRequestedRegion ()
{
return true;
}
const mitk::Geometry3D * mitk::ContourModel::GetUpdatedGeometry (int t)
{
return NULL;
}
mitk::Geometry3D* mitk::ContourModel::GetGeometry (int t)const
{
return NULL;
}
void mitk::ContourModel::SetRequestedRegion (itk::DataObject *data)
{
}<|endoftext|> |
<commit_before>// Copyright 2020 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//===--- FusionOfTensorsOps.cpp - Pass to fuse operations on tensors-------===//
//
// Pass to fuse operations on tensors after conversion to Linalg. Uses the
// patterns from MLIR for fusion linalg operations on tensors, and a few
// patterns to fuse these with IREE specific operations.
//
//===----------------------------------------------------------------------===//
#include "iree/compiler/Dialect/Flow/Transforms/PassDetail.h"
#include "iree/compiler/Dialect/Flow/Transforms/Passes.h"
#include "mlir/Dialect/Affine/IR/AffineOps.h"
#include "mlir/Dialect/Linalg/IR/LinalgOps.h"
#include "mlir/Dialect/Linalg/Transforms/Transforms.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
static llvm::cl::opt<bool> clEnableFusionWithReductionOps(
"iree-enable-fusion-with-reduction-ops",
llvm::cl::desc("Allow fusing generic ops with reductions"),
llvm::cl::init(false));
namespace mlir {
namespace iree_compiler {
namespace IREE {
namespace Flow {
namespace {
using linalg::LinalgOp;
/// Pass to fuse linalg on tensor operations as well as fusion of hal.interface*
/// operations with linalg.tensor_reshape operation.
struct FusionOfTensorOpsPass
: public FusionOfTensorOpsBase<FusionOfTensorOpsPass> {
void getDependentDialects(DialectRegistry ®istry) const override {
registry.insert<AffineDialect, linalg::LinalgDialect>();
}
void runOnOperation() override {
OwningRewritePatternList fusionPatterns(&getContext());
OwningRewritePatternList interfacePatterns(&getContext());
Operation *op = getOperation();
MLIRContext *context = op->getContext();
// Only fuse operations where all uses of the producer are generic
// operations. If an operation is used in a named op, it will be computed
// anyway, so the consumers can just use that value.
linalg::ControlElementwiseOpsFusionFn controlFn =
[](const OpResult &producer, const OpOperand &consumer) {
// TODO(GH-5611): Enable fusion with reduction consumer for all
// targets. Currently vectorization doesn't handle generic ops with
// reduction iterators we will disable for now to allow vectorizing
// producer pointwise ops to avoid performance regressions on CPU.
if (!clEnableFusionWithReductionOps) {
auto consumerOp = consumer.getOwner();
if (isa<linalg::GenericOp>(consumerOp) &&
dyn_cast<LinalgOp>(consumerOp).getNumReductionLoops()) {
return false;
}
}
// Limit the number of operands. We have hard limit (32) of bindings
// passing down to HAL. Set the number to be as same as the limit --
// IREE_HAL_MODULE_MAX_DESCRIPTOR_BINDING_COUNT.
constexpr int64_t kIreeMaxOperandCount = 32;
auto numOperands = producer.getOwner()->getNumOperands() +
consumer.getOwner()->getNumOperands() - 1;
if (numOperands >= kIreeMaxOperandCount) return false;
llvm::SmallDenseSet<Operation *, 4> numUsers;
for (Operation *user : producer.getUsers()) {
if (isa<linalg::GenericOp>(user)) continue;
numUsers.insert(user);
}
return numUsers.empty();
};
// Simple heuristic to decide if reshaope should be folded in the linalg.
// If the source of the reshape is a linalg op fold to potentially allow the
// two linalg ops to be fused. Otherwise leave it to avoid adding dimensions
// to the consumer linalg op.
linalg::ControlElementwiseOpsFusionFn foldReshapeBetweenLinalgFn =
[](const OpResult &producer, const OpOperand &consumer) {
auto collapseOp =
producer.getDefiningOp<linalg::TensorCollapseShapeOp>();
if (collapseOp)
return collapseOp.src().getDefiningOp<LinalgOp>() != nullptr;
auto expandOp = producer.getDefiningOp<linalg::TensorExpandShapeOp>();
if (expandOp)
return expandOp.src().getDefiningOp<LinalgOp>() != nullptr;
return false;
};
linalg::populateElementwiseOpsFusionPatterns(
fusionPatterns,
linalg::LinalgElementwiseFusionOptions()
.setControlFoldingReshapes(foldReshapeBetweenLinalgFn)
.setControlElementwiseOpsFusionFn(controlFn));
(void)applyPatternsAndFoldGreedily(op->getRegions(),
std::move(fusionPatterns));
OwningRewritePatternList reshapeCanonicalizations(&getContext());
linalg::populateFoldUnitDimsReshapeOpsByLinearizationPatterns(
reshapeCanonicalizations);
linalg::TensorCollapseShapeOp::getCanonicalizationPatterns(
reshapeCanonicalizations, context);
linalg::TensorExpandShapeOp::getCanonicalizationPatterns(
reshapeCanonicalizations, context);
(void)applyPatternsAndFoldGreedily(op->getRegions(),
std::move(reshapeCanonicalizations));
// Push the remaining reshapes down the graphs.
OwningRewritePatternList pushReshapePatterns(&getContext());
linalg::populatePushReshapeOpsPatterns(pushReshapePatterns);
linalg::TensorCollapseShapeOp::getCanonicalizationPatterns(
pushReshapePatterns, context);
linalg::TensorExpandShapeOp::getCanonicalizationPatterns(
pushReshapePatterns, context);
(void)applyPatternsAndFoldGreedily(op->getRegions(),
std::move(pushReshapePatterns));
}
};
} // namespace
std::unique_ptr<Pass> createFusionOfTensorOpsPass() {
return std::make_unique<FusionOfTensorOpsPass>();
}
} // namespace Flow
} // namespace IREE
} // namespace iree_compiler
} // namespace mlir
<commit_msg>Considering duplicate operands in Linalg fusion. (#6644)<commit_after>// Copyright 2020 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//===--- FusionOfTensorsOps.cpp - Pass to fuse operations on tensors-------===//
//
// Pass to fuse operations on tensors after conversion to Linalg. Uses the
// patterns from MLIR for fusion linalg operations on tensors, and a few
// patterns to fuse these with IREE specific operations.
//
//===----------------------------------------------------------------------===//
#include "iree/compiler/Dialect/Flow/Transforms/PassDetail.h"
#include "iree/compiler/Dialect/Flow/Transforms/Passes.h"
#include "mlir/Dialect/Affine/IR/AffineOps.h"
#include "mlir/Dialect/Linalg/IR/LinalgOps.h"
#include "mlir/Dialect/Linalg/Transforms/Transforms.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
static llvm::cl::opt<bool> clEnableFusionWithReductionOps(
"iree-enable-fusion-with-reduction-ops",
llvm::cl::desc("Allow fusing generic ops with reductions"),
llvm::cl::init(false));
namespace mlir {
namespace iree_compiler {
namespace IREE {
namespace Flow {
namespace {
using linalg::LinalgOp;
/// Pass to fuse linalg on tensor operations as well as fusion of hal.interface*
/// operations with linalg.tensor_reshape operation.
struct FusionOfTensorOpsPass
: public FusionOfTensorOpsBase<FusionOfTensorOpsPass> {
void getDependentDialects(DialectRegistry ®istry) const override {
registry.insert<AffineDialect, linalg::LinalgDialect>();
}
void runOnOperation() override {
OwningRewritePatternList fusionPatterns(&getContext());
OwningRewritePatternList interfacePatterns(&getContext());
Operation *op = getOperation();
MLIRContext *context = op->getContext();
// Only fuse operations where all uses of the producer are generic
// operations. If an operation is used in a named op, it will be computed
// anyway, so the consumers can just use that value.
linalg::ControlElementwiseOpsFusionFn controlFn =
[](const OpResult &producer, OpOperand &consumer) {
// TODO(GH-5611): Enable fusion with reduction consumer for all
// targets. Currently vectorization doesn't handle generic ops with
// reduction iterators we will disable for now to allow vectorizing
// producer pointwise ops to avoid performance regressions on CPU.
if (!clEnableFusionWithReductionOps) {
auto consumerOp = consumer.getOwner();
if (isa<linalg::GenericOp>(consumerOp) &&
dyn_cast<LinalgOp>(consumerOp).getNumReductionLoops()) {
return false;
}
}
// Limit the number of operands. We have hard limit (32) of bindings
// passing down to HAL. Set the number to be as same as the limit --
// IREE_HAL_MODULE_MAX_DESCRIPTOR_BINDING_COUNT.
constexpr int64_t kIreeMaxOperandCount = 32;
DenseSet<Value> operands;
operands.insert(producer.getOwner()->operand_begin(),
producer.getOwner()->operand_end());
operands.insert(consumer.getOwner()->operand_begin(),
std::next(consumer.getOwner()->operand_begin(),
consumer.getOperandNumber()));
operands.insert(std::next(consumer.getOwner()->operand_begin(),
consumer.getOperandNumber() + 1),
consumer.getOwner()->operand_end());
if (operands.size() >= kIreeMaxOperandCount) return false;
llvm::SmallDenseSet<Operation *, 4> numUsers;
for (Operation *user : producer.getUsers()) {
if (isa<linalg::GenericOp>(user)) continue;
numUsers.insert(user);
}
return numUsers.empty();
};
// Simple heuristic to decide if reshaope should be folded in the linalg.
// If the source of the reshape is a linalg op fold to potentially allow the
// two linalg ops to be fused. Otherwise leave it to avoid adding dimensions
// to the consumer linalg op.
linalg::ControlElementwiseOpsFusionFn foldReshapeBetweenLinalgFn =
[](const OpResult &producer, const OpOperand &consumer) {
auto collapseOp =
producer.getDefiningOp<linalg::TensorCollapseShapeOp>();
if (collapseOp)
return collapseOp.src().getDefiningOp<LinalgOp>() != nullptr;
auto expandOp = producer.getDefiningOp<linalg::TensorExpandShapeOp>();
if (expandOp)
return expandOp.src().getDefiningOp<LinalgOp>() != nullptr;
return false;
};
linalg::populateElementwiseOpsFusionPatterns(
fusionPatterns,
linalg::LinalgElementwiseFusionOptions()
.setControlFoldingReshapes(foldReshapeBetweenLinalgFn)
.setControlElementwiseOpsFusionFn(controlFn));
(void)applyPatternsAndFoldGreedily(op->getRegions(),
std::move(fusionPatterns));
OwningRewritePatternList reshapeCanonicalizations(&getContext());
linalg::populateFoldUnitDimsReshapeOpsByLinearizationPatterns(
reshapeCanonicalizations);
linalg::TensorCollapseShapeOp::getCanonicalizationPatterns(
reshapeCanonicalizations, context);
linalg::TensorExpandShapeOp::getCanonicalizationPatterns(
reshapeCanonicalizations, context);
(void)applyPatternsAndFoldGreedily(op->getRegions(),
std::move(reshapeCanonicalizations));
// Push the remaining reshapes down the graphs.
OwningRewritePatternList pushReshapePatterns(&getContext());
linalg::populatePushReshapeOpsPatterns(pushReshapePatterns);
linalg::TensorCollapseShapeOp::getCanonicalizationPatterns(
pushReshapePatterns, context);
linalg::TensorExpandShapeOp::getCanonicalizationPatterns(
pushReshapePatterns, context);
(void)applyPatternsAndFoldGreedily(op->getRegions(),
std::move(pushReshapePatterns));
}
};
} // namespace
std::unique_ptr<Pass> createFusionOfTensorOpsPass() {
return std::make_unique<FusionOfTensorOpsPass>();
}
} // namespace Flow
} // namespace IREE
} // namespace iree_compiler
} // namespace mlir
<|endoftext|> |
<commit_before>/**
* SimpleTruthValue.cc
*
* @author Guilherme Lamacie
* @author Welter Silva
*/
#include "SimpleTruthValue.h"
#include "exceptions.h"
#include <math.h>
#define KKK 800.0f
SimpleTruthValue::SimpleTruthValue(float m, float c){
mean = m;
count = c;
}
SimpleTruthValue::SimpleTruthValue(SimpleTruthValue const& source) {
mean = source.mean;
count = source.count;
}
void SimpleTruthValue::setMean(float m){
mean = m;
}
void SimpleTruthValue::setCount(float c){
count = c;
}
void SimpleTruthValue::setConfidence(float c){
count = confidenceToCount(c);
}
float SimpleTruthValue::getMean() const{
return mean;
}
float SimpleTruthValue::getCount() const{
return count;
}
float SimpleTruthValue::getConfidence() const{
return countToConfidence(count);
}
float SimpleTruthValue::toFloat() const{
return getMean();
}
std::string SimpleTruthValue::toString() const{
char buf[1024];
// TODO: confidence is not needed for Saving&Loading. So, for saving memory space
// in dump files, it should be removed. However, toString is being used for debug
// purposes...
sprintf(buf, "[%f,%f=%f]", getMean(), getCount(),getConfidence());
return buf;
}
SimpleTruthValue* SimpleTruthValue::clone() const {
return new SimpleTruthValue(*this);
}
SimpleTruthValue& SimpleTruthValue::operator=(const TruthValue& rhs) throw (RuntimeException) {
const SimpleTruthValue* tv = dynamic_cast<const SimpleTruthValue*>(&rhs);
if (tv) {
if (tv != this) { // check if this is the same object first.
mean = tv->mean;
count = tv->count;
}
} else {
#if 0
// The following line was causing a compilation error on MSVC...
throw RuntimeException(TRACE_INFO, "Cannot assign a TV of type '%s' to one of type '%s'\n",
typeid(rhs).name(), typeid(*this).name());
#else
throw RuntimeException(TRACE_INFO,
"SimpleTruthValue - Invalid assignment of a SimpleTV object.");
#endif
}
return *this;
}
TruthValueType SimpleTruthValue::getType() const{
return SIMPLE_TRUTH_VALUE;
}
float SimpleTruthValue::confidenceToCount(float c) {
c = min(c, 0.9999999f);
return -KKK*c/(c-1);
}
float SimpleTruthValue::countToConfidence(float c) {
return (c/(c+KKK));
}
SimpleTruthValue* SimpleTruthValue::fromString(const char* tvStr) {
float mean, count, conf;
// TODO: confidence is not needed for Saving&Loading. So, for saving memory space
// in dump files, it should be removed. However, toString is being used for debug
// purposes...
sscanf(tvStr, "[%f,%f=%f]", &mean, &count,&conf);
//printf("SimpleTruthValue::fromString(%s) => mean = %f, count = %f, conf = %f\n", tvStr, mean, count, conf);
return new SimpleTruthValue(mean, count);
}
<commit_msg>eliminate spurious minus sign.<commit_after>/**
* SimpleTruthValue.cc
*
* @author Guilherme Lamacie
* @author Welter Silva
*/
#include "SimpleTruthValue.h"
#include "exceptions.h"
#include <math.h>
#define KKK 800.0f
SimpleTruthValue::SimpleTruthValue(float m, float c){
mean = m;
count = c;
}
SimpleTruthValue::SimpleTruthValue(SimpleTruthValue const& source) {
mean = source.mean;
count = source.count;
}
void SimpleTruthValue::setMean(float m){
mean = m;
}
void SimpleTruthValue::setCount(float c){
count = c;
}
void SimpleTruthValue::setConfidence(float c){
count = confidenceToCount(c);
}
float SimpleTruthValue::getMean() const{
return mean;
}
float SimpleTruthValue::getCount() const{
return count;
}
float SimpleTruthValue::getConfidence() const{
return countToConfidence(count);
}
float SimpleTruthValue::toFloat() const{
return getMean();
}
std::string SimpleTruthValue::toString() const{
char buf[1024];
// TODO: confidence is not needed for Saving&Loading. So, for saving memory space
// in dump files, it should be removed. However, toString is being used for debug
// purposes...
sprintf(buf, "[%f,%f=%f]", getMean(), getCount(),getConfidence());
return buf;
}
SimpleTruthValue* SimpleTruthValue::clone() const {
return new SimpleTruthValue(*this);
}
SimpleTruthValue& SimpleTruthValue::operator=(const TruthValue& rhs) throw (RuntimeException) {
const SimpleTruthValue* tv = dynamic_cast<const SimpleTruthValue*>(&rhs);
if (tv) {
if (tv != this) { // check if this is the same object first.
mean = tv->mean;
count = tv->count;
}
} else {
#if 0
// The following line was causing a compilation error on MSVC...
throw RuntimeException(TRACE_INFO, "Cannot assign a TV of type '%s' to one of type '%s'\n",
typeid(rhs).name(), typeid(*this).name());
#else
throw RuntimeException(TRACE_INFO,
"SimpleTruthValue - Invalid assignment of a SimpleTV object.");
#endif
}
return *this;
}
TruthValueType SimpleTruthValue::getType() const{
return SIMPLE_TRUTH_VALUE;
}
float SimpleTruthValue::confidenceToCount(float c) {
c = min(c, 0.9999999f);
return KKK*c/(1.0-c);
}
float SimpleTruthValue::countToConfidence(float c) {
return (c/(c+KKK));
}
SimpleTruthValue* SimpleTruthValue::fromString(const char* tvStr) {
float mean, count, conf;
// TODO: confidence is not needed for Saving&Loading. So, for saving memory space
// in dump files, it should be removed. However, toString is being used for debug
// purposes...
sscanf(tvStr, "[%f,%f=%f]", &mean, &count,&conf);
//printf("SimpleTruthValue::fromString(%s) => mean = %f, count = %f, conf = %f\n", tvStr, mean, count, conf);
return new SimpleTruthValue(mean, count);
}
<|endoftext|> |
<commit_before>// RUN: %clang_cc1 -S -emit-llvm -g %s -o - | FileCheck %s
template <typename T>
struct a {
};
extern template class a<int>;
// CHECK-NOT: ; [ DW_TAG_structure_type ] [a<int>]
template <typename T>
struct b {
};
extern template class b<int>;
b<int> bi;
// CHECK: ; [ DW_TAG_structure_type ] [b<int>] {{.*}} [def]
template <typename T>
struct c {
void f() {}
};
extern template class c<int>;
c<int> ci;
// CHECK: ; [ DW_TAG_structure_type ] [c<int>] {{.*}} [decl]
template <typename T>
struct d {
void f();
};
extern template class d<int>;
d<int> di;
// CHECK: ; [ DW_TAG_structure_type ] [d<int>] {{.*}} [def]
template <typename T>
struct e {
void f();
};
template <typename T>
void e<T>::f() {
}
extern template class e<int>;
e<int> ei;
// CHECK: ; [ DW_TAG_structure_type ] [e<int>] {{.*}} [decl]
template <typename T>
struct f {
void g();
};
extern template class f<int>;
template <typename T>
void f<T>::g() {
}
f<int> fi;
// Is this right? We don't seem to emit a def for 'f<int>::g' (even if it is
// called in this translation unit) so I guess if we're relying on its
// definition to be wherever the explicit instantiation definition is, we can do
// the same for the debug info.
// CHECK: ; [ DW_TAG_structure_type ] [f<int>] {{.*}} [decl]
template <typename T>
struct g {
void f();
};
template <>
void g<int>::f();
extern template class g<int>;
g<int> gi;
// CHECK: ; [ DW_TAG_structure_type ] [g<int>] {{.*}} [def]
template <typename T>
struct h {
};
template class h<int>;
// CHECK: ; [ DW_TAG_structure_type ] [h<int>] {{.*}} [def]
<commit_msg>Add triple to test. On Mac OS it was failing to generate debug info which matched the check lines<commit_after>// RUN: %clang_cc1 -S -emit-llvm -g %s -o - -triple=x86_64-unknown-unknown | FileCheck %s
template <typename T>
struct a {
};
extern template class a<int>;
// CHECK-NOT: ; [ DW_TAG_structure_type ] [a<int>]
template <typename T>
struct b {
};
extern template class b<int>;
b<int> bi;
// CHECK: ; [ DW_TAG_structure_type ] [b<int>] {{.*}} [def]
template <typename T>
struct c {
void f() {}
};
extern template class c<int>;
c<int> ci;
// CHECK: ; [ DW_TAG_structure_type ] [c<int>] {{.*}} [decl]
template <typename T>
struct d {
void f();
};
extern template class d<int>;
d<int> di;
// CHECK: ; [ DW_TAG_structure_type ] [d<int>] {{.*}} [def]
template <typename T>
struct e {
void f();
};
template <typename T>
void e<T>::f() {
}
extern template class e<int>;
e<int> ei;
// CHECK: ; [ DW_TAG_structure_type ] [e<int>] {{.*}} [decl]
template <typename T>
struct f {
void g();
};
extern template class f<int>;
template <typename T>
void f<T>::g() {
}
f<int> fi;
// Is this right? We don't seem to emit a def for 'f<int>::g' (even if it is
// called in this translation unit) so I guess if we're relying on its
// definition to be wherever the explicit instantiation definition is, we can do
// the same for the debug info.
// CHECK: ; [ DW_TAG_structure_type ] [f<int>] {{.*}} [decl]
template <typename T>
struct g {
void f();
};
template <>
void g<int>::f();
extern template class g<int>;
g<int> gi;
// CHECK: ; [ DW_TAG_structure_type ] [g<int>] {{.*}} [def]
template <typename T>
struct h {
};
template class h<int>;
// CHECK: ; [ DW_TAG_structure_type ] [h<int>] {{.*}} [def]
<|endoftext|> |
<commit_before>#include "ContentWindowGraphicsItem.h"
#include "Content.h"
#include "ContentWindowManager.h"
#include "DisplayGroupManager.h"
#include "DisplayGroupGraphicsView.h"
#include "main.h"
qreal ContentWindowGraphicsItem::zCounter_ = 0;
ContentWindowGraphicsItem::ContentWindowGraphicsItem(boost::shared_ptr<ContentWindowManager> contentWindowManager) : ContentWindowInterface(contentWindowManager)
{
// defaults
resizing_ = false;
// graphics items are movable
setFlag(QGraphicsItem::ItemIsMovable, true);
// default fill color / opacity
setBrush(QBrush(QColor(0, 0, 0, 128)));
// border based on if we're selected or not
// use the -1 argument to force an update but not emit signals
setSelected(selected_, (ContentWindowInterface *)-1);
// current coordinates
setRect(x_, y_, w_, h_);
// new items at the front
// we assume that interface items will be constructed in depth order so this produces the correct result...
setZToFront();
}
void ContentWindowGraphicsItem::paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget)
{
QGraphicsRectItem::paint(painter, option, widget);
boost::shared_ptr<ContentWindowManager> contentWindowManager = getContentWindowManager();
if(contentWindowManager != NULL)
{
// default pen
QPen pen;
// button dimensions
float buttonWidth, buttonHeight;
getButtonDimensions(buttonWidth, buttonHeight);
// draw close button
QRectF closeRect(rect().x() + rect().width() - buttonWidth, rect().y(), buttonWidth, buttonHeight);
pen.setColor(QColor(255,0,0));
painter->setPen(pen);
painter->drawRect(closeRect);
painter->drawLine(QPointF(rect().x() + rect().width() - buttonWidth, rect().y()), QPointF(rect().x() + rect().width(), rect().y() + buttonHeight));
painter->drawLine(QPointF(rect().x() + rect().width(), rect().y()), QPointF(rect().x() + rect().width() - buttonWidth, rect().y() + buttonHeight));
// resize indicator
QRectF resizeRect(rect().x() + rect().width() - buttonWidth, rect().y() + rect().height() - buttonHeight, buttonWidth, buttonHeight);
pen.setColor(QColor(128,128,128));
painter->setPen(pen);
painter->drawRect(resizeRect);
painter->drawLine(QPointF(rect().x() + rect().width(), rect().y() + rect().height() - buttonHeight), QPointF(rect().x() + rect().width() - buttonWidth, rect().y() + rect().height()));
// text label
// set the font
float fontSize = 24.;
QFont font;
font.setPixelSize(fontSize);
painter->setFont(font);
// color the text black
pen.setColor(QColor(0,0,0));
painter->setPen(pen);
// scale the text size down to the height of the graphics view
// and, calculate the bounding rectangle for the text based on this scale
// the dimensions of the view need to be corrected for the tiled display aspect ratio
// recall the tiled display UI is only part of the graphics view since we show it at the correct aspect ratio
float viewWidth = (float)scene()->views()[0]->width();
float viewHeight = (float)scene()->views()[0]->height();
float tiledDisplayAspect = (float)g_configuration->getTotalWidth() / (float)g_configuration->getTotalHeight();
if(viewWidth / viewHeight > tiledDisplayAspect)
{
viewWidth = viewHeight * tiledDisplayAspect;
}
else if(viewWidth / viewHeight <= tiledDisplayAspect)
{
viewHeight = viewWidth / tiledDisplayAspect;
}
float verticalTextScale = 1. / viewHeight;
float horizontalTextScale = viewHeight / viewWidth * verticalTextScale;
painter->scale(horizontalTextScale, verticalTextScale);
QRectF textBoundingRect = QRectF(rect().x() / horizontalTextScale, rect().y() / verticalTextScale, rect().width() / horizontalTextScale, rect().height() / verticalTextScale);
// get the label and render it
QString label(contentWindowManager->getContent()->getURI().c_str());
QString labelSection = label.section("/", -1, -1).prepend(" ");
painter->drawText(textBoundingRect, Qt::AlignLeft | Qt::AlignTop, labelSection);
// draw window info at smaller scale
verticalTextScale *= 0.5;
horizontalTextScale *= 0.5;
painter->scale(0.5, 0.5);
textBoundingRect = QRectF(rect().x() / horizontalTextScale, rect().y() / verticalTextScale, rect().width() / horizontalTextScale, rect().height() / verticalTextScale);
QString coordinatesLabel = QString(" (") + QString::number(x_, 'f', 2) + QString(" ,") + QString::number(y_, 'f', 2) + QString(", ") + QString::number(w_, 'f', 2) + QString(", ") + QString::number(h_, 'f', 2) + QString(")\n");
QString zoomCenterLabel = QString(" zoom = ") + QString::number(zoom_, 'f', 2) + QString(" @ (") + QString::number(centerX_, 'f', 2) + QString(", ") + QString::number(centerY_, 'f', 2) + QString(")");
QString windowInfoLabel = coordinatesLabel + zoomCenterLabel;
painter->drawText(textBoundingRect, Qt::AlignLeft | Qt::AlignBottom, windowInfoLabel);
}
}
void ContentWindowGraphicsItem::setCoordinates(double x, double y, double w, double h, ContentWindowInterface * source)
{
ContentWindowInterface::setCoordinates(x, y, w, h, source);
if(source != this)
{
setPos(x_, y_);
setRect(mapRectFromScene(x_, y_, w_, h_));
}
}
void ContentWindowGraphicsItem::setPosition(double x, double y, ContentWindowInterface * source)
{
ContentWindowInterface::setPosition(x, y, source);
if(source != this)
{
setPos(x_, y_);
setRect(mapRectFromScene(x_, y_, w_, h_));
}
}
void ContentWindowGraphicsItem::setSize(double w, double h, ContentWindowInterface * source)
{
ContentWindowInterface::setSize(w, h, source);
if(source != this)
{
setPos(x_, y_);
setRect(mapRectFromScene(x_, y_, w_, h_));
}
}
void ContentWindowGraphicsItem::setCenter(double centerX, double centerY, ContentWindowInterface * source)
{
ContentWindowInterface::setCenter(centerX, centerY, source);
if(source != this)
{
// force a redraw to update window info label
update();
}
}
void ContentWindowGraphicsItem::setZoom(double zoom, ContentWindowInterface * source)
{
ContentWindowInterface::setZoom(zoom, source);
if(source != this)
{
// force a redraw to update window info label
update();
}
}
void ContentWindowGraphicsItem::setSelected(bool selected, ContentWindowInterface * source)
{
ContentWindowInterface::setSelected(selected, source);
if(source != this)
{
// set the pen
QPen p = pen();
if(selected_ == true)
{
p.setColor(QColor(255,0,0));
}
else
{
p.setColor(QColor(0,0,0));
}
setPen(p);
// force a redraw
update();
}
}
void ContentWindowGraphicsItem::setZToFront()
{
zCounter_ = zCounter_ + 1;
setZValue(zCounter_);
}
void ContentWindowGraphicsItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event)
{
// handle mouse movements differently depending on selected mode of item
if(selected_ == false)
{
if(event->buttons().testFlag(Qt::LeftButton) == true)
{
if(resizing_ == true)
{
QRectF r = rect();
QPointF eventPos = event->pos();
r.setBottomRight(eventPos);
QRectF sceneRect = mapRectToScene(r);
double w = sceneRect.width();
double h = sceneRect.height();
setSize(w, h);
}
else
{
QPointF delta = event->pos() - event->lastPos();
double x = x_ + delta.x();
double y = y_ + delta.y();
setPosition(x, y);
}
}
}
else
{
// handle zooms / pans
QPointF delta = event->scenePos() - event->lastScenePos();
if(event->buttons().testFlag(Qt::RightButton) == true)
{
// increment zoom
// if this is a touch event, use cross-product for determining change in zoom (counterclockwise rotation == zoom in, etc.)
// otherwise, use y as the change in zoom
double zoomDelta;
if(event->modifiers().testFlag(Qt::AltModifier) == true)
{
zoomDelta = (event->scenePos().x()-0.5) * delta.y() - (event->scenePos().y()-0.5) * delta.x();
zoomDelta *= 2.;
}
else
{
zoomDelta = delta.y();
}
double zoom = zoom_ * (1. - zoomDelta);
setZoom(zoom);
}
else if(event->buttons().testFlag(Qt::LeftButton) == true)
{
// pan (move center coordinates)
double centerX = centerX_ + 2.*delta.x() / zoom_;
double centerY = centerY_ + 2.*delta.y() / zoom_;
setCenter(centerX, centerY);
}
// force a redraw to update window info label
update();
}
}
void ContentWindowGraphicsItem::mousePressEvent(QGraphicsSceneMouseEvent * event)
{
// button dimensions
float buttonWidth, buttonHeight;
getButtonDimensions(buttonWidth, buttonHeight);
// item rectangle and event position
QRectF r = rect();
QPointF eventPos = event->pos();
// check to see if user clicked on the close button
if(fabs((r.x()+r.width()) - eventPos.x()) <= buttonWidth && fabs((r.y()) - eventPos.y()) <= buttonHeight)
{
close();
return;
}
// check to see if user clicked on the resize button
if(fabs((r.x()+r.width()) - eventPos.x()) <= buttonWidth && fabs((r.y()+r.height()) - eventPos.y()) <= buttonHeight)
{
resizing_ = true;
}
// move to the front of the GUI display
moveToFront();
QGraphicsItem::mousePressEvent(event);
}
void ContentWindowGraphicsItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent * event)
{
bool selected = !selected_;
setSelected(selected);
QGraphicsItem::mouseDoubleClickEvent(event);
}
void ContentWindowGraphicsItem::mouseReleaseEvent(QGraphicsSceneMouseEvent * event)
{
resizing_ = false;
QGraphicsItem::mouseReleaseEvent(event);
}
void ContentWindowGraphicsItem::wheelEvent(QGraphicsSceneWheelEvent * event)
{
// handle wheel movements differently depending on selected mode of item
if(selected_ == false)
{
// scale size based on wheel delta
// typical delta value is 120, so scale based on that
double factor = 1. + (double)event->delta() / (10. * 120.);
scaleSize(factor);
}
else
{
// change zoom based on wheel delta
// deltas are counted in 1/8 degrees. so, scale based on 180 degrees => delta = 180*8 = 1440
double zoomDelta = (double)event->delta() / 1440.;
double zoom = zoom_ * (1. + zoomDelta);
setZoom(zoom);
}
}
<commit_msg>Qt 4.7+ sends mouse events to the wrong graphics items on Mac. implemented a workaround to fix the problem.<commit_after>#include "ContentWindowGraphicsItem.h"
#include "Content.h"
#include "ContentWindowManager.h"
#include "DisplayGroupManager.h"
#include "DisplayGroupGraphicsView.h"
#include "main.h"
qreal ContentWindowGraphicsItem::zCounter_ = 0;
ContentWindowGraphicsItem::ContentWindowGraphicsItem(boost::shared_ptr<ContentWindowManager> contentWindowManager) : ContentWindowInterface(contentWindowManager)
{
// defaults
resizing_ = false;
// graphics items are movable
setFlag(QGraphicsItem::ItemIsMovable, true);
// default fill color / opacity
setBrush(QBrush(QColor(0, 0, 0, 128)));
// border based on if we're selected or not
// use the -1 argument to force an update but not emit signals
setSelected(selected_, (ContentWindowInterface *)-1);
// current coordinates
setRect(x_, y_, w_, h_);
// new items at the front
// we assume that interface items will be constructed in depth order so this produces the correct result...
setZToFront();
}
void ContentWindowGraphicsItem::paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget)
{
QGraphicsRectItem::paint(painter, option, widget);
boost::shared_ptr<ContentWindowManager> contentWindowManager = getContentWindowManager();
if(contentWindowManager != NULL)
{
// default pen
QPen pen;
// button dimensions
float buttonWidth, buttonHeight;
getButtonDimensions(buttonWidth, buttonHeight);
// draw close button
QRectF closeRect(rect().x() + rect().width() - buttonWidth, rect().y(), buttonWidth, buttonHeight);
pen.setColor(QColor(255,0,0));
painter->setPen(pen);
painter->drawRect(closeRect);
painter->drawLine(QPointF(rect().x() + rect().width() - buttonWidth, rect().y()), QPointF(rect().x() + rect().width(), rect().y() + buttonHeight));
painter->drawLine(QPointF(rect().x() + rect().width(), rect().y()), QPointF(rect().x() + rect().width() - buttonWidth, rect().y() + buttonHeight));
// resize indicator
QRectF resizeRect(rect().x() + rect().width() - buttonWidth, rect().y() + rect().height() - buttonHeight, buttonWidth, buttonHeight);
pen.setColor(QColor(128,128,128));
painter->setPen(pen);
painter->drawRect(resizeRect);
painter->drawLine(QPointF(rect().x() + rect().width(), rect().y() + rect().height() - buttonHeight), QPointF(rect().x() + rect().width() - buttonWidth, rect().y() + rect().height()));
// text label
// set the font
float fontSize = 24.;
QFont font;
font.setPixelSize(fontSize);
painter->setFont(font);
// color the text black
pen.setColor(QColor(0,0,0));
painter->setPen(pen);
// scale the text size down to the height of the graphics view
// and, calculate the bounding rectangle for the text based on this scale
// the dimensions of the view need to be corrected for the tiled display aspect ratio
// recall the tiled display UI is only part of the graphics view since we show it at the correct aspect ratio
float viewWidth = (float)scene()->views()[0]->width();
float viewHeight = (float)scene()->views()[0]->height();
float tiledDisplayAspect = (float)g_configuration->getTotalWidth() / (float)g_configuration->getTotalHeight();
if(viewWidth / viewHeight > tiledDisplayAspect)
{
viewWidth = viewHeight * tiledDisplayAspect;
}
else if(viewWidth / viewHeight <= tiledDisplayAspect)
{
viewHeight = viewWidth / tiledDisplayAspect;
}
float verticalTextScale = 1. / viewHeight;
float horizontalTextScale = viewHeight / viewWidth * verticalTextScale;
painter->scale(horizontalTextScale, verticalTextScale);
QRectF textBoundingRect = QRectF(rect().x() / horizontalTextScale, rect().y() / verticalTextScale, rect().width() / horizontalTextScale, rect().height() / verticalTextScale);
// get the label and render it
QString label(contentWindowManager->getContent()->getURI().c_str());
QString labelSection = label.section("/", -1, -1).prepend(" ");
painter->drawText(textBoundingRect, Qt::AlignLeft | Qt::AlignTop, labelSection);
// draw window info at smaller scale
verticalTextScale *= 0.5;
horizontalTextScale *= 0.5;
painter->scale(0.5, 0.5);
textBoundingRect = QRectF(rect().x() / horizontalTextScale, rect().y() / verticalTextScale, rect().width() / horizontalTextScale, rect().height() / verticalTextScale);
QString coordinatesLabel = QString(" (") + QString::number(x_, 'f', 2) + QString(" ,") + QString::number(y_, 'f', 2) + QString(", ") + QString::number(w_, 'f', 2) + QString(", ") + QString::number(h_, 'f', 2) + QString(")\n");
QString zoomCenterLabel = QString(" zoom = ") + QString::number(zoom_, 'f', 2) + QString(" @ (") + QString::number(centerX_, 'f', 2) + QString(", ") + QString::number(centerY_, 'f', 2) + QString(")");
QString windowInfoLabel = coordinatesLabel + zoomCenterLabel;
painter->drawText(textBoundingRect, Qt::AlignLeft | Qt::AlignBottom, windowInfoLabel);
}
}
void ContentWindowGraphicsItem::setCoordinates(double x, double y, double w, double h, ContentWindowInterface * source)
{
ContentWindowInterface::setCoordinates(x, y, w, h, source);
if(source != this)
{
setPos(x_, y_);
setRect(mapRectFromScene(x_, y_, w_, h_));
}
}
void ContentWindowGraphicsItem::setPosition(double x, double y, ContentWindowInterface * source)
{
ContentWindowInterface::setPosition(x, y, source);
if(source != this)
{
setPos(x_, y_);
setRect(mapRectFromScene(x_, y_, w_, h_));
}
}
void ContentWindowGraphicsItem::setSize(double w, double h, ContentWindowInterface * source)
{
ContentWindowInterface::setSize(w, h, source);
if(source != this)
{
setPos(x_, y_);
setRect(mapRectFromScene(x_, y_, w_, h_));
}
}
void ContentWindowGraphicsItem::setCenter(double centerX, double centerY, ContentWindowInterface * source)
{
ContentWindowInterface::setCenter(centerX, centerY, source);
if(source != this)
{
// force a redraw to update window info label
update();
}
}
void ContentWindowGraphicsItem::setZoom(double zoom, ContentWindowInterface * source)
{
ContentWindowInterface::setZoom(zoom, source);
if(source != this)
{
// force a redraw to update window info label
update();
}
}
void ContentWindowGraphicsItem::setSelected(bool selected, ContentWindowInterface * source)
{
ContentWindowInterface::setSelected(selected, source);
if(source != this)
{
// set the pen
QPen p = pen();
if(selected_ == true)
{
p.setColor(QColor(255,0,0));
}
else
{
p.setColor(QColor(0,0,0));
}
setPen(p);
// force a redraw
update();
}
}
void ContentWindowGraphicsItem::setZToFront()
{
zCounter_ = zCounter_ + 1;
setZValue(zCounter_);
}
void ContentWindowGraphicsItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event)
{
// handle mouse movements differently depending on selected mode of item
if(selected_ == false)
{
if(event->buttons().testFlag(Qt::LeftButton) == true)
{
if(resizing_ == true)
{
QRectF r = rect();
QPointF eventPos = event->pos();
r.setBottomRight(eventPos);
QRectF sceneRect = mapRectToScene(r);
double w = sceneRect.width();
double h = sceneRect.height();
setSize(w, h);
}
else
{
QPointF delta = event->pos() - event->lastPos();
double x = x_ + delta.x();
double y = y_ + delta.y();
setPosition(x, y);
}
}
}
else
{
// handle zooms / pans
QPointF delta = event->scenePos() - event->lastScenePos();
if(event->buttons().testFlag(Qt::RightButton) == true)
{
// increment zoom
// if this is a touch event, use cross-product for determining change in zoom (counterclockwise rotation == zoom in, etc.)
// otherwise, use y as the change in zoom
double zoomDelta;
if(event->modifiers().testFlag(Qt::AltModifier) == true)
{
zoomDelta = (event->scenePos().x()-0.5) * delta.y() - (event->scenePos().y()-0.5) * delta.x();
zoomDelta *= 2.;
}
else
{
zoomDelta = delta.y();
}
double zoom = zoom_ * (1. - zoomDelta);
setZoom(zoom);
}
else if(event->buttons().testFlag(Qt::LeftButton) == true)
{
// pan (move center coordinates)
double centerX = centerX_ + 2.*delta.x() / zoom_;
double centerY = centerY_ + 2.*delta.y() / zoom_;
setCenter(centerX, centerY);
}
// force a redraw to update window info label
update();
}
}
void ContentWindowGraphicsItem::mousePressEvent(QGraphicsSceneMouseEvent * event)
{
// on Mac we've seen that mouse events can go to the wrong graphics item
// this is due to the bug: https://bugreports.qt.nokia.com/browse/QTBUG-20493
// here we ignore the event if it shouldn't have been sent to us, which ensures
// it will go to the correct item...
if(boundingRect().contains(event->pos()) == false)
{
event->ignore();
return;
}
// button dimensions
float buttonWidth, buttonHeight;
getButtonDimensions(buttonWidth, buttonHeight);
// item rectangle and event position
QRectF r = rect();
QPointF eventPos = event->pos();
// check to see if user clicked on the close button
if(fabs((r.x()+r.width()) - eventPos.x()) <= buttonWidth && fabs((r.y()) - eventPos.y()) <= buttonHeight)
{
close();
return;
}
// check to see if user clicked on the resize button
if(fabs((r.x()+r.width()) - eventPos.x()) <= buttonWidth && fabs((r.y()+r.height()) - eventPos.y()) <= buttonHeight)
{
resizing_ = true;
}
// move to the front of the GUI display
moveToFront();
QGraphicsItem::mousePressEvent(event);
}
void ContentWindowGraphicsItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent * event)
{
// on Mac we've seen that mouse events can go to the wrong graphics item
// this is due to the bug: https://bugreports.qt.nokia.com/browse/QTBUG-20493
// here we ignore the event if it shouldn't have been sent to us, which ensures
// it will go to the correct item...
if(boundingRect().contains(event->pos()) == false)
{
event->ignore();
return;
}
bool selected = !selected_;
setSelected(selected);
QGraphicsItem::mouseDoubleClickEvent(event);
}
void ContentWindowGraphicsItem::mouseReleaseEvent(QGraphicsSceneMouseEvent * event)
{
resizing_ = false;
QGraphicsItem::mouseReleaseEvent(event);
}
void ContentWindowGraphicsItem::wheelEvent(QGraphicsSceneWheelEvent * event)
{
// on Mac we've seen that mouse events can go to the wrong graphics item
// this is due to the bug: https://bugreports.qt.nokia.com/browse/QTBUG-20493
// here we ignore the event if it shouldn't have been sent to us, which ensures
// it will go to the correct item...
if(boundingRect().contains(event->pos()) == false)
{
event->ignore();
return;
}
// handle wheel movements differently depending on selected mode of item
if(selected_ == false)
{
// scale size based on wheel delta
// typical delta value is 120, so scale based on that
double factor = 1. + (double)event->delta() / (10. * 120.);
scaleSize(factor);
}
else
{
// change zoom based on wheel delta
// deltas are counted in 1/8 degrees. so, scale based on 180 degrees => delta = 180*8 = 1440
double zoomDelta = (double)event->delta() / 1440.;
double zoom = zoom_ * (1. + zoomDelta);
setZoom(zoom);
}
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2009-2012 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "CoordinatorService.h"
#include "CoordinatorServiceRecovery.h"
namespace RAMCloud {
CoordinatorServiceRecovery::CoordinatorServiceRecovery(
CoordinatorService& coordinatorService)
: service(coordinatorService)
{
}
CoordinatorServiceRecovery::~CoordinatorServiceRecovery()
{
}
/**
* Replay the LogCabin log, parse the log entries to extract the states,
* and dispatch to the appropriate recovery methods in CoordinatorServerManger.
*/
void
CoordinatorServiceRecovery::replay(bool testing)
{
// Get all the entries appended to the log.
// TODO(ankitak): After ongaro has added curser API to LogCabin,
// use that to read in one entry at a time.
// Also, since LogCabin doesn't have a log cleaner yet, a read()
// returns all entries, including those that were invalidated.
// Thus, use the temporary workaround function,
// LogCabinHelper::readValidEntries() that returns only valid entries.
vector<Entry> entriesRead = service.logCabinHelper->readValidEntries();
for (vector<Entry>::iterator it = entriesRead.begin();
it < entriesRead.end(); it++) {
EntryId entryId = it->getId();
string entryType = service.logCabinHelper->getEntryType(*it);
RAMCLOUD_LOG(DEBUG, "Entry Id: %lu, Entry Type: %s\n",
entryId, entryType.c_str());
if (testing) continue;
// Dispatch
if (!entryType.compare("ServerEnlisted")) {
RAMCLOUD_LOG(DEBUG, "ServiceRecovery: ServerEnlisted");
ProtoBuf::ServerInformation state;
service.logCabinHelper->parseProtoBufFromEntry(*it, state);
service.serverList->recoverAliveServer(&state, entryId);
} else if (!entryType.compare("AppendServerAlive")) {
RAMCLOUD_LOG(DEBUG, "ServiceRecovery: AppendServerAlive");
service.serverList->recoverAppendServerAlive(entryId);
} else if (!entryType.compare("ServerEnlisting")) {
RAMCLOUD_LOG(DEBUG, "ServiceRecovery: ServerEnlisting");
ProtoBuf::ServerInformation state;
service.logCabinHelper->parseProtoBufFromEntry(*it, state);
service.serverList->recoverEnlistServer(&state, entryId);
} else if (!entryType.compare("ServerCrashed")) {
RAMCLOUD_LOG(DEBUG, "ServiceRecovery: ServerCrashed");
ProtoBuf::ServerCrashInfo state;
service.logCabinHelper->parseProtoBufFromEntry(*it, state);
service.serverList->recoverServerCrashed(&state, entryId);
} else if (!entryType.compare("ServerListVersion")) {
RAMCLOUD_LOG(DEBUG, "ServiceRecovery: ServerListVersion");
ProtoBuf::ServerListVersion state;
service.logCabinHelper->parseProtoBufFromEntry(*it, state);
service.serverList->recoverServerListVersion(&state, entryId);
} else if (!entryType.compare("ServerNeedsRecovery")) {
RAMCLOUD_LOG(DEBUG, "ServiceRecovery: ServerNeedsRecovery");
ProtoBuf::ServerCrashInfo state;
service.logCabinHelper->parseProtoBufFromEntry(*it, state);
service.serverList->recoverServerNeedsRecovery(&state, entryId);
} else if (!entryType.compare("ServerUpdate")) {
RAMCLOUD_LOG(DEBUG, "ServiceRecovery: ServerUpdate");
ProtoBuf::ServerUpdate state;
service.logCabinHelper->parseProtoBufFromEntry(*it, state);
service.serverList->recoverServerUpdate(&state, entryId);
} else if (!entryType.compare("AliveTable")) {
RAMCLOUD_LOG(DEBUG, "ServiceRecovery: AliveTable");
ProtoBuf::TableInformation state;
service.logCabinHelper->parseProtoBufFromEntry(*it, state);
service.tableManager->recoverAliveTable(&state, entryId);
} else if (!entryType.compare("CreatingTable")) {
RAMCLOUD_LOG(DEBUG, "ServiceRecovery: CreatingTable");
ProtoBuf::TableInformation state;
service.logCabinHelper->parseProtoBufFromEntry(*it, state);
service.tableManager->recoverCreateTable(&state, entryId);
} else if (!entryType.compare("DroppingTable")) {
RAMCLOUD_LOG(DEBUG, "ServiceRecovery: DroppingTable");
ProtoBuf::TableDrop state;
service.logCabinHelper->parseProtoBufFromEntry(*it, state);
service.tableManager->recoverDropTable(&state, entryId);
} else if (!entryType.compare("SplitTablet")) {
RAMCLOUD_LOG(DEBUG, "ServiceRecovery: SplitTablet");
ProtoBuf::SplitTablet state;
service.logCabinHelper->parseProtoBufFromEntry(*it, state);
service.tableManager->recoverSplitTablet(&state, entryId);
} else if (!entryType.compare("TabletRecovered")) {
RAMCLOUD_LOG(DEBUG, "ServiceRecovery: TabletRecovered");
ProtoBuf::TabletRecovered state;
service.logCabinHelper->parseProtoBufFromEntry(*it, state);
service.tableManager->recoverTabletRecovered(&state, entryId);
} else {
// Ignore, and continue.
// There could be entries appended by processes other than the
// Coordinator that we want to ignore.
RAMCLOUD_LOG(DEBUG, "ServiceRecovery: Unknown type");
}
}
}
} // namespace RAMCloud
<commit_msg>Bug fix in Coordinator Recovery.<commit_after>/* Copyright (c) 2009-2012 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "CoordinatorService.h"
#include "CoordinatorServiceRecovery.h"
namespace RAMCloud {
CoordinatorServiceRecovery::CoordinatorServiceRecovery(
CoordinatorService& coordinatorService)
: service(coordinatorService)
{
}
CoordinatorServiceRecovery::~CoordinatorServiceRecovery()
{
}
/**
* Replay the LogCabin log, parse the log entries to extract the states,
* and dispatch to the appropriate recovery methods in CoordinatorServerManger.
*/
void
CoordinatorServiceRecovery::replay(bool testing)
{
// Get all the entries appended to the log.
// TODO(ankitak): After ongaro has added curser API to LogCabin,
// use that to read in one entry at a time.
// Also, since LogCabin doesn't have a log cleaner yet, a read()
// returns all entries, including those that were invalidated.
// Thus, use the temporary workaround function,
// LogCabinHelper::readValidEntries() that returns only valid entries.
vector<Entry> entriesRead = service.logCabinHelper->readValidEntries();
for (vector<Entry>::iterator it = entriesRead.begin();
it < entriesRead.end(); it++) {
EntryId entryId = it->getId();
string entryType = service.logCabinHelper->getEntryType(*it);
RAMCLOUD_LOG(DEBUG, "Entry Id: %lu, Entry Type: %s\n",
entryId, entryType.c_str());
if (testing) continue;
// Dispatch
if (entryType.compare("ServerEnlisted") == 0) {
RAMCLOUD_LOG(DEBUG, "ServiceRecovery: ServerEnlisted");
ProtoBuf::ServerInformation state;
service.logCabinHelper->parseProtoBufFromEntry(*it, state);
service.serverList->recoverAliveServer(&state, entryId);
} else if (entryType.compare("AppendServerAlive") == 0) {
RAMCLOUD_LOG(DEBUG, "ServiceRecovery: AppendServerAlive");
service.serverList->recoverAppendServerAlive(entryId);
} else if (entryType.compare("ServerEnlisting") == 0) {
RAMCLOUD_LOG(DEBUG, "ServiceRecovery: ServerEnlisting");
ProtoBuf::ServerInformation state;
service.logCabinHelper->parseProtoBufFromEntry(*it, state);
service.serverList->recoverEnlistServer(&state, entryId);
} else if (entryType.compare("ServerCrashed") == 0) {
RAMCLOUD_LOG(DEBUG, "ServiceRecovery: ServerCrashed");
ProtoBuf::ServerCrashInfo state;
service.logCabinHelper->parseProtoBufFromEntry(*it, state);
service.serverList->recoverServerCrashed(&state, entryId);
} else if (entryType.compare("ServerListVersion") == 0) {
RAMCLOUD_LOG(DEBUG, "ServiceRecovery: ServerListVersion");
ProtoBuf::ServerListVersion state;
service.logCabinHelper->parseProtoBufFromEntry(*it, state);
service.serverList->recoverServerListVersion(&state, entryId);
} else if (entryType.compare("ServerNeedsRecovery") == 0) {
RAMCLOUD_LOG(DEBUG, "ServiceRecovery: ServerNeedsRecovery");
ProtoBuf::ServerCrashInfo state;
service.logCabinHelper->parseProtoBufFromEntry(*it, state);
service.serverList->recoverServerNeedsRecovery(&state, entryId);
} else if (entryType.compare("ServerUpdate") == 0) {
RAMCLOUD_LOG(DEBUG, "ServiceRecovery: ServerUpdate");
ProtoBuf::ServerUpdate state;
service.logCabinHelper->parseProtoBufFromEntry(*it, state);
service.serverList->recoverServerUpdate(&state, entryId);
} else if (entryType.compare("AliveTable") == 0) {
RAMCLOUD_LOG(DEBUG, "ServiceRecovery: AliveTable");
ProtoBuf::TableInformation state;
service.logCabinHelper->parseProtoBufFromEntry(*it, state);
service.tableManager->recoverAliveTable(&state, entryId);
} else if (entryType.compare("CreatingTable") == 0) {
RAMCLOUD_LOG(DEBUG, "ServiceRecovery: CreatingTable");
ProtoBuf::TableInformation state;
service.logCabinHelper->parseProtoBufFromEntry(*it, state);
service.tableManager->recoverCreateTable(&state, entryId);
} else if (entryType.compare("DroppingTable") == 0) {
RAMCLOUD_LOG(DEBUG, "ServiceRecovery: DroppingTable");
ProtoBuf::TableDrop state;
service.logCabinHelper->parseProtoBufFromEntry(*it, state);
service.tableManager->recoverDropTable(&state, entryId);
} else if (entryType.compare("SplitTablet") == 0) {
RAMCLOUD_LOG(DEBUG, "ServiceRecovery: SplitTablet");
ProtoBuf::SplitTablet state;
service.logCabinHelper->parseProtoBufFromEntry(*it, state);
service.tableManager->recoverSplitTablet(&state, entryId);
} else if (entryType.compare("TabletRecovered") == 0) {
RAMCLOUD_LOG(DEBUG, "ServiceRecovery: TabletRecovered");
ProtoBuf::TabletRecovered state;
service.logCabinHelper->parseProtoBufFromEntry(*it, state);
service.tableManager->recoverTabletRecovered(&state, entryId);
} else {
// Ignore, and continue.
// There could be entries appended by processes other than the
// Coordinator that we want to ignore.
RAMCLOUD_LOG(DEBUG, "ServiceRecovery: Unknown type");
}
}
}
} // namespace RAMCloud
<|endoftext|> |
<commit_before>#include <osg/Transform>
#include <osg/Billboard>
#include <osg/Geode>
#include <osg/Group>
#include <osg/Notify>
#include <osg/Material>
#include <osg/PolygonOffset>
#include <osg/PolygonMode>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgUtil/TrackballManipulator>
#include <osgUtil/FlightManipulator>
#include <osgUtil/DriveManipulator>
#include <osgGLUT/glut>
#include <osgGLUT/Viewer>
#include <osgUtil/Optimizer>
void write_usage(std::ostream& out,const std::string& name)
{
out << std::endl;
out <<"usage:"<< std::endl;
out <<" "<<name<<" [options] infile1 [infile2 ...]"<< std::endl;
out << std::endl;
out <<"options:"<< std::endl;
out <<" -l libraryName - load plugin of name libraryName"<< std::endl;
out <<" i.e. -l osgdb_pfb"<< std::endl;
out <<" Useful for loading reader/writers which can load"<< std::endl;
out <<" other file formats in addition to its extension."<< std::endl;
out <<" -e extensionName - load reader/wrter plugin for file extension"<< std::endl;
out <<" i.e. -e pfb"<< std::endl;
out <<" Useful short hand for specifying full library name as"<< std::endl;
out <<" done with -l above, as it automatically expands to"<< std::endl;
out <<" the full library name appropriate for each platform."<< std::endl;
out <<std::endl;
out <<" -stereo - switch on stereo rendering, using the default of,"<< std::endl;
out <<" ANAGLYPHIC or the value set in the OSG_STEREO_MODE "<< std::endl;
out <<" environmental variable. See doc/stereo.html for "<< std::endl;
out <<" further details on setting up accurate stereo "<< std::endl;
out <<" for your system. "<< std::endl;
out <<" -stereo ANAGLYPHIC - switch on anaglyphic(red/cyan) stereo rendering."<< std::endl;
out <<" -stereo QUAD_BUFFER - switch on quad buffered stereo rendering."<< std::endl;
out <<std::endl;
out <<" -stencil - use a visual with stencil buffer enabled, this "<< std::endl;
out <<" also allows the depth complexity statistics mode"<< std::endl;
out <<" to be used (press 'p' three times to cycle to it)."<< std::endl;
out << std::endl;
}
int main( int argc, char **argv )
{
// initialize the GLUT
glutInit( &argc, argv );
if (argc<2)
{
write_usage(osg::notify(osg::NOTICE),argv[0]);
return 0;
}
// create the commandline args.
std::vector<std::string> commandLine;
for(int i=1;i<argc;++i) commandLine.push_back(argv[i]);
// initialize the viewer.
osgGLUT::Viewer viewer;
// configure the viewer from the commandline arguments, and eat any
// parameters that have been matched.
viewer.readCommandLine(commandLine);
// configure the plugin registry from the commandline arguments, and
// eat any parameters that have been matched.
osgDB::readCommandLine(commandLine);
// load the nodes from the commandline arguments.
osg::Node* loadedModel = osgDB::readNodeFiles(commandLine);
if (!loadedModel)
{
write_usage(osg::notify(osg::NOTICE),argv[0]);
return 1;
}
// to do scribe mode we create a top most group to contain the
// original model, and then a second group contains the same model
// but overrides various state attributes, so that the second instance
// is rendered as wireframe.
osg::Group* rootnode = new osg::Group;
osg::Group* decorator = new osg::Group;
rootnode->addChild(loadedModel);
rootnode->addChild(decorator);
decorator->addChild(loadedModel);
// set up the state so that the underlying color is not seen through
// and that the drawing mode is changed to wireframe, and a polygon offset
// is added to ensure that we see the wireframe itself, and turn off
// so texturing too.
osg::StateSet* stateset = new osg::StateSet;
osg::Material* material = new osg::Material;
osg::PolygonOffset* polyoffset = new osg::PolygonOffset;
polyoffset->setFactor(-1.0f);
polyoffset->setUnits(-1.0f);
osg::PolygonMode* polymode = new osg::PolygonMode;
polymode->setMode(osg::PolygonMode::FRONT_AND_BACK,osg::PolygonMode::LINE);
stateset->setAttributeAndModes(material,osg::StateAttribute::OVERRIDE_ON);
stateset->setAttributeAndModes(polyoffset,osg::StateAttribute::OVERRIDE_ON);
stateset->setAttributeAndModes(polymode,osg::StateAttribute::OVERRIDE_ON);
stateset->setMode(GL_TEXTURE_2D,osg::StateAttribute::OVERRIDE_OFF);
decorator->setStateSet(stateset);
// run optimization over the scene graph
osgUtil::Optimizer optimzer;
// turn off temporarily since the above single child decorator group gets
// removed as the optimizer assumes its redundent. Will fix next. Robert.
// optimzer.optimize(rootnode);
// add a viewport to the viewer and attach the scene graph.
viewer.addViewport( rootnode );
// register trackball, flight and drive.
viewer.registerCameraManipulator(new osgUtil::TrackballManipulator);
viewer.registerCameraManipulator(new osgUtil::FlightManipulator);
viewer.registerCameraManipulator(new osgUtil::DriveManipulator);
// open the viewer window.
viewer.open();
// fire up the event loop.
viewer.run();
return 0;
}
<commit_msg>Added stateset->setMode(GL_LIGHTING,osg::StateAttribute::OVERRIDE_ON); to scribbed subgraph so that lighting is always on, this is needed since glMaterial is only active when lighting is enabled.<commit_after>#include <osg/Transform>
#include <osg/Billboard>
#include <osg/Geode>
#include <osg/Group>
#include <osg/Notify>
#include <osg/Material>
#include <osg/PolygonOffset>
#include <osg/PolygonMode>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgUtil/TrackballManipulator>
#include <osgUtil/FlightManipulator>
#include <osgUtil/DriveManipulator>
#include <osgGLUT/glut>
#include <osgGLUT/Viewer>
#include <osgUtil/Optimizer>
void write_usage(std::ostream& out,const std::string& name)
{
out << std::endl;
out <<"usage:"<< std::endl;
out <<" "<<name<<" [options] infile1 [infile2 ...]"<< std::endl;
out << std::endl;
out <<"options:"<< std::endl;
out <<" -l libraryName - load plugin of name libraryName"<< std::endl;
out <<" i.e. -l osgdb_pfb"<< std::endl;
out <<" Useful for loading reader/writers which can load"<< std::endl;
out <<" other file formats in addition to its extension."<< std::endl;
out <<" -e extensionName - load reader/wrter plugin for file extension"<< std::endl;
out <<" i.e. -e pfb"<< std::endl;
out <<" Useful short hand for specifying full library name as"<< std::endl;
out <<" done with -l above, as it automatically expands to"<< std::endl;
out <<" the full library name appropriate for each platform."<< std::endl;
out <<std::endl;
out <<" -stereo - switch on stereo rendering, using the default of,"<< std::endl;
out <<" ANAGLYPHIC or the value set in the OSG_STEREO_MODE "<< std::endl;
out <<" environmental variable. See doc/stereo.html for "<< std::endl;
out <<" further details on setting up accurate stereo "<< std::endl;
out <<" for your system. "<< std::endl;
out <<" -stereo ANAGLYPHIC - switch on anaglyphic(red/cyan) stereo rendering."<< std::endl;
out <<" -stereo QUAD_BUFFER - switch on quad buffered stereo rendering."<< std::endl;
out <<std::endl;
out <<" -stencil - use a visual with stencil buffer enabled, this "<< std::endl;
out <<" also allows the depth complexity statistics mode"<< std::endl;
out <<" to be used (press 'p' three times to cycle to it)."<< std::endl;
out << std::endl;
}
int main( int argc, char **argv )
{
// initialize the GLUT
glutInit( &argc, argv );
if (argc<2)
{
write_usage(osg::notify(osg::NOTICE),argv[0]);
return 0;
}
// create the commandline args.
std::vector<std::string> commandLine;
for(int i=1;i<argc;++i) commandLine.push_back(argv[i]);
// initialize the viewer.
osgGLUT::Viewer viewer;
// configure the viewer from the commandline arguments, and eat any
// parameters that have been matched.
viewer.readCommandLine(commandLine);
// configure the plugin registry from the commandline arguments, and
// eat any parameters that have been matched.
osgDB::readCommandLine(commandLine);
// load the nodes from the commandline arguments.
osg::Node* loadedModel = osgDB::readNodeFiles(commandLine);
if (!loadedModel)
{
write_usage(osg::notify(osg::NOTICE),argv[0]);
return 1;
}
// to do scribe mode we create a top most group to contain the
// original model, and then a second group contains the same model
// but overrides various state attributes, so that the second instance
// is rendered as wireframe.
osg::Group* rootnode = new osg::Group;
osg::Group* decorator = new osg::Group;
rootnode->addChild(loadedModel);
rootnode->addChild(decorator);
decorator->addChild(loadedModel);
// set up the state so that the underlying color is not seen through
// and that the drawing mode is changed to wireframe, and a polygon offset
// is added to ensure that we see the wireframe itself, and turn off
// so texturing too.
osg::StateSet* stateset = new osg::StateSet;
osg::Material* material = new osg::Material;
osg::PolygonOffset* polyoffset = new osg::PolygonOffset;
polyoffset->setFactor(-1.0f);
polyoffset->setUnits(-1.0f);
osg::PolygonMode* polymode = new osg::PolygonMode;
polymode->setMode(osg::PolygonMode::FRONT_AND_BACK,osg::PolygonMode::LINE);
stateset->setAttributeAndModes(material,osg::StateAttribute::OVERRIDE_ON);
stateset->setAttributeAndModes(polyoffset,osg::StateAttribute::OVERRIDE_ON);
stateset->setAttributeAndModes(polymode,osg::StateAttribute::OVERRIDE_ON);
stateset->setMode(GL_TEXTURE_2D,osg::StateAttribute::OVERRIDE_OFF);
stateset->setMode(GL_LIGHTING,osg::StateAttribute::OVERRIDE_ON);
decorator->setStateSet(stateset);
// run optimization over the scene graph
osgUtil::Optimizer optimzer;
// turn off temporarily since the above single child decorator group gets
// removed as the optimizer assumes its redundent. Will fix next. Robert.
// optimzer.optimize(rootnode);
// add a viewport to the viewer and attach the scene graph.
viewer.addViewport( rootnode );
// register trackball, flight and drive.
viewer.registerCameraManipulator(new osgUtil::TrackballManipulator);
viewer.registerCameraManipulator(new osgUtil::FlightManipulator);
viewer.registerCameraManipulator(new osgUtil::DriveManipulator);
// open the viewer window.
viewer.open();
// fire up the event loop.
viewer.run();
return 0;
}
<|endoftext|> |
<commit_before>/*
@file remove_noexcept
@Copyright Barrett Adair 2015-2017
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_CLBL_TRTS_REMOVE_NOEXCEPT_HPP
#define BOOST_CLBL_TRTS_REMOVE_NOEXCEPT_HPP
#include <boost/callable_traits/detail/core.hpp>
namespace boost { namespace callable_traits {
BOOST_CLBL_TRTS_DEFINE_SFINAE_ERROR_ORIGIN(remove_noexcept)
BOOST_CLBL_TRTS_SFINAE_MSG(remove_noexcept, cannot_remove_noexcept_from_this_type)
//[ remove_noexcept_hpp
/*`
[section:ref_remove_noexcept remove_noexcept]
[heading Header]
``#include <boost/callable_traits/remove_noexcept.hpp>``
[heading Definition]
*/
template<typename T>
using remove_noexcept_t = //see below
//<-
detail::try_but_fail_if_invalid<
typename detail::traits<T>::remove_noexcept,
cannot_remove_noexcept_from_this_type>;
namespace detail {
template<typename T, typename = std::false_type>
struct remove_noexcept_impl {};
template<typename T>
struct remove_noexcept_impl <T, typename std::is_same<
remove_noexcept_t<T>, detail::dummy>::type>
{
using type = remove_noexcept_t<T>;
};
}
//->
template<typename T>
struct remove_noexcept : detail::remove_noexcept_impl<T> {};
//<-
}} // namespace boost::callable_traits
//->
/*`
[heading Constraints]
* `T` must be one of the following:
* function type
* function pointer type
* function reference type
* member function pointer type
* If `T` is a pointer, it may not be cv/ref qualified
[heading Behavior]
* A substitution failure occurs if the constraints are violated.
* Removes the `noexcept` specifier from `T`, if present.
[heading Input/Output Examples]
[table
[[`T`] [`remove_noexcept_t<T>`]]
[[`int() const noexcept`] [`int() const`]]
[[`int(*)() noexcept`] [`int(*)()`]]
[[`int(&)() noexcept`] [`int(&)()`]]
[[`int(foo::*)() noexcept`] [`int(foo::*)()`]]
[[`int() const`] [`int() const`]]
[[`int(*)()`] [`int(*)()`]]
[[`int(&)()`] [`int(&)()`]]
[[`int`] [(substitution failure)]]
[[`int foo::*`] [(substitution failure)]]
[[`int (foo::* const)()`] [(substitution failure)]]
]
[heading Example Program]
[import ../example/remove_noexcept.cpp]
[remove_noexcept]
[endsect]
*/
//]
#endif // #ifndef BOOST_CLBL_TRTS_REMOVE_NOEXCEPT_HPP
<commit_msg>Delete remove_noexcept.hpp<commit_after><|endoftext|> |
<commit_before>
AliAnalysisTaskCaloTrackCorrelation *AddTaskPi0EMCALPbPb(
const TString data = "AOD",
const TString calorimeter = "EMCAL",
const Bool_t printSettings = kFALSE,
const Bool_t simulation = kFALSE,
const Bool_t outputAOD = kFALSE,
const TString outputfile = "",
const Int_t year = 2011,
const TString col = "PbPb",
const TString trig = "",
const TString clustersArray = ""
)
{
// Creates a PartCorr task, configures it and adds it to the analysis manager.
// Get the pointer to the existing analysis manager via the static access method.
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTask", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
if (!mgr->GetInputEventHandler()) {
::Error("AddTask", "This task requires an input event handler");
return NULL;
}
Bool_t kInputDataType = "AOD";
if(!data.Contains("delta"))
kInputDataType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
Bool_t kUseKinematics = kFALSE;
if(simulation) {
kUseKinematics = (mgr->GetMCtruthEventHandler())?kTRUE:kFALSE;
if (!kUseKinematics && data=="AOD" && kInputDataType != "ESD") kUseKinematics = kTRUE; //AOD primary should be available ...
}
//cout<<"********* ACCESS KINE? "<<kUseKinematics<<endl;
// #### Configure analysis ####
AliAnaPartCorrMaker * maker = new AliAnaPartCorrMaker();
// General frame setting and configuration
maker->SetReader (ConfigureReader(data,kInputDataType,calorimeter,clustersArray,col,outputAOD,kUseKinematics,printSettings) );
maker->SetCaloUtils(ConfigureCaloUtils(year,col,clustersArray, simulation, printSettings));
// Analysis tasks setting and configuration
Int_t n = 0;//Analysis number, order is important
maker->AddAnalysis(ConfigurePhotonAnalysis(data,calorimeter,year,col,clustersArray,simulation,"",printSettings), n++); // Photon cluster selection
maker->AddAnalysis(ConfigurePi0Analysis (data,calorimeter,year,col,clustersArray,simulation,"",printSettings), n++); // Pi0 invariant mass analysis
maker->SetAnaDebug(-1) ;
maker->SwitchOnHistogramsMaker() ;
if(data.Contains("delta")) maker->SwitchOffAODsMaker() ;
else maker->SwitchOnAODsMaker() ;
if(printSettings) maker->Print("");
//printf("<< End Configuration of %d analysis for calorimeter %s >>\n",n, calorimeter.Data());
// Create task
AliAnalysisTaskCaloTrackCorrelation * task = new AliAnalysisTaskCaloTrackCorrelation (Form("PartCorr%s_Trig%s_Cl%s",calorimeter.Data(),trig.Data(),clustersArray.Data()));
task->SetConfigFileName(""); //Don't configure the analysis via configuration file.
//task->SetDebugLevel(-1);
task->SetBranches("ESD:AliESDRun.,AliESDHeader"); //just a trick to get Constantin's analysis to work
task->SetAnalysisMaker(maker);
mgr->AddTask(task);
//Create containers
if(outputfile.Length()==0)outputfile = AliAnalysisManager::GetCommonFileName();
TString name(Form("%s_Trig%s_Cl%s",calorimeter.Data(),trig.Data(),clustersArray.Data()));
AliAnalysisDataContainer *cout_pc = mgr->CreateContainer(name.Data(), TList::Class(),
AliAnalysisManager::kOutputContainer,
Form("%s:%s",outputfile.Data(),name.Data()));
AliAnalysisDataContainer *cout_cuts = mgr->CreateContainer(Form("%sCuts",name.Data()), TList::Class(),
AliAnalysisManager::kParamContainer,
Form("%s:%sCuts",outputfile.Data(),name.Data()));
// Create ONLY the output containers for the data produced by the task.
// Get and connect other common input/output containers via the manager as below
//==============================================================================
mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer());
// AOD output slot will be used in a different way in future
if(!data.Contains("delta") && outputAOD) mgr->ConnectOutput (task, 0, mgr->GetCommonOutputContainer());
mgr->ConnectOutput (task, 1, cout_pc);
mgr->ConnectOutput (task, 2, cout_cuts);
return task;
}
//____________________________________
AliCaloTrackReader * ConfigureReader(TString kData,TString kInputDataType, TString kCalorimeter,
TString kClusterArray, TString kCollisions,
Bool_t kOutputAOD, Bool_t kUseKinematics, Bool_t kPrint)
{
AliCaloTrackReader * reader = 0;
if (kData.Contains("AOD")) reader = new AliCaloTrackAODReader();
else if(kData=="ESD") reader = new AliCaloTrackESDReader();
else if(kData=="MC" &&
kInputDataType == "ESD") reader = new AliCaloTrackMCReader();
reader->SetDebug(-1);//10 for lots of messages
//Delta AOD?
//reader->SetDeltaAODFileName("");
if(kOutputAOD) reader->SwitchOnWriteDeltaAOD() ;
// MC settings
if(kUseKinematics){
if(kInputDataType == "ESD"){
reader->SwitchOnStack();
reader->SwitchOffAODMCParticles();
}
else if(kInputDataType == "AOD"){
reader->SwitchOffStack();
reader->SwitchOnAODMCParticles();
}
}
//------------------------
// Detector input filling
//------------------------
//Min cluster/track E
reader->SetEMCALEMin(0.5);
reader->SetEMCALEMax(1000);
reader->SetPHOSEMin(0.3);
reader->SetPHOSEMax(1000);
reader->SetCTSPtMin(0.1);
reader->SetCTSPtMax(1000);
reader->SwitchOffFiducialCut();
// Tracks
reader->SwitchOffCTS();
// Calorimeter
reader->SetEMCALClusterListName(kClusterArray);
if(kClusterArray == "") {
//printf("**************** Normal analysis **************** \n");
reader->SwitchOnClusterRecalculation(); // Bad map removal
}
else {
printf("**************** Input for analysis is Clusterizer %s **************** \n", kClusterArray.Data());
reader->SwitchOffClusterRecalculation();
}
if(kCalorimeter == "EMCAL") {
reader->SwitchOnEMCALCells();
reader->SwitchOnEMCAL();
}
if(kCalorimeter == "PHOS") {
reader->SwitchOnPHOSCells();
reader->SwitchOnPHOS();
}
// for case data="deltaAOD", no need to fill the EMCAL/PHOS cluster lists
if(kData.Contains("delta")){
reader->SwitchOffEMCAL();
reader->SwitchOffPHOS();
reader->SwitchOffEMCALCells();
reader->SwitchOffPHOSCells();
}
//-----------------
// Event selection
//-----------------
//if(!kUseKinematics) reader->SetFiredTriggerClassName("CEMC7EGA-B-NOPF-CENTNOTRD"); // L1 Gamma
if (kCollisions=="pp" ) {
reader->SwitchOffPileUpEventRejection(); // remove pileup by default
reader->SwitchOffV0ANDSelection() ; // and besides v0 AND
reader->SwitchOffPrimaryVertexSelection(); // and besides primary vertex
reader->SetZvertexCut(50.); // Open cut
}
else if(kCollisions=="PbPb") {
reader->SwitchOffPileUpEventRejection(); // remove pileup by default
reader->SwitchOffV0ANDSelection() ; // and besides v0 AND
reader->SwitchOffPrimaryVertexSelection(); // and besides primary vertex
reader->SetZvertexCut(10.); // Centrality defined in this range.
// Centrality
reader->SetCentralityClass("V0M");
reader->SetCentralityOpt(10); // 10 centrality bins
reader->SetCentralityBin(-1,-1); // Accept all events, if not select range
// Event plane (only used in AliAnaPi0 for the moment)
reader->SetEventPlaneMethod("Q");
}
if(kPrint) reader->Print("");
return reader;
}
//_______________________________________
AliCalorimeterUtils* ConfigureCaloUtils(Int_t kYears, TString kCollisions, TString kClusterArray,
Bool_t kSimulation, Bool_t kPrint)
{
AliCalorimeterUtils *cu = new AliCalorimeterUtils;
cu->SetDebug(-1);
if(kYears==2010) cu->SetEMCALGeometryName("EMCAL_FIRSTYEARV1");
else cu->SetEMCALGeometryName("EMCAL_COMPLETEV1");
// Remove clusters close to borders, at least max energy cell is 1 cell away
cu->SetNumberOfCellsFromEMCALBorder(1);
cu->SetNumberOfCellsFromPHOSBorder(2);
//if(kClusterArray == "")
// cu->SwitchOffRecalculateClusterTrackMatching(); // Done in clusterization
//else
// cu->SwitchOnRecalculateClusterTrackMatching();
//EMCAL only settings
AliEMCALRecoUtils * recou = cu->GetEMCALRecoUtils();
if(kCollisions=="pp" ) { // Do only for pp for the moment
cu->SwitchOnCorrectClusterLinearity();
if(!kSimulation) recou->SetNonLinearityFunction(AliEMCALRecoUtils::kBeamTestCorrected);
else recou->SetNonLinearityFunction(AliEMCALRecoUtils::kPi0MC);
}
recou->SwitchOnRejectExoticCell();
if(kClusterArray == "") recou->SwitchOnRejectExoticCluster();
else recou->SwitchOffRejectExoticCluster();
if(kCalorimeter=="PHOS")
{
if (kYears < 2014) cu->SetNumberOfSuperModulesUsed(3);
else cu->SetNumberOfSuperModulesUsed(4);
}
else
{
if (kYears == 2010) cu->SetNumberOfSuperModulesUsed(4); //EMCAL first year
else if (kYears < 2014) cu->SetNumberOfSuperModulesUsed(10);
else cu->SetNumberOfSuperModulesUsed(20);
}
if(kPrint) cu->Print("");
return cu;
}
//_____________________________________
AliAnaPhoton* ConfigurePhotonAnalysis(TString kData, TString kCalorimeter, Int_t kYears, TString kCollisions, TString kClusterArray,
Bool_t kSimulation, TString kTrig = "", Bool_t kPrint)
{
AliAnaPhoton *anaphoton = new AliAnaPhoton();
anaphoton->SetDebug(-1); //10 for lots of messages
// cluster selection cuts
anaphoton->SwitchOffFiducialCut();
anaphoton->SetCalorimeter(kCalorimeter);
if(kCalorimeter == "PHOS"){
anaphoton->SetNCellCut(2);// At least 2 cells
anaphoton->SetMinPt(0.3);
anaphoton->SetMinDistanceToBadChannel(2, 4, 5);
}
else {//EMCAL
anaphoton->SetNCellCut(1);// At least 2 cells
anaphoton->SetMinPt(0.5); // avoid mip peak at E = 260 MeV
anaphoton->SetMaxPt(1000);
anaphoton->SetTimeCut(-1000,1000); // open cut, usual time window of [425-825] ns if time recalibration is off
anaphoton->SetMinDistanceToBadChannel(1, 2, 3); // For filtered AODs, new releases.
}
anaphoton->SwitchOnTrackMatchRejection() ;
//PID cuts (shower shape)
anaphoton->SwitchOnCaloPID(); // do PID selection, unless specified in GetCaloPID, selection not based on bayesian
AliCaloPID* caloPID = anaphoton->GetCaloPID();
//Not used in bayesian
//EMCAL
caloPID->SetEMCALLambda0CutMax(0.30);
caloPID->SetEMCALLambda0CutMin(0.10);
caloPID->SetEMCALDEtaCut(0.025);
caloPID->SetEMCALDPhiCut(0.05);
// In case of official AODs when dX and dZ was not stored, open the cuts
// and rely on having a match recorded. In case of reclusterization, try.
if(kData=="AOD" && kClusterArray==""){
caloPID->SetEMCALDEtaCut(2000);
caloPID->SetEMCALDPhiCut(2000);
}
//PHOS
caloPID->SetPHOSDispersionCut(2.5);
caloPID->SetPHOSRCut(2.);
if(kData=="AOD") caloPID->SetPHOSRCut(2000.); // Open cut since dX, dZ not stored
if(kCalorimeter=="PHOS"){
caloPID->SetHistoDEtaRangeAndNBins(-200, 200, 200); // dZ
caloPID->SetHistoDPhiRangeAndNBins(-200, 200, 200); // dX
}
//caloPID->SetTOFCut(10000000); // Not used, only to set PID bits
anaphoton->SwitchOffFillShowerShapeHistograms(); // Filled before photon shower shape selection
// Input / output delta AOD settings
if(!kData.Contains("delta")) {
anaphoton->SetOutputAODName(Form("Photon%s_Trig%s_Cl%s",kCalorimeter.Data(), kTrig.Data(),kClusterArray.Data()));
anaphoton->SetOutputAODClassName("AliAODPWG4ParticleCorrelation");
//anaphoton->SetOutputAODClassName("AliAODPWG4Particle"); // use if no correlation done
}
else anaphoton->SetInputAODName(Form("Photon%s_Trig%s_Cl%s",kCalorimeter.Data(), kTrig.Data(),kClusterArray.Data()));
//Set Histograms name tag, bins and ranges
anaphoton->AddToHistogramsName("AnaPhoton_");
SetHistoRangeAndNBins(anaphoton); // see method below
// Number of particle type MC histograms
anaphoton->FillNOriginHistograms(8);
anaphoton->FillNPrimaryHistograms(4);
if(kPrint) anaphoton->Print("");
return anaphoton;
}
//_______________________________
AliAnaPi0* ConfigurePi0Analysis(TString kData, TString kCalorimeter, Int_t kYears, TString kCollisions, TString kClusterArray,
Bool_t kSimulation, TString kTrig = "", Bool_t kPrint)
{
AliAnaPi0 *anapi0 = new AliAnaPi0();
anapi0->SetDebug(-1);//10 for lots of messages
if(kPrint) anapi0->Print("");
// Input delta AOD settings
anapi0->SetInputAODName(Form("Photon%s_Trig%s_Cl%s",kCalorimeter.Data(), kTrig.Data(),kClusterArray.Data()));
// Calorimeter settings
anapi0->SetCalorimeter(kCalorimeter);
//settings for pp collision mixing
anapi0->SwitchOnOwnMix(); //Off when mixing done with general mixing frame
// Cuts
if(kCalorimeter=="EMCAL") anapi0->SetPairTimeCut(70);
if (kCollisions=="pp" ) {
printf("****** Configure Pi0 for pp analysis\n");
anapi0->SetNCentrBin(1);
anapi0->SetNZvertBin(10);
anapi0->SetNRPBin(1);
anapi0->SetNMaxEvMix(100);
}
else if(kCollisions=="PbPb") {
printf("****** Configure Pi0 for PbPb analysis\n");
anapi0->SetNCentrBin(5);
anapi0->SetNZvertBin(3);
anapi0->SetNRPBin(1);
anapi0->SetNMaxEvMix(5);
}
anapi0->SwitchOffMultipleCutAnalysis();
anapi0->SwitchOffSMCombinations();
//Set Histograms name tag, bins and ranges
anapi0->AddToHistogramsName("AnaPi0_");
SetHistoRangeAndNBins(anapi0, kCalorimeter, kYears, kCollisions, kSimulation); // see method below
return anapi0;
}
//________________________________________________________
void SetHistoRangeAndNBins (AliAnaPartCorrBaseClass* ana, TString kCalorimeter,
Int_t kYears, TString kCollisions, Bool_t kSimulation)
{
// Set common bins for all analysis and MC histograms filling
if(kSimulation) ana->SwitchOnDataMC() ;//Access MC stack and fill more histograms, AOD MC not implemented yet.
else ana->SwitchOffDataMC() ;
ana->SetHistoPtRangeAndNBins(0, 100, 250) ; // Energy and pt histograms
if(kCalorimeter=="EMCAL"){
if(kYears==2010){
ana->SetHistoPhiRangeAndNBins(78*TMath::DegToRad(), 122*TMath::DegToRad(), 78) ;
ana->SetHistoXRangeAndNBins(-230,90,120); // QA
ana->SetHistoYRangeAndNBins(370,450,40); // QA
}
else {
ana->SetHistoPhiRangeAndNBins(78*TMath::DegToRad(), 182*TMath::DegToRad(), 108) ;
ana->SetHistoXRangeAndNBins(-600,90,200); // QA
ana->SetHistoYRangeAndNBins(100,450,100); // QA
}
ana->SetHistoEtaRangeAndNBins(-0.72, 0.72, 144) ;
}
else{
ana->SetHistoPhiRangeAndNBins(260*TMath::DegToRad(), 320*TMath::DegToRad(), 60) ;
ana->SetHistoEtaRangeAndNBins(-0.13, 0.13, 130) ;
}
ana->SetHistoShowerShapeRangeAndNBins(0, 3, 300);
// Invariant mass analysis
ana->SetHistoMassRangeAndNBins(0., 1., 200) ;
ana->SetHistoAsymmetryRangeAndNBins(0., 1. , 100) ;
// check if time calibration is on
ana->SetHistoTimeRangeAndNBins(-1000.,1000,1000);
ana->SetHistoDiffTimeRangeAndNBins(-200, 200, 800);
// QA, electron, charged
ana->SetHistoPOverERangeAndNBins(0,10.,100);
ana->SetHistodEdxRangeAndNBins(0.,200.,200);
// QA
ana->SetHistoFinePtRangeAndNBins(0, 10, 200) ; // bining for fhAmpId
ana->SetHistodRRangeAndNBins(0.,TMath::Pi(),150);
ana->SetHistoRatioRangeAndNBins(0.,2.,100);
ana->SetHistoVertexDistRangeAndNBins(0.,500.,500);
ana->SetHistoNClusterCellRangeAndNBins(0,500,500);
ana->SetHistoZRangeAndNBins(-400,400,200);
ana->SetHistoRRangeAndNBins(400,450,25);
ana->SetHistoV0SignalRangeAndNBins(0,5000,500);
ana->SetHistoV0MultiplicityRangeAndNBins(0,5000,500);
ana->SetHistoTrackMultiplicityRangeAndNBins(0,5000,500);
}
<commit_msg>remove unused<commit_after><|endoftext|> |
<commit_before>/*
* Super Entity Game Server Project
* http://segs.sf.net/
* Copyright (c) 2006 Super Entity Game Server Team (see Authors.txt)
* This software is licensed! (See License.txt for details)
*
* $Id$
*/
#define _USE_MATH_DEFINES
#include <cmath>
#include "types.h"
#include "Events/InputState.h"
#include "Entity.h"
void InputState::serializeto(BitStream &) const
{
assert(!"Not implemented");
}
void InputState::partial_2(BitStream &bs)
{
uint8_t control_id;
//uint16_t v6;
uint16_t time_since_prev;
int v;
do
{
if(bs.GetBits(1))
control_id=8;
else
control_id=bs.GetBits(4);
if(bs.GetBits(1)) //
time_since_prev=bs.GetBits(2)+32;
else
time_since_prev=bs.GetBits(m_csc_deltabits);
switch(control_id)
{
case 0: case 1: case 2:
case 3: case 4: case 5:
// field_38 bits , control_id is the number of the bit
fprintf(stderr,"CtrlId %d : %d - ",control_id,time_since_prev);
v = bs.GetBits(1);
fprintf(stderr,"P2[%d]:%d\n",control_id,v);
break;
case 6:
case 7:
{
v = bs.GetBits(11);
// v = (x+pi)*(2048/2pi)
// x = (v*(pi/1024))-pi
float recovered = (float(v)/2048.0f)*(2*M_PI) - M_PI;
fprintf(stderr,"Pyr %f : %f \n",camera_pyr.x,camera_pyr.y);
if(control_id==6) //TODO: use camera_pyr.v[] here ?
camera_pyr.x = recovered;
else
camera_pyr.y = recovered;
break;
}
case 8:
v = bs.GetBits(1);
// fprintf(stderr,"\tCTRL_8[%d] ",v);
if ( m_send_deltas )
{
m_t1=bs.GetPackedBits(8);
m_t2=bs.GetPackedBits(8);
}
else
{
m_send_deltas = true;
m_t1=bs.GetBits(32);
m_t2=bs.GetPackedBits(10);
}
// fprintf(stderr,"[%d, ",t1);
// fprintf(stderr,",%d] ",t2);
if(bs.GetBits(1))
{
v=bs.GetBits(8);
// fprintf(stderr,"CTRL_8C[%d] ",v);
// fprintf(stderr,"P2_8_opt : %d\n",v);
}
break;
case 9:
//a2->timerel_18
//fprintf(stderr,"CtrlId %d : %d - ",control_id,time_since_prev);
fprintf(stderr,"%d\n",bs.GetBits(8));
break;
case 10:
fprintf(stderr,"CtrlId %d : %d - ",control_id,time_since_prev);
fprintf(stderr,"%d\n",bs.GetBits(1)); //a2->timerel_18 & 1
break;
default:
assert(!"Unknown control_id");
}
} while(bs.GetBits(1));
}
void InputState::extended_input(BitStream &bs)
{
if(bs.GetBits(1)) // list of partial_2 follows
{
m_csc_deltabits=bs.GetBits(5) + 1; // number of bits in max_time_diff_ms
someOtherbits = bs.GetBits(16);//ControlStateChange::field_8 or OptRel::field_19A8
current_state_P = 0;
#ifdef DEBUG_INPUT
fprintf(stderr,"CSC_DELTA[%x-%x] : ",m_csc_deltabits,someOtherbits);
#endif
partial_2(bs);
}
controlBits = 0;
for(int idx=0; idx<6; ++idx)
controlBits |= (bs.GetBits(1))<<idx;
#ifdef DEBUG_INPUT
fprintf(stderr,"E input %x : ",controlBits);
#endif
if(bs.GetBits(1))//if ( abs(s_prevTime - ms_time) < 1000 )
{
m_A_ang11_propably = bs.GetBits(11);//pak->SendBits(11, control_state.field_1C[0]);
m_B_ang11_propably = bs.GetBits(11);//pak->SendBits(11, control_state.field_1C[1]);
#ifdef DEBUG_INPUT
fprintf(stderr,"%x : %x",v1,v2);
#endif
}
}
struct ControlState
{
int field0;
int time_res;
float timestep;
float time_rel1C;
uint64_t m_perf_cntr_diff;
uint64_t m_perf_freq_diff;
// recover actual ControlState from network data and previous entry
void serializefrom_delta(BitStream &bs,const ControlState &prev)
{
field0 = bs.GetPackedBits(1); // field_0 diff next-current
time_res = bs.GetPackedBits(1); // time to next state ?
timestep = bs.GetFloat(); // next state's timestep
time_rel1C = timestep;
if(bs.GetBits(1)) //timestep!=time_rel1C
time_rel1C = bs.GetFloat();
m_perf_cntr_diff = bs.Get64Bits(); //next_state->ticks - current_state->ticks
if(bs.GetBits(1))
{
// perf freq changed between current and next
m_perf_freq_diff = bs.Get64Bits();
}
}
void serializefrom_base(BitStream &bs)
{
field0 = bs.GetBits(32); //field_0
time_res = bs.GetBits(32); // get_time_resl
timestep = bs.GetFloat(); //v7->timestep
time_rel1C = timestep;
if(bs.GetBits(1)) //timestep!=time_rel1C
time_rel1C = bs.GetFloat();
m_perf_cntr_diff = bs.Get64Bits(); //next_state->ticks - current_state->ticks
m_perf_cntr_diff = bs.Get64Bits(); //v7->perf_cntr1
}
void dump()
{
#ifdef DEBUG_INPUT
fprintf(stderr,"CSC: %d,%d, [%f,%f]",field0,time_res,timestep,time_rel1C);
fprintf(stderr, "(%lld %lld)",m_perf_cntr_diff,m_perf_freq_diff);
#endif
}
};
void InputState::serializefrom(BitStream &bs)
{
m_send_deltas=false;
#ifdef DEBUG_INPUT
fprintf(stderr,"I:");
#endif
if(bs.GetBits(1))
extended_input(bs);
bool has_targeted_entity = bs.GetBits(1);
int tgt_idx=bs.GetPackedBits(14); // targeted entity server index
int ctrl_idx=0;
#ifdef DEBUG_INPUT
fprintf(stderr,"T:[%d]",has_targeted_entity);
fprintf(stderr,"TI:[%d]",tgt_idx);
#endif
ControlState prev_fld;
while(bs.GetBits(1)) // receive control state array entries ?
{
ControlState fld;
if(ctrl_idx)
{
fld.serializefrom_delta(bs,prev_fld);
}
else // initial values
{
fld.serializefrom_base(bs);
}
fld.dump();
prev_fld = fld;
ctrl_idx++;
}
recv_client_opts(bs); // g_pak contents will follow
#ifdef DEBUG_INPUT
fprintf(stderr,"\n");
#endif
}
//TODO: use generic ReadableStructures here ?
void InputState::recv_client_opts(BitStream &bs)
{
ClientOptions opts;
ClientOption *entry;
int opt_idx=0;
int some_idx = bs.GetPackedBits(1);
entry=opts.get(opt_idx);
Vector3 vec;
while(some_idx!=0)
{
for(size_t i=0; i<entry->m_args.size(); i++)
{
ClientOption::Arg &arg=entry->m_args[i];
switch ( arg.type )
{
case ClientOption::t_int:
{
*((int32_t *)arg.tgt) = bs.GetPackedBits(1);
break;
}
case ClientOption::t_float:
{
*((float *)arg.tgt)=bs.GetFloat();
break;
}
case 5:
{
printf("Quant:%d\n",bs.GetBits(14)); //quantized angle
break;
}
case ClientOption::t_string:
case 4:
{
std::string v;
bs.GetString(v);
break;
}
case 7:
{
for (int j = 0; j < 3; ++j )
{
vec.v[j] = bs.GetFloat();
}
break;
}
default:
continue;
}
}
some_idx = bs.GetPackedBits(1);
opt_idx++;
entry=opts.get(opt_idx);
}
}
<commit_msg>Added correct dumping of received control events<commit_after>/*
* Super Entity Game Server Project
* http://segs.sf.net/
* Copyright (c) 2006 Super Entity Game Server Team (see Authors.txt)
* This software is licensed! (See License.txt for details)
*
* $Id$
*/
#define _USE_MATH_DEFINES
#include <cmath>
#include "types.h"
#include "Events/InputState.h"
#include "Entity.h"
void InputState::serializeto(BitStream &) const
{
assert(!"Not implemented");
}
void InputState::partial_2(BitStream &bs)
{
uint8_t control_id;
//uint16_t v6;
uint16_t time_since_prev;
int v;
static char *control_name[] = {"FORWARD",
"BACK",
"LEFT",
"RIGHT",
"UP",
"DOWN"};
do
{
if(bs.GetBits(1))
control_id = 8;
else
control_id = bs.GetBits(4);
if(bs.GetBits(1)) //
time_since_prev=bs.GetBits(2)+32;
else
time_since_prev=bs.GetBits(m_csc_deltabits);
switch(control_id)
{
case 0: case 1: case 2:
case 3: case 4: case 5:
// field_38 bits , control_id is the number of the bit
fprintf(stderr,"%s : %d - ",control_name[control_id],time_since_prev);
v = bs.GetBits(1); // press release
fprintf(stderr,"%d\n",v);
break;
case 6:
case 7:
{
v = bs.GetBits(11);
// v = (x+pi)*(2048/2pi)
// x = (v*(pi/1024))-pi
float recovered = (float(v)/2048.0f)*(2*M_PI) - M_PI;
fprintf(stderr,"Pyr %f : %f \n",camera_pyr.x,camera_pyr.y);
if(control_id==6) //TODO: use camera_pyr.v[] here ?
camera_pyr.x = recovered;
else
camera_pyr.y = recovered;
break;
}
case 8:
v = bs.GetBits(1);
// fprintf(stderr,"\tCTRL_8[%d] ",v);
if ( m_send_deltas )
{
m_t1=bs.GetPackedBits(8);
m_t2=bs.GetPackedBits(8);
}
else
{
m_send_deltas = true;
m_t1=bs.GetBits(32);
m_t2=bs.GetPackedBits(10);
}
// fprintf(stderr,"[%d, ",t1);
// fprintf(stderr,",%d] ",t2);
if(bs.GetBits(1))
{
v=bs.GetBits(8);
// fprintf(stderr,"CTRL_8C[%d] ",v);
// fprintf(stderr,"P2_8_opt : %d\n",v);
}
break;
case 9:
//a2->timerel_18
//fprintf(stderr,"CtrlId %d : %d - ",control_id,time_since_prev);
fprintf(stderr,"%d\n",bs.GetBits(8));
break;
case 10:
fprintf(stderr,"CtrlId %d : %d - ",control_id,time_since_prev);
fprintf(stderr,"%d\n",bs.GetBits(1)); //a2->timerel_18 & 1
break;
default:
assert(!"Unknown control_id");
}
} while(bs.GetBits(1));
}
void InputState::extended_input(BitStream &bs)
{
if(bs.GetBits(1)) // list of partial_2 follows
{
m_csc_deltabits=bs.GetBits(5) + 1; // number of bits in max_time_diff_ms
someOtherbits = bs.GetBits(16);//ControlStateChange::field_8 or OptRel::field_19A8
current_state_P = 0;
#ifdef DEBUG_INPUT
fprintf(stderr,"CSC_DELTA[%x-%x] : ",m_csc_deltabits,someOtherbits);
#endif
partial_2(bs);
}
controlBits = 0;
for(int idx=0; idx<6; ++idx)
controlBits |= (bs.GetBits(1))<<idx;
#ifdef DEBUG_INPUT
fprintf(stderr,"E input %x : ",controlBits);
#endif
if(bs.GetBits(1))//if ( abs(s_prevTime - ms_time) < 1000 )
{
m_A_ang11_propably = bs.GetBits(11);//pak->SendBits(11, control_state.field_1C[0]);
m_B_ang11_propably = bs.GetBits(11);//pak->SendBits(11, control_state.field_1C[1]);
#ifdef DEBUG_INPUT
fprintf(stderr,"%x : %x",v1,v2);
#endif
}
}
struct ControlState
{
int field0;
int time_res;
float timestep;
float time_rel1C;
uint64_t m_perf_cntr_diff;
uint64_t m_perf_freq_diff;
// recover actual ControlState from network data and previous entry
void serializefrom_delta(BitStream &bs,const ControlState &prev)
{
field0 = bs.GetPackedBits(1); // field_0 diff next-current
time_res = bs.GetPackedBits(1); // time to next state ?
timestep = bs.GetFloat(); // next state's timestep
time_rel1C = timestep;
if(bs.GetBits(1)) //timestep!=time_rel1C
time_rel1C = bs.GetFloat();
m_perf_cntr_diff = bs.Get64Bits(); //next_state->ticks - current_state->ticks
if(bs.GetBits(1))
{
// perf freq changed between current and next
m_perf_freq_diff = bs.Get64Bits();
}
}
void serializefrom_base(BitStream &bs)
{
field0 = bs.GetBits(32); //field_0
time_res = bs.GetBits(32); // get_time_resl
timestep = bs.GetFloat(); //v7->timestep
time_rel1C = timestep;
if(bs.GetBits(1)) //timestep!=time_rel1C
time_rel1C = bs.GetFloat();
m_perf_cntr_diff = bs.Get64Bits(); //next_state->ticks - current_state->ticks
m_perf_cntr_diff = bs.Get64Bits(); //v7->perf_cntr1
}
void dump()
{
#ifdef DEBUG_INPUT
fprintf(stderr,"CSC: %d,%d, [%f,%f]",field0,time_res,timestep,time_rel1C);
fprintf(stderr, "(%lld %lld)",m_perf_cntr_diff,m_perf_freq_diff);
#endif
}
};
void InputState::serializefrom(BitStream &bs)
{
m_send_deltas=false;
#ifdef DEBUG_INPUT
fprintf(stderr,"I:");
#endif
if(bs.GetBits(1))
extended_input(bs);
bool has_targeted_entity = bs.GetBits(1);
int tgt_idx=bs.GetPackedBits(14); // targeted entity server index
int ctrl_idx=0;
#ifdef DEBUG_INPUT
fprintf(stderr,"T:[%d]",has_targeted_entity);
fprintf(stderr,"TI:[%d]",tgt_idx);
#endif
ControlState prev_fld;
while(bs.GetBits(1)) // receive control state array entries ?
{
ControlState fld;
if(ctrl_idx)
{
fld.serializefrom_delta(bs,prev_fld);
}
else // initial values
{
fld.serializefrom_base(bs);
}
fld.dump();
prev_fld = fld;
ctrl_idx++;
}
recv_client_opts(bs); // g_pak contents will follow
#ifdef DEBUG_INPUT
fprintf(stderr,"\n");
#endif
}
//TODO: use generic ReadableStructures here ?
void InputState::recv_client_opts(BitStream &bs)
{
ClientOptions opts;
ClientOption *entry;
int opt_idx=0;
int some_idx = bs.GetPackedBits(1);
entry=opts.get(opt_idx);
Vector3 vec;
while(some_idx!=0)
{
for(size_t i=0; i<entry->m_args.size(); i++)
{
ClientOption::Arg &arg=entry->m_args[i];
switch ( arg.type )
{
case ClientOption::t_int:
{
*((int32_t *)arg.tgt) = bs.GetPackedBits(1);
break;
}
case ClientOption::t_float:
{
*((float *)arg.tgt)=bs.GetFloat();
break;
}
case 5:
{
printf("Quant:%d\n",bs.GetBits(14)); //quantized angle
break;
}
case ClientOption::t_string:
case 4:
{
std::string v;
bs.GetString(v);
break;
}
case 7:
{
for (int j = 0; j < 3; ++j )
{
vec.v[j] = bs.GetFloat();
}
break;
}
default:
continue;
}
}
some_idx = bs.GetPackedBits(1);
opt_idx++;
entry=opts.get(opt_idx);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/process.h"
#include "base/logging.h"
#include "base/process_util.h"
namespace base {
void Process::Close() {
process_ = 0;
// if the process wasn't termiated (so we waited) or the state
// wasn't already collected w/ a wait from process_utils, we're gonna
// end up w/ a zombie when it does finally exit.
}
void Process::Terminate(int result_code) {
// result_code isn't supportable.
if (!process_)
return;
// Wait so we clean up the zombie
KillProcess(process_, result_code, true);
}
bool Process::IsProcessBackgrounded() const {
return false;
}
bool Process::SetProcessBackgrounded(bool value) {
NOTIMPLEMENTED();
return false;
}
bool Process::ReduceWorkingSet() {
NOTIMPLEMENTED();
return false;
}
bool Process::UnReduceWorkingSet() {
NOTIMPLEMENTED();
return false;
}
bool Process::EmptyWorkingSet() {
NOTIMPLEMENTED();
return false;
}
int32 Process::pid() const {
if (process_ == 0)
return 0;
return GetProcId(process_);
}
bool Process::is_current() const {
return process_ == GetCurrentProcessHandle();
}
// static
Process Process::Current() {
return Process(GetCurrentProcessHandle());
}
} // namspace base
<commit_msg>Lie on the priority change and saw we did it w/ a comment about why we won't be able to, but w/ the current api and higher layers, it's much more work to fully clean that up. Review URL: http://codereview.chromium.org/28029<commit_after>// Copyright (c) 2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/process.h"
#include "base/logging.h"
#include "base/process_util.h"
namespace base {
void Process::Close() {
process_ = 0;
// if the process wasn't termiated (so we waited) or the state
// wasn't already collected w/ a wait from process_utils, we're gonna
// end up w/ a zombie when it does finally exit.
}
void Process::Terminate(int result_code) {
// result_code isn't supportable.
if (!process_)
return;
// Wait so we clean up the zombie
KillProcess(process_, result_code, true);
}
bool Process::IsProcessBackgrounded() const {
return false;
}
bool Process::SetProcessBackgrounded(bool value) {
NOTIMPLEMENTED();
// Just say we did it to keep renderer happy at the moment. Need to finish
// cleaning this up w/in higher layers since windows is probably the only
// one that can raise priorities w/o privileges.
return true;
}
bool Process::ReduceWorkingSet() {
NOTIMPLEMENTED();
return false;
}
bool Process::UnReduceWorkingSet() {
NOTIMPLEMENTED();
return false;
}
bool Process::EmptyWorkingSet() {
NOTIMPLEMENTED();
return false;
}
int32 Process::pid() const {
if (process_ == 0)
return 0;
return GetProcId(process_);
}
bool Process::is_current() const {
return process_ == GetCurrentProcessHandle();
}
// static
Process Process::Current() {
return Process(GetCurrentProcessHandle());
}
} // namspace base
<|endoftext|> |
<commit_before>// @(#)root/base:$Name: $:$Id: TBrowser.cxx,v 1.5 2001/09/18 21:58:39 rdm Exp $
// Author: Fons Rademakers 25/10/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// Using a TBrowser one can browse all ROOT objects. It shows in a list //
// on the left side of the window all browsable ROOT classes. Selecting //
// one of the classes displays, in the iconbox on the right side, all //
// objects in the class. Selecting one of the objects in the iconbox, //
// will place all browsable objects in a new list and draws the //
// contents of the selected class in the iconbox. And so on.... //
// //
//Begin_Html <img src="gif/browser.gif"> End_Html //
// //
//////////////////////////////////////////////////////////////////////////
#include "TBrowser.h"
#include "TGuiFactory.h"
#include "TROOT.h"
#include "TSystem.h"
#include "TStyle.h"
#include "TTimer.h"
#include "TContextMenu.h"
#include "TInterpreter.h"
//////////////////////////////////////////////////////////////////////////
// //
// TBrowserTimer //
// //
//////////////////////////////////////////////////////////////////////////
class TBrowserTimer : public TTimer {
protected:
TBrowser *fBrowser;
Bool_t fActivate;
public:
TBrowserTimer(TBrowser *b, Long_t ms = 1000)
: TTimer(ms, kTRUE), fBrowser(b), fActivate(kFALSE) { }
Bool_t Notify();
};
ClassImp(TBrowser)
//______________________________________________________________________________
TBrowser::TBrowser(const char *name, const char *title)
: TNamed(name, title)
{
// Create a new browser with a name, title. Width and height are by
// default set to 640x400 and (optionally) adjusted by the screen factor
// (depending on Rint.Canvas.UseScreenFactor to be true or false, default
// is true).
Float_t cx = gStyle->GetScreenFactor();
UInt_t w = UInt_t(cx*640);
UInt_t h = UInt_t(cx*400);
fImp = gGuiFactory->CreateBrowserImp(this, title, w, h);
Create();
}
//______________________________________________________________________________
TBrowser::TBrowser(const char *name, const char *title, UInt_t width, UInt_t height)
: TNamed(name, title)
{
// Create a new browser with a name, title, width and height.
fImp = gGuiFactory->CreateBrowserImp(this, title, width, height);
Create();
}
//______________________________________________________________________________
TBrowser::TBrowser(const char *name, const char *title, Int_t x, Int_t y, UInt_t width, UInt_t height)
: TNamed(name, title)
{
// Create a new browser with a name, title, position, width and height.
fImp = gGuiFactory->CreateBrowserImp(this, title, x, y, width, height);
Create();
}
//______________________________________________________________________________
TBrowser::TBrowser(const char *name, TObject *obj, const char *title)
: TNamed(name, title)
{
// Create a new browser with a name, title, width and height for TObject *obj.
Float_t cx = gStyle->GetScreenFactor();
UInt_t w = UInt_t(cx*640);
UInt_t h = UInt_t(cx*400);
fImp = gGuiFactory->CreateBrowserImp(this, title, w, h);
Create(obj);
}
//______________________________________________________________________________
TBrowser::TBrowser(const char *name, TObject *obj, const char *title, UInt_t width, UInt_t height)
: TNamed(name, title)
{
// Create a new browser with a name, title, width and height for TObject *obj.
fImp = gGuiFactory->CreateBrowserImp(this, title, width, height);
Create(obj);
}
//______________________________________________________________________________
TBrowser::TBrowser(const char *name, TObject *obj, const char *title, Int_t x, Int_t y, UInt_t width, UInt_t height)
: TNamed(name, title)
{
// Create a new browser with a name, title, width and height for TObject *obj.
fImp = gGuiFactory->CreateBrowserImp(this, title, x, y, width, height);
Create(obj);
}
//______________________________________________________________________________
TBrowser::~TBrowser()
{
// Delete the browser.
gROOT->GetListOfBrowsers()->Remove(this);
delete fContextMenu;
delete fTimer;
delete fImp;
}
//______________________________________________________________________________
void TBrowser::Add(TObject *obj, const char *name)
{
// Add object with name to browser. If name not set the objects GetName()
// is used.
if (obj && fImp) {
fImp->Add(obj, name);
obj->SetBit(kMustCleanup);
}
}
//______________________________________________________________________________
void TBrowser::Create(TObject *obj)
{
// Create the browser, called by the ctors.
fNeedRefresh = kFALSE;
fTimer = new TBrowserTimer(this);
gSystem->AddTimer(fTimer);
gROOT->GetListOfBrowsers()->Add(this);
// Get the list of globals
gROOT->GetListOfGlobals(kTRUE);
gROOT->GetListOfGlobalFunctions(kTRUE);
fContextMenu = new TContextMenu("BrowserContextMenu") ;
// Fill the first list from the present TObject obj
if (obj) {
Add(obj);
#ifndef WIN32
if (fImp) fImp->BrowseObj(obj);
#else
#ifdef GDK_WIN32
if (fImp) fImp->BrowseObj(obj);
#endif
// obj->Browse(this);
#endif
}
// Fill the first list with all browsable classes from TROOT
#ifndef WIN32
else if (fImp) fImp->BrowseObj(gROOT);
#else
#ifdef GDK_WIN32
else if (fImp) fImp->BrowseObj(gROOT);
#endif
// The first list will be filled by TWin32BrowserImp ctor
// with all browsable classes from TROOT
#endif
}
//______________________________________________________________________________
void TBrowser::ExecuteDefaultAction(TObject *obj)
{
// Execute default action for selected object (action is specified
// in the $HOME/.root.mimes or $ROOTSYS/etc/root.mimes file.
if (obj && fImp)
fImp->ExecuteDefaultAction(obj);
}
//______________________________________________________________________________
void TBrowser::RecursiveRemove(TObject *obj)
{
// Recursively remove obj from browser.
if (fImp && obj) {
fImp->RecursiveRemove(obj);
fNeedRefresh = kTRUE;
}
}
//______________________________________________________________________________
void TBrowser::Refresh()
{
// Refresh browser contents.
fNeedRefresh = kTRUE;
if (fImp) fImp->Refresh();
fNeedRefresh = kFALSE;
}
//______________________________________________________________________________
void TBrowser::SetSelected(TObject *clickedObject)
{
// Assign the last selected object.
fLastSelectedObject = clickedObject;
}
//////////////////////////////////////////////////////////////////////////
// //
// TBrowserTimer //
// //
//////////////////////////////////////////////////////////////////////////
//______________________________________________________________________________
Bool_t TBrowserTimer::Notify()
{
// Called whenever timer times out.
if (fBrowser) {
if (fBrowser->GetRefreshFlag()) {
fBrowser->SetRefreshFlag(kFALSE);
fActivate = kTRUE;
} else if (fActivate) {
fActivate = kFALSE;
fBrowser->Refresh();
}
}
Reset();
return kFALSE;
}
<commit_msg>Remove win32 conditional code, now that we have TWin32BrowserImp::BrowseObj<commit_after>// @(#)root/base:$Name: $:$Id: TBrowser.cxx,v 1.6 2001/11/28 15:58:13 rdm Exp $
// Author: Fons Rademakers 25/10/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// Using a TBrowser one can browse all ROOT objects. It shows in a list //
// on the left side of the window all browsable ROOT classes. Selecting //
// one of the classes displays, in the iconbox on the right side, all //
// objects in the class. Selecting one of the objects in the iconbox, //
// will place all browsable objects in a new list and draws the //
// contents of the selected class in the iconbox. And so on.... //
// //
//Begin_Html <img src="gif/browser.gif"> End_Html //
// //
//////////////////////////////////////////////////////////////////////////
#include "TBrowser.h"
#include "TGuiFactory.h"
#include "TROOT.h"
#include "TSystem.h"
#include "TStyle.h"
#include "TTimer.h"
#include "TContextMenu.h"
#include "TInterpreter.h"
//////////////////////////////////////////////////////////////////////////
// //
// TBrowserTimer //
// //
//////////////////////////////////////////////////////////////////////////
class TBrowserTimer : public TTimer {
protected:
TBrowser *fBrowser;
Bool_t fActivate;
public:
TBrowserTimer(TBrowser *b, Long_t ms = 1000)
: TTimer(ms, kTRUE), fBrowser(b), fActivate(kFALSE) { }
Bool_t Notify();
};
ClassImp(TBrowser)
//______________________________________________________________________________
TBrowser::TBrowser(const char *name, const char *title)
: TNamed(name, title)
{
// Create a new browser with a name, title. Width and height are by
// default set to 640x400 and (optionally) adjusted by the screen factor
// (depending on Rint.Canvas.UseScreenFactor to be true or false, default
// is true).
Float_t cx = gStyle->GetScreenFactor();
UInt_t w = UInt_t(cx*640);
UInt_t h = UInt_t(cx*400);
fImp = gGuiFactory->CreateBrowserImp(this, title, w, h);
Create();
}
//______________________________________________________________________________
TBrowser::TBrowser(const char *name, const char *title, UInt_t width, UInt_t height)
: TNamed(name, title)
{
// Create a new browser with a name, title, width and height.
fImp = gGuiFactory->CreateBrowserImp(this, title, width, height);
Create();
}
//______________________________________________________________________________
TBrowser::TBrowser(const char *name, const char *title, Int_t x, Int_t y, UInt_t width, UInt_t height)
: TNamed(name, title)
{
// Create a new browser with a name, title, position, width and height.
fImp = gGuiFactory->CreateBrowserImp(this, title, x, y, width, height);
Create();
}
//______________________________________________________________________________
TBrowser::TBrowser(const char *name, TObject *obj, const char *title)
: TNamed(name, title)
{
// Create a new browser with a name, title, width and height for TObject *obj.
Float_t cx = gStyle->GetScreenFactor();
UInt_t w = UInt_t(cx*640);
UInt_t h = UInt_t(cx*400);
fImp = gGuiFactory->CreateBrowserImp(this, title, w, h);
Create(obj);
}
//______________________________________________________________________________
TBrowser::TBrowser(const char *name, TObject *obj, const char *title, UInt_t width, UInt_t height)
: TNamed(name, title)
{
// Create a new browser with a name, title, width and height for TObject *obj.
fImp = gGuiFactory->CreateBrowserImp(this, title, width, height);
Create(obj);
}
//______________________________________________________________________________
TBrowser::TBrowser(const char *name, TObject *obj, const char *title, Int_t x, Int_t y, UInt_t width, UInt_t height)
: TNamed(name, title)
{
// Create a new browser with a name, title, width and height for TObject *obj.
fImp = gGuiFactory->CreateBrowserImp(this, title, x, y, width, height);
Create(obj);
}
//______________________________________________________________________________
TBrowser::~TBrowser()
{
// Delete the browser.
gROOT->GetListOfBrowsers()->Remove(this);
delete fContextMenu;
delete fTimer;
delete fImp;
}
//______________________________________________________________________________
void TBrowser::Add(TObject *obj, const char *name)
{
// Add object with name to browser. If name not set the objects GetName()
// is used.
if (obj && fImp) {
fImp->Add(obj, name);
obj->SetBit(kMustCleanup);
}
}
//______________________________________________________________________________
void TBrowser::Create(TObject *obj)
{
// Create the browser, called by the ctors.
fNeedRefresh = kFALSE;
fTimer = new TBrowserTimer(this);
gSystem->AddTimer(fTimer);
gROOT->GetListOfBrowsers()->Add(this);
// Get the list of globals
gROOT->GetListOfGlobals(kTRUE);
gROOT->GetListOfGlobalFunctions(kTRUE);
fContextMenu = new TContextMenu("BrowserContextMenu") ;
// Fill the first list from the present TObject obj
if (obj) {
Add(obj);
if (fImp) fImp->BrowseObj(obj);
}
// Fill the first list with all browsable classes from TROOT
else if (fImp) fImp->BrowseObj(gROOT);
// The first list will be filled by TWin32BrowserImp ctor
// with all browsable classes from TROOT
}
//______________________________________________________________________________
void TBrowser::ExecuteDefaultAction(TObject *obj)
{
// Execute default action for selected object (action is specified
// in the $HOME/.root.mimes or $ROOTSYS/etc/root.mimes file.
if (obj && fImp)
fImp->ExecuteDefaultAction(obj);
}
//______________________________________________________________________________
void TBrowser::RecursiveRemove(TObject *obj)
{
// Recursively remove obj from browser.
if (fImp && obj) {
fImp->RecursiveRemove(obj);
fNeedRefresh = kTRUE;
}
}
//______________________________________________________________________________
void TBrowser::Refresh()
{
// Refresh browser contents.
fNeedRefresh = kTRUE;
if (fImp) fImp->Refresh();
fNeedRefresh = kFALSE;
}
//______________________________________________________________________________
void TBrowser::SetSelected(TObject *clickedObject)
{
// Assign the last selected object.
fLastSelectedObject = clickedObject;
}
//////////////////////////////////////////////////////////////////////////
// //
// TBrowserTimer //
// //
//////////////////////////////////////////////////////////////////////////
//______________________________________________________________________________
Bool_t TBrowserTimer::Notify()
{
// Called whenever timer times out.
if (fBrowser) {
if (fBrowser->GetRefreshFlag()) {
fBrowser->SetRefreshFlag(kFALSE);
fActivate = kTRUE;
} else if (fActivate) {
fActivate = kFALSE;
fBrowser->Refresh();
}
}
Reset();
return kFALSE;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBenchmark.h"
#include "SkAAClip.h"
#include "SkPath.h"
#include "SkRegion.h"
#include "SkString.h"
#include "SkCanvas.h"
#include "SkRandom.h"
////////////////////////////////////////////////////////////////////////////////
// This bench tests out AA/BW clipping via canvas' clipPath and clipRect calls
class AAClipBench : public SkBenchmark {
SkString fName;
SkPath fClipPath;
SkRect fClipRect;
SkRect fDrawRect;
bool fDoPath;
bool fDoAA;
enum {
N = SkBENCHLOOP(200),
};
public:
AAClipBench(void* param, bool doPath, bool doAA)
: INHERITED(param)
, fDoPath(doPath)
, fDoAA(doAA) {
fName.printf("aaclip_%s_%s",
doPath ? "path" : "rect",
doAA ? "AA" : "BW");
fClipRect.set(SkFloatToScalar(10.5), SkFloatToScalar(10.5),
SkFloatToScalar(50.5), SkFloatToScalar(50.5));
fClipPath.addRoundRect(fClipRect, SkIntToScalar(10), SkIntToScalar(10));
fDrawRect.set(SkIntToScalar(0), SkIntToScalar(0),
SkIntToScalar(100), SkIntToScalar(100));
SkASSERT(fClipPath.isConvex());
}
protected:
virtual const char* onGetName() { return fName.c_str(); }
virtual void onDraw(SkCanvas* canvas) {
SkPaint paint;
this->setupPaint(&paint);
for (int i = 0; i < N; ++i) {
// jostle the clip regions each time to prevent caching
fClipRect.offset((i % 2) == 0 ? SkIntToScalar(10) : SkIntToScalar(-10), 0);
fClipPath.reset();
fClipPath.addRoundRect(fClipRect,
SkIntToScalar(5), SkIntToScalar(5));
SkASSERT(fClipPath.isConvex());
canvas->save();
#if 1
if (fDoPath) {
canvas->clipPath(fClipPath, SkRegion::kReplace_Op, fDoAA);
} else {
canvas->clipRect(fClipRect, SkRegion::kReplace_Op, fDoAA);
}
canvas->drawRect(fDrawRect, paint);
#else
// this path tests out directly draw the clip primitive
// use it to comparing just drawing the clip vs. drawing using
// the clip
if (fDoPath) {
canvas->drawPath(fClipPath, paint);
} else {
canvas->drawRect(fClipRect, paint);
}
#endif
canvas->restore();
}
}
private:
typedef SkBenchmark INHERITED;
};
////////////////////////////////////////////////////////////////////////////////
// This bench tests out nested clip stacks. It is intended to simulate
// how WebKit nests clips.
class NestedAAClipBench : public SkBenchmark {
SkString fName;
bool fDoAA;
SkRect fDrawRect;
SkRandom fRandom;
static const int kNumDraws = SkBENCHLOOP(200);
static const int kNestingDepth = 4;
static const int kImageSize = 400;
SkPoint fSizes[kNestingDepth+1];
public:
NestedAAClipBench(void* param, bool doAA)
: INHERITED(param)
, fDoAA(doAA) {
fName.printf("nested_aaclip_%s", doAA ? "AA" : "BW");
fDrawRect = SkRect::MakeLTRB(0, 0,
SkIntToScalar(kImageSize),
SkIntToScalar(kImageSize));
fSizes[0].set(SkIntToScalar(kImageSize), SkIntToScalar(kImageSize));
for (int i = 1; i < kNestingDepth+1; ++i) {
fSizes[i].set(fSizes[i-1].fX/2, fSizes[i-1].fY/2);
}
}
protected:
virtual const char* onGetName() { return fName.c_str(); }
void recurse(SkCanvas* canvas,
int depth,
const SkPoint& offset) {
canvas->save();
SkRect temp = SkRect::MakeLTRB(0, 0,
fSizes[depth].fX, fSizes[depth].fY);
temp.offset(offset);
SkPath path;
path.addRoundRect(temp, SkIntToScalar(3), SkIntToScalar(3));
SkASSERT(path.isConvex());
canvas->clipPath(path,
0 == depth ? SkRegion::kReplace_Op :
SkRegion::kIntersect_Op,
fDoAA);
if (kNestingDepth == depth) {
// we only draw the draw rect at the lowest nesting level
SkPaint paint;
paint.setColor(0xff000000 | fRandom.nextU());
canvas->drawRect(fDrawRect, paint);
} else {
SkPoint childOffset = offset;
this->recurse(canvas, depth+1, childOffset);
childOffset += fSizes[depth+1];
this->recurse(canvas, depth+1, childOffset);
childOffset.fX = offset.fX + fSizes[depth+1].fX;
childOffset.fY = offset.fY;
this->recurse(canvas, depth+1, childOffset);
childOffset.fX = offset.fX;
childOffset.fY = offset.fY + fSizes[depth+1].fY;
this->recurse(canvas, depth+1, childOffset);
}
canvas->restore();
}
virtual void onDraw(SkCanvas* canvas) {
for (int i = 0; i < kNumDraws; ++i) {
SkPoint offset = SkPoint::Make(0, 0);
this->recurse(canvas, 0, offset);
}
}
private:
typedef SkBenchmark INHERITED;
};
////////////////////////////////////////////////////////////////////////////////
class AAClipBuilderBench : public SkBenchmark {
SkString fName;
SkPath fPath;
SkRect fRect;
SkRegion fRegion;
bool fDoPath;
bool fDoAA;
enum {
N = SkBENCHLOOP(200),
};
public:
AAClipBuilderBench(void* param, bool doPath, bool doAA) : INHERITED(param) {
fDoPath = doPath;
fDoAA = doAA;
fName.printf("aaclip_build_%s_%s", doPath ? "path" : "rect",
doAA ? "AA" : "BW");
fRegion.setRect(0, 0, 640, 480);
fRect.set(fRegion.getBounds());
fRect.inset(SK_Scalar1/4, SK_Scalar1/4);
fPath.addRoundRect(fRect, SkIntToScalar(20), SkIntToScalar(20));
}
protected:
virtual const char* onGetName() { return fName.c_str(); }
virtual void onDraw(SkCanvas* canvas) {
SkPaint paint;
this->setupPaint(&paint);
for (int i = 0; i < N; ++i) {
SkAAClip clip;
if (fDoPath) {
clip.setPath(fPath, &fRegion, fDoAA);
} else {
clip.setRect(fRect, fDoAA);
}
}
}
private:
typedef SkBenchmark INHERITED;
};
////////////////////////////////////////////////////////////////////////////////
class AAClipRegionBench : public SkBenchmark {
public:
AAClipRegionBench(void* param) : INHERITED(param) {
SkPath path;
// test conversion of a complex clip to a aaclip
path.addCircle(0, 0, SkIntToScalar(200));
path.addCircle(0, 0, SkIntToScalar(180));
// evenodd means we've constructed basically a stroked circle
path.setFillType(SkPath::kEvenOdd_FillType);
SkIRect bounds;
path.getBounds().roundOut(&bounds);
fRegion.setPath(path, SkRegion(bounds));
}
protected:
virtual const char* onGetName() { return "aaclip_setregion"; }
virtual void onDraw(SkCanvas* canvas) {
for (int i = 0; i < N; ++i) {
SkAAClip clip;
clip.setRegion(fRegion);
}
}
private:
enum {
N = SkBENCHLOOP(400),
};
SkRegion fRegion;
typedef SkBenchmark INHERITED;
};
////////////////////////////////////////////////////////////////////////////////
static SkBenchmark* Fact0(void* p) { return SkNEW_ARGS(AAClipBuilderBench, (p, false, false)); }
static SkBenchmark* Fact1(void* p) { return SkNEW_ARGS(AAClipBuilderBench, (p, false, true)); }
static SkBenchmark* Fact2(void* p) { return SkNEW_ARGS(AAClipBuilderBench, (p, true, false)); }
static SkBenchmark* Fact3(void* p) { return SkNEW_ARGS(AAClipBuilderBench, (p, true, true)); }
static BenchRegistry gReg0(Fact0);
static BenchRegistry gReg1(Fact1);
static BenchRegistry gReg2(Fact2);
static BenchRegistry gReg3(Fact3);
static SkBenchmark* Fact01(void* p) { return SkNEW_ARGS(AAClipRegionBench, (p)); }
static BenchRegistry gReg01(Fact01);
static SkBenchmark* Fact000(void* p) { return SkNEW_ARGS(AAClipBench, (p, false, false)); }
static SkBenchmark* Fact001(void* p) { return SkNEW_ARGS(AAClipBench, (p, false, true)); }
static SkBenchmark* Fact002(void* p) { return SkNEW_ARGS(AAClipBench, (p, true, false)); }
static SkBenchmark* Fact003(void* p) { return SkNEW_ARGS(AAClipBench, (p, true, true)); }
static BenchRegistry gReg000(Fact000);
static BenchRegistry gReg001(Fact001);
static BenchRegistry gReg002(Fact002);
static BenchRegistry gReg003(Fact003);
static SkBenchmark* Fact004(void* p) { return SkNEW_ARGS(NestedAAClipBench, (p, false)); }
static SkBenchmark* Fact005(void* p) { return SkNEW_ARGS(NestedAAClipBench, (p, true)); }
static BenchRegistry gReg004(Fact004);
static BenchRegistry gReg005(Fact005);
<commit_msg>Dialed back complexity of nested clip bench to bring time down to a reasonable level<commit_after>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBenchmark.h"
#include "SkAAClip.h"
#include "SkPath.h"
#include "SkRegion.h"
#include "SkString.h"
#include "SkCanvas.h"
#include "SkRandom.h"
////////////////////////////////////////////////////////////////////////////////
// This bench tests out AA/BW clipping via canvas' clipPath and clipRect calls
class AAClipBench : public SkBenchmark {
SkString fName;
SkPath fClipPath;
SkRect fClipRect;
SkRect fDrawRect;
bool fDoPath;
bool fDoAA;
enum {
N = SkBENCHLOOP(200),
};
public:
AAClipBench(void* param, bool doPath, bool doAA)
: INHERITED(param)
, fDoPath(doPath)
, fDoAA(doAA) {
fName.printf("aaclip_%s_%s",
doPath ? "path" : "rect",
doAA ? "AA" : "BW");
fClipRect.set(SkFloatToScalar(10.5), SkFloatToScalar(10.5),
SkFloatToScalar(50.5), SkFloatToScalar(50.5));
fClipPath.addRoundRect(fClipRect, SkIntToScalar(10), SkIntToScalar(10));
fDrawRect.set(SkIntToScalar(0), SkIntToScalar(0),
SkIntToScalar(100), SkIntToScalar(100));
SkASSERT(fClipPath.isConvex());
}
protected:
virtual const char* onGetName() { return fName.c_str(); }
virtual void onDraw(SkCanvas* canvas) {
SkPaint paint;
this->setupPaint(&paint);
for (int i = 0; i < N; ++i) {
// jostle the clip regions each time to prevent caching
fClipRect.offset((i % 2) == 0 ? SkIntToScalar(10) : SkIntToScalar(-10), 0);
fClipPath.reset();
fClipPath.addRoundRect(fClipRect,
SkIntToScalar(5), SkIntToScalar(5));
SkASSERT(fClipPath.isConvex());
canvas->save();
#if 1
if (fDoPath) {
canvas->clipPath(fClipPath, SkRegion::kReplace_Op, fDoAA);
} else {
canvas->clipRect(fClipRect, SkRegion::kReplace_Op, fDoAA);
}
canvas->drawRect(fDrawRect, paint);
#else
// this path tests out directly draw the clip primitive
// use it to comparing just drawing the clip vs. drawing using
// the clip
if (fDoPath) {
canvas->drawPath(fClipPath, paint);
} else {
canvas->drawRect(fClipRect, paint);
}
#endif
canvas->restore();
}
}
private:
typedef SkBenchmark INHERITED;
};
////////////////////////////////////////////////////////////////////////////////
// This bench tests out nested clip stacks. It is intended to simulate
// how WebKit nests clips.
class NestedAAClipBench : public SkBenchmark {
SkString fName;
bool fDoAA;
SkRect fDrawRect;
SkRandom fRandom;
static const int kNumDraws = SkBENCHLOOP(2);
static const int kNestingDepth = 3;
static const int kImageSize = 400;
SkPoint fSizes[kNestingDepth+1];
public:
NestedAAClipBench(void* param, bool doAA)
: INHERITED(param)
, fDoAA(doAA) {
fName.printf("nested_aaclip_%s", doAA ? "AA" : "BW");
fDrawRect = SkRect::MakeLTRB(0, 0,
SkIntToScalar(kImageSize),
SkIntToScalar(kImageSize));
fSizes[0].set(SkIntToScalar(kImageSize), SkIntToScalar(kImageSize));
for (int i = 1; i < kNestingDepth+1; ++i) {
fSizes[i].set(fSizes[i-1].fX/2, fSizes[i-1].fY/2);
}
}
protected:
virtual const char* onGetName() { return fName.c_str(); }
void recurse(SkCanvas* canvas,
int depth,
const SkPoint& offset) {
canvas->save();
SkRect temp = SkRect::MakeLTRB(0, 0,
fSizes[depth].fX, fSizes[depth].fY);
temp.offset(offset);
SkPath path;
path.addRoundRect(temp, SkIntToScalar(3), SkIntToScalar(3));
SkASSERT(path.isConvex());
canvas->clipPath(path,
0 == depth ? SkRegion::kReplace_Op :
SkRegion::kIntersect_Op,
fDoAA);
if (kNestingDepth == depth) {
// we only draw the draw rect at the lowest nesting level
SkPaint paint;
paint.setColor(0xff000000 | fRandom.nextU());
canvas->drawRect(fDrawRect, paint);
} else {
SkPoint childOffset = offset;
this->recurse(canvas, depth+1, childOffset);
childOffset += fSizes[depth+1];
this->recurse(canvas, depth+1, childOffset);
childOffset.fX = offset.fX + fSizes[depth+1].fX;
childOffset.fY = offset.fY;
this->recurse(canvas, depth+1, childOffset);
childOffset.fX = offset.fX;
childOffset.fY = offset.fY + fSizes[depth+1].fY;
this->recurse(canvas, depth+1, childOffset);
}
canvas->restore();
}
virtual void onDraw(SkCanvas* canvas) {
for (int i = 0; i < kNumDraws; ++i) {
SkPoint offset = SkPoint::Make(0, 0);
this->recurse(canvas, 0, offset);
}
}
private:
typedef SkBenchmark INHERITED;
};
////////////////////////////////////////////////////////////////////////////////
class AAClipBuilderBench : public SkBenchmark {
SkString fName;
SkPath fPath;
SkRect fRect;
SkRegion fRegion;
bool fDoPath;
bool fDoAA;
enum {
N = SkBENCHLOOP(200),
};
public:
AAClipBuilderBench(void* param, bool doPath, bool doAA) : INHERITED(param) {
fDoPath = doPath;
fDoAA = doAA;
fName.printf("aaclip_build_%s_%s", doPath ? "path" : "rect",
doAA ? "AA" : "BW");
fRegion.setRect(0, 0, 640, 480);
fRect.set(fRegion.getBounds());
fRect.inset(SK_Scalar1/4, SK_Scalar1/4);
fPath.addRoundRect(fRect, SkIntToScalar(20), SkIntToScalar(20));
}
protected:
virtual const char* onGetName() { return fName.c_str(); }
virtual void onDraw(SkCanvas* canvas) {
SkPaint paint;
this->setupPaint(&paint);
for (int i = 0; i < N; ++i) {
SkAAClip clip;
if (fDoPath) {
clip.setPath(fPath, &fRegion, fDoAA);
} else {
clip.setRect(fRect, fDoAA);
}
}
}
private:
typedef SkBenchmark INHERITED;
};
////////////////////////////////////////////////////////////////////////////////
class AAClipRegionBench : public SkBenchmark {
public:
AAClipRegionBench(void* param) : INHERITED(param) {
SkPath path;
// test conversion of a complex clip to a aaclip
path.addCircle(0, 0, SkIntToScalar(200));
path.addCircle(0, 0, SkIntToScalar(180));
// evenodd means we've constructed basically a stroked circle
path.setFillType(SkPath::kEvenOdd_FillType);
SkIRect bounds;
path.getBounds().roundOut(&bounds);
fRegion.setPath(path, SkRegion(bounds));
}
protected:
virtual const char* onGetName() { return "aaclip_setregion"; }
virtual void onDraw(SkCanvas* canvas) {
for (int i = 0; i < N; ++i) {
SkAAClip clip;
clip.setRegion(fRegion);
}
}
private:
enum {
N = SkBENCHLOOP(400),
};
SkRegion fRegion;
typedef SkBenchmark INHERITED;
};
////////////////////////////////////////////////////////////////////////////////
static SkBenchmark* Fact0(void* p) { return SkNEW_ARGS(AAClipBuilderBench, (p, false, false)); }
static SkBenchmark* Fact1(void* p) { return SkNEW_ARGS(AAClipBuilderBench, (p, false, true)); }
static SkBenchmark* Fact2(void* p) { return SkNEW_ARGS(AAClipBuilderBench, (p, true, false)); }
static SkBenchmark* Fact3(void* p) { return SkNEW_ARGS(AAClipBuilderBench, (p, true, true)); }
static BenchRegistry gReg0(Fact0);
static BenchRegistry gReg1(Fact1);
static BenchRegistry gReg2(Fact2);
static BenchRegistry gReg3(Fact3);
static SkBenchmark* Fact01(void* p) { return SkNEW_ARGS(AAClipRegionBench, (p)); }
static BenchRegistry gReg01(Fact01);
static SkBenchmark* Fact000(void* p) { return SkNEW_ARGS(AAClipBench, (p, false, false)); }
static SkBenchmark* Fact001(void* p) { return SkNEW_ARGS(AAClipBench, (p, false, true)); }
static SkBenchmark* Fact002(void* p) { return SkNEW_ARGS(AAClipBench, (p, true, false)); }
static SkBenchmark* Fact003(void* p) { return SkNEW_ARGS(AAClipBench, (p, true, true)); }
static BenchRegistry gReg000(Fact000);
static BenchRegistry gReg001(Fact001);
static BenchRegistry gReg002(Fact002);
static BenchRegistry gReg003(Fact003);
static SkBenchmark* Fact004(void* p) { return SkNEW_ARGS(NestedAAClipBench, (p, false)); }
static SkBenchmark* Fact005(void* p) { return SkNEW_ARGS(NestedAAClipBench, (p, true)); }
static BenchRegistry gReg004(Fact004);
static BenchRegistry gReg005(Fact005);
<|endoftext|> |
<commit_before>///
/// @file main.cpp
/// @brief This file contains the main() function of the primesieve
/// console (terminal) application.
///
/// Copyright (C) 2013 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/soe/ParallelPrimeSieve.h>
#include "cmdoptions.h"
#include <iostream>
#include <exception>
#include <iomanip>
#include <algorithm>
#include <string>
using namespace std;
void printResults(const ParallelPrimeSieve& pps)
{
const string primeLabels[7] =
{
"Prime numbers",
"Twin primes",
"Prime triplets",
"Prime quadruplets",
"Prime quintuplets",
"Prime sextuplets",
"Prime septuplets"
};
int size = 0;
for (int i = 0; i < 7; i++) {
if (pps.isCount(i))
size = max(size, static_cast<int>(primeLabels[i].size()));
}
for (int i = 0; i < 7; i++) {
if (pps.isCount(i))
cout << setw(size) << primeLabels[i] << " : "
<< pps.getCount(i)
<< endl;
}
if (!pps.isPrint())
cout << setw(size) << "Time elapsed" << " : "
<< pps.getSeconds() << " sec"
<< endl;
}
int main(int argc, char** argv)
{
PrimeSieveOptions options = parseOptions(argc, argv);
ParallelPrimeSieve pps;
cout << left;
try
{
// needed to print the number of threads
if (options.nthPrime)
{
if (options.n.size() == 1)
options.n.push_back(0);
pps.setStart(options.n[1]);
pps.setStop(options.n[1]+ options.n[0] * 30);
}
else
{
if (options.n.size() == 1)
options.n.push_front(0);
pps.setStart(options.n[0]);
pps.setStop(options.n[1]);
}
if (options.flags != 0) pps.setFlags(options.flags);
if (options.sieveSize != 0) pps.setSieveSize(options.sieveSize);
if (options.threads != 0) pps.setNumThreads(options.threads);
else if (pps.isPrint()) pps.setNumThreads(1);
if (!options.quiet)
{
cout << "Sieve size = " << pps.getSieveSize() << " kilobytes" << endl;
cout << "Threads = " << pps.getNumThreads() << endl;
if (!pps.isPrint())
pps.addFlags(pps.PRINT_STATUS);
}
if (options.nthPrime)
{
uint64_t nthPrime = pps.nthPrime(options.n[0], options.n[1]);
cout << "Nth prime : " << nthPrime << endl;
cout << "Time elapsed : " << pps.getSeconds() << " sec" << endl;
}
else
{
pps.sieve();
printResults(pps);
}
}
catch (exception& e)
{
cerr << "Error: " << e.what() << "." << endl
<< "Try `primesieve --help' for more information." << endl;
return 1;
}
return 0;
}
<commit_msg>Refactoring<commit_after>///
/// @file main.cpp
/// @brief This file contains the main() function of the primesieve
/// console (terminal) application.
///
/// Copyright (C) 2013 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/soe/ParallelPrimeSieve.h>
#include "cmdoptions.h"
#include <iostream>
#include <exception>
#include <iomanip>
#include <algorithm>
#include <string>
using namespace std;
void printResults(const ParallelPrimeSieve& pps)
{
const string primeLabels[7] =
{
"Prime numbers",
"Twin primes",
"Prime triplets",
"Prime quadruplets",
"Prime quintuplets",
"Prime sextuplets",
"Prime septuplets"
};
int size = 0;
for (int i = 0; i < 7; i++) {
if (pps.isCount(i))
size = max(size, static_cast<int>(primeLabels[i].size()));
}
for (int i = 0; i < 7; i++) {
if (pps.isCount(i))
cout << setw(size) << primeLabels[i] << " : "
<< pps.getCount(i)
<< endl;
}
if (!pps.isPrint())
cout << setw(size) << "Time elapsed" << " : "
<< pps.getSeconds() << " sec"
<< endl;
}
int main(int argc, char** argv)
{
PrimeSieveOptions options = parseOptions(argc, argv);
ParallelPrimeSieve pps;
cout << left;
try
{
// needed to print the number of threads
if (options.nthPrime)
{
if (options.n.size() == 1)
options.n.push_back(0);
pps.setStart(options.n[1]);
pps.setStop(options.n[1] + options.n[0] * 30);
}
else
{
if (options.n.size() == 1)
options.n.push_front(0);
pps.setStart(options.n[0]);
pps.setStop(options.n[1]);
}
if (options.flags != 0) pps.setFlags(options.flags);
if (options.sieveSize != 0) pps.setSieveSize(options.sieveSize);
if (options.threads != 0) pps.setNumThreads(options.threads);
else if (pps.isPrint()) pps.setNumThreads(1);
if (!options.quiet)
{
cout << "Sieve size = " << pps.getSieveSize() << " kilobytes" << endl;
cout << "Threads = " << pps.getNumThreads() << endl;
if (!pps.isPrint())
pps.addFlags(pps.PRINT_STATUS);
}
if (options.nthPrime)
{
uint64_t nthPrime = pps.nthPrime(options.n[0], options.n[1]);
cout << "Nth prime : " << nthPrime << endl;
cout << "Time elapsed : " << pps.getSeconds() << " sec" << endl;
}
else
{
pps.sieve();
printResults(pps);
}
}
catch (exception& e)
{
cerr << "Error: " << e.what() << "." << endl
<< "Try `primesieve --help' for more information." << endl;
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>/* This file is part of the Vc library.
Copyright (C) 2009 Matthias Kretz <[email protected]>
Vc is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
Vc is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with Vc. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Vc/float_v>
#include <Vc/uint_v>
#include <Vc/IO>
#include "benchmark.h"
using namespace Vc;
// to benchmark the performance of gathers there are some different interesting cases:
// 1) gathers from the same memory location (basically broadcasts)
// 2) gathers from the same cache line (random access but localized to 64 or 128 bytes) (64 on
// most CPUs)
// 3) random access on memory that fits into L1 but is larger than a cache line
// 4) random access on memory that fits into L2 (per core) but is larger than L1
// 4b) random access on memory that fits into all of L2 but is larger than the per core L2
// 5) random access on memory that fits into L3 but is larger than L2
// 6) random access on memory that fits into memory but is larger than L3
// 7) random access on memory that fits into virtual memory but is larger than physical memory
//
// of those the last 3 are probably not interesting because they basically measure memory
// latency.
// Intel Core 2 Quad (Q6600) has 8MB L2
enum {
Repetitions = 2,
Factor = 160000 / float_v::Size,
MaxArraySize = 16 * 1024 * 1024 / sizeof(float), // 16 MB
L2ArraySize = 256 * 1024 / sizeof(float), // 256 KB
L1ArraySize = 32 * 1024 / sizeof(float), // 32 KB
CacheLineArraySize = 64 / sizeof(float), // 64 B
SingleArraySize = 1 // 4 B
};
// this is not a random number generator
class PseudoRandom
{
public:
PseudoRandom() : state(IndexesFromZero) {}
uint_v next();
private:
uint_v state;
};
uint_v PseudoRandom::next()
{
state = (state * 1103515245 + 12345);
return state >> 10;
}
void nextIndexes(uint_v &i, const unsigned int size)
{
static PseudoRandom r;
i = r.next() & (size - 1);
}
int doGather(const char *name, const unsigned int size, const float *data)
{
int blackHole = 0;
Benchmark timer(name, 2. * float_v::Size * Factor * sizeof(float), "B");
uint_v indexes1(IndexesFromZero);
uint_v indexes2(indexes1 + 1);
nextIndexes(indexes1, size);
nextIndexes(indexes2, size);
for (int repetitions = 0; repetitions < Repetitions; ++repetitions) {
float_v aa(Zero);
float_v bb(Zero);
timer.Start();
for (int i = 0; i < Factor; ++i) {
nextIndexes(indexes1, size);
nextIndexes(indexes2, size);
float_v a(data, indexes1);
float_v b(data, indexes2);
aa += a;
bb += b;
}
timer.Stop();
const int k = (aa < 20.f) && (bb < 20.f);
blackHole += k;
}
timer.Print();
return blackHole;
}
int main()
{
int blackHole = 1;
float *data = new float[MaxArraySize];
for (int i = 0; i < MaxArraySize; ++i) {
data[i] = static_cast<float>(static_cast<double>(rand()) / static_cast<double>(RAND_MAX));
}
blackHole += doGather("Broadcast Gather", SingleArraySize, data);
blackHole += doGather("Cacheline Gather", CacheLineArraySize, data);
blackHole += doGather("L1 Gather", L1ArraySize, data);
blackHole += doGather("L2 Gather", L2ArraySize, data);
blackHole += doGather("Memory Gather", MaxArraySize, data);
if (blackHole < 10) {
std::cout << std::endl;
}
return 0;
}
<commit_msg>compile with icc<commit_after>/* This file is part of the Vc library.
Copyright (C) 2009 Matthias Kretz <[email protected]>
Vc is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
Vc is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with Vc. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Vc/float_v>
#include <Vc/uint_v>
#include <Vc/IO>
#include "benchmark.h"
#include <cstdlib>
using namespace Vc;
// to benchmark the performance of gathers there are some different interesting cases:
// 1) gathers from the same memory location (basically broadcasts)
// 2) gathers from the same cache line (random access but localized to 64 or 128 bytes) (64 on
// most CPUs)
// 3) random access on memory that fits into L1 but is larger than a cache line
// 4) random access on memory that fits into L2 (per core) but is larger than L1
// 4b) random access on memory that fits into all of L2 but is larger than the per core L2
// 5) random access on memory that fits into L3 but is larger than L2
// 6) random access on memory that fits into memory but is larger than L3
// 7) random access on memory that fits into virtual memory but is larger than physical memory
//
// of those the last 3 are probably not interesting because they basically measure memory
// latency.
// Intel Core 2 Quad (Q6600) has 8MB L2
enum {
Repetitions = 2,
Factor = 160000 / float_v::Size,
MaxArraySize = 16 * 1024 * 1024 / sizeof(float), // 16 MB
L2ArraySize = 256 * 1024 / sizeof(float), // 256 KB
L1ArraySize = 32 * 1024 / sizeof(float), // 32 KB
CacheLineArraySize = 64 / sizeof(float), // 64 B
SingleArraySize = 1 // 4 B
};
// this is not a random number generator
class PseudoRandom
{
public:
PseudoRandom() : state(IndexesFromZero) {}
uint_v next();
private:
uint_v state;
};
uint_v PseudoRandom::next()
{
state = (state * 1103515245 + 12345);
return state >> 10;
}
void nextIndexes(uint_v &i, const unsigned int size)
{
static PseudoRandom r;
i = r.next() & (size - 1);
}
int doGather(const char *name, const unsigned int size, const float *data)
{
int blackHole = 0;
Benchmark timer(name, 2. * float_v::Size * Factor * sizeof(float), "B");
uint_v indexes1(IndexesFromZero);
uint_v indexes2(indexes1 + 1);
nextIndexes(indexes1, size);
nextIndexes(indexes2, size);
for (int repetitions = 0; repetitions < Repetitions; ++repetitions) {
float_v aa(Zero);
float_v bb(Zero);
timer.Start();
for (int i = 0; i < Factor; ++i) {
nextIndexes(indexes1, size);
nextIndexes(indexes2, size);
float_v a(data, indexes1);
float_v b(data, indexes2);
aa += a;
bb += b;
}
timer.Stop();
const int k = (aa < 20.f) && (bb < 20.f);
blackHole += k;
}
timer.Print();
return blackHole;
}
int main()
{
int blackHole = 1;
float *data = new float[MaxArraySize];
for (int i = 0; i < MaxArraySize; ++i) {
data[i] = static_cast<float>(static_cast<double>(std::rand()) / static_cast<double>(RAND_MAX));
}
blackHole += doGather("Broadcast Gather", SingleArraySize, data);
blackHole += doGather("Cacheline Gather", CacheLineArraySize, data);
blackHole += doGather("L1 Gather", L1ArraySize, data);
blackHole += doGather("L2 Gather", L2ArraySize, data);
blackHole += doGather("Memory Gather", MaxArraySize, data);
if (blackHole < 10) {
std::cout << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>// __BEGIN_LICENSE__
// Copyright (c) 2006-2013, United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration. All
// rights reserved.
//
// The NASA Vision Workbench is licensed under the Apache License,
// Version 2.0 (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// __END_LICENSE__
/// \file stereo_gui_MainWindow.cc
///
/// The Vision Workbench image viewer main window class.
///
#include <QtGui>
#include <asp/GUI/MainWindow.h>
#include <asp/GUI/MainWidget.h>
#include <asp/GUI/Utils.h>
using namespace vw::gui;
#include <vw/config.h>
#include <vw/Image/MaskViews.h>
#include <vw/FileIO/DiskImageView.h>
#include <vw/FileIO/DiskImageResource.h>
#include <vw/Image/Statistics.h>
#include <vw/Image/PixelMask.h>
#include <boost/filesystem/path.hpp>
#include <sstream>
namespace po = boost::program_options;
MainWindow::MainWindow(std::vector<std::string> const& images,
std::string const& geom,
bool ignore_georef, bool hillshade, int argc, char ** argv) :
m_images(images), m_widRatio(0.3), m_main_widget(NULL),
m_chooseFiles(NULL), m_argc(argc), m_argv(argv) {
int windowWidX, windowWidY;
extractWindowDims(geom, windowWidX, windowWidY);
resize(windowWidX, windowWidY);
// Set the window title and add tabs
std::string window_title = "Stereo GUI";
this->setWindowTitle(window_title.c_str());
// Set up the basic layout of the window and its menus.
create_menus();
if (images.size() > 1){
// Split the window into two, with the sidebar on the left
QWidget * centralFrame;
centralFrame = new QWidget(this);
setCentralWidget(centralFrame);
QSplitter *splitter = new QSplitter(centralFrame);
#if 0
m_chooseFiles = new chooseFilesDlg(this);
m_chooseFiles->setMaximumSize(int(m_widRatio*size().width()), size().height());
m_main_widget = new MainWidget(centralFrame, images, m_chooseFiles,
ignore_georef, hillshade);
splitter->addWidget(m_chooseFiles);
splitter->addWidget(m_main_widget);
#else
// for doing stereo
std::vector<std::string> left_images, right_images;
// TODO: Verify that these are valid images.
// TODO: Invoke here asp's handle_arguments().
if (images.size() >= 1)
left_images.push_back(images[0]);
if (images.size() >= 2)
right_images.push_back(images[1]);
m_left_widget = new MainWidget(centralFrame, left_images, m_chooseFiles,
ignore_georef, hillshade);
splitter->addWidget(m_left_widget);
if (images.size() >= 2) {
m_right_widget = new MainWidget(centralFrame, right_images, m_chooseFiles,
ignore_georef, hillshade);
splitter->addWidget(m_right_widget);
}
#endif
QGridLayout *layout = new QGridLayout(centralFrame);
layout->addWidget (splitter, 0, 0, 0);
centralFrame->setLayout (layout);
}else{
// Set up MainWidget
m_main_widget = new MainWidget(this, images, NULL, ignore_georef, hillshade);
setCentralWidget(m_main_widget);
}
}
//********************************************************************
// MAIN WINDOW SETUP
//********************************************************************
void MainWindow::create_menus() {
QMenuBar* menu = menuBar();
// Exit or Quit
m_exit_action = new QAction(tr("Exit"), this);
m_exit_action->setShortcut(tr("Q"));
m_exit_action->setStatusTip(tr("Exit the application"));
connect(m_exit_action, SIGNAL(triggered()), this, SLOT(forceQuit()));
// Run stereo
m_run_stereo_action = new QAction(tr("Run stereo"), this);
m_run_stereo_action->setStatusTip(tr("Run stereo on selected clips."));
connect(m_run_stereo_action, SIGNAL(triggered()), this, SLOT(run_stereo()));
m_run_stereo_action->setShortcut(tr("R"));
// Size to fit
m_size_to_fit_action = new QAction(tr("Size to fit"), this);
m_size_to_fit_action->setStatusTip(tr("Change the view to encompass the images."));
connect(m_size_to_fit_action, SIGNAL(triggered()), this, SLOT(size_to_fit()));
m_size_to_fit_action->setShortcut(tr("F"));
// The About Box
m_about_action = new QAction(tr("About stereo_gui"), this);
m_about_action->setStatusTip(tr("Show the stereo_gui about box."));
connect(m_about_action, SIGNAL(triggered()), this, SLOT(about()));
// File menu
m_file_menu = menu->addMenu(tr("&File"));
m_file_menu->addAction(m_exit_action);
// Run menu
m_file_menu = menu->addMenu(tr("&Run"));
m_file_menu->addAction(m_run_stereo_action);
// View menu
menu->addSeparator();
m_view_menu = menu->addMenu(tr("&View"));
m_view_menu->addAction(m_size_to_fit_action);
// Help menu
menu->addSeparator();
m_help_menu = menu->addMenu(tr("&Help"));
m_help_menu->addAction(m_about_action);
}
void MainWindow::resizeEvent(QResizeEvent *){
if (m_chooseFiles)
m_chooseFiles->setMaximumSize(int(m_widRatio*size().width()), size().height());
}
void MainWindow::closeEvent(QCloseEvent *){
forceQuit();
}
void MainWindow::forceQuit(){
exit(0); // A fix for an older buggy version of Qt
}
void MainWindow::size_to_fit(){
if (m_main_widget)
m_main_widget->size_to_fit();
if (m_left_widget)
m_left_widget->size_to_fit();
if (m_right_widget)
m_right_widget->size_to_fit();
}
void MainWindow::run_stereo(){
if (m_left_widget && m_right_widget) {
QRect left_win = m_left_widget->get_crop_win();
QRect right_win = m_right_widget->get_crop_win();
int left_x = left_win.x();
int left_y = left_win.y();
int left_wx = left_win.width();
int left_wy = left_win.height();
int right_x = right_win.x();
int right_y = right_win.y();
int right_wx = right_win.width();
int right_wy = right_win.height();
// Run stereo
std::string run_cmd = "stereo ";
for (int i = 1; i < m_argc; i++) {
run_cmd += std::string(m_argv[i]) + " ";
}
std::ostringstream os;
os << "--left-image-crop-win " << left_x << " " << left_y << " "
<< left_wx << " " << left_wy << " ";
os << "--right-image-crop-win " << right_x << " " << right_y << " "
<< right_wx << " " << right_wy << " ";
run_cmd += os.str();
std::cout << "Running: " << run_cmd << std::endl;
system(run_cmd.c_str());
QMessageBox::about(this, tr("Error"), tr("Done running stereo"));
} else {
QMessageBox::about(this, tr("Error"), tr("Not ready to run stereo"));
}
}
void MainWindow::about() {
std::ostringstream about_text;
about_text << "<h3>stereo_gui</h3>"
<< "<p>Copyright © 2015 NASA Ames Research Center. See the manual for documentation.</p>";
QMessageBox::about(this, tr("About stereo_gui"),
tr(about_text.str().c_str()));
}
void MainWindow::keyPressEvent(QKeyEvent *event) {
std::ostringstream s;
switch (event->key()) {
case Qt::Key_Escape: // Quit
close();
break;
}
}
<commit_msg>stereo_gui: Minor robusness tweaks<commit_after>// __BEGIN_LICENSE__
// Copyright (c) 2006-2013, United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration. All
// rights reserved.
//
// The NASA Vision Workbench is licensed under the Apache License,
// Version 2.0 (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// __END_LICENSE__
/// \file stereo_gui_MainWindow.cc
///
/// The Vision Workbench image viewer main window class.
///
#include <QtGui>
#include <asp/GUI/MainWindow.h>
#include <asp/GUI/MainWidget.h>
#include <asp/GUI/Utils.h>
using namespace vw::gui;
#include <vw/config.h>
#include <vw/Image/MaskViews.h>
#include <vw/FileIO/DiskImageView.h>
#include <vw/FileIO/DiskImageResource.h>
#include <vw/Image/Statistics.h>
#include <vw/Image/PixelMask.h>
#include <boost/filesystem/path.hpp>
#include <sstream>
namespace po = boost::program_options;
MainWindow::MainWindow(std::vector<std::string> const& images,
std::string const& geom,
bool ignore_georef, bool hillshade,
int argc, char ** argv) :
m_images(images), m_widRatio(0.3), m_main_widget(NULL),
m_left_widget(NULL), m_right_widget(NULL),
m_chooseFiles(NULL), m_argc(argc), m_argv(argv) {
int windowWidX, windowWidY;
extractWindowDims(geom, windowWidX, windowWidY);
resize(windowWidX, windowWidY);
// Set the window title and add tabs
std::string window_title = "Stereo GUI";
this->setWindowTitle(window_title.c_str());
// Set up the basic layout of the window and its menus.
create_menus();
if (images.size() > 1){
// Split the window into two, with the sidebar on the left
QWidget * centralFrame;
centralFrame = new QWidget(this);
setCentralWidget(centralFrame);
QSplitter *splitter = new QSplitter(centralFrame);
#if 0
m_chooseFiles = new chooseFilesDlg(this);
m_chooseFiles->setMaximumSize(int(m_widRatio*size().width()), size().height());
m_main_widget = new MainWidget(centralFrame, images, m_chooseFiles,
ignore_georef, hillshade);
splitter->addWidget(m_chooseFiles);
splitter->addWidget(m_main_widget);
#else
// for doing stereo
std::vector<std::string> left_images, right_images;
// TODO: Verify that these are valid images.
// TODO: Invoke here asp's handle_arguments().
if (images.size() >= 1)
left_images.push_back(images[0]);
if (images.size() >= 2)
right_images.push_back(images[1]);
m_left_widget = new MainWidget(centralFrame, left_images, m_chooseFiles,
ignore_georef, hillshade);
splitter->addWidget(m_left_widget);
if (images.size() >= 2) {
m_right_widget = new MainWidget(centralFrame, right_images, m_chooseFiles,
ignore_georef, hillshade);
splitter->addWidget(m_right_widget);
}
#endif
QGridLayout *layout = new QGridLayout(centralFrame);
layout->addWidget (splitter, 0, 0, 0);
centralFrame->setLayout (layout);
}else{
// Set up MainWidget
m_main_widget = new MainWidget(this, images, NULL, ignore_georef, hillshade);
setCentralWidget(m_main_widget);
}
}
//********************************************************************
// MAIN WINDOW SETUP
//********************************************************************
void MainWindow::create_menus() {
QMenuBar* menu = menuBar();
// Exit or Quit
m_exit_action = new QAction(tr("Exit"), this);
m_exit_action->setShortcut(tr("Q"));
m_exit_action->setStatusTip(tr("Exit the application"));
connect(m_exit_action, SIGNAL(triggered()), this, SLOT(forceQuit()));
// Run stereo
m_run_stereo_action = new QAction(tr("Run stereo"), this);
m_run_stereo_action->setStatusTip(tr("Run stereo on selected clips."));
connect(m_run_stereo_action, SIGNAL(triggered()), this, SLOT(run_stereo()));
m_run_stereo_action->setShortcut(tr("R"));
// Size to fit
m_size_to_fit_action = new QAction(tr("Size to fit"), this);
m_size_to_fit_action->setStatusTip(tr("Change the view to encompass the images."));
connect(m_size_to_fit_action, SIGNAL(triggered()), this, SLOT(size_to_fit()));
m_size_to_fit_action->setShortcut(tr("F"));
// The About Box
m_about_action = new QAction(tr("About stereo_gui"), this);
m_about_action->setStatusTip(tr("Show the stereo_gui about box."));
connect(m_about_action, SIGNAL(triggered()), this, SLOT(about()));
// File menu
m_file_menu = menu->addMenu(tr("&File"));
m_file_menu->addAction(m_exit_action);
// Run menu
m_file_menu = menu->addMenu(tr("&Run"));
m_file_menu->addAction(m_run_stereo_action);
// View menu
menu->addSeparator();
m_view_menu = menu->addMenu(tr("&View"));
m_view_menu->addAction(m_size_to_fit_action);
// Help menu
menu->addSeparator();
m_help_menu = menu->addMenu(tr("&Help"));
m_help_menu->addAction(m_about_action);
}
void MainWindow::resizeEvent(QResizeEvent *){
if (m_chooseFiles)
m_chooseFiles->setMaximumSize(int(m_widRatio*size().width()), size().height());
}
void MainWindow::closeEvent(QCloseEvent *){
forceQuit();
}
void MainWindow::forceQuit(){
exit(0); // A fix for an older buggy version of Qt
}
void MainWindow::size_to_fit(){
if (m_main_widget)
m_main_widget->size_to_fit();
if (m_left_widget)
m_left_widget->size_to_fit();
if (m_right_widget)
m_right_widget->size_to_fit();
}
void MainWindow::run_stereo(){
if (m_left_widget && m_right_widget) {
QRect left_win = m_left_widget->get_crop_win();
QRect right_win = m_right_widget->get_crop_win();
int left_x = left_win.x();
int left_y = left_win.y();
int left_wx = left_win.width();
int left_wy = left_win.height();
int right_x = right_win.x();
int right_y = right_win.y();
int right_wx = right_win.width();
int right_wy = right_win.height();
// Run stereo
std::string run_cmd = "stereo ";
for (int i = 1; i < m_argc; i++) {
run_cmd += std::string(m_argv[i]) + " ";
}
std::ostringstream os;
os << "--left-image-crop-win " << left_x << " " << left_y << " "
<< left_wx << " " << left_wy << " ";
os << "--right-image-crop-win " << right_x << " " << right_y << " "
<< right_wx << " " << right_wy << " ";
run_cmd += os.str();
std::cout << "Running: " << run_cmd << std::endl;
system(run_cmd.c_str());
QMessageBox::about(this, tr("Error"), tr("Done running stereo"));
} else {
QMessageBox::about(this, tr("Error"), tr("Not ready to run stereo"));
}
}
void MainWindow::about() {
std::ostringstream about_text;
about_text << "<h3>stereo_gui</h3>"
<< "<p>Copyright © 2015 NASA Ames Research Center. See the manual for documentation.</p>";
QMessageBox::about(this, tr("About stereo_gui"),
tr(about_text.str().c_str()));
}
void MainWindow::keyPressEvent(QKeyEvent *event) {
std::ostringstream s;
switch (event->key()) {
case Qt::Key_Escape: // Quit
close();
break;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2015 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cstdint>
#include <cstdio>
#include <signal.h>
#include <util/CommandOptionParser.h>
#include <thread>
#include <Aeron.h>
#include <array>
#include <concurrent/BusySpinIdleStrategy.h>
#include "Configuration.h"
#include "RateReporter.h"
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
using namespace aeron::util;
using namespace aeron;
std::atomic<bool> running (true);
void sigIntHandler (int param)
{
running = false;
}
static const char optHelp = 'h';
static const char optPrefix = 'p';
static const char optChannel = 'c';
static const char optStreamId = 's';
static const char optMessages = 'm';
static const char optLinger = 'l';
static const char optLength = 'L';
static const char optRandLen = 'r';
struct Settings
{
std::string dirPrefix = "";
std::string channel = samples::configuration::DEFAULT_CHANNEL;
std::int32_t streamId = samples::configuration::DEFAULT_STREAM_ID;
long numberOfMessages = samples::configuration::DEFAULT_NUMBER_OF_MESSAGES;
int messageLength = samples::configuration::DEFAULT_MESSAGE_LENGTH;
int lingerTimeoutMs = samples::configuration::DEFAULT_LINGER_TIMEOUT_MS;
bool randomMessageLength = samples::configuration::DEFAULT_RANDOM_MESSAGE_LENGTH;
};
Settings parseCmdLine(CommandOptionParser& cp, int argc, char** argv)
{
cp.parse(argc, argv);
if (cp.getOption(optHelp).isPresent())
{
cp.displayOptionsHelp(std::cout);
exit(0);
}
Settings s;
s.dirPrefix = cp.getOption(optPrefix).getParam(0, s.dirPrefix);
s.channel = cp.getOption(optChannel).getParam(0, s.channel);
s.streamId = cp.getOption(optStreamId).getParamAsInt(0, 1, INT32_MAX, s.streamId);
s.numberOfMessages = cp.getOption(optMessages).getParamAsLong(0, 0, INT64_MAX, s.numberOfMessages);
s.messageLength = cp.getOption(optLength).getParamAsInt(0, sizeof(std::int64_t), INT32_MAX, s.messageLength);
s.lingerTimeoutMs = cp.getOption(optLinger).getParamAsInt(0, 0, 60 * 60 * 1000, s.lingerTimeoutMs);
s.randomMessageLength = cp.getOption(optRandLen).isPresent();
return s;
}
std::atomic<bool> printingActive;
void printRate(double messagesPerSec, double bytesPerSec, long totalFragments, long totalBytes)
{
if (printingActive)
{
std::printf(
"%.02g msgs/sec, %.02g bytes/sec, totals %ld messages %ld MB\n",
messagesPerSec, bytesPerSec, totalFragments, totalBytes / (1024 * 1024));
}
}
typedef std::function<int()> on_new_length_t;
static std::random_device randomDevice;
static std::default_random_engine randomEngine(randomDevice());
static std::uniform_int_distribution<int> uniformLengthDistribution;
on_new_length_t composeLengthGenerator(bool random, int max)
{
if (random)
{
std::uniform_int_distribution<int>::param_type param(sizeof(std::int64_t), max);
uniformLengthDistribution.param(param);
return [&]()
{
return uniformLengthDistribution(randomEngine);
};
}
else
{
return [&]() { return max; };
}
}
int main(int argc, char **argv)
{
CommandOptionParser cp;
cp.addOption(CommandOption (optHelp, 0, 0, " Displays help information."));
cp.addOption(CommandOption (optRandLen, 0, 0, " Random Message Length."));
cp.addOption(CommandOption (optPrefix, 1, 1, "dir Prefix directory for aeron driver."));
cp.addOption(CommandOption (optChannel, 1, 1, "channel Channel."));
cp.addOption(CommandOption (optStreamId, 1, 1, "streamId Stream ID."));
cp.addOption(CommandOption (optMessages, 1, 1, "number Number of Messages."));
cp.addOption(CommandOption (optLength, 1, 1, "length Length of Messages."));
cp.addOption(CommandOption (optLinger, 1, 1, "milliseconds Linger timeout in milliseconds."));
signal (SIGINT, sigIntHandler);
try
{
Settings settings = parseCmdLine(cp, argc, argv);
::setlocale(LC_NUMERIC, "");
std::printf(
"Streaming %'ld messages of%s size %d bytes to %s on stream ID %d\n",
settings.numberOfMessages,
settings.randomMessageLength ? " random" : "",
settings.messageLength,
settings.channel.c_str(),
settings.streamId);
aeron::Context context;
if (settings.dirPrefix != "")
{
context.aeronDir(settings.dirPrefix);
}
context.newPublicationHandler(
[](const std::string& channel, std::int32_t streamId, std::int32_t sessionId, std::int64_t correlationId)
{
std::cout << "Publication: " << channel << " " << correlationId << ":" << streamId << ":" << sessionId << std::endl;
});
Aeron aeron(context);
// add the publication to start the process
std::int64_t id = aeron.addPublication(settings.channel, settings.streamId);
std::shared_ptr<Publication> publication = aeron.findPublication(id);
// wait for the publication to be valid
while (!publication)
{
std::this_thread::yield();
publication = aeron.findPublication(id);
}
std::unique_ptr<std::uint8_t[]> buffer(new std::uint8_t[settings.messageLength]);
concurrent::AtomicBuffer srcBuffer(buffer.get(), settings.messageLength);
BusySpinIdleStrategy offerIdleStrategy;
on_new_length_t lengthGenerator = composeLengthGenerator(settings.randomMessageLength, settings.messageLength);
RateReporter rateReporter(std::chrono::seconds(1), printRate);
std::thread rateReporterThread([&](){ rateReporter.run(); });
do
{
printingActive = true;
for (long i = 0; i < settings.numberOfMessages && running; i++)
{
const int length = lengthGenerator();
srcBuffer.putInt64(0, i);
while (publication->offer(srcBuffer, 0, length) < 0L)
{
offerIdleStrategy.idle(0);
}
rateReporter.onMessage(1, length);
}
std::cout << "Done streaming." << std::endl;
if (running && settings.lingerTimeoutMs > 0)
{
std::cout << "Lingering for " << settings.lingerTimeoutMs << " milliseconds." << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(settings.lingerTimeoutMs));
}
printingActive = false;
}
while (running && continuationBarrier("Execute again?"));
rateReporter.halt();
rateReporterThread.join();
}
catch (CommandOptionException& e)
{
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
cp.displayOptionsHelp(std::cerr);
return -1;
}
catch (SourcedException& e)
{
std::cerr << "FAILED: " << e.what() << " : " << e.where() << std::endl;
return -1;
}
catch (std::exception& e)
{
std::cerr << "FAILED: " << e.what() << " : " << std::endl;
return -1;
}
return 0;
}
<commit_msg>[C++]: add back pressure ratio to StreamingPublisher<commit_after>/*
* Copyright 2015 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cstdint>
#include <cstdio>
#include <signal.h>
#include <util/CommandOptionParser.h>
#include <thread>
#include <Aeron.h>
#include <array>
#include <concurrent/BusySpinIdleStrategy.h>
#include "Configuration.h"
#include "RateReporter.h"
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
using namespace aeron::util;
using namespace aeron;
std::atomic<bool> running (true);
void sigIntHandler (int param)
{
running = false;
}
static const char optHelp = 'h';
static const char optPrefix = 'p';
static const char optChannel = 'c';
static const char optStreamId = 's';
static const char optMessages = 'm';
static const char optLinger = 'l';
static const char optLength = 'L';
static const char optRandLen = 'r';
struct Settings
{
std::string dirPrefix = "";
std::string channel = samples::configuration::DEFAULT_CHANNEL;
std::int32_t streamId = samples::configuration::DEFAULT_STREAM_ID;
long numberOfMessages = samples::configuration::DEFAULT_NUMBER_OF_MESSAGES;
int messageLength = samples::configuration::DEFAULT_MESSAGE_LENGTH;
int lingerTimeoutMs = samples::configuration::DEFAULT_LINGER_TIMEOUT_MS;
bool randomMessageLength = samples::configuration::DEFAULT_RANDOM_MESSAGE_LENGTH;
};
Settings parseCmdLine(CommandOptionParser& cp, int argc, char** argv)
{
cp.parse(argc, argv);
if (cp.getOption(optHelp).isPresent())
{
cp.displayOptionsHelp(std::cout);
exit(0);
}
Settings s;
s.dirPrefix = cp.getOption(optPrefix).getParam(0, s.dirPrefix);
s.channel = cp.getOption(optChannel).getParam(0, s.channel);
s.streamId = cp.getOption(optStreamId).getParamAsInt(0, 1, INT32_MAX, s.streamId);
s.numberOfMessages = cp.getOption(optMessages).getParamAsLong(0, 0, INT64_MAX, s.numberOfMessages);
s.messageLength = cp.getOption(optLength).getParamAsInt(0, sizeof(std::int64_t), INT32_MAX, s.messageLength);
s.lingerTimeoutMs = cp.getOption(optLinger).getParamAsInt(0, 0, 60 * 60 * 1000, s.lingerTimeoutMs);
s.randomMessageLength = cp.getOption(optRandLen).isPresent();
return s;
}
std::atomic<bool> printingActive;
void printRate(double messagesPerSec, double bytesPerSec, long totalFragments, long totalBytes)
{
if (printingActive)
{
std::printf(
"%.02g msgs/sec, %.02g bytes/sec, totals %ld messages %ld MB\n",
messagesPerSec, bytesPerSec, totalFragments, totalBytes / (1024 * 1024));
}
}
typedef std::function<int()> on_new_length_t;
static std::random_device randomDevice;
static std::default_random_engine randomEngine(randomDevice());
static std::uniform_int_distribution<int> uniformLengthDistribution;
on_new_length_t composeLengthGenerator(bool random, int max)
{
if (random)
{
std::uniform_int_distribution<int>::param_type param(sizeof(std::int64_t), max);
uniformLengthDistribution.param(param);
return [&]()
{
return uniformLengthDistribution(randomEngine);
};
}
else
{
return [&]() { return max; };
}
}
int main(int argc, char **argv)
{
CommandOptionParser cp;
cp.addOption(CommandOption (optHelp, 0, 0, " Displays help information."));
cp.addOption(CommandOption (optRandLen, 0, 0, " Random Message Length."));
cp.addOption(CommandOption (optPrefix, 1, 1, "dir Prefix directory for aeron driver."));
cp.addOption(CommandOption (optChannel, 1, 1, "channel Channel."));
cp.addOption(CommandOption (optStreamId, 1, 1, "streamId Stream ID."));
cp.addOption(CommandOption (optMessages, 1, 1, "number Number of Messages."));
cp.addOption(CommandOption (optLength, 1, 1, "length Length of Messages."));
cp.addOption(CommandOption (optLinger, 1, 1, "milliseconds Linger timeout in milliseconds."));
signal (SIGINT, sigIntHandler);
try
{
Settings settings = parseCmdLine(cp, argc, argv);
::setlocale(LC_NUMERIC, "");
std::printf(
"Streaming %'ld messages of%s size %d bytes to %s on stream ID %d\n",
settings.numberOfMessages,
settings.randomMessageLength ? " random" : "",
settings.messageLength,
settings.channel.c_str(),
settings.streamId);
aeron::Context context;
if (settings.dirPrefix != "")
{
context.aeronDir(settings.dirPrefix);
}
context.newPublicationHandler(
[](const std::string& channel, std::int32_t streamId, std::int32_t sessionId, std::int64_t correlationId)
{
std::cout << "Publication: " << channel << " " << correlationId << ":" << streamId << ":" << sessionId << std::endl;
});
Aeron aeron(context);
// add the publication to start the process
std::int64_t id = aeron.addPublication(settings.channel, settings.streamId);
std::shared_ptr<Publication> publication = aeron.findPublication(id);
// wait for the publication to be valid
while (!publication)
{
std::this_thread::yield();
publication = aeron.findPublication(id);
}
std::unique_ptr<std::uint8_t[]> buffer(new std::uint8_t[settings.messageLength]);
concurrent::AtomicBuffer srcBuffer(buffer.get(), settings.messageLength);
BusySpinIdleStrategy offerIdleStrategy;
on_new_length_t lengthGenerator = composeLengthGenerator(settings.randomMessageLength, settings.messageLength);
RateReporter rateReporter(std::chrono::seconds(1), printRate);
std::thread rateReporterThread([&](){ rateReporter.run(); });
do
{
printingActive = true;
long backPressureCount = 0;
for (long i = 0; i < settings.numberOfMessages && running; i++)
{
const int length = lengthGenerator();
srcBuffer.putInt64(0, i);
while (publication->offer(srcBuffer, 0, length) < 0L)
{
backPressureCount++;
offerIdleStrategy.idle(0);
}
rateReporter.onMessage(1, length);
}
std::cout << "Done streaming. Back pressure ratio ";
std::cout << ((double)backPressureCount / (double)settings.numberOfMessages) << std::endl;
if (running && settings.lingerTimeoutMs > 0)
{
std::cout << "Lingering for " << settings.lingerTimeoutMs << " milliseconds." << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(settings.lingerTimeoutMs));
}
printingActive = false;
}
while (running && continuationBarrier("Execute again?"));
rateReporter.halt();
rateReporterThread.join();
}
catch (CommandOptionException& e)
{
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
cp.displayOptionsHelp(std::cerr);
return -1;
}
catch (SourcedException& e)
{
std::cerr << "FAILED: " << e.what() << " : " << e.where() << std::endl;
return -1;
}
catch (std::exception& e)
{
std::cerr << "FAILED: " << e.what() << " : " << std::endl;
return -1;
}
return 0;
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2010, Image Engine Design Inc. 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 Image Engine Design nor the names of any
// other contributors to this software 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 OWNER 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.
//
//////////////////////////////////////////////////////////////////////////
// This include needs to be the very first to prevent problems with warnings
// regarding redefinition of _POSIX_C_SOURCE
#include "boost/python.hpp"
#include "IECore/Group.h"
#include "IECorePython/GroupBinding.h"
#include "IECorePython/RunTimeTypedBinding.h"
using namespace boost::python;
using namespace IECore;
namespace IECorePython
{
/// \todo: this should return a tuple rather than a list
static list children( Group &g )
{
list result;
for( Group::ChildContainer::const_iterator it=g.children().begin(); it!=g.children().end(); it++ )
{
result.append( *it );
}
return result;
}
/// \todo: this should return a tuple rather than a list
static list state( Group &g )
{
list result;
for( Group::StateContainer::const_iterator it=g.state().begin(); it!=g.state().end(); it++ )
{
result.append( *it );
}
return result;
}
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS( transformMatrixOverloads, transformMatrix, 0, 1 );
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS( globalTransformMatrixOverloads, globalTransformMatrix, 0, 1 );
void bindGroup()
{
RunTimeTypedClass<Group>()
.def( init<>() )
.def( "children", &children, "Returns all the children in a list - note that modifying the list will not add or remove children." )
.def( "addChild", &Group::addChild )
.def( "removeChild", &Group::removeChild )
.def( "clearChildren", &Group::clearChildren )
.def( "state", &state, "Returns all the state in a list - note that modifying the list will not add or remove state." )
.def( "addState", &Group::addState )
.def( "removeState", &Group::removeState )
.def( "clearState", &Group::clearState )
.def( "getTransform", (TransformPtr (Group::*)())&Group::getTransform )
.def( "setTransform", &Group::setTransform )
.def( "transformMatrix", &Group::transformMatrix, transformMatrixOverloads() )
.def( "globalTransformMatrix", &Group::globalTransformMatrix, globalTransformMatrixOverloads() )
.def( "parent", (GroupPtr (Group::*)())&Group::parent )
;
}
}
<commit_msg>Adding binding changes which should have been with previous commit.<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2010, Image Engine Design Inc. 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 Image Engine Design nor the names of any
// other contributors to this software 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 OWNER 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.
//
//////////////////////////////////////////////////////////////////////////
// This include needs to be the very first to prevent problems with warnings
// regarding redefinition of _POSIX_C_SOURCE
#include "boost/python.hpp"
#include "IECore/Group.h"
#include "IECore/Renderer.h"
#include "IECorePython/GroupBinding.h"
#include "IECorePython/RunTimeTypedBinding.h"
#include "IECorePython/ScopedGILRelease.h"
using namespace boost::python;
using namespace IECore;
namespace IECorePython
{
/// \todo: this should return a tuple rather than a list
static list children( Group &g )
{
list result;
for( Group::ChildContainer::const_iterator it=g.children().begin(); it!=g.children().end(); it++ )
{
result.append( *it );
}
return result;
}
/// \todo: this should return a tuple rather than a list
static list state( Group &g )
{
list result;
for( Group::StateContainer::const_iterator it=g.state().begin(); it!=g.state().end(); it++ )
{
result.append( *it );
}
return result;
}
static void render( const Group &group, Renderer *renderer )
{
IECorePython::ScopedGILRelease gilRelease;
group.render( renderer );
}
static void render2( const Group &group, Renderer *renderer, bool inAttributeBlock )
{
IECorePython::ScopedGILRelease gilRelease;
group.render( renderer, inAttributeBlock );
}
static void renderState( const Group &group, Renderer *renderer )
{
IECorePython::ScopedGILRelease gilRelease;
group.renderState( renderer );
}
static void renderChildren( const Group &group, Renderer *renderer )
{
IECorePython::ScopedGILRelease gilRelease;
group.renderChildren( renderer );
}
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS( transformMatrixOverloads, transformMatrix, 0, 1 );
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS( globalTransformMatrixOverloads, globalTransformMatrix, 0, 1 );
void bindGroup()
{
RunTimeTypedClass<Group>()
.def( init<>() )
.def( "children", &children, "Returns all the children in a list - note that modifying the list will not add or remove children." )
.def( "addChild", &Group::addChild )
.def( "removeChild", &Group::removeChild )
.def( "clearChildren", &Group::clearChildren )
.def( "state", &state, "Returns all the state in a list - note that modifying the list will not add or remove state." )
.def( "addState", &Group::addState )
.def( "removeState", &Group::removeState )
.def( "clearState", &Group::clearState )
.def( "getTransform", (TransformPtr (Group::*)())&Group::getTransform )
.def( "setTransform", &Group::setTransform )
.def( "transformMatrix", &Group::transformMatrix, transformMatrixOverloads() )
.def( "globalTransformMatrix", &Group::globalTransformMatrix, globalTransformMatrixOverloads() )
.def( "parent", (GroupPtr (Group::*)())&Group::parent )
.def( "render", &render )
.def( "render", &render2 )
.def( "renderState", &renderState )
.def( "renderChildren", &renderChildren )
;
}
}
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (c) sliptonic ([email protected]) 2020 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <boost/algorithm/string.hpp>
#endif
#include "Mod/Path/App/Voronoi.h"
#include "Mod/Path/App/VoronoiCell.h"
#include "Mod/Path/App/VoronoiEdge.h"
#include "Mod/Path/App/VoronoiVertex.h"
#include <Base/Exception.h>
#include <Base/GeometryPyCXX.h>
#include <Base/Vector3D.h>
#include <Base/VectorPy.h>
// files generated out of VoronoiPy.xml
#include "VoronoiPy.h"
#include "VoronoiPy.cpp"
#include "VoronoiCellPy.h"
#include "VoronoiEdgePy.h"
#include "VoronoiVertexPy.h"
using namespace Path;
// returns a string which represents the object e.g. when printed in python
std::string VoronoiPy::representation(void) const
{
std::stringstream ss;
ss.precision(5);
ss << "Voronoi("
<< "{" << getVoronoiPtr()->numSegments() << ", " << getVoronoiPtr()->numPoints() << "}"
<< " -> "
<< "{" << getVoronoiPtr()->numCells() << ", " << getVoronoiPtr()->numEdges() << ", " << getVoronoiPtr()->numVertices() << "}"
<< ")";
return ss.str();
}
PyObject *VoronoiPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper
{
// create a new instance of VoronoiPy and its twin object
return new VoronoiPy(new Voronoi);
}
// constructor
int VoronoiPy::PyInit(PyObject* args, PyObject* /*kwds*/)
{
Voronoi *vo = getVoronoiPtr();
double scale = vo->getScale();
if (!PyArg_ParseTuple(args, "|d", &scale)) {
PyErr_SetString(PyExc_RuntimeError, "scale argument (double) accepted, default = 1000");
return -1;
}
vo->setScale(scale);
return 0;
}
Voronoi::point_type getPointFromPy(PyObject *obj) {
if (obj) {
if (PyObject_TypeCheck(obj, &Base::VectorPy::Type)) {
Base::Vector3d *vect = (static_cast<Base::VectorPy*>(obj))->getVectorPtr();
return Voronoi::point_type(vect->x, vect->y);
} else if (PyObject_TypeCheck(obj, Base::Vector2dPy::type_object())) {
Base::Vector2d vect = Py::toVector2d(obj);
return Voronoi::point_type(vect.x, vect.y);
}
}
throw Py::TypeError("Points must be Base::Vector or Base::Vector2d");
return Voronoi::point_type();
}
PyObject* VoronoiPy::addPoint(PyObject *args) {
PyObject *obj = 0;
if (PyArg_ParseTuple(args, "O", &obj)) {
getVoronoiPtr()->addPoint(getPointFromPy(obj));
}
Py_INCREF(Py_None);
return Py_None;
}
PyObject* VoronoiPy::addSegment(PyObject *args) {
PyObject *objBegin = 0;
PyObject *objEnd = 0;
if (PyArg_ParseTuple(args, "OO", &objBegin, &objEnd)) {
auto p0 = getPointFromPy(objBegin);
auto p1 = getPointFromPy(objEnd);
getVoronoiPtr()->addSegment(Voronoi::segment_type(p0, p1));
}
Py_INCREF(Py_None);
return Py_None;
}
PyObject* VoronoiPy::construct(PyObject *args) {
if (!PyArg_ParseTuple(args, "")) {
throw Py::RuntimeError("no arguments accepted");
}
getVoronoiPtr()->construct();
Py_INCREF(Py_None);
return Py_None;
}
PyObject* VoronoiPy::numCells(PyObject *args)
{
if (!PyArg_ParseTuple(args, "")) {
throw Py::RuntimeError("no arguments accepted");
}
return PyLong_FromLong(getVoronoiPtr()->numCells());
}
PyObject* VoronoiPy::numEdges(PyObject *args)
{
if (!PyArg_ParseTuple(args, "")) {
throw Py::RuntimeError("no arguments accepted");
}
return PyLong_FromLong(getVoronoiPtr()->numEdges());
}
PyObject* VoronoiPy::numVertices(PyObject *args)
{
if (!PyArg_ParseTuple(args, "")) {
throw Py::RuntimeError("no arguments accepted");
}
return PyLong_FromLong(getVoronoiPtr()->numVertices());
}
Py::List VoronoiPy::getVertices(void) const {
Py::List list;
for (int i=0; i<getVoronoiPtr()->numVertices(); ++i) {
list.append(Py::asObject(new VoronoiVertexPy(getVoronoiPtr()->create<VoronoiVertex>(i))));
}
return list;
}
Py::List VoronoiPy::getEdges(void) const {
Py::List list;
for (int i=0; i<getVoronoiPtr()->numEdges(); ++i) {
list.append(Py::asObject(new VoronoiEdgePy(getVoronoiPtr()->create<VoronoiEdge>(i))));
}
return list;
}
Py::List VoronoiPy::getCells(void) const {
Py::List list;
for (int i=0; i<getVoronoiPtr()->numCells(); ++i) {
list.append(Py::asObject(new VoronoiCellPy(getVoronoiPtr()->create<VoronoiCell>(i))));
}
return list;
}
static bool callbackWithVertex(Voronoi::diagram_type *dia, PyObject *callback, const Voronoi::diagram_type::vertex_type *v, bool &isExterior) {
if (!isExterior && v->color() == 0) {
PyObject *vx = new VoronoiVertexPy(new VoronoiVertex(dia, v));
PyObject *arglist = Py_BuildValue("(O)", vx);
PyObject *result = PyEval_CallObject(callback, arglist);
Py_DECREF(arglist);
Py_DECREF(vx);
if (result == NULL) {
return false;
}
isExterior = result == Py_True;
Py_DECREF(result);
}
return true;
}
PyObject* VoronoiPy::colorExterior(PyObject *args) {
Voronoi::color_type color = 0;
PyObject *callback = 0;
if (!PyArg_ParseTuple(args, "k|O", &color, &callback)) {
throw Py::RuntimeError("colorExterior requires an integer (color) argument");
}
Voronoi *vo = getVoronoiPtr();
vo->colorExterior(color);
if (callback) {
for (auto e = vo->vd->edges().begin(); e != vo->vd->edges().end(); ++e) {
if (e->is_finite() && e->color() == 0) {
const Voronoi::diagram_type::vertex_type *v0 = e->vertex0();
const Voronoi::diagram_type::vertex_type *v1 = e->vertex1();
bool is0 = false;
bool is1 = false;
if (!callbackWithVertex(vo->vd, callback, v0, is0) || !callbackWithVertex(vo->vd, callback, v1, is1)) {
return NULL;
}
if (is0 && is1) {
vo->colorExterior(&(*e), color);
}
}
}
}
Py_INCREF(Py_None);
return Py_None;
}
PyObject* VoronoiPy::colorTwins(PyObject *args) {
Voronoi::color_type color = 0;
if (!PyArg_ParseTuple(args, "k", &color)) {
throw Py::RuntimeError("colorTwins requires an integer (color) argument");
}
getVoronoiPtr()->colorTwins(color);
Py_INCREF(Py_None);
return Py_None;
}
PyObject* VoronoiPy::colorColinear(PyObject *args) {
Voronoi::color_type color = 0;
double degree = 10.;
if (!PyArg_ParseTuple(args, "k|d", &color, °ree)) {
throw Py::RuntimeError("colorColinear requires an integer (color) and optionally a derivation in degrees argument (default 10)");
}
getVoronoiPtr()->colorColinear(color, degree);
Py_INCREF(Py_None);
return Py_None;
}
PyObject* VoronoiPy::resetColor(PyObject *args) {
Voronoi::color_type color = 0;
if (!PyArg_ParseTuple(args, "k", &color)) {
throw Py::RuntimeError("clearColor requires an integer (color) argument");
}
getVoronoiPtr()->resetColor(color);
Py_INCREF(Py_None);
return Py_None;
}
// custom attributes get/set
PyObject *VoronoiPy::getCustomAttributes(const char* /*attr*/) const
{
return 0;
}
int VoronoiPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/)
{
return 0;
}
<commit_msg>Simplified and further optimised colinear colorisation<commit_after>/***************************************************************************
* Copyright (c) sliptonic ([email protected]) 2020 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <boost/algorithm/string.hpp>
#endif
#include "Mod/Path/App/Voronoi.h"
#include "Mod/Path/App/VoronoiCell.h"
#include "Mod/Path/App/VoronoiEdge.h"
#include "Mod/Path/App/VoronoiVertex.h"
#include <Base/Exception.h>
#include <Base/GeometryPyCXX.h>
#include <Base/Vector3D.h>
#include <Base/VectorPy.h>
// files generated out of VoronoiPy.xml
#include "VoronoiPy.h"
#include "VoronoiPy.cpp"
#include "VoronoiCellPy.h"
#include "VoronoiEdgePy.h"
#include "VoronoiVertexPy.h"
using namespace Path;
// returns a string which represents the object e.g. when printed in python
std::string VoronoiPy::representation(void) const
{
std::stringstream ss;
ss.precision(5);
ss << "Voronoi("
<< "{" << getVoronoiPtr()->numSegments() << ", " << getVoronoiPtr()->numPoints() << "}"
<< " -> "
<< "{" << getVoronoiPtr()->numCells() << ", " << getVoronoiPtr()->numEdges() << ", " << getVoronoiPtr()->numVertices() << "}"
<< ")";
return ss.str();
}
PyObject *VoronoiPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper
{
// create a new instance of VoronoiPy and its twin object
return new VoronoiPy(new Voronoi);
}
// constructor
int VoronoiPy::PyInit(PyObject* args, PyObject* /*kwds*/)
{
Voronoi *vo = getVoronoiPtr();
double scale = vo->getScale();
if (!PyArg_ParseTuple(args, "|d", &scale)) {
PyErr_SetString(PyExc_RuntimeError, "scale argument (double) accepted, default = 1000");
return -1;
}
vo->setScale(scale);
return 0;
}
Voronoi::point_type getPointFromPy(PyObject *obj) {
if (obj) {
if (PyObject_TypeCheck(obj, &Base::VectorPy::Type)) {
Base::Vector3d *vect = (static_cast<Base::VectorPy*>(obj))->getVectorPtr();
return Voronoi::point_type(vect->x, vect->y);
} else if (PyObject_TypeCheck(obj, Base::Vector2dPy::type_object())) {
Base::Vector2d vect = Py::toVector2d(obj);
return Voronoi::point_type(vect.x, vect.y);
}
}
throw Py::TypeError("Points must be Base::Vector or Base::Vector2d");
return Voronoi::point_type();
}
PyObject* VoronoiPy::addPoint(PyObject *args) {
PyObject *obj = 0;
if (PyArg_ParseTuple(args, "O", &obj)) {
getVoronoiPtr()->addPoint(getPointFromPy(obj));
}
Py_INCREF(Py_None);
return Py_None;
}
PyObject* VoronoiPy::addSegment(PyObject *args) {
PyObject *objBegin = 0;
PyObject *objEnd = 0;
if (PyArg_ParseTuple(args, "OO", &objBegin, &objEnd)) {
auto p0 = getPointFromPy(objBegin);
auto p1 = getPointFromPy(objEnd);
getVoronoiPtr()->addSegment(Voronoi::segment_type(p0, p1));
}
Py_INCREF(Py_None);
return Py_None;
}
PyObject* VoronoiPy::construct(PyObject *args) {
if (!PyArg_ParseTuple(args, "")) {
throw Py::RuntimeError("no arguments accepted");
}
getVoronoiPtr()->construct();
Py_INCREF(Py_None);
return Py_None;
}
PyObject* VoronoiPy::numCells(PyObject *args)
{
if (!PyArg_ParseTuple(args, "")) {
throw Py::RuntimeError("no arguments accepted");
}
return PyLong_FromLong(getVoronoiPtr()->numCells());
}
PyObject* VoronoiPy::numEdges(PyObject *args)
{
if (!PyArg_ParseTuple(args, "")) {
throw Py::RuntimeError("no arguments accepted");
}
return PyLong_FromLong(getVoronoiPtr()->numEdges());
}
PyObject* VoronoiPy::numVertices(PyObject *args)
{
if (!PyArg_ParseTuple(args, "")) {
throw Py::RuntimeError("no arguments accepted");
}
return PyLong_FromLong(getVoronoiPtr()->numVertices());
}
Py::List VoronoiPy::getVertices(void) const {
Py::List list;
for (int i=0; i<getVoronoiPtr()->numVertices(); ++i) {
list.append(Py::asObject(new VoronoiVertexPy(getVoronoiPtr()->create<VoronoiVertex>(i))));
}
return list;
}
Py::List VoronoiPy::getEdges(void) const {
Py::List list;
for (int i=0; i<getVoronoiPtr()->numEdges(); ++i) {
list.append(Py::asObject(new VoronoiEdgePy(getVoronoiPtr()->create<VoronoiEdge>(i))));
}
return list;
}
Py::List VoronoiPy::getCells(void) const {
Py::List list;
for (int i=0; i<getVoronoiPtr()->numCells(); ++i) {
list.append(Py::asObject(new VoronoiCellPy(getVoronoiPtr()->create<VoronoiCell>(i))));
}
return list;
}
static bool callbackWithVertex(Voronoi::diagram_type *dia, PyObject *callback, const Voronoi::diagram_type::vertex_type *v, bool &bail) {
bool rc = false;
if (!bail && v->color() == 0) {
PyObject *vx = new VoronoiVertexPy(new VoronoiVertex(dia, v));
PyObject *arglist = Py_BuildValue("(O)", vx);
PyObject *result = PyEval_CallObject(callback, arglist);
Py_DECREF(arglist);
Py_DECREF(vx);
if (result == NULL) {
bail = true;
} else {
rc = result == Py_True;
Py_DECREF(result);
}
}
return rc;
}
PyObject* VoronoiPy::colorExterior(PyObject *args) {
Voronoi::color_type color = 0;
PyObject *callback = 0;
if (!PyArg_ParseTuple(args, "k|O", &color, &callback)) {
throw Py::RuntimeError("colorExterior requires an integer (color) argument");
}
Voronoi *vo = getVoronoiPtr();
vo->colorExterior(color);
if (callback) {
for (auto e = vo->vd->edges().begin(); e != vo->vd->edges().end(); ++e) {
if (e->is_finite() && e->color() == 0) {
const Voronoi::diagram_type::vertex_type *v0 = e->vertex0();
const Voronoi::diagram_type::vertex_type *v1 = e->vertex1();
bool bail = false;
if (callbackWithVertex(vo->vd, callback, v0, bail) && callbackWithVertex(vo->vd, callback, v1, bail)) {
vo->colorExterior(&(*e), color);
}
if (bail) {
return NULL;
}
}
}
}
Py_INCREF(Py_None);
return Py_None;
}
PyObject* VoronoiPy::colorTwins(PyObject *args) {
Voronoi::color_type color = 0;
if (!PyArg_ParseTuple(args, "k", &color)) {
throw Py::RuntimeError("colorTwins requires an integer (color) argument");
}
getVoronoiPtr()->colorTwins(color);
Py_INCREF(Py_None);
return Py_None;
}
PyObject* VoronoiPy::colorColinear(PyObject *args) {
Voronoi::color_type color = 0;
double degree = 10.;
if (!PyArg_ParseTuple(args, "k|d", &color, °ree)) {
throw Py::RuntimeError("colorColinear requires an integer (color) and optionally a derivation in degrees argument (default 10)");
}
getVoronoiPtr()->colorColinear(color, degree);
Py_INCREF(Py_None);
return Py_None;
}
PyObject* VoronoiPy::resetColor(PyObject *args) {
Voronoi::color_type color = 0;
if (!PyArg_ParseTuple(args, "k", &color)) {
throw Py::RuntimeError("clearColor requires an integer (color) argument");
}
getVoronoiPtr()->resetColor(color);
Py_INCREF(Py_None);
return Py_None;
}
// custom attributes get/set
PyObject *VoronoiPy::getCustomAttributes(const char* /*attr*/) const
{
return 0;
}
int VoronoiPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/)
{
return 0;
}
<|endoftext|> |
<commit_before>// The MIT License (MIT)
// Copyright (c) 2016, Microsoft
// 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.
#include "gtest/gtest.h"
#include "Allocator.h"
#include "BitFunnel/Utilities/TextObjectFormatter.h"
#include "CompileNode.h"
#include "PlainTextCodeGenerator.h"
#include "TextObjectParser.h"
namespace BitFunnel
{
namespace CompileNodeUnitTest
{
// TODO: Tests of illegal trees, e.g. and/or/phrases with 0, 1 child
const char* c_parseFormatCases[] = {
//
// AndRowJz
//
// AndRowJz does not allow a null child.
// AndRowJz followed by Report.
"AndRowJz {\n"
" Row: Row(1, 2, 0, false),\n"
" Child: Report {\n"
" Child: \n"
" }\n"
"}",
//
// LoadRowJz
//
// LoadRowJz with no child.
"LoadRowJz {\n"
" Row: Row(1, 2, 0, false),\n"
" Child: Report {\n"
" Child: \n"
" }\n"
"}",
// LoadRowJz with Report child.
"LoadRowJz {\n"
" Row: Row(1, 2, 0, false),\n"
" Child: Report {\n"
" Child: \n"
" }\n"
"}",
//
// Or
//
// Or with 0 children no longer legal.
// Or with 1 child no longer legal.
// Or with two children.
"Or {\n"
" Children: [\n"
" Report {\n"
" Child: \n"
" },\n"
" Report {\n"
" Child: \n"
" }\n"
" ]\n"
"}",
// Or with three children.
"Or {\n"
" Children: [\n"
" Report {\n"
" Child: \n"
" },\n"
" Report {\n"
" Child: \n"
" },\n"
" Report {\n"
" Child: \n"
" }\n"
" ]\n"
"}",
//
// RankDown
//
// RankDown with Report child.
"RankDown {\n"
" Delta: 3,\n"
" Child: Report {\n"
" Child: \n"
" }\n"
"}",
//
// Report
//
// Report with no child.
"Report {\n"
" Child: \n"
"}",
// Report with LoadRowJz child.
"Report {\n"
" Child: LoadRowJz {\n"
" Row: Row(1, 2, 0, false),\n"
" Child: Report {\n"
" Child: \n"
" }\n"
" }\n"
"}",
//
// AndTree
//
"AndTree {\n"
" Children: [\n"
" LoadRow(0, 6, 0, false),\n"
" LoadRow(1, 0, 0, false)\n"
" ]\n"
"}",
"AndTree {\n"
" Children: [\n"
" LoadRow(0, 6, 0, false),\n"
" LoadRow(1, 3, 0, false),\n"
" LoadRow(2, 0, 0, false)\n"
" ]\n"
"}",
//
// LoadRow
//
"LoadRow(0, 6, 0, false)",
"LoadRow(1, 5, 0, true)",
//
// Not
//
"Not {\n"
" Child: LoadRow(0, 6, 0, false)\n"
"}",
//
// OrTree
//
"OrTree {\n"
" Children: [\n"
" LoadRow(0, 6, 0, false),\n"
" LoadRow(1, 0, 0, false)\n"
" ]\n"
"}",
"OrTree {\n"
" Children: [\n"
" LoadRow(0, 6, 0, false),\n"
" LoadRow(1, 3, 0, false),\n"
" LoadRow(2, 0, 0, false)\n"
" ]\n"
"}",
};
struct InputOutput
{
public:
char const * m_input;
char const * m_output;
};
const InputOutput c_codeGenerationCases[] =
{
// AndRowJz
{
"AndRowJz {\n"
" Row: Row(1, 2, 0, false),\n"
" Child: Report {\n"
" Child: \n"
" }\n"
"}",
" AndRow(1, false, 0)\n"
" Jz(0)\n"
" Report()\n"
"L0:\n"
},
// LoadRowJz
{
"LoadRowJz {\n"
" Row: Row(1, 2, 0, false),\n"
" Child: Report {\n"
" Child: \n"
" }\n"
"}",
" LoadRow(1, false, 0)\n"
" Jz(0)\n"
" Report()\n"
"L0:\n"
},
// Or
{
"Or {\n"
" Children: [\n"
" LoadRowJz {\n"
" Row: Row(0, 6, 0, false),\n"
" Child: Report {\n"
" Child: \n"
" }\n"
" },"
" LoadRowJz {\n"
" Row: Row(1, 6, 0, false),\n"
" Child: Report {\n"
" Child: \n"
" }\n"
" }"
" ]"
"}",
" Push()\n"
" LoadRow(0, false, 0)\n"
" Jz(0)\n"
" Report()\n"
"L0:\n"
" Pop()\n"
" LoadRow(1, false, 0)\n"
" Jz(1)\n"
" Report()\n"
"L1:\n"
},
// RankDown
{
"RankDown {"
" Delta: 1,"
" Child: LoadRow(1, 2, 0, false)"
"}",
" LeftShiftOffset(1)\n"
" Push()\n"
" Call(0)\n"
" Pop()\n"
" IncrementOffset()\n"
" Call(0)\n"
" Jmp(1)\n"
"L0:\n"
" LoadRow(1, false, 0)\n"
" Return()\n"
"L1:\n"
" RightShiftOffset(1)\n"
},
// Report with no child.
// RankDown algorithm does Jz around Report().
{
"Report {"
" Child:"
"}",
" Report()\n"
},
// Report with one child.
// Includes Jz around Report().
// TODO: What happens if this is the entire tree? Don't we need to
// -1 into the accumulator first?
{
"Report {"
" Child: LoadRow(1, 2, 0, false)\n"
"}",
" Push()\n"
" LoadRow(1, false, 0)\n"
" AndStack()\n"
" Jz(0)\n"
" Report()\n"
"L0:\n"
},
{
"AndTree {\n"
" Children: [\n"
" LoadRow(0, 6, 0, false),\n"
" LoadRow(1, 0, 0, false)\n"
" ]\n"
"}",
" LoadRow(0, false, 0)\n"
" UpdateFlags()\n"
" Jz(0)\n"
" Push()\n"
" LoadRow(1, false, 0)\n"
" AndStack()\n"
"L0:\n"
},
{
"Not {\n"
" Child: LoadRow(0, 6, 0, false)\n"
"}",
" LoadRow(0, false, 0)\n"
" Not()\n"
},
{
"OrTree {\n"
" Children: [\n"
" LoadRow(0, 6, 0, false),\n"
" LoadRow(1, 0, 0, false)\n"
" ]\n"
"}",
" LoadRow(0, false, 0)\n"
" Push()\n"
" LoadRow(1, false, 0)\n"
" OrStack()\n"
}
};
//*********************************************************************
//
// Parse/Format cases.
//
//*********************************************************************
void VerifyRoundtripCase(const char* text)
{
std::stringstream input(text);
Allocator allocator(1024);
TextObjectParser parser(input, allocator, &CompileNode::GetType);
CompileNode const & node = CompileNode::Parse(parser);
std::stringstream output;
TextObjectFormatter formatter(output);
node.Format(formatter);
// std::cout << "\"" << text << "\"" << std::endl;
// std::cout << "\"" << output.str() << "\"" << std::endl;
EXPECT_EQ(text, output.str());
}
TEST(CompileNode, ParseFormat)
{
for (unsigned i = 0; i < sizeof(c_parseFormatCases) / sizeof(const char*); ++i)
{
VerifyRoundtripCase(c_parseFormatCases[i]);
}
}
//*********************************************************************
//
// Code generation cases.
//
//*********************************************************************
void VerifyCodeGenerationCase(InputOutput const & testCase)
{
std::stringstream input(testCase.m_input);
Allocator allocator(1024);
TextObjectParser parser(input, allocator, &CompileNode::GetType);
CompileNode const & node = CompileNode::Parse(parser);
std::stringstream output;
PlainTextCodeGenerator code(output);
node.Compile(code);
//std::cout << "+++++++++++++++++++" << std::endl;
//std::cout << "\"" << testCase.m_output << "\"" << std::endl;
//std::cout << "+++" << std::endl;
//std::cout << "\"" << output.str() << "\"" << std::endl;
EXPECT_EQ(testCase.m_output, output.str());
}
TEST(CompileNode, CodeGeneration)
{
for (unsigned i = 0; i < sizeof(c_codeGenerationCases) / sizeof(InputOutput); ++i)
{
VerifyCodeGenerationCase(c_codeGenerationCases[i]);
}
}
}
}
<commit_msg>Shrink allocators in test.<commit_after>// The MIT License (MIT)
// Copyright (c) 2016, Microsoft
// 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.
#include "gtest/gtest.h"
#include "Allocator.h"
#include "BitFunnel/Utilities/TextObjectFormatter.h"
#include "CompileNode.h"
#include "PlainTextCodeGenerator.h"
#include "TextObjectParser.h"
namespace BitFunnel
{
namespace CompileNodeUnitTest
{
// TODO: Tests of illegal trees, e.g. and/or/phrases with 0, 1 child
const char* c_parseFormatCases[] = {
//
// AndRowJz
//
// AndRowJz does not allow a null child.
// AndRowJz followed by Report.
"AndRowJz {\n"
" Row: Row(1, 2, 0, false),\n"
" Child: Report {\n"
" Child: \n"
" }\n"
"}",
//
// LoadRowJz
//
// LoadRowJz with no child.
"LoadRowJz {\n"
" Row: Row(1, 2, 0, false),\n"
" Child: Report {\n"
" Child: \n"
" }\n"
"}",
// LoadRowJz with Report child.
"LoadRowJz {\n"
" Row: Row(1, 2, 0, false),\n"
" Child: Report {\n"
" Child: \n"
" }\n"
"}",
//
// Or
//
// Or with 0 children no longer legal.
// Or with 1 child no longer legal.
// Or with two children.
"Or {\n"
" Children: [\n"
" Report {\n"
" Child: \n"
" },\n"
" Report {\n"
" Child: \n"
" }\n"
" ]\n"
"}",
// Or with three children.
"Or {\n"
" Children: [\n"
" Report {\n"
" Child: \n"
" },\n"
" Report {\n"
" Child: \n"
" },\n"
" Report {\n"
" Child: \n"
" }\n"
" ]\n"
"}",
//
// RankDown
//
// RankDown with Report child.
"RankDown {\n"
" Delta: 3,\n"
" Child: Report {\n"
" Child: \n"
" }\n"
"}",
//
// Report
//
// Report with no child.
"Report {\n"
" Child: \n"
"}",
// Report with LoadRowJz child.
"Report {\n"
" Child: LoadRowJz {\n"
" Row: Row(1, 2, 0, false),\n"
" Child: Report {\n"
" Child: \n"
" }\n"
" }\n"
"}",
//
// AndTree
//
"AndTree {\n"
" Children: [\n"
" LoadRow(0, 6, 0, false),\n"
" LoadRow(1, 0, 0, false)\n"
" ]\n"
"}",
"AndTree {\n"
" Children: [\n"
" LoadRow(0, 6, 0, false),\n"
" LoadRow(1, 3, 0, false),\n"
" LoadRow(2, 0, 0, false)\n"
" ]\n"
"}",
//
// LoadRow
//
"LoadRow(0, 6, 0, false)",
"LoadRow(1, 5, 0, true)",
//
// Not
//
"Not {\n"
" Child: LoadRow(0, 6, 0, false)\n"
"}",
//
// OrTree
//
"OrTree {\n"
" Children: [\n"
" LoadRow(0, 6, 0, false),\n"
" LoadRow(1, 0, 0, false)\n"
" ]\n"
"}",
"OrTree {\n"
" Children: [\n"
" LoadRow(0, 6, 0, false),\n"
" LoadRow(1, 3, 0, false),\n"
" LoadRow(2, 0, 0, false)\n"
" ]\n"
"}",
};
struct InputOutput
{
public:
char const * m_input;
char const * m_output;
};
const InputOutput c_codeGenerationCases[] =
{
// AndRowJz
{
"AndRowJz {\n"
" Row: Row(1, 2, 0, false),\n"
" Child: Report {\n"
" Child: \n"
" }\n"
"}",
" AndRow(1, false, 0)\n"
" Jz(0)\n"
" Report()\n"
"L0:\n"
},
// LoadRowJz
{
"LoadRowJz {\n"
" Row: Row(1, 2, 0, false),\n"
" Child: Report {\n"
" Child: \n"
" }\n"
"}",
" LoadRow(1, false, 0)\n"
" Jz(0)\n"
" Report()\n"
"L0:\n"
},
// Or
{
"Or {\n"
" Children: [\n"
" LoadRowJz {\n"
" Row: Row(0, 6, 0, false),\n"
" Child: Report {\n"
" Child: \n"
" }\n"
" },"
" LoadRowJz {\n"
" Row: Row(1, 6, 0, false),\n"
" Child: Report {\n"
" Child: \n"
" }\n"
" }"
" ]"
"}",
" Push()\n"
" LoadRow(0, false, 0)\n"
" Jz(0)\n"
" Report()\n"
"L0:\n"
" Pop()\n"
" LoadRow(1, false, 0)\n"
" Jz(1)\n"
" Report()\n"
"L1:\n"
},
// RankDown
{
"RankDown {"
" Delta: 1,"
" Child: LoadRow(1, 2, 0, false)"
"}",
" LeftShiftOffset(1)\n"
" Push()\n"
" Call(0)\n"
" Pop()\n"
" IncrementOffset()\n"
" Call(0)\n"
" Jmp(1)\n"
"L0:\n"
" LoadRow(1, false, 0)\n"
" Return()\n"
"L1:\n"
" RightShiftOffset(1)\n"
},
// Report with no child.
// RankDown algorithm does Jz around Report().
{
"Report {"
" Child:"
"}",
" Report()\n"
},
// Report with one child.
// Includes Jz around Report().
// TODO: What happens if this is the entire tree? Don't we need to
// -1 into the accumulator first?
{
"Report {"
" Child: LoadRow(1, 2, 0, false)\n"
"}",
" Push()\n"
" LoadRow(1, false, 0)\n"
" AndStack()\n"
" Jz(0)\n"
" Report()\n"
"L0:\n"
},
{
"AndTree {\n"
" Children: [\n"
" LoadRow(0, 6, 0, false),\n"
" LoadRow(1, 0, 0, false)\n"
" ]\n"
"}",
" LoadRow(0, false, 0)\n"
" UpdateFlags()\n"
" Jz(0)\n"
" Push()\n"
" LoadRow(1, false, 0)\n"
" AndStack()\n"
"L0:\n"
},
{
"Not {\n"
" Child: LoadRow(0, 6, 0, false)\n"
"}",
" LoadRow(0, false, 0)\n"
" Not()\n"
},
{
"OrTree {\n"
" Children: [\n"
" LoadRow(0, 6, 0, false),\n"
" LoadRow(1, 0, 0, false)\n"
" ]\n"
"}",
" LoadRow(0, false, 0)\n"
" Push()\n"
" LoadRow(1, false, 0)\n"
" OrStack()\n"
}
};
//*********************************************************************
//
// Parse/Format cases.
//
//*********************************************************************
void VerifyRoundtripCase(const char* text)
{
std::stringstream input(text);
Allocator allocator(256);
TextObjectParser parser(input, allocator, &CompileNode::GetType);
CompileNode const & node = CompileNode::Parse(parser);
std::stringstream output;
TextObjectFormatter formatter(output);
node.Format(formatter);
// std::cout << "\"" << text << "\"" << std::endl;
// std::cout << "\"" << output.str() << "\"" << std::endl;
EXPECT_EQ(text, output.str());
}
TEST(CompileNode, ParseFormat)
{
for (unsigned i = 0; i < sizeof(c_parseFormatCases) / sizeof(const char*); ++i)
{
VerifyRoundtripCase(c_parseFormatCases[i]);
}
}
//*********************************************************************
//
// Code generation cases.
//
//*********************************************************************
void VerifyCodeGenerationCase(InputOutput const & testCase)
{
std::stringstream input(testCase.m_input);
Allocator allocator(256);
TextObjectParser parser(input, allocator, &CompileNode::GetType);
CompileNode const & node = CompileNode::Parse(parser);
std::stringstream output;
PlainTextCodeGenerator code(output);
node.Compile(code);
//std::cout << "+++++++++++++++++++" << std::endl;
//std::cout << "\"" << testCase.m_output << "\"" << std::endl;
//std::cout << "+++" << std::endl;
//std::cout << "\"" << output.str() << "\"" << std::endl;
EXPECT_EQ(testCase.m_output, output.str());
}
TEST(CompileNode, CodeGeneration)
{
for (unsigned i = 0; i < sizeof(c_codeGenerationCases) / sizeof(InputOutput); ++i)
{
VerifyCodeGenerationCase(c_codeGenerationCases[i]);
}
}
}
}
<|endoftext|> |
<commit_before>//
// Projectname: amos-ss16-proj5
//
// Copyright (c) 2016 de.fau.cs.osr.amos2016.gruppe5
//
// This file is part of the AMOS Project 2016 @ FAU
// (Friedrich-Alexander University Erlangen-Nürnberg)
//
// 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 Affero General Public
// License along with this program. If not, see
// <http://www.gnu.org/licenses/>.
//
//opencv
#include <opencv2/opencv.hpp>
//local
#include "../ObjectDetection/cascade_haar_detector.h"
#include "../ObjectDetection/daimler_people_detector.h"
#include "../ObjectDetection/detection.h"
//#include "../ObjectDetection/hog_people_detector.h"
#include "../StreamDecoder/image_view.h"
#include "../ScenarioAnalysation/scenario.h"
#include "../ScenarioAnalysation/humans_in_front_of_bus_scenario.h"
#include "../ScenarioAnalysation/analyser.h"
#include "controller.h"
#include "../CarCommunication/protoagent.h"
//define keys
const int KEY_ESC = 27;
const int KEY_SPACE = 32;
void Controller::PlayAsVideo(std::string videofile) {
FrameSelectorFactory frame_selector_factory(videofile);
FrameSelector* pipeline = frame_selector_factory.GetFrameSelector();
ImageView image_view;
int protobuf_counts = pipeline->GetImageCount();
for (int i=0; i<protobuf_counts; i++) {
Image * current_image = pipeline->ReadImage(i);
image_view.ShowImage(current_image);
delete current_image;
current_image = NULL;
if( cvWaitKey(5) == KEY_ESC ) break;
}
}
void Controller::AnalyseVideo(std::string videofile, uint16_t port, std::string host) {
ImageView image_view;
FrameSelectorFactory frame_selector_factory(videofile);
FrameSelector* pipeline = frame_selector_factory.GetFrameSelector();
int protobuf_counts = pipeline->GetImageCount();
DaimlerPeopleDetector people_detector;
//HOGPeopleDetector people_detector;
CascadeHaarDetector vehicle_detector("cars3.xml");
Detection detection(&people_detector, &vehicle_detector);
// set up all objects needed for analysing
std::vector<Scenario*> possible_scenarios;
possible_scenarios.push_back(new HumansInFrontOfBusScenario());
Analyser analyser(possible_scenarios);
for (int i=0; i<protobuf_counts; i++) {
Image * current_image = pipeline->ReadImage(i);
FrameDetectionData* current_detections = detection.ProcessFrame(current_image);
if(!current_detections){
continue;
}
Scenario* scenario = analyser.Analyse(*current_detections);
if(!scenario){
std::cout << "No scenario in frame " << i << " was detected!" <<std::endl;
}else{
if( HumansInFrontOfBusScenario* result = dynamic_cast<HumansInFrontOfBusScenario*>(scenario) ){
// TODO here for later: inform the communication module that a "Humans in front of bus" scenario was detected
}
// for demo: show information about scenario in current frame
std::cout << "Current detected scenario: " << scenario->GetScenarioInformation() << " in frame: " << i << std::endl;
#ifdef COMBINE
//Notifying other car
if(port!=0)
{
std::cout << "Informing other car" << std::endl;
ProtoAgent::startClient(port,host);
}
#endif
}
int key = cvWaitKey(10);
if(key == KEY_ESC)
break;
if (key == KEY_SPACE)
key = cvWaitKey(0);
delete current_image;
current_image = NULL;
delete current_detections;
current_detections = NULL;
//delete scenario;
scenario = NULL;
}
}
void Controller::SaveAllImagesAsJPEG(std::string videofile) {
FrameSelectorFactory frame_selector_factory(videofile);
FrameSelector* pipeline = frame_selector_factory.GetFrameSelector();
int protobuf_counts = pipeline->GetImageCount();
std::string filename = videofile.substr(videofile.find_last_of("/\\")+1);
std::ostringstream os;
for (int i=0; i<protobuf_counts; i++){
os << i;
cv::imwrite(filename+"_"+os.str()+".jpeg", pipeline->ReadImage(i)->GetRGBImage());
}
}
<commit_msg>the DetectInRoi() function is now used vor the people detection<commit_after>//
// Projectname: amos-ss16-proj5
//
// Copyright (c) 2016 de.fau.cs.osr.amos2016.gruppe5
//
// This file is part of the AMOS Project 2016 @ FAU
// (Friedrich-Alexander University Erlangen-Nürnberg)
//
// 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 Affero General Public
// License along with this program. If not, see
// <http://www.gnu.org/licenses/>.
//
//opencv
#include <opencv2/opencv.hpp>
//local
#include "../ObjectDetection/cascade_haar_detector.h"
#include "../ObjectDetection/daimler_people_detector.h"
#include "../ObjectDetection/detection.h"
// #include "../ObjectDetection/hog_people_detector.h"
#include "../StreamDecoder/image_view.h"
#include "../ScenarioAnalysation/scenario.h"
#include "../ScenarioAnalysation/humans_in_front_of_bus_scenario.h"
#include "../ScenarioAnalysation/analyser.h"
#include "controller.h"
#include "../CarCommunication/protoagent.h"
//define keys
const int KEY_ESC = 27;
const int KEY_SPACE = 32;
void Controller::PlayAsVideo(std::string videofile) {
FrameSelectorFactory frame_selector_factory(videofile);
FrameSelector* pipeline = frame_selector_factory.GetFrameSelector();
ImageView image_view;
int protobuf_counts = pipeline->GetImageCount();
for (int i=0; i<protobuf_counts; i++) {
Image * current_image = pipeline->ReadImage(i);
image_view.ShowImage(current_image);
delete current_image;
current_image = NULL;
if( cvWaitKey(5) == KEY_ESC ) break;
}
}
void Controller::AnalyseVideo(std::string videofile, uint16_t port, std::string host) {
ImageView image_view;
FrameSelectorFactory frame_selector_factory(videofile);
FrameSelector* pipeline = frame_selector_factory.GetFrameSelector();
int protobuf_counts = pipeline->GetImageCount();
DaimlerPeopleDetector people_detector;
// HOGPeopleDetector people_detector;
CascadeHaarDetector vehicle_detector("cars3.xml");
// CascadeHaarDetector people_detector("haarcascade_fullbody.xml", 1.5, 1, cv::Size(14,28), cv::Size(56,112));
Detection detection(&people_detector, &vehicle_detector);
// set up all objects needed for analysing
std::vector<Scenario*> possible_scenarios;
possible_scenarios.push_back(new HumansInFrontOfBusScenario());
Analyser analyser(possible_scenarios);
for (int i=0; i<protobuf_counts; i++) {
Image * current_image = pipeline->ReadImage(i);
FrameDetectionData* current_detections = detection.ProcessFrame(current_image);
if(!current_detections){
continue;
}
Scenario* scenario = analyser.Analyse(*current_detections);
if(!scenario){
std::cout << "No scenario in frame " << i << " was detected!" <<std::endl;
}else{
if( HumansInFrontOfBusScenario* result = dynamic_cast<HumansInFrontOfBusScenario*>(scenario) ){
// TODO here for later: inform the communication module that a "Humans in front of bus" scenario was detected
}
// for demo: show information about scenario in current frame
std::cout << "Current detected scenario: " << scenario->GetScenarioInformation() << " in frame: " << i << std::endl;
#ifdef COMBINE
//Notifying other car
if(port!=0)
{
std::cout << "Informing other car" << std::endl;
ProtoAgent::startClient(port,host);
}
#endif
}
int key = cvWaitKey(10);
if(key == KEY_ESC)
break;
if (key == KEY_SPACE)
key = cvWaitKey(0);
delete current_image;
current_image = NULL;
delete current_detections;
current_detections = NULL;
//delete scenario;
scenario = NULL;
}
}
void Controller::SaveAllImagesAsJPEG(std::string videofile) {
FrameSelectorFactory frame_selector_factory(videofile);
FrameSelector* pipeline = frame_selector_factory.GetFrameSelector();
int protobuf_counts = pipeline->GetImageCount();
std::string filename = videofile.substr(videofile.find_last_of("/\\")+1);
std::ostringstream os;
for (int i=0; i<protobuf_counts; i++){
os << i;
cv::imwrite(filename+"_"+os.str()+".jpeg", pipeline->ReadImage(i)->GetRGBImage());
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/utf_string_conversions.h"
#include "chrome/browser/automation/automation_util.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/web_contents.h"
#include "net/base/mock_host_resolver.h"
using content::NavigationController;
using content::WebContents;
namespace {
class ProcessManagementTest : public ExtensionBrowserTest {
private:
// This is needed for testing isolated apps, which are still experimental.
virtual void SetUpCommandLine(CommandLine* command_line) {
ExtensionBrowserTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
}
};
} // namespace
// Ensure that an isolated app never shares a process with WebUIs, non-isolated
// extensions, and normal webpages. None of these should ever comingle
// RenderProcessHosts even if we hit the process limit.
IN_PROC_BROWSER_TEST_F(ProcessManagementTest, ProcessOverflow) {
// Set max renderers to 1 to force running out of processes.
content::RenderProcessHost::SetMaxRendererProcessCount(1);
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("isolated_apps/app1")));
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("isolated_apps/app2")));
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("hosted_app")));
ASSERT_TRUE(
LoadExtension(test_data_dir_.AppendASCII("api_test/app_process")));
// The app under test acts on URLs whose host is "localhost",
// so the URLs we navigate to must have host "localhost".
GURL base_url = test_server()->GetURL(
"files/extensions/");
GURL::Replacements replace_host;
std::string host_str("localhost"); // Must stay in scope with replace_host.
replace_host.SetHostStr(host_str);
base_url = base_url.ReplaceComponents(replace_host);
// Load an extension before adding tabs.
const Extension* extension1 = LoadExtension(
test_data_dir_.AppendASCII("api_test/browser_action/basics"));
ASSERT_TRUE(extension1);
GURL extension1_url = extension1->url();
// Create multiple tabs for each type of renderer that might exist.
ui_test_utils::NavigateToURLWithDisposition(
browser(), base_url.Resolve("isolated_apps/app1/main.html"),
CURRENT_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
ui_test_utils::NavigateToURLWithDisposition(
browser(), GURL(chrome::kChromeUINewTabURL),
NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
ui_test_utils::NavigateToURLWithDisposition(
browser(), base_url.Resolve("hosted_app/main.html"),
NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
ui_test_utils::NavigateToURLWithDisposition(
browser(), base_url.Resolve("test_file.html"),
NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
ui_test_utils::NavigateToURLWithDisposition(
browser(), base_url.Resolve("isolated_apps/app2/main.html"),
NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
ui_test_utils::NavigateToURLWithDisposition(
browser(), GURL(chrome::kChromeUINewTabURL),
NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
ui_test_utils::NavigateToURLWithDisposition(
browser(), base_url.Resolve("api_test/app_process/path1/empty.html"),
NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
ui_test_utils::NavigateToURLWithDisposition(
browser(), base_url.Resolve("test_file_with_body.html"),
NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
// Load another copy of isolated app 1.
ui_test_utils::NavigateToURLWithDisposition(
browser(), base_url.Resolve("isolated_apps/app1/main.html"),
NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
// Load another extension.
const Extension* extension2 = LoadExtension(
test_data_dir_.AppendASCII("api_test/browser_action/close_background"));
ASSERT_TRUE(extension2);
GURL extension2_url = extension2->url();
// Get tab processes.
ASSERT_EQ(9, browser()->tab_count());
content::RenderProcessHost* isolated1_host =
browser()->GetWebContentsAt(0)->GetRenderProcessHost();
content::RenderProcessHost* ntp1_host =
browser()->GetWebContentsAt(1)->GetRenderProcessHost();
content::RenderProcessHost* hosted1_host =
browser()->GetWebContentsAt(2)->GetRenderProcessHost();
content::RenderProcessHost* web1_host =
browser()->GetWebContentsAt(3)->GetRenderProcessHost();
content::RenderProcessHost* isolated2_host =
browser()->GetWebContentsAt(4)->GetRenderProcessHost();
content::RenderProcessHost* ntp2_host =
browser()->GetWebContentsAt(5)->GetRenderProcessHost();
content::RenderProcessHost* hosted2_host =
browser()->GetWebContentsAt(6)->GetRenderProcessHost();
content::RenderProcessHost* web2_host =
browser()->GetWebContentsAt(7)->GetRenderProcessHost();
content::RenderProcessHost* second_isolated1_host =
browser()->GetWebContentsAt(8)->GetRenderProcessHost();
// Get extension processes.
ExtensionProcessManager* process_manager =
browser()->GetProfile()->GetExtensionProcessManager();
content::RenderProcessHost* extension1_host =
process_manager->GetSiteInstanceForURL(extension1_url)->GetProcess();
content::RenderProcessHost* extension2_host =
process_manager->GetSiteInstanceForURL(extension2_url)->GetProcess();
// An isolated app only shares with other instances of itself, not other
// isolated apps or anything else.
EXPECT_EQ(isolated1_host, second_isolated1_host);
EXPECT_NE(isolated1_host, isolated2_host);
EXPECT_NE(isolated1_host, ntp1_host);
EXPECT_NE(isolated1_host, hosted1_host);
EXPECT_NE(isolated1_host, web1_host);
EXPECT_NE(isolated1_host, extension1_host);
EXPECT_NE(isolated2_host, ntp1_host);
EXPECT_NE(isolated2_host, hosted1_host);
EXPECT_NE(isolated2_host, web1_host);
EXPECT_NE(isolated2_host, extension1_host);
// Everything else is clannish. WebUI only shares with other WebUI.
EXPECT_EQ(ntp1_host, ntp2_host);
EXPECT_NE(ntp1_host, hosted1_host);
EXPECT_NE(ntp1_host, web1_host);
EXPECT_NE(ntp1_host, extension1_host);
// Hosted apps only share with each other.
EXPECT_EQ(hosted1_host, hosted2_host);
EXPECT_NE(hosted1_host, web1_host);
EXPECT_NE(hosted1_host, extension1_host);
// Web pages only share with each other.
EXPECT_EQ(web1_host, web2_host);
EXPECT_NE(web1_host, extension1_host);
// Extensions only share with each other.
EXPECT_EQ(extension1_host, extension2_host);
}
// Test to verify that the policy of maximum share of extension processes is
// properly enforced.
IN_PROC_BROWSER_TEST_F(ProcessManagementTest, ExtensionProcessBalancing) {
// Set max renderers to 6 so we can expect 2 extension processes to be
// allocated.
content::RenderProcessHost::SetMaxRendererProcessCount(6);
// The app under test acts on URLs whose host is "localhost",
// so the URLs we navigate to must have host "localhost".
GURL base_url = test_server()->GetURL(
"files/extensions/");
GURL::Replacements replace_host;
std::string host_str("localhost"); // Must stay in scope with replace_host.
replace_host.SetHostStr(host_str);
base_url = base_url.ReplaceComponents(replace_host);
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("api_test/browser_action/none")));
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("api_test/browser_action/basics")));
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("api_test/browser_action/remove_popup")));
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("api_test/browser_action/add_popup")));
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("api_test/browser_action/no_icon")));
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("isolated_apps/app1")));
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("api_test/management/test")));
ui_test_utils::NavigateToURLWithDisposition(
browser(), base_url.Resolve("isolated_apps/app1/main.html"),
CURRENT_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
ui_test_utils::NavigateToURLWithDisposition(
browser(), base_url.Resolve("api_test/management/test/basics.html"),
CURRENT_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
std::set<int> process_ids;
Profile* profile = browser()->GetProfile();
ExtensionProcessManager* epm = profile->GetExtensionProcessManager();
for (ExtensionProcessManager::const_iterator iter = epm->begin();
iter != epm->end();
++iter) {
ExtensionHost* host = *iter;
if (host->extension()->has_background_page()) {
process_ids.insert(host->render_process_host()->GetID());
}
}
// We've loaded 5 extensions with background pages, 1 extension without
// background page, and one isolated app. We expect only 2 unique processes
// hosting those extensions.
ASSERT_EQ((size_t) 5, profile->GetExtensionService()->process_map()->size());
ASSERT_EQ((size_t) 2, process_ids.size());
}
<commit_msg>Making the test more reliable.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/utf_string_conversions.h"
#include "chrome/browser/automation/automation_util.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/web_contents.h"
#include "net/base/mock_host_resolver.h"
using content::NavigationController;
using content::WebContents;
namespace {
class ProcessManagementTest : public ExtensionBrowserTest {
private:
// This is needed for testing isolated apps, which are still experimental.
virtual void SetUpCommandLine(CommandLine* command_line) {
ExtensionBrowserTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
}
};
} // namespace
// Ensure that an isolated app never shares a process with WebUIs, non-isolated
// extensions, and normal webpages. None of these should ever comingle
// RenderProcessHosts even if we hit the process limit.
IN_PROC_BROWSER_TEST_F(ProcessManagementTest, ProcessOverflow) {
// Set max renderers to 1 to force running out of processes.
content::RenderProcessHost::SetMaxRendererProcessCount(1);
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("isolated_apps/app1")));
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("isolated_apps/app2")));
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("hosted_app")));
ASSERT_TRUE(
LoadExtension(test_data_dir_.AppendASCII("api_test/app_process")));
// The app under test acts on URLs whose host is "localhost",
// so the URLs we navigate to must have host "localhost".
GURL base_url = test_server()->GetURL(
"files/extensions/");
GURL::Replacements replace_host;
std::string host_str("localhost"); // Must stay in scope with replace_host.
replace_host.SetHostStr(host_str);
base_url = base_url.ReplaceComponents(replace_host);
// Load an extension before adding tabs.
const Extension* extension1 = LoadExtension(
test_data_dir_.AppendASCII("api_test/browser_action/basics"));
ASSERT_TRUE(extension1);
GURL extension1_url = extension1->url();
// Create multiple tabs for each type of renderer that might exist.
ui_test_utils::NavigateToURLWithDisposition(
browser(), base_url.Resolve("isolated_apps/app1/main.html"),
CURRENT_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
ui_test_utils::NavigateToURLWithDisposition(
browser(), GURL(chrome::kChromeUINewTabURL),
NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
ui_test_utils::NavigateToURLWithDisposition(
browser(), base_url.Resolve("hosted_app/main.html"),
NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
ui_test_utils::NavigateToURLWithDisposition(
browser(), base_url.Resolve("test_file.html"),
NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
ui_test_utils::NavigateToURLWithDisposition(
browser(), base_url.Resolve("isolated_apps/app2/main.html"),
NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
ui_test_utils::NavigateToURLWithDisposition(
browser(), GURL(chrome::kChromeUINewTabURL),
NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
ui_test_utils::NavigateToURLWithDisposition(
browser(), base_url.Resolve("api_test/app_process/path1/empty.html"),
NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
ui_test_utils::NavigateToURLWithDisposition(
browser(), base_url.Resolve("test_file_with_body.html"),
NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
// Load another copy of isolated app 1.
ui_test_utils::NavigateToURLWithDisposition(
browser(), base_url.Resolve("isolated_apps/app1/main.html"),
NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
// Load another extension.
const Extension* extension2 = LoadExtension(
test_data_dir_.AppendASCII("api_test/browser_action/close_background"));
ASSERT_TRUE(extension2);
GURL extension2_url = extension2->url();
// Get tab processes.
ASSERT_EQ(9, browser()->tab_count());
content::RenderProcessHost* isolated1_host =
browser()->GetWebContentsAt(0)->GetRenderProcessHost();
content::RenderProcessHost* ntp1_host =
browser()->GetWebContentsAt(1)->GetRenderProcessHost();
content::RenderProcessHost* hosted1_host =
browser()->GetWebContentsAt(2)->GetRenderProcessHost();
content::RenderProcessHost* web1_host =
browser()->GetWebContentsAt(3)->GetRenderProcessHost();
content::RenderProcessHost* isolated2_host =
browser()->GetWebContentsAt(4)->GetRenderProcessHost();
content::RenderProcessHost* ntp2_host =
browser()->GetWebContentsAt(5)->GetRenderProcessHost();
content::RenderProcessHost* hosted2_host =
browser()->GetWebContentsAt(6)->GetRenderProcessHost();
content::RenderProcessHost* web2_host =
browser()->GetWebContentsAt(7)->GetRenderProcessHost();
content::RenderProcessHost* second_isolated1_host =
browser()->GetWebContentsAt(8)->GetRenderProcessHost();
// Get extension processes.
ExtensionProcessManager* process_manager =
browser()->GetProfile()->GetExtensionProcessManager();
content::RenderProcessHost* extension1_host =
process_manager->GetSiteInstanceForURL(extension1_url)->GetProcess();
content::RenderProcessHost* extension2_host =
process_manager->GetSiteInstanceForURL(extension2_url)->GetProcess();
// An isolated app only shares with other instances of itself, not other
// isolated apps or anything else.
EXPECT_EQ(isolated1_host, second_isolated1_host);
EXPECT_NE(isolated1_host, isolated2_host);
EXPECT_NE(isolated1_host, ntp1_host);
EXPECT_NE(isolated1_host, hosted1_host);
EXPECT_NE(isolated1_host, web1_host);
EXPECT_NE(isolated1_host, extension1_host);
EXPECT_NE(isolated2_host, ntp1_host);
EXPECT_NE(isolated2_host, hosted1_host);
EXPECT_NE(isolated2_host, web1_host);
EXPECT_NE(isolated2_host, extension1_host);
// Everything else is clannish. WebUI only shares with other WebUI.
EXPECT_EQ(ntp1_host, ntp2_host);
EXPECT_NE(ntp1_host, hosted1_host);
EXPECT_NE(ntp1_host, web1_host);
EXPECT_NE(ntp1_host, extension1_host);
// Hosted apps only share with each other.
EXPECT_EQ(hosted1_host, hosted2_host);
EXPECT_NE(hosted1_host, web1_host);
EXPECT_NE(hosted1_host, extension1_host);
// Web pages only share with each other.
EXPECT_EQ(web1_host, web2_host);
EXPECT_NE(web1_host, extension1_host);
// Extensions only share with each other.
EXPECT_EQ(extension1_host, extension2_host);
}
// Test to verify that the policy of maximum share of extension processes is
// properly enforced.
IN_PROC_BROWSER_TEST_F(ProcessManagementTest, ExtensionProcessBalancing) {
// Set max renderers to 6 so we can expect 2 extension processes to be
// allocated.
content::RenderProcessHost::SetMaxRendererProcessCount(6);
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
// The app under test acts on URLs whose host is "localhost",
// so the URLs we navigate to must have host "localhost".
GURL base_url = test_server()->GetURL(
"files/extensions/");
GURL::Replacements replace_host;
std::string host_str("localhost"); // Must stay in scope with replace_host.
replace_host.SetHostStr(host_str);
base_url = base_url.ReplaceComponents(replace_host);
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("api_test/browser_action/none")));
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("api_test/browser_action/basics")));
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("api_test/browser_action/remove_popup")));
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("api_test/browser_action/add_popup")));
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("api_test/browser_action/no_icon")));
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("isolated_apps/app1")));
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("api_test/management/test")));
ui_test_utils::NavigateToURLWithDisposition(
browser(), base_url.Resolve("isolated_apps/app1/main.html"),
CURRENT_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
ui_test_utils::NavigateToURLWithDisposition(
browser(), base_url.Resolve("api_test/management/test/basics.html"),
CURRENT_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
std::set<int> process_ids;
Profile* profile = browser()->GetProfile();
ExtensionProcessManager* epm = profile->GetExtensionProcessManager();
for (ExtensionProcessManager::const_iterator iter = epm->begin();
iter != epm->end();
++iter) {
ExtensionHost* host = *iter;
if (host->extension()->has_background_page()) {
process_ids.insert(host->render_process_host()->GetID());
}
}
// We've loaded 5 extensions with background pages, 1 extension without
// background page, and one isolated app. We expect only 2 unique processes
// hosting those extensions.
EXPECT_GE((size_t) 6, profile->GetExtensionService()->process_map()->size());
EXPECT_EQ((size_t) 2, process_ids.size());
}
<|endoftext|> |
<commit_before>// Copyright (c) 2014-2018 Sebastien Rombauts ([email protected])
//
// Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
// or copy at http://opensource.org/licenses/MIT)
#include "GitSourceControlPrivatePCH.h"
#include "GitSourceControlMenu.h"
#include "GitSourceControlModule.h"
#include "GitSourceControlProvider.h"
#include "GitSourceControlOperations.h"
#include "ISourceControlOperation.h"
#include "SourceControlOperations.h"
#include "LevelEditor.h"
#include "Widgets/Notifications/SNotificationList.h"
#include "Framework/Notifications/NotificationManager.h"
#include "EditorStyleSet.h"
#include "PackageTools.h"
#include "FileHelpers.h"
#include "Logging/MessageLog.h"
static const FName GitSourceControlMenuTabName("GitSourceControlMenu");
#define LOCTEXT_NAMESPACE "GitSourceControl"
void FGitSourceControlMenu::Register()
{
// Register the extension with the level editor
FLevelEditorModule* LevelEditorModule = FModuleManager::GetModulePtr<FLevelEditorModule>("LevelEditor");
if (LevelEditorModule)
{
FLevelEditorModule::FLevelEditorMenuExtender ViewMenuExtender = FLevelEditorModule::FLevelEditorMenuExtender::CreateRaw(this, &FGitSourceControlMenu::OnExtendLevelEditorViewMenu);
auto& MenuExtenders = LevelEditorModule->GetAllLevelEditorToolbarSourceControlMenuExtenders();
MenuExtenders.Add(ViewMenuExtender);
ViewMenuExtenderHandle = MenuExtenders.Last().GetHandle();
}
}
void FGitSourceControlMenu::Unregister()
{
// Unregister the level editor extensions
FLevelEditorModule* LevelEditorModule = FModuleManager::GetModulePtr<FLevelEditorModule>("LevelEditor");
if (LevelEditorModule)
{
LevelEditorModule->GetAllLevelEditorToolbarSourceControlMenuExtenders().RemoveAll([=](const FLevelEditorModule::FLevelEditorMenuExtender& Extender) { return Extender.GetHandle() == ViewMenuExtenderHandle; });
}
}
bool FGitSourceControlMenu::HaveRemoteUrl() const
{
FGitSourceControlModule& GitSourceControl = FModuleManager::LoadModuleChecked<FGitSourceControlModule>("GitSourceControl");
FGitSourceControlProvider& Provider = GitSourceControl.GetProvider();
return !Provider.GetRemoteUrl().IsEmpty();
}
void FGitSourceControlMenu::UnlinkSyncAndReloadPackages()
{
// Prompt to save or discard all packages
bool bOkToExit = false;
bool bHadPackagesToSave = false;
{
const bool bPromptUserToSave = true;
const bool bSaveMapPackages = true;
const bool bSaveContentPackages = true;
const bool bFastSave = false;
const bool bNotifyNoPackagesSaved = false;
const bool bCanBeDeclined = true; // If the user clicks "don't save" this will continue and lose their changes
bOkToExit = FEditorFileUtils::SaveDirtyPackages(bPromptUserToSave, bSaveMapPackages, bSaveContentPackages, bFastSave, bNotifyNoPackagesSaved, bCanBeDeclined, &bHadPackagesToSave);
}
// bOkToExit can be true if the user selects to not save an asset by unchecking it and clicking "save"
if (bOkToExit)
{
TArray<UPackage*> DirtyPackages;
FEditorFileUtils::GetDirtyWorldPackages(DirtyPackages);
FEditorFileUtils::GetDirtyContentPackages(DirtyPackages);
bOkToExit = DirtyPackages.Num() == 0;
}
if (bOkToExit)
{
FGitSourceControlModule& GitSourceControl = FModuleManager::LoadModuleChecked<FGitSourceControlModule>("GitSourceControl");
FGitSourceControlProvider& Provider = GitSourceControl.GetProvider();
// Unload all packages in Content directory
TArray<FString> PackageRelativePaths;
FPackageName::FindPackagesInDirectory(PackageRelativePaths, *FPaths::ConvertRelativePathToFull(FPaths::ProjectContentDir()));
TArray<FString> PackageNames;
PackageNames.Reserve(PackageRelativePaths.Num());
for(const FString& Path : PackageRelativePaths)
{
FString PackageName;
FString FailureReason;
if (FPackageName::TryConvertFilenameToLongPackageName(Path, PackageName, &FailureReason))
{
PackageNames.Add(PackageName);
}
else
{
FMessageLog("GitSourceControl").Error(FText::FromString(FailureReason));
}
}
// Inspired from ContentBrowserUtils.cpp ContentBrowserUtils::SyncPathsFromSourceControl()
TArray<UPackage*> LoadedPackages = UnlinkPackages(PackageNames);
// Execute a Source Control "Sync" synchronously, displaying an ongoing notification during the whole operation
TSharedRef<FSync, ESPMode::ThreadSafe> SyncOperation = ISourceControlOperation::Create<FSync>();
DisplayInProgressNotification(SyncOperation->GetInProgressString());
const ECommandResult::Type Result = Provider.Execute(SyncOperation, TArray<FString>(), EConcurrency::Synchronous);
OnSourceControlOperationComplete(SyncOperation, Result);
// Reload all packages
ReloadPackages(LoadedPackages);
}
else
{
FMessageLog ErrorMessage("GitSourceControl");
ErrorMessage.Warning(LOCTEXT("SourceControlMenu_Sync_Unsaved", "Save All Assets before attempting to Sync!"));
ErrorMessage.Notify();
}
}
TArray<UPackage*> FGitSourceControlMenu::UnlinkPackages(const TArray<FString>& InPackageNames)
{
TArray<UPackage*> LoadedPackages;
if (InPackageNames.Num() > 0)
{
// Form a list of loaded packages to reload...
LoadedPackages.Reserve(InPackageNames.Num());
for(const FString& PackageName : InPackageNames)
{
UPackage* Package = FindPackage(nullptr, *PackageName);
if (Package)
{
LoadedPackages.Emplace(Package);
// Detach the linkers of any loaded packages so that SCC can overwrite the files...
if (!Package->IsFullyLoaded())
{
FlushAsyncLoading();
Package->FullyLoad();
}
ResetLoaders(Package);
}
}
UE_LOG(LogSourceControl, Log, TEXT("Reseted Loader for %d Packages"), LoadedPackages.Num());
}
return LoadedPackages;
}
void FGitSourceControlMenu::ReloadPackages(TArray<UPackage*>& InLoadedPackages)
{
UE_LOG(LogSourceControl, Log, TEXT("Reloading %d Packages..."), InLoadedPackages.Num());
// Syncing may have deleted some packages, so we need to unload those rather than re-load them...
TArray<UPackage*> PackagesToUnload;
InLoadedPackages.RemoveAll([&](UPackage* InPackage) -> bool
{
const FString PackageExtension = InPackage->ContainsMap() ? FPackageName::GetMapPackageExtension() : FPackageName::GetAssetPackageExtension();
const FString PackageFilename = FPackageName::LongPackageNameToFilename(InPackage->GetName(), PackageExtension);
if (!FPaths::FileExists(PackageFilename))
{
PackagesToUnload.Emplace(InPackage);
return true; // remove package
}
return false; // keep package
});
// Hot-reload the new packages...
PackageTools::ReloadPackages(InLoadedPackages);
// Unload any deleted packages...
PackageTools::UnloadPackages(PackagesToUnload);
}
void FGitSourceControlMenu::SyncClicked()
{
if (!OperationInProgressNotification.IsValid())
{
UnlinkSyncAndReloadPackages();
}
else
{
FMessageLog LogSourceControl("LogSourceControl");
LogSourceControl.Warning(LOCTEXT("SourceControlMenu_InProgress", "Source control operation already in progress"));
LogSourceControl.Notify();
}
}
void FGitSourceControlMenu::PushClicked()
{
if (!OperationInProgressNotification.IsValid())
{
// Launch a "Push" Operation
FGitSourceControlModule& GitSourceControl = FModuleManager::LoadModuleChecked<FGitSourceControlModule>("GitSourceControl");
FGitSourceControlProvider& Provider = GitSourceControl.GetProvider();
TSharedRef<FGitPush, ESPMode::ThreadSafe> PushOperation = ISourceControlOperation::Create<FGitPush>();
ECommandResult::Type Result = Provider.Execute(PushOperation, TArray<FString>(), EConcurrency::Asynchronous, FSourceControlOperationComplete::CreateRaw(this, &FGitSourceControlMenu::OnSourceControlOperationComplete));
if (Result == ECommandResult::Succeeded)
{
// Display an ongoing notification during the whole operation
DisplayInProgressNotification(PushOperation->GetInProgressString());
}
else
{
// Report failure with a notification
DisplayFailureNotification(PushOperation->GetName());
}
}
else
{
FMessageLog LogSourceControl("LogSourceControl");
LogSourceControl.Warning(LOCTEXT("SourceControlMenu_InProgress", "Source control operation already in progress"));
LogSourceControl.Notify();
}
}
void FGitSourceControlMenu::RefreshClicked()
{
if (!OperationInProgressNotification.IsValid())
{
// Launch an "UpdateStatus" Operation
FGitSourceControlModule& GitSourceControl = FModuleManager::LoadModuleChecked<FGitSourceControlModule>("GitSourceControl");
FGitSourceControlProvider& Provider = GitSourceControl.GetProvider();
TSharedRef<FUpdateStatus, ESPMode::ThreadSafe> RefreshOperation = ISourceControlOperation::Create<FUpdateStatus>();
RefreshOperation->SetCheckingAllFiles(true);
RefreshOperation->SetGetOpenedOnly(true);
ECommandResult::Type Result = Provider.Execute(RefreshOperation, TArray<FString>(), EConcurrency::Asynchronous, FSourceControlOperationComplete::CreateRaw(this, &FGitSourceControlMenu::OnSourceControlOperationComplete));
if (Result == ECommandResult::Succeeded)
{
// Display an ongoing notification during the whole operation
DisplayInProgressNotification(RefreshOperation->GetInProgressString());
}
else
{
// Report failure with a notification
DisplayFailureNotification(RefreshOperation->GetName());
}
}
else
{
FMessageLog LogSourceControl("LogSourceControl");
LogSourceControl.Warning(LOCTEXT("SourceControlMenu_InProgress", "Source control operation already in progress"));
LogSourceControl.Notify();
}
}
// Display an ongoing notification during the whole operation
void FGitSourceControlMenu::DisplayInProgressNotification(const FText& InOperationInProgressString)
{
if (!OperationInProgressNotification.IsValid())
{
FNotificationInfo Info(InOperationInProgressString);
Info.bFireAndForget = false;
Info.ExpireDuration = 0.0f;
Info.FadeOutDuration = 1.0f;
OperationInProgressNotification = FSlateNotificationManager::Get().AddNotification(Info);
if (OperationInProgressNotification.IsValid())
{
OperationInProgressNotification.Pin()->SetCompletionState(SNotificationItem::CS_Pending);
}
}
}
// Remove the ongoing notification at the end of the operation
void FGitSourceControlMenu::RemoveInProgressNotification()
{
if (OperationInProgressNotification.IsValid())
{
OperationInProgressNotification.Pin()->ExpireAndFadeout();
OperationInProgressNotification.Reset();
}
}
// Display a temporary success notification at the end of the operation
void FGitSourceControlMenu::DisplaySucessNotification(const FName& InOperationName)
{
const FText NotificationText = FText::Format(
LOCTEXT("SourceControlMenu_Success", "{0} operation was successful!"),
FText::FromName(InOperationName)
);
FNotificationInfo Info(NotificationText);
Info.bUseSuccessFailIcons = true;
Info.Image = FEditorStyle::GetBrush(TEXT("NotificationList.SuccessImage"));
FSlateNotificationManager::Get().AddNotification(Info);
FMessageLog("LogSourceControl").Info(NotificationText);
}
// Display a temporary failure notification at the end of the operation
void FGitSourceControlMenu::DisplayFailureNotification(const FName& InOperationName)
{
const FText NotificationText = FText::Format(
LOCTEXT("SourceControlMenu_Failure", "Error: {0} operation failed!"),
FText::FromName(InOperationName)
);
FNotificationInfo Info(NotificationText);
Info.ExpireDuration = 8.0f;
FSlateNotificationManager::Get().AddNotification(Info);
FMessageLog("LogSourceControl").Info(NotificationText);
}
void FGitSourceControlMenu::OnSourceControlOperationComplete(const FSourceControlOperationRef& InOperation, ECommandResult::Type InResult)
{
RemoveInProgressNotification();
// Report result with a notification
if (InResult == ECommandResult::Succeeded)
{
DisplaySucessNotification(InOperation->GetName());
}
else
{
DisplayFailureNotification(InOperation->GetName());
}
}
void FGitSourceControlMenu::AddMenuExtension(FMenuBuilder& Builder)
{
Builder.AddMenuEntry(
LOCTEXT("GitPush", "Push"),
LOCTEXT("GitPushTooltip", "Push all local commits to the remote server."),
FSlateIcon(FEditorStyle::GetStyleSetName(), "SourceControl.Actions.Submit"),
FUIAction(
FExecuteAction::CreateRaw(this, &FGitSourceControlMenu::PushClicked),
FCanExecuteAction::CreateRaw(this, &FGitSourceControlMenu::HaveRemoteUrl)
)
);
Builder.AddMenuEntry(
LOCTEXT("GitSync", "Sync/Pull"),
LOCTEXT("GitSyncTooltip", "Update all files in the local repository to the latest version of the remote server."),
FSlateIcon(FEditorStyle::GetStyleSetName(), "SourceControl.Actions.Sync"),
FUIAction(
FExecuteAction::CreateRaw(this, &FGitSourceControlMenu::SyncClicked),
FCanExecuteAction::CreateRaw(this, &FGitSourceControlMenu::HaveRemoteUrl)
)
);
Builder.AddMenuEntry(
LOCTEXT("GitRefresh", "Refresh"),
LOCTEXT("GitRefreshTooltip", "Update the source control status of all files in the local repository."),
FSlateIcon(FEditorStyle::GetStyleSetName(), "SourceControl.Actions.Refresh"),
FUIAction(
FExecuteAction::CreateRaw(this, &FGitSourceControlMenu::RefreshClicked),
FCanExecuteAction()
)
);
}
TSharedRef<FExtender> FGitSourceControlMenu::OnExtendLevelEditorViewMenu(const TSharedRef<FUICommandList> CommandList)
{
TSharedRef<FExtender> Extender(new FExtender());
Extender->AddMenuExtension(
"SourceControlActions",
EExtensionHook::After,
nullptr,
FMenuExtensionDelegate::CreateRaw(this, &FGitSourceControlMenu::AddMenuExtension));
return Extender;
}
#undef LOCTEXT_NAMESPACE
<commit_msg>Fix non-unity build: missing include file for LogSourceControl définition<commit_after>// Copyright (c) 2014-2018 Sebastien Rombauts ([email protected])
//
// Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
// or copy at http://opensource.org/licenses/MIT)
#include "GitSourceControlPrivatePCH.h"
#include "GitSourceControlMenu.h"
#include "GitSourceControlModule.h"
#include "GitSourceControlProvider.h"
#include "GitSourceControlOperations.h"
#include "ISourceControlModule.h"
#include "ISourceControlOperation.h"
#include "SourceControlOperations.h"
#include "LevelEditor.h"
#include "Widgets/Notifications/SNotificationList.h"
#include "Framework/Notifications/NotificationManager.h"
#include "EditorStyleSet.h"
#include "PackageTools.h"
#include "FileHelpers.h"
#include "Logging/MessageLog.h"
static const FName GitSourceControlMenuTabName("GitSourceControlMenu");
#define LOCTEXT_NAMESPACE "GitSourceControl"
void FGitSourceControlMenu::Register()
{
// Register the extension with the level editor
FLevelEditorModule* LevelEditorModule = FModuleManager::GetModulePtr<FLevelEditorModule>("LevelEditor");
if (LevelEditorModule)
{
FLevelEditorModule::FLevelEditorMenuExtender ViewMenuExtender = FLevelEditorModule::FLevelEditorMenuExtender::CreateRaw(this, &FGitSourceControlMenu::OnExtendLevelEditorViewMenu);
auto& MenuExtenders = LevelEditorModule->GetAllLevelEditorToolbarSourceControlMenuExtenders();
MenuExtenders.Add(ViewMenuExtender);
ViewMenuExtenderHandle = MenuExtenders.Last().GetHandle();
}
}
void FGitSourceControlMenu::Unregister()
{
// Unregister the level editor extensions
FLevelEditorModule* LevelEditorModule = FModuleManager::GetModulePtr<FLevelEditorModule>("LevelEditor");
if (LevelEditorModule)
{
LevelEditorModule->GetAllLevelEditorToolbarSourceControlMenuExtenders().RemoveAll([=](const FLevelEditorModule::FLevelEditorMenuExtender& Extender) { return Extender.GetHandle() == ViewMenuExtenderHandle; });
}
}
bool FGitSourceControlMenu::HaveRemoteUrl() const
{
FGitSourceControlModule& GitSourceControl = FModuleManager::LoadModuleChecked<FGitSourceControlModule>("GitSourceControl");
FGitSourceControlProvider& Provider = GitSourceControl.GetProvider();
return !Provider.GetRemoteUrl().IsEmpty();
}
void FGitSourceControlMenu::UnlinkSyncAndReloadPackages()
{
// Prompt to save or discard all packages
bool bOkToExit = false;
bool bHadPackagesToSave = false;
{
const bool bPromptUserToSave = true;
const bool bSaveMapPackages = true;
const bool bSaveContentPackages = true;
const bool bFastSave = false;
const bool bNotifyNoPackagesSaved = false;
const bool bCanBeDeclined = true; // If the user clicks "don't save" this will continue and lose their changes
bOkToExit = FEditorFileUtils::SaveDirtyPackages(bPromptUserToSave, bSaveMapPackages, bSaveContentPackages, bFastSave, bNotifyNoPackagesSaved, bCanBeDeclined, &bHadPackagesToSave);
}
// bOkToExit can be true if the user selects to not save an asset by unchecking it and clicking "save"
if (bOkToExit)
{
TArray<UPackage*> DirtyPackages;
FEditorFileUtils::GetDirtyWorldPackages(DirtyPackages);
FEditorFileUtils::GetDirtyContentPackages(DirtyPackages);
bOkToExit = DirtyPackages.Num() == 0;
}
if (bOkToExit)
{
FGitSourceControlModule& GitSourceControl = FModuleManager::LoadModuleChecked<FGitSourceControlModule>("GitSourceControl");
FGitSourceControlProvider& Provider = GitSourceControl.GetProvider();
// Unload all packages in Content directory
TArray<FString> PackageRelativePaths;
FPackageName::FindPackagesInDirectory(PackageRelativePaths, *FPaths::ConvertRelativePathToFull(FPaths::ProjectContentDir()));
TArray<FString> PackageNames;
PackageNames.Reserve(PackageRelativePaths.Num());
for(const FString& Path : PackageRelativePaths)
{
FString PackageName;
FString FailureReason;
if (FPackageName::TryConvertFilenameToLongPackageName(Path, PackageName, &FailureReason))
{
PackageNames.Add(PackageName);
}
else
{
FMessageLog("GitSourceControl").Error(FText::FromString(FailureReason));
}
}
// Inspired from ContentBrowserUtils.cpp ContentBrowserUtils::SyncPathsFromSourceControl()
TArray<UPackage*> LoadedPackages = UnlinkPackages(PackageNames);
// Execute a Source Control "Sync" synchronously, displaying an ongoing notification during the whole operation
TSharedRef<FSync, ESPMode::ThreadSafe> SyncOperation = ISourceControlOperation::Create<FSync>();
DisplayInProgressNotification(SyncOperation->GetInProgressString());
const ECommandResult::Type Result = Provider.Execute(SyncOperation, TArray<FString>(), EConcurrency::Synchronous);
OnSourceControlOperationComplete(SyncOperation, Result);
// Reload all packages
ReloadPackages(LoadedPackages);
}
else
{
FMessageLog ErrorMessage("GitSourceControl");
ErrorMessage.Warning(LOCTEXT("SourceControlMenu_Sync_Unsaved", "Save All Assets before attempting to Sync!"));
ErrorMessage.Notify();
}
}
TArray<UPackage*> FGitSourceControlMenu::UnlinkPackages(const TArray<FString>& InPackageNames)
{
TArray<UPackage*> LoadedPackages;
if (InPackageNames.Num() > 0)
{
// Form a list of loaded packages to reload...
LoadedPackages.Reserve(InPackageNames.Num());
for(const FString& PackageName : InPackageNames)
{
UPackage* Package = FindPackage(nullptr, *PackageName);
if (Package)
{
LoadedPackages.Emplace(Package);
// Detach the linkers of any loaded packages so that SCC can overwrite the files...
if (!Package->IsFullyLoaded())
{
FlushAsyncLoading();
Package->FullyLoad();
}
ResetLoaders(Package);
}
}
UE_LOG(LogSourceControl, Log, TEXT("Reseted Loader for %d Packages"), LoadedPackages.Num());
}
return LoadedPackages;
}
void FGitSourceControlMenu::ReloadPackages(TArray<UPackage*>& InLoadedPackages)
{
UE_LOG(LogSourceControl, Log, TEXT("Reloading %d Packages..."), InLoadedPackages.Num());
// Syncing may have deleted some packages, so we need to unload those rather than re-load them...
TArray<UPackage*> PackagesToUnload;
InLoadedPackages.RemoveAll([&](UPackage* InPackage) -> bool
{
const FString PackageExtension = InPackage->ContainsMap() ? FPackageName::GetMapPackageExtension() : FPackageName::GetAssetPackageExtension();
const FString PackageFilename = FPackageName::LongPackageNameToFilename(InPackage->GetName(), PackageExtension);
if (!FPaths::FileExists(PackageFilename))
{
PackagesToUnload.Emplace(InPackage);
return true; // remove package
}
return false; // keep package
});
// Hot-reload the new packages...
PackageTools::ReloadPackages(InLoadedPackages);
// Unload any deleted packages...
PackageTools::UnloadPackages(PackagesToUnload);
}
void FGitSourceControlMenu::SyncClicked()
{
if (!OperationInProgressNotification.IsValid())
{
UnlinkSyncAndReloadPackages();
}
else
{
FMessageLog LogSourceControl("LogSourceControl");
LogSourceControl.Warning(LOCTEXT("SourceControlMenu_InProgress", "Source control operation already in progress"));
LogSourceControl.Notify();
}
}
void FGitSourceControlMenu::PushClicked()
{
if (!OperationInProgressNotification.IsValid())
{
// Launch a "Push" Operation
FGitSourceControlModule& GitSourceControl = FModuleManager::LoadModuleChecked<FGitSourceControlModule>("GitSourceControl");
FGitSourceControlProvider& Provider = GitSourceControl.GetProvider();
TSharedRef<FGitPush, ESPMode::ThreadSafe> PushOperation = ISourceControlOperation::Create<FGitPush>();
ECommandResult::Type Result = Provider.Execute(PushOperation, TArray<FString>(), EConcurrency::Asynchronous, FSourceControlOperationComplete::CreateRaw(this, &FGitSourceControlMenu::OnSourceControlOperationComplete));
if (Result == ECommandResult::Succeeded)
{
// Display an ongoing notification during the whole operation
DisplayInProgressNotification(PushOperation->GetInProgressString());
}
else
{
// Report failure with a notification
DisplayFailureNotification(PushOperation->GetName());
}
}
else
{
FMessageLog LogSourceControl("LogSourceControl");
LogSourceControl.Warning(LOCTEXT("SourceControlMenu_InProgress", "Source control operation already in progress"));
LogSourceControl.Notify();
}
}
void FGitSourceControlMenu::RefreshClicked()
{
if (!OperationInProgressNotification.IsValid())
{
// Launch an "UpdateStatus" Operation
FGitSourceControlModule& GitSourceControl = FModuleManager::LoadModuleChecked<FGitSourceControlModule>("GitSourceControl");
FGitSourceControlProvider& Provider = GitSourceControl.GetProvider();
TSharedRef<FUpdateStatus, ESPMode::ThreadSafe> RefreshOperation = ISourceControlOperation::Create<FUpdateStatus>();
RefreshOperation->SetCheckingAllFiles(true);
RefreshOperation->SetGetOpenedOnly(true);
ECommandResult::Type Result = Provider.Execute(RefreshOperation, TArray<FString>(), EConcurrency::Asynchronous, FSourceControlOperationComplete::CreateRaw(this, &FGitSourceControlMenu::OnSourceControlOperationComplete));
if (Result == ECommandResult::Succeeded)
{
// Display an ongoing notification during the whole operation
DisplayInProgressNotification(RefreshOperation->GetInProgressString());
}
else
{
// Report failure with a notification
DisplayFailureNotification(RefreshOperation->GetName());
}
}
else
{
FMessageLog LogSourceControl("LogSourceControl");
LogSourceControl.Warning(LOCTEXT("SourceControlMenu_InProgress", "Source control operation already in progress"));
LogSourceControl.Notify();
}
}
// Display an ongoing notification during the whole operation
void FGitSourceControlMenu::DisplayInProgressNotification(const FText& InOperationInProgressString)
{
if (!OperationInProgressNotification.IsValid())
{
FNotificationInfo Info(InOperationInProgressString);
Info.bFireAndForget = false;
Info.ExpireDuration = 0.0f;
Info.FadeOutDuration = 1.0f;
OperationInProgressNotification = FSlateNotificationManager::Get().AddNotification(Info);
if (OperationInProgressNotification.IsValid())
{
OperationInProgressNotification.Pin()->SetCompletionState(SNotificationItem::CS_Pending);
}
}
}
// Remove the ongoing notification at the end of the operation
void FGitSourceControlMenu::RemoveInProgressNotification()
{
if (OperationInProgressNotification.IsValid())
{
OperationInProgressNotification.Pin()->ExpireAndFadeout();
OperationInProgressNotification.Reset();
}
}
// Display a temporary success notification at the end of the operation
void FGitSourceControlMenu::DisplaySucessNotification(const FName& InOperationName)
{
const FText NotificationText = FText::Format(
LOCTEXT("SourceControlMenu_Success", "{0} operation was successful!"),
FText::FromName(InOperationName)
);
FNotificationInfo Info(NotificationText);
Info.bUseSuccessFailIcons = true;
Info.Image = FEditorStyle::GetBrush(TEXT("NotificationList.SuccessImage"));
FSlateNotificationManager::Get().AddNotification(Info);
FMessageLog("LogSourceControl").Info(NotificationText);
}
// Display a temporary failure notification at the end of the operation
void FGitSourceControlMenu::DisplayFailureNotification(const FName& InOperationName)
{
const FText NotificationText = FText::Format(
LOCTEXT("SourceControlMenu_Failure", "Error: {0} operation failed!"),
FText::FromName(InOperationName)
);
FNotificationInfo Info(NotificationText);
Info.ExpireDuration = 8.0f;
FSlateNotificationManager::Get().AddNotification(Info);
FMessageLog("LogSourceControl").Info(NotificationText);
}
void FGitSourceControlMenu::OnSourceControlOperationComplete(const FSourceControlOperationRef& InOperation, ECommandResult::Type InResult)
{
RemoveInProgressNotification();
// Report result with a notification
if (InResult == ECommandResult::Succeeded)
{
DisplaySucessNotification(InOperation->GetName());
}
else
{
DisplayFailureNotification(InOperation->GetName());
}
}
void FGitSourceControlMenu::AddMenuExtension(FMenuBuilder& Builder)
{
Builder.AddMenuEntry(
LOCTEXT("GitPush", "Push"),
LOCTEXT("GitPushTooltip", "Push all local commits to the remote server."),
FSlateIcon(FEditorStyle::GetStyleSetName(), "SourceControl.Actions.Submit"),
FUIAction(
FExecuteAction::CreateRaw(this, &FGitSourceControlMenu::PushClicked),
FCanExecuteAction::CreateRaw(this, &FGitSourceControlMenu::HaveRemoteUrl)
)
);
Builder.AddMenuEntry(
LOCTEXT("GitSync", "Sync/Pull"),
LOCTEXT("GitSyncTooltip", "Update all files in the local repository to the latest version of the remote server."),
FSlateIcon(FEditorStyle::GetStyleSetName(), "SourceControl.Actions.Sync"),
FUIAction(
FExecuteAction::CreateRaw(this, &FGitSourceControlMenu::SyncClicked),
FCanExecuteAction::CreateRaw(this, &FGitSourceControlMenu::HaveRemoteUrl)
)
);
Builder.AddMenuEntry(
LOCTEXT("GitRefresh", "Refresh"),
LOCTEXT("GitRefreshTooltip", "Update the source control status of all files in the local repository."),
FSlateIcon(FEditorStyle::GetStyleSetName(), "SourceControl.Actions.Refresh"),
FUIAction(
FExecuteAction::CreateRaw(this, &FGitSourceControlMenu::RefreshClicked),
FCanExecuteAction()
)
);
}
TSharedRef<FExtender> FGitSourceControlMenu::OnExtendLevelEditorViewMenu(const TSharedRef<FUICommandList> CommandList)
{
TSharedRef<FExtender> Extender(new FExtender());
Extender->AddMenuExtension(
"SourceControlActions",
EExtensionHook::After,
nullptr,
FMenuExtensionDelegate::CreateRaw(this, &FGitSourceControlMenu::AddMenuExtension));
return Extender;
}
#undef LOCTEXT_NAMESPACE
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "base/logging.h"
#include "base/sha2.h"
#include "chrome/browser/safe_browsing/safe_browsing_util.h"
#include "googleurl/src/gurl.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
bool VectorContains(const std::vector<std::string>& data,
const std::string& str) {
for (size_t i = 0; i < data.size(); ++i) {
if (data[i] == str)
return true;
}
return false;
}
SBFullHash CreateFullHash(SBPrefix prefix) {
SBFullHash result;
memset(&result, 0, sizeof(result));
memcpy(&result, &prefix, sizeof(result));
return result;
}
}
// Tests that we generate the required host/path combinations for testing
// according to the Safe Browsing spec.
// See section 6.2 in
// http://code.google.com/p/google-safe-browsing/wiki/Protocolv2Spec.
TEST(SafeBrowsingUtilTest, UrlParsing) {
std::vector<std::string> hosts, paths;
GURL url("http://a.b.c/1/2.html?param=1");
safe_browsing_util::GenerateHostsToCheck(url, &hosts);
safe_browsing_util::GeneratePathsToCheck(url, &paths);
EXPECT_EQ(hosts.size(), 2);
EXPECT_EQ(paths.size(), 4);
EXPECT_EQ(hosts[0], "b.c");
EXPECT_EQ(hosts[1], "a.b.c");
EXPECT_TRUE(VectorContains(paths, "/1/2.html?param=1"));
EXPECT_TRUE(VectorContains(paths, "/1/2.html"));
EXPECT_TRUE(VectorContains(paths, "/1/"));
EXPECT_TRUE(VectorContains(paths, "/"));
url = GURL("http://a.b.c.d.e.f.g/1.html");
safe_browsing_util::GenerateHostsToCheck(url, &hosts);
safe_browsing_util::GeneratePathsToCheck(url, &paths);
EXPECT_EQ(hosts.size(), 5);
EXPECT_EQ(paths.size(), 2);
EXPECT_EQ(hosts[0], "f.g");
EXPECT_EQ(hosts[1], "e.f.g");
EXPECT_EQ(hosts[2], "d.e.f.g");
EXPECT_EQ(hosts[3], "c.d.e.f.g");
EXPECT_EQ(hosts[4], "a.b.c.d.e.f.g");
EXPECT_TRUE(VectorContains(paths, "/1.html"));
EXPECT_TRUE(VectorContains(paths, "/"));
url = GURL("http://a.b/saw-cgi/eBayISAPI.dll/");
safe_browsing_util::GeneratePathsToCheck(url, &paths);
EXPECT_EQ(paths.size(), 3);
EXPECT_TRUE(VectorContains(paths, "/saw-cgi/eBayISAPI.dll/"));
EXPECT_TRUE(VectorContains(paths, "/saw-cgi/"));
EXPECT_TRUE(VectorContains(paths, "/"));
}
TEST(SafeBrowsingUtilTest, FullHashCompare) {
GURL url("http://www.evil.com/phish.html");
SBFullHashResult full_hash;
base::SHA256HashString(url.host() + url.path(),
&full_hash.hash,
sizeof(SBFullHash));
std::vector<SBFullHashResult> full_hashes;
full_hashes.push_back(full_hash);
EXPECT_EQ(safe_browsing_util::CompareFullHashes(url, full_hashes), 0);
url = GURL("http://www.evil.com/okay_path.html");
EXPECT_EQ(safe_browsing_util::CompareFullHashes(url, full_hashes), -1);
}
// Checks the reading/writing code of the database information for a hostkey.
TEST(SafeBrowsing, HostInfo) {
// Test a simple case of adding a prefix from scratch.
SBEntry* entry = SBEntry::Create(SBEntry::ADD_PREFIX, 1);
entry->SetPrefixAt(0, 0x01000000);
entry->set_list_id(1);
entry->set_chunk_id(1);
SBHostInfo info;
info.AddPrefixes(entry);
entry->Destroy();
int list_id;
std::vector<SBFullHash> full_hashes;
full_hashes.push_back(CreateFullHash(0x01000000));
std::vector<SBPrefix> prefix_hits;
EXPECT_TRUE(info.Contains(full_hashes, &list_id, &prefix_hits));
// Test appending prefixes to an existing entry.
entry = SBEntry::Create(SBEntry::ADD_PREFIX, 2);
entry->SetPrefixAt(0, 0x02000000);
entry->SetPrefixAt(1, 0x02000001);
entry->set_list_id(1);
entry->set_chunk_id(2);
info.AddPrefixes(entry);
entry->Destroy();
full_hashes.clear();
full_hashes.push_back(CreateFullHash(0x01000000));
EXPECT_TRUE(info.Contains(full_hashes, &list_id, &prefix_hits));
full_hashes.clear();
full_hashes.push_back(CreateFullHash(0x02000000));
EXPECT_TRUE(info.Contains(full_hashes, &list_id, &prefix_hits));
full_hashes.clear();
full_hashes.push_back(CreateFullHash(0x02000001));
EXPECT_TRUE(info.Contains(full_hashes, &list_id, &prefix_hits));
// Test removing the entire first entry.
entry = SBEntry::Create(SBEntry::SUB_PREFIX, 0);
entry->set_list_id(1);
entry->set_chunk_id(1);
info.RemovePrefixes(entry, false);
entry->Destroy();
full_hashes.clear();
full_hashes.push_back(CreateFullHash(0x01000000));
EXPECT_FALSE(info.Contains(full_hashes, &list_id, &prefix_hits));
full_hashes.clear();
full_hashes.push_back(CreateFullHash(0x02000000));
EXPECT_TRUE(info.Contains(full_hashes, &list_id, &prefix_hits));
full_hashes.clear();
full_hashes.push_back(CreateFullHash(0x02000001));
EXPECT_TRUE(info.Contains(full_hashes, &list_id, &prefix_hits));
// Test removing one prefix from the second entry.
entry = SBEntry::Create(SBEntry::SUB_PREFIX, 1);
entry->SetPrefixAt(0,0x02000000);
entry->SetChunkIdAtPrefix(0, 2);
entry->set_list_id(1);
info.RemovePrefixes(entry, false);
entry->Destroy();
full_hashes.clear();
full_hashes.push_back(CreateFullHash(0x02000000));
EXPECT_FALSE(info.Contains(full_hashes, &list_id, &prefix_hits));
full_hashes.clear();
full_hashes.push_back(CreateFullHash(0x02000001));
EXPECT_TRUE(info.Contains(full_hashes, &list_id, &prefix_hits));
// Test adding a sub that specifies a prefix before the add.
entry = SBEntry::Create(SBEntry::SUB_PREFIX, 1);
entry->SetPrefixAt(0, 0x1000);
entry->SetChunkIdAtPrefix(0, 100);
entry->set_list_id(1);
info.RemovePrefixes(entry, true);
entry->Destroy();
// Make sure we don't get a match from a sub.
full_hashes.clear();
full_hashes.push_back(CreateFullHash(0x1000));
EXPECT_FALSE(info.Contains(full_hashes, &list_id, &prefix_hits));
// Now add the prefixes.
entry = SBEntry::Create(SBEntry::ADD_PREFIX, 3);
entry->SetPrefixAt(0, 0x10000);
entry->SetPrefixAt(1, 0x1000);
entry->SetPrefixAt(2, 0x100000);
entry->set_list_id(1);
entry->set_chunk_id(100);
info.AddPrefixes(entry);
entry->Destroy();
full_hashes.clear();
full_hashes.push_back(CreateFullHash(0x10000));
EXPECT_TRUE(info.Contains(full_hashes, &list_id, &prefix_hits));
full_hashes.clear();
full_hashes.push_back(CreateFullHash(0x1000));
EXPECT_FALSE(info.Contains(full_hashes, &list_id, &prefix_hits));
full_hashes.clear();
full_hashes.push_back(CreateFullHash(0x100000));
EXPECT_TRUE(info.Contains(full_hashes, &list_id, &prefix_hits));
// Now try adding a sub that deletes all prefixes from the chunk.
entry = SBEntry::Create(SBEntry::SUB_PREFIX, 0);
entry->set_list_id(1);
entry->set_chunk_id(100);
info.RemovePrefixes(entry, true);
entry->Destroy();
full_hashes.clear();
full_hashes.push_back(CreateFullHash(0x10000));
EXPECT_FALSE(info.Contains(full_hashes, &list_id, &prefix_hits));
full_hashes.clear();
full_hashes.push_back(CreateFullHash(0x100000));
EXPECT_FALSE(info.Contains(full_hashes, &list_id, &prefix_hits));
// Add a sub for all prefixes before the add comes.
entry = SBEntry::Create(SBEntry::SUB_PREFIX, 0);
entry->set_list_id(1);
entry->set_chunk_id(200);
info.RemovePrefixes(entry, true);
entry->Destroy();
// Now add the prefixes.
entry = SBEntry::Create(SBEntry::ADD_PREFIX, 3);
entry->SetPrefixAt(0, 0x2000);
entry->SetPrefixAt(1, 0x20000);
entry->SetPrefixAt(2, 0x200000);
entry->set_list_id(1);
entry->set_chunk_id(200);
info.AddPrefixes(entry);
entry->Destroy();
// None of the prefixes should be found.
full_hashes.clear();
full_hashes.push_back(CreateFullHash(0x2000));
full_hashes.push_back(CreateFullHash(0x20000));
full_hashes.push_back(CreateFullHash(0x200000));
EXPECT_FALSE(info.Contains(full_hashes, &list_id, &prefix_hits));
}
// Checks that if we have a hostname blacklisted and we get a sub prefix, the
// hostname remains blacklisted.
TEST(SafeBrowsing, HostInfo2) {
// Blacklist the entire hostname.
SBEntry* entry = SBEntry::Create(SBEntry::ADD_PREFIX, 0);
entry->set_list_id(1);
entry->set_chunk_id(1);
SBHostInfo info;
info.AddPrefixes(entry);
entry->Destroy();
int list_id;
std::vector<SBFullHash> full_hashes;
full_hashes.push_back(CreateFullHash(0x01000000));
std::vector<SBPrefix> prefix_hits;
EXPECT_TRUE(info.Contains(full_hashes, &list_id, &prefix_hits));
// Now add a sub prefix.
entry = SBEntry::Create(SBEntry::SUB_PREFIX, 1);
entry->SetPrefixAt(0, 0x02000000);
entry->SetChunkIdAtPrefix(0, 2);
entry->set_list_id(1);
info.RemovePrefixes(entry, true);
entry->Destroy();
// Any prefix except the one removed should still be blocked.
EXPECT_TRUE(info.Contains(full_hashes, &list_id, &prefix_hits));
}
<commit_msg>Take out uneeded comment (and test public Rietveld instance!).<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/logging.h"
#include "base/sha2.h"
#include "chrome/browser/safe_browsing/safe_browsing_util.h"
#include "googleurl/src/gurl.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
bool VectorContains(const std::vector<std::string>& data,
const std::string& str) {
for (size_t i = 0; i < data.size(); ++i) {
if (data[i] == str)
return true;
}
return false;
}
SBFullHash CreateFullHash(SBPrefix prefix) {
SBFullHash result;
memset(&result, 0, sizeof(result));
memcpy(&result, &prefix, sizeof(result));
return result;
}
}
// Tests that we generate the required host/path combinations for testing
// according to the Safe Browsing spec.
// See section 6.2 in
// http://code.google.com/p/google-safe-browsing/wiki/Protocolv2Spec.
TEST(SafeBrowsingUtilTest, UrlParsing) {
std::vector<std::string> hosts, paths;
GURL url("http://a.b.c/1/2.html?param=1");
safe_browsing_util::GenerateHostsToCheck(url, &hosts);
safe_browsing_util::GeneratePathsToCheck(url, &paths);
EXPECT_EQ(hosts.size(), 2);
EXPECT_EQ(paths.size(), 4);
EXPECT_EQ(hosts[0], "b.c");
EXPECT_EQ(hosts[1], "a.b.c");
EXPECT_TRUE(VectorContains(paths, "/1/2.html?param=1"));
EXPECT_TRUE(VectorContains(paths, "/1/2.html"));
EXPECT_TRUE(VectorContains(paths, "/1/"));
EXPECT_TRUE(VectorContains(paths, "/"));
url = GURL("http://a.b.c.d.e.f.g/1.html");
safe_browsing_util::GenerateHostsToCheck(url, &hosts);
safe_browsing_util::GeneratePathsToCheck(url, &paths);
EXPECT_EQ(hosts.size(), 5);
EXPECT_EQ(paths.size(), 2);
EXPECT_EQ(hosts[0], "f.g");
EXPECT_EQ(hosts[1], "e.f.g");
EXPECT_EQ(hosts[2], "d.e.f.g");
EXPECT_EQ(hosts[3], "c.d.e.f.g");
EXPECT_EQ(hosts[4], "a.b.c.d.e.f.g");
EXPECT_TRUE(VectorContains(paths, "/1.html"));
EXPECT_TRUE(VectorContains(paths, "/"));
url = GURL("http://a.b/saw-cgi/eBayISAPI.dll/");
safe_browsing_util::GeneratePathsToCheck(url, &paths);
EXPECT_EQ(paths.size(), 3);
EXPECT_TRUE(VectorContains(paths, "/saw-cgi/eBayISAPI.dll/"));
EXPECT_TRUE(VectorContains(paths, "/saw-cgi/"));
EXPECT_TRUE(VectorContains(paths, "/"));
}
TEST(SafeBrowsingUtilTest, FullHashCompare) {
GURL url("http://www.evil.com/phish.html");
SBFullHashResult full_hash;
base::SHA256HashString(url.host() + url.path(),
&full_hash.hash,
sizeof(SBFullHash));
std::vector<SBFullHashResult> full_hashes;
full_hashes.push_back(full_hash);
EXPECT_EQ(safe_browsing_util::CompareFullHashes(url, full_hashes), 0);
url = GURL("http://www.evil.com/okay_path.html");
EXPECT_EQ(safe_browsing_util::CompareFullHashes(url, full_hashes), -1);
}
// Checks the reading/writing code of the database information for a hostkey.
TEST(SafeBrowsing, HostInfo) {
// Test a simple case of adding a prefix from scratch.
SBEntry* entry = SBEntry::Create(SBEntry::ADD_PREFIX, 1);
entry->SetPrefixAt(0, 0x01000000);
entry->set_list_id(1);
entry->set_chunk_id(1);
SBHostInfo info;
info.AddPrefixes(entry);
entry->Destroy();
int list_id;
std::vector<SBFullHash> full_hashes;
full_hashes.push_back(CreateFullHash(0x01000000));
std::vector<SBPrefix> prefix_hits;
EXPECT_TRUE(info.Contains(full_hashes, &list_id, &prefix_hits));
// Test appending prefixes to an existing entry.
entry = SBEntry::Create(SBEntry::ADD_PREFIX, 2);
entry->SetPrefixAt(0, 0x02000000);
entry->SetPrefixAt(1, 0x02000001);
entry->set_list_id(1);
entry->set_chunk_id(2);
info.AddPrefixes(entry);
entry->Destroy();
full_hashes.clear();
full_hashes.push_back(CreateFullHash(0x01000000));
EXPECT_TRUE(info.Contains(full_hashes, &list_id, &prefix_hits));
full_hashes.clear();
full_hashes.push_back(CreateFullHash(0x02000000));
EXPECT_TRUE(info.Contains(full_hashes, &list_id, &prefix_hits));
full_hashes.clear();
full_hashes.push_back(CreateFullHash(0x02000001));
EXPECT_TRUE(info.Contains(full_hashes, &list_id, &prefix_hits));
// Test removing the entire first entry.
entry = SBEntry::Create(SBEntry::SUB_PREFIX, 0);
entry->set_list_id(1);
entry->set_chunk_id(1);
info.RemovePrefixes(entry, false);
entry->Destroy();
full_hashes.clear();
full_hashes.push_back(CreateFullHash(0x01000000));
EXPECT_FALSE(info.Contains(full_hashes, &list_id, &prefix_hits));
full_hashes.clear();
full_hashes.push_back(CreateFullHash(0x02000000));
EXPECT_TRUE(info.Contains(full_hashes, &list_id, &prefix_hits));
full_hashes.clear();
full_hashes.push_back(CreateFullHash(0x02000001));
EXPECT_TRUE(info.Contains(full_hashes, &list_id, &prefix_hits));
// Test removing one prefix from the second entry.
entry = SBEntry::Create(SBEntry::SUB_PREFIX, 1);
entry->SetPrefixAt(0,0x02000000);
entry->SetChunkIdAtPrefix(0, 2);
entry->set_list_id(1);
info.RemovePrefixes(entry, false);
entry->Destroy();
full_hashes.clear();
full_hashes.push_back(CreateFullHash(0x02000000));
EXPECT_FALSE(info.Contains(full_hashes, &list_id, &prefix_hits));
full_hashes.clear();
full_hashes.push_back(CreateFullHash(0x02000001));
EXPECT_TRUE(info.Contains(full_hashes, &list_id, &prefix_hits));
// Test adding a sub that specifies a prefix before the add.
entry = SBEntry::Create(SBEntry::SUB_PREFIX, 1);
entry->SetPrefixAt(0, 0x1000);
entry->SetChunkIdAtPrefix(0, 100);
entry->set_list_id(1);
info.RemovePrefixes(entry, true);
entry->Destroy();
// Make sure we don't get a match from a sub.
full_hashes.clear();
full_hashes.push_back(CreateFullHash(0x1000));
EXPECT_FALSE(info.Contains(full_hashes, &list_id, &prefix_hits));
// Now add the prefixes.
entry = SBEntry::Create(SBEntry::ADD_PREFIX, 3);
entry->SetPrefixAt(0, 0x10000);
entry->SetPrefixAt(1, 0x1000);
entry->SetPrefixAt(2, 0x100000);
entry->set_list_id(1);
entry->set_chunk_id(100);
info.AddPrefixes(entry);
entry->Destroy();
full_hashes.clear();
full_hashes.push_back(CreateFullHash(0x10000));
EXPECT_TRUE(info.Contains(full_hashes, &list_id, &prefix_hits));
full_hashes.clear();
full_hashes.push_back(CreateFullHash(0x1000));
EXPECT_FALSE(info.Contains(full_hashes, &list_id, &prefix_hits));
full_hashes.clear();
full_hashes.push_back(CreateFullHash(0x100000));
EXPECT_TRUE(info.Contains(full_hashes, &list_id, &prefix_hits));
// Now try adding a sub that deletes all prefixes from the chunk.
entry = SBEntry::Create(SBEntry::SUB_PREFIX, 0);
entry->set_list_id(1);
entry->set_chunk_id(100);
info.RemovePrefixes(entry, true);
entry->Destroy();
full_hashes.clear();
full_hashes.push_back(CreateFullHash(0x10000));
EXPECT_FALSE(info.Contains(full_hashes, &list_id, &prefix_hits));
full_hashes.clear();
full_hashes.push_back(CreateFullHash(0x100000));
EXPECT_FALSE(info.Contains(full_hashes, &list_id, &prefix_hits));
// Add a sub for all prefixes before the add comes.
entry = SBEntry::Create(SBEntry::SUB_PREFIX, 0);
entry->set_list_id(1);
entry->set_chunk_id(200);
info.RemovePrefixes(entry, true);
entry->Destroy();
// Now add the prefixes.
entry = SBEntry::Create(SBEntry::ADD_PREFIX, 3);
entry->SetPrefixAt(0, 0x2000);
entry->SetPrefixAt(1, 0x20000);
entry->SetPrefixAt(2, 0x200000);
entry->set_list_id(1);
entry->set_chunk_id(200);
info.AddPrefixes(entry);
entry->Destroy();
// None of the prefixes should be found.
full_hashes.clear();
full_hashes.push_back(CreateFullHash(0x2000));
full_hashes.push_back(CreateFullHash(0x20000));
full_hashes.push_back(CreateFullHash(0x200000));
EXPECT_FALSE(info.Contains(full_hashes, &list_id, &prefix_hits));
}
// Checks that if we have a hostname blacklisted and we get a sub prefix, the
// hostname remains blacklisted.
TEST(SafeBrowsing, HostInfo2) {
// Blacklist the entire hostname.
SBEntry* entry = SBEntry::Create(SBEntry::ADD_PREFIX, 0);
entry->set_list_id(1);
entry->set_chunk_id(1);
SBHostInfo info;
info.AddPrefixes(entry);
entry->Destroy();
int list_id;
std::vector<SBFullHash> full_hashes;
full_hashes.push_back(CreateFullHash(0x01000000));
std::vector<SBPrefix> prefix_hits;
EXPECT_TRUE(info.Contains(full_hashes, &list_id, &prefix_hits));
// Now add a sub prefix.
entry = SBEntry::Create(SBEntry::SUB_PREFIX, 1);
entry->SetPrefixAt(0, 0x02000000);
entry->SetChunkIdAtPrefix(0, 2);
entry->set_list_id(1);
info.RemovePrefixes(entry, true);
entry->Destroy();
// Any prefix except the one removed should still be blocked.
EXPECT_TRUE(info.Contains(full_hashes, &list_id, &prefix_hits));
}
<|endoftext|> |
<commit_before>// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#include "UnrealEnginePythonPrivatePCH.h"
void unreal_engine_init_py_module();
#if defined(UNREAL_ENGINE_PYTHON_ON_LINUX)
const char *ue4_module_options = "linux_global_symbols";
#endif
#if PY_MAJOR_VERSION < 3
char *PyUnicode_AsUTF8(PyObject *py_str) {
if (PyUnicode_Check(py_str)) {
PyObject *unicode = PyUnicode_AsUTF8String(py_str);
if (unicode) {
return PyString_AsString(unicode);
}
// just a hack to avoid crashes
return (char *)"<invalid_string>";
}
return PyString_AsString(py_str);
}
int PyGILState_Check() {
PyThreadState * tstate = _PyThreadState_Current;
return tstate && (tstate == PyGILState_GetThisThreadState());
}
#endif
bool PyUnicodeOrString_Check(PyObject *py_obj) {
if (PyUnicode_Check(py_obj)) {
return true;
}
#if PY_MAJOR_VERSION < 3
else if (PyString_Check(py_obj)) {
return true;
}
#endif
return false;
}
#define LOCTEXT_NAMESPACE "FUnrealEnginePythonModule"
void FUnrealEnginePythonModule::PythonGILRelease() {
#if defined(UEPY_THREADING)
if (PyGILState_Check() == 1) {
ue_python_gil = PyEval_SaveThread();
}
#endif
}
bool FUnrealEnginePythonModule::PythonGILAcquire() {
#if defined(UEPY_THREADING)
if (PyGILState_Check() == 0) {
PyEval_RestoreThread((PyThreadState *)ue_python_gil);
return true;
}
return false;
#endif
return true;
}
static void UESetupPythonInterpeter(bool verbose) {
unreal_engine_init_py_module();
PyObject *py_sys = PyImport_ImportModule("sys");
PyObject *py_sys_dict = PyModule_GetDict(py_sys);
PyObject *py_path = PyDict_GetItemString(py_sys_dict, "path");
char *zip_path = TCHAR_TO_UTF8(*FPaths::Combine(*FPaths::GameContentDir(), UTF8_TO_TCHAR("ue_python.zip")));
PyObject *py_zip_path = PyUnicode_FromString(zip_path);
PyList_Insert(py_path, 0, py_zip_path);
char *scripts_path = TCHAR_TO_UTF8(*FPaths::Combine(*FPaths::GameContentDir(), UTF8_TO_TCHAR("Scripts")));
PyObject *py_scripts_path = PyUnicode_FromString(scripts_path);
PyList_Insert(py_path, 0, py_scripts_path);
if (verbose) {
UE_LOG(LogPython, Log, TEXT("Python VM initialized: %s"), UTF8_TO_TCHAR(Py_GetVersion()));
UE_LOG(LogPython, Log, TEXT("Python Scripts search path: %s"), UTF8_TO_TCHAR(scripts_path));
}
}
void FUnrealEnginePythonModule::StartupModule()
{
// This code will execute after your module is loaded into memory; the exact timing is specified in the .uplugin file per-module
Py_Initialize();
#if PY_MAJOR_VERSION >= 3
wchar_t *argv[] = { UTF8_TO_TCHAR("UnrealEngine"), NULL };
#else
char *argv[] = { (char *)"UnrealEngine", NULL };
#endif
PySys_SetArgv(1, argv);
PyEval_InitThreads();
UESetupPythonInterpeter(true);
PyObject *main_module = PyImport_AddModule("__main__");
main_dict = PyModule_GetDict(main_module);
local_dict = main_dict;// PyDict_New();
if (PyImport_ImportModule("ue_site")) {
UE_LOG(LogPython, Log, TEXT("ue_site Python module successfully imported"));
}
else {
// TODO gracefully manage the error
unreal_engine_py_log_error();
}
#if WITH_EDITOR
// register commands (after importing ue_site)
FPythonSlateCommands::Register();
// apply extenders
FPythonSlateCommands::ApplyPythonExtenders();
#endif
// release the GIL
PythonGILRelease();
}
void FUnrealEnginePythonModule::ShutdownModule()
{
// This function may be called during shutdown to clean up your module. For modules that support dynamic reloading,
// we call this function before unloading the module.
UE_LOG(LogPython, Log, TEXT("Goodbye Python"));
PythonGILAcquire();
Py_Finalize();
}
void FUnrealEnginePythonModule::RunString(char *str) {
FScopePythonGIL gil;
PyObject *eval_ret = PyRun_String(str, Py_file_input, (PyObject *)main_dict, (PyObject *)local_dict);
if (!eval_ret) {
unreal_engine_py_log_error();
return;
}
Py_DECREF(eval_ret);
}
void FUnrealEnginePythonModule::RunFile(char *filename) {
FScopePythonGIL gil;
char *full_path = filename;
if (!FPaths::FileExists(filename))
{
full_path = TCHAR_TO_UTF8(*FPaths::Combine(*FPaths::GameContentDir(), UTF8_TO_TCHAR("Scripts"), *FString("/"), UTF8_TO_TCHAR(filename)));
}
#if PY_MAJOR_VERSION >= 3
FILE *fd = nullptr;
#if PLATFORM_WINDOWS
if (fopen_s(&fd, full_path, "r") != 0) {
UE_LOG(LogPython, Error, TEXT("Unable to open file %s"), UTF8_TO_TCHAR(full_path));
return;
}
#else
fd = fopen(full_path, "r");
if (!fd) {
UE_LOG(LogPython, Error, TEXT("Unable to open file %s"), UTF8_TO_TCHAR(full_path));
return;
}
#endif
PyObject *eval_ret = PyRun_File(fd, full_path, Py_file_input, (PyObject *)main_dict, (PyObject *)local_dict);
fclose(fd);
if (!eval_ret) {
unreal_engine_py_log_error();
return;
}
Py_DECREF(eval_ret);
#else
// damn, this is horrible, but it is the only way i found to avoid the CRT error :(
FString command = FString::Printf(TEXT("execfile(\"%s\")"), UTF8_TO_TCHAR(full_path));
PyObject *eval_ret = PyRun_String(TCHAR_TO_UTF8(*command), Py_file_input, (PyObject *)main_dict, (PyObject *)local_dict);
if (!eval_ret) {
unreal_engine_py_log_error();
return;
}
#endif
}
// run a python script in a new sub interpreter (useful for unit tests)
void FUnrealEnginePythonModule::RunFileSandboxed(char *filename) {
FScopePythonGIL gil;
char *full_path = filename;
if (!FPaths::FileExists(filename))
{
full_path = TCHAR_TO_UTF8(*FPaths::Combine(*FPaths::GameContentDir(), UTF8_TO_TCHAR("Scripts"), *FString("/"), UTF8_TO_TCHAR(filename)));
}
#if PY_MAJOR_VERSION >= 3
FILE *fd = nullptr;
#if PLATFORM_WINDOWS
if (fopen_s(&fd, full_path, "r") != 0) {
UE_LOG(LogPython, Error, TEXT("Unable to open file %s"), UTF8_TO_TCHAR(full_path));
return;
}
#else
fd = fopen(full_path, "r");
if (!fd) {
UE_LOG(LogPython, Error, TEXT("Unable to open file %s"), UTF8_TO_TCHAR(full_path));
return;
}
#endif
PyThreadState *_main = PyThreadState_Get();
PyThreadState *py_new_state = Py_NewInterpreter();
if (!py_new_state) {
UE_LOG(LogPython, Error, TEXT("Unable to create new Python interpreter"));
return;
}
PyThreadState_Swap(nullptr);
PyThreadState_Swap(py_new_state);
UESetupPythonInterpeter(false);
PyObject *m = PyImport_AddModule("__main__");
if (m == NULL) {
UE_LOG(LogPython, Error, TEXT("Unable to create new global dict"));
Py_EndInterpreter(py_new_state);
PyThreadState_Swap(_main);
return;
}
PyObject *global_dict = PyModule_GetDict(m);
PyObject *eval_ret = PyRun_File(fd, full_path, Py_file_input, global_dict, global_dict);
fclose(fd);
if (!eval_ret) {
unreal_engine_py_log_error();
Py_EndInterpreter(py_new_state);
PyThreadState_Swap(_main);
return;
}
Py_DECREF(eval_ret);
#else
// damn, this is horrible, but it is the only way i found to avoid the CRT error :(
FString command = FString::Printf(TEXT("execfile(\"%s\")"), UTF8_TO_TCHAR(full_path));
PyObject *eval_ret = PyRun_String(TCHAR_TO_UTF8(*command), Py_file_input, global_dict, global_dict);
if (!eval_ret) {
unreal_engine_py_log_error();
Py_EndInterpreter(py_new_state);
PyThreadState_Swap(_main);
return;
}
#endif
Py_EndInterpreter(py_new_state);
PyThreadState_Swap(_main);
}
#undef LOCTEXT_NAMESPACE
IMPLEMENT_MODULE(FUnrealEnginePythonModule, UnrealEnginePython)
<commit_msg>Fixed the build on linux python2.7<commit_after>// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#include "UnrealEnginePythonPrivatePCH.h"
void unreal_engine_init_py_module();
#if defined(UNREAL_ENGINE_PYTHON_ON_LINUX)
const char *ue4_module_options = "linux_global_symbols";
#endif
#if PY_MAJOR_VERSION < 3
char *PyUnicode_AsUTF8(PyObject *py_str) {
if (PyUnicode_Check(py_str)) {
PyObject *unicode = PyUnicode_AsUTF8String(py_str);
if (unicode) {
return PyString_AsString(unicode);
}
// just a hack to avoid crashes
return (char *)"<invalid_string>";
}
return PyString_AsString(py_str);
}
int PyGILState_Check() {
PyThreadState * tstate = _PyThreadState_Current;
return tstate && (tstate == PyGILState_GetThisThreadState());
}
#endif
bool PyUnicodeOrString_Check(PyObject *py_obj) {
if (PyUnicode_Check(py_obj)) {
return true;
}
#if PY_MAJOR_VERSION < 3
else if (PyString_Check(py_obj)) {
return true;
}
#endif
return false;
}
#define LOCTEXT_NAMESPACE "FUnrealEnginePythonModule"
void FUnrealEnginePythonModule::PythonGILRelease() {
#if defined(UEPY_THREADING)
if (PyGILState_Check() == 1) {
ue_python_gil = PyEval_SaveThread();
}
#endif
}
bool FUnrealEnginePythonModule::PythonGILAcquire() {
#if defined(UEPY_THREADING)
if (PyGILState_Check() == 0) {
PyEval_RestoreThread((PyThreadState *)ue_python_gil);
return true;
}
return false;
#endif
return true;
}
static void UESetupPythonInterpeter(bool verbose) {
unreal_engine_init_py_module();
PyObject *py_sys = PyImport_ImportModule("sys");
PyObject *py_sys_dict = PyModule_GetDict(py_sys);
PyObject *py_path = PyDict_GetItemString(py_sys_dict, "path");
char *zip_path = TCHAR_TO_UTF8(*FPaths::Combine(*FPaths::GameContentDir(), UTF8_TO_TCHAR("ue_python.zip")));
PyObject *py_zip_path = PyUnicode_FromString(zip_path);
PyList_Insert(py_path, 0, py_zip_path);
char *scripts_path = TCHAR_TO_UTF8(*FPaths::Combine(*FPaths::GameContentDir(), UTF8_TO_TCHAR("Scripts")));
PyObject *py_scripts_path = PyUnicode_FromString(scripts_path);
PyList_Insert(py_path, 0, py_scripts_path);
if (verbose) {
UE_LOG(LogPython, Log, TEXT("Python VM initialized: %s"), UTF8_TO_TCHAR(Py_GetVersion()));
UE_LOG(LogPython, Log, TEXT("Python Scripts search path: %s"), UTF8_TO_TCHAR(scripts_path));
}
}
void FUnrealEnginePythonModule::StartupModule()
{
// This code will execute after your module is loaded into memory; the exact timing is specified in the .uplugin file per-module
Py_Initialize();
#if PY_MAJOR_VERSION >= 3
wchar_t *argv[] = { UTF8_TO_TCHAR("UnrealEngine"), NULL };
#else
char *argv[] = { (char *)"UnrealEngine", NULL };
#endif
PySys_SetArgv(1, argv);
PyEval_InitThreads();
UESetupPythonInterpeter(true);
PyObject *main_module = PyImport_AddModule("__main__");
main_dict = PyModule_GetDict(main_module);
local_dict = main_dict;// PyDict_New();
if (PyImport_ImportModule("ue_site")) {
UE_LOG(LogPython, Log, TEXT("ue_site Python module successfully imported"));
}
else {
// TODO gracefully manage the error
unreal_engine_py_log_error();
}
#if WITH_EDITOR
// register commands (after importing ue_site)
FPythonSlateCommands::Register();
// apply extenders
FPythonSlateCommands::ApplyPythonExtenders();
#endif
// release the GIL
PythonGILRelease();
}
void FUnrealEnginePythonModule::ShutdownModule()
{
// This function may be called during shutdown to clean up your module. For modules that support dynamic reloading,
// we call this function before unloading the module.
UE_LOG(LogPython, Log, TEXT("Goodbye Python"));
PythonGILAcquire();
Py_Finalize();
}
void FUnrealEnginePythonModule::RunString(char *str) {
FScopePythonGIL gil;
PyObject *eval_ret = PyRun_String(str, Py_file_input, (PyObject *)main_dict, (PyObject *)local_dict);
if (!eval_ret) {
unreal_engine_py_log_error();
return;
}
Py_DECREF(eval_ret);
}
void FUnrealEnginePythonModule::RunFile(char *filename) {
FScopePythonGIL gil;
char *full_path = filename;
if (!FPaths::FileExists(filename))
{
full_path = TCHAR_TO_UTF8(*FPaths::Combine(*FPaths::GameContentDir(), UTF8_TO_TCHAR("Scripts"), *FString("/"), UTF8_TO_TCHAR(filename)));
}
#if PY_MAJOR_VERSION >= 3
FILE *fd = nullptr;
#if PLATFORM_WINDOWS
if (fopen_s(&fd, full_path, "r") != 0) {
UE_LOG(LogPython, Error, TEXT("Unable to open file %s"), UTF8_TO_TCHAR(full_path));
return;
}
#else
fd = fopen(full_path, "r");
if (!fd) {
UE_LOG(LogPython, Error, TEXT("Unable to open file %s"), UTF8_TO_TCHAR(full_path));
return;
}
#endif
PyObject *eval_ret = PyRun_File(fd, full_path, Py_file_input, (PyObject *)main_dict, (PyObject *)local_dict);
fclose(fd);
if (!eval_ret) {
unreal_engine_py_log_error();
return;
}
Py_DECREF(eval_ret);
#else
// damn, this is horrible, but it is the only way i found to avoid the CRT error :(
FString command = FString::Printf(TEXT("execfile(\"%s\")"), UTF8_TO_TCHAR(full_path));
PyObject *eval_ret = PyRun_String(TCHAR_TO_UTF8(*command), Py_file_input, (PyObject *)main_dict, (PyObject *)local_dict);
if (!eval_ret) {
unreal_engine_py_log_error();
return;
}
#endif
}
// run a python script in a new sub interpreter (useful for unit tests)
void FUnrealEnginePythonModule::RunFileSandboxed(char *filename) {
FScopePythonGIL gil;
char *full_path = filename;
if (!FPaths::FileExists(filename))
{
full_path = TCHAR_TO_UTF8(*FPaths::Combine(*FPaths::GameContentDir(), UTF8_TO_TCHAR("Scripts"), *FString("/"), UTF8_TO_TCHAR(filename)));
}
PyThreadState *_main = PyThreadState_Get();
PyThreadState *py_new_state = Py_NewInterpreter();
if (!py_new_state) {
UE_LOG(LogPython, Error, TEXT("Unable to create new Python interpreter"));
return;
}
PyThreadState_Swap(nullptr);
PyThreadState_Swap(py_new_state);
UESetupPythonInterpeter(false);
PyObject *m = PyImport_AddModule("__main__");
if (m == NULL) {
UE_LOG(LogPython, Error, TEXT("Unable to create new global dict"));
Py_EndInterpreter(py_new_state);
PyThreadState_Swap(_main);
return;
}
PyObject *global_dict = PyModule_GetDict(m);
#if PY_MAJOR_VERSION >= 3
FILE *fd = nullptr;
#if PLATFORM_WINDOWS
if (fopen_s(&fd, full_path, "r") != 0) {
UE_LOG(LogPython, Error, TEXT("Unable to open file %s"), UTF8_TO_TCHAR(full_path));
return;
}
#else
fd = fopen(full_path, "r");
if (!fd) {
UE_LOG(LogPython, Error, TEXT("Unable to open file %s"), UTF8_TO_TCHAR(full_path));
return;
}
#endif
PyObject *eval_ret = PyRun_File(fd, full_path, Py_file_input, global_dict, global_dict);
fclose(fd);
if (!eval_ret) {
unreal_engine_py_log_error();
Py_EndInterpreter(py_new_state);
PyThreadState_Swap(_main);
return;
}
Py_DECREF(eval_ret);
#else
// damn, this is horrible, but it is the only way i found to avoid the CRT error :(
FString command = FString::Printf(TEXT("execfile(\"%s\")"), UTF8_TO_TCHAR(full_path));
PyObject *eval_ret = PyRun_String(TCHAR_TO_UTF8(*command), Py_file_input, global_dict, global_dict);
if (!eval_ret) {
unreal_engine_py_log_error();
Py_EndInterpreter(py_new_state);
PyThreadState_Swap(_main);
return;
}
#endif
Py_EndInterpreter(py_new_state);
PyThreadState_Swap(_main);
}
#undef LOCTEXT_NAMESPACE
IMPLEMENT_MODULE(FUnrealEnginePythonModule, UnrealEnginePython)
<|endoftext|> |
<commit_before>#include <chain.hpp>
#include <vector>
#include <list>
#include <string>
#include <vector>
#include <iterator>
#include <utility>
#include "catch.hpp"
using iter::chain;
using Vec = const std::vector<char>;
TEST_CASE("chain three strings", "[chain]") {
std::string s1{"abc"};
std::string s2{"mno"};
std::string s3{"xyz"};
auto ch = chain(s1, s2, s3);
Vec v(std::begin(ch), std::end(ch));
Vec vc{'a','b','c','m','n','o','x','y','z'};
REQUIRE( v == vc );
}
TEST_CASE("chain with different container types", "[chain]") {
std::string s1{"abc"};
std::list<char> li{'m', 'n', 'o'};
std::vector<char> vec{'x', 'y', 'z'};
auto ch = chain(s1, li, vec);
Vec v(std::begin(ch), std::end(ch));
Vec vc{'a','b','c','m','n','o','x','y','z'};
REQUIRE( v == vc );
}
TEST_CASE("chain handles empty containers", "[chain]") {
std::string emp;
std::string a{"a"};
std::string b{"b"};
std::string c{"c"};
Vec vc{'a', 'b', 'c'};
SECTION("Empty container at front") {
auto ch = chain(emp, a, b, c);
Vec v(std::begin(ch), std::end(ch));
REQUIRE( v == vc );
}
SECTION("Empty container at back") {
auto ch = chain(a, b, c, emp);
Vec v(std::begin(ch), std::end(ch));
REQUIRE( v == vc );
}
SECTION("Empty container in middle") {
auto ch = chain(a, emp, b, emp, c);
Vec v(std::begin(ch), std::end(ch));
REQUIRE( v == vc );
}
SECTION("Consecutive empty containers at front") {
auto ch = chain(emp, emp, a, b, c);
Vec v(std::begin(ch), std::end(ch));
REQUIRE( v == vc );
}
SECTION("Consecutive empty containers at back") {
auto ch = chain(a, b, c, emp, emp);
Vec v(std::begin(ch), std::end(ch));
REQUIRE( v == vc );
}
SECTION("Consecutive empty containers in middle") {
auto ch = chain(a, emp, emp, b, emp, emp, c);
Vec v(std::begin(ch), std::end(ch));
REQUIRE( v == vc );
}
}
<commit_msg>adds chain tests with only empty containers<commit_after>#include <chain.hpp>
#include <vector>
#include <list>
#include <string>
#include <vector>
#include <iterator>
#include <utility>
#include "catch.hpp"
using iter::chain;
using Vec = const std::vector<char>;
TEST_CASE("chain three strings", "[chain]") {
std::string s1{"abc"};
std::string s2{"mno"};
std::string s3{"xyz"};
auto ch = chain(s1, s2, s3);
Vec v(std::begin(ch), std::end(ch));
Vec vc{'a','b','c','m','n','o','x','y','z'};
REQUIRE( v == vc );
}
TEST_CASE("chain with different container types", "[chain]") {
std::string s1{"abc"};
std::list<char> li{'m', 'n', 'o'};
std::vector<char> vec{'x', 'y', 'z'};
auto ch = chain(s1, li, vec);
Vec v(std::begin(ch), std::end(ch));
Vec vc{'a','b','c','m','n','o','x','y','z'};
REQUIRE( v == vc );
}
TEST_CASE("chain handles empty containers", "[chain]") {
std::string emp;
std::string a{"a"};
std::string b{"b"};
std::string c{"c"};
Vec vc{'a', 'b', 'c'};
SECTION("Empty container at front") {
auto ch = chain(emp, a, b, c);
Vec v(std::begin(ch), std::end(ch));
REQUIRE( v == vc );
}
SECTION("Empty container at back") {
auto ch = chain(a, b, c, emp);
Vec v(std::begin(ch), std::end(ch));
REQUIRE( v == vc );
}
SECTION("Empty container in middle") {
auto ch = chain(a, emp, b, emp, c);
Vec v(std::begin(ch), std::end(ch));
REQUIRE( v == vc );
}
SECTION("Consecutive empty containers at front") {
auto ch = chain(emp, emp, a, b, c);
Vec v(std::begin(ch), std::end(ch));
REQUIRE( v == vc );
}
SECTION("Consecutive empty containers at back") {
auto ch = chain(a, b, c, emp, emp);
Vec v(std::begin(ch), std::end(ch));
REQUIRE( v == vc );
}
SECTION("Consecutive empty containers in middle") {
auto ch = chain(a, emp, emp, b, emp, emp, c);
Vec v(std::begin(ch), std::end(ch));
REQUIRE( v == vc );
}
}
TEST_CASE("chain with only empty containers", "[chain]") {
std::string emp{};
SECTION("one empty container") {
auto ch = chain(emp);
REQUIRE_FALSE( std::begin(ch) != std::end(ch) );
}
SECTION("two empty containers") {
auto ch = chain(emp, emp);
REQUIRE_FALSE( std::begin(ch) != std::end(ch) );
}
SECTION("three empty containers") {
auto ch = chain(emp, emp, emp);
REQUIRE_FALSE( std::begin(ch) != std::end(ch) );
}
}
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// Peloton
//
// main.cpp
//
// Identification: src/backend/main/main.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <unistd.h>
#include "postgres/include/postgres.h"
#include "postgres/include/bootstrap/bootstrap.h"
#include "postgres/include/common/username.h"
#include "postgres/include/postmaster/postmaster.h"
#include "postgres/include/storage/barrier.h"
#include "postgres/include/storage/s_lock.h"
#include "postgres/include/storage/spin.h"
#include "postgres/include/tcop/tcopprot.h"
#include "postgres/include/utils/help_config.h"
#include "postgres/include/utils/memutils.h"
#include "postgres/include/utils/pg_locale.h"
#include "postgres/include/utils/ps_status.h"
const char *progname;
static void startup_hacks(const char *progname);
static void init_locale(int category, const char *locale);
static void help(const char *progname);
static void check_root(const char *progname);
/*
* Any Postgres server process begins execution here.
*/
int main(int argc, char *argv[]) {
bool do_check_root = true;
progname = "peloton";
// progname = get_progname(argv[0]);
/*
* Platform-specific startup hacks
*/
startup_hacks(progname);
/*
* Remember the physical location of the initially given argv[] array for
* possible use by ps display. On some platforms, the argv[] storage must
* be overwritten in order to set the process title for ps. In such cases
* save_ps_display_args makes and returns a new copy of the argv[] array.
*
* save_ps_display_args may also move the environment strings to make
* extra room. Therefore this should be done as early as possible during
* startup, to avoid entanglements with code that might save a getenv()
* result pointer.
*/
argv = save_ps_display_args(argc, argv);
/*
* If supported on the current platform, set up a handler to be called if
* the backend/postmaster crashes with a fatal signal or exception.
*/
#if defined(WIN32) && defined(HAVE_MINIDUMP_TYPE)
pgwin32_install_crashdump_handler();
#endif
/*
* Fire up essential subsystems: error and memory management
*
* Code after this point is allowed to use elog/ereport, though
* localization of messages may not work right away, and messages won't go
* anywhere but stderr until GUC settings get loaded.
*/
MemoryContextInit();
/*
* Set up locale information from environment. Note that LC_CTYPE and
* LC_COLLATE will be overridden later from pg_control if we are in an
* already-initialized database. We set them here so that they will be
* available to fill pg_control during initdb. LC_MESSAGES will get set
* later during GUC option processing, but we set it here to allow startup
* error messages to be localized.
*/
set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("postgres"));
init_locale(LC_COLLATE, "");
init_locale(LC_CTYPE, "");
#ifdef LC_MESSAGES
init_locale(LC_MESSAGES, "");
#endif
/*
* We keep these set to "C" always, except transiently in pg_locale.c; see
* that file for explanations.
*/
init_locale(LC_MONETARY, "C");
init_locale(LC_NUMERIC, "C");
init_locale(LC_TIME, "C");
/*
* Now that we have absorbed as much as we wish to from the locale
* environment, remove any LC_ALL setting, so that the environment
* variables installed by pg_perm_setlocale have force.
*/
unsetenv("LC_ALL");
/*
* Catch standard options before doing much else, in particular before we
* insist on not being root.
*/
if (argc > 1) {
if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0) {
help(progname);
exit(0);
}
if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0) {
puts("postgres (PostgreSQL) " PG_VERSION);
exit(0);
}
/*
* In addition to the above, we allow "--describe-config" and "-C var"
* to be called by root. This is reasonably safe since these are
* read-only activities. The -C case is important because pg_ctl may
* try to invoke it while still holding administrator privileges on
* Windows. Note that while -C can normally be in any argv position,
* if you wanna bypass the root check you gotta put it first. This
* reduces the risk that we might misinterpret some other mode's -C
* switch as being the postmaster/postgres one.
*/
if (strcmp(argv[1], "--describe-config") == 0)
do_check_root = false;
else if (argc > 2 && strcmp(argv[1], "-C") == 0)
do_check_root = false;
}
/*
* Make sure we are not running as root, unless it's safe for the selected
* option.
*/
if (do_check_root) check_root(progname);
/*
* Dispatch to one of various subprograms depending on first argument.
*/
#ifdef EXEC_BACKEND
if (argc > 1 && strncmp(argv[1], "--fork", 6) == 0)
SubPostmasterMain(argc, argv); /* does not return */
#endif
if (argc > 1 && strcmp(argv[1], "--boot") == 0)
AuxiliaryProcessMain(argc, argv); /* does not return */
else if (argc > 1 && strcmp(argv[1], "--describe-config") == 0)
GucInfoMain(); /* does not return */
else if (argc > 1 && strcmp(argv[1], "--single") == 0)
PostgresMain(argc, argv, NULL, /* no dbname */
strdup(get_user_name_or_exit(progname))); /* does not return */
else
PostmasterMain(argc, argv); /* does not return */
abort(); /* should not get here */
}
/*
* Place platform-specific startup hacks here. This is the right
* place to put code that must be executed early in the launch of any new
* server process. Note that this code will NOT be executed when a backend
* or sub-bootstrap process is forked, unless we are in a fork/exec
* environment (ie EXEC_BACKEND is defined).
*
* XXX The need for code here is proof that the platform in question
* is too brain-dead to provide a standard C execution environment
* without help. Avoid adding more here, if you can.
*/
static void startup_hacks(const char *progname __attribute__((unused))) {
/*
* Initialize dummy_spinlock, in case we are on a platform where we have
* to use the fallback implementation of pg_memory_barrier().
*/
SpinLockInit(&dummy_spinlock);
}
/*
* Make the initial permanent setting for a locale category. If that fails,
* perhaps due to LC_foo=invalid in the environment, use locale C. If even
* that fails, perhaps due to out-of-memory, the entire startup fails with it.
* When this returns, we are guaranteed to have a setting for the given
* category's environment variable.
*/
static void init_locale(int category, const char *locale) {
if (pg_perm_setlocale(category, locale) == NULL &&
pg_perm_setlocale(category, "C") == NULL)
elog(FATAL, "could not adopt C locale");
}
/*
* Help display should match the options accepted by PostmasterMain()
* and PostgresMain().
*
* XXX On Windows, non-ASCII localizations of these messages only display
* correctly if the console output code page covers the necessary characters.
* Messages emitted in write_console() do not exhibit this problem.
*/
static void help(const char *progname) {
std::string message = std::string(progname) + " is the PostgreSQL server.\n\n";
message +="Usage:\n " + std::string(progname) + " [OPTION]...\n\n";
message +="Options:\n";
message +=" -B NBUFFERS number of shared buffers\n";
message +=" -c NAME=VALUE set run-time parameter\n";
message +=" -C NAME print value of run-time parameter, then exit\n";
message +=" -d 1-5 debugging level\n";
message +=" -D DATADIR database directory\n";
message +=" -e use European date input format (DMY)\n";
message +=" -F turn fsync off\n";
message +=" -h HOSTNAME host name or IP address to listen on\n";
message +=" -i enable TCP/IP connections\n";
message +=" -k DIRECTORY Unix-domain socket location\n";
#ifdef USE_SSL
message +=" -l enable SSL connections\n";
#endif
message +=" -N MAX-CONNECT maximum number of allowed connections\n";
message +=" -o OPTIONS pass \"OPTIONS\" to each server process "
"(obsolete)\n";
message +=" -p PORT port number to listen on\n";
message +=" -s show statistics after each query\n";
message +=" -S WORK-MEM set amount of memory for sorts (in kB)\n";
message +=" -V, --version output version information, then exit\n";
message +=" --NAME=VALUE set run-time parameter\n";
message +=" --describe-config describe configuration parameters, then exit\n";
message +=" -?, --help show this help, then exit\n";
message +="\nDeveloper options:\n";
message +=" -f s|i|n|m|h forbid use of some plan types\n";
message +=" -n do not reinitialize shared memory after abnormal "
"exit\n";
message +=" -O allow system table structure changes\n";
message +=" -P disable system indexes\n";
message +=" -t pa|pl|ex show timings after each query\n";
message +=" -T send SIGSTOP to all backend processes if one "
"dies\n";
message +=" -W NUM wait NUM seconds to allow attach from a "
"debugger\n";
message +="\nOptions for single-user mode:\n";
message +=" --single selects single-user mode (must be first "
"argument)\n";
message +=" DBNAME database name (defaults to user name)\n";
message +=" -d 0-5 override debugging level\n";
message +=" -E echo statement before execution\n";
message +=" -j do not use newline as interactive query "
"delimiter\n";
message +=" -r FILENAME send stdout and stderr to given file\n";
message +="\nOptions for bootstrapping mode:\n";
message +=" --boot selects bootstrapping mode (must be first "
"argument)\n";
message +=" DBNAME database name (mandatory argument in "
"bootstrapping mode)\n";
message +=" -r FILENAME send stdout and stderr to given file\n";
message +=" -x NUM internal use\n";
message +="\nPlease read the documentation for the complete list of run-time\n"
"configuration settings and how to set them on the command line or in\n"
"the configuration file.\n\n"
"Report bugs to <[email protected]>.\n";
fprintf(stderr, "%s", message.c_str());
}
static void check_root(const char *progname) {
if (geteuid() == 0) {
write_stderr(
"\"root\" execution of the PostgreSQL server is not permitted.\n"
"The server must be started under an unprivileged user ID to prevent\n"
"possible system security compromise. See the documentation for\n"
"more information on how to properly start the server.\n");
exit(1);
}
/*
* Also make sure that real and effective uids are the same. Executing as
* a setuid program from a root shell is a security hole, since on many
* platforms a nefarious subroutine could setuid back to root if real uid
* is root. (Since nobody actually uses postgres as a setuid program,
* trying to actively fix this situation seems more trouble than it's
* worth; we'll just expend the effort to check for it.)
*/
if (getuid() != geteuid()) {
write_stderr("%s: real and effective user IDs must match\n", progname);
exit(1);
}
}
<commit_msg>Fix main<commit_after>//===----------------------------------------------------------------------===//
//
// Peloton
//
// main.cpp
//
// Identification: src/backend/main/main.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <unistd.h>
#include "postgres/include/postgres.h"
#include "postgres/include/bootstrap/bootstrap.h"
#include "postgres/include/common/username.h"
#include "postgres/include/postmaster/postmaster.h"
#include "postgres/include/storage/barrier.h"
#include "postgres/include/storage/s_lock.h"
#include "postgres/include/storage/spin.h"
#include "postgres/include/tcop/tcopprot.h"
#include "postgres/include/utils/help_config.h"
#include "postgres/include/utils/memutils.h"
#include "postgres/include/utils/pg_locale.h"
#include "postgres/include/utils/ps_status.h"
const char *progname;
static void startup_hacks(const char *progname);
static void init_locale(int category, const char *locale);
static void help(const char *progname);
static void check_root(const char *progname);
/*
* Any Postgres server process begins execution here.
*/
int main(int argc, char *argv[]) {
bool do_check_root = true;
progname = "peloton";
// progname = get_progname(argv[0]);
/*
* Platform-specific startup hacks
*/
startup_hacks(progname);
/*
* Remember the physical location of the initially given argv[] array for
* possible use by ps display. On some platforms, the argv[] storage must
* be overwritten in order to set the process title for ps. In such cases
* save_ps_display_args makes and returns a new copy of the argv[] array.
*
* save_ps_display_args may also move the environment strings to make
* extra room. Therefore this should be done as early as possible during
* startup, to avoid entanglements with code that might save a getenv()
* result pointer.
*/
argv = save_ps_display_args(argc, argv);
/*
* If supported on the current platform, set up a handler to be called if
* the backend/postmaster crashes with a fatal signal or exception.
*/
#if defined(WIN32) && defined(HAVE_MINIDUMP_TYPE)
pgwin32_install_crashdump_handler();
#endif
/*
* Fire up essential subsystems: error and memory management
*
* Code after this point is allowed to use elog/ereport, though
* localization of messages may not work right away, and messages won't go
* anywhere but stderr until GUC settings get loaded.
*/
MemoryContextInit();
/*
* Set up locale information from environment. Note that LC_CTYPE and
* LC_COLLATE will be overridden later from pg_control if we are in an
* already-initialized database. We set them here so that they will be
* available to fill pg_control during initdb. LC_MESSAGES will get set
* later during GUC option processing, but we set it here to allow startup
* error messages to be localized.
*/
set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("postgres"));
init_locale(LC_COLLATE, "");
init_locale(LC_CTYPE, "");
#ifdef LC_MESSAGES
init_locale(LC_MESSAGES, "");
#endif
/*
* We keep these set to "C" always, except transiently in pg_locale.c; see
* that file for explanations.
*/
init_locale(LC_MONETARY, "C");
init_locale(LC_NUMERIC, "C");
init_locale(LC_TIME, "C");
/*
* Now that we have absorbed as much as we wish to from the locale
* environment, remove any LC_ALL setting, so that the environment
* variables installed by pg_perm_setlocale have force.
*/
unsetenv("LC_ALL");
/*
* Catch standard options before doing much else, in particular before we
* insist on not being root.
*/
if (argc > 1) {
if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0) {
help(progname);
exit(0);
}
if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0) {
puts("postgres (PostgreSQL) " PG_VERSION);
exit(0);
}
/*
* In addition to the above, we allow "--describe-config" and "-C var"
* to be called by root. This is reasonably safe since these are
* read-only activities. The -C case is important because pg_ctl may
* try to invoke it while still holding administrator privileges on
* Windows. Note that while -C can normally be in any argv position,
* if you wanna bypass the root check you gotta put it first. This
* reduces the risk that we might misinterpret some other mode's -C
* switch as being the postmaster/postgres one.
*/
if (strcmp(argv[1], "--describe-config") == 0)
do_check_root = false;
else if (argc > 2 && strcmp(argv[1], "-C") == 0)
do_check_root = false;
}
/*
* Make sure we are not running as root, unless it's safe for the selected
* option.
*/
if (do_check_root) check_root(progname);
/*
* Dispatch to one of various subprograms depending on first argument.
*/
#ifdef EXEC_BACKEND
if (argc > 1 && strncmp(argv[1], "--fork", 6) == 0)
SubPostmasterMain(argc, argv); /* does not return */
#endif
if (argc > 1 && strcmp(argv[1], "--boot") == 0)
AuxiliaryProcessMain(argc, argv); /* does not return */
else if (argc > 1 && strcmp(argv[1], "--describe-config") == 0)
GucInfoMain(); /* does not return */
else if (argc > 1 && strcmp(argv[1], "--single") == 0)
PostgresMain(argc, argv, NULL, /* no dbname */
strdup(get_user_name_or_exit(progname))); /* does not return */
else
PostmasterMain(argc, argv); /* does not return */
abort(); /* should not get here */
}
/*
* Place platform-specific startup hacks here. This is the right
* place to put code that must be executed early in the launch of any new
* server process. Note that this code will NOT be executed when a backend
* or sub-bootstrap process is forked, unless we are in a fork/exec
* environment (ie EXEC_BACKEND is defined).
*
* XXX The need for code here is proof that the platform in question
* is too brain-dead to provide a standard C execution environment
* without help. Avoid adding more here, if you can.
*/
static void startup_hacks(const char *progname __attribute__((unused))) {
/*
* Initialize dummy_spinlock, in case we are on a platform where we have
* to use the fallback implementation of pg_memory_barrier().
*/
SpinLockInit(&dummy_spinlock);
}
/*
* Make the initial permanent setting for a locale category. If that fails,
* perhaps due to LC_foo=invalid in the environment, use locale C. If even
* that fails, perhaps due to out-of-memory, the entire startup fails with it.
* When this returns, we are guaranteed to have a setting for the given
* category's environment variable.
*/
static void init_locale(int category, const char *locale) {
if (pg_perm_setlocale(category, locale) == NULL &&
pg_perm_setlocale(category, "C") == NULL)
elog(FATAL, "could not adopt C locale");
}
/*
* Help display should match the options accepted by PostmasterMain()
* and PostgresMain().
*
* XXX On Windows, non-ASCII localizations of these messages only display
* correctly if the console output code page covers the necessary characters.
* Messages emitted in write_console() do not exhibit this problem.
*/
static void help(const char *progname) {
fprintf(stderr,"%s is the PostgreSQL server.\n\n", progname);
fprintf(stderr,"Usage:\n %s [OPTION]...\n\n", progname);
fprintf(stderr,"Options:\n");
fprintf(stderr," -B NBUFFERS number of shared buffers\n");
fprintf(stderr," -c NAME=VALUE set run-time parameter\n");
fprintf(stderr," -C NAME print value of run-time parameter, then exit\n");
fprintf(stderr," -d 1-5 debugging level\n");
fprintf(stderr," -D DATADIR database directory\n");
fprintf(stderr," -e use European date input format (DMY)\n");
fprintf(stderr," -F turn fsync off\n");
fprintf(stderr," -h HOSTNAME host name or IP address to listen on\n");
fprintf(stderr," -i enable TCP/IP connections\n");
fprintf(stderr," -k DIRECTORY Unix-domain socket location\n");
#ifdef USE_SSL
fprintf(stderr," -l enable SSL connections\n");
#endif
fprintf(stderr," -N MAX-CONNECT maximum number of allowed connections\n");
fprintf(stderr," -o OPTIONS pass \"OPTIONS\" to each server process "
"(obsolete)\n");
fprintf(stderr," -p PORT port number to listen on\n");
fprintf(stderr," -s show statistics after each query\n");
fprintf(stderr," -S WORK-MEM set amount of memory for sorts (in kB)\n");
fprintf(stderr," -V, --version output version information, then exit\n");
fprintf(stderr," --NAME=VALUE set run-time parameter\n");
fprintf(stderr," --describe-config describe configuration parameters, then exit\n");
fprintf(stderr," -?, --help show this help, then exit\n");
fprintf(stderr,"\nDeveloper options:\n");
fprintf(stderr," -f s|i|n|m|h forbid use of some plan types\n");
fprintf(stderr," -n do not reinitialize shared memory after abnormal "
"exit\n");
fprintf(stderr," -O allow system table structure changes\n");
fprintf(stderr," -P disable system indexes\n");
fprintf(stderr," -t pa|pl|ex show timings after each query\n");
fprintf(stderr," -T send SIGSTOP to all backend processes if one "
"dies\n");
fprintf(stderr," -W NUM wait NUM seconds to allow attach from a "
"debugger\n");
fprintf(stderr,"\nOptions for single-user mode:\n");
fprintf(stderr," --single selects single-user mode (must be first "
"argument)\n");
fprintf(stderr," DBNAME database name (defaults to user name)\n");
fprintf(stderr," -d 0-5 override debugging level\n");
fprintf(stderr," -E echo statement before execution\n");
fprintf(stderr," -j do not use newline as interactive query "
"delimiter\n");
fprintf(stderr," -r FILENAME send stdout and stderr to given file\n");
fprintf(stderr,"\nOptions for bootstrapping mode:\n");
fprintf(stderr," --boot selects bootstrapping mode (must be first "
"argument)\n");
fprintf(stderr," DBNAME database name (mandatory argument in "
"bootstrapping mode)\n");
fprintf(stderr," -r FILENAME send stdout and stderr to given file\n");
fprintf(stderr," -x NUM internal use\n");
fprintf(stderr,"\nPlease read the documentation for the complete list of run-time\n"
"configuration settings and how to set them on the command line or in\n"
"the configuration file.\n\n"
"Report bugs to <[email protected]>.\n");
}
static void check_root(const char *progname) {
if (geteuid() == 0) {
write_stderr(
"\"root\" execution of the PostgreSQL server is not permitted.\n"
"The server must be started under an unprivileged user ID to prevent\n"
"possible system security compromise. See the documentation for\n"
"more information on how to properly start the server.\n");
exit(1);
}
/*
* Also make sure that real and effective uids are the same. Executing as
* a setuid program from a root shell is a security hole, since on many
* platforms a nefarious subroutine could setuid back to root if real uid
* is root. (Since nobody actually uses postgres as a setuid program,
* trying to actively fix this situation seems more trouble than it's
* worth; we'll just expend the effort to check for it.)
*/
if (getuid() != geteuid()) {
write_stderr("%s: real and effective user IDs must match\n", progname);
exit(1);
}
}
<|endoftext|> |
<commit_before>#include "pch.h"
#include "carousel.h"
Carousel::Carousel()
: _currentItemIndex(INVALID_ITEM_INDEX)
, _currentItemBeforeTouch(INVALID_ITEM_INDEX)
, _startScrollingPosition(0.0f, 0.0f)
, _itemScrollingClip(NULL)
, _rawScrollPosition(0, 0)
, _freeSliding(false)
{
}
Carousel::~Carousel()
{
}
const char * Carousel::getTypeName() const
{
return "Carousel";
}
gameplay::Control * Carousel::create(gameplay::Theme::Style* style, gameplay::Properties* properties)
{
Carousel * res = new Carousel();
res->initialize(res->getTypeName(), style, properties);
return res;
}
void Carousel::initialize(const char* typeName, gameplay::Theme::Style* style, gameplay::Properties* properties)
{
gameplay::Container::initialize(typeName, style, properties);
_freeSliding = properties->getBool("freeSliding");
setReceiveInputEvents(true);
for (gameplay::Control * child : getControls())
unsetConsumeInputEvents(child);
}
bool Carousel::touchEventScroll(gameplay::Touch::TouchEvent evt, int x, int y, unsigned int contactIndex)
{
if (evt != gameplay::Touch::TOUCH_PRESS && _currentItemBeforeTouch == INVALID_ITEM_INDEX)
return false;
// using _currentItemBeforeTouch also as a flag that touch is still pressed (INVALID_ITEM_INDEX)
// remap scroll position only when touch is pressed
if (_currentItemBeforeTouch == INVALID_ITEM_INDEX)
_rawScrollPosition = _scrollPosition;
_scrollPosition = _rawScrollPosition;
bool res = gameplay::Container::touchEventScroll(evt, x, y, contactIndex) || _currentItemBeforeTouch != INVALID_ITEM_INDEX;
_rawScrollPosition = _scrollPosition;
// reset velocity
_scrollingVelocity.set(0.0f, 0.0f);
if (getControlCount() > 0)
{
unsigned closestControlIndex = findClosestControlIndex(-_scrollPosition.x, false);
if (!_freeSliding)
{
// remap scrollPosition so it feels like there is a spring inside button
// that help items to stick to borders when rotating a dial
gameplay::Control * closestControl = getControl(closestControlIndex);
float distance = 0.5f * (closestControl->getWidth() + closestControl->getMargin().left + closestControl->getMargin().bottom);
float relativeOffsetToClosestItem = (closestControl->getX() + closestControl->getWidth() * 0.5f + _scrollPosition.x) / distance - 1.0f;
relativeOffsetToClosestItem = std::min(1.0f, std::max(-1.0f, relativeOffsetToClosestItem));
relativeOffsetToClosestItem *= relativeOffsetToClosestItem * relativeOffsetToClosestItem;
_scrollPosition.x = (relativeOffsetToClosestItem + 1.0f) * distance - closestControl->getX() - closestControl->getWidth() * 0.5f;
closestControlIndex = findClosestControlIndex(-_scrollPosition.x, false);
}
switch (evt)
{
case gameplay::Touch::TOUCH_MOVE:
if (_currentItemBeforeTouch != INVALID_ITEM_INDEX && _currentItemIndex != closestControlIndex)
{
_currentItemIndex = closestControlIndex;
}
break;
case gameplay::Touch::TOUCH_RELEASE:
// scroll to nearest item
if (_currentItemBeforeTouch != INVALID_ITEM_INDEX)
{
_currentItemIndex = closestControlIndex;
scrollToItem(closestControlIndex);
if (_currentItemBeforeTouch != _currentItemIndex)
notifyListeners(gameplay::Control::Listener::VALUE_CHANGED);
_currentItemBeforeTouch = INVALID_ITEM_INDEX;
}
break;
case gameplay::Touch::TOUCH_PRESS:
if (getControl(closestControlIndex)->getBounds().height > y)
if (_currentItemIndex != INVALID_ITEM_INDEX)
_currentItemBeforeTouch = _currentItemIndex;
break;
}
}
return res;
}
unsigned Carousel::findClosestControlIndex(float localX, bool exitOnPositiveOffset) const
{
float minDistance = FLT_MAX;
unsigned closestControlIndex = 0;
unsigned index = 0;
for (gameplay::Control * control : getControls())
{
if (control->isVisible())
{
float distance = control->getX() - control->getMargin().left - localX;
if (exitOnPositiveOffset && distance > -control->getHeight())
return index;
if (fabs(distance) < minDistance)
{
minDistance = fabs(distance);
closestControlIndex = index;
if (distance > 0.0f)
return closestControlIndex;
}
}
index++;
}
return closestControlIndex < getControlCount() ? closestControlIndex : INVALID_ITEM_INDEX;
}
void Carousel::scrollToItem(unsigned itemIndex, bool immediately)
{
if (itemIndex >= getControlCount())
return;
if (_itemScrollingClip && _itemScrollingClip->isPlaying())
{
_itemScrollingClip->stop();
_itemScrollingClip = NULL;
}
unsigned int lastItem = _currentItemIndex;
if (_currentItemIndex != itemIndex)
{
_currentItemIndex = itemIndex;
notifyListeners(gameplay::Control::Listener::VALUE_CHANGED);
// controls count may change after notifying listeners
if (_currentItemIndex >= getControlCount())
{
_currentItemIndex = INVALID_ITEM_INDEX;
notifyListeners(gameplay::Control::Listener::VALUE_CHANGED);
return;
}
}
if (!immediately && lastItem < getControlCount())
{
float from = 0.0f;
float to = 1.0f;
_startScrollingPosition = _scrollPosition;
gameplay::Animation * animation = createAnimationFromTo("scrollbar-scroll-to-item", ANIMATE_SCROLL_TO_ITEM, &from, &to,
gameplay::Curve::QUADRATIC_IN, 200);
_itemScrollingClip = animation->getClip();
_itemScrollingClip->play();
}
else
{
updateChildBounds();
updateBounds();
gameplay::Control * itemToScrollTo = getControl(itemIndex);
gameplay::Vector2 desiredScrollPosition(-(itemToScrollTo->getX() - itemToScrollTo->getMargin().left), 0.0f);
setScrollPosition(desiredScrollPosition);
}
}
unsigned int Carousel::getAnimationPropertyComponentCount(int propertyId) const
{
switch (propertyId)
{
case ANIMATE_SCROLL_TO_ITEM:
return 1;
default:
return Container::getAnimationPropertyComponentCount(propertyId);
}
}
void Carousel::getAnimationPropertyValue(int propertyId, gameplay::AnimationValue* value)
{
GP_ASSERT(value);
switch (propertyId)
{
case ANIMATE_SCROLL_TO_ITEM:
{
GP_ASSERT(_currentItemIndex < getControlCount());
gameplay::Control * itemToScrollTo = getControl(_currentItemIndex);
gameplay::Vector2 desiredScrollPosition(-(itemToScrollTo->getX() - itemToScrollTo->getMargin().left), 0.0f);
value->setFloat(0, (_scrollPosition - _startScrollingPosition).length() / (desiredScrollPosition - _startScrollingPosition).length());
}
break;
default:
Container::getAnimationPropertyValue(propertyId, value);
break;
}
}
void Carousel::setAnimationPropertyValue(int propertyId, gameplay::AnimationValue* value, float blendWeight)
{
GP_ASSERT(value);
switch (propertyId)
{
case ANIMATE_SCROLL_TO_ITEM:
{
GP_ASSERT(_currentItemIndex < getControlCount());
gameplay::Control * itemToScrollTo = getControl(_currentItemIndex);
gameplay::Vector2 desiredScrollPosition(-(itemToScrollTo->getX() - itemToScrollTo->getMargin().left), 0.0f);
float scrollFactor = value->getFloat(0);
_scrollPosition = _startScrollingPosition + (desiredScrollPosition - _startScrollingPosition) * scrollFactor * blendWeight;
setDirty(DIRTY_BOUNDS);
setChildrenDirty(DIRTY_BOUNDS, true);
}
break;
default:
Container::setAnimationPropertyValue(propertyId, value, blendWeight);
break;
}
}
void Carousel::removeControl(unsigned int index)
{
gameplay::Container::removeControl(index);
if (_currentItemIndex != INVALID_ITEM_INDEX && _currentItemIndex >= getControlCount())
_currentItemIndex--;
if (_currentItemIndex >= getControlCount())
{
_currentItemIndex = INVALID_ITEM_INDEX;
notifyListeners(gameplay::Control::Listener::VALUE_CHANGED);
}
}
unsigned int Carousel::addControl(gameplay::Control * control)
{
unsigned int res = gameplay::Container::addControl(control);
unsetConsumeInputEvents(control);
return res;
}
void Carousel::insertControl(gameplay::Control * control, unsigned int index)
{
gameplay::Container::insertControl(control, index);
unsetConsumeInputEvents(control);
}
void Carousel::setEnabled(bool enabled)
{
gameplay::Container::setEnabled(enabled);
if (!enabled)
{
// reset any behavior related to user input
stopScrolling();
if (_currentItemBeforeTouch != INVALID_ITEM_INDEX)
_currentItemBeforeTouch = INVALID_ITEM_INDEX;
}
}
void Carousel::unsetConsumeInputEvents(gameplay::Control * control)
{
control->setConsumeInputEvents(false);
if (control->isContainer())
for (gameplay::Control * child : static_cast<gameplay::Container*>(control)->getControls())
unsetConsumeInputEvents(child);
}<commit_msg>using up-to-date children bounds for scrolling over carousel items<commit_after>#include "pch.h"
#include "carousel.h"
Carousel::Carousel()
: _currentItemIndex(INVALID_ITEM_INDEX)
, _currentItemBeforeTouch(INVALID_ITEM_INDEX)
, _startScrollingPosition(0.0f, 0.0f)
, _itemScrollingClip(NULL)
, _rawScrollPosition(0, 0)
, _freeSliding(false)
{
}
Carousel::~Carousel()
{
}
const char * Carousel::getTypeName() const
{
return "Carousel";
}
gameplay::Control * Carousel::create(gameplay::Theme::Style* style, gameplay::Properties* properties)
{
Carousel * res = new Carousel();
res->initialize(res->getTypeName(), style, properties);
return res;
}
void Carousel::initialize(const char* typeName, gameplay::Theme::Style* style, gameplay::Properties* properties)
{
gameplay::Container::initialize(typeName, style, properties);
_freeSliding = properties->getBool("freeSliding");
setReceiveInputEvents(true);
for (gameplay::Control * child : getControls())
unsetConsumeInputEvents(child);
}
bool Carousel::touchEventScroll(gameplay::Touch::TouchEvent evt, int x, int y, unsigned int contactIndex)
{
if (evt != gameplay::Touch::TOUCH_PRESS && _currentItemBeforeTouch == INVALID_ITEM_INDEX)
return false;
// using _currentItemBeforeTouch also as a flag that touch is still pressed (INVALID_ITEM_INDEX)
// remap scroll position only when touch is pressed
if (_currentItemBeforeTouch == INVALID_ITEM_INDEX)
_rawScrollPosition = _scrollPosition;
_scrollPosition = _rawScrollPosition;
bool res = gameplay::Container::touchEventScroll(evt, x, y, contactIndex) || _currentItemBeforeTouch != INVALID_ITEM_INDEX;
_rawScrollPosition = _scrollPosition;
// reset velocity
_scrollingVelocity.set(0.0f, 0.0f);
if (getControlCount() > 0)
{
unsigned closestControlIndex = findClosestControlIndex(-_scrollPosition.x, false);
if (!_freeSliding)
{
// remap scrollPosition so it feels like there is a spring inside button
// that help items to stick to borders when rotating a dial
gameplay::Control * closestControl = getControl(closestControlIndex);
float distance = 0.5f * (closestControl->getWidth() + closestControl->getMargin().left + closestControl->getMargin().bottom);
float relativeOffsetToClosestItem = (closestControl->getX() + closestControl->getWidth() * 0.5f + _scrollPosition.x) / distance - 1.0f;
relativeOffsetToClosestItem = std::min(1.0f, std::max(-1.0f, relativeOffsetToClosestItem));
relativeOffsetToClosestItem *= relativeOffsetToClosestItem * relativeOffsetToClosestItem;
_scrollPosition.x = (relativeOffsetToClosestItem + 1.0f) * distance - closestControl->getX() - closestControl->getWidth() * 0.5f;
closestControlIndex = findClosestControlIndex(-_scrollPosition.x, false);
}
switch (evt)
{
case gameplay::Touch::TOUCH_MOVE:
if (_currentItemBeforeTouch != INVALID_ITEM_INDEX && _currentItemIndex != closestControlIndex)
{
_currentItemIndex = closestControlIndex;
}
break;
case gameplay::Touch::TOUCH_RELEASE:
// scroll to nearest item
if (_currentItemBeforeTouch != INVALID_ITEM_INDEX)
{
_currentItemIndex = closestControlIndex;
scrollToItem(closestControlIndex);
if (_currentItemBeforeTouch != _currentItemIndex)
notifyListeners(gameplay::Control::Listener::VALUE_CHANGED);
_currentItemBeforeTouch = INVALID_ITEM_INDEX;
}
break;
case gameplay::Touch::TOUCH_PRESS:
if (getControl(closestControlIndex)->getBounds().height > y)
if (_currentItemIndex != INVALID_ITEM_INDEX)
_currentItemBeforeTouch = _currentItemIndex;
break;
}
}
return res;
}
unsigned Carousel::findClosestControlIndex(float localX, bool exitOnPositiveOffset) const
{
float minDistance = FLT_MAX;
unsigned closestControlIndex = 0;
unsigned index = 0;
for (gameplay::Control * control : getControls())
{
if (control->isVisible())
{
float distance = control->getX() - control->getMargin().left - localX;
if (exitOnPositiveOffset && distance > -control->getHeight())
return index;
if (fabs(distance) < minDistance)
{
minDistance = fabs(distance);
closestControlIndex = index;
if (distance > 0.0f)
return closestControlIndex;
}
}
index++;
}
return closestControlIndex < getControlCount() ? closestControlIndex : INVALID_ITEM_INDEX;
}
void Carousel::scrollToItem(unsigned itemIndex, bool immediately)
{
if (itemIndex >= getControlCount())
return;
if (_itemScrollingClip && _itemScrollingClip->isPlaying())
{
_itemScrollingClip->stop();
_itemScrollingClip = NULL;
}
unsigned int lastItem = _currentItemIndex;
if (_currentItemIndex != itemIndex)
{
_currentItemIndex = itemIndex;
notifyListeners(gameplay::Control::Listener::VALUE_CHANGED);
// controls count may change after notifying listeners
if (_currentItemIndex >= getControlCount())
{
_currentItemIndex = INVALID_ITEM_INDEX;
notifyListeners(gameplay::Control::Listener::VALUE_CHANGED);
return;
}
}
if (!immediately && lastItem < getControlCount())
{
float from = 0.0f;
float to = 1.0f;
_startScrollingPosition = _scrollPosition;
gameplay::Animation * animation = createAnimationFromTo("scrollbar-scroll-to-item", ANIMATE_SCROLL_TO_ITEM, &from, &to,
gameplay::Curve::QUADRATIC_IN, 200);
_itemScrollingClip = animation->getClip();
_itemScrollingClip->play();
}
else
{
updateChildBounds();
updateBounds();
gameplay::Control * itemToScrollTo = getControl(itemIndex);
gameplay::Vector2 desiredScrollPosition(-(itemToScrollTo->getX() - itemToScrollTo->getMargin().left), 0.0f);
setScrollPosition(desiredScrollPosition);
}
}
unsigned int Carousel::getAnimationPropertyComponentCount(int propertyId) const
{
switch (propertyId)
{
case ANIMATE_SCROLL_TO_ITEM:
return 1;
default:
return Container::getAnimationPropertyComponentCount(propertyId);
}
}
void Carousel::getAnimationPropertyValue(int propertyId, gameplay::AnimationValue* value)
{
GP_ASSERT(value);
switch (propertyId)
{
case ANIMATE_SCROLL_TO_ITEM:
{
GP_ASSERT(_currentItemIndex < getControlCount());
gameplay::Control * itemToScrollTo = getControl(_currentItemIndex);
gameplay::Vector2 desiredScrollPosition(-(itemToScrollTo->getX() - itemToScrollTo->getMargin().left), 0.0f);
value->setFloat(0, (_scrollPosition - _startScrollingPosition).length() / (desiredScrollPosition - _startScrollingPosition).length());
}
break;
default:
Container::getAnimationPropertyValue(propertyId, value);
break;
}
}
void Carousel::setAnimationPropertyValue(int propertyId, gameplay::AnimationValue* value, float blendWeight)
{
GP_ASSERT(value);
switch (propertyId)
{
case ANIMATE_SCROLL_TO_ITEM:
if (_currentItemIndex < getControlCount())
{
updateChildBounds();
updateBounds();
gameplay::Control * itemToScrollTo = getControl(_currentItemIndex);
gameplay::Vector2 desiredScrollPosition(-(itemToScrollTo->getX() - itemToScrollTo->getMargin().left), 0.0f);
float scrollFactor = value->getFloat(0);
_scrollPosition = _startScrollingPosition + (desiredScrollPosition - _startScrollingPosition) * scrollFactor * blendWeight;
setDirty(DIRTY_BOUNDS);
setChildrenDirty(DIRTY_BOUNDS, true);
}
break;
default:
Container::setAnimationPropertyValue(propertyId, value, blendWeight);
break;
}
}
void Carousel::removeControl(unsigned int index)
{
gameplay::Container::removeControl(index);
if (_currentItemIndex != INVALID_ITEM_INDEX && _currentItemIndex >= getControlCount())
_currentItemIndex--;
if (_currentItemIndex >= getControlCount())
{
_currentItemIndex = INVALID_ITEM_INDEX;
notifyListeners(gameplay::Control::Listener::VALUE_CHANGED);
}
}
unsigned int Carousel::addControl(gameplay::Control * control)
{
unsigned int res = gameplay::Container::addControl(control);
unsetConsumeInputEvents(control);
return res;
}
void Carousel::insertControl(gameplay::Control * control, unsigned int index)
{
gameplay::Container::insertControl(control, index);
unsetConsumeInputEvents(control);
}
void Carousel::setEnabled(bool enabled)
{
gameplay::Container::setEnabled(enabled);
if (!enabled)
{
// reset any behavior related to user input
stopScrolling();
if (_currentItemBeforeTouch != INVALID_ITEM_INDEX)
_currentItemBeforeTouch = INVALID_ITEM_INDEX;
}
}
void Carousel::unsetConsumeInputEvents(gameplay::Control * control)
{
control->setConsumeInputEvents(false);
if (control->isContainer())
for (gameplay::Control * child : static_cast<gameplay::Container*>(control)->getControls())
unsetConsumeInputEvents(child);
}<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: prnmon.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: cd $ $Date: 2002-10-22 06:05:54 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef SVTOOLS_ASYNCLINK_HXX
#include <svtools/asynclink.hxx>
#endif
#include <svtools/printwarningoptions.hxx>
#pragma hdrstop
#include "prnmon.hxx"
#include "viewsh.hxx"
#include "viewfrm.hxx"
#include "objsh.hxx"
#include "docfile.hxx"
#include "sfxtypes.hxx"
#include "progress.hxx"
#include "desrupt.hxx"
#include "bindings.hxx"
#include "sfxresid.hxx"
#include "view.hrc"
//------------------------------------------------------------------------
#define SFX_TITLE_MAXLEN_PRINTMONITOR 22
//------------------------------------------------------------------------
struct SfxPrintMonitor_Impl: public ModelessDialog
{
SfxPrintMonitor_Impl( Window *pParent );
FixedText aDocName;
FixedText aPrinting;
FixedText aPrinter;
FixedText aPrintInfo;
CancelButton aCancel;
};
//-------------------------------------------------------------------------
struct SfxPrintProgress_Impl
{
SfxPrintMonitor_Impl* pMonitor;
SfxViewShell* pViewShell;
SfxPrinter* pPrinter;
SfxPrinter* pOldPrinter;
USHORT nLastPage;
BOOL bRunning;
BOOL bCancel;
BOOL bDeleteOnEndPrint;
BOOL bShow;
BOOL bCallbacks;
BOOL bOldEnablePrintFile;
BOOL bOldFlag;
BOOL bRestoreFlag;
svtools::AsynchronLink aDeleteLink;
Link aCancelHdl;
private:
DECL_LINK( CancelHdl, Button * );
DECL_STATIC_LINK( SfxPrintProgress_Impl, DeleteHdl, SfxPrintProgress * );
public:
SfxPrintProgress_Impl( SfxViewShell* pTheViewShell, SfxPrinter* pThePrinter );
~SfxPrintProgress_Impl();
void Delete( SfxPrintProgress* pAntiImpl ) { aDeleteLink.Call( pAntiImpl ); }
SfxViewShell* GetViewShell() const { return pViewShell; }
BOOL SetPage( USHORT nPage, const String &rPage );
};
//------------------------------------------------------------------------
SfxPrintMonitor_Impl::SfxPrintMonitor_Impl( Window* pParent ) :
ModelessDialog( pParent, SfxResId( DLG_PRINTMONITOR ) ),
aDocName ( this, ResId( FT_DOCNAME ) ),
aPrinting ( this, ResId( FT_PRINTING ) ),
aPrinter ( this, ResId( FT_PRINTER ) ),
aPrintInfo ( this, ResId( FT_PRINTINFO ) ),
aCancel ( this, ResId( PB_CANCELPRNMON ) )
{
FreeResource();
}
//------------------------------------------------------------------------
IMPL_STATIC_LINK( SfxPrintProgress_Impl, DeleteHdl, SfxPrintProgress*, pAntiImpl )
{
delete pAntiImpl;
return 0;
}
//------------------------------------------------------------------------
SfxPrintProgress_Impl::SfxPrintProgress_Impl( SfxViewShell* pTheViewShell,
SfxPrinter* pThePrinter ) :
pViewShell ( pTheViewShell ),
pPrinter ( pThePrinter ),
pOldPrinter ( NULL ),
bRunning ( TRUE ),
bDeleteOnEndPrint ( FALSE ),
bCancel ( FALSE ),
bCallbacks ( FALSE ),
bOldEnablePrintFile ( FALSE ),
bOldFlag ( TRUE ),
bRestoreFlag ( FALSE ),
nLastPage ( 0 ),
aDeleteLink ( STATIC_LINK( this, SfxPrintProgress_Impl, DeleteHdl ) )
{
Window* pParent =
pTheViewShell->GetWindow()->IsReallyVisible() ? pTheViewShell->GetWindow() : NULL;
pMonitor = new SfxPrintMonitor_Impl( pParent );
pMonitor->aDocName.SetText(
pViewShell->GetViewFrame()->GetObjectShell()->GetTitle( SFX_TITLE_MAXLEN_PRINTMONITOR ) );
pMonitor->aPrinter.SetText( pViewShell->GetPrinter()->GetName() );
pMonitor->aCancel.SetClickHdl( LINK( this, SfxPrintProgress_Impl, CancelHdl ) );
}
//------------------------------------------------------------------------
SfxPrintProgress_Impl::~SfxPrintProgress_Impl()
{
if ( pMonitor )
{
pMonitor->Hide(); // sieht optisch besser aus, wenn alles auf einmal verschwindet
delete pMonitor;
}
}
//------------------------------------------------------------------------
BOOL SfxPrintProgress_Impl::SetPage( USHORT nPage, const String &rPage )
{
// wurde der Druckauftrag abgebrochen?
if ( bCancel || !pMonitor )
return FALSE;
nLastPage = nPage;
String aStrPrintInfo = String( SfxResId( STR_PAGE ) );
if ( !rPage.Len() )
aStrPrintInfo += String::CreateFromInt32( nLastPage );
else
aStrPrintInfo += rPage;
pMonitor->aPrintInfo.SetText( aStrPrintInfo );
pMonitor->Update();
return TRUE;
}
//------------------------------------------------------------------------
IMPL_LINK_INLINE_START( SfxPrintProgress_Impl, CancelHdl, Button *, pButton )
{
if ( pMonitor )
pMonitor->Hide();
pViewShell->GetPrinter()->AbortJob();
bCancel = TRUE;
if ( aCancelHdl.IsSet() )
aCancelHdl.Call( this );
return 0;
}
IMPL_LINK_INLINE_END( SfxPrintProgress_Impl, CancelHdl, Button *, pButton )
//--------------------------------------------------------------------
SfxPrintProgress::SfxPrintProgress( SfxViewShell* pViewSh, FASTBOOL bShow )
: SfxProgress( pViewSh->GetViewFrame()->GetObjectShell(),
String(SfxResId(STR_PRINTING)), 1, FALSE ),
pImp( new SfxPrintProgress_Impl( pViewSh, pViewSh->GetPrinter() ) )
{
// Callback fuer Fehler und EndPrint setzen
pImp->pPrinter->SetEndPrintHdl(
LINK( this, SfxPrintProgress, EndPrintNotify ));
pImp->pPrinter->SetErrorHdl(
LINK( this, SfxPrintProgress, PrintErrorNotify ));
pImp->bCallbacks = TRUE;
pImp->pViewShell->GetViewFrame()->GetFrame()->Lock_Impl(TRUE);
pImp->bShow = bShow;
Lock();
if ( !SvtPrintWarningOptions().IsModifyDocumentOnPrintingAllowed() )
{
pImp->bRestoreFlag = TRUE;
pImp->bOldFlag = pViewSh->GetObjectShell()->IsEnableSetModified();
if ( pImp->bOldFlag )
pViewSh->GetObjectShell()->EnableSetModified( FALSE );
}
}
//--------------------------------------------------------------------
SfxPrintProgress::~SfxPrintProgress()
{
// k"onnte auch schon weg sein (in EndPrintNotify)
DELETEZ(pImp->pMonitor);
// ggf. Callbacks entfermen
if ( pImp->bCallbacks )
{
pImp->pPrinter->SetEndPrintHdl( Link() );
pImp->pPrinter->SetErrorHdl( Link() );
pImp->bCallbacks = FALSE;
}
// ggf. vorherigen Drucker wieder einsetzen
if ( pImp->pOldPrinter )
pImp->pViewShell->SetPrinter( pImp->pOldPrinter, SFX_PRINTER_PRINTER );
else
// ggf. vorherigen Print-To-File-Status zuruecksetzen
pImp->pViewShell->GetPrinter()->EnablePrintFile(
pImp->bOldEnablePrintFile );
// EndPrint-Notification an Frame
pImp->pViewShell->GetViewFrame()->GetFrame()->Lock_Impl(FALSE);
delete pImp;
}
//--------------------------------------------------------------------
BOOL SfxPrintProgress::SetState( ULONG nVal, ULONG nNewRange )
{
#ifndef MAC
// auf dem MAC kommt einer vom Betriebssystem
if ( pImp->bShow )
{
pImp->bShow = FALSE;
pImp->pMonitor->Show();
pImp->pMonitor->Update();
}
#endif
return pImp->SetPage( (USHORT)nVal, GetStateText_Impl() ) &&
SfxProgress::SetState( nVal, nNewRange );
}
//--------------------------------------------------------------------
void SfxPrintProgress::SetText( const String& rText )
{
if ( pImp->pMonitor )
{
pImp->pMonitor->SetText( rText );
pImp->pMonitor->Update();
}
SfxProgress::SetText( rText );
}
//------------------------------------------------------------------------
IMPL_LINK_INLINE_START( SfxPrintProgress, PrintErrorNotify, void *, pvoid )
{
if ( pImp->pMonitor )
pImp->pMonitor->Hide();
pImp->pPrinter->AbortJob();
InfoBox( pImp->GetViewShell()->GetWindow(),
String( SfxResId(STR_ERROR_PRINT) ) ).Execute();
if ( pImp->bRestoreFlag && pImp->pViewShell->GetObjectShell()->IsEnableSetModified() != pImp->bOldFlag )
pImp->pViewShell->GetObjectShell()->EnableSetModified( pImp->bOldFlag );
return 0;
}
IMPL_LINK_INLINE_END( SfxPrintProgress, PrintErrorNotify, void *, pvoid )
//------------------------------------------------------------------------
IMPL_LINK( SfxPrintProgress, EndPrintNotify, void *, pvoid )
{
if ( pImp->pMonitor )
pImp->pMonitor->Hide();
// Slots enablen
pImp->pViewShell->Invalidate( SID_PRINTDOC );
pImp->pViewShell->Invalidate( SID_PRINTDOCDIRECT );
pImp->pViewShell->Invalidate( SID_SETUPPRINTER );
// . . . falls der Printer im System umgestellt wurde, hier Aenderung
// nachziehen.
//! if( pMDI->IsPrinterChanged() ) pMDI->Changed( 0L );
// Callbacks rausnehmen
pImp->pPrinter->SetEndPrintHdl( Link() );
pImp->pPrinter->SetErrorHdl( Link() );
pImp->bCallbacks = FALSE;
// ggf. alten Printer wieder einsetzen
if ( pImp->pOldPrinter )
{
// Fix #59613#: niemals den aktuellen Printer synchron abschiessen !
// Da sowieso immer bDeleteOnEndPrint gesetzt wird, wird der der Drucker im
// dtor vom Printprogress ( dann aber asynchron !! ) zur"uckgesetzt.
/*
pImp->pViewShell->SetPrinter( pImp->pOldPrinter, SFX_PRINTER_PRINTER );
pImp->pOldPrinter = 0;
pImp->pPrinter = 0;
*/
}
else
// ggf. vorherigen Print-To-File-Status zuruecksetzen
pImp->pViewShell->GetPrinter()->EnablePrintFile( pImp->bOldEnablePrintFile );
// lief der Drucker im Thread?
if ( pImp->bDeleteOnEndPrint )
{
// Dialog sofort l"oschen sonst wird ggf. das MDI vorher geschlossen
DELETEZ(pImp->pMonitor);
// Progress per PostMessage zerst"oren, nicht sofort sonst GPF
pImp->Delete( this );
}
else
{
DBG_ASSERT( !pImp->pOldPrinter, "Printer konnte nicht korrekt restauriert werden!" );
pImp->bRunning = FALSE;
}
if ( pImp->bRestoreFlag && pImp->pViewShell->GetObjectShell()->IsEnableSetModified() != pImp->bOldFlag )
pImp->pViewShell->GetObjectShell()->EnableSetModified( TRUE );
return 0;
}
//------------------------------------------------------------------------
void SfxPrintProgress::DeleteOnEndPrint()
{
UnLock(); // jetzt schon, wg. Drucken im Thread
#ifndef WIN
// da das Drucken im 'Thread' unter Windows zu undefiniert ist bleibt der
// Print-Monitor dort stehen, auf den anderen Plattformen kann man dann
// weiterarbeiten, also kommt das Teil weg
DELETEZ( pImp->pMonitor );
#endif
pImp->bDeleteOnEndPrint = TRUE;
if ( !pImp->bRunning )
delete this;
}
//------------------------------------------------------------------------
void SfxPrintProgress::RestoreOnEndPrint( SfxPrinter *pOldPrinter,
BOOL bOldEnablePrintFile )
{
pImp->pOldPrinter = pOldPrinter;
pImp->bOldEnablePrintFile = bOldEnablePrintFile;
}
//------------------------------------------------------------------------
void SfxPrintProgress::RestoreOnEndPrint( SfxPrinter *pOldPrinter )
{
RestoreOnEndPrint( pOldPrinter, FALSE );
}
//------------------------------------------------------------------------
void SfxPrintProgress::SetCancelHdl( const Link& aCancelHdl )
{
pImp->aCancelHdl = aCancelHdl;
}
<commit_msg>#88560#: allow to close frame after printing if controller received a request for that<commit_after>/*************************************************************************
*
* $RCSfile: prnmon.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: mba $ $Date: 2002-10-24 12:14:07 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _COM_SUN_STAR_UTIL_XCLOSEABLE_HPP_
#include <com/sun/star/util/XCloseable.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XCLOSEBROADCASTER_HPP_
#include <com/sun/star/util/XCloseBroadcaster.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XCLOSELISTENER_HPP_
#include <com/sun/star/util/XCloseListener.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_CLOSEVETOEXCEPTION_HPP_
#include <com/sun/star/util/CloseVetoException.hpp>
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef SVTOOLS_ASYNCLINK_HXX
#include <svtools/asynclink.hxx>
#endif
#include <svtools/printwarningoptions.hxx>
#pragma hdrstop
#include "prnmon.hxx"
#include "viewsh.hxx"
#include "viewfrm.hxx"
#include "objsh.hxx"
#include "docfile.hxx"
#include "sfxtypes.hxx"
#include "progress.hxx"
#include "desrupt.hxx"
#include "bindings.hxx"
#include "sfxresid.hxx"
#include "view.hrc"
//------------------------------------------------------------------------
#define SFX_TITLE_MAXLEN_PRINTMONITOR 22
//------------------------------------------------------------------------
struct SfxPrintMonitor_Impl: public ModelessDialog
{
SfxPrintMonitor_Impl( Window *pParent );
FixedText aDocName;
FixedText aPrinting;
FixedText aPrinter;
FixedText aPrintInfo;
CancelButton aCancel;
};
//-------------------------------------------------------------------------
struct SfxPrintProgress_Impl
{
SfxPrintMonitor_Impl* pMonitor;
SfxViewShell* pViewShell;
SfxPrinter* pPrinter;
SfxPrinter* pOldPrinter;
USHORT nLastPage;
BOOL bRunning;
BOOL bCancel;
BOOL bDeleteOnEndPrint;
BOOL bShow;
BOOL bCallbacks;
BOOL bOldEnablePrintFile;
BOOL bOldFlag;
BOOL bRestoreFlag;
svtools::AsynchronLink aDeleteLink;
Link aCancelHdl;
private:
DECL_LINK( CancelHdl, Button * );
DECL_STATIC_LINK( SfxPrintProgress_Impl, DeleteHdl, SfxPrintProgress * );
public:
SfxPrintProgress_Impl( SfxViewShell* pTheViewShell, SfxPrinter* pThePrinter );
~SfxPrintProgress_Impl();
void Delete( SfxPrintProgress* pAntiImpl ) { aDeleteLink.Call( pAntiImpl ); }
SfxViewShell* GetViewShell() const { return pViewShell; }
BOOL SetPage( USHORT nPage, const String &rPage );
};
//------------------------------------------------------------------------
SfxPrintMonitor_Impl::SfxPrintMonitor_Impl( Window* pParent ) :
ModelessDialog( pParent, SfxResId( DLG_PRINTMONITOR ) ),
aDocName ( this, ResId( FT_DOCNAME ) ),
aPrinting ( this, ResId( FT_PRINTING ) ),
aPrinter ( this, ResId( FT_PRINTER ) ),
aPrintInfo ( this, ResId( FT_PRINTINFO ) ),
aCancel ( this, ResId( PB_CANCELPRNMON ) )
{
FreeResource();
}
//------------------------------------------------------------------------
IMPL_STATIC_LINK( SfxPrintProgress_Impl, DeleteHdl, SfxPrintProgress*, pAntiImpl )
{
delete pAntiImpl;
return 0;
}
//------------------------------------------------------------------------
SfxPrintProgress_Impl::SfxPrintProgress_Impl( SfxViewShell* pTheViewShell,
SfxPrinter* pThePrinter ) :
pViewShell ( pTheViewShell ),
pPrinter ( pThePrinter ),
pOldPrinter ( NULL ),
bRunning ( TRUE ),
bDeleteOnEndPrint ( FALSE ),
bCancel ( FALSE ),
bCallbacks ( FALSE ),
bOldEnablePrintFile ( FALSE ),
bOldFlag ( TRUE ),
bRestoreFlag ( FALSE ),
nLastPage ( 0 ),
aDeleteLink ( STATIC_LINK( this, SfxPrintProgress_Impl, DeleteHdl ) )
{
Window* pParent =
pTheViewShell->GetWindow()->IsReallyVisible() ? pTheViewShell->GetWindow() : NULL;
pMonitor = new SfxPrintMonitor_Impl( pParent );
pMonitor->aDocName.SetText(
pViewShell->GetViewFrame()->GetObjectShell()->GetTitle( SFX_TITLE_MAXLEN_PRINTMONITOR ) );
pMonitor->aPrinter.SetText( pViewShell->GetPrinter()->GetName() );
pMonitor->aCancel.SetClickHdl( LINK( this, SfxPrintProgress_Impl, CancelHdl ) );
}
//------------------------------------------------------------------------
SfxPrintProgress_Impl::~SfxPrintProgress_Impl()
{
if ( pMonitor )
{
pMonitor->Hide(); // sieht optisch besser aus, wenn alles auf einmal verschwindet
delete pMonitor;
}
}
//------------------------------------------------------------------------
BOOL SfxPrintProgress_Impl::SetPage( USHORT nPage, const String &rPage )
{
// wurde der Druckauftrag abgebrochen?
if ( bCancel || !pMonitor )
return FALSE;
nLastPage = nPage;
String aStrPrintInfo = String( SfxResId( STR_PAGE ) );
if ( !rPage.Len() )
aStrPrintInfo += String::CreateFromInt32( nLastPage );
else
aStrPrintInfo += rPage;
pMonitor->aPrintInfo.SetText( aStrPrintInfo );
pMonitor->Update();
return TRUE;
}
//------------------------------------------------------------------------
IMPL_LINK_INLINE_START( SfxPrintProgress_Impl, CancelHdl, Button *, pButton )
{
if ( pMonitor )
pMonitor->Hide();
pViewShell->GetPrinter()->AbortJob();
bCancel = TRUE;
if ( aCancelHdl.IsSet() )
aCancelHdl.Call( this );
return 0;
}
IMPL_LINK_INLINE_END( SfxPrintProgress_Impl, CancelHdl, Button *, pButton )
//--------------------------------------------------------------------
SfxPrintProgress::SfxPrintProgress( SfxViewShell* pViewSh, FASTBOOL bShow )
: SfxProgress( pViewSh->GetViewFrame()->GetObjectShell(),
String(SfxResId(STR_PRINTING)), 1, FALSE ),
pImp( new SfxPrintProgress_Impl( pViewSh, pViewSh->GetPrinter() ) )
{
// Callback fuer Fehler und EndPrint setzen
pImp->pPrinter->SetEndPrintHdl(
LINK( this, SfxPrintProgress, EndPrintNotify ));
pImp->pPrinter->SetErrorHdl(
LINK( this, SfxPrintProgress, PrintErrorNotify ));
pImp->bCallbacks = TRUE;
//pImp->pViewShell->GetViewFrame()->GetFrame()->Lock_Impl(TRUE);
pImp->bShow = bShow;
Lock();
if ( !SvtPrintWarningOptions().IsModifyDocumentOnPrintingAllowed() )
{
pImp->bRestoreFlag = TRUE;
pImp->bOldFlag = pViewSh->GetObjectShell()->IsEnableSetModified();
if ( pImp->bOldFlag )
pViewSh->GetObjectShell()->EnableSetModified( FALSE );
}
}
//--------------------------------------------------------------------
SfxPrintProgress::~SfxPrintProgress()
{
// k"onnte auch schon weg sein (in EndPrintNotify)
DELETEZ(pImp->pMonitor);
// ggf. Callbacks entfermen
if ( pImp->bCallbacks )
{
pImp->pPrinter->SetEndPrintHdl( Link() );
pImp->pPrinter->SetErrorHdl( Link() );
pImp->bCallbacks = FALSE;
}
// ggf. vorherigen Drucker wieder einsetzen
if ( pImp->pOldPrinter )
pImp->pViewShell->SetPrinter( pImp->pOldPrinter, SFX_PRINTER_PRINTER );
else
// ggf. vorherigen Print-To-File-Status zuruecksetzen
pImp->pViewShell->GetPrinter()->EnablePrintFile(
pImp->bOldEnablePrintFile );
// EndPrint-Notification an Frame
//pImp->pViewShell->GetViewFrame()->GetFrame()->Lock_Impl(FALSE);
if ( pImp->pViewShell->GotOwnerShip_Impl() )
{
com::sun::star::uno::Reference < com::sun::star::util::XCloseable > xModel( pImp->pViewShell->GetObjectShell()->GetModel(), com::sun::star::uno::UNO_QUERY );
if ( xModel.is() )
{
try
{
xModel->close( sal_True );
}
catch ( com::sun::star::util::CloseVetoException& )
{
}
}
}
delete pImp;
}
//--------------------------------------------------------------------
BOOL SfxPrintProgress::SetState( ULONG nVal, ULONG nNewRange )
{
#ifndef MAC
// auf dem MAC kommt einer vom Betriebssystem
if ( pImp->bShow )
{
pImp->bShow = FALSE;
pImp->pMonitor->Show();
pImp->pMonitor->Update();
}
#endif
return pImp->SetPage( (USHORT)nVal, GetStateText_Impl() ) &&
SfxProgress::SetState( nVal, nNewRange );
}
//--------------------------------------------------------------------
void SfxPrintProgress::SetText( const String& rText )
{
if ( pImp->pMonitor )
{
pImp->pMonitor->SetText( rText );
pImp->pMonitor->Update();
}
SfxProgress::SetText( rText );
}
//------------------------------------------------------------------------
IMPL_LINK_INLINE_START( SfxPrintProgress, PrintErrorNotify, void *, pvoid )
{
if ( pImp->pMonitor )
pImp->pMonitor->Hide();
pImp->pPrinter->AbortJob();
InfoBox( pImp->GetViewShell()->GetWindow(),
String( SfxResId(STR_ERROR_PRINT) ) ).Execute();
if ( pImp->bRestoreFlag && pImp->pViewShell->GetObjectShell()->IsEnableSetModified() != pImp->bOldFlag )
pImp->pViewShell->GetObjectShell()->EnableSetModified( pImp->bOldFlag );
return 0;
}
IMPL_LINK_INLINE_END( SfxPrintProgress, PrintErrorNotify, void *, pvoid )
//------------------------------------------------------------------------
IMPL_LINK( SfxPrintProgress, EndPrintNotify, void *, pvoid )
{
if ( pImp->pMonitor )
pImp->pMonitor->Hide();
// Slots enablen
pImp->pViewShell->Invalidate( SID_PRINTDOC );
pImp->pViewShell->Invalidate( SID_PRINTDOCDIRECT );
pImp->pViewShell->Invalidate( SID_SETUPPRINTER );
// . . . falls der Printer im System umgestellt wurde, hier Aenderung
// nachziehen.
//! if( pMDI->IsPrinterChanged() ) pMDI->Changed( 0L );
// Callbacks rausnehmen
pImp->pPrinter->SetEndPrintHdl( Link() );
pImp->pPrinter->SetErrorHdl( Link() );
pImp->bCallbacks = FALSE;
// ggf. alten Printer wieder einsetzen
if ( pImp->pOldPrinter )
{
// Fix #59613#: niemals den aktuellen Printer synchron abschiessen !
// Da sowieso immer bDeleteOnEndPrint gesetzt wird, wird der der Drucker im
// dtor vom Printprogress ( dann aber asynchron !! ) zur"uckgesetzt.
/*
pImp->pViewShell->SetPrinter( pImp->pOldPrinter, SFX_PRINTER_PRINTER );
pImp->pOldPrinter = 0;
pImp->pPrinter = 0;
*/
}
else
// ggf. vorherigen Print-To-File-Status zuruecksetzen
pImp->pViewShell->GetPrinter()->EnablePrintFile( pImp->bOldEnablePrintFile );
// lief der Drucker im Thread?
if ( pImp->bDeleteOnEndPrint )
{
// Dialog sofort l"oschen sonst wird ggf. das MDI vorher geschlossen
DELETEZ(pImp->pMonitor);
// Progress per PostMessage zerst"oren, nicht sofort sonst GPF
pImp->Delete( this );
}
else
{
DBG_ASSERT( !pImp->pOldPrinter, "Printer konnte nicht korrekt restauriert werden!" );
pImp->bRunning = FALSE;
}
if ( pImp->bRestoreFlag && pImp->pViewShell->GetObjectShell()->IsEnableSetModified() != pImp->bOldFlag )
pImp->pViewShell->GetObjectShell()->EnableSetModified( TRUE );
return 0;
}
//------------------------------------------------------------------------
void SfxPrintProgress::DeleteOnEndPrint()
{
UnLock(); // jetzt schon, wg. Drucken im Thread
#ifndef WIN
// da das Drucken im 'Thread' unter Windows zu undefiniert ist bleibt der
// Print-Monitor dort stehen, auf den anderen Plattformen kann man dann
// weiterarbeiten, also kommt das Teil weg
DELETEZ( pImp->pMonitor );
#endif
pImp->bDeleteOnEndPrint = TRUE;
if ( !pImp->bRunning )
delete this;
}
//------------------------------------------------------------------------
void SfxPrintProgress::RestoreOnEndPrint( SfxPrinter *pOldPrinter,
BOOL bOldEnablePrintFile )
{
pImp->pOldPrinter = pOldPrinter;
pImp->bOldEnablePrintFile = bOldEnablePrintFile;
}
//------------------------------------------------------------------------
void SfxPrintProgress::RestoreOnEndPrint( SfxPrinter *pOldPrinter )
{
RestoreOnEndPrint( pOldPrinter, FALSE );
}
//------------------------------------------------------------------------
void SfxPrintProgress::SetCancelHdl( const Link& aCancelHdl )
{
pImp->aCancelHdl = aCancelHdl;
}
<|endoftext|> |
<commit_before>/**
* \file dcs/testbed/rain_workload_driver.hpp
*
* \brief Workload driver based on the RAIN workload toolkit.
*
* \author Marco Guazzone ([email protected])
*
* <hr/>
*
* Copyright (C) 2012 Marco Guazzone
* [Distributed Computing System (DCS) Group,
* Computer Science Institute,
* Department of Science and Technological Innovation,
* University of Piemonte Orientale,
* Alessandria (Italy)]
*
* This file is part of dcsxx-testbed.
*
* dcsxx-testbed is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* dcsxx-testbed is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with dcsxx-testbed. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef DCS_TESTBED_RAIN_WORKLOAD_DRIVER_HPP
#define DCS_TESTBED_RAIN_WORKLOAD_DRIVER_HPP
#include <boost/smart_ptr.hpp>
#include <cstdlib>
#include <dcs/exception.hpp>
#include <dcs/system/posix_process.hpp>
#include <dcs/system/process_status_category.hpp>
#include <dcs/testbed/base_workload_driver.hpp>
#include <istream>
extern "C" {
#include <pthread.h>
}
#include <string>
#include <vector>
namespace dcs { namespace testbed {
namespace detail {
namespace /*<unnamed>*/ {
inline
::std::string make_java_command(::std::string const& java_home)
{
return java_home + "/bin/java";
}
inline
::std::string make_java_command()
{
char* java_path = ::std::getenv("JAVA_HOME");
if (java_path)
{
return make_java_command(::std::string(java_path));
}
java_path = ::std::getenv("JRE_HOME");
if (java_path)
{
return make_java_command(::std::string(java_path));
}
return ::std::string("java");
}
/**
* \brief Build arguments to pass to RAIN workload toolkit.
*
* The basic structure of the RAIN command is:
* <pre>
* java [<java-arg1> ... <java-argN>] \
* -cp "rain.jar:<path to workload JAR>" \
* radlab.rain.Benchmark <path to Rain JSON configuration file>
* </pre>
*/
template <typename FwdIterT>
inline
::std::vector< ::std::string > make_rain_args(::std::string const& workload,
::std::string const& rain_home,
FwdIterT arg_first,
FwdIterT arg_last)
{
::std::vector< ::std::string > args(arg_first, arg_last);
args.push_back("-cp");
args.push_back(rain_home + "/rain.jar:" + rain_home + "/workloads/" + workload + ".jar");
args.push_back("radlab.rain.Benchmark");
args.push_back(rain_home + "/config/rain.config." + workload + ".json");
return args;
}
inline
::std::vector< ::std::string > make_rain_args(::std::string const& workload,
::std::string const& rain_home)
{
::std::vector< ::std::string > java_args;
java_args.push_back("-Xmx1g");
java_args.push_back("-Xms256m");
return make_rain_args(workload, rain_home, java_args.begin(), java_args.end());
}
inline
::std::vector< ::std::string > make_rain_args(::std::string const& workload)
{
return make_rain_args(workload, ".");
}
} // Namespace <unnamed>
void* monitor_rain_rampup(void* arg);
} // Namespace detail
class rain_workload_driver: public base_workload_driver
{
private: typedef ::dcs::system::posix_process sys_process_type;
private: typedef ::boost::shared_ptr<sys_process_type> sys_process_pointer;
friend void* detail::monitor_rain_rampup(void*);
public: enum workload_category
{
olio_workload
};
public: rain_workload_driver()
: p_thread_(0),
p_mutex_(0)
{
}
public: ~rain_workload_driver()
{
if (p_thread_)
{
::pthread_join(*p_thread_, 0);
}
}
public: rain_workload_driver(workload_category wkl_cat)
: cmd_(detail::make_java_command()),
args_(detail::make_rain_args(to_string(wkl_cat))),
ready_(false)
{
}
public: rain_workload_driver(workload_category wkl_cat,
::std::string const& rain_home)
: cmd_(detail::make_java_command()),
args_(detail::make_rain_args(to_string(wkl_cat), rain_home)),
ready_(false)
{
}
public: rain_workload_driver(workload_category wkl_cat,
::std::string const& rain_home,
::std::string const& java_home)
: cmd_(detail::make_java_command(java_home)),
args_(detail::make_rain_args(to_string(wkl_cat), rain_home)),
ready_(false)
{
}
public: template <typename FwdIterT>
rain_workload_driver(workload_category wkl_cat,
::std::string const& rain_home,
::std::string const& java_home,
FwdIterT arg_first,
FwdIterT arg_last)
: cmd_(detail::make_java_command(java_home)),
args_(detail::make_rain_args(to_string(wkl_cat), rain_home, arg_first, arg_last)),
ready_(false)
{
}
private: static ::std::string to_string(workload_category wkl_cat)
{
switch (wkl_cat)
{
case olio_workload:
return "olio";
}
DCS_EXCEPTION_THROW(::std::invalid_argument,
"Unknown workload category");
}
private: void ready(bool val)
{
::pthread_mutex_lock(p_mutex_);
ready_ = val;
::pthread_mutex_unlock(p_mutex_);
}
private: sys_process_pointer process()
{
return p_proc_;
}
private: sys_process_pointer process() const
{
return p_proc_;
}
private: void do_start()
{
if (p_proc_ && p_proc_->alive())
{
p_proc_->terminate();
}
ready_ = false;
p_proc_ = ::boost::make_shared<sys_process_type>(cmd_);
p_proc_->asynch(true);
p_proc_->run(args_.begin(), args_.end(), false, false, true);
if (p_proc_->status() != ::dcs::system::running_process_status)
{
DCS_EXCEPTION_THROW(::std::runtime_error,
"Unable to start RAIN workload driver");
}
//TODO: create a thread that monitor the output of the process
::pthread_create(p_thread_, 0, &detail::monitor_rain_rampup, this);
}
private: void do_stop()
{
p_proc_->terminate();
if (::pthread_join(*p_thread_, 0) != 0)
{
DCS_EXCEPTION_THROW(::std::runtime_error,
"Unable to join thread");
}
p_thread_ = 0;
}
private: bool do_alive() const
{
return p_proc_->alive();
}
private: bool do_ready() const
{
return ready_;
}
private: ::std::string cmd_;
private: ::std::vector< ::std::string > args_;
private: sys_process_pointer p_proc_;
private: bool ready_;
private: ::pthread_t* p_thread_;
private: ::pthread_mutex_t* p_mutex_;
}; // rain_workload_driver
namespace detail {
inline
void* monitor_rain_rampup(void* arg)
{
rain_workload_driver* p_driver = static_cast<rain_workload_driver*>(arg);
::std::istream& eis = p_driver->process()->error_stream();
while (eis.good())
{
::std::string line;
::std::getline(eis, line);
// Look for "Ramp up finished!" string
if (line.find("Ramp up finished") != ::std::string::npos)
{
p_driver->ready(true);
break;
}
}
return 0;
}
} // Namespace detail
}} // Namespace dcs::testbed
#endif // DCS_TESTBED_RAIN_WORKLOAD_DRIVER_HPP
<commit_msg>(change:major) * Process and thread are not stored as pointers * Added thread clean-up code.<commit_after>/**
* \file dcs/testbed/rain_workload_driver.hpp
*
* \brief Workload driver based on the RAIN workload toolkit.
*
* \author Marco Guazzone ([email protected])
*
* <hr/>
*
* Copyright (C) 2012 Marco Guazzone
* [Distributed Computing System (DCS) Group,
* Computer Science Institute,
* Department of Science and Technological Innovation,
* University of Piemonte Orientale,
* Alessandria (Italy)]
*
* This file is part of dcsxx-testbed.
*
* dcsxx-testbed is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* dcsxx-testbed is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with dcsxx-testbed. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef DCS_TESTBED_RAIN_WORKLOAD_DRIVER_HPP
#define DCS_TESTBED_RAIN_WORKLOAD_DRIVER_HPP
#include <boost/smart_ptr.hpp>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <dcs/exception.hpp>
#include <dcs/system/posix_process.hpp>
#include <dcs/system/process_status_category.hpp>
#include <dcs/testbed/base_workload_driver.hpp>
#include <istream>
extern "C" {
#include <pthread.h>
}
#include <string>
#include <vector>
namespace dcs { namespace testbed {
namespace detail {
namespace /*<unnamed>*/ {
inline
::std::string make_java_command(::std::string const& java_home)
{
return java_home + "/bin/java";
}
inline
::std::string make_java_command()
{
char* java_path = ::std::getenv("JAVA_HOME");
if (java_path)
{
return make_java_command(::std::string(java_path));
}
java_path = ::std::getenv("JRE_HOME");
if (java_path)
{
return make_java_command(::std::string(java_path));
}
return ::std::string("java");
}
/**
* \brief Build arguments to pass to RAIN workload toolkit.
*
* The basic structure of the RAIN command is:
* <pre>
* java [<java-arg1> ... <java-argN>] \
* -cp "rain.jar:<path to workload JAR>" \
* radlab.rain.Benchmark <path to Rain JSON configuration file>
* </pre>
*/
template <typename FwdIterT>
inline
::std::vector< ::std::string > make_rain_args(::std::string const& workload,
::std::string const& rain_home,
FwdIterT arg_first,
FwdIterT arg_last)
{
::std::vector< ::std::string > args(arg_first, arg_last);
args.push_back("-cp");
args.push_back(rain_home + "/rain.jar:" + rain_home + "/workloads/" + workload + ".jar");
args.push_back("radlab.rain.Benchmark");
args.push_back(rain_home + "/config/rain.config." + workload + ".json");
return args;
}
inline
::std::vector< ::std::string > make_rain_args(::std::string const& workload,
::std::string const& rain_home)
{
::std::vector< ::std::string > java_args;
java_args.push_back("-Xmx1g");
java_args.push_back("-Xms256m");
return make_rain_args(workload, rain_home, java_args.begin(), java_args.end());
}
inline
::std::vector< ::std::string > make_rain_args(::std::string const& workload)
{
return make_rain_args(workload, ".");
}
} // Namespace <unnamed>
void* monitor_rain_rampup(void* arg);
} // Namespace detail
class rain_workload_driver: public base_workload_driver
{
private: typedef ::dcs::system::posix_process sys_process_type;
private: typedef ::boost::shared_ptr<sys_process_type> sys_process_pointer;
friend void* detail::monitor_rain_rampup(void*);
public: enum workload_category
{
olio_workload
};
public: rain_workload_driver(workload_category wkl_cat)
: cmd_(detail::make_java_command()),
args_(detail::make_rain_args(to_string(wkl_cat))),
ready_(false)
{
}
public: rain_workload_driver(workload_category wkl_cat,
::std::string const& rain_home)
: cmd_(detail::make_java_command()),
args_(detail::make_rain_args(to_string(wkl_cat), rain_home)),
ready_(false)
{
}
public: rain_workload_driver(workload_category wkl_cat,
::std::string const& rain_home,
::std::string const& java_home)
: cmd_(detail::make_java_command(java_home)),
args_(detail::make_rain_args(to_string(wkl_cat), rain_home)),
ready_(false)
{
}
public: template <typename FwdIterT>
rain_workload_driver(workload_category wkl_cat,
::std::string const& rain_home,
::std::string const& java_home,
FwdIterT arg_first,
FwdIterT arg_last)
: cmd_(detail::make_java_command(java_home)),
args_(detail::make_rain_args(to_string(wkl_cat), rain_home, arg_first, arg_last)),
ready_(false)
{
}
public: ~rain_workload_driver()
{
try
{
proc_.terminate();
}
catch (...)
{
// empty
}
::pthread_cancel(thread_);
::pthread_join(thread_, 0);
}
private: static ::std::string to_string(workload_category wkl_cat)
{
switch (wkl_cat)
{
case olio_workload:
return "olio";
}
DCS_EXCEPTION_THROW(::std::invalid_argument,
"Unknown workload category");
}
private: void ready(bool val)
{
::pthread_mutex_lock(&mutex_);
ready_ = val;
::pthread_mutex_unlock(&mutex_);
}
private: sys_process_type process()
{
return proc_;
}
private: sys_process_type process() const
{
return proc_;
}
private: void do_start()
{
// Stop previously running process and thread (if any)
if (proc_.alive())
{
proc_.terminate();
}
pthread_cancel(thread_);
pthread_join(thread_, 0);
// Run a new process
ready_ = false;
proc_ = sys_process_type(cmd_);
proc_.asynch(true);
proc_.run(args_.begin(), args_.end(), false, false, true);
if (proc_.status() != ::dcs::system::running_process_status)
{
::std::ostringstream oss;
oss << "Unable to start RAIN workload driver: " << ::strerror(errno);
DCS_EXCEPTION_THROW(::std::runtime_error, oss.str());
}
// Run a thread to monitor RAIN ramp-up (transient) phase
if (::pthread_create(&thread_, 0, &detail::monitor_rain_rampup, this) != 0)
{
::std::ostringstream oss;
oss << "Unable to start transient phase monitor thread for the RAIN workload driver: " << ::strerror(errno);
DCS_EXCEPTION_THROW(::std::runtime_error,
"Unable to start transient phase monitor thread for the RAIN workload driver");
}
}
private: void do_stop()
{
proc_.terminate();
if (::pthread_cancel(thread_) != 0)
{
::std::ostringstream oss;
oss << "Unable to cancel transient phase monitor thread for the RAIN workload driver: " << ::strerror(errno);
DCS_EXCEPTION_THROW(::std::runtime_error, oss.str());
}
if (::pthread_join(thread_, 0) != 0)
{
::std::ostringstream oss;
oss << "Unable to join transient phase monitor thread for the RAIN workload driver: " << ::strerror(errno);
DCS_EXCEPTION_THROW(::std::runtime_error, oss.str());
}
}
private: bool do_alive() const
{
return proc_.alive();
}
private: bool do_ready() const
{
return ready_;
}
private: ::std::string cmd_;
private: ::std::vector< ::std::string > args_;
private: bool ready_;
private: sys_process_type proc_;
private: ::pthread_t thread_;
private: ::pthread_mutex_t mutex_;
}; // rain_workload_driver
namespace detail {
inline
void* monitor_rain_rampup(void* arg)
{
rain_workload_driver* p_driver = static_cast<rain_workload_driver*>(arg);
::std::istream& eis = p_driver->process().error_stream();
while (eis.good())
{
::std::string line;
::std::getline(eis, line);
// Look for "Ramp up finished!" string
if (line.find("Ramp up finished") != ::std::string::npos)
{
p_driver->ready(true);
break;
}
}
return 0;
}
} // Namespace detail
}} // Namespace dcs::testbed
#endif // DCS_TESTBED_RAIN_WORKLOAD_DRIVER_HPP
<|endoftext|> |
<commit_before>#include "drawRule.h"
#include "tile/tile.h"
#include "scene/scene.h"
#include "scene/sceneLayer.h"
#include "scene/stops.h"
#include "scene/styleContext.h"
#include "style/style.h"
#include "platform.h"
#include <algorithm>
namespace Tangram {
DrawRuleData::DrawRuleData(std::string _name, int _id,
const std::vector<StyleParam>& _parameters) :
parameters(_parameters),
name(std::move(_name)),
id(_id) {}
std::string DrawRuleData::toString() const {
std::string str = "{\n";
for (auto& p : parameters) {
str += " { "
+ std::to_string(static_cast<int>(p.key))
+ ", "
+ p.toString()
+ " }\n";
}
str += "}\n";
return str;
}
DrawRule::DrawRule(const DrawRuleData& _ruleData) :
name(&_ruleData.name),
id(_ruleData.id) {}
void DrawRule::merge(const DrawRuleData& _ruleData, const SceneLayer& _layer) {
for (const auto& param : _ruleData.parameters) {
auto key = static_cast<uint8_t>(param.key);
const auto depthOld = depths[key];
const auto depthNew = _layer.depth();
const char* layerOld = layers[key];
const char* layerNew = _layer.name().c_str();
if (depthNew > depthOld || (depthNew == depthOld && strcmp(layerNew, layerOld) > 0)) {
params[key] = ¶m;
depths[key] = depthNew;
layers[key] = layerNew;
}
}
}
bool DrawRule::isJSFunction(StyleParamKey _key) const {
auto& param = findParameter(_key);
if (!param) {
return false;
}
return param.function >= 0;
}
bool DrawRule::contains(StyleParamKey _key) const {
return findParameter(_key) != false;
}
const StyleParam& DrawRule::findParameter(StyleParamKey _key) const {
static const StyleParam NONE;
const auto* p = params[static_cast<uint8_t>(_key)];
if (p) {
return *p;
}
return NONE;
}
const std::string& DrawRule::getStyleName() const {
const auto& style = findParameter(StyleParamKey::style);
if (style) {
return style.value.get<std::string>();
} else {
return *name;
}
}
void DrawRule::logGetError(StyleParamKey _expectedKey, const StyleParam& _param) const {
LOGE("wrong type '%d'for StyleParam '%d'", _param.value.which(), _expectedKey);
}
bool DrawRuleMergeSet::match(const Feature& _feature, const SceneLayer& _layer, StyleContext& _ctx) {
_ctx.setFeature(_feature);
matchedRules.clear();
queuedLayers.clear();
// If the first filter doesn't match, return immediately
if (!_layer.filter().eval(_feature, _ctx)) { return false; }
// Add the first layer to the stack
queuedLayers.push_back(&_layer);
// Iterate depth-first over the layer hierarchy
while (!queuedLayers.empty()) {
// Pop a layer off the top of the stack
const auto& layer = *queuedLayers.back();
queuedLayers.pop_back();
// If the filter doesn't pass, move on to the next one
if (!layer.filter().eval(_feature, _ctx)) { continue; }
// Push each of the layer's sublayers onto the stack
for (const auto& sublayer : layer.sublayers()) {
queuedLayers.push_back(&sublayer);
}
// Merge rules from current layer into accumulated set
mergeRules(layer);
}
return true;
}
void DrawRuleMergeSet::apply(const Feature& _feature, const Scene& _scene, const SceneLayer& _layer,
StyleContext& _ctx, Tile& _tile) {
// If no rules matched the feature, return immediately
if (!match(_feature, _layer, _ctx)) { return; }
// For each matched rule, find the style to be used and build the feature with the rule's parameters
for (auto& rule : matchedRules) {
auto* style = _scene.findStyle(rule.getStyleName());
if (!style) {
LOGE("Invalid style %s", rule.getStyleName().c_str());
continue;
}
// Evaluate JS functions and Stops
bool valid = true;
for (size_t i = 0; i < StyleParamKeySize; ++i) {
auto* param = rule.params[i];
if (!param) { continue; }
if (param->function >= 0) {
if (!_ctx.evalStyle(param->function, param->key, evaluated[i].value) && StyleParam::isRequired(param->key)) {
valid = false;
break;
}
evaluated[i].function = param->function;
rule.params[i] = &evaluated[i];
}
if (param->stops) {
evaluated[i].stops = param->stops;
if (StyleParam::isColor(param->key)) {
evaluated[i].value = param->stops->evalColor(_ctx.getGlobalZoom());
} else if (StyleParam::isWidth(param->key)) {
// FIXME width result is ignored from here
evaluated[i].value = param->stops->evalWidth(_ctx.getGlobalZoom());
} else {
evaluated[i].value = param->stops->evalFloat(_ctx.getGlobalZoom());
}
rule.params[i] = &evaluated[i];
}
}
if (valid) {
style->buildFeature(_tile, _feature, rule);
}
}
}
void DrawRuleMergeSet::mergeRules(const SceneLayer& _layer) {
for (const auto& rule : _layer.rules()) {
auto it = std::find_if(matchedRules.begin(), matchedRules.end(),
[&](auto& m) { return rule.id == m.id; });
if (it == matchedRules.end()) {
it = matchedRules.insert(it, DrawRule(rule));
}
it->merge(rule, _layer);
}
}
}
<commit_msg>Prevent potentially passing a null pointer to strcmp<commit_after>#include "drawRule.h"
#include "tile/tile.h"
#include "scene/scene.h"
#include "scene/sceneLayer.h"
#include "scene/stops.h"
#include "scene/styleContext.h"
#include "style/style.h"
#include "platform.h"
#include <algorithm>
namespace Tangram {
DrawRuleData::DrawRuleData(std::string _name, int _id,
const std::vector<StyleParam>& _parameters) :
parameters(_parameters),
name(std::move(_name)),
id(_id) {}
std::string DrawRuleData::toString() const {
std::string str = "{\n";
for (auto& p : parameters) {
str += " { "
+ std::to_string(static_cast<int>(p.key))
+ ", "
+ p.toString()
+ " }\n";
}
str += "}\n";
return str;
}
DrawRule::DrawRule(const DrawRuleData& _ruleData) :
name(&_ruleData.name),
id(_ruleData.id) {
const static char* empty = "";
std::fill_n(layers, StyleParamKeySize, empty);
}
void DrawRule::merge(const DrawRuleData& _ruleData, const SceneLayer& _layer) {
for (const auto& param : _ruleData.parameters) {
auto key = static_cast<uint8_t>(param.key);
const auto depthOld = depths[key];
const auto depthNew = _layer.depth();
const char* layerOld = layers[key];
const char* layerNew = _layer.name().c_str();
if (depthNew > depthOld || (depthNew == depthOld && strcmp(layerNew, layerOld) > 0)) {
params[key] = ¶m;
depths[key] = depthNew;
layers[key] = layerNew;
}
}
}
bool DrawRule::isJSFunction(StyleParamKey _key) const {
auto& param = findParameter(_key);
if (!param) {
return false;
}
return param.function >= 0;
}
bool DrawRule::contains(StyleParamKey _key) const {
return findParameter(_key) != false;
}
const StyleParam& DrawRule::findParameter(StyleParamKey _key) const {
static const StyleParam NONE;
const auto* p = params[static_cast<uint8_t>(_key)];
if (p) {
return *p;
}
return NONE;
}
const std::string& DrawRule::getStyleName() const {
const auto& style = findParameter(StyleParamKey::style);
if (style) {
return style.value.get<std::string>();
} else {
return *name;
}
}
void DrawRule::logGetError(StyleParamKey _expectedKey, const StyleParam& _param) const {
LOGE("wrong type '%d'for StyleParam '%d'", _param.value.which(), _expectedKey);
}
bool DrawRuleMergeSet::match(const Feature& _feature, const SceneLayer& _layer, StyleContext& _ctx) {
_ctx.setFeature(_feature);
matchedRules.clear();
queuedLayers.clear();
// If the first filter doesn't match, return immediately
if (!_layer.filter().eval(_feature, _ctx)) { return false; }
// Add the first layer to the stack
queuedLayers.push_back(&_layer);
// Iterate depth-first over the layer hierarchy
while (!queuedLayers.empty()) {
// Pop a layer off the top of the stack
const auto& layer = *queuedLayers.back();
queuedLayers.pop_back();
// If the filter doesn't pass, move on to the next one
if (!layer.filter().eval(_feature, _ctx)) { continue; }
// Push each of the layer's sublayers onto the stack
for (const auto& sublayer : layer.sublayers()) {
queuedLayers.push_back(&sublayer);
}
// Merge rules from current layer into accumulated set
mergeRules(layer);
}
return true;
}
void DrawRuleMergeSet::apply(const Feature& _feature, const Scene& _scene, const SceneLayer& _layer,
StyleContext& _ctx, Tile& _tile) {
// If no rules matched the feature, return immediately
if (!match(_feature, _layer, _ctx)) { return; }
// For each matched rule, find the style to be used and build the feature with the rule's parameters
for (auto& rule : matchedRules) {
auto* style = _scene.findStyle(rule.getStyleName());
if (!style) {
LOGE("Invalid style %s", rule.getStyleName().c_str());
continue;
}
// Evaluate JS functions and Stops
bool valid = true;
for (size_t i = 0; i < StyleParamKeySize; ++i) {
auto* param = rule.params[i];
if (!param) { continue; }
if (param->function >= 0) {
if (!_ctx.evalStyle(param->function, param->key, evaluated[i].value) && StyleParam::isRequired(param->key)) {
valid = false;
break;
}
evaluated[i].function = param->function;
rule.params[i] = &evaluated[i];
}
if (param->stops) {
evaluated[i].stops = param->stops;
if (StyleParam::isColor(param->key)) {
evaluated[i].value = param->stops->evalColor(_ctx.getGlobalZoom());
} else if (StyleParam::isWidth(param->key)) {
// FIXME width result is ignored from here
evaluated[i].value = param->stops->evalWidth(_ctx.getGlobalZoom());
} else {
evaluated[i].value = param->stops->evalFloat(_ctx.getGlobalZoom());
}
rule.params[i] = &evaluated[i];
}
}
if (valid) {
style->buildFeature(_tile, _feature, rule);
}
}
}
void DrawRuleMergeSet::mergeRules(const SceneLayer& _layer) {
for (const auto& rule : _layer.rules()) {
auto it = std::find_if(matchedRules.begin(), matchedRules.end(),
[&](auto& m) { return rule.id == m.id; });
if (it == matchedRules.end()) {
it = matchedRules.insert(it, DrawRule(rule));
}
it->merge(rule, _layer);
}
}
}
<|endoftext|> |
<commit_before>#include <string>
#include "PointerSubgraphValidator.h"
namespace dg {
namespace analysis {
namespace pta {
namespace debug {
static void dumpNode(const PSNode *nd, std::string& errors) {
errors += std::string(PSNodeTypeToCString(nd->getType())) + " with ID " +
std::to_string(nd->getID()) + "\n - operands: [";
for (unsigned i = 0, e = nd->getOperandsNum(); i < e; ++i) {
const PSNode *op = nd->getOperand(i);
errors += std::to_string(op->getID()) += " ";
errors += std::string(PSNodeTypeToCString(op->getType()));
if (i != e - 1)
errors += ", ";
}
errors += "]\n";
}
bool PointerSubgraphValidator::reportInvalOperands(const PSNode *nd, const std::string& user_err) {
errors += "Invalid operands:\n";
dumpNode(nd, errors);
if (!user_err.empty())
errors += "(" + user_err + ")\n";
return true;
}
bool PointerSubgraphValidator::reportInvalEdges(const PSNode *nd, const std::string& user_err) {
errors += "Invalid number of edges:\n";
dumpNode(nd, errors);
if (!user_err.empty())
errors += "(" + user_err + ")\n";
return true;
}
bool PointerSubgraphValidator::reportInvalNode(const PSNode *nd, const std::string& user_err) {
errors += "Invalid node:\n";
dumpNode(nd, errors);
if (!user_err.empty())
errors += "(" + user_err + ")\n";
return true;
}
bool PointerSubgraphValidator::reportUnreachableNode(const PSNode *nd) {
errors += "Unreachable node:\n";
dumpNode(nd, errors);
return true;
}
static bool hasDuplicateOperand(const PSNode *nd)
{
std::set<const PSNode *> ops;
for (const PSNode *op : nd->getOperands()) {
if (!ops.insert(op).second)
return true;
}
return false;
}
bool PointerSubgraphValidator::checkOperands() {
bool invalid = false;
std::set<const PSNode *> known_nodes;
const auto& nodes = PS->getNodes();
for (const PSNode *nd : nodes) {
if (!nd)
continue;
if (!known_nodes.insert(nd).second)
invalid |= reportInvalNode(nd, "Node multiple times in the graph");
}
for (const PSNode *nd : nodes) {
if (!nd)
continue;
for (const PSNode *op : nd->getOperands()) {
if (op != NULLPTR && op != UNKNOWN_MEMORY && op != INVALIDATED &&
known_nodes.count(op) == 0) {
invalid |= reportInvalOperands(nd, "Node has unknown (maybe dangling) operand");
}
}
switch (nd->getType()) {
case PSNodeType::PHI:
if (nd->getOperandsNum() == 0) {
invalid |= reportInvalOperands(nd, "Empty PHI");
} else if (hasDuplicateOperand(nd)) {
invalid |= reportInvalOperands(nd, "PHI Node contains duplicated operand");
}
break;
case PSNodeType::NULL_ADDR:
case PSNodeType::UNKNOWN_MEM:
case PSNodeType::NOOP:
case PSNodeType::FUNCTION:
if (nd->getOperandsNum() != 0) {
invalid |= reportInvalOperands(nd, "Should not have an operand");
}
break;
case PSNodeType::GEP:
case PSNodeType::LOAD:
case PSNodeType::CAST:
case PSNodeType::INVALIDATE_OBJECT:
case PSNodeType::CONSTANT:
case PSNodeType::FREE:
if (nd->getOperandsNum() != 1) {
invalid |= reportInvalOperands(nd, "Should have exactly one operand");
}
break;
case PSNodeType::STORE:
case PSNodeType::MEMCPY:
if (nd->getOperandsNum() != 2) {
invalid |= reportInvalOperands(nd, "Should have exactly two operands");
}
break;
}
}
return invalid;
}
static inline bool isInPredecessors(const PSNode *nd, const PSNode *of) {
for (const PSNode *pred: of->getPredecessors()) {
if (pred == nd)
return true;
}
return false;
}
static inline bool canBeOutsideGraph(const PSNode *nd) {
return (nd->getType() == PSNodeType::FUNCTION ||
nd->getType() == PSNodeType::CONSTANT ||
nd->getType() == PSNodeType::UNKNOWN_MEM ||
nd->getType() == PSNodeType::NULL_ADDR);
}
std::set<const PSNode *> reachableNodes(const PSNode *nd) {
std::set<const PSNode *> reachable;
reachable.insert(nd);
std::vector<const PSNode *> to_process;
to_process.reserve(4);
to_process.push_back(nd);
while (!to_process.empty()) {
std::vector<const PSNode *> new_to_process;
new_to_process.reserve(to_process.size());
for (const PSNode *cur : to_process) {
for (const PSNode *succ : cur->getSuccessors()) {
if (reachable.insert(succ).second)
new_to_process.push_back(succ);
}
}
new_to_process.swap(to_process);
}
return reachable;
}
bool PointerSubgraphValidator::checkEdges() {
bool invalid = false;
// check incoming/outcoming edges of all nodes
auto nodes = PS->getNodes();
for (const PSNode *nd : nodes) {
if (!nd)
continue;
if (nd->predecessorsNum() == 0 && nd != PS->getRoot() && !canBeOutsideGraph(nd)) {
invalid |= reportInvalEdges(nd, "Non-root node has no predecessors");
}
for (const PSNode *succ : nd->getSuccessors()) {
if (!isInPredecessors(nd, succ))
invalid |= reportInvalEdges(nd, "Node not set as a predecessor of some of its successors");
}
}
// check that the edges form valid CFG (all nodes are reachable)
auto reachable = reachableNodes(PS->getRoot());
for (const PSNode *nd : nodes) {
if (!nd)
continue;
if (reachable.count(nd) < 1 && !canBeOutsideGraph(nd)) {
invalid |= reportUnreachableNode(nd);
}
}
return invalid;
}
bool PointerSubgraphValidator::validate() {
bool invalid = false;
invalid |= checkOperands();
invalid |= checkEdges();
return invalid;
}
} // namespace debug
} // namespace pta
} // namespace analysis
} // namespace dg
<commit_msg>PTA validator: check the type of operands<commit_after>#include <string>
#include "PointerSubgraphValidator.h"
namespace dg {
namespace analysis {
namespace pta {
namespace debug {
static void dumpNode(const PSNode *nd, std::string& errors) {
errors += std::string(PSNodeTypeToCString(nd->getType())) + " with ID " +
std::to_string(nd->getID()) + "\n - operands: [";
for (unsigned i = 0, e = nd->getOperandsNum(); i < e; ++i) {
const PSNode *op = nd->getOperand(i);
errors += std::to_string(op->getID()) += " ";
errors += std::string(PSNodeTypeToCString(op->getType()));
if (i != e - 1)
errors += ", ";
}
errors += "]\n";
}
bool PointerSubgraphValidator::reportInvalOperands(const PSNode *nd, const std::string& user_err) {
errors += "Invalid operands:\n";
dumpNode(nd, errors);
if (!user_err.empty())
errors += "(" + user_err + ")\n";
return true;
}
bool PointerSubgraphValidator::reportInvalEdges(const PSNode *nd, const std::string& user_err) {
errors += "Invalid number of edges:\n";
dumpNode(nd, errors);
if (!user_err.empty())
errors += "(" + user_err + ")\n";
return true;
}
bool PointerSubgraphValidator::reportInvalNode(const PSNode *nd, const std::string& user_err) {
errors += "Invalid node:\n";
dumpNode(nd, errors);
if (!user_err.empty())
errors += "(" + user_err + ")\n";
return true;
}
bool PointerSubgraphValidator::reportUnreachableNode(const PSNode *nd) {
errors += "Unreachable node:\n";
dumpNode(nd, errors);
return true;
}
static bool hasDuplicateOperand(const PSNode *nd)
{
std::set<const PSNode *> ops;
for (const PSNode *op : nd->getOperands()) {
if (!ops.insert(op).second)
return true;
}
return false;
}
static bool hasNonpointerOperand(const PSNode *nd)
{
for (const PSNode *op : nd->getOperands()) {
if (op->getType() == PSNodeType::NOOP ||
op->getType() == PSNodeType::FREE ||
op->getType() == PSNodeType::ENTRY ||
op->getType() == PSNodeType::INVALIDATE_LOCALS ||
op->getType() == PSNodeType::INVALIDATE_OBJECT ||
op->getType() == PSNodeType::MEMCPY ||
op->getType() == PSNodeType::STORE)
return true;
}
return false;
}
bool PointerSubgraphValidator::checkOperands() {
bool invalid = false;
std::set<const PSNode *> known_nodes;
const auto& nodes = PS->getNodes();
for (const PSNode *nd : nodes) {
if (!nd)
continue;
if (!known_nodes.insert(nd).second)
invalid |= reportInvalNode(nd, "Node multiple times in the graph");
}
for (const PSNode *nd : nodes) {
if (!nd)
continue;
for (const PSNode *op : nd->getOperands()) {
if (op != NULLPTR && op != UNKNOWN_MEMORY && op != INVALIDATED &&
known_nodes.count(op) == 0) {
invalid |= reportInvalOperands(nd, "Node has unknown (maybe dangling) operand");
}
}
switch (nd->getType()) {
case PSNodeType::PHI:
if (nd->getOperandsNum() == 0) {
invalid |= reportInvalOperands(nd, "Empty PHI");
} else if (hasDuplicateOperand(nd)) {
invalid |= reportInvalOperands(nd, "PHI Node contains duplicated operand");
} else if (hasNonpointerOperand(nd)) {
invalid |= reportInvalOperands(nd, "PHI Node contains non-pointer operand");
}
break;
case PSNodeType::NULL_ADDR:
case PSNodeType::UNKNOWN_MEM:
case PSNodeType::NOOP:
case PSNodeType::FUNCTION:
if (nd->getOperandsNum() != 0) {
invalid |= reportInvalOperands(nd, "Should not have an operand");
}
break;
case PSNodeType::GEP:
case PSNodeType::LOAD:
case PSNodeType::CAST:
case PSNodeType::INVALIDATE_OBJECT:
case PSNodeType::CONSTANT:
case PSNodeType::FREE:
if (hasNonpointerOperand(nd)) {
invalid |= reportInvalOperands(nd, "Node has non-pointer operand");
}
if (nd->getOperandsNum() != 1) {
invalid |= reportInvalOperands(nd, "Should have exactly one operand");
}
break;
case PSNodeType::STORE:
case PSNodeType::MEMCPY:
if (hasNonpointerOperand(nd)) {
invalid |= reportInvalOperands(nd, "Node has non-pointer operand");
}
if (nd->getOperandsNum() != 2) {
invalid |= reportInvalOperands(nd, "Should have exactly two operands");
}
break;
}
}
return invalid;
}
static inline bool isInPredecessors(const PSNode *nd, const PSNode *of) {
for (const PSNode *pred: of->getPredecessors()) {
if (pred == nd)
return true;
}
return false;
}
static inline bool canBeOutsideGraph(const PSNode *nd) {
return (nd->getType() == PSNodeType::FUNCTION ||
nd->getType() == PSNodeType::CONSTANT ||
nd->getType() == PSNodeType::UNKNOWN_MEM ||
nd->getType() == PSNodeType::NULL_ADDR);
}
std::set<const PSNode *> reachableNodes(const PSNode *nd) {
std::set<const PSNode *> reachable;
reachable.insert(nd);
std::vector<const PSNode *> to_process;
to_process.reserve(4);
to_process.push_back(nd);
while (!to_process.empty()) {
std::vector<const PSNode *> new_to_process;
new_to_process.reserve(to_process.size());
for (const PSNode *cur : to_process) {
for (const PSNode *succ : cur->getSuccessors()) {
if (reachable.insert(succ).second)
new_to_process.push_back(succ);
}
}
new_to_process.swap(to_process);
}
return reachable;
}
bool PointerSubgraphValidator::checkEdges() {
bool invalid = false;
// check incoming/outcoming edges of all nodes
auto nodes = PS->getNodes();
for (const PSNode *nd : nodes) {
if (!nd)
continue;
if (nd->predecessorsNum() == 0 && nd != PS->getRoot() && !canBeOutsideGraph(nd)) {
invalid |= reportInvalEdges(nd, "Non-root node has no predecessors");
}
for (const PSNode *succ : nd->getSuccessors()) {
if (!isInPredecessors(nd, succ))
invalid |= reportInvalEdges(nd, "Node not set as a predecessor of some of its successors");
}
}
// check that the edges form valid CFG (all nodes are reachable)
auto reachable = reachableNodes(PS->getRoot());
for (const PSNode *nd : nodes) {
if (!nd)
continue;
if (reachable.count(nd) < 1 && !canBeOutsideGraph(nd)) {
invalid |= reportUnreachableNode(nd);
}
}
return invalid;
}
bool PointerSubgraphValidator::validate() {
bool invalid = false;
invalid |= checkOperands();
invalid |= checkEdges();
return invalid;
}
} // namespace debug
} // namespace pta
} // namespace analysis
} // namespace dg
<|endoftext|> |
<commit_before>/***************************************************************************
* @file main.cpp
* @author Alan.W
* @date 07 JAN 2014
* @remark
***************************************************************************/
//!
//! Exercise 13.47:
//! Give the copy constructor and copy-assignment operator in your String class
//! from exercise 13.44 in § 13.5 (p. 531) a statement that prints a message
//! each time the function is executed.
//!
//! Exercise 13.48:
//! Define a vector<String> and call push_back several times on that vector.
//! Run your program and see how often Strings are copied.
// times = 2i;///////error
//!
#include "string.h"
#include <vector>
int main()
{
std::vector<String> v;
String s("sssssss");
for (unsigned i = 0; i != 3; ++i)
v.push_back(s);
return 0;
}
<commit_msg>update the ans to 13.48<commit_after>/***************************************************************************
* @file main.cpp
* @author Alan.W
* @date 07 JAN 2014
* @remark
***************************************************************************/
//!
//! Exercise 13.47:
//! Give the copy constructor and copy-assignment operator in your String class
//! from exercise 13.44 in § 13.5 (p. 531) a statement that prints a message
//! each time the function is executed.
//!
//! Exercise 13.48:
//! Define a vector<String> and call push_back several times on that vector.
//! Run your program and see how often Strings are copied.
// Since no "move" members implemented, anytime when size() is equal to capacity(),
// std::vector<T> performs reallocation by calling String's copy constructor.
// In a word, it depends on the state of std::vector<String>.
//!
#include "string.h"
#include <vector>
int main()
{
std::vector<String> v;
String s("sssssss");
for (unsigned i = 0; i != 3; ++i)
v.push_back(s);
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>icoverity#705451: comparison of array against NULL<commit_after><|endoftext|> |
<commit_before><commit_msg>coverity#735386 Copy-paste error<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: unoaprms.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2006-01-10 14:31:26 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#pragma hdrstop
#include "drawdoc.hxx"
#include "unoaprms.hxx"
#include "anminfo.hxx"
TYPEINIT1(SdAnimationPrmsUndoAction, SdUndoAction);
/*************************************************************************
|*
|* 2. Ctor, der den ersten (inline) nach der Version 4.0 einmal ersetzen
|* soll (mit 3. Parameter dann)
|* Hier werden die Member mit den Animations-Informationen vorbelegt,
|* um nicht immer alle inline-Methoden aufrufen zu muessen, auch im
|* Hinblick auf zukuenftige Erweiterungen (neue Member etc.)
|*
\************************************************************************/
SdAnimationPrmsUndoAction::SdAnimationPrmsUndoAction(
SdDrawDocument* pTheDoc,
SdrObject* pObj ) :
SdUndoAction ( pTheDoc ),
pObject ( pObj ),
bInfoCreated ( FALSE ) // Fuer Animationsreihenfolge existiert Info
{
SdAnimationInfo* pInfo = pTheDoc->GetAnimationInfo( pObject );
if( pInfo )
{
bNewActive = bOldActive = pInfo->bActive;
eNewEffect = eOldEffect = pInfo->eEffect;
eNewTextEffect = eOldTextEffect = pInfo->eTextEffect;
eNewSpeed = eOldSpeed = pInfo->eSpeed;
bNewDimPrevious = bOldDimPrevious= pInfo->bDimPrevious;
aNewDimColor = aOldDimColor = pInfo->aDimColor;
bNewDimHide = bOldDimHide = pInfo->bDimHide;
bNewSoundOn = bOldSoundOn = pInfo->bSoundOn;
aNewSoundFile = aOldSoundFile = pInfo->aSoundFile;
bNewPlayFull = bOldPlayFull = pInfo->bPlayFull;
pNewPathObj = pOldPathObj = pInfo->pPathObj;
eNewClickAction = eOldClickAction = pInfo->eClickAction;
aNewBookmark = aOldBookmark = pInfo->aBookmark;
// bNewInvisibleInPres = bOldInvisibleInPres= pInfo->bInvisibleInPresentation;
nNewVerb = nOldVerb = pInfo->nVerb;
nNewPresOrder = nOldPresOrder = pInfo->nPresOrder;
eNewSecondEffect = eOldSecondEffect = pInfo->eSecondEffect;
eNewSecondSpeed = eOldSecondSpeed = pInfo->eSecondSpeed;
bNewSecondSoundOn = bOldSecondSoundOn = pInfo->bSecondSoundOn;
bNewSecondPlayFull = bOldSecondPlayFull = pInfo->bSecondPlayFull;
}
}
/*************************************************************************
|*
|* Undo()
|*
\************************************************************************/
void SdAnimationPrmsUndoAction::Undo()
{
// keine neu Info erzeugt: Daten restaurieren
if (!bInfoCreated)
{
SdDrawDocument* pDoc = (SdDrawDocument*)pObject->GetModel();
if( pDoc )
{
SdAnimationInfo* pInfo = pDoc->GetAnimationInfo( pObject );
// So nicht...
//SdAnimationInfo* pInfo = (SdAnimationInfo*)pObject->GetUserData(0);
pInfo->bActive = bOldActive;
pInfo->eEffect = eOldEffect;
pInfo->eTextEffect = eOldTextEffect;
pInfo->eSpeed = eOldSpeed;
pInfo->bDimPrevious = bOldDimPrevious;
pInfo->aDimColor = aOldDimColor;
pInfo->bDimHide = bOldDimHide;
pInfo->bSoundOn = bOldSoundOn;
pInfo->aSoundFile = aOldSoundFile;
pInfo->bPlayFull = bOldPlayFull;
// pInfo->SetPath(pOldPathObj);
pInfo->eClickAction = eOldClickAction;
pInfo->aBookmark = aOldBookmark;
// pInfo->bInvisibleInPresentation = bOldInvisibleInPres;
pInfo->nVerb = nOldVerb;
pInfo->nPresOrder = nOldPresOrder;
pInfo->eSecondEffect = eOldSecondEffect;
pInfo->eSecondSpeed = eOldSecondSpeed;
pInfo->bSecondSoundOn = bOldSecondSoundOn;
pInfo->bSecondPlayFull = bOldSecondPlayFull;
}
}
// Info wurde durch Aktion erzeugt: Info loeschen
else
{
pObject->DeleteUserData(0);
}
// Damit ein ModelHasChanged() ausgeloest wird, um das Effekte-Window
// auf Stand zu bringen (Animations-Reihenfolge)
pObject->SetChanged();
pObject->BroadcastObjectChange();
}
/*************************************************************************
|*
|* Redo()
|*
\************************************************************************/
void SdAnimationPrmsUndoAction::Redo()
{
SdAnimationInfo* pInfo = NULL;
pInfo = SdDrawDocument::GetShapeUserData(*pObject,true);
pInfo->bActive = bNewActive;
pInfo->eEffect = eNewEffect;
pInfo->eTextEffect = eNewTextEffect;
pInfo->eSpeed = eNewSpeed;
pInfo->bDimPrevious = bNewDimPrevious;
pInfo->aDimColor = aNewDimColor;
pInfo->bDimHide = bNewDimHide;
pInfo->bSoundOn = bNewSoundOn;
pInfo->aSoundFile = aNewSoundFile;
pInfo->bPlayFull = bNewPlayFull;
// pInfo->SetPath(pNewPathObj);
pInfo->eClickAction = eNewClickAction;
pInfo->aBookmark = aNewBookmark;
// pInfo->bInvisibleInPresentation = bNewInvisibleInPres;
pInfo->nVerb = nNewVerb;
pInfo->nPresOrder = nNewPresOrder;
pInfo->eSecondEffect = eNewSecondEffect;
pInfo->eSecondSpeed = eNewSecondSpeed;
pInfo->bSecondSoundOn = bNewSecondSoundOn;
pInfo->bSecondPlayFull = bNewSecondPlayFull;
// Damit ein ModelHasChanged() ausgeloest wird, um das Effekte-Window
// auf Stand zu bringen (Animations-Reihenfolge)
pObject->SetChanged();
pObject->BroadcastObjectChange();
}
/*************************************************************************
|*
|* Repeat()
|*
\************************************************************************/
void SdAnimationPrmsUndoAction::Repeat()
{
}
/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/
SdAnimationPrmsUndoAction::~SdAnimationPrmsUndoAction()
{
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.7.200); FILE MERGED 2006/09/01 17:37:13 kaib 1.7.200.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: unoaprms.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2006-09-16 19:00:48 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "drawdoc.hxx"
#include "unoaprms.hxx"
#include "anminfo.hxx"
TYPEINIT1(SdAnimationPrmsUndoAction, SdUndoAction);
/*************************************************************************
|*
|* 2. Ctor, der den ersten (inline) nach der Version 4.0 einmal ersetzen
|* soll (mit 3. Parameter dann)
|* Hier werden die Member mit den Animations-Informationen vorbelegt,
|* um nicht immer alle inline-Methoden aufrufen zu muessen, auch im
|* Hinblick auf zukuenftige Erweiterungen (neue Member etc.)
|*
\************************************************************************/
SdAnimationPrmsUndoAction::SdAnimationPrmsUndoAction(
SdDrawDocument* pTheDoc,
SdrObject* pObj ) :
SdUndoAction ( pTheDoc ),
pObject ( pObj ),
bInfoCreated ( FALSE ) // Fuer Animationsreihenfolge existiert Info
{
SdAnimationInfo* pInfo = pTheDoc->GetAnimationInfo( pObject );
if( pInfo )
{
bNewActive = bOldActive = pInfo->bActive;
eNewEffect = eOldEffect = pInfo->eEffect;
eNewTextEffect = eOldTextEffect = pInfo->eTextEffect;
eNewSpeed = eOldSpeed = pInfo->eSpeed;
bNewDimPrevious = bOldDimPrevious= pInfo->bDimPrevious;
aNewDimColor = aOldDimColor = pInfo->aDimColor;
bNewDimHide = bOldDimHide = pInfo->bDimHide;
bNewSoundOn = bOldSoundOn = pInfo->bSoundOn;
aNewSoundFile = aOldSoundFile = pInfo->aSoundFile;
bNewPlayFull = bOldPlayFull = pInfo->bPlayFull;
pNewPathObj = pOldPathObj = pInfo->pPathObj;
eNewClickAction = eOldClickAction = pInfo->eClickAction;
aNewBookmark = aOldBookmark = pInfo->aBookmark;
// bNewInvisibleInPres = bOldInvisibleInPres= pInfo->bInvisibleInPresentation;
nNewVerb = nOldVerb = pInfo->nVerb;
nNewPresOrder = nOldPresOrder = pInfo->nPresOrder;
eNewSecondEffect = eOldSecondEffect = pInfo->eSecondEffect;
eNewSecondSpeed = eOldSecondSpeed = pInfo->eSecondSpeed;
bNewSecondSoundOn = bOldSecondSoundOn = pInfo->bSecondSoundOn;
bNewSecondPlayFull = bOldSecondPlayFull = pInfo->bSecondPlayFull;
}
}
/*************************************************************************
|*
|* Undo()
|*
\************************************************************************/
void SdAnimationPrmsUndoAction::Undo()
{
// keine neu Info erzeugt: Daten restaurieren
if (!bInfoCreated)
{
SdDrawDocument* pDoc = (SdDrawDocument*)pObject->GetModel();
if( pDoc )
{
SdAnimationInfo* pInfo = pDoc->GetAnimationInfo( pObject );
// So nicht...
//SdAnimationInfo* pInfo = (SdAnimationInfo*)pObject->GetUserData(0);
pInfo->bActive = bOldActive;
pInfo->eEffect = eOldEffect;
pInfo->eTextEffect = eOldTextEffect;
pInfo->eSpeed = eOldSpeed;
pInfo->bDimPrevious = bOldDimPrevious;
pInfo->aDimColor = aOldDimColor;
pInfo->bDimHide = bOldDimHide;
pInfo->bSoundOn = bOldSoundOn;
pInfo->aSoundFile = aOldSoundFile;
pInfo->bPlayFull = bOldPlayFull;
// pInfo->SetPath(pOldPathObj);
pInfo->eClickAction = eOldClickAction;
pInfo->aBookmark = aOldBookmark;
// pInfo->bInvisibleInPresentation = bOldInvisibleInPres;
pInfo->nVerb = nOldVerb;
pInfo->nPresOrder = nOldPresOrder;
pInfo->eSecondEffect = eOldSecondEffect;
pInfo->eSecondSpeed = eOldSecondSpeed;
pInfo->bSecondSoundOn = bOldSecondSoundOn;
pInfo->bSecondPlayFull = bOldSecondPlayFull;
}
}
// Info wurde durch Aktion erzeugt: Info loeschen
else
{
pObject->DeleteUserData(0);
}
// Damit ein ModelHasChanged() ausgeloest wird, um das Effekte-Window
// auf Stand zu bringen (Animations-Reihenfolge)
pObject->SetChanged();
pObject->BroadcastObjectChange();
}
/*************************************************************************
|*
|* Redo()
|*
\************************************************************************/
void SdAnimationPrmsUndoAction::Redo()
{
SdAnimationInfo* pInfo = NULL;
pInfo = SdDrawDocument::GetShapeUserData(*pObject,true);
pInfo->bActive = bNewActive;
pInfo->eEffect = eNewEffect;
pInfo->eTextEffect = eNewTextEffect;
pInfo->eSpeed = eNewSpeed;
pInfo->bDimPrevious = bNewDimPrevious;
pInfo->aDimColor = aNewDimColor;
pInfo->bDimHide = bNewDimHide;
pInfo->bSoundOn = bNewSoundOn;
pInfo->aSoundFile = aNewSoundFile;
pInfo->bPlayFull = bNewPlayFull;
// pInfo->SetPath(pNewPathObj);
pInfo->eClickAction = eNewClickAction;
pInfo->aBookmark = aNewBookmark;
// pInfo->bInvisibleInPresentation = bNewInvisibleInPres;
pInfo->nVerb = nNewVerb;
pInfo->nPresOrder = nNewPresOrder;
pInfo->eSecondEffect = eNewSecondEffect;
pInfo->eSecondSpeed = eNewSecondSpeed;
pInfo->bSecondSoundOn = bNewSecondSoundOn;
pInfo->bSecondPlayFull = bNewSecondPlayFull;
// Damit ein ModelHasChanged() ausgeloest wird, um das Effekte-Window
// auf Stand zu bringen (Animations-Reihenfolge)
pObject->SetChanged();
pObject->BroadcastObjectChange();
}
/*************************************************************************
|*
|* Repeat()
|*
\************************************************************************/
void SdAnimationPrmsUndoAction::Repeat()
{
}
/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/
SdAnimationPrmsUndoAction::~SdAnimationPrmsUndoAction()
{
}
<|endoftext|> |
<commit_before>#ifndef STAN__MATH__MATRIX__MULTIPLY_LOWER_TRI_SELF_HPP
#define STAN__MATH__MATRIX__MULTIPLY_LOWER_TRI_SELF_HPP
#include <stan/math/matrix/typedefs.hpp>
namespace stan {
namespace math {
/**
* Returns the result of multiplying the lower triangular
* portion of the input matrix by its own transpose.
* @param L Matrix to multiply.
* @return The lower triangular values in L times their own
* transpose.
* @throw std::domain_error If the input matrix is not square.
*/
inline matrix_d
multiply_lower_tri_self_transpose(const matrix_d& L) {
if (L.rows() == 0)
return matrix_d(0,0);
if (L.rows() == 1) {
matrix_d result(1,1);
result(0,0) = L(0,0) * L(0,0);
return result;
}
// FIXME: write custom following agrad/matrix because can't get L_tri into
// multiplication as no template support for tri * tri
matrix_d L_tri = L.transpose().triangularView<Eigen::Upper>();
return L.triangularView<Eigen::Lower>() * L_tri;
}
}
}
#endif
<commit_msg>Efficient implementation of multiply_lower_tri_self_transpose.hpp<commit_after>#ifndef STAN__MATH__MATRIX__MULTIPLY_LOWER_TRI_SELF_HPP
#define STAN__MATH__MATRIX__MULTIPLY_LOWER_TRI_SELF_HPP
#include <stan/math/matrix/typedefs.hpp>
namespace stan {
namespace math {
/**
* Returns the result of multiplying the lower triangular
* portion of the input matrix by its own transpose.
* @param L Matrix to multiply.
* @return The lower triangular values in L times their own
* transpose.
* @throw std::domain_error If the input matrix is not square.
*/
inline matrix_d
multiply_lower_tri_self_transpose(const matrix_d& L) {
int K = L.rows();
int J = L.cols();
int k;
matrix_d LLt(K,K);
matrix_d Lt = L.transpose();
if (K == 0)
return matrix_d(0,0);
if (K == 1) {
matrix_d result(1,1);
result(0,0) = L(0,0) * L(0,0);
return result;
}
for (int m = 0; m < K; ++m) {
k = (J < m + 1) ? J : m + 1;
LLt(m,m) = Lt.col(m).head(k).squaredNorm();
for (int n = (m + 1); n < K; ++n) {
LLt(n,m) = LLt(m,n) = Lt.col(m).head(k).dot(Lt.col(n).head(k));
}
}
return LLt;
// FIXME: write custom following agrad/matrix because can't get L_tri into
// multiplication as no template support for tri * tri
//matrix_d L_tri = L.transpose().triangularView<Eigen::Upper>();
//return L.triangularView<Eigen::Lower>() * L_tri;
}
}
}
#endif
<|endoftext|> |
<commit_before>#ifndef __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__BETA_HPP__
#define __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__BETA_HPP__
#include <stan/agrad.hpp>
#include <stan/prob/traits.hpp>
#include <stan/math/error_handling.hpp>
#include <stan/math/special_functions.hpp>
#include <stan/prob/constants.hpp>
namespace stan {
namespace prob {
/**
* The log of the beta density for the specified scalar(s) given the specified
* sample size(s). y, alpha, or beta can each either be scalar or std::vector.
* Any vector inputs must be the same length.
*
* <p> The result log probability is defined to be the sum of
* the log probabilities for each observation/alpha/beta triple.
*
* Prior sample sizes, alpha and beta, must be greater than 0.
*
* @param y (Sequence of) scalar(s).
* @param alpha (Sequence of) prior sample size(s).
* @param beta (Sequence of) prior sample size(s).
* @return The log of the product of densities.
* @tparam T_y Type of scalar outcome.
* @tparam T_scale_succ Type of prior scale for successes.
* @tparam T_scale_fail Type of prior scale for failures.
* @error_policy
* @li alpha must be positive and finite.
* @li beta must be positive and finite.
*/
template <bool Prop,
typename T_y, typename T_scale_succ, typename T_scale_fail,
class Policy>
typename return_type<T_y,T_scale_succ,T_scale_fail>::type
beta_log(const T_y& y, const T_scale_succ& alpha, const T_scale_fail& beta,
const Policy&) {
static const char* function = "stan::prob::beta_log(%1%)";
using stan::math::check_positive;
using stan::math::check_finite;
using stan::math::check_not_nan;
using stan::math::check_consistent_sizes;
using stan::math::multiply_log;
using stan::math::log1m;
using stan::math::value_of;
using stan::prob::include_summand;
// check if no variables are involved and prop-to
if (!include_summand<Prop,T_y,T_scale_succ,T_scale_fail>::value)
return 0.0;
// check if any vectors are zero length
if (!(stan::length(y)
&& stan::length(alpha)
&& stan::length(beta)))
return 0.0;
// set up return value accumulator
double logp(0.0);
// validate args (here done over var, which should be OK)
if (!check_finite(function, alpha,
"First shape parameter",
&logp, Policy()))
return logp;
if (!check_positive(function, alpha,
"First shape parameter",
&logp, Policy()))
return logp;
if (!check_finite(function, beta,
"Second shape parameter",
&logp, Policy()))
return logp;
if (!check_positive(function, beta,
"Second shape parameter",
&logp, Policy()))
return logp;
if (!check_not_nan(function, y, "Random variable", &logp, Policy()))
return logp;
if (!(check_consistent_sizes(function,
y,alpha,beta,
"Random variable","First shape parameter","Second shape parameter",
&logp, Policy())))
return logp;
// set up template expressions wrapping scalars into vector views
VectorView<const T_y> y_vec(y);
VectorView<const T_scale_succ> alpha_vec(alpha);
VectorView<const T_scale_fail> beta_vec(beta);
size_t N = max_size(y, alpha, beta);
agrad::OperandsAndPartials<T_y, T_scale_succ, T_scale_fail>
operands_and_partials(y, alpha, beta, y_vec, alpha_vec, beta_vec);
for (size_t n = 0; n < N; n++) {
// pull out values of arguments
const double y_dbl = value_of(y_vec[n]);
const double alpha_dbl = value_of(alpha_vec[n]);
const double beta_dbl = value_of(beta_vec[n]);
// reusable subexpressions values
if (y_dbl < 0 || y_dbl > 1)
return 0.0;
const double log_y = log(y_dbl);
const double log1m_y = log1m(y_dbl);
// log probability
if (include_summand<Prop,T_scale_succ,T_scale_fail>::value)
logp += lgamma(alpha_dbl + beta_dbl);
if (include_summand<Prop,T_scale_succ>::value)
logp -= lgamma(alpha_dbl);
if (include_summand<Prop,T_scale_fail>::value)
logp -= lgamma(beta_dbl);
if (include_summand<Prop,T_y,T_scale_succ>::value)
logp += (alpha_dbl-1.0) * log_y;
if (include_summand<Prop,T_y,T_scale_fail>::value)
logp += (beta_dbl-1.0) * log1m_y;
// gradients
const double digamma_alpha_beta = boost::math::digamma(alpha_dbl + beta_dbl);
const double digamma_alpha = boost::math::digamma(alpha_dbl);
const double digamma_beta = boost::math::digamma(beta_dbl);
if (!is_constant<typename is_vector<T_y>::type>::value)
operands_and_partials.d_x1[n] += (alpha_dbl-1)/y_dbl + (beta_dbl-1)/(y_dbl-1);
if (!is_constant<typename is_vector<T_scale_succ>::type>::value)
operands_and_partials.d_x2[n] += log_y + digamma_alpha_beta - digamma_alpha;
if (!is_constant<typename is_vector<T_scale_fail>::type>::value)
operands_and_partials.d_x3[n] += log1m_y + digamma_alpha_beta - digamma_beta;
}
return operands_and_partials.to_var(logp);
}
template <bool Prop,
typename T_y, typename T_scale_succ, typename T_scale_fail>
inline
typename return_type<T_y,T_scale_succ,T_scale_fail>::type
beta_log(const T_y& y, const T_scale_succ& alpha, const T_scale_fail& beta) {
return beta_log<Prop>(y,alpha,beta,stan::math::default_policy());
}
template <typename T_y, typename T_scale_succ, typename T_scale_fail,
class Policy>
typename return_type<T_y,T_scale_succ,T_scale_fail>::type
beta_log(const T_y& y, const T_scale_succ& alpha, const T_scale_fail& beta,
const Policy&) {
return beta_log<false>(y,alpha,beta,Policy());
}
template <typename T_y, typename T_scale_succ, typename T_scale_fail>
inline
typename return_type<T_y,T_scale_succ,T_scale_fail>::type
beta_log(const T_y& y, const T_scale_succ& alpha, const T_scale_fail& beta) {
return beta_log<false>(y,alpha,beta,stan::math::default_policy());
}
/**
* Calculates the beta cumulative distribution function for the given
* variate and scale variables.
*
* @param y A scalar variate.
* @param alpha Prior sample size.
* @param beta Prior sample size.
* @return The beta cdf evaluated at the specified arguments.
* @tparam T_y Type of y.
* @tparam T_scale_succ Type of alpha.
* @tparam T_scale_fail Type of beta.
* @tparam Policy Error-handling policy.
*/
template <typename T_y, typename T_scale_succ, typename T_scale_fail,
class Policy>
typename return_type<T_y,T_scale_succ,T_scale_fail>::type
beta_cdf(const T_y& y, const T_scale_succ& alpha, const T_scale_fail& beta,
const Policy&) {
static const char* function = "stan::prob::beta_cdf(%1%)";
using stan::math::check_positive;
using stan::math::check_finite;
using stan::math::check_not_nan;
using boost::math::tools::promote_args;
typename promote_args<T_y,T_scale_succ,T_scale_fail>::type lp;
if (!check_finite(function, alpha,
"First shape parameter",
&lp, Policy()))
return lp;
if (!check_positive(function, alpha,
"First shape parameter",
&lp, Policy()))
return lp;
if (!check_finite(function, beta,
"Second shape parameter",
&lp, Policy()))
return lp;
if (!check_positive(function, beta,
"Second shape parameter",
&lp, Policy()))
return lp;
if (!check_not_nan(function, y, "Random variable", &lp, Policy()))
return lp;
if (y < 0.0)
return 0;
if (y > 1.0)
return 1.0;
return stan::math::ibeta(alpha, beta, y);
}
template <typename T_y, typename T_scale_succ, typename T_scale_fail>
typename return_type<T_y,T_scale_succ,T_scale_fail>::type
beta_cdf(const T_y& y, const T_scale_succ& alpha, const T_scale_fail& beta) {
return beta_cdf(y,alpha,beta,stan::math::default_policy());
}
}
}
#endif
<commit_msg>reordering includes<commit_after>#ifndef __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__BETA_HPP__
#define __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__BETA_HPP__
#include <stan/agrad.hpp>
#include <stan/math/error_handling.hpp>
#include <stan/math/special_functions.hpp>
#include <stan/meta/traits.hpp>
#include <stan/prob/constants.hpp>
#include <stan/prob/traits.hpp>
namespace stan {
namespace prob {
/**
* The log of the beta density for the specified scalar(s) given the specified
* sample size(s). y, alpha, or beta can each either be scalar or std::vector.
* Any vector inputs must be the same length.
*
* <p> The result log probability is defined to be the sum of
* the log probabilities for each observation/alpha/beta triple.
*
* Prior sample sizes, alpha and beta, must be greater than 0.
*
* @param y (Sequence of) scalar(s).
* @param alpha (Sequence of) prior sample size(s).
* @param beta (Sequence of) prior sample size(s).
* @return The log of the product of densities.
* @tparam T_y Type of scalar outcome.
* @tparam T_scale_succ Type of prior scale for successes.
* @tparam T_scale_fail Type of prior scale for failures.
* @error_policy
* @li alpha must be positive and finite.
* @li beta must be positive and finite.
*/
template <bool Prop,
typename T_y, typename T_scale_succ, typename T_scale_fail,
class Policy>
typename return_type<T_y,T_scale_succ,T_scale_fail>::type
beta_log(const T_y& y, const T_scale_succ& alpha, const T_scale_fail& beta,
const Policy&) {
static const char* function = "stan::prob::beta_log(%1%)";
using stan::math::check_positive;
using stan::math::check_finite;
using stan::math::check_not_nan;
using stan::math::check_consistent_sizes;
using stan::math::multiply_log;
using stan::math::log1m;
using stan::math::value_of;
using stan::prob::include_summand;
// check if no variables are involved and prop-to
if (!include_summand<Prop,T_y,T_scale_succ,T_scale_fail>::value)
return 0.0;
// check if any vectors are zero length
if (!(stan::length(y)
&& stan::length(alpha)
&& stan::length(beta)))
return 0.0;
// set up return value accumulator
double logp(0.0);
// validate args (here done over var, which should be OK)
if (!check_finite(function, alpha,
"First shape parameter",
&logp, Policy()))
return logp;
if (!check_positive(function, alpha,
"First shape parameter",
&logp, Policy()))
return logp;
if (!check_finite(function, beta,
"Second shape parameter",
&logp, Policy()))
return logp;
if (!check_positive(function, beta,
"Second shape parameter",
&logp, Policy()))
return logp;
if (!check_not_nan(function, y, "Random variable", &logp, Policy()))
return logp;
if (!(check_consistent_sizes(function,
y,alpha,beta,
"Random variable","First shape parameter","Second shape parameter",
&logp, Policy())))
return logp;
// set up template expressions wrapping scalars into vector views
VectorView<const T_y> y_vec(y);
VectorView<const T_scale_succ> alpha_vec(alpha);
VectorView<const T_scale_fail> beta_vec(beta);
size_t N = max_size(y, alpha, beta);
agrad::OperandsAndPartials<T_y, T_scale_succ, T_scale_fail>
operands_and_partials(y, alpha, beta, y_vec, alpha_vec, beta_vec);
for (size_t n = 0; n < N; n++) {
// pull out values of arguments
const double y_dbl = value_of(y_vec[n]);
const double alpha_dbl = value_of(alpha_vec[n]);
const double beta_dbl = value_of(beta_vec[n]);
// reusable subexpressions values
if (y_dbl < 0 || y_dbl > 1)
return 0.0;
const double log_y = log(y_dbl);
const double log1m_y = log1m(y_dbl);
// log probability
if (include_summand<Prop,T_scale_succ,T_scale_fail>::value)
logp += lgamma(alpha_dbl + beta_dbl);
if (include_summand<Prop,T_scale_succ>::value)
logp -= lgamma(alpha_dbl);
if (include_summand<Prop,T_scale_fail>::value)
logp -= lgamma(beta_dbl);
if (include_summand<Prop,T_y,T_scale_succ>::value)
logp += (alpha_dbl-1.0) * log_y;
if (include_summand<Prop,T_y,T_scale_fail>::value)
logp += (beta_dbl-1.0) * log1m_y;
// gradients
const double digamma_alpha_beta = boost::math::digamma(alpha_dbl + beta_dbl);
const double digamma_alpha = boost::math::digamma(alpha_dbl);
const double digamma_beta = boost::math::digamma(beta_dbl);
if (!is_constant<typename is_vector<T_y>::type>::value)
operands_and_partials.d_x1[n] += (alpha_dbl-1)/y_dbl + (beta_dbl-1)/(y_dbl-1);
if (!is_constant<typename is_vector<T_scale_succ>::type>::value)
operands_and_partials.d_x2[n] += log_y + digamma_alpha_beta - digamma_alpha;
if (!is_constant<typename is_vector<T_scale_fail>::type>::value)
operands_and_partials.d_x3[n] += log1m_y + digamma_alpha_beta - digamma_beta;
}
return operands_and_partials.to_var(logp);
}
template <bool Prop,
typename T_y, typename T_scale_succ, typename T_scale_fail>
inline
typename return_type<T_y,T_scale_succ,T_scale_fail>::type
beta_log(const T_y& y, const T_scale_succ& alpha, const T_scale_fail& beta) {
return beta_log<Prop>(y,alpha,beta,stan::math::default_policy());
}
template <typename T_y, typename T_scale_succ, typename T_scale_fail,
class Policy>
typename return_type<T_y,T_scale_succ,T_scale_fail>::type
beta_log(const T_y& y, const T_scale_succ& alpha, const T_scale_fail& beta,
const Policy&) {
return beta_log<false>(y,alpha,beta,Policy());
}
template <typename T_y, typename T_scale_succ, typename T_scale_fail>
inline
typename return_type<T_y,T_scale_succ,T_scale_fail>::type
beta_log(const T_y& y, const T_scale_succ& alpha, const T_scale_fail& beta) {
return beta_log<false>(y,alpha,beta,stan::math::default_policy());
}
/**
* Calculates the beta cumulative distribution function for the given
* variate and scale variables.
*
* @param y A scalar variate.
* @param alpha Prior sample size.
* @param beta Prior sample size.
* @return The beta cdf evaluated at the specified arguments.
* @tparam T_y Type of y.
* @tparam T_scale_succ Type of alpha.
* @tparam T_scale_fail Type of beta.
* @tparam Policy Error-handling policy.
*/
template <typename T_y, typename T_scale_succ, typename T_scale_fail,
class Policy>
typename return_type<T_y,T_scale_succ,T_scale_fail>::type
beta_cdf(const T_y& y, const T_scale_succ& alpha, const T_scale_fail& beta,
const Policy&) {
static const char* function = "stan::prob::beta_cdf(%1%)";
using stan::math::check_positive;
using stan::math::check_finite;
using stan::math::check_not_nan;
using boost::math::tools::promote_args;
typename promote_args<T_y,T_scale_succ,T_scale_fail>::type lp;
if (!check_finite(function, alpha,
"First shape parameter",
&lp, Policy()))
return lp;
if (!check_positive(function, alpha,
"First shape parameter",
&lp, Policy()))
return lp;
if (!check_finite(function, beta,
"Second shape parameter",
&lp, Policy()))
return lp;
if (!check_positive(function, beta,
"Second shape parameter",
&lp, Policy()))
return lp;
if (!check_not_nan(function, y, "Random variable", &lp, Policy()))
return lp;
if (y < 0.0)
return 0;
if (y > 1.0)
return 1.0;
return stan::math::ibeta(alpha, beta, y);
}
template <typename T_y, typename T_scale_succ, typename T_scale_fail>
typename return_type<T_y,T_scale_succ,T_scale_fail>::type
beta_cdf(const T_y& y, const T_scale_succ& alpha, const T_scale_fail& beta) {
return beta_cdf(y,alpha,beta,stan::math::default_policy());
}
}
}
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: grviewsh.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: kz $ $Date: 2006-12-12 19:18:03 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "GraphicViewShell.hxx"
#include "LayerTabBar.hxx"
#include "FrameView.hxx"
#include <sfx2/objsh.hxx>
#include <sfx2/viewfrm.hxx>
#include <vcl/scrbar.hxx>
#ifndef _SV_SALBTYPE_HXX
#include <vcl/salbtype.hxx> // FRound
#endif
namespace sd {
static const int TABCONTROL_INITIAL_SIZE = 350;
/*************************************************************************
|*
|* Standard-Konstruktor
|*
\************************************************************************/
GraphicViewShell::GraphicViewShell (
SfxViewFrame* pFrame,
ViewShellBase& rViewShellBase,
::Window* pParentWindow,
FrameView* pFrameView)
: DrawViewShell (
pFrame,
rViewShellBase,
pParentWindow,
PK_STANDARD,
pFrameView)
{
ConstructGraphicViewShell();
}
/*************************************************************************
|*
|* Copy-Konstruktor
|*
\************************************************************************/
GraphicViewShell::GraphicViewShell (
SfxViewFrame* pFrame,
::Window* pParentWindow,
const DrawViewShell& rShell)
: DrawViewShell (pFrame, pParentWindow, rShell)
{
ConstructGraphicViewShell();
}
GraphicViewShell::~GraphicViewShell (void)
{
}
void GraphicViewShell::ConstructGraphicViewShell(void)
{
meShellType = ST_DRAW;
mpLayerTabBar.reset (new LayerTabBar(this,GetParentWindow()));
mpLayerTabBar->SetSplitHdl(LINK(this,GraphicViewShell,TabBarSplitHandler));
// pb: #i67363# no layer tabbar on preview mode
if ( !GetObjectShell()->IsPreview() )
mpLayerTabBar->Show();
}
void GraphicViewShell::ChangeEditMode (
EditMode eMode,
bool )
{
// There is no page tab that could be shown instead of the layer tab.
// Therefore we have it allways visible regardless of what the caller
// said. (We have to change the callers behaviour, of course.)
DrawViewShell::ChangeEditMode (eMode, true);
}
void GraphicViewShell::ArrangeGUIElements (void)
{
if (mpLayerTabBar.get()!=NULL && mpLayerTabBar->IsVisible())
{
Size aSize = mpLayerTabBar->GetSizePixel();
const Size aFrameSize (
GetViewFrame()->GetWindow().GetOutputSizePixel());
if (aSize.Width() == 0)
{
if (mpFrameView->GetTabCtrlPercent() == 0.0)
aSize.Width() = TABCONTROL_INITIAL_SIZE;
else
aSize.Width() = FRound(aFrameSize.Width()
* mpFrameView->GetTabCtrlPercent());
}
aSize.Height() = GetParentWindow()->GetSettings().GetStyleSettings()
.GetScrollBarSize();
Point aPos (0, maViewSize.Height() - aSize.Height());
mpLayerTabBar->SetPosSizePixel (aPos, aSize);
if (aFrameSize.Width() > 0)
mpFrameView->SetTabCtrlPercent (
(double) maTabControl.GetSizePixel().Width()
/ aFrameSize.Width());
else
mpFrameView->SetTabCtrlPercent( 0.0 );
}
DrawViewShell::ArrangeGUIElements();
}
IMPL_LINK(GraphicViewShell, TabBarSplitHandler, TabBar*, pTabBar)
{
const long int nMax = maViewSize.Width()
- maScrBarWH.Width()
- pTabBar->GetPosPixel().X();
Size aTabSize = pTabBar->GetSizePixel();
aTabSize.Width() = Min(pTabBar->GetSplitSize(), (long)(nMax-1));
pTabBar->SetSizePixel (aTabSize);
Point aPos = pTabBar->GetPosPixel();
aPos.X() += aTabSize.Width();
Size aScrSize (nMax - aTabSize.Width(), maScrBarWH.Height());
mpHorizontalScrollBar->SetPosSizePixel(aPos, aScrSize);
return 0;
}
} // end of namespace sd
<commit_msg>INTEGRATION: CWS changefileheader (1.9.298); FILE MERGED 2008/04/01 15:36:35 thb 1.9.298.2: #i85898# Stripping all external header guards 2008/03/31 13:59:13 rt 1.9.298.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: grviewsh.cxx,v $
* $Revision: 1.10 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "GraphicViewShell.hxx"
#include "LayerTabBar.hxx"
#include "FrameView.hxx"
#include <sfx2/objsh.hxx>
#include <sfx2/viewfrm.hxx>
#include <vcl/scrbar.hxx>
#include <vcl/salbtype.hxx> // FRound
namespace sd {
static const int TABCONTROL_INITIAL_SIZE = 350;
/*************************************************************************
|*
|* Standard-Konstruktor
|*
\************************************************************************/
GraphicViewShell::GraphicViewShell (
SfxViewFrame* pFrame,
ViewShellBase& rViewShellBase,
::Window* pParentWindow,
FrameView* pFrameView)
: DrawViewShell (
pFrame,
rViewShellBase,
pParentWindow,
PK_STANDARD,
pFrameView)
{
ConstructGraphicViewShell();
}
/*************************************************************************
|*
|* Copy-Konstruktor
|*
\************************************************************************/
GraphicViewShell::GraphicViewShell (
SfxViewFrame* pFrame,
::Window* pParentWindow,
const DrawViewShell& rShell)
: DrawViewShell (pFrame, pParentWindow, rShell)
{
ConstructGraphicViewShell();
}
GraphicViewShell::~GraphicViewShell (void)
{
}
void GraphicViewShell::ConstructGraphicViewShell(void)
{
meShellType = ST_DRAW;
mpLayerTabBar.reset (new LayerTabBar(this,GetParentWindow()));
mpLayerTabBar->SetSplitHdl(LINK(this,GraphicViewShell,TabBarSplitHandler));
// pb: #i67363# no layer tabbar on preview mode
if ( !GetObjectShell()->IsPreview() )
mpLayerTabBar->Show();
}
void GraphicViewShell::ChangeEditMode (
EditMode eMode,
bool )
{
// There is no page tab that could be shown instead of the layer tab.
// Therefore we have it allways visible regardless of what the caller
// said. (We have to change the callers behaviour, of course.)
DrawViewShell::ChangeEditMode (eMode, true);
}
void GraphicViewShell::ArrangeGUIElements (void)
{
if (mpLayerTabBar.get()!=NULL && mpLayerTabBar->IsVisible())
{
Size aSize = mpLayerTabBar->GetSizePixel();
const Size aFrameSize (
GetViewFrame()->GetWindow().GetOutputSizePixel());
if (aSize.Width() == 0)
{
if (mpFrameView->GetTabCtrlPercent() == 0.0)
aSize.Width() = TABCONTROL_INITIAL_SIZE;
else
aSize.Width() = FRound(aFrameSize.Width()
* mpFrameView->GetTabCtrlPercent());
}
aSize.Height() = GetParentWindow()->GetSettings().GetStyleSettings()
.GetScrollBarSize();
Point aPos (0, maViewSize.Height() - aSize.Height());
mpLayerTabBar->SetPosSizePixel (aPos, aSize);
if (aFrameSize.Width() > 0)
mpFrameView->SetTabCtrlPercent (
(double) maTabControl.GetSizePixel().Width()
/ aFrameSize.Width());
else
mpFrameView->SetTabCtrlPercent( 0.0 );
}
DrawViewShell::ArrangeGUIElements();
}
IMPL_LINK(GraphicViewShell, TabBarSplitHandler, TabBar*, pTabBar)
{
const long int nMax = maViewSize.Width()
- maScrBarWH.Width()
- pTabBar->GetPosPixel().X();
Size aTabSize = pTabBar->GetSizePixel();
aTabSize.Width() = Min(pTabBar->GetSplitSize(), (long)(nMax-1));
pTabBar->SetSizePixel (aTabSize);
Point aPos = pTabBar->GetPosPixel();
aPos.X() += aTabSize.Width();
Size aScrSize (nMax - aTabSize.Width(), maScrBarWH.Height());
mpHorizontalScrollBar->SetPosSizePixel(aPos, aScrSize);
return 0;
}
} // end of namespace sd
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tabcontr.cxx,v $
*
* $Revision: 1.19 $
*
* last change: $Author: kz $ $Date: 2006-12-12 19:22:49 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "TabControl.hxx"
#include <sfx2/viewfrm.hxx>
#ifndef _SVDLAYER_HXX
#include <svx/svdlayer.hxx>
#endif
#ifndef _SVDPAGV_HXX //autogen
#include <svx/svdpagv.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#include "sdattr.hxx"
#include "app.hxx"
#include "app.hrc"
#include "glob.hrc"
#include "res_bmp.hrc"
#ifndef SD_DRAW_VIEW_SHELL_HXX
#include "DrawViewShell.hxx"
#endif
#ifndef SD_GRAPHIC_VIEW_SHELL_HXX
#include "GraphicViewShell.hxx"
#endif
#include "helpids.h"
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#include "sdpage.hxx"
#include "drawdoc.hxx"
#ifndef SD_WINDOW_HXX
#include "Window.hxx"
#endif
#include "unmodpg.hxx"
#include "DrawDocShell.hxx"
#include "sdresid.hxx"
namespace sd {
#define SWITCH_TIMEOUT 20
// -----------------------------------------
// - SdTabControl::SdPageObjsTransferable -
// -----------------------------------------
TabControl::TabControlTransferable::~TabControlTransferable()
{
}
// -----------------------------------------------------------------------------
void TabControl::TabControlTransferable::AddSupportedFormats()
{
AddFormat( SOT_FORMATSTR_ID_STARDRAW_TABBAR );
}
// -----------------------------------------------------------------------------
sal_Bool TabControl::TabControlTransferable::GetData( const ::com::sun::star::datatransfer::DataFlavor& )
{
return sal_False;
}
// -----------------------------------------------------------------------------
void TabControl::TabControlTransferable::DragFinished( sal_Int8 nDropAction )
{
mrParent.DragFinished( nDropAction );
}
/*************************************************************************
|*
|* Standard-Konstruktor
|*
\************************************************************************/
TabControl::TabControl(DrawViewShell* pViewSh, Window* pParent) :
TabBar( pParent, WinBits( WB_BORDER | WB_3DLOOK | WB_SCROLL | WB_SIZEABLE | WB_DRAG) ),
DragSourceHelper( this ),
DropTargetHelper( this ),
pDrViewSh(pViewSh),
bInternalMove(FALSE)
{
EnableEditMode();
SetSizePixel(Size(0, 0));
SetMaxPageWidth( 150 );
SetHelpId( HID_SD_TABBAR_PAGES );
}
/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/
TabControl::~TabControl()
{
}
/*************************************************************************
|*
\************************************************************************/
void TabControl::Select()
{
SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher();
pDispatcher->Execute(SID_SWITCHPAGE, SFX_CALLMODE_ASYNCHRON |
SFX_CALLMODE_RECORD);
}
/*************************************************************************
|*
\************************************************************************/
void TabControl::MouseButtonDown(const MouseEvent& rMEvt)
{
if (rMEvt.IsLeft()
&& !rMEvt.IsMod1()
&& !rMEvt.IsMod2()
&& !rMEvt.IsShift())
{
Point aPos = PixelToLogic( rMEvt.GetPosPixel() );
USHORT aPageId = GetPageId(aPos);
if (aPageId == 0)
{
SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher();
pDispatcher->Execute(SID_INSERTPAGE_QUICK,
SFX_CALLMODE_SYNCHRON | SFX_CALLMODE_RECORD);
}
}
// A single left click with pressed control key on a tab page first
// switches to that page before the usual handling (copying with drag
// and drop) takes place.
else if (rMEvt.IsLeft() && rMEvt.IsMod1() && !rMEvt.IsMod2() && !rMEvt.IsShift())
{
pDrViewSh->SwitchPage (GetPageId (rMEvt.GetPosPixel()) - 1);
}
// When only the right button is pressed then first process a
// synthesized left button click to make the page the current one
// whose tab has been clicked. When then the actual right button
// click is processed the resulting context menu relates to the
// now current page.
if (rMEvt.IsRight() && ! rMEvt.IsLeft())
{
MouseEvent aSyntheticEvent (
rMEvt.GetPosPixel(),
rMEvt.GetClicks(),
rMEvt.GetMode(),
MOUSE_LEFT,
rMEvt.GetModifier());
TabBar::MouseButtonDown(aSyntheticEvent);
}
TabBar::MouseButtonDown(rMEvt);
}
/*************************************************************************
|*
\************************************************************************/
void TabControl::DoubleClick()
{
if (GetCurPageId() != 0)
{
SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher();
pDispatcher->Execute( SID_MODIFYPAGE,
SFX_CALLMODE_SYNCHRON | SFX_CALLMODE_RECORD );
}
}
/*************************************************************************
|*
|* StartDrag-Request
|*
\************************************************************************/
void TabControl::StartDrag( sal_Int8, const Point& )
{
bInternalMove = TRUE;
// object is delete by reference mechanismn
( new TabControl::TabControlTransferable( *this ) )->StartDrag( this, DND_ACTION_COPYMOVE );
}
/*************************************************************************
|*
|* DragFinished
|*
\************************************************************************/
void TabControl::DragFinished( sal_Int8 )
{
bInternalMove = FALSE;
}
/*************************************************************************
|*
|* AcceptDrop-Event
|*
\************************************************************************/
sal_Int8 TabControl::AcceptDrop( const AcceptDropEvent& rEvt )
{
sal_Int8 nRet = DND_ACTION_NONE;
if( rEvt.mbLeaving )
EndSwitchPage();
if( !pDrViewSh->GetDocSh()->IsReadOnly() )
{
SdDrawDocument* pDoc = pDrViewSh->GetDoc();
Point aPos( rEvt.maPosPixel );
if( bInternalMove )
{
if( rEvt.mbLeaving || ( pDrViewSh->GetEditMode() == EM_MASTERPAGE ) )
HideDropPos();
else
{
ShowDropPos( aPos );
nRet = rEvt.mnAction;
}
}
else
{
HideDropPos();
sal_Int32 nPageId = GetPageId( aPos ) - 1;
if( ( nPageId >= 0 ) && pDoc->GetPage( (USHORT)nPageId ) )
{
nRet = pDrViewSh->AcceptDrop( rEvt, *this, NULL, (USHORT)nPageId, SDRLAYER_NOTFOUND );
SwitchPage( aPos );
}
}
}
return nRet;
}
/*************************************************************************
|*
|* ExecuteDrop-Event
|*
\************************************************************************/
sal_Int8 TabControl::ExecuteDrop( const ExecuteDropEvent& rEvt )
{
SdDrawDocument* pDoc = pDrViewSh->GetDoc();
Point aPos( rEvt.maPosPixel );
sal_Int8 nRet = DND_ACTION_NONE;
if( bInternalMove )
{
USHORT nPageId = ShowDropPos( aPos ) - 1;
switch (rEvt.mnAction)
{
case DND_ACTION_MOVE:
if( pDrViewSh->IsSwitchPageAllowed() && pDoc->MovePages( nPageId ) )
{
SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher();
pDispatcher->Execute(SID_SWITCHPAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
}
break;
case DND_ACTION_COPY:
{
// Copying the selected page to the place that rEvt points
// takes place in three steps:
// 1. Create a copy of the selected page. This copy will
// lie directly behind the selected page.
// 2. Move the copy to the desired place.
// 3. Select the copy.
if (pDrViewSh->IsSwitchPageAllowed())
{
// 1. Create a copy.
USHORT nPageNumOfCopy = pDoc->DuplicatePage (GetCurPageId() - 1);
// 2. Move page. For this first switch to the copy:
// MovePages operates on the currently selected page(s).
pDrViewSh->SwitchPage (nPageNumOfCopy);
// Adapt target page id when necessary, i.e. page copy
// has been inserted in front of the target page.
USHORT nPageNum = nPageId;
if ((nPageNumOfCopy <= nPageNum) && (nPageNum != (USHORT)-1))
nPageNum += 1;
if (pDoc->MovePages(nPageNum))
{
// 3. Switch to the copy that has been moved to its
// final destination. Use an asynchron slot call to
// be executed after the still pending ones.
if (nPageNumOfCopy >= nPageNum || (nPageNum == (USHORT)-1))
nPageNum += 1;
SetCurPageId (GetPageId(nPageNum));
SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher();
pDispatcher->Execute(SID_SWITCHPAGE,
SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
}
}
break;
}
}
nRet = rEvt.mnAction;
}
else
{
sal_Int32 nPageId = GetPageId( aPos ) - 1;
if( ( nPageId >= 0 ) && pDoc->GetPage( (USHORT)nPageId ) )
{
nRet = pDrViewSh->ExecuteDrop( rEvt, *this, NULL, (USHORT)nPageId, SDRLAYER_NOTFOUND );
}
}
HideDropPos();
EndSwitchPage();
return nRet;
}
/*************************************************************************
|*
\************************************************************************/
void TabControl::Command(const CommandEvent& rCEvt)
{
USHORT nCmd = rCEvt.GetCommand();
if ( nCmd == COMMAND_CONTEXTMENU )
{
BOOL bGraphicShell = pDrViewSh->ISA(GraphicViewShell);
USHORT nResId = bGraphicShell ? RID_GRAPHIC_PAGETAB_POPUP :
RID_DRAW_PAGETAB_POPUP;
SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher();
pDispatcher->ExecutePopup( SdResId( nResId ) );
}
}
/*************************************************************************
|*
\************************************************************************/
long TabControl::StartRenaming()
{
BOOL bOK = FALSE;
if (pDrViewSh->GetPageKind() == PK_STANDARD)
{
bOK = TRUE;
::sd::View* pView = pDrViewSh->GetView();
if ( pView->IsTextEdit() )
pView->SdrEndTextEdit();
}
return( bOK );
}
/*************************************************************************
|*
\************************************************************************/
long TabControl::AllowRenaming()
{
BOOL bOK = TRUE;
String aNewName( GetEditText() );
String aCompareName( GetPageText( GetEditPageId() ) );
if( aCompareName != aNewName )
{
// Seite umbenennen
if( pDrViewSh->GetDocSh()->CheckPageName( this, aNewName ) )
{
SetEditText( aNewName );
EndRenaming();
}
else
{
bOK = FALSE;
}
}
return( bOK );
}
/*************************************************************************
|*
\************************************************************************/
void TabControl::EndRenaming()
{
if( !IsEditModeCanceled() )
pDrViewSh->RenameSlide( GetEditPageId(), GetEditText() );
}
/*************************************************************************
|*
\************************************************************************/
void TabControl::ActivatePage()
{
if ( /*IsInSwitching && */ pDrViewSh->IsSwitchPageAllowed() )
{
SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher();
pDispatcher->Execute(SID_SWITCHPAGE,
SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
}
}
/*************************************************************************
|*
\************************************************************************/
long TabControl::DeactivatePage()
{
return pDrViewSh->IsSwitchPageAllowed();
}
void TabControl::SendActivatePageEvent (void)
{
CallEventListeners (VCLEVENT_TABBAR_PAGEACTIVATED,
reinterpret_cast<void*>(GetCurPageId()));
}
void TabControl::SendDeactivatePageEvent (void)
{
CallEventListeners (VCLEVENT_TABBAR_PAGEDEACTIVATED,
reinterpret_cast<void*>(GetCurPageId()));
}
} // end of namespace sd
<commit_msg>INTEGRATION: CWS changefileheader (1.19.298); FILE MERGED 2008/04/01 15:36:41 thb 1.19.298.3: #i85898# Stripping all external header guards 2008/04/01 12:39:43 thb 1.19.298.2: #i85898# Stripping all external header guards 2008/03/31 13:59:14 rt 1.19.298.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tabcontr.cxx,v $
* $Revision: 1.20 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "TabControl.hxx"
#include <sfx2/viewfrm.hxx>
#include <svx/svdlayer.hxx>
#include <svx/svdpagv.hxx>
#include <sfx2/dispatch.hxx>
#include "sdattr.hxx"
#include "app.hxx"
#include "app.hrc"
#include "glob.hrc"
#include "res_bmp.hrc"
#include "DrawViewShell.hxx"
#include "GraphicViewShell.hxx"
#include "helpids.h"
#include "View.hxx"
#include "sdpage.hxx"
#include "drawdoc.hxx"
#include "Window.hxx"
#include "unmodpg.hxx"
#include "DrawDocShell.hxx"
#include "sdresid.hxx"
namespace sd {
#define SWITCH_TIMEOUT 20
// -----------------------------------------
// - SdTabControl::SdPageObjsTransferable -
// -----------------------------------------
TabControl::TabControlTransferable::~TabControlTransferable()
{
}
// -----------------------------------------------------------------------------
void TabControl::TabControlTransferable::AddSupportedFormats()
{
AddFormat( SOT_FORMATSTR_ID_STARDRAW_TABBAR );
}
// -----------------------------------------------------------------------------
sal_Bool TabControl::TabControlTransferable::GetData( const ::com::sun::star::datatransfer::DataFlavor& )
{
return sal_False;
}
// -----------------------------------------------------------------------------
void TabControl::TabControlTransferable::DragFinished( sal_Int8 nDropAction )
{
mrParent.DragFinished( nDropAction );
}
/*************************************************************************
|*
|* Standard-Konstruktor
|*
\************************************************************************/
TabControl::TabControl(DrawViewShell* pViewSh, Window* pParent) :
TabBar( pParent, WinBits( WB_BORDER | WB_3DLOOK | WB_SCROLL | WB_SIZEABLE | WB_DRAG) ),
DragSourceHelper( this ),
DropTargetHelper( this ),
pDrViewSh(pViewSh),
bInternalMove(FALSE)
{
EnableEditMode();
SetSizePixel(Size(0, 0));
SetMaxPageWidth( 150 );
SetHelpId( HID_SD_TABBAR_PAGES );
}
/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/
TabControl::~TabControl()
{
}
/*************************************************************************
|*
\************************************************************************/
void TabControl::Select()
{
SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher();
pDispatcher->Execute(SID_SWITCHPAGE, SFX_CALLMODE_ASYNCHRON |
SFX_CALLMODE_RECORD);
}
/*************************************************************************
|*
\************************************************************************/
void TabControl::MouseButtonDown(const MouseEvent& rMEvt)
{
if (rMEvt.IsLeft()
&& !rMEvt.IsMod1()
&& !rMEvt.IsMod2()
&& !rMEvt.IsShift())
{
Point aPos = PixelToLogic( rMEvt.GetPosPixel() );
USHORT aPageId = GetPageId(aPos);
if (aPageId == 0)
{
SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher();
pDispatcher->Execute(SID_INSERTPAGE_QUICK,
SFX_CALLMODE_SYNCHRON | SFX_CALLMODE_RECORD);
}
}
// A single left click with pressed control key on a tab page first
// switches to that page before the usual handling (copying with drag
// and drop) takes place.
else if (rMEvt.IsLeft() && rMEvt.IsMod1() && !rMEvt.IsMod2() && !rMEvt.IsShift())
{
pDrViewSh->SwitchPage (GetPageId (rMEvt.GetPosPixel()) - 1);
}
// When only the right button is pressed then first process a
// synthesized left button click to make the page the current one
// whose tab has been clicked. When then the actual right button
// click is processed the resulting context menu relates to the
// now current page.
if (rMEvt.IsRight() && ! rMEvt.IsLeft())
{
MouseEvent aSyntheticEvent (
rMEvt.GetPosPixel(),
rMEvt.GetClicks(),
rMEvt.GetMode(),
MOUSE_LEFT,
rMEvt.GetModifier());
TabBar::MouseButtonDown(aSyntheticEvent);
}
TabBar::MouseButtonDown(rMEvt);
}
/*************************************************************************
|*
\************************************************************************/
void TabControl::DoubleClick()
{
if (GetCurPageId() != 0)
{
SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher();
pDispatcher->Execute( SID_MODIFYPAGE,
SFX_CALLMODE_SYNCHRON | SFX_CALLMODE_RECORD );
}
}
/*************************************************************************
|*
|* StartDrag-Request
|*
\************************************************************************/
void TabControl::StartDrag( sal_Int8, const Point& )
{
bInternalMove = TRUE;
// object is delete by reference mechanismn
( new TabControl::TabControlTransferable( *this ) )->StartDrag( this, DND_ACTION_COPYMOVE );
}
/*************************************************************************
|*
|* DragFinished
|*
\************************************************************************/
void TabControl::DragFinished( sal_Int8 )
{
bInternalMove = FALSE;
}
/*************************************************************************
|*
|* AcceptDrop-Event
|*
\************************************************************************/
sal_Int8 TabControl::AcceptDrop( const AcceptDropEvent& rEvt )
{
sal_Int8 nRet = DND_ACTION_NONE;
if( rEvt.mbLeaving )
EndSwitchPage();
if( !pDrViewSh->GetDocSh()->IsReadOnly() )
{
SdDrawDocument* pDoc = pDrViewSh->GetDoc();
Point aPos( rEvt.maPosPixel );
if( bInternalMove )
{
if( rEvt.mbLeaving || ( pDrViewSh->GetEditMode() == EM_MASTERPAGE ) )
HideDropPos();
else
{
ShowDropPos( aPos );
nRet = rEvt.mnAction;
}
}
else
{
HideDropPos();
sal_Int32 nPageId = GetPageId( aPos ) - 1;
if( ( nPageId >= 0 ) && pDoc->GetPage( (USHORT)nPageId ) )
{
nRet = pDrViewSh->AcceptDrop( rEvt, *this, NULL, (USHORT)nPageId, SDRLAYER_NOTFOUND );
SwitchPage( aPos );
}
}
}
return nRet;
}
/*************************************************************************
|*
|* ExecuteDrop-Event
|*
\************************************************************************/
sal_Int8 TabControl::ExecuteDrop( const ExecuteDropEvent& rEvt )
{
SdDrawDocument* pDoc = pDrViewSh->GetDoc();
Point aPos( rEvt.maPosPixel );
sal_Int8 nRet = DND_ACTION_NONE;
if( bInternalMove )
{
USHORT nPageId = ShowDropPos( aPos ) - 1;
switch (rEvt.mnAction)
{
case DND_ACTION_MOVE:
if( pDrViewSh->IsSwitchPageAllowed() && pDoc->MovePages( nPageId ) )
{
SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher();
pDispatcher->Execute(SID_SWITCHPAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
}
break;
case DND_ACTION_COPY:
{
// Copying the selected page to the place that rEvt points
// takes place in three steps:
// 1. Create a copy of the selected page. This copy will
// lie directly behind the selected page.
// 2. Move the copy to the desired place.
// 3. Select the copy.
if (pDrViewSh->IsSwitchPageAllowed())
{
// 1. Create a copy.
USHORT nPageNumOfCopy = pDoc->DuplicatePage (GetCurPageId() - 1);
// 2. Move page. For this first switch to the copy:
// MovePages operates on the currently selected page(s).
pDrViewSh->SwitchPage (nPageNumOfCopy);
// Adapt target page id when necessary, i.e. page copy
// has been inserted in front of the target page.
USHORT nPageNum = nPageId;
if ((nPageNumOfCopy <= nPageNum) && (nPageNum != (USHORT)-1))
nPageNum += 1;
if (pDoc->MovePages(nPageNum))
{
// 3. Switch to the copy that has been moved to its
// final destination. Use an asynchron slot call to
// be executed after the still pending ones.
if (nPageNumOfCopy >= nPageNum || (nPageNum == (USHORT)-1))
nPageNum += 1;
SetCurPageId (GetPageId(nPageNum));
SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher();
pDispatcher->Execute(SID_SWITCHPAGE,
SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
}
}
break;
}
}
nRet = rEvt.mnAction;
}
else
{
sal_Int32 nPageId = GetPageId( aPos ) - 1;
if( ( nPageId >= 0 ) && pDoc->GetPage( (USHORT)nPageId ) )
{
nRet = pDrViewSh->ExecuteDrop( rEvt, *this, NULL, (USHORT)nPageId, SDRLAYER_NOTFOUND );
}
}
HideDropPos();
EndSwitchPage();
return nRet;
}
/*************************************************************************
|*
\************************************************************************/
void TabControl::Command(const CommandEvent& rCEvt)
{
USHORT nCmd = rCEvt.GetCommand();
if ( nCmd == COMMAND_CONTEXTMENU )
{
BOOL bGraphicShell = pDrViewSh->ISA(GraphicViewShell);
USHORT nResId = bGraphicShell ? RID_GRAPHIC_PAGETAB_POPUP :
RID_DRAW_PAGETAB_POPUP;
SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher();
pDispatcher->ExecutePopup( SdResId( nResId ) );
}
}
/*************************************************************************
|*
\************************************************************************/
long TabControl::StartRenaming()
{
BOOL bOK = FALSE;
if (pDrViewSh->GetPageKind() == PK_STANDARD)
{
bOK = TRUE;
::sd::View* pView = pDrViewSh->GetView();
if ( pView->IsTextEdit() )
pView->SdrEndTextEdit();
}
return( bOK );
}
/*************************************************************************
|*
\************************************************************************/
long TabControl::AllowRenaming()
{
BOOL bOK = TRUE;
String aNewName( GetEditText() );
String aCompareName( GetPageText( GetEditPageId() ) );
if( aCompareName != aNewName )
{
// Seite umbenennen
if( pDrViewSh->GetDocSh()->CheckPageName( this, aNewName ) )
{
SetEditText( aNewName );
EndRenaming();
}
else
{
bOK = FALSE;
}
}
return( bOK );
}
/*************************************************************************
|*
\************************************************************************/
void TabControl::EndRenaming()
{
if( !IsEditModeCanceled() )
pDrViewSh->RenameSlide( GetEditPageId(), GetEditText() );
}
/*************************************************************************
|*
\************************************************************************/
void TabControl::ActivatePage()
{
if ( /*IsInSwitching && */ pDrViewSh->IsSwitchPageAllowed() )
{
SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher();
pDispatcher->Execute(SID_SWITCHPAGE,
SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
}
}
/*************************************************************************
|*
\************************************************************************/
long TabControl::DeactivatePage()
{
return pDrViewSh->IsSwitchPageAllowed();
}
void TabControl::SendActivatePageEvent (void)
{
CallEventListeners (VCLEVENT_TABBAR_PAGEACTIVATED,
reinterpret_cast<void*>(GetCurPageId()));
}
void TabControl::SendDeactivatePageEvent (void)
{
CallEventListeners (VCLEVENT_TABBAR_PAGEDEACTIVATED,
reinterpret_cast<void*>(GetCurPageId()));
}
} // end of namespace sd
<|endoftext|> |
<commit_before>#define CATCH_CONFIG_MAIN
#include <catch.hpp>
#include <Plugins/RoutingServices/CrowFlyRoutingService/CrowFlyRoutingService.h>
#include <Engine/SceneManager/SceneManager.h>
#include <Engine/SceneManager/Scene.h>
#include <Engine/SceneManager/Operation.h>
#include <Engine/Concepts/Basic/Capacity.h>
#include <Engine/SceneManager/Vehicle.h>
#include <Engine/SceneManager/Performer.h>
#include <Engine/SceneManager/Schedule.h>
#include <Engine/Concepts/Basic/RoutingProfile.h>
#include <Tests/Utils/Concepts/MakeLocation.h>
#include <Utils/Units/DurationUnits.h>
#include <Tests/Utils/Concepts/MakeTimeWindow.h>
#include <Utils/Collections/Algorithms.h>
#include <Engine/SceneManager/Run.h>
#include <Engine/SceneManager/Stop.h>
#include <engine/SceneManager/ScheduleActualization/Algorithms/StopDurationActualizationAlgorithm.h>
#include <Engine/SceneManager/ScheduleActualization/Algorithms/StopArrivalTimeActualizationAlgorithm.h>
#include <Tests/ConceptStreamOperators.h>
TEST_CASE("ScheduleActualizers - StopDurationActualizationAlgorithm", "[integration][schedule_actualizers]")
{
using namespace Scheduler;
CrowFlyRoutingService routing_service;
SceneManager sm;
sm.setRoutingService(&routing_service);
Location start_location = make_location(0, 0);
Location end_location = make_location(0, 0.5);
Location loc1 = make_location(0, 0.1);
Location loc2 = make_location(0, 0.2);
Location loc3 = make_location(0, 0.3);
Location loc4 = make_location(0, 0.4);
Scene* s = sm.createScene();
Performer* performer = s->createPerformer();
Vehicle* vehicle = s->createVehicle();
Schedule* schedule = s->createSchedule(performer);
schedule->setDepotLocation(start_location);
schedule->setShiftEndLocation(end_location);
schedule->getScheduleActualizer()->createAlgorithm<StopDurationActualizationAlgorithm>();
Run* r = schedule->createRun(start_location, end_location);
r->setVehicle(vehicle);
SECTION("Simple duration check")
{
Duration dur = Units::minutes(10);
Operation* sop = s->createFreeOperation();
sop->setDuration(dur);
sop->setLocation(start_location);
Operation* sop2 = s->createFreeOperation();
sop2->setDuration(dur);
sop2->setLocation(start_location);
Operation* op1 = s->createFreeOperation();
op1->setDuration(dur);
op1->setLocation(loc1);
Operation* op2 = s->createFreeOperation();
op2->setDuration(dur);
op2->setLocation(loc2);
Operation* op3 = s->createFreeOperation();
op3->setDuration(dur);
op3->setLocation(loc3);
Operation* op4 = s->createFreeOperation();
op4->setDuration(dur);
op4->setLocation(loc4);
Operation* eop = s->createFreeOperation();
eop->setDuration(dur);
eop->setLocation(end_location);
r->allocateStartOperation(sop);
r->allocateStartOperation(sop2);
r->allocateEndOperation(eop);
Stop *s1 = r->getStartStop();
Stop *s2 = r->allocateWorkOperation(op1, 0);
Stop *s3 = r->allocateWorkOperation(op2, 1);
Stop *s4 = r->allocateWorkOperation(op3, 2);
Stop *s5 = r->allocateWorkOperation(op4, 3);
Stop *s6 = r->getEndStop();
REQUIRE(s1->getDuration() == dur);
REQUIRE(s2->getDuration() == dur);
REQUIRE(s3->getDuration() == dur);
REQUIRE(s4->getDuration() == dur);
REQUIRE(s5->getDuration() == dur);
REQUIRE(s6->getDuration() == dur);
}
sm.destroyScene(s);
}
TEST_CASE("ScheduleActualizers - StopArrivalTimeActualizationAlgorithm", "[integration][schedule_actualizers]")
{
using namespace Scheduler;
CrowFlyRoutingService routing_service;
SceneManager sm;
sm.setRoutingService(&routing_service);
Location start_location = make_location(0, 0);
Location end_location = make_location(0, 0.5);
Location loc1 = make_location(0, 0.1);
Location loc2 = make_location(0, 0.2);
Location loc3 = make_location(0, 0.3);
Location loc4 = make_location(0, 0.4);
Scene* s = sm.createScene();
Duration dur = Units::minutes(10);
Operation* op1 = s->createFreeOperation();
op1->setDuration(dur);
op1->setLocation(loc1);
Operation* op2 = s->createFreeOperation();
op2->setDuration(dur);
op2->setLocation(loc2);
Operation* op3 = s->createFreeOperation();
op3->setDuration(dur);
op3->setLocation(loc3);
Operation* op4 = s->createFreeOperation();
op4->setDuration(dur);
op4->setLocation(loc4);
Performer* performer = s->createPerformer();
Vehicle* vehicle = s->createVehicle();
Schedule* schedule = s->createSchedule(performer);
schedule->setDepotLocation(start_location);
schedule->setShiftEndLocation(end_location);
Run* r = schedule->createRun(start_location, end_location);
r->setVehicle(vehicle);
Route r1 = routing_service.calculateRoute(start_location, loc1, vehicle->getRoutingProfile());
Route r2 = routing_service.calculateRoute(loc1, loc2, vehicle->getRoutingProfile());
Route r3 = routing_service.calculateRoute(loc2, loc3, vehicle->getRoutingProfile());
Route r4 = routing_service.calculateRoute(loc3, loc4, vehicle->getRoutingProfile());
Route r5 = routing_service.calculateRoute(loc4, end_location, vehicle->getRoutingProfile());
schedule->getScheduleActualizer()->createAlgorithm<StopDurationActualizationAlgorithm>();
schedule->getScheduleActualizer()->createAlgorithm<StopArrivalTimeActualizationAlgorithm>();
SECTION("Broad time windows")
{
Stop *s1 = r->getStartStop();
Stop *s2 = r->allocateWorkOperation(op1, 0);
Stop *s3 = r->allocateWorkOperation(op2, 1);
Stop *s4 = r->allocateWorkOperation(op3, 2);
Stop *s5 = r->allocateWorkOperation(op4, 3);
Stop *s6 = r->getEndStop();
TimeWindow estimated_allocation_1;
estimated_allocation_1.setStartTime(TimePoint(0));
estimated_allocation_1.setEndTime(TimePoint(0));
TimeWindow estimated_allocation_2;
estimated_allocation_2.setStartTime(estimated_allocation_1.getEndTime() + r1.getDuration());
estimated_allocation_2.setEndTime(estimated_allocation_2.getStartTime() + dur);
TimeWindow estimated_allocation_3;
estimated_allocation_3.setStartTime(estimated_allocation_2.getEndTime() + r2.getDuration());
estimated_allocation_3.setEndTime(estimated_allocation_3.getStartTime() + dur);
TimeWindow estimated_allocation_4;
estimated_allocation_4.setStartTime(estimated_allocation_3.getEndTime() + r3.getDuration());
estimated_allocation_4.setEndTime(estimated_allocation_4.getStartTime() + dur);
TimeWindow estimated_allocation_5;
estimated_allocation_5.setStartTime(estimated_allocation_4.getEndTime() + r4.getDuration());
estimated_allocation_5.setEndTime(estimated_allocation_5.getStartTime() + dur);
TimeWindow estimated_allocation_6;
estimated_allocation_6.setStartTime(estimated_allocation_5.getEndTime() + r5.getDuration());
estimated_allocation_6.setEndTime(estimated_allocation_6.getStartTime());
REQUIRE(s1->getAllocationTime() == estimated_allocation_1);
REQUIRE(s2->getAllocationTime() == estimated_allocation_2);
REQUIRE(s3->getAllocationTime() == estimated_allocation_3);
REQUIRE(s4->getAllocationTime() == estimated_allocation_4);
REQUIRE(s5->getAllocationTime() == estimated_allocation_5);
REQUIRE(s6->getAllocationTime() == estimated_allocation_6);
}
sm.destroyScene(s);
}<commit_msg>close #15 Tests are added and working<commit_after>#define CATCH_CONFIG_MAIN
#include <catch.hpp>
#include <Plugins/RoutingServices/CrowFlyRoutingService/CrowFlyRoutingService.h>
#include <Engine/SceneManager/SceneManager.h>
#include <Engine/SceneManager/Scene.h>
#include <Engine/SceneManager/Operation.h>
#include <Engine/Concepts/Basic/Capacity.h>
#include <Engine/SceneManager/Vehicle.h>
#include <Engine/SceneManager/Performer.h>
#include <Engine/SceneManager/Schedule.h>
#include <Engine/Concepts/Basic/RoutingProfile.h>
#include <Tests/Utils/Concepts/MakeLocation.h>
#include <Utils/Units/DurationUnits.h>
#include <Tests/Utils/Concepts/MakeTimeWindow.h>
#include <Utils/Collections/Algorithms.h>
#include <Engine/SceneManager/Run.h>
#include <Engine/SceneManager/Stop.h>
#include <engine/SceneManager/ScheduleActualization/Algorithms/StopDurationActualizationAlgorithm.h>
#include <Engine/SceneManager/ScheduleActualization/Algorithms/StopArrivalTimeActualizationAlgorithm.h>
#include <Tests/ConceptStreamOperators.h>
TEST_CASE("ScheduleActualizers - StopDurationActualizationAlgorithm", "[integration][schedule_actualizers]")
{
using namespace Scheduler;
CrowFlyRoutingService routing_service;
SceneManager sm;
sm.setRoutingService(&routing_service);
Location start_location = make_location(0, 0);
Location end_location = make_location(0, 0.5);
Location loc1 = make_location(0, 0.1);
Location loc2 = make_location(0, 0.2);
Location loc3 = make_location(0, 0.3);
Location loc4 = make_location(0, 0.4);
Scene* s = sm.createScene();
Performer* performer = s->createPerformer();
Vehicle* vehicle = s->createVehicle();
Schedule* schedule = s->createSchedule(performer);
schedule->setDepotLocation(start_location);
schedule->setShiftEndLocation(end_location);
schedule->getScheduleActualizer()->createAlgorithm<StopDurationActualizationAlgorithm>();
Run* r = schedule->createRun(start_location, end_location);
r->setVehicle(vehicle);
SECTION("Simple duration check")
{
Duration dur = Units::minutes(10);
Operation* sop = s->createFreeOperation();
sop->setDuration(dur);
sop->setLocation(start_location);
Operation* sop2 = s->createFreeOperation();
sop2->setDuration(dur);
sop2->setLocation(start_location);
Operation* op1 = s->createFreeOperation();
op1->setDuration(dur);
op1->setLocation(loc1);
Operation* op2 = s->createFreeOperation();
op2->setDuration(dur);
op2->setLocation(loc2);
Operation* op3 = s->createFreeOperation();
op3->setDuration(dur);
op3->setLocation(loc3);
Operation* op4 = s->createFreeOperation();
op4->setDuration(dur);
op4->setLocation(loc4);
Operation* eop = s->createFreeOperation();
eop->setDuration(dur);
eop->setLocation(end_location);
r->allocateStartOperation(sop);
r->allocateStartOperation(sop2);
r->allocateEndOperation(eop);
Stop *s1 = r->getStartStop();
Stop *s2 = r->allocateWorkOperation(op1, 0);
Stop *s3 = r->allocateWorkOperation(op2, 1);
Stop *s4 = r->allocateWorkOperation(op3, 2);
Stop *s5 = r->allocateWorkOperation(op4, 3);
Stop *s6 = r->getEndStop();
REQUIRE(s1->getDuration() == dur*2);
REQUIRE(s2->getDuration() == dur);
REQUIRE(s3->getDuration() == dur);
REQUIRE(s4->getDuration() == dur);
REQUIRE(s5->getDuration() == dur);
REQUIRE(s6->getDuration() == dur);
}
sm.destroyScene(s);
}
TEST_CASE("ScheduleActualizers - StopArrivalTimeActualizationAlgorithm", "[integration][schedule_actualizers]")
{
using namespace Scheduler;
CrowFlyRoutingService routing_service;
SceneManager sm;
sm.setRoutingService(&routing_service);
Location start_location = make_location(0, 0);
Location end_location = make_location(0, 0.5);
Location loc1 = make_location(0, 0.1);
Location loc2 = make_location(0, 0.2);
Location loc3 = make_location(0, 0.3);
Location loc4 = make_location(0, 0.4);
Scene* s = sm.createScene();
Duration dur = Units::minutes(10);
Operation* op1 = s->createFreeOperation();
op1->setDuration(dur);
op1->setLocation(loc1);
Operation* op2 = s->createFreeOperation();
op2->setDuration(dur);
op2->setLocation(loc2);
Operation* op3 = s->createFreeOperation();
op3->setDuration(dur);
op3->setLocation(loc3);
Operation* op4 = s->createFreeOperation();
op4->setDuration(dur);
op4->setLocation(loc4);
Performer* performer = s->createPerformer();
Vehicle* vehicle = s->createVehicle();
Schedule* schedule = s->createSchedule(performer);
schedule->setDepotLocation(start_location);
schedule->setShiftEndLocation(end_location);
Run* r = schedule->createRun(start_location, end_location);
r->setVehicle(vehicle);
Route r1 = routing_service.calculateRoute(start_location, loc1, vehicle->getRoutingProfile());
Route r2 = routing_service.calculateRoute(loc1, loc2, vehicle->getRoutingProfile());
Route r3 = routing_service.calculateRoute(loc2, loc3, vehicle->getRoutingProfile());
Route r4 = routing_service.calculateRoute(loc3, loc4, vehicle->getRoutingProfile());
Route r5 = routing_service.calculateRoute(loc4, end_location, vehicle->getRoutingProfile());
schedule->getScheduleActualizer()->createAlgorithm<StopDurationActualizationAlgorithm>();
schedule->getScheduleActualizer()->createAlgorithm<StopArrivalTimeActualizationAlgorithm>();
TimeWindow estimated_allocation_1;
TimeWindow estimated_allocation_2;
TimeWindow estimated_allocation_3;
TimeWindow estimated_allocation_4;
TimeWindow estimated_allocation_5;
TimeWindow estimated_allocation_6;
SECTION("Broad time windows") {
estimated_allocation_1.setStartTime(TimePoint(0));
estimated_allocation_1.setEndTime(TimePoint(0));
estimated_allocation_2.setStartTime(estimated_allocation_1.getEndTime() + r1.getDuration());
estimated_allocation_2.setEndTime(estimated_allocation_2.getStartTime() + dur);
estimated_allocation_3.setStartTime(estimated_allocation_2.getEndTime() + r2.getDuration());
estimated_allocation_3.setEndTime(estimated_allocation_3.getStartTime() + dur);
estimated_allocation_4.setStartTime(estimated_allocation_3.getEndTime() + r3.getDuration());
estimated_allocation_4.setEndTime(estimated_allocation_4.getStartTime() + dur);
estimated_allocation_5.setStartTime(estimated_allocation_4.getEndTime() + r4.getDuration());
estimated_allocation_5.setEndTime(estimated_allocation_5.getStartTime() + dur);
estimated_allocation_6.setStartTime(estimated_allocation_5.getEndTime() + r5.getDuration());
estimated_allocation_6.setEndTime(estimated_allocation_6.getStartTime());
}
SECTION("Narrow time windows")
{
op1->setTimeWindows({make_time_window(770, 1370)});
op2->setTimeWindows({make_time_window(2140, 2740)});
op3->setTimeWindows({make_time_window(3510, 4110)});
op4->setTimeWindows({make_time_window(4880, 5480)});
estimated_allocation_1.setStartTime(TimePoint(100));
estimated_allocation_1.setEndTime(TimePoint(100));
estimated_allocation_2.setStartTime(TimePoint(770));
estimated_allocation_2.setEndTime(estimated_allocation_2.getStartTime() + dur);
estimated_allocation_3.setStartTime(TimePoint(2140));
estimated_allocation_3.setEndTime(estimated_allocation_3.getStartTime() + dur);
estimated_allocation_4.setStartTime(TimePoint(3510));
estimated_allocation_4.setEndTime(estimated_allocation_4.getStartTime() + dur);
estimated_allocation_5.setStartTime(TimePoint(4880));
estimated_allocation_5.setEndTime(estimated_allocation_5.getStartTime() + dur);
estimated_allocation_6.setStartTime(estimated_allocation_5.getEndTime() + r5.getDuration());
estimated_allocation_6.setEndTime(estimated_allocation_6.getStartTime());
}
SECTION("Narrow time windows with budget")
{
op1->setTimeWindows({make_time_window(770, 20000)});
op2->setTimeWindows({make_time_window(2140, 20000)});
op3->setTimeWindows({make_time_window(3510, 20000)});
op4->setTimeWindows({make_time_window(4880, 20000)});
estimated_allocation_1.setStartTime(TimePoint(400));
estimated_allocation_1.setEndTime(estimated_allocation_1.getStartTime());
estimated_allocation_2.setStartTime(TimePoint(1070));
estimated_allocation_2.setEndTime(estimated_allocation_2.getStartTime() + dur);
estimated_allocation_3.setStartTime(TimePoint(2340));
estimated_allocation_3.setEndTime(estimated_allocation_3.getStartTime() + dur);
estimated_allocation_4.setStartTime(TimePoint(3610));
estimated_allocation_4.setEndTime(estimated_allocation_4.getStartTime() + dur);
estimated_allocation_5.setStartTime(TimePoint(4880));
estimated_allocation_5.setEndTime(estimated_allocation_5.getStartTime() + dur);
estimated_allocation_6.setStartTime(estimated_allocation_5.getEndTime() + r5.getDuration());
estimated_allocation_6.setEndTime(estimated_allocation_6.getStartTime());
}
SECTION("Narrow time windows with budget gap")
{
op1->setTimeWindows({make_time_window(770, 20000)});
op2->setTimeWindows({make_time_window(2140, 2740)}); // <== This stop can't be shifted to compensate waiting due to its time window
op3->setTimeWindows({make_time_window(3510, 20000)});
op4->setTimeWindows({make_time_window(4880, 20000)});
estimated_allocation_1.setStartTime(TimePoint(200));
estimated_allocation_1.setEndTime(estimated_allocation_1.getStartTime());
estimated_allocation_2.setStartTime(TimePoint(870));
estimated_allocation_2.setEndTime(estimated_allocation_2.getStartTime() + dur);
estimated_allocation_3.setStartTime(TimePoint(2140));
estimated_allocation_3.setEndTime(estimated_allocation_3.getStartTime() + dur);
estimated_allocation_4.setStartTime(TimePoint(3510));
estimated_allocation_4.setEndTime(estimated_allocation_4.getStartTime() + dur);
estimated_allocation_5.setStartTime(TimePoint(4880));
estimated_allocation_5.setEndTime(estimated_allocation_5.getStartTime() + dur);
estimated_allocation_6.setStartTime(estimated_allocation_5.getEndTime() + r5.getDuration());
estimated_allocation_6.setEndTime(estimated_allocation_6.getStartTime());
}
Stop *s1 = r->getStartStop();
Stop *s2 = r->allocateWorkOperation(op1, 0);
Stop *s3 = r->allocateWorkOperation(op2, 1);
Stop *s4 = r->allocateWorkOperation(op3, 2);
Stop *s5 = r->allocateWorkOperation(op4, 3);
Stop *s6 = r->getEndStop();
CAPTURE(s1->getAllocationTime());
CAPTURE(s2->getAllocationTime());
CAPTURE(s3->getAllocationTime());
CAPTURE(s4->getAllocationTime());
CAPTURE(s5->getAllocationTime());
CAPTURE(s6->getAllocationTime());
REQUIRE(s1->getAllocationTime() == estimated_allocation_1);
REQUIRE(s2->getAllocationTime() == estimated_allocation_2);
REQUIRE(s3->getAllocationTime() == estimated_allocation_3);
REQUIRE(s4->getAllocationTime() == estimated_allocation_4);
REQUIRE(s5->getAllocationTime() == estimated_allocation_5);
REQUIRE(s6->getAllocationTime() == estimated_allocation_6);
sm.destroyScene(s);
}<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2000 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 [email protected].
*
* 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 "XalanToXercesTranscoderWrapper.hpp"
#include <cassert>
#include <util/TransService.hpp>
#include <util/XMLException.hpp>
XalanToXercesTranscoderWrapper::XalanToXercesTranscoderWrapper(XMLTranscoder* theTranscoder) :
XalanOutputTranscoder(),
m_transcoder(theTranscoder)
{
}
XalanToXercesTranscoderWrapper::~XalanToXercesTranscoderWrapper()
{
delete m_transcoder;
}
XalanToXercesTranscoderWrapper::eCode
XalanToXercesTranscoderWrapper::transcode(
const XalanDOMChar* theSourceData,
unsigned int theSourceCount,
XalanXMLByte* theTarget,
unsigned int theTargetSize,
unsigned int& theSourceCharsTranscoded,
unsigned int& theTargetBytesUsed)
{
eCode theCode = XalanTranscodingServices::OK;
try
{
theTargetBytesUsed = m_transcoder->transcodeTo(
theSourceData,
theSourceCount,
theTarget,
theTargetSize,
theSourceCharsTranscoded,
XMLTranscoder::UnRep_Throw);
}
catch(const XMLException&)
{
theSourceCharsTranscoded = 0;
theTargetBytesUsed = 0;
theCode = XalanTranscodingServices::InternalFailure;
}
return theCode;
}
<commit_msg>Used replace character instead of throwing an exception when unable to transcode a character.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2000 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 [email protected].
*
* 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 "XalanToXercesTranscoderWrapper.hpp"
#include <cassert>
#include <util/TransService.hpp>
#include <util/XMLException.hpp>
XalanToXercesTranscoderWrapper::XalanToXercesTranscoderWrapper(XMLTranscoder* theTranscoder) :
XalanOutputTranscoder(),
m_transcoder(theTranscoder)
{
}
XalanToXercesTranscoderWrapper::~XalanToXercesTranscoderWrapper()
{
delete m_transcoder;
}
XalanToXercesTranscoderWrapper::eCode
XalanToXercesTranscoderWrapper::transcode(
const XalanDOMChar* theSourceData,
unsigned int theSourceCount,
XalanXMLByte* theTarget,
unsigned int theTargetSize,
unsigned int& theSourceCharsTranscoded,
unsigned int& theTargetBytesUsed)
{
eCode theCode = XalanTranscodingServices::OK;
try
{
theTargetBytesUsed = m_transcoder->transcodeTo(
theSourceData,
theSourceCount,
theTarget,
theTargetSize,
theSourceCharsTranscoded,
// $$$ ToDo: Eventually, we're going to want to
// replace this with UnRep_Throw, and let the
// caller try to recover.
// XMLTranscoder::UnRep_Throw);
XMLTranscoder::UnRep_RepChar);
}
catch(const XMLException&)
{
theSourceCharsTranscoded = 0;
theTargetBytesUsed = 0;
theCode = XalanTranscodingServices::InternalFailure;
}
return theCode;
}
<|endoftext|> |
<commit_before>
#ifdef NDA_CODE_AMD_MANTLE
// NDACodeStripper v0.17: 1181 lines removed
#endif
<commit_msg>Mantle backend updated to match D3D11 behaviour.<commit_after>
#ifdef NDA_CODE_AMD_MANTLE
// NDACodeStripper v0.17: 1328 lines removed
#endif
<|endoftext|> |
<commit_before>#ifndef INCLUDE_AL_CONVERSION_HPP
#define INCLUDE_AL_CONVERSION_HPP
/* Allocore --
Multimedia / virtual environment application class library
Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
Copyright (C) 2006-2008. The Regents of the University of California (REGENTS).
All Rights Reserved.
Permission to use, copy, modify, distribute, and distribute modified versions
of this software and its documentation without fee and without a signed
licensing agreement, is hereby granted, provided that the above copyright
notice, the list of contributors, this paragraph and the following two paragraphs
appear in all copies, modifications, and distributions.
IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING
OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
File description:
This is a grab bag of routines for converting between built-in types
File author(s):
Lance Putnam, 2010, [email protected]
*/
#include <stdio.h>
#include <iostream>
#include <limits.h>
#include <sstream> /* string conversion */
#include "allocore/system/al_Config.h"
namespace al{
#ifndef UINT32_C
#define UINT32_C(v) v ## UL
#endif
#ifndef UINT64_C
#define UINT64_C(v) v ## ULL
#endif
#define CONST(N, vf, vd)\
template <class T> struct N;\
template<> struct N< float>{ operator uint32_t() const { return UINT32_C(vf); } };\
template<> struct N<double>{ operator uint64_t() const { return UINT64_C(vd); } };
CONST(MaskExpo, 0x7F800000, 0x7FF0000000000000) // IEEE-754 floating-point exponent bit mask
CONST(MaskFrac, 0x007FFFFF, 0x000FFFFFFFFFFFFF) // IEEE-754 floating-point fraction bit mask
CONST(MaskSign, 0x80000000, 0x8000000000000000) // IEEE-754 floating-point sign bit mask
CONST(Expo1 , 0x3F800000, 0x3FF0000000000000) // IEEE-754 floating-point [1-2) exponent interval
#undef CONST
/// Union for twiddling bits of floats
template<class T> struct Twiddle;
template<> struct Twiddle<float>{
Twiddle(const float& v): f(v){}
Twiddle(const uint32_t& v): u(v){}
Twiddle(const int32_t& v): i(v){}
union{ int32_t i; uint32_t u; float f; };
};
template<> struct Twiddle<double>{
Twiddle(const double& v): f(v){}
Twiddle(const uint64_t& v): u(v){}
Twiddle(const int64_t& v): i(v){}
union{ int64_t i; uint64_t u; double f; };
};
/// Convert decimal integer to ascii base-36 character
char base10To36(int dec10);
/// Convert ascii base-36 character to decimal integer
int base36To10(char ascii36);
/// Convert a string of 1s and 0s to an integer.
/// @param[in] strBin binary string where the first character is the most-significant digit
///
uint32_t bitsToUInt(const char * strBin);
/// Returns zero if argument is subnormal, otherwise returns argument
float blockSubnormal(float v);
/// Returns zero if argument is subnormal, otherwise returns argument
double blockSubnormal(double v);
/// Returns 1 if little endian, 0 if big endian
int endian();
/// Returns biased decimal value of 32-bit float exponent field.
/// The true exponent is the return value minus 127.
/// For example, values in [0.5, 1) return 126 (01111110), so the true
/// exponent is 126 - 127 = -1.
uint32_t floatExponent(float v);
/// Returns mantissa field as float between [0, 1).
float floatMantissa(float v);
/// Converts linear integer phase to fraction
/// 2^bits is the effective size of the lookup table. \n
/// Note: the fraction only has 24-bits of precision.
float fraction(uint32_t bits, uint32_t phase);
/// Convert 16-bit signed integer to floating point in [-1, 1)
float intToUnit(int16_t v);
/// Type-pun 32-bit unsigned int to 32-bit float
/// This function uses a union to avoid problems with direct pointer casting
/// when the fstrict-aliasing compiler flag is on.
inline float punUF(uint32_t v){ Twiddle<float> u(v); return u.f; }
/// Type-pun 32-bit float to 32-bit unsigned int
/// This function uses a union to avoid problems with direct pointer casting
/// when the fstrict-aliasing compiler flag is on.
inline uint32_t punFU( float v){ Twiddle< float> u(v); return u.u; }
/// Type-pun 32-bit float to 32-bit signed int
inline int32_t punFI( float v){ Twiddle< float> u(v); return u.i; }
/// Type-pun 64-bit float to 64-bit unsigned int
inline uint64_t punFU( double v){ Twiddle<double> u(v); return u.u; }
/// Type-pun 64-bit float to 64-bit signed int
inline int64_t punFI( double v){ Twiddle<double> u(v); return u.i; }
/// Type-pun 64-bit unsigned int to 64-bit float
inline double punUF(uint64_t v){ Twiddle<double> u(v); return u.f; }
/// Type-pun 64-bit signed int to 64-bit float
inline double punIF( int64_t v){ Twiddle<double> u(v); return u.f; }
/// Convert numerical type to a string
template <class T> std::string toString(const T& v);
/// Convert array of numerical types to a comma separated string
template <class T>
std::string toString(const T * v, int num, int stride=1);
/// Convert 32-bit unsigned integer to unit float in [0, 1)
template<class T> T uintToUnit (uint32_t v);
/// Convert 32-bit unsigned integer to unit float in [-1, 1)
template<class T> T uintToUnitS(uint32_t v);
/// Convert floating point in [0, 1) to unsigned long in [0, 2^32)
/// This conversion is most accurate on a linear scale.
/// Input values outside [0, 1) result in undefined behavior.
uint32_t unitToUInt(float u);
/// Convert floating point in [0, 1) to unsigned long in [0, 2^32)
/// This conversion is most accurate on an exponential scale.
/// Input values outside [-1, 1) return 0.
/// Values in [-1, 0] behave as positive values in [0, 1).
uint32_t unitToUInt2(float u);
/// Convert unit float in [0,1) to 8-bit unsigned int in [0, 256).
uint8_t unitToUInt8(float u);
// Implementation
//------------------------------------------------------------------------------
inline char base10To36(int v){
static const char * c = "0123456789abcdefghijklmnopqrstuvwxyz";
if(v>=0 && v<=35) return c[v];
return '0';
}
inline int base36To10(char v){
v = tolower(v);
if(v>='0' && v<='9') return v - '0';
if(v>='a' && v<='z') return v - 'a' + 10;
return 0; // non-alphanumeric
}
inline uint32_t bitsToUInt(const char * string){
uint32_t v=0; int n = strlen(string);
for(int i=0; i<n; ++i) if(string[i] == '1') v |= 1<<(n-1-i);
return v;
}
// alternate version...
//inline uint32_t bitsToUInt(const char * bits){
// uint32_t i=0, r=0;
// for(; bits[i] && i<32; ++i) r |= ((bits[i]=='1'?1:0) << (31-i));
// return r>>(32-i);
//}
/// Sets argument to zero if subnormal
inline float blockSubnormal(float v){
const uint32_t i = punFU(v);
const uint32_t frac = i & MaskFrac<float>();
const uint32_t expo = i & MaskExpo<float>();
if(expo == 0 && frac != 0) v = 0.f;
return v;
}
/// Sets argument to zero if subnormal
inline double blockSubnormal(double v){
const uint64_t i = punFU(v);
const uint64_t frac = i & MaskFrac<double>();
const uint64_t expo = i & MaskExpo<double>();
if(expo == 0 && frac != 0) v = 0.;
return v;
}
inline int endian(){
static int x=1;
return *(char *)&x;
}
inline uint32_t floatExponent(float v){
return punFU(v) >> 23 & 0xff;
}
inline float floatMantissa(float v){
uint32_t frac = punFU(v);
frac = (frac & MaskFrac<float>()) | Expo1<float>();
return punUF(frac) - 1.f;
}
inline float fraction(uint32_t bits, uint32_t phase){
phase = phase << bits >> 9 | Expo1<float>();
return punUF(phase) - 1.f;
}
inline float intToUnit(int16_t v){
uint32_t vu = (((uint32_t)v) + 0x808000) << 7; // set fraction in float [2, 4)
return punUF(vu) - 3.f;
}
template <class T>
std::string toString(const T * v, int n, int s){
std::string r;
for(int i=0; i<n; ++i){
r += toString(v[i*s]);
if(i<(n-1)) r += ", ";
}
return r;
}
template <class T>
std::string toString(const T& v){
using namespace std;
stringstream ss(stringstream::in | stringstream::out);
ss << v;
string r;
ss >> r;
return r;
}
template<> inline float uintToUnit<float>(uint32_t v){
v = v >> 9 | Expo1<float>(); // float in [1, 2)
return punUF(v) - 1.f;
}
template<> inline float uintToUnitS<float>(uint32_t v){
v = v >> 9 | 0x40000000; // float in [2, 4)
return punUF(v) - 3.f;
}
inline uint32_t unitToUInt(float v){
++v; // go into [1,2] range, FP fraction is now result
return punFU(v) << 9;
}
// TODO: make 64-bit ready
inline uint32_t unitToUInt2(float v){
uint32_t normalU = punFU(v);
uint32_t rbs = 126UL - (normalU >> 23UL);
// printf("%x %lu\n", (normalU | 0x800000) << 8, rbs);
// printf("%x\n", 0x80000000UL >> rbs);
return (((normalU | 0x800000UL) << 8UL) & (~ULONG_MAX | 0xffffffffUL)) >> rbs;
// uint32_t normalU = punFU(v);
// uint32_t rbs = 118UL - ((normalU >> 23UL) & (~ULONG_MAX | 0x7fffffUL));
//// printf("%x %lu\n", (normalU | 0x800000) << 8, rbs);
//// printf("%x\n", 0x80000000UL >> rbs);
// return ((normalU & (~ULONG_MAX | 0xffffffUL)) | 0x800000UL) >> rbs;
//// return (((normalU | 0x800000UL) << 8UL) & (~ULONG_MAX | 0xffffffffUL)) >> rbs;
//Her00
//float y = v + 1.f;
//return ((unsigned long&)v) & 0x7FFFFF; // last 23 bits
}
inline uint8_t unitToUInt8(float u){
++u;
return (punFU(u) >> 15) & MaskFrac<float>();
}
} // al::
#endif
<commit_msg>add unit float to 16-bit int function<commit_after>#ifndef INCLUDE_AL_CONVERSION_HPP
#define INCLUDE_AL_CONVERSION_HPP
/* Allocore --
Multimedia / virtual environment application class library
Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
Copyright (C) 2006-2008. The Regents of the University of California (REGENTS).
All Rights Reserved.
Permission to use, copy, modify, distribute, and distribute modified versions
of this software and its documentation without fee and without a signed
licensing agreement, is hereby granted, provided that the above copyright
notice, the list of contributors, this paragraph and the following two paragraphs
appear in all copies, modifications, and distributions.
IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING
OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
File description:
This is a grab bag of routines for converting between built-in types
File author(s):
Lance Putnam, 2010, [email protected]
*/
#include <stdio.h>
#include <iostream>
#include <limits.h>
#include <sstream> /* string conversion */
#include "allocore/system/al_Config.h"
namespace al{
#ifndef UINT32_C
#define UINT32_C(v) v ## UL
#endif
#ifndef UINT64_C
#define UINT64_C(v) v ## ULL
#endif
#define CONST(N, vf, vd)\
template <class T> struct N;\
template<> struct N< float>{ operator uint32_t() const { return UINT32_C(vf); } };\
template<> struct N<double>{ operator uint64_t() const { return UINT64_C(vd); } };
CONST(MaskExpo, 0x7F800000, 0x7FF0000000000000) // IEEE-754 floating-point exponent bit mask
CONST(MaskFrac, 0x007FFFFF, 0x000FFFFFFFFFFFFF) // IEEE-754 floating-point fraction bit mask
CONST(MaskSign, 0x80000000, 0x8000000000000000) // IEEE-754 floating-point sign bit mask
CONST(Expo1 , 0x3F800000, 0x3FF0000000000000) // IEEE-754 floating-point [1-2) exponent interval
#undef CONST
/// Union for twiddling bits of floats
template<class T> struct Twiddle;
template<> struct Twiddle<float>{
Twiddle(const float& v): f(v){}
Twiddle(const uint32_t& v): u(v){}
Twiddle(const int32_t& v): i(v){}
union{ int32_t i; uint32_t u; float f; };
};
template<> struct Twiddle<double>{
Twiddle(const double& v): f(v){}
Twiddle(const uint64_t& v): u(v){}
Twiddle(const int64_t& v): i(v){}
union{ int64_t i; uint64_t u; double f; };
};
/// Convert decimal integer to ascii base-36 character
char base10To36(int dec10);
/// Convert ascii base-36 character to decimal integer
int base36To10(char ascii36);
/// Convert a string of 1s and 0s to an integer.
/// @param[in] strBin binary string where the first character is the most-significant digit
///
uint32_t bitsToUInt(const char * strBin);
/// Returns zero if argument is subnormal, otherwise returns argument
float blockSubnormal(float v);
/// Returns zero if argument is subnormal, otherwise returns argument
double blockSubnormal(double v);
/// Returns 1 if little endian, 0 if big endian
int endian();
/// Returns biased decimal value of 32-bit float exponent field.
/// The true exponent is the return value minus 127.
/// For example, values in [0.5, 1) return 126 (01111110), so the true
/// exponent is 126 - 127 = -1.
uint32_t floatExponent(float v);
/// Returns mantissa field as float between [0, 1).
float floatMantissa(float v);
/// Converts linear integer phase to fraction
/// 2^bits is the effective size of the lookup table. \n
/// Note: the fraction only has 24-bits of precision.
float fraction(uint32_t bits, uint32_t phase);
/// Convert 16-bit signed integer to floating point in [-1, 1)
float intToUnit(int16_t v);
/// Type-pun 32-bit unsigned int to 32-bit float
/// This function uses a union to avoid problems with direct pointer casting
/// when the fstrict-aliasing compiler flag is on.
inline float punUF(uint32_t v){ Twiddle<float> u(v); return u.f; }
/// Type-pun 32-bit float to 32-bit unsigned int
/// This function uses a union to avoid problems with direct pointer casting
/// when the fstrict-aliasing compiler flag is on.
inline uint32_t punFU( float v){ Twiddle< float> u(v); return u.u; }
/// Type-pun 32-bit float to 32-bit signed int
inline int32_t punFI( float v){ Twiddle< float> u(v); return u.i; }
/// Type-pun 64-bit float to 64-bit unsigned int
inline uint64_t punFU( double v){ Twiddle<double> u(v); return u.u; }
/// Type-pun 64-bit float to 64-bit signed int
inline int64_t punFI( double v){ Twiddle<double> u(v); return u.i; }
/// Type-pun 64-bit unsigned int to 64-bit float
inline double punUF(uint64_t v){ Twiddle<double> u(v); return u.f; }
/// Type-pun 64-bit signed int to 64-bit float
inline double punIF( int64_t v){ Twiddle<double> u(v); return u.f; }
/// Convert numerical type to a string
template <class T> std::string toString(const T& v);
/// Convert array of numerical types to a comma separated string
template <class T>
std::string toString(const T * v, int num, int stride=1);
/// Convert 32-bit unsigned integer to unit float in [0, 1)
template<class T> T uintToUnit (uint32_t v);
/// Convert 32-bit unsigned integer to unit float in [-1, 1)
template<class T> T uintToUnitS(uint32_t v);
/// Convert float in [-1, 1) to 16-bit signed int in [0, 2^16)
int16_t unitToInt16(float v);
/// Convert float in [0, 1) to 32-bit unsigned int in [0, 2^32)
/// This conversion is most accurate on a linear scale.
/// Input values outside [0, 1) result in undefined behavior.
uint32_t unitToUInt(float u);
/// Convert float in [0, 1) to 32-bit unsigned int in [0, 2^32)
/// This conversion is most accurate on an exponential scale.
/// Input values outside [-1, 1) return 0.
/// Values in [-1, 0] behave as positive values in [0, 1).
uint32_t unitToUInt2(float u);
/// Convert float in [0, 1) to 8-bit unsigned int in [0, 256)
uint8_t unitToUInt8(float u);
// Implementation
//------------------------------------------------------------------------------
inline char base10To36(int v){
static const char * c = "0123456789abcdefghijklmnopqrstuvwxyz";
if(v>=0 && v<=35) return c[v];
return '0';
}
inline int base36To10(char v){
v = tolower(v);
if(v>='0' && v<='9') return v - '0';
if(v>='a' && v<='z') return v - 'a' + 10;
return 0; // non-alphanumeric
}
inline uint32_t bitsToUInt(const char * string){
uint32_t v=0; int n = strlen(string);
for(int i=0; i<n; ++i) if(string[i] == '1') v |= 1<<(n-1-i);
return v;
}
// alternate version...
//inline uint32_t bitsToUInt(const char * bits){
// uint32_t i=0, r=0;
// for(; bits[i] && i<32; ++i) r |= ((bits[i]=='1'?1:0) << (31-i));
// return r>>(32-i);
//}
/// Sets argument to zero if subnormal
inline float blockSubnormal(float v){
const uint32_t i = punFU(v);
const uint32_t frac = i & MaskFrac<float>();
const uint32_t expo = i & MaskExpo<float>();
if(expo == 0 && frac != 0) v = 0.f;
return v;
}
/// Sets argument to zero if subnormal
inline double blockSubnormal(double v){
const uint64_t i = punFU(v);
const uint64_t frac = i & MaskFrac<double>();
const uint64_t expo = i & MaskExpo<double>();
if(expo == 0 && frac != 0) v = 0.;
return v;
}
inline int endian(){
static int x=1;
return *(char *)&x;
}
inline uint32_t floatExponent(float v){
return punFU(v) >> 23 & 0xff;
}
inline float floatMantissa(float v){
uint32_t frac = punFU(v);
frac = (frac & MaskFrac<float>()) | Expo1<float>();
return punUF(frac) - 1.f;
}
inline float fraction(uint32_t bits, uint32_t phase){
phase = phase << bits >> 9 | Expo1<float>();
return punUF(phase) - 1.f;
}
inline float intToUnit(int16_t v){
uint32_t vu = (((uint32_t)v) + 0x808000) << 7; // set fraction in float [2, 4)
return punUF(vu) - 3.f;
}
template <class T>
std::string toString(const T * v, int n, int s){
std::string r;
for(int i=0; i<n; ++i){
r += toString(v[i*s]);
if(i<(n-1)) r += ", ";
}
return r;
}
template <class T>
std::string toString(const T& v){
using namespace std;
stringstream ss(stringstream::in | stringstream::out);
ss << v;
string r;
ss >> r;
return r;
}
template<> inline float uintToUnit<float>(uint32_t v){
v = v >> 9 | Expo1<float>(); // float in [1, 2)
return punUF(v) - 1.f;
}
template<> inline float uintToUnitS<float>(uint32_t v){
v = v >> 9 | 0x40000000; // float in [2, 4)
return punUF(v) - 3.f;
}
inline int16_t unitToInt16(float v){
float r = v + 3.f; // put in [2,4)
return int16_t((al::punFU(r) >> 7) + (1<<15));
}
inline uint32_t unitToUInt(float v){
++v; // go into [1,2] range, FP fraction is now result
return punFU(v) << 9;
}
// TODO: make 64-bit ready
inline uint32_t unitToUInt2(float v){
uint32_t normalU = punFU(v);
uint32_t rbs = 126UL - (normalU >> 23UL);
// printf("%x %lu\n", (normalU | 0x800000) << 8, rbs);
// printf("%x\n", 0x80000000UL >> rbs);
return (((normalU | 0x800000UL) << 8UL) & (~ULONG_MAX | 0xffffffffUL)) >> rbs;
// uint32_t normalU = punFU(v);
// uint32_t rbs = 118UL - ((normalU >> 23UL) & (~ULONG_MAX | 0x7fffffUL));
//// printf("%x %lu\n", (normalU | 0x800000) << 8, rbs);
//// printf("%x\n", 0x80000000UL >> rbs);
// return ((normalU & (~ULONG_MAX | 0xffffffUL)) | 0x800000UL) >> rbs;
//// return (((normalU | 0x800000UL) << 8UL) & (~ULONG_MAX | 0xffffffffUL)) >> rbs;
//Her00
//float y = v + 1.f;
//return ((unsigned long&)v) & 0x7FFFFF; // last 23 bits
}
inline uint8_t unitToUInt8(float u){
++u;
return (punFU(u) >> 15) & MaskFrac<float>();
}
} // al::
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "bin/dartdev_utils.h"
#include <memory>
#include "bin/directory.h"
#include "bin/exe_utils.h"
#include "bin/file.h"
#include "platform/utils.h"
namespace dart {
namespace bin {
bool DartDevUtils::ShouldParseCommand(const char* script_uri) {
// If script_uri is not a file path or of a known URI scheme, we can assume
// that this is a DartDev command.
return (!File::ExistsUri(nullptr, script_uri) &&
(strncmp(script_uri, "http://", 7) != 0) &&
(strncmp(script_uri, "https://", 8) != 0) &&
(strncmp(script_uri, "file://", 7) != 0) &&
(strncmp(script_uri, "google3://", 10) != 0));
}
bool DartDevUtils::TryResolveDartDevSnapshotPath(char** script_name) {
// |dir_prefix| includes the last path seperator.
auto dir_prefix = std::unique_ptr<char, void (*)(void*)>(
EXEUtils::GetDirectoryPrefixFromExeName(), free);
// First assume we're in dart-sdk/bin.
char* snapshot_path =
Utils::SCreate("%s/snapshots/dartdev.dart.snapshot", dir_prefix.get());
if (File::Exists(nullptr, snapshot_path)) {
*script_name = snapshot_path;
return true;
}
free(snapshot_path);
// If we're not in dart-sdk/bin, we might be in one of the $SDK/out/*
// directories. Try to use a snapshot from a previously built SDK.
snapshot_path = Utils::SCreate(
"%s/dart-sdk/bin/snapshots/dartdev.dart.snapshot", dir_prefix.get());
if (File::Exists(nullptr, snapshot_path)) {
*script_name = snapshot_path;
return true;
}
free(snapshot_path);
return false;
}
} // namespace bin
} // namespace dart
<commit_msg>[vm] Fix command line inspection to allow package: scripts<commit_after>// Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "bin/dartdev_utils.h"
#include <memory>
#include "bin/directory.h"
#include "bin/exe_utils.h"
#include "bin/file.h"
#include "platform/utils.h"
namespace dart {
namespace bin {
bool DartDevUtils::ShouldParseCommand(const char* script_uri) {
// If script_uri is not a file path or of a known URI scheme, we can assume
// that this is a DartDev command.
return (!File::ExistsUri(nullptr, script_uri) &&
(strncmp(script_uri, "http://", 7) != 0) &&
(strncmp(script_uri, "https://", 8) != 0) &&
(strncmp(script_uri, "file://", 7) != 0) &&
(strncmp(script_uri, "package:", 8) != 0) &&
(strncmp(script_uri, "google3://", 10) != 0));
}
bool DartDevUtils::TryResolveDartDevSnapshotPath(char** script_name) {
// |dir_prefix| includes the last path seperator.
auto dir_prefix = std::unique_ptr<char, void (*)(void*)>(
EXEUtils::GetDirectoryPrefixFromExeName(), free);
// First assume we're in dart-sdk/bin.
char* snapshot_path =
Utils::SCreate("%s/snapshots/dartdev.dart.snapshot", dir_prefix.get());
if (File::Exists(nullptr, snapshot_path)) {
*script_name = snapshot_path;
return true;
}
free(snapshot_path);
// If we're not in dart-sdk/bin, we might be in one of the $SDK/out/*
// directories. Try to use a snapshot from a previously built SDK.
snapshot_path = Utils::SCreate(
"%s/dart-sdk/bin/snapshots/dartdev.dart.snapshot", dir_prefix.get());
if (File::Exists(nullptr, snapshot_path)) {
*script_name = snapshot_path;
return true;
}
free(snapshot_path);
return false;
}
} // namespace bin
} // namespace dart
<|endoftext|> |
<commit_before>/* Copyright 2019 Benjamin Worpitz, René Widera
*
* This file is part of alpaka.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#pragma once
#ifdef ALPAKA_ACC_ANY_BT_OMP5_ENABLED
#if _OPENMP < 201307
#error If ALPAKA_ACC_ANY_BT_OMP5_ENABLED is set, the compiler has to support OpenMP 4.0 or higher!
#endif
// Specialized traits.
#include <alpaka/acc/Traits.hpp>
#include <alpaka/dev/Traits.hpp>
#include <alpaka/dim/Traits.hpp>
#include <alpaka/pltf/Traits.hpp>
#include <alpaka/idx/Traits.hpp>
// Implementation details.
#include <alpaka/acc/AccOmp5.hpp>
#include <alpaka/core/Decay.hpp>
#include <alpaka/dev/DevOmp5.hpp>
#include <alpaka/idx/MapIdx.hpp>
#include <alpaka/kernel/Traits.hpp>
#include <alpaka/workdiv/WorkDivMembers.hpp>
#include <alpaka/meta/ApplyTuple.hpp>
#include <omp.h>
#include <functional>
#include <stdexcept>
#include <tuple>
#include <type_traits>
#include <algorithm>
#if ALPAKA_DEBUG >= ALPAKA_DEBUG_MINIMAL
#include <iostream>
#endif
namespace alpaka
{
namespace kernel
{
//#############################################################################
//! The OpenMP 5.0 accelerator execution task.
template<
typename TDim,
typename TIdx,
typename TKernelFnObj,
typename... TArgs>
class TaskKernelOmp5 final :
public workdiv::WorkDivMembers<TDim, TIdx>
{
public:
//-----------------------------------------------------------------------------
template<
typename TWorkDiv>
ALPAKA_FN_HOST TaskKernelOmp5(
TWorkDiv && workDiv,
TKernelFnObj const & kernelFnObj,
TArgs && ... args) :
workdiv::WorkDivMembers<TDim, TIdx>(std::forward<TWorkDiv>(workDiv)),
m_kernelFnObj(kernelFnObj),
m_args(std::forward<TArgs>(args)...)
{
static_assert(
dim::Dim<std::decay_t<TWorkDiv>>::value == TDim::value,
"The work division and the execution task have to be of the same dimensionality!");
}
//-----------------------------------------------------------------------------
TaskKernelOmp5(TaskKernelOmp5 const & other) = default;
//-----------------------------------------------------------------------------
TaskKernelOmp5(TaskKernelOmp5 && other) = default;
//-----------------------------------------------------------------------------
auto operator=(TaskKernelOmp5 const &) -> TaskKernelOmp5 & = default;
//-----------------------------------------------------------------------------
auto operator=(TaskKernelOmp5 &&) -> TaskKernelOmp5 & = default;
//-----------------------------------------------------------------------------
~TaskKernelOmp5() = default;
//-----------------------------------------------------------------------------
//! Executes the kernel function object.
ALPAKA_FN_HOST auto operator()(
const
dev::DevOmp5& dev
) const
-> void
{
ALPAKA_DEBUG_MINIMAL_LOG_SCOPE;
auto const gridBlockExtent(
workdiv::getWorkDiv<Grid, Blocks>(*this));
auto const blockThreadExtent(
workdiv::getWorkDiv<Block, Threads>(*this));
auto const threadElemExtent(
workdiv::getWorkDiv<Thread, Elems>(*this));
#if ALPAKA_DEBUG >= ALPAKA_DEBUG_MINIMAL
std::cout << "m_gridBlockExtent=" << this->m_gridBlockExtent << "\tgridBlockExtent=" << gridBlockExtent << std::endl;
std::cout << "m_blockThreadExtent=" << this->m_blockThreadExtent << "\tblockThreadExtent=" << blockThreadExtent << std::endl;
std::cout << "m_threadElemExtent=" << this->m_threadElemExtent << "\tthreadElemExtent=" << threadElemExtent << std::endl;
#endif
// Get the size of the block shared dynamic memory.
auto const blockSharedMemDynSizeBytes(
meta::apply(
[&](ALPAKA_DECAY_T(TArgs) const & ... args)
{
return
kernel::getBlockSharedMemDynSizeBytes<
acc::AccOmp5<TDim, TIdx>>(
m_kernelFnObj,
blockThreadExtent,
threadElemExtent,
args...);
},
m_args));
#if ALPAKA_DEBUG >= ALPAKA_DEBUG_FULL
std::cout << __func__
<< " blockSharedMemDynSizeBytes: " << blockSharedMemDynSizeBytes << " B" << std::endl;
#endif
// We have to make sure, that the OpenMP runtime keeps enough threads for executing a block in parallel.
TIdx const maxOmpThreadCount(static_cast<TIdx>(::omp_get_max_threads()));
// The number of blocks in the grid.
TIdx const gridBlockCount(gridBlockExtent.prod());
// The number of threads in a block.
TIdx const blockThreadCount(blockThreadExtent.prod());
#if ALPAKA_DEBUG >= ALPAKA_DEBUG_MINIMAL
if(maxOmpThreadCount < blockThreadExtent.prod())
std::cout << "Warning: TaskKernelOmp5: maxOmpThreadCount smaller than blockThreadCount requested by caller:" <<
maxOmpThreadCount << " < " << blockThreadExtent.prod() << std::endl;
#endif
// make sure there is at least on team
TIdx const teamCount(std::max(std::min(static_cast<TIdx>(maxOmpThreadCount/blockThreadCount), gridBlockCount), static_cast<TIdx>(1u)));
#if ALPAKA_DEBUG >= ALPAKA_DEBUG_FULL
std::cout << "threadElemCount=" << threadElemExtent[0u] << std::endl;
std::cout << "teamCount=" << teamCount << "\tgridBlockCount=" << gridBlockCount << std::endl;
#endif
if(::omp_in_parallel() != 0)
{
throw std::runtime_error("The OpenMP 5.0 backend can not be used within an existing parallel region!");
}
// Force the environment to use the given number of threads.
int const ompIsDynamic(::omp_get_dynamic());
::omp_set_dynamic(0);
// `When an if(scalar-expression) evaluates to false, the structured block is executed on the host.`
auto argsD = m_args;
auto kernelFnObj = m_kernelFnObj;
const auto iDevice = dev.iDevice();
#pragma omp target device(iDevice)
{
#pragma omp teams num_teams(teamCount) thread_limit(blockThreadCount)
{
#if ALPAKA_DEBUG >= ALPAKA_DEBUG_MINIMAL
// The first team does some checks ...
if((::omp_get_team_num() == 0))
{
int const iNumTeams(::omp_get_num_teams());
printf("%s omp_get_num_teams: %d\n", __func__, iNumTeams);
}
printf("threadElemCount_dev %d\n", int(threadElemExtent[0u]));
#endif
// iterate over groups of teams to stay withing thread limit
for(TIdx t = 0u; t < gridBlockCount; t+=teamCount)
{
acc::AccOmp5<TDim, TIdx> acc(
gridBlockExtent,
blockThreadExtent,
threadElemExtent,
t,
blockSharedMemDynSizeBytes);
// printf("acc->threadElemCount %d\n"
// , int(acc.m_threadElemExtent[0]));
const TIdx bsup = std::min(static_cast<TIdx>(t + teamCount), gridBlockCount);
#pragma omp distribute
for(TIdx b = t; b<bsup; ++b)
{
vec::Vec<dim::DimInt<1u>, TIdx> const gridBlockIdx(b);
// When this is not repeated here:
// error: gridBlockExtent referenced in target region does not have a mappable type
auto const gridBlockExtent2(
workdiv::getWorkDiv<Grid, Blocks>(*static_cast<workdiv::WorkDivMembers<TDim, TIdx> const *>(this)));
acc.m_gridBlockIdx = idx::mapIdx<TDim::value>(
gridBlockIdx,
gridBlockExtent2);
// Execute the threads in parallel.
// Parallel execution of the threads in a block is required because when syncBlockThreads is called all of them have to be done with their work up to this line.
// So we have to spawn one OS thread per thread in a block.
// 'omp for' is not useful because it is meant for cases where multiple iterations are executed by one thread but in our case a 1:1 mapping is required.
// Therefore we use 'omp parallel' with the specified number of threads in a block.
#ifndef __ibmxl_vrm__
// setting num_threads to any value leads XL to run only one thread per team
omp_set_num_threads(static_cast<int>(blockThreadCount));
#endif
#pragma omp parallel
{
#if ALPAKA_DEBUG >= ALPAKA_DEBUG_MINIMAL
// The first thread does some checks in the first block executed.
if((::omp_get_thread_num() == 0) && (b == 0))
{
int const numThreads(::omp_get_num_threads());
printf("%s omp_get_num_threads: %d\n", __func__, numThreads);
if(numThreads != static_cast<int>(blockThreadCount))
{
printf("ERROR: The OpenMP runtime did not use the number of threads that had been requested!\n");
}
}
#endif
meta::apply(
[kernelFnObj, &acc](typename std::decay<TArgs>::type const & ... args)
{
kernelFnObj(
acc,
args...);
},
argsD);
// Wait for all threads to finish before deleting the shared memory.
// This is done by default if the omp 'nowait' clause is missing
//block::sync::syncBlockThreads(acc);
}
// After a block has been processed, the shared memory has to be deleted.
block::shared::st::freeMem(acc);
}
}
}
}
// Reset the dynamic thread number setting.
::omp_set_dynamic(ompIsDynamic);
}
private:
TKernelFnObj m_kernelFnObj;
std::tuple<std::decay_t<TArgs>...> m_args;
};
}
namespace acc
{
namespace traits
{
//#############################################################################
//! The OpenMP 5.0 execution task accelerator type trait specialization.
template<
typename TDim,
typename TIdx,
typename TKernelFnObj,
typename... TArgs>
struct AccType<
kernel::TaskKernelOmp5<TDim, TIdx, TKernelFnObj, TArgs...>>
{
using type = acc::AccOmp5<TDim, TIdx>;
};
}
}
namespace dev
{
namespace traits
{
//#############################################################################
//! The OpenMP 5.0 execution task device type trait specialization.
template<
typename TDim,
typename TIdx,
typename TKernelFnObj,
typename... TArgs>
struct DevType<
kernel::TaskKernelOmp5<TDim, TIdx, TKernelFnObj, TArgs...>>
{
using type = dev::DevOmp5;
};
}
}
namespace dim
{
namespace traits
{
//#############################################################################
//! The OpenMP 5.0 execution task dimension getter trait specialization.
template<
typename TDim,
typename TIdx,
typename TKernelFnObj,
typename... TArgs>
struct DimType<
kernel::TaskKernelOmp5<TDim, TIdx, TKernelFnObj, TArgs...>>
{
using type = TDim;
};
}
}
namespace pltf
{
namespace traits
{
//#############################################################################
//! The OpenMP 5.0 execution task platform type trait specialization.
template<
typename TDim,
typename TIdx,
typename TKernelFnObj,
typename... TArgs>
struct PltfType<
kernel::TaskKernelOmp5<TDim, TIdx, TKernelFnObj, TArgs...>>
{
using type = pltf::PltfOmp5;
};
}
}
namespace idx
{
namespace traits
{
//#############################################################################
//! The OpenMP 5.0 execution task idx type trait specialization.
template<
typename TDim,
typename TIdx,
typename TKernelFnObj,
typename... TArgs>
struct IdxType<
kernel::TaskKernelOmp5<TDim, TIdx, TKernelFnObj, TArgs...>>
{
using type = TIdx;
};
}
}
namespace queue
{
namespace traits
{
template<
typename TDim,
typename TIdx,
typename TKernelFnObj,
typename... TArgs>
struct Enqueue<
queue::QueueOmp5Blocking,
kernel::TaskKernelOmp5<TDim, TIdx, TKernelFnObj, TArgs...> >
{
ALPAKA_FN_HOST static auto enqueue(
queue::QueueOmp5Blocking& queue,
kernel::TaskKernelOmp5<TDim, TIdx, TKernelFnObj, TArgs...> const & task)
-> void
{
std::lock_guard<std::mutex> lk(queue.m_spQueueImpl->m_mutex);
queue.m_spQueueImpl->m_bCurrentlyExecutingTask = true;
task(
queue.m_spQueueImpl->m_dev
);
queue.m_spQueueImpl->m_bCurrentlyExecutingTask = false;
}
};
template<
typename TDim,
typename TIdx,
typename TKernelFnObj,
typename... TArgs>
struct Enqueue<
queue::QueueOmp5NonBlocking,
kernel::TaskKernelOmp5<TDim, TIdx, TKernelFnObj, TArgs...> >
{
//-----------------------------------------------------------------------------
ALPAKA_FN_HOST static auto enqueue(
queue::QueueOmp5NonBlocking& queue,
kernel::TaskKernelOmp5<TDim, TIdx, TKernelFnObj, TArgs...> const & task)
-> void
{
queue.m_spQueueImpl->m_workerThread.enqueueTask(
[&queue, task]()
{
task(
queue.m_spQueueImpl->m_dev
);
});
}
};
}
}
}
#endif
<commit_msg>TaskKernelOmp5: use num_threads clause ...<commit_after>/* Copyright 2019 Benjamin Worpitz, René Widera
*
* This file is part of alpaka.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#pragma once
#ifdef ALPAKA_ACC_ANY_BT_OMP5_ENABLED
#if _OPENMP < 201307
#error If ALPAKA_ACC_ANY_BT_OMP5_ENABLED is set, the compiler has to support OpenMP 4.0 or higher!
#endif
// Specialized traits.
#include <alpaka/acc/Traits.hpp>
#include <alpaka/dev/Traits.hpp>
#include <alpaka/dim/Traits.hpp>
#include <alpaka/pltf/Traits.hpp>
#include <alpaka/idx/Traits.hpp>
// Implementation details.
#include <alpaka/acc/AccOmp5.hpp>
#include <alpaka/core/Decay.hpp>
#include <alpaka/dev/DevOmp5.hpp>
#include <alpaka/idx/MapIdx.hpp>
#include <alpaka/kernel/Traits.hpp>
#include <alpaka/workdiv/WorkDivMembers.hpp>
#include <alpaka/meta/ApplyTuple.hpp>
#include <omp.h>
#include <functional>
#include <stdexcept>
#include <tuple>
#include <type_traits>
#include <algorithm>
#if ALPAKA_DEBUG >= ALPAKA_DEBUG_MINIMAL
#include <iostream>
#endif
namespace alpaka
{
namespace kernel
{
//#############################################################################
//! The OpenMP 5.0 accelerator execution task.
template<
typename TDim,
typename TIdx,
typename TKernelFnObj,
typename... TArgs>
class TaskKernelOmp5 final :
public workdiv::WorkDivMembers<TDim, TIdx>
{
public:
//-----------------------------------------------------------------------------
template<
typename TWorkDiv>
ALPAKA_FN_HOST TaskKernelOmp5(
TWorkDiv && workDiv,
TKernelFnObj const & kernelFnObj,
TArgs && ... args) :
workdiv::WorkDivMembers<TDim, TIdx>(std::forward<TWorkDiv>(workDiv)),
m_kernelFnObj(kernelFnObj),
m_args(std::forward<TArgs>(args)...)
{
static_assert(
dim::Dim<std::decay_t<TWorkDiv>>::value == TDim::value,
"The work division and the execution task have to be of the same dimensionality!");
}
//-----------------------------------------------------------------------------
TaskKernelOmp5(TaskKernelOmp5 const & other) = default;
//-----------------------------------------------------------------------------
TaskKernelOmp5(TaskKernelOmp5 && other) = default;
//-----------------------------------------------------------------------------
auto operator=(TaskKernelOmp5 const &) -> TaskKernelOmp5 & = default;
//-----------------------------------------------------------------------------
auto operator=(TaskKernelOmp5 &&) -> TaskKernelOmp5 & = default;
//-----------------------------------------------------------------------------
~TaskKernelOmp5() = default;
//-----------------------------------------------------------------------------
//! Executes the kernel function object.
ALPAKA_FN_HOST auto operator()(
const
dev::DevOmp5& dev
) const
-> void
{
ALPAKA_DEBUG_MINIMAL_LOG_SCOPE;
auto const gridBlockExtent(
workdiv::getWorkDiv<Grid, Blocks>(*this));
auto const blockThreadExtent(
workdiv::getWorkDiv<Block, Threads>(*this));
auto const threadElemExtent(
workdiv::getWorkDiv<Thread, Elems>(*this));
#if ALPAKA_DEBUG >= ALPAKA_DEBUG_MINIMAL
std::cout << "m_gridBlockExtent=" << this->m_gridBlockExtent << "\tgridBlockExtent=" << gridBlockExtent << std::endl;
std::cout << "m_blockThreadExtent=" << this->m_blockThreadExtent << "\tblockThreadExtent=" << blockThreadExtent << std::endl;
std::cout << "m_threadElemExtent=" << this->m_threadElemExtent << "\tthreadElemExtent=" << threadElemExtent << std::endl;
#endif
// Get the size of the block shared dynamic memory.
auto const blockSharedMemDynSizeBytes(
meta::apply(
[&](ALPAKA_DECAY_T(TArgs) const & ... args)
{
return
kernel::getBlockSharedMemDynSizeBytes<
acc::AccOmp5<TDim, TIdx>>(
m_kernelFnObj,
blockThreadExtent,
threadElemExtent,
args...);
},
m_args));
#if ALPAKA_DEBUG >= ALPAKA_DEBUG_FULL
std::cout << __func__
<< " blockSharedMemDynSizeBytes: " << blockSharedMemDynSizeBytes << " B" << std::endl;
#endif
// We have to make sure, that the OpenMP runtime keeps enough threads for executing a block in parallel.
TIdx const maxOmpThreadCount(static_cast<TIdx>(::omp_get_max_threads()));
// The number of blocks in the grid.
TIdx const gridBlockCount(gridBlockExtent.prod());
// The number of threads in a block.
TIdx const blockThreadCount(blockThreadExtent.prod());
#if ALPAKA_DEBUG >= ALPAKA_DEBUG_MINIMAL
if(maxOmpThreadCount < blockThreadExtent.prod())
std::cout << "Warning: TaskKernelOmp5: maxOmpThreadCount smaller than blockThreadCount requested by caller:" <<
maxOmpThreadCount << " < " << blockThreadExtent.prod() << std::endl;
#endif
// make sure there is at least on team
TIdx const teamCount(std::max(std::min(static_cast<TIdx>(maxOmpThreadCount/blockThreadCount), gridBlockCount), static_cast<TIdx>(1u)));
#if ALPAKA_DEBUG >= ALPAKA_DEBUG_FULL
std::cout << "threadElemCount=" << threadElemExtent[0u] << std::endl;
std::cout << "teamCount=" << teamCount << "\tgridBlockCount=" << gridBlockCount << std::endl;
#endif
if(::omp_in_parallel() != 0)
{
throw std::runtime_error("The OpenMP 5.0 backend can not be used within an existing parallel region!");
}
// Force the environment to use the given number of threads.
int const ompIsDynamic(::omp_get_dynamic());
::omp_set_dynamic(0);
// `When an if(scalar-expression) evaluates to false, the structured block is executed on the host.`
auto argsD = m_args;
auto kernelFnObj = m_kernelFnObj;
const auto iDevice = dev.iDevice();
#pragma omp target device(iDevice)
{
#pragma omp teams num_teams(teamCount) //thread_limit(blockThreadCount)
{
#if ALPAKA_DEBUG >= ALPAKA_DEBUG_MINIMAL
// The first team does some checks ...
if((::omp_get_team_num() == 0))
{
int const iNumTeams(::omp_get_num_teams());
printf("%s omp_get_num_teams: %d\n", __func__, iNumTeams);
}
printf("threadElemCount_dev %d\n", int(threadElemExtent[0u]));
#endif
// iterate over groups of teams to stay withing thread limit
for(TIdx t = 0u; t < gridBlockCount; t+=teamCount)
{
acc::AccOmp5<TDim, TIdx> acc(
gridBlockExtent,
blockThreadExtent,
threadElemExtent,
t,
blockSharedMemDynSizeBytes);
// printf("acc->threadElemCount %d\n"
// , int(acc.m_threadElemExtent[0]));
const TIdx bsup = std::min(static_cast<TIdx>(t + teamCount), gridBlockCount);
#pragma omp distribute
for(TIdx b = t; b<bsup; ++b)
{
vec::Vec<dim::DimInt<1u>, TIdx> const gridBlockIdx(b);
// When this is not repeated here:
// error: gridBlockExtent referenced in target region does not have a mappable type
auto const gridBlockExtent2(
workdiv::getWorkDiv<Grid, Blocks>(*static_cast<workdiv::WorkDivMembers<TDim, TIdx> const *>(this)));
acc.m_gridBlockIdx = idx::mapIdx<TDim::value>(
gridBlockIdx,
gridBlockExtent2);
// Execute the threads in parallel.
// Parallel execution of the threads in a block is required because when syncBlockThreads is called all of them have to be done with their work up to this line.
// So we have to spawn one OS thread per thread in a block.
// 'omp for' is not useful because it is meant for cases where multiple iterations are executed by one thread but in our case a 1:1 mapping is required.
// Therefore we use 'omp parallel' with the specified number of threads in a block.
#ifndef __ibmxl_vrm__
// setting num_threads to any value leads XL to run only one thread per team
#pragma omp parallel num_threads(blockThreadCount)
#else
#pragma omp parallel
#endif
{
#if ALPAKA_DEBUG >= ALPAKA_DEBUG_MINIMAL
// The first thread does some checks in the first block executed.
if((::omp_get_thread_num() == 0) && (b == 0))
{
int const numThreads(::omp_get_num_threads());
printf("%s omp_get_num_threads: %d\n", __func__, numThreads);
if(numThreads != static_cast<int>(blockThreadCount))
{
printf("ERROR: The OpenMP runtime did not use the number of threads that had been requested!\n");
}
}
#endif
meta::apply(
[kernelFnObj, &acc](typename std::decay<TArgs>::type const & ... args)
{
kernelFnObj(
acc,
args...);
},
argsD);
// Wait for all threads to finish before deleting the shared memory.
// This is done by default if the omp 'nowait' clause is missing
//block::sync::syncBlockThreads(acc);
}
// After a block has been processed, the shared memory has to be deleted.
block::shared::st::freeMem(acc);
}
}
}
}
// Reset the dynamic thread number setting.
::omp_set_dynamic(ompIsDynamic);
}
private:
TKernelFnObj m_kernelFnObj;
std::tuple<std::decay_t<TArgs>...> m_args;
};
}
namespace acc
{
namespace traits
{
//#############################################################################
//! The OpenMP 5.0 execution task accelerator type trait specialization.
template<
typename TDim,
typename TIdx,
typename TKernelFnObj,
typename... TArgs>
struct AccType<
kernel::TaskKernelOmp5<TDim, TIdx, TKernelFnObj, TArgs...>>
{
using type = acc::AccOmp5<TDim, TIdx>;
};
}
}
namespace dev
{
namespace traits
{
//#############################################################################
//! The OpenMP 5.0 execution task device type trait specialization.
template<
typename TDim,
typename TIdx,
typename TKernelFnObj,
typename... TArgs>
struct DevType<
kernel::TaskKernelOmp5<TDim, TIdx, TKernelFnObj, TArgs...>>
{
using type = dev::DevOmp5;
};
}
}
namespace dim
{
namespace traits
{
//#############################################################################
//! The OpenMP 5.0 execution task dimension getter trait specialization.
template<
typename TDim,
typename TIdx,
typename TKernelFnObj,
typename... TArgs>
struct DimType<
kernel::TaskKernelOmp5<TDim, TIdx, TKernelFnObj, TArgs...>>
{
using type = TDim;
};
}
}
namespace pltf
{
namespace traits
{
//#############################################################################
//! The OpenMP 5.0 execution task platform type trait specialization.
template<
typename TDim,
typename TIdx,
typename TKernelFnObj,
typename... TArgs>
struct PltfType<
kernel::TaskKernelOmp5<TDim, TIdx, TKernelFnObj, TArgs...>>
{
using type = pltf::PltfOmp5;
};
}
}
namespace idx
{
namespace traits
{
//#############################################################################
//! The OpenMP 5.0 execution task idx type trait specialization.
template<
typename TDim,
typename TIdx,
typename TKernelFnObj,
typename... TArgs>
struct IdxType<
kernel::TaskKernelOmp5<TDim, TIdx, TKernelFnObj, TArgs...>>
{
using type = TIdx;
};
}
}
namespace queue
{
namespace traits
{
template<
typename TDim,
typename TIdx,
typename TKernelFnObj,
typename... TArgs>
struct Enqueue<
queue::QueueOmp5Blocking,
kernel::TaskKernelOmp5<TDim, TIdx, TKernelFnObj, TArgs...> >
{
ALPAKA_FN_HOST static auto enqueue(
queue::QueueOmp5Blocking& queue,
kernel::TaskKernelOmp5<TDim, TIdx, TKernelFnObj, TArgs...> const & task)
-> void
{
std::lock_guard<std::mutex> lk(queue.m_spQueueImpl->m_mutex);
queue.m_spQueueImpl->m_bCurrentlyExecutingTask = true;
task(
queue.m_spQueueImpl->m_dev
);
queue.m_spQueueImpl->m_bCurrentlyExecutingTask = false;
}
};
template<
typename TDim,
typename TIdx,
typename TKernelFnObj,
typename... TArgs>
struct Enqueue<
queue::QueueOmp5NonBlocking,
kernel::TaskKernelOmp5<TDim, TIdx, TKernelFnObj, TArgs...> >
{
//-----------------------------------------------------------------------------
ALPAKA_FN_HOST static auto enqueue(
queue::QueueOmp5NonBlocking& queue,
kernel::TaskKernelOmp5<TDim, TIdx, TKernelFnObj, TArgs...> const & task)
-> void
{
queue.m_spQueueImpl->m_workerThread.enqueueTask(
[&queue, task]()
{
task(
queue.m_spQueueImpl->m_dev
);
});
}
};
}
}
}
#endif
<|endoftext|> |
<commit_before>/*******************************************************************************
* include/construction/building_blocks.hpp
*
* Copyright (C) 2018 Marvin Löbel <[email protected]>
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
#pragma once
template <typename level_bv_t, typename loop_body_t>
inline void write_bits_wordwise(uint64_t start,
uint64_t size,
level_bv_t const& level_bv,
loop_body_t body) {
uint64_t cur_pos = start;
for (; cur_pos + 64 <= size; cur_pos += 64) {
uint64_t word = 0ULL;
for (uint64_t i = 0; i < 64; ++i) {
uint64_t const bit = body(cur_pos + i);
word <<= 1;
word |= bit;
}
level_bv[cur_pos >> 6] = word;
}
if (size & 63ULL) {
uint64_t word = 0ULL;
for (uint64_t i = cur_pos; i < size; ++i) {
uint64_t const bit = body(i);
word <<= 1;
word |= bit;
}
word <<= (64 - (size & 63ULL));
level_bv[size >> 6] = word;
}
}
template <typename text_t, typename ctx_t, typename bv_t>
inline void
scan_text_compute_first_level_bv_and_last_level_hist(text_t const& text,
size_t const size,
uint64_t const levels,
bv_t& bv,
ctx_t& ctx) {
auto&& hist = ctx.hist_at_level(levels);
write_bits_wordwise(0, size, bv[0], [&](uint64_t i) {
++hist[text[i]];
uint64_t const bit = ((text[i] >> (levels - 1)) & 1ULL);
return bit;
});
}
template <typename ctx_t>
inline void bottom_up_compute_hist_and_borders_and_optional_zeros(
uint64_t const size, uint64_t const levels, ctx_t& ctx) {
for (uint64_t level = levels - 1; level > 0; --level) {
auto&& hist = ctx.hist_at_level(level);
auto&& next_hist = ctx.hist_at_level(level + 1);
auto&& borders = ctx.borders_at_level(level);
for (uint64_t pos = 0; pos < ctx.hist_size(level); ++pos) {
hist[pos] = next_hist[pos << 1] + next_hist[(pos << 1) + 1];
}
borders[0] = 0;
for (uint64_t pos = 1; pos < ctx.hist_size(level); ++pos) {
auto const prev_rho = ctx.rho(level, pos - 1);
borders[ctx.rho(level, pos)] = borders[prev_rho] + hist[prev_rho];
}
// The number of 0s is the position of the first 1 in the previous level
if constexpr (ctx_t::compute_zeros) {
ctx.zeros()[level - 1] = borders[1];
}
}
ctx.hist_at_level(0)[0] = size;
}
template <typename ctx_t>
inline void compute_borders_and_optional_zeros_and_optional_rho(uint64_t level,
uint64_t blocks,
ctx_t& ctx) {
auto&& borders = ctx.borders_at_level(level);
auto&& hist = ctx.hist_at_level(level);
// Compute the starting positions of characters with respect to their
// bit prefixes and the bit-reversal permutation
borders[0] = 0;
for (uint64_t i = 1; i < blocks; ++i) {
auto const prev_block = ctx.rho(level, i - 1);
auto const this_block = ctx.rho(level, i);
borders[this_block] = borders[prev_block] + hist[prev_block];
// NB: The above calulcation produces _wrong_ border offsets
// for huffman codes that are one-shorter than the current level.
//
// Since those codes will not be used in the loop below, this does not
// produce wrong or out-of-bound accesses.
if (ctx_t::compute_rho) {
ctx.set_rho(level - 1, i - 1, prev_block >> 1);
}
}
if (ctx_t::compute_zeros) {
// If we compute zeros, we are working on a WM instead of a WT.
// For a WM, borders is permuted with rho such that
// borders[1] contains the position of the first 1-bit block.
ctx.zeros()[level - 1] = borders[1];
}
}
<commit_msg>optimize write_bits_wordwise<commit_after>/*******************************************************************************
* include/construction/building_blocks.hpp
*
* Copyright (C) 2018 Marvin Löbel <[email protected]>
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
#pragma once
#include <omp.h>
#include "arrays/span.hpp"
// NB: This formulation as an inline-always function
// has been roghly tested to produce the least amount of machine code if
// used from `write_bits_wordwise()`.
template <typename level_bv_t, typename loop_body_t>
inline __attribute__((always_inline)) void
write_bits_word(uint64_t const start,
uint64_t const size,
level_bv_t const& level_bv,
loop_body_t body) {
DCHECK(size <= 64);
uint64_t word = 0ULL;
for (uint64_t i = 0; i < size; ++i) {
uint64_t const bit = body(start + i);
word <<= 1;
word |= bit;
}
// NB. This gets optimized out if size is a constant 64
word <<= (64 - size);
level_bv[start >> 6] = word;
}
template <typename level_bv_t, typename loop_body_t>
inline void write_bits_wordwise(uint64_t start,
uint64_t size,
level_bv_t const& level_bv,
loop_body_t body) {
for (uint64_t cur_pos = start; cur_pos + 64 <= size; cur_pos += 64) {
write_bits_word(cur_pos, 64, level_bv, body);
}
uint64_t const remainder = size & 63ULL;
if (remainder) {
write_bits_word(size - remainder, remainder, level_bv, body);
}
}
template <typename level_bv_t, typename loop_body_t>
inline void omp_write_bits_wordwise(uint64_t start,
uint64_t size,
level_bv_t const& level_bv,
loop_body_t body) {
const auto omp_rank = omp_get_thread_num();
const auto omp_size = omp_get_num_threads();
#pragma omp for
for (int64_t scur_pos = start; scur_pos <= (int64_t(size) - 64);
scur_pos += 64) {
DCHECK(scur_pos >= 0);
write_bits_word(scur_pos, 64, level_bv, body);
}
uint64_t const remainder = size & 63ULL;
if (remainder && ((omp_rank + 1) == omp_size)) {
write_bits_word(size - remainder, remainder, level_bv, body);
}
}
template <typename text_t, typename ctx_t, typename bv_t>
inline void
scan_text_compute_first_level_bv_and_last_level_hist(text_t const& text,
size_t const size,
uint64_t const levels,
bv_t& bv,
ctx_t& ctx) {
auto&& hist = ctx.hist_at_level(levels);
write_bits_wordwise(0, size, bv[0], [&](uint64_t i) {
++hist[text[i]];
uint64_t const bit = ((text[i] >> (levels - 1)) & 1ULL);
return bit;
});
}
template <typename ctx_t>
inline void bottom_up_compute_hist_and_borders_and_optional_zeros(
uint64_t const size, uint64_t const levels, ctx_t& ctx) {
for (uint64_t level = levels - 1; level > 0; --level) {
auto&& hist = ctx.hist_at_level(level);
auto&& next_hist = ctx.hist_at_level(level + 1);
auto&& borders = ctx.borders_at_level(level);
for (uint64_t pos = 0; pos < ctx.hist_size(level); ++pos) {
hist[pos] = next_hist[pos << 1] + next_hist[(pos << 1) + 1];
}
borders[0] = 0;
for (uint64_t pos = 1; pos < ctx.hist_size(level); ++pos) {
auto const prev_rho = ctx.rho(level, pos - 1);
borders[ctx.rho(level, pos)] = borders[prev_rho] + hist[prev_rho];
}
// The number of 0s is the position of the first 1 in the previous level
if constexpr (ctx_t::compute_zeros) {
ctx.zeros()[level - 1] = borders[1];
}
}
ctx.hist_at_level(0)[0] = size;
}
template <typename ctx_t>
inline void compute_borders_and_optional_zeros_and_optional_rho(uint64_t level,
uint64_t blocks,
ctx_t& ctx) {
auto&& borders = ctx.borders_at_level(level);
auto&& hist = ctx.hist_at_level(level);
// Compute the starting positions of characters with respect to their
// bit prefixes and the bit-reversal permutation
borders[0] = 0;
for (uint64_t i = 1; i < blocks; ++i) {
auto const prev_block = ctx.rho(level, i - 1);
auto const this_block = ctx.rho(level, i);
borders[this_block] = borders[prev_block] + hist[prev_block];
// NB: The above calulcation produces _wrong_ border offsets
// for huffman codes that are one-shorter than the current level.
//
// Since those codes will not be used in the loop below, this does not
// produce wrong or out-of-bound accesses.
if (ctx_t::compute_rho) {
ctx.set_rho(level - 1, i - 1, prev_block >> 1);
}
}
if (ctx_t::compute_zeros) {
// If we compute zeros, we are working on a WM instead of a WT.
// For a WM, borders is permuted with rho such that
// borders[1] contains the position of the first 1-bit block.
ctx.zeros()[level - 1] = borders[1];
}
}
<|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) 2015 Francois Beaune, The appleseedhq Organization
//
// 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 "orthographiccamera.h"
// appleseed.renderer headers.
#include "renderer/global/globallogger.h"
#include "renderer/global/globaltypes.h"
#include "renderer/kernel/shading/shadingray.h"
#include "renderer/modeling/camera/camera.h"
#include "renderer/modeling/frame/frame.h"
#include "renderer/modeling/project/project.h"
#include "renderer/utility/transformsequence.h"
// appleseed.foundation headers.
#include "foundation/image/canvasproperties.h"
#include "foundation/image/image.h"
#include "foundation/math/intersection/planesegment.h"
#include "foundation/math/dual.h"
#include "foundation/math/matrix.h"
#include "foundation/math/transform.h"
#include "foundation/math/vector.h"
#include "foundation/platform/compiler.h"
#include "foundation/utility/containers/specializedarrays.h"
#include "foundation/utility/autoreleaseptr.h"
// Standard headers.
#include <cstddef>
// Forward declarations.
namespace foundation { class IAbortSwitch; }
using namespace foundation;
using namespace std;
namespace renderer
{
namespace
{
//
// Orthographic camera.
//
const char* Model = "orthographic_camera";
class OrthographicCamera
: public Camera
{
public:
OrthographicCamera(
const char* name,
const ParamArray& params)
: Camera(name, params)
{
}
virtual void release() APPLESEED_OVERRIDE
{
delete this;
}
virtual const char* get_model() const APPLESEED_OVERRIDE
{
return Model;
}
virtual bool on_frame_begin(
const Project& project,
IAbortSwitch* abort_switch) APPLESEED_OVERRIDE
{
if (!Camera::on_frame_begin(project, abort_switch))
return false;
// Extract the film dimensions from the camera parameters.
m_film_dimensions = extract_film_dimensions();
// Extract the abscissa of the near plane from the camera parameters.
m_near_z = extract_near_z();
// Precompute reciprocals of film dimensions.
m_rcp_film_width = 1.0 / m_film_dimensions[0];
m_rcp_film_height = 1.0 / m_film_dimensions[1];
// Precompute pixel area.
const size_t pixel_count = project.get_frame()->image().properties().m_pixel_count;
m_rcp_pixel_area = pixel_count / (m_film_dimensions[0] * m_film_dimensions[1]);
print_settings();
return true;
}
virtual void spawn_ray(
SamplingContext& sampling_context,
const Dual2d& ndc,
ShadingRay& ray) const APPLESEED_OVERRIDE
{
// Initialize the ray.
initialize_ray(sampling_context, ray);
// Retrieve the camera transform.
Transformd tmp;
const Transformd& transform =
m_transform_sequence.evaluate(ray.m_time.m_absolute, tmp);
// Compute ray origin and direction.
ray.m_org = transform.point_to_parent(ndc_to_camera(ndc.get_value()));
ray.m_dir = normalize(transform.vector_to_parent(Vector3d(0.0, 0.0, -1.0)));
// Compute ray derivatives.
if (ndc.has_derivatives())
{
const Vector2d px(ndc.get_value() + ndc.get_dx());
const Vector2d py(ndc.get_value() + ndc.get_dy());
ray.m_rx.m_org = transform.point_to_parent(ndc_to_camera(px));
ray.m_ry.m_org = transform.point_to_parent(ndc_to_camera(py));
ray.m_rx.m_dir = ray.m_dir;
ray.m_ry.m_dir = ray.m_dir;
ray.m_has_differentials = true;
}
}
virtual bool connect_vertex(
SamplingContext& sampling_context,
const double time,
const Vector3d& point,
Vector2d& ndc,
Vector3d& outgoing,
double& importance) const APPLESEED_OVERRIDE
{
// Retrieve the camera transform.
Transformd tmp;
const Transformd& transform = m_transform_sequence.evaluate(time, tmp);
// Transform the input point to camera space.
const Vector3d p = transform.point_to_local(point);
// Compute the normalized device coordinates of the film point.
ndc[0] = 0.5 + p[0];
ndc[1] = 0.5 - p[1];
// The connection is impossible if the projected point lies outside the film.
if (ndc[0] < 0.0 || ndc[0] >= 1.0 ||
ndc[1] < 0.0 || ndc[1] >= 1.0)
return false;
// Compute the outgoing direction vector in world space.
outgoing = transform.vector_to_parent(Vector3d(0.0, 0.0, p.z));
// Compute the emitted importance.
importance = m_rcp_pixel_area;
// The connection was possible.
return true;
}
virtual bool project_camera_space_point(
const Vector3d& point,
Vector2d& ndc) const APPLESEED_OVERRIDE
{
// Cannot project the point if it is behind the near plane.
if (point.z > m_near_z)
return false;
// Project the point onto the film plane.
ndc = camera_to_ndc(point);
// Projection was successful.
return true;
}
virtual bool project_segment(
const double time,
const Vector3d& a,
const Vector3d& b,
Vector2d& a_ndc,
Vector2d& b_ndc) const APPLESEED_OVERRIDE
{
// Retrieve the camera transform.
Transformd tmp;
const Transformd& transform = m_transform_sequence.evaluate(time, tmp);
// Transform the segment to camera space.
Vector3d local_a = transform.point_to_local(a);
Vector3d local_b = transform.point_to_local(b);
// Clip the segment against the near plane.
if (!clip(Vector4d(0.0, 0.0, 1.0, -m_near_z), local_a, local_b))
return false;
// Project the segment onto the film plane.
a_ndc = camera_to_ndc(local_a);
b_ndc = camera_to_ndc(local_b);
// Projection was successful.
return true;
}
private:
// Parameters.
Vector2d m_film_dimensions; // film dimensions in camera space, in meters
double m_near_z; // Z value of the near plane in camera space, in meters
// Precomputed values.
double m_rcp_film_width; // film width reciprocal in camera space
double m_rcp_film_height; // film height reciprocal in camera space
double m_rcp_pixel_area; // reciprocal of pixel area in camera space
void print_settings() const
{
RENDERER_LOG_INFO(
"camera settings:\n"
" model %s\n"
" film width %f\n"
" film height %f\n"
" near z %f\n"
" shutter open %f\n"
" shutter close %f",
Model,
m_film_dimensions[0],
m_film_dimensions[1],
m_near_z,
m_shutter_open_time,
m_shutter_close_time);
}
Vector3d ndc_to_camera(const Vector2d& point) const
{
return
Vector3d(
(point.x - 0.5) * m_film_dimensions[0],
(0.5 - point.y) * m_film_dimensions[1],
0.0);
}
Vector2d camera_to_ndc(const Vector3d& point) const
{
return
Vector2d(
0.5 + point.x * m_rcp_film_width,
0.5 - point.y * m_rcp_film_height);
}
};
}
//
// OrthographicCameraFactory class implementation.
//
const char* OrthographicCameraFactory::get_model() const
{
return Model;
}
Dictionary OrthographicCameraFactory::get_model_metadata() const
{
return
Dictionary()
.insert("name", Model)
.insert("label", "Orthographic Camera");
}
DictionaryArray OrthographicCameraFactory::get_input_metadata() const
{
DictionaryArray metadata = CameraFactory::get_input_metadata();
metadata.push_back(
Dictionary()
.insert("name", "film_dimensions")
.insert("label", "Film Dimensions")
.insert("type", "text")
.insert("use", "required"));
metadata.push_back(
Dictionary()
.insert("name", "film_width")
.insert("label", "Film Width")
.insert("type", "text")
.insert("use", "required"));
metadata.push_back(
Dictionary()
.insert("name", "film_height")
.insert("label", "Film Height")
.insert("type", "text")
.insert("use", "required"));
metadata.push_back(
Dictionary()
.insert("name", "aspect_ratio")
.insert("label", "Aspect Ratio")
.insert("type", "text")
.insert("use", "required"));
metadata.push_back(
Dictionary()
.insert("name", "near_z")
.insert("label", "Near Z")
.insert("type", "text")
.insert("use", "optional")
.insert("default", "-0.001"));
return metadata;
}
auto_release_ptr<Camera> OrthographicCameraFactory::create(
const char* name,
const ParamArray& params) const
{
return auto_release_ptr<Camera>(new OrthographicCamera(name, params));
}
} // namespace renderer
<commit_msg>Fix orthographic camera position<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) 2015 Francois Beaune, The appleseedhq Organization
//
// 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 "orthographiccamera.h"
// appleseed.renderer headers.
#include "renderer/global/globallogger.h"
#include "renderer/global/globaltypes.h"
#include "renderer/kernel/shading/shadingray.h"
#include "renderer/modeling/camera/camera.h"
#include "renderer/modeling/frame/frame.h"
#include "renderer/modeling/project/project.h"
#include "renderer/modeling/scene/scene.h"
#include "renderer/utility/transformsequence.h"
// appleseed.foundation headers.
#include "foundation/image/canvasproperties.h"
#include "foundation/image/image.h"
#include "foundation/math/intersection/planesegment.h"
#include "foundation/math/dual.h"
#include "foundation/math/matrix.h"
#include "foundation/math/transform.h"
#include "foundation/math/vector.h"
#include "foundation/platform/compiler.h"
#include "foundation/utility/containers/specializedarrays.h"
#include "foundation/utility/autoreleaseptr.h"
// Standard headers.
#include <cstddef>
// Forward declarations.
namespace foundation { class IAbortSwitch; }
using namespace foundation;
using namespace std;
namespace renderer
{
namespace
{
//
// Orthographic camera.
//
const char* Model = "orthographic_camera";
class OrthographicCamera
: public Camera
{
public:
OrthographicCamera(
const char* name,
const ParamArray& params)
: Camera(name, params)
{
}
virtual void release() APPLESEED_OVERRIDE
{
delete this;
}
virtual const char* get_model() const APPLESEED_OVERRIDE
{
return Model;
}
virtual bool on_frame_begin(
const Project& project,
IAbortSwitch* abort_switch) APPLESEED_OVERRIDE
{
if (!Camera::on_frame_begin(project, abort_switch))
return false;
// Extract the film dimensions from the camera parameters.
m_film_dimensions = extract_film_dimensions();
// Extract the abscissa of the near plane from the camera parameters.
m_near_z = extract_near_z();
// Retrieve the scene diameter that will be used to position the camera.
const Scene::CachedInfo* scene_info = project.get_scene()->get_cached_info();
assert(scene_info);
m_safe_scene_diameter = scene_info->m_safe_diameter;
// Precompute reciprocals of film dimensions.
m_rcp_film_width = 1.0 / m_film_dimensions[0];
m_rcp_film_height = 1.0 / m_film_dimensions[1];
// Precompute pixel area.
const size_t pixel_count = project.get_frame()->image().properties().m_pixel_count;
m_rcp_pixel_area = pixel_count / (m_film_dimensions[0] * m_film_dimensions[1]);
print_settings();
return true;
}
virtual void spawn_ray(
SamplingContext& sampling_context,
const Dual2d& ndc,
ShadingRay& ray) const APPLESEED_OVERRIDE
{
// Initialize the ray.
initialize_ray(sampling_context, ray);
// Retrieve the camera transform.
Transformd tmp;
const Transformd& transform =
m_transform_sequence.evaluate(ray.m_time.m_absolute, tmp);
// Compute ray origin and direction.
ray.m_org = transform.point_to_parent(ndc_to_camera(ndc.get_value()));
ray.m_dir = normalize(transform.vector_to_parent(Vector3d(0.0, 0.0, -1.0)));
// Compute ray derivatives.
if (ndc.has_derivatives())
{
const Vector2d px(ndc.get_value() + ndc.get_dx());
const Vector2d py(ndc.get_value() + ndc.get_dy());
ray.m_rx.m_org = transform.point_to_parent(ndc_to_camera(px));
ray.m_ry.m_org = transform.point_to_parent(ndc_to_camera(py));
ray.m_rx.m_dir = ray.m_dir;
ray.m_ry.m_dir = ray.m_dir;
ray.m_has_differentials = true;
}
}
virtual bool connect_vertex(
SamplingContext& sampling_context,
const double time,
const Vector3d& point,
Vector2d& ndc,
Vector3d& outgoing,
double& importance) const APPLESEED_OVERRIDE
{
// Retrieve the camera transform.
Transformd tmp;
const Transformd& transform = m_transform_sequence.evaluate(time, tmp);
// Transform the input point to camera space.
const Vector3d p = transform.point_to_local(point);
// Compute the normalized device coordinates of the film point.
ndc[0] = 0.5 + p[0];
ndc[1] = 0.5 - p[1];
// The connection is impossible if the projected point lies outside the film.
if (ndc[0] < 0.0 || ndc[0] >= 1.0 ||
ndc[1] < 0.0 || ndc[1] >= 1.0)
return false;
// Compute the outgoing direction vector in world space.
outgoing = transform.vector_to_parent(Vector3d(0.0, 0.0, p.z));
// Compute the emitted importance.
importance = m_rcp_pixel_area;
// The connection was possible.
return true;
}
virtual bool project_camera_space_point(
const Vector3d& point,
Vector2d& ndc) const APPLESEED_OVERRIDE
{
// Cannot project the point if it is behind the near plane.
if (point.z > m_near_z)
return false;
// Project the point onto the film plane.
ndc = camera_to_ndc(point);
// Projection was successful.
return true;
}
virtual bool project_segment(
const double time,
const Vector3d& a,
const Vector3d& b,
Vector2d& a_ndc,
Vector2d& b_ndc) const APPLESEED_OVERRIDE
{
// Retrieve the camera transform.
Transformd tmp;
const Transformd& transform = m_transform_sequence.evaluate(time, tmp);
// Transform the segment to camera space.
Vector3d local_a = transform.point_to_local(a);
Vector3d local_b = transform.point_to_local(b);
// Clip the segment against the near plane.
if (!clip(Vector4d(0.0, 0.0, 1.0, -m_near_z), local_a, local_b))
return false;
// Project the segment onto the film plane.
a_ndc = camera_to_ndc(local_a);
b_ndc = camera_to_ndc(local_b);
// Projection was successful.
return true;
}
private:
// Parameters.
Vector2d m_film_dimensions; // film dimensions in camera space, in meters
double m_near_z; // Z value of the near plane in camera space, in meters
// Precomputed values.
double m_safe_scene_diameter; // scene diameter plus a safety margin
double m_rcp_film_width; // film width reciprocal in camera space
double m_rcp_film_height; // film height reciprocal in camera space
double m_rcp_pixel_area; // reciprocal of pixel area in camera space
void print_settings() const
{
RENDERER_LOG_INFO(
"camera settings:\n"
" model %s\n"
" film width %f\n"
" film height %f\n"
" near z %f\n"
" shutter open %f\n"
" shutter close %f",
Model,
m_film_dimensions[0],
m_film_dimensions[1],
m_near_z,
m_shutter_open_time,
m_shutter_close_time);
}
Vector3d ndc_to_camera(const Vector2d& point) const
{
return
Vector3d(
(point.x - 0.5) * m_film_dimensions[0],
(0.5 - point.y) * m_film_dimensions[1],
m_safe_scene_diameter);
}
Vector2d camera_to_ndc(const Vector3d& point) const
{
return
Vector2d(
0.5 + point.x * m_rcp_film_width,
0.5 - point.y * m_rcp_film_height);
}
};
}
//
// OrthographicCameraFactory class implementation.
//
const char* OrthographicCameraFactory::get_model() const
{
return Model;
}
Dictionary OrthographicCameraFactory::get_model_metadata() const
{
return
Dictionary()
.insert("name", Model)
.insert("label", "Orthographic Camera");
}
DictionaryArray OrthographicCameraFactory::get_input_metadata() const
{
DictionaryArray metadata = CameraFactory::get_input_metadata();
metadata.push_back(
Dictionary()
.insert("name", "film_dimensions")
.insert("label", "Film Dimensions")
.insert("type", "text")
.insert("use", "required"));
metadata.push_back(
Dictionary()
.insert("name", "film_width")
.insert("label", "Film Width")
.insert("type", "text")
.insert("use", "required"));
metadata.push_back(
Dictionary()
.insert("name", "film_height")
.insert("label", "Film Height")
.insert("type", "text")
.insert("use", "required"));
metadata.push_back(
Dictionary()
.insert("name", "aspect_ratio")
.insert("label", "Aspect Ratio")
.insert("type", "text")
.insert("use", "required"));
metadata.push_back(
Dictionary()
.insert("name", "near_z")
.insert("label", "Near Z")
.insert("type", "text")
.insert("use", "optional")
.insert("default", "-0.001"));
return metadata;
}
auto_release_ptr<Camera> OrthographicCameraFactory::create(
const char* name,
const ParamArray& params) const
{
return auto_release_ptr<Camera>(new OrthographicCamera(name, params));
}
} // namespace renderer
<|endoftext|> |
<commit_before>//最长公共子序列
//longest_common_subsequence.cpp
//求两长度相同的序列s1,s2的最长公共子序列的长度
//子序列中相邻的两个成员在原序列中可以是不相邻的,但在原序列中的相对顺序不变
//子序列中相邻的两个成员在原序列中可以是不相邻的,但在原序列中的相对顺序不变
//这意味着可以出现这样的情况,对于序列s1(1, 2, 3, 4, 5)和s2(1, 4, 0, 2, 3)
//它们的最长公共子序列是(1, 4),其中成员1和4在原序列s1中不相邻,但相对顺序不变
//
//设置f[i][j]表示s1中前i个元素,s2中前j个元素的最长公共子列长度
//本章中的所有动态规划在解题时都会使用f数组来存储决策结果
//状态转移方程:
//f[i][j] = | 0 i == 0 || j == 0
// | f[i - 1][j - 1] + 1 i > 0 && j > 0 && s1[i] == s2[j]
// | max(f[i][j - 1], f[i - 1][j]) i > 0 && j > 0 && s1[i] != s2[j]
//初始条件:f[i][0]和f[0][i]为0,0 <= i <= n
//
//本章中使用数组的方式与其他章节不太一样
//一般情况下我会将一个数组长度设为n,其中成员设为从0到n-1
//但在本章的所有算法中,数组的长度都被设置为n+1,成员都是从1到n,而把0空出来
//这是为了给状态转移方程中的初始状态留出一个位置,请留意这个细节
//本章的所有算法都会这样处理数组,以后不再特别说明
#include "general_head.h"
int longest_common_subsequence(int *s1, int *s2, int n)
{//序列s1,s2的长度都为n+1,下标从1到n,空出0位置
//返回s1,s2的最长公共子序列的长度
int f[MAX + 1][MAX + 1];
for(int i = 0; i <= n; ++ i)
f[0][i] = 0, f[i][0] = 0;
for(int i = 1; i <= n; ++ i)
for(int j = 1; j <= n; ++ j){
if(s1[i] == s2[j])
f[i][j] = f[i - 1][j - 1] + 1;
else
f[i][j] = max(f[i][j - 1], f[i - 1][j]);
}
return(f[n][n]);
}
<commit_msg>Update 1_longest_common_subsequence.cpp<commit_after>//最长公共子序列
//longest_common_subsequence.cpp
//求两长度相同的序列s1,s2的最长公共子序列的长度
//子序列中相邻的两个成员在原序列中可以是不相邻的,但在原序列中的相对顺序不变
//子序列中相邻的两个成员在原序列中可以是不相邻的,但在原序列中的相对顺序不变
//这意味着可以出现这样的情况,对于序列s1(1, 2, 3, 4, 5)和s2(1, 4, 0, 7, 8)
//它们的最长公共子序列是(1, 4),其中成员1和4在原序列s1中不相邻,但相对顺序不变
//
//设置f[i][j]表示s1中前i个元素,s2中前j个元素的最长公共子列长度
//本章中的所有动态规划在解题时都会使用f数组来存储决策结果
//状态转移方程:
//f[i][j] = | 0 i == 0 || j == 0
// | f[i - 1][j - 1] + 1 i > 0 && j > 0 && s1[i] == s2[j]
// | max(f[i][j - 1], f[i - 1][j]) i > 0 && j > 0 && s1[i] != s2[j]
//初始条件:f[i][0]和f[0][i]为0,0 <= i <= n
//
//本章中使用数组的方式与其他章节不太一样
//一般情况下我会将一个数组长度设为n,其中成员设为从0到n-1
//但在本章的所有算法中,数组的长度都被设置为n+1,成员都是从1到n,而把0空出来
//这是为了给状态转移方程中的初始状态留出一个位置,请留意这个细节
//本章的所有算法都会这样处理数组,以后不再特别说明
#include "general_head.h"
int longest_common_subsequence(int *s1, int *s2, int n)
{//序列s1,s2的长度都为n+1,下标从1到n,空出0位置
//返回s1,s2的最长公共子序列的长度
int f[MAX + 1][MAX + 1];
for(int i = 0; i <= n; ++ i)
f[0][i] = 0, f[i][0] = 0;
for(int i = 1; i <= n; ++ i)
for(int j = 1; j <= n; ++ j){
if(s1[i] == s2[j])
f[i][j] = f[i - 1][j - 1] + 1;
else
f[i][j] = max(f[i][j - 1], f[i - 1][j]);
}
return(f[n][n]);
}
<|endoftext|> |
<commit_before><commit_msg>Call InitLogging() for courgette.<commit_after><|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
#include "etl/expr/base_temporary_expr.hpp"
#include "etl/impl/functions.hpp"
namespace etl {
/*!
* \brief An unary function expression.
* \tparam A The unary sub type
*/
template <typename A, typename Impl>
struct unary_function_expr : base_temporary_expr_un<unary_function_expr<A, Impl>, A> {
using value_type = value_t<A>; ///< The type of value of the expression
using this_type = unary_function_expr<A, Impl>; ///< The type of this expression
using base_type = base_temporary_expr_un<this_type, A>; ///< The base type
using sub_traits = decay_traits<A>; ///< The traits of the sub type
static constexpr auto storage_order = sub_traits::storage_order; ///< The sub storage order
/*!
* \brief Construct a new expression
* \param a The sub expression
*/
explicit unary_function_expr(A a) : base_type(a) {
//Nothing else to init
}
/*!
* \brief Validate the function dimensions
* \param a The input matrix
* \þaram c The output matrix
*/
template <typename C, cpp_enable_if(all_fast<A,C>::value)>
static void check(const A& a, const C& c) {
cpp_unused(a);
cpp_unused(c);
static constexpr etl::order order_lhs = decay_traits<C>::storage_order;
static constexpr etl::order order_rhs = decay_traits<A>::storage_order;
static_assert(order_lhs == order_rhs, "Cannot change storage order");
static_assert(decay_traits<A>::dimensions() == decay_traits<C>::dimensions(), "Invalid dimensions");
static_assert(decay_traits<A>::size() == decay_traits<C>::size(), "Invalid size");
}
/*!
* \brief Validate the function dimensions
* \param a The input matrix
* \þaram c The output matrix
*/
template <typename C, cpp_disable_if(all_fast<A,C>::value)>
static void check(const A& a, const C& c) {
static constexpr etl::order order_lhs = decay_traits<A>::storage_order;
static constexpr etl::order order_rhs = decay_traits<A>::storage_order;
static_assert(order_lhs == order_rhs, "Cannot change storage order");
static_assert(decay_traits<A>::dimensions() == decay_traits<C>::dimensions(), "Invalid dimensions");
cpp_assert(etl::size(a) == etl::size(c), "Invalid size");
cpp_unused(a);
cpp_unused(c);
}
// Assignment functions
/*!
* \brief Assign to a matrix of the same storage order
* \param c The expression to which assign
*/
template<typename C, cpp_enable_if(decay_traits<C>::storage_order == storage_order)>
void assign_to(C&& c) const {
static_assert(all_etl_expr<A, C>::value, "Function expression only supported for ETL expressions");
auto& a = this->a();
standard_evaluator::pre_assign_rhs(a);
check(a, c);
Impl::apply(make_temporary(a), c);
}
/*!
* \brief Assign to a matrix of a different storage order
* \param c The expression to which assign
*/
template<typename C, cpp_enable_if(decay_traits<C>::storage_order != storage_order)>
void assign_to(C&& c) const {
std_assign_evaluate(*this, c);
}
/*!
* \brief Add to the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_add_to(L&& lhs) const {
std_add_evaluate(*this, lhs);
}
/*!
* \brief Sub from the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_sub_to(L&& lhs) const {
std_sub_evaluate(*this, lhs);
}
/*!
* \brief Multiply the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_mul_to(L&& lhs) const {
std_mul_evaluate(*this, lhs);
}
/*!
* \brief Divide the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_div_to(L&& lhs) const {
std_div_evaluate(*this, lhs);
}
/*!
* \brief Modulo the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_mod_to(L&& lhs) const {
std_mod_evaluate(*this, lhs);
}
/*!
* \brief Print a representation of the expression on the given stream
* \param os The output stream
* \param expr The expression to print
* \return the output stream
*/
friend std::ostream& operator<<(std::ostream& os, const unary_function_expr& expr) {
return os << Impl::name() << "(" << expr._a << ")";
}
};
/*!
* \brief Traits for an unary function expression
* \tparam A The unary sub type
*/
template <typename A, typename Impl>
struct etl_traits<etl::unary_function_expr<A, Impl>> {
using expr_t = etl::unary_function_expr<A, Impl>; ///< The expression type
using sub_expr_t = std::decay_t<A>; ///< The sub expression type
using sub_traits = etl_traits<sub_expr_t>; ///< The sub traits
using value_type = value_t<A>; ///< The value type of the expression
static constexpr bool is_etl = true; ///< Indicates if the type is an ETL expression
static constexpr bool is_transformer = false; ///< Indicates if the type is a transformer
static constexpr bool is_view = false; ///< Indicates if the type is a view
static constexpr bool is_magic_view = false; ///< Indicates if the type is a magic view
static constexpr bool is_fast = sub_traits::is_fast; ///< Indicates if the expression is fast
static constexpr bool is_linear = true; ///< Indicates if the expression is linear
static constexpr bool is_thread_safe = true; ///< Indicates if the expression is thread safe
static constexpr bool is_value = false; ///< Indicates if the expression is of value type
static constexpr bool is_direct = true; ///< Indicates if the expression has direct memory access
static constexpr bool is_generator = false; ///< Indicates if the expression is a generator
static constexpr bool is_padded = false; ///< Indicates if the expression is padded
static constexpr bool is_aligned = true; ///< Indicates if the expression is padded
static constexpr bool is_temporary = true; ///< Indicates if the expression needs a evaluator visitor
static constexpr order storage_order = sub_traits::storage_order; ///< The expression's storage order
/*!
* \brief Indicates if the expression is vectorizable using the
* given vector mode
* \tparam V The vector mode
*/
template <vector_mode_t V>
using vectorizable = std::true_type;
/*!
* \brief Returns the DDth dimension of the expression
* \return the DDth dimension of the expression
*/
template <size_t DD>
static constexpr size_t dim() {
return decay_traits<A>::template dim<DD>();
}
/*!
* \brief Returns the dth dimension of the expression
* \param e The sub expression
* \param d The dimension to get
* \return the dth dimension of the expression
*/
static size_t dim(const expr_t& e, size_t d) {
return etl::dim(e._a, d);
}
/*!
* \brief Returns the size of the expression
* \param e The sub expression
* \return the size of the expression
*/
static size_t size(const expr_t& e) {
return etl::size(e._a);
}
/*!
* \brief Returns the size of the expression
* \return the size of the expression
*/
static constexpr size_t size() {
return decay_traits<A>::size();
}
/*!
* \brief Returns the number of dimensions of the expression
* \return the number of dimensions of the expression
*/
static constexpr size_t dimensions() {
return decay_traits<A>::dimensions();
}
};
} //end of namespace etl
<commit_msg>Fix bug in check<commit_after>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
#include "etl/expr/base_temporary_expr.hpp"
#include "etl/impl/functions.hpp"
namespace etl {
/*!
* \brief An unary function expression.
* \tparam A The unary sub type
*/
template <typename A, typename Impl>
struct unary_function_expr : base_temporary_expr_un<unary_function_expr<A, Impl>, A> {
using value_type = value_t<A>; ///< The type of value of the expression
using this_type = unary_function_expr<A, Impl>; ///< The type of this expression
using base_type = base_temporary_expr_un<this_type, A>; ///< The base type
using sub_traits = decay_traits<A>; ///< The traits of the sub type
static constexpr auto storage_order = sub_traits::storage_order; ///< The sub storage order
/*!
* \brief Construct a new expression
* \param a The sub expression
*/
explicit unary_function_expr(A a) : base_type(a) {
//Nothing else to init
}
/*!
* \brief Validate the function dimensions
* \param a The input matrix
* \þaram c The output matrix
*/
template <typename C, cpp_enable_if(all_fast<A,C>::value)>
static void check(const A& a, const C& c) {
cpp_unused(a);
cpp_unused(c);
static constexpr etl::order order_lhs = decay_traits<C>::storage_order;
static constexpr etl::order order_rhs = decay_traits<A>::storage_order;
static_assert(order_lhs == order_rhs, "Cannot change storage order");
static_assert(decay_traits<A>::dimensions() == decay_traits<C>::dimensions(), "Invalid dimensions");
static_assert(decay_traits<A>::size() == decay_traits<C>::size(), "Invalid size");
}
/*!
* \brief Validate the function dimensions
* \param a The input matrix
* \þaram c The output matrix
*/
template <typename C, cpp_disable_if(all_fast<A,C>::value)>
static void check(const A& a, const C& c) {
static constexpr etl::order order_lhs = decay_traits<C>::storage_order;
static constexpr etl::order order_rhs = decay_traits<A>::storage_order;
static_assert(order_lhs == order_rhs, "Cannot change storage order");
static_assert(decay_traits<A>::dimensions() == decay_traits<C>::dimensions(), "Invalid dimensions");
cpp_assert(etl::size(a) == etl::size(c), "Invalid size");
cpp_unused(a);
cpp_unused(c);
}
// Assignment functions
/*!
* \brief Assign to a matrix of the same storage order
* \param c The expression to which assign
*/
template<typename C, cpp_enable_if(decay_traits<C>::storage_order == storage_order)>
void assign_to(C&& c) const {
static_assert(all_etl_expr<A, C>::value, "Function expression only supported for ETL expressions");
auto& a = this->a();
standard_evaluator::pre_assign_rhs(a);
check(a, c);
Impl::apply(make_temporary(a), c);
}
/*!
* \brief Assign to a matrix of a different storage order
* \param c The expression to which assign
*/
template<typename C, cpp_enable_if(decay_traits<C>::storage_order != storage_order)>
void assign_to(C&& c) const {
std_assign_evaluate(*this, c);
}
/*!
* \brief Add to the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_add_to(L&& lhs) const {
std_add_evaluate(*this, lhs);
}
/*!
* \brief Sub from the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_sub_to(L&& lhs) const {
std_sub_evaluate(*this, lhs);
}
/*!
* \brief Multiply the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_mul_to(L&& lhs) const {
std_mul_evaluate(*this, lhs);
}
/*!
* \brief Divide the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_div_to(L&& lhs) const {
std_div_evaluate(*this, lhs);
}
/*!
* \brief Modulo the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_mod_to(L&& lhs) const {
std_mod_evaluate(*this, lhs);
}
/*!
* \brief Print a representation of the expression on the given stream
* \param os The output stream
* \param expr The expression to print
* \return the output stream
*/
friend std::ostream& operator<<(std::ostream& os, const unary_function_expr& expr) {
return os << Impl::name() << "(" << expr._a << ")";
}
};
/*!
* \brief Traits for an unary function expression
* \tparam A The unary sub type
*/
template <typename A, typename Impl>
struct etl_traits<etl::unary_function_expr<A, Impl>> {
using expr_t = etl::unary_function_expr<A, Impl>; ///< The expression type
using sub_expr_t = std::decay_t<A>; ///< The sub expression type
using sub_traits = etl_traits<sub_expr_t>; ///< The sub traits
using value_type = value_t<A>; ///< The value type of the expression
static constexpr bool is_etl = true; ///< Indicates if the type is an ETL expression
static constexpr bool is_transformer = false; ///< Indicates if the type is a transformer
static constexpr bool is_view = false; ///< Indicates if the type is a view
static constexpr bool is_magic_view = false; ///< Indicates if the type is a magic view
static constexpr bool is_fast = sub_traits::is_fast; ///< Indicates if the expression is fast
static constexpr bool is_linear = true; ///< Indicates if the expression is linear
static constexpr bool is_thread_safe = true; ///< Indicates if the expression is thread safe
static constexpr bool is_value = false; ///< Indicates if the expression is of value type
static constexpr bool is_direct = true; ///< Indicates if the expression has direct memory access
static constexpr bool is_generator = false; ///< Indicates if the expression is a generator
static constexpr bool is_padded = false; ///< Indicates if the expression is padded
static constexpr bool is_aligned = true; ///< Indicates if the expression is padded
static constexpr bool is_temporary = true; ///< Indicates if the expression needs a evaluator visitor
static constexpr order storage_order = sub_traits::storage_order; ///< The expression's storage order
/*!
* \brief Indicates if the expression is vectorizable using the
* given vector mode
* \tparam V The vector mode
*/
template <vector_mode_t V>
using vectorizable = std::true_type;
/*!
* \brief Returns the DDth dimension of the expression
* \return the DDth dimension of the expression
*/
template <size_t DD>
static constexpr size_t dim() {
return decay_traits<A>::template dim<DD>();
}
/*!
* \brief Returns the dth dimension of the expression
* \param e The sub expression
* \param d The dimension to get
* \return the dth dimension of the expression
*/
static size_t dim(const expr_t& e, size_t d) {
return etl::dim(e._a, d);
}
/*!
* \brief Returns the size of the expression
* \param e The sub expression
* \return the size of the expression
*/
static size_t size(const expr_t& e) {
return etl::size(e._a);
}
/*!
* \brief Returns the size of the expression
* \return the size of the expression
*/
static constexpr size_t size() {
return decay_traits<A>::size();
}
/*!
* \brief Returns the number of dimensions of the expression
* \return the number of dimensions of the expression
*/
static constexpr size_t dimensions() {
return decay_traits<A>::dimensions();
}
};
} //end of namespace etl
<|endoftext|> |
<commit_before>/*
* ArcEmu MMORPG Server
* Copyright (C) 2008-2020 <http://www.ArcEmu.org/>
*
* 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
* 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 Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "StdAfx.h"
#include "LFGPacketHandlers.h"
DEFINE_PACKET_HANDLER_METHOD( LFGProposalResultPacketHandler )
{
Player *_player = session.GetPlayer();
CHECK_INWORLD_RETURN
Arcemu::GamePackets::LFG::CLFGProposalResult result;
result.deserialize( recv_data );
LOG_DEBUG( "Received proposal result" );
}
DEFINE_PACKET_HANDLER_METHOD( LFGSetCommentHandler )
{
Player *_player = session.GetPlayer();
CHECK_INWORLD_RETURN
Arcemu::GamePackets::LFG::CLFGSetComment packet;
packet.deserialize( recv_data );
_player->Lfgcomment = packet.comment;
LOG_DEBUG( "Received set comment message" );
}
DEFINE_PACKET_HANDLER_METHOD( LFGPlayerInfoHandler )
{
Player *_player = session.GetPlayer();
CHECK_INWORLD_RETURN
LOG_DEBUG( "Received LFG player info request." );
PacketBuffer response( SMSG_LFG_PLAYER_INFO, 5 );
response << uint8( 0 );
response << uint32( 0 );
_player->SendPacket( &response );
LOG_DEBUG( "Sent (empty) LFG player info response." );
}
DEFINE_PACKET_HANDLER_METHOD( LFGPartyInfoHandler )
{
Player *_player = session.GetPlayer();
CHECK_INWORLD_RETURN
LOG_DEBUG( "Received LFG party info request." );
PacketBuffer response( SMSG_LFG_PARTY_INFO, 1 );
response << uint8( 0 );
_player->SendPacket( &response );
LOG_DEBUG( "Sent (empty) LFG party info response." );
}
DEFINE_PACKET_HANDLER_METHOD( LFGJoinHandler )
{
Player *_player = session.GetPlayer();
CHECK_INWORLD_RETURN
Arcemu::GamePackets::LFG::CLFGJoin packet;
packet.deserialize( recv_data );
LOG_DEBUG( "Received LFG join request." );
// If experimental LFG is not enabled, just send an internal LFG error message
if( !Config.OptionalConfig.GetBoolDefault( "Experimental", "lfg", false ) )
{
PacketBuffer buffer;
Arcemu::GamePackets::LFG::SLFGJoinResult response;
response.result = Arcemu::GamePackets::LFG::SLFGJoinResult::LFG_JOIN_INTERNAL_ERROR;
response.state = 0;
response.serialize( buffer );
_player->SendPacket( &buffer );
LOG_DEBUG( "Sent LFG join result" );
return;
}
}
DEFINE_PACKET_HANDLER_METHOD( LFGLeaveHandler )
{
Player *_player = session.GetPlayer();
CHECK_INWORLD_RETURN
LOG_DEBUG( "Received LFG leave request." );
}
<commit_msg>Print roles, and first dungeon entry's details to the console<commit_after>/*
* ArcEmu MMORPG Server
* Copyright (C) 2008-2020 <http://www.ArcEmu.org/>
*
* 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
* 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 Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "StdAfx.h"
#include "LFGPacketHandlers.h"
DEFINE_PACKET_HANDLER_METHOD( LFGProposalResultPacketHandler )
{
Player *_player = session.GetPlayer();
CHECK_INWORLD_RETURN
Arcemu::GamePackets::LFG::CLFGProposalResult result;
result.deserialize( recv_data );
LOG_DEBUG( "Received proposal result" );
}
DEFINE_PACKET_HANDLER_METHOD( LFGSetCommentHandler )
{
Player *_player = session.GetPlayer();
CHECK_INWORLD_RETURN
Arcemu::GamePackets::LFG::CLFGSetComment packet;
packet.deserialize( recv_data );
_player->Lfgcomment = packet.comment;
LOG_DEBUG( "Received set comment message" );
}
DEFINE_PACKET_HANDLER_METHOD( LFGPlayerInfoHandler )
{
Player *_player = session.GetPlayer();
CHECK_INWORLD_RETURN
LOG_DEBUG( "Received LFG player info request." );
PacketBuffer response( SMSG_LFG_PLAYER_INFO, 5 );
response << uint8( 0 );
response << uint32( 0 );
_player->SendPacket( &response );
LOG_DEBUG( "Sent (empty) LFG player info response." );
}
DEFINE_PACKET_HANDLER_METHOD( LFGPartyInfoHandler )
{
Player *_player = session.GetPlayer();
CHECK_INWORLD_RETURN
LOG_DEBUG( "Received LFG party info request." );
PacketBuffer response( SMSG_LFG_PARTY_INFO, 1 );
response << uint8( 0 );
_player->SendPacket( &response );
LOG_DEBUG( "Sent (empty) LFG party info response." );
}
DEFINE_PACKET_HANDLER_METHOD( LFGJoinHandler )
{
Player *_player = session.GetPlayer();
CHECK_INWORLD_RETURN
Arcemu::GamePackets::LFG::CLFGJoin packet;
packet.deserialize( recv_data );
if( packet.dungeons.size() == 0 )
{
LOG_DEBUG( "Received LFG join request without dungeons." );
return;
}
LOG_DEBUG( "Received LFG join request. Roles: %u Dungeon1: %u Type1: %u", packet.roles, packet.dungeons[ 0 ].dungeon, packet.dungeons[ 0 ].unk2 );
// If experimental LFG is not enabled, just send an internal LFG error message
if( !Config.OptionalConfig.GetBoolDefault( "Experimental", "lfg", false ) )
{
PacketBuffer buffer;
Arcemu::GamePackets::LFG::SLFGJoinResult response;
response.result = Arcemu::GamePackets::LFG::SLFGJoinResult::LFG_JOIN_INTERNAL_ERROR;
response.state = 0;
response.serialize( buffer );
_player->SendPacket( &buffer );
LOG_DEBUG( "Sent LFG join result" );
return;
}
}
DEFINE_PACKET_HANDLER_METHOD( LFGLeaveHandler )
{
Player *_player = session.GetPlayer();
CHECK_INWORLD_RETURN
LOG_DEBUG( "Received LFG leave request." );
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
using namespace std;
int main(){
int length;
cin >> length;
vector<int> vector(length);
for (int i = 0; i < length; i++)
{
cin >> vector[i];
}
for (int i = 0; i < length; i++)
{
int j = i-1;
int intermediate = vector[i];
while(j >= 0 && vector[j] > intermediate)
{
vector[j+1] = vector[j];
vector[j] = intermediate;
j--;
}
cout << vector[0];
for (int k = 1; k < length; k++)
{
cout << ' ' << vector[k];
}
cout << endl;
}
}<commit_msg>Refactor curly bracket.<commit_after>#include <iostream>
#include <vector>
using namespace std;
int main()
{
int length;
cin >> length;
vector<int> vector(length);
for (int i = 0; i < length; i++)
{
cin >> vector[i];
}
for (int i = 0; i < length; i++)
{
int j = i-1;
int intermediate = vector[i];
while(j >= 0 && vector[j] > intermediate)
{
vector[j+1] = vector[j];
vector[j] = intermediate;
j--;
}
cout << vector[0];
for (int k = 1; k < length; k++)
{
cout << ' ' << vector[k];
}
cout << endl;
}
}<|endoftext|> |
<commit_before>#include "Halide.h"
#include <tiramisu/utils.h>
#include <cstdlib>
#include <iostream>
#include "mkl_cblas.h"
#include "sgemm_wrapper.h"
#include "benchmarks.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
} // extern "C"
#endif
int main(int, char **)
{
std::vector<std::chrono::duration<double,std::milli>> duration_vector_1;
std::vector<std::chrono::duration<double,std::milli>> duration_vector_2;
float a = 3, b = 3;
#if 1
bool run_mkl = false;
bool run_tiramisu = false;
const char* env_mkl = std::getenv("RUN_REF");
if ((env_mkl != NULL) && (env_mkl[0] == '1'))
run_mkl = true;
const char* env_tira = std::getenv("RUN_TIRAMISU");
if ((env_tira != NULL) && (env_tira[0] == '1'))
run_tiramisu = true;
#else
bool run_mkl = true;
bool run_tiramisu = true;
#endif
int sizes[27][4], D = 1060 * 1060;
/************ SIZE_IS_MULTIPLE_OF_TILE 1 ******************/
sizes[0][0] = 4096;
sizes[0][1] = 4096;
sizes[0][2] = 4096;
sizes[0][3] = 65536 * 4096;
sizes[1][0] = 128;
sizes[1][1] = 128;
sizes[1][2] = 128;
sizes[1][3] = 128;
sizes[2][0] = 512;
sizes[2][1] = 512;
sizes[2][2] = 512;
sizes[2][3] = 1024;
sizes[3][0] = 1024;
sizes[3][1] = 1024;
sizes[3][2] = 1024;
sizes[3][3] = 1024 * 1024;
sizes[4][0] = 128;
sizes[4][1] = 128;
sizes[4][2] = 256;
sizes[4][3] = D;
sizes[5][0] = 2048;
sizes[5][1] = 2048;
sizes[5][2] = 2048;
sizes[5][3] = D;
sizes[6][0] = 2048;
sizes[6][1] = 2048;
sizes[6][2] = 1024;
sizes[6][3] = D;
sizes[7][0] = 1024;
sizes[7][1] = 1024;
sizes[7][2] = 2048;
sizes[7][3] = D;
sizes[8][0] = 1024;
sizes[8][1] = 1024;
sizes[8][2] = 512;
sizes[8][3] = D;
sizes[9][0] = 512;
sizes[9][1] = 512;
sizes[9][2] = 1024;
sizes[9][3] = D;
sizes[10][0] = 512;
sizes[10][1] = 512;
sizes[10][2] = 256;
sizes[10][3] = D;
sizes[11][0] = 128;
sizes[11][1] = 128;
sizes[11][2] = 2048;
sizes[11][3] = D;
sizes[12][0] = 256;
sizes[12][1] = 256;
sizes[12][2] = 256;
sizes[12][3] = D;
sizes[13][0] = 128;
sizes[13][1] = 128;
sizes[13][2] = 512;
sizes[13][3] = D;
sizes[14][0] = 128;
sizes[14][1] = 128;
sizes[14][2] = 1024;
sizes[14][3] = D;
sizes[15][0] = 128;
sizes[15][1] = 128;
sizes[15][2] = 64;
sizes[15][3] = D;
/************** SIZE_IS_MULTIPLE_OF_TILE 0 ****************/
sizes[16][0] = 1060;
sizes[16][1] = 1060;
sizes[16][2] = 1060;
sizes[16][3] = D;
sizes[17][0] = 4;
sizes[17][1] = 4;
sizes[17][2] = 4;
sizes[17][3] = D;
sizes[18][0] = 8;
sizes[18][1] = 8;
sizes[18][2] = 4;
sizes[18][3] = D;
sizes[19][0] = 16;
sizes[19][1] = 16;
sizes[19][2] = 4;
sizes[19][3] = D;
sizes[20][0] = 16;
sizes[20][1] = 16;
sizes[20][2] = 16;
sizes[20][3] = D;
sizes[21][0] = 8;
sizes[21][1] = 8;
sizes[21][2] = 16;
sizes[21][3] = D;
int p, q;
if (SIZE_IS_MULTIPLE_OF_TILE)
{
p = 0;
q = 16;
}
else
{
p = 16;
q = 22;
}
for (int j = p; j < q; j++)
{
int local_N = sizes[j][0];
int local_M = sizes[j][1];
int local_K = sizes[j][2];
int local_size = sizes[j][3];
Halide::Buffer<int> SIZES(3, "SIZES");
Halide::Buffer<float> alpha(1, "alpha");
Halide::Buffer<float> beta(1, "beta");
Halide::Buffer<float> A(local_N, local_K, "A");
Halide::Buffer<float> B(local_K, local_M, "B");
Halide::Buffer<float> C(local_N, local_M, "C");
Halide::Buffer<float> C_mkl(local_N, local_M, "C_mkl");
SIZES(0) = local_N; SIZES(1) = local_M; SIZES(2) = local_K;
alpha(0) = a; beta(0) = b;
init_buffer(A, (float)1);
init_buffer(B, (float)1);
init_buffer(C, (float)1);
init_buffer(C_mkl, (float)1);
// Calling MKL
{
long long int lda, ldb, ldc;
long long int rmaxa, cmaxa, rmaxb, cmaxb, rmaxc, cmaxc;
CBLAS_LAYOUT layout = CblasRowMajor;
CBLAS_TRANSPOSE transA = CblasNoTrans, transB = CblasNoTrans;
long long int ma, na, mb, nb;
if( transA == CblasNoTrans ) {
rmaxa = local_M + 1;
cmaxa = local_K;
ma = local_M;
na = local_K;
} else {
rmaxa = local_K + 1;
cmaxa = local_M;
ma = local_K;
na = local_M;
}
if( transB == CblasNoTrans ) {
rmaxb = local_K + 1;
cmaxb = local_N;
mb = local_K;
nb = local_N;
} else {
rmaxb = local_N + 1;
cmaxb = local_K;
mb = local_N;
nb = local_K;
}
rmaxc = local_M + 1;
cmaxc = local_N;
if (layout == CblasRowMajor) {
lda=cmaxa;
ldb=cmaxb;
ldc=cmaxc;
} else {
lda=rmaxa;
ldb=rmaxb;
ldc=rmaxc;
}
for (int i = 0; i < NB_TESTS; i++)
{
init_buffer(C_mkl, (float)1);
auto start1 = std::chrono::high_resolution_clock::now();
if (run_mkl == true)
cblas_sgemm(layout, transA, transB, local_M, local_N, local_K, a, (float *) A.raw_buffer()->host, lda, (float *) B.raw_buffer()->host, ldb, b, (float *) C_mkl.raw_buffer()->host, ldc);
auto end1 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double,std::milli> duration1 = end1 - start1;
duration_vector_1.push_back(duration1);
}
}
for (int i = 0; i < NB_TESTS; i++)
{
init_buffer(C, (float)1);
auto start2 = std::chrono::high_resolution_clock::now();
if (run_tiramisu == true)
sgemm_tiramisu(SIZES.raw_buffer(), alpha.raw_buffer(), beta.raw_buffer(), A.raw_buffer(), B.raw_buffer(), C.raw_buffer());
auto end2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double,std::milli> duration2 = end2 - start2;
duration_vector_2.push_back(duration2);
}
print_time("performance_CPU.csv", "sgemm",
{"MKL", "Tiramisu"},
{median(duration_vector_1), median(duration_vector_2)});
if (CHECK_CORRECTNESS)
if (run_mkl == 1 && run_tiramisu == 1)
{
compare_buffers("sgemm", C, C_mkl);
}
if (PRINT_OUTPUT)
{
std::cout << "Tiramisu sgemm " << std::endl;
print_buffer(C);
std::cout << "MKL sgemm " << std::endl;
print_buffer(C_mkl);
}
}
return 0;
}
<commit_msg>Update sgemm_wrapper.cpp<commit_after>#include "Halide.h"
#include <tiramisu/utils.h>
#include <cstdlib>
#include <iostream>
#include "mkl_cblas.h"
#include "sgemm_wrapper.h"
#include "benchmarks.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
} // extern "C"
#endif
int main(int, char **)
{
std::vector<std::chrono::duration<double,std::milli>> duration_vector_1;
std::vector<std::chrono::duration<double,std::milli>> duration_vector_2;
float a = 3, b = 3;
#if 1
bool run_mkl = false;
bool run_tiramisu = false;
const char* env_mkl = std::getenv("RUN_REF");
if ((env_mkl != NULL) && (env_mkl[0] == '1'))
run_mkl = true;
const char* env_tira = std::getenv("RUN_TIRAMISU");
if ((env_tira != NULL) && (env_tira[0] == '1'))
run_tiramisu = true;
#else
bool run_mkl = true;
bool run_tiramisu = true;
#endif
int sizes[27][4], D = 1060 * 1060;
/************ SIZE_IS_MULTIPLE_OF_TILE 1 ******************/
sizes[0][0] = 4096;
sizes[0][1] = 4096;
sizes[0][2] = 4096;
sizes[0][3] = 65536 * 4096;
sizes[1][0] = 128;
sizes[1][1] = 128;
sizes[1][2] = 128;
sizes[1][3] = 128;
sizes[2][0] = 512;
sizes[2][1] = 512;
sizes[2][2] = 512;
sizes[2][3] = 1024;
sizes[3][0] = 1024;
sizes[3][1] = 1024;
sizes[3][2] = 1024;
sizes[3][3] = 1024 * 1024;
sizes[4][0] = 128;
sizes[4][1] = 128;
sizes[4][2] = 256;
sizes[4][3] = D;
sizes[5][0] = 2048;
sizes[5][1] = 2048;
sizes[5][2] = 2048;
sizes[5][3] = D;
sizes[6][0] = 2048;
sizes[6][1] = 2048;
sizes[6][2] = 1024;
sizes[6][3] = D;
sizes[7][0] = 1024;
sizes[7][1] = 1024;
sizes[7][2] = 2048;
sizes[7][3] = D;
sizes[8][0] = 1024;
sizes[8][1] = 1024;
sizes[8][2] = 512;
sizes[8][3] = D;
sizes[9][0] = 512;
sizes[9][1] = 512;
sizes[9][2] = 1024;
sizes[9][3] = D;
sizes[10][0] = 512;
sizes[10][1] = 512;
sizes[10][2] = 256;
sizes[10][3] = D;
sizes[11][0] = 128;
sizes[11][1] = 128;
sizes[11][2] = 2048;
sizes[11][3] = D;
sizes[12][0] = 256;
sizes[12][1] = 256;
sizes[12][2] = 256;
sizes[12][3] = D;
sizes[13][0] = 128;
sizes[13][1] = 128;
sizes[13][2] = 512;
sizes[13][3] = D;
sizes[14][0] = 128;
sizes[14][1] = 128;
sizes[14][2] = 1024;
sizes[14][3] = D;
sizes[15][0] = 128;
sizes[15][1] = 128;
sizes[15][2] = 64;
sizes[15][3] = D;
/************** SIZE_IS_MULTIPLE_OF_TILE 0 ****************/
sizes[16][0] = 1060;
sizes[16][1] = 1060;
sizes[16][2] = 1060;
sizes[16][3] = D;
sizes[17][0] = 4;
sizes[17][1] = 4;
sizes[17][2] = 4;
sizes[17][3] = D;
sizes[18][0] = 8;
sizes[18][1] = 8;
sizes[18][2] = 4;
sizes[18][3] = D;
sizes[19][0] = 16;
sizes[19][1] = 16;
sizes[19][2] = 4;
sizes[19][3] = D;
sizes[20][0] = 16;
sizes[20][1] = 16;
sizes[20][2] = 16;
sizes[20][3] = D;
sizes[21][0] = 8;
sizes[21][1] = 8;
sizes[21][2] = 16;
sizes[21][3] = D;
int p, q;
if (SIZE_IS_MULTIPLE_OF_TILE)
{
p = 0;
q = 16;
}
else
{
p = 16;
q = 22;
}
for (int j = p; j < q; j++)
{
int local_N = sizes[j][0];
int local_M = sizes[j][1];
int local_K = sizes[j][2];
int local_size = sizes[j][3];
Halide::Buffer<int> SIZES(3, "SIZES");
Halide::Buffer<float> alpha(1, "alpha");
Halide::Buffer<float> beta(1, "beta");
Halide::Buffer<float> A(local_N, local_K, "A");
Halide::Buffer<float> B(local_K, local_M, "B");
Halide::Buffer<float> C(local_N, local_M, "C");
Halide::Buffer<float> C_mkl(local_N, local_M, "C_mkl");
SIZES(0) = local_N; SIZES(1) = local_M; SIZES(2) = local_K;
alpha(0) = a; beta(0) = b;
init_buffer(A, (float)1);
init_buffer(B, (float)1);
init_buffer(C, (float)1);
init_buffer(C_mkl, (float)1);
// Calling MKL
{
long long int lda, ldb, ldc;
long long int rmaxa, cmaxa, rmaxb, cmaxb, rmaxc, cmaxc;
CBLAS_LAYOUT layout = CblasRowMajor;
CBLAS_TRANSPOSE transA = CblasNoTrans, transB = CblasNoTrans;
long long int ma, na, mb, nb;
if( transA == CblasNoTrans ) {
rmaxa = local_M + 1;
cmaxa = local_K;
ma = local_M;
na = local_K;
} else {
rmaxa = local_K + 1;
cmaxa = local_M;
ma = local_K;
na = local_M;
}
if( transB == CblasNoTrans ) {
rmaxb = local_K + 1;
cmaxb = local_N;
mb = local_K;
nb = local_N;
} else {
rmaxb = local_N + 1;
cmaxb = local_K;
mb = local_N;
nb = local_K;
}
rmaxc = local_M + 1;
cmaxc = local_N;
if (layout == CblasRowMajor) {
lda=cmaxa;
ldb=cmaxb;
ldc=cmaxc;
} else {
lda=rmaxa;
ldb=rmaxb;
ldc=rmaxc;
}
for (int i = 0; i < NB_TESTS; i++)
{
init_buffer(C_mkl, (float)1);
auto start1 = std::chrono::high_resolution_clock::now();
if (run_mkl == true)
cblas_sgemm(layout, transA, transB, local_M, local_N, local_K, a, (float *) A.raw_buffer()->host, lda, (float *) B.raw_buffer()->host, ldb, b, (float *) C_mkl.raw_buffer()->host, ldc);
auto end1 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double,std::milli> duration1 = end1 - start1;
duration_vector_1.push_back(duration1);
}
}
for (int i = 0; i < NB_TESTS; i++)
{
init_buffer(C, (float)1);
auto start2 = std::chrono::high_resolution_clock::now();
if (run_tiramisu == true)
sgemm_tiramisu(SIZES.raw_buffer(), alpha.raw_buffer(), beta.raw_buffer(), A.raw_buffer(), B.raw_buffer(), C.raw_buffer());
auto end2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double,std::milli> duration2 = end2 - start2;
duration_vector_2.push_back(duration2);
}
print_time("performance_CPU.csv", "sgemm",
{"MKL", "Tiramisu"},
{median(duration_vector_1), median(duration_vector_2)});
if (CHECK_CORRECTNESS)
if (run_mkl == 1 && run_tiramisu == 1)
{
compare_buffers("sgemm", C, C_mkl);
}
if (PRINT_OUTPUT)
{
std::cout << "Tiramisu sgemm " << std::endl;
print_buffer(C);
std::cout << "MKL sgemm " << std::endl;
print_buffer(C_mkl);
}
}
return 0;
}
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 Scientific Computing and Imaging Institute,
University of Utah.
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.
*/
#include <Interface/Modules/Python/CompositeModuleDialog.h>
#include <Modules/Basic/CompositeModuleWithStaticPorts.h>
#include <Interface/Modules/Base/ModuleDialogManager.h>
#include <Interface/Modules/Base/ModuleLogWindow.h>
//#include <Interface/Modules/Base/CustomWidgets/CodeEditorWidgets.h>
using namespace SCIRun::Gui;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms::Python;
CompositeModuleDialog::CompositeModuleDialog(const std::string& name, ModuleStateHandle state,
QWidget* parent /* = 0 */)
: ModuleDialogGeneric(state, parent)
{
setupUi(this);
setWindowTitle(QString::fromStdString(name));
fixSize();
addPlainTextEditManager(networkXMLplainTextEdit_, Parameters::NetworkXml);
addPlainTextEditManager(portReportPlainTextEdit_, Parameters::PortSettings);
connect(clearPushButton_, &QPushButton::clicked, [this]() { networkXMLplainTextEdit_->clear(); });
connect(pastePushButton_, &QPushButton::clicked, [this]() { networkXMLplainTextEdit_->setPlainText(QGuiApplication::clipboard()->text()); });
state_->connectSpecificStateChanged(Parameters::ModuleIdList,
[this]() { updateModuleUIButtons(); });
}
CompositeModuleDialog::~CompositeModuleDialog()
{
for (auto& dialog : dialogManagers_)
{
dialog->destroyLog();
dialog->closeOptions();
dialog->destroyOptions();
}
}
void CompositeModuleDialog::updateModuleUIButtons()
{
auto moduleMap = transient_value_cast<SCIRun::Modules::Basic::CompositeModuleInfoMap>(state_->getTransientValue(Parameters::ModuleIdList));
if (moduleMap.empty())
{
for (int i = 0; i < moduleUIgridLayout_->rowCount(); ++i)
{
for (int j = 0; j < moduleUIgridLayout_->columnCount(); ++j)
{
delete moduleUIgridLayout_->itemAtPosition(i, j)->widget();
}
}
for (auto& dialog : dialogManagers_)
{
dialog->destroyLog();
dialog->closeOptions();
dialog->destroyOptions();
}
dialogManagers_.clear();
return;
}
int i = 0;
for (const auto& p : moduleMap)
{
auto mod = p.second;
auto dialogs = makeShared<ModuleDialogManager>(mod);
if (mod->hasUI())
{
auto uiLabel = p.first.id_.c_str() + QString(" UI");
auto ui = new QPushButton(uiLabel);
moduleUIgridLayout_->addWidget(ui, i, 0);
dialogs->createOptions();
auto options = dialogs->options();
connect(ui, &QPushButton::clicked, [options]() { options->show(); options->raise(); });
}
{
auto logLabel = p.first.id_.c_str() + QString(" log");
auto log = new QPushButton(logLabel);
moduleUIgridLayout_->addWidget(log, i, 1);
auto logWindow = dialogs->setupLogging(nullptr, nullptr, this);
connect(log, &QPushButton::clicked, [logWindow]() { logWindow->show(); logWindow->raise(); });
}
dialogManagers_.push_back(dialogs);
++i;
}
}
<commit_msg>Initial pull<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 Scientific Computing and Imaging Institute,
University of Utah.
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.
*/
#include <Interface/Modules/Python/CompositeModuleDialog.h>
#include <Modules/Basic/CompositeModuleWithStaticPorts.h>
#include <Interface/Modules/Base/ModuleDialogManager.h>
#include <Interface/Modules/Base/ModuleLogWindow.h>
//#include <Interface/Modules/Base/CustomWidgets/CodeEditorWidgets.h>
using namespace SCIRun::Gui;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms::Python;
CompositeModuleDialog::CompositeModuleDialog(const std::string& name, ModuleStateHandle state,
QWidget* parent /* = 0 */)
: ModuleDialogGeneric(state, parent)
{
setupUi(this);
setWindowTitle(QString::fromStdString(name));
fixSize();
addPlainTextEditManager(networkXMLplainTextEdit_, Parameters::NetworkXml);
addPlainTextEditManager(portReportPlainTextEdit_, Parameters::PortSettings);
connect(clearPushButton_, &QPushButton::clicked, [this]() { networkXMLplainTextEdit_->clear(); });
connect(pastePushButton_, &QPushButton::clicked, [this]() { networkXMLplainTextEdit_->setPlainText(QGuiApplication::clipboard()->text()); });
state_->connectSpecificStateChanged(Parameters::ModuleIdList,
[this]() { updateModuleUIButtons(); });
}
CompositeModuleDialog::~CompositeModuleDialog()
{
for (auto& dialog : dialogManagers_)
{
dialog->destroyLog();
dialog->closeOptions();
dialog->destroyOptions();
}
}
void CompositeModuleDialog::updateModuleUIButtons()
{
auto moduleMap = transient_value_cast<SCIRun::Modules::Basic::CompositeModuleInfoMap>(state_->getTransientValue(Parameters::ModuleIdList));
if (moduleMap.empty())
{
for (int i = 0; i < moduleUIgridLayout_->rowCount(); ++i)
{
for (int j = 0; j < moduleUIgridLayout_->columnCount(); ++j)
{
delete moduleUIgridLayout_->itemAtPosition(i, j)->widget();
}
}
for (auto& dialog : dialogManagers_)
{
dialog->destroyLog();
dialog->closeOptions();
dialog->destroyOptions();
}
dialogManagers_.clear();
return;
}
int i = 0;
for (const auto& p : moduleMap)
{
auto mod = p.second;
auto dialogs = makeShared<ModuleDialogManager>(mod);
if (mod->hasUI())
{
auto uiLabel = p.first.id_.c_str() + QString(" UI");
auto ui = new QPushButton(uiLabel);
moduleUIgridLayout_->addWidget(ui, i, 0);
dialogs->createOptions();
auto options = dialogs->options();
connect(ui, &QPushButton::clicked, [options]() { options->show(); options->raise(); });
options->pull();
}
{
auto logLabel = p.first.id_.c_str() + QString(" log");
auto log = new QPushButton(logLabel);
moduleUIgridLayout_->addWidget(log, i, 1);
auto logWindow = dialogs->setupLogging(nullptr, nullptr, this);
connect(log, &QPushButton::clicked, [logWindow]() { logWindow->show(); logWindow->raise(); });
}
dialogManagers_.push_back(dialogs);
++i;
}
}
<|endoftext|> |
<commit_before>#include "schedulers/schedule.h"
namespace schedulers {
//TODO: Why the compiler asks me for explicit schedulers::?
schedulers::Sched::Sched(game::CarTracker* car_tracker, int horizon)
: car_tracker_(car_tracker), throttles_(horizon, 0), distance_(0), switch_position_(-1) {
// There is no state given, so we assume no initial speed, thus distance = 0,
// but this state of Sched is actually invalid, because no CarState is provided
}
void schedulers::Sched::UpdateDistance(const game::CarState& state) {
distance_ = car_tracker_->velocity_model().PredictDistance(state.velocity(), throttles_);
}
void schedulers::Sched::UpdateDistance(double new_distance) {
distance_ = new_distance;
}
int schedulers::Sched::GetTicksToTheRequiredSwitch(const game::CarState& state, double distance_to_switch) {
if (distance_to_switch < 0)
return -1;
int distance = 0;
game::CarState next = state;
for (int pos = 0; pos < size(); ++pos) {
//TODO(minor) I could use the quicker PredictVelocity (waiting for turbo)
next = car_tracker_->Predict(next, game::Command(throttles_[pos]));
distance += next.velocity();
if (distance >= distance_to_switch) {
if (throttles_[pos] == 0.0) {
return pos;
} else {
// +1 might be too much in some cases, but I am looking for the upper bound
return pos + 1;
}
}
}
// Distance longer then the current horizon. We will not care yet.
return -1;
}
void schedulers::Sched::UpdateSwitchPosition(int switch_position) {
switch_position_ = switch_position;
}
void schedulers::Sched::RemoveSwitch() {
UpdateSwitchPosition(-1);
}
void schedulers::Sched::CorrectSwitch(const game::CarState& state, double last_throttle) {
bool switch_is_planned = (switch_position_ >= 0);
if (switch_is_planned) {
if (switch_position_ > 0) {
last_throttle = throttles_[switch_position_ - 1];
}
throttles_[switch_position_] = last_throttle;
}
}
// Return if succeded (the resulting schedule is safe and switch-correct).
bool schedulers::Sched::TryUpdateSwitchPosition(const game::CarState& state, int new_switch_position,
double distance_to_switch, double last_throttle) {
int saved_switch_position = switch_position_;
double saved_throttle = throttles_[new_switch_position];
UpdateSwitchPosition(new_switch_position);
CorrectSwitch(state, last_throttle);
bool success = IsSafe(state, distance_to_switch, last_throttle);
if (!success) {
// Undo if failed
switch_position_ = saved_switch_position;
throttles_[new_switch_position] = saved_throttle;
}
return success;
}
//TODO: Improve performance by adding "from"
// Whether schedule is safe and switch-correct
bool schedulers::Sched::IsSafe(const game::CarState& state, double distance_to_switch, double last_throttle) {
bool check_switch = (distance_to_switch >= 0);
int distance = 0;
game::CarState next = state;
// Are all scheduled states safe and switch-correct?
for (int pos = 0; pos < size(); ++pos) {
// Are angles safe?
next = car_tracker_->Predict(next, game::Command(throttles_[pos]));
if (!car_tracker_->crash_model().IsSafe(next.position().angle())) {
std::cerr << "here: " << pos << std::endl;
return false;
}
if (check_switch) {
// Check whether switch is planned in tick from range [0,pos]
distance += next.velocity();
if (distance_to_switch <= distance) {
bool switch_done = (switch_position_ >= 0 && switch_position_ <= pos);
if (!switch_done) {
// Switch was supposed to be done before distance_to_switch, but it was not
std::cerr << "check: " << pos << " " << distance << " " << distance_to_switch << std::endl;
return false;
}
}
}
}
// Check whether the planned switch is correct
if (check_switch && distance_to_switch <= distance) {
if (switch_position_ < 0) {
// We should have switch before the end of the horizon, but we have not
std::cerr << "bbbb: " << distance << " " << distance_to_switch << std::endl;
return false;
}
// Now, check if there are two consecutive throttles
if (switch_position_ > 0) {
last_throttle = throttles_[switch_position_ - 1];
}
if (throttles_[switch_position_] != last_throttle) {
// It still could be safe, but I treat it as incorrect. So it should be first corrected
// by calling CorrectSwitch().
std::cerr << "Schedule has incorrect throttles" << std::endl;
return false;
}
}
// This check is last, for efficiency
return car_tracker_->IsSafe(next);
}
// No guarantee it is still safe
void schedulers::Sched::ShiftLeft(const game::CarState& state) {
for (int i = 0; i < size() - 1; ++i) {
throttles_[i] = throttles_[i + 1];
}
throttles_[size() - 1] = 0.0;
switch_position_ -= 1;
UpdateDistance(state);
}
void schedulers::Sched::ShiftLeftFillSafe(const game::CarState& state, double distance_to_switch, double last_throttle) {
ShiftLeft(state);
// Try 1.0 at the end
throttles_[size() - 1] = 1.0;
if (IsSafe(state, distance_to_switch, last_throttle)) {
return ;
}
// If not then try to set the last value + switch at the end.
// Tt might work if a switch appeared in the horizon
if (distance_to_switch >= 0) {
throttles_[size() - 1] = throttles_[size() - 2];
int saved_switch_position_ = switch_position_;
switch_position_ = size() - 1;
if (IsSafe(state, distance_to_switch, last_throttle)) {
return;
}
// Undo switch position change
switch_position_ = saved_switch_position_;
}
// Otherwise, fall back to 0.0
throttles_[size() - 1] = 0.0;
}
void schedulers::Sched::Reset(const game::CarState& state) {
for (int i = 0; i<size(); ++i) {
throttles_[i] = 0;
}
switch_position_ = -1;
UpdateDistance(state);
}
void schedulers::Sched::Print() {
for (int i = 0; i < size(); ++i) {
printf("%.1f ", throttles_[i]);
}
printf(" [%.1f] s=%d\n", distance_, switch_position_);
}
} // namespace
<commit_msg>Commented out some debug messages<commit_after>#include "schedulers/schedule.h"
namespace schedulers {
//TODO: Why the compiler asks me for explicit schedulers::?
schedulers::Sched::Sched(game::CarTracker* car_tracker, int horizon)
: car_tracker_(car_tracker), throttles_(horizon, 0), distance_(0), switch_position_(-1) {
// There is no state given, so we assume no initial speed, thus distance = 0,
// but this state of Sched is actually invalid, because no CarState is provided
}
void schedulers::Sched::UpdateDistance(const game::CarState& state) {
distance_ = car_tracker_->velocity_model().PredictDistance(state.velocity(), throttles_);
}
void schedulers::Sched::UpdateDistance(double new_distance) {
distance_ = new_distance;
}
int schedulers::Sched::GetTicksToTheRequiredSwitch(const game::CarState& state, double distance_to_switch) {
if (distance_to_switch < 0)
return -1;
int distance = 0;
game::CarState next = state;
for (int pos = 0; pos < size(); ++pos) {
//TODO(minor) I could use the quicker PredictVelocity (waiting for turbo)
next = car_tracker_->Predict(next, game::Command(throttles_[pos]));
distance += next.velocity();
if (distance >= distance_to_switch) {
if (throttles_[pos] == 0.0) {
return pos;
} else {
// +1 might be too much in some cases, but I am looking for the upper bound
return pos + 1;
}
}
}
// Distance longer then the current horizon. We will not care yet.
return -1;
}
void schedulers::Sched::UpdateSwitchPosition(int switch_position) {
switch_position_ = switch_position;
}
void schedulers::Sched::RemoveSwitch() {
UpdateSwitchPosition(-1);
}
void schedulers::Sched::CorrectSwitch(const game::CarState& state, double last_throttle) {
bool switch_is_planned = (switch_position_ >= 0);
if (switch_is_planned) {
if (switch_position_ > 0) {
last_throttle = throttles_[switch_position_ - 1];
}
throttles_[switch_position_] = last_throttle;
}
}
// Return if succeded (the resulting schedule is safe and switch-correct).
bool schedulers::Sched::TryUpdateSwitchPosition(const game::CarState& state, int new_switch_position,
double distance_to_switch, double last_throttle) {
int saved_switch_position = switch_position_;
double saved_throttle = throttles_[new_switch_position];
UpdateSwitchPosition(new_switch_position);
CorrectSwitch(state, last_throttle);
bool success = IsSafe(state, distance_to_switch, last_throttle);
if (!success) {
// Undo if failed
switch_position_ = saved_switch_position;
throttles_[new_switch_position] = saved_throttle;
}
return success;
}
//TODO: Improve performance by adding "from"
// Whether schedule is safe and switch-correct
bool schedulers::Sched::IsSafe(const game::CarState& state, double distance_to_switch, double last_throttle) {
bool check_switch = (distance_to_switch >= 0);
int distance = 0;
game::CarState next = state;
// Are all scheduled states safe and switch-correct?
for (int pos = 0; pos < size(); ++pos) {
// Are angles safe?
next = car_tracker_->Predict(next, game::Command(throttles_[pos]));
if (!car_tracker_->crash_model().IsSafe(next.position().angle())) {
//std::cerr << "here: " << pos << std::endl;
return false;
}
if (check_switch) {
// Check whether switch is planned in tick from range [0,pos]
distance += next.velocity();
if (distance_to_switch <= distance) {
bool switch_done = (switch_position_ >= 0 && switch_position_ <= pos);
if (!switch_done) {
// Switch was supposed to be done before distance_to_switch, but it was not
//std::cerr << "check: " << pos << " " << distance << " " << distance_to_switch << std::endl;
return false;
}
}
}
}
// Check whether the planned switch is correct
if (check_switch && distance_to_switch <= distance) {
if (switch_position_ < 0) {
// We should have switch before the end of the horizon, but we have not
//std::cerr << "bbbb: " << distance << " " << distance_to_switch << std::endl;
return false;
}
// Now, check if there are two consecutive throttles
if (switch_position_ > 0) {
last_throttle = throttles_[switch_position_ - 1];
}
if (throttles_[switch_position_] != last_throttle) {
// It still could be safe, but I treat it as incorrect. So it should be first corrected
// by calling CorrectSwitch().
//std::cerr << "Schedule has incorrect throttles" << std::endl;
return false;
}
}
// This check is last, for efficiency
return car_tracker_->IsSafe(next);
}
// No guarantee it is still safe
void schedulers::Sched::ShiftLeft(const game::CarState& state) {
for (int i = 0; i < size() - 1; ++i) {
throttles_[i] = throttles_[i + 1];
}
throttles_[size() - 1] = 0.0;
switch_position_ -= 1;
UpdateDistance(state);
}
void schedulers::Sched::ShiftLeftFillSafe(const game::CarState& state, double distance_to_switch, double last_throttle) {
ShiftLeft(state);
// Try 1.0 at the end
throttles_[size() - 1] = 1.0;
if (IsSafe(state, distance_to_switch, last_throttle)) {
return ;
}
// If not then try to set the last value + switch at the end.
// Tt might work if a switch appeared in the horizon
if (distance_to_switch >= 0) {
throttles_[size() - 1] = throttles_[size() - 2];
int saved_switch_position_ = switch_position_;
switch_position_ = size() - 1;
if (IsSafe(state, distance_to_switch, last_throttle)) {
return;
}
// Undo switch position change
switch_position_ = saved_switch_position_;
}
// Otherwise, fall back to 0.0
throttles_[size() - 1] = 0.0;
}
void schedulers::Sched::Reset(const game::CarState& state) {
for (int i = 0; i<size(); ++i) {
throttles_[i] = 0;
}
switch_position_ = -1;
UpdateDistance(state);
}
void schedulers::Sched::Print() {
for (int i = 0; i < size(); ++i) {
printf("%.1f ", throttles_[i]);
}
printf(" [%.1f] s=%d\n", distance_, switch_position_);
}
} // namespace
<|endoftext|> |
<commit_before>//
// yas_operation.cpp
//
#include <atomic>
#include <deque>
#include <mutex>
#include <thread>
#include <vector>
#include "yas_operation.h"
using namespace yas;
#pragma mark - operation
class operation::impl : public base::impl {
public:
std::atomic<bool> canceled;
execution_f execution;
operation_option_t option;
impl(execution_f const &exe, operation_option_t &&option)
: canceled(false), execution(exe), option(std::move(option)) {
}
impl(execution_f &&exe, operation_option_t &&option)
: canceled(false), execution(std::move(exe)), option(std::move(option)) {
}
};
operation::operation(execution_f const &exe, operation_option_t option)
: super_class(std::make_unique<impl>(exe, std::move(option))) {
}
operation::operation(execution_f &&exe, operation_option_t opt)
: super_class(std::make_unique<impl>(std::move(exe), std::move(opt))) {
}
operation::operation(std::nullptr_t) : super_class(nullptr) {
}
void operation::cancel() {
_cancel();
}
bool operation::is_canceled() const {
return impl_ptr<impl>()->canceled;
}
operation_option_t const &operation::option() const {
return impl_ptr<impl>()->option;
}
void operation::_execute() {
if (auto &exe = impl_ptr<impl>()->execution) {
if (!is_canceled()) {
exe(*this);
}
}
}
void operation::_cancel() {
impl_ptr<impl>()->canceled = true;
}
#pragma mark - queue
class operation_queue::impl : public base::impl {
public:
impl(size_t const count) : _operations(count) {
}
~impl() {
cancel();
}
void push_back(operation &&op) {
std::lock_guard<std::recursive_mutex> lock(_mutex);
auto &dq = _operations.at(op.option().priority);
dq.emplace_back(std::move(op));
_start_next_operation_if_needed();
}
void push_front(operation &&op) {
std::lock_guard<std::recursive_mutex> lock(_mutex);
auto &dq = _operations.at(op.option().priority);
dq.emplace_front(std::move(op));
_start_next_operation_if_needed();
}
void cancel(operation const &operation) {
std::lock_guard<std::recursive_mutex> lock(_mutex);
for (auto &dq : _operations) {
for (auto &op : dq) {
if (operation == op) {
op.cancel();
}
}
}
if (_current_operation) {
if (_current_operation == operation) {
_current_operation.cancel();
}
}
}
void cancel() {
std::lock_guard<std::recursive_mutex> lock(_mutex);
for (auto &dq : _operations) {
for (auto &op : dq) {
op.cancel();
}
dq.clear();
}
if (_current_operation) {
_current_operation.cancel();
}
}
void wait_until_all_operations_are_finished() {
while (true) {
std::lock_guard<std::recursive_mutex> lock(_mutex);
bool op_exists = _current_operation != nullptr;
if (!op_exists) {
for (auto &dq : _operations) {
if (dq.size() > 0) {
op_exists = true;
}
}
}
if (op_exists) {
if (_suspended) {
throw "operation_queue is suspended.";
}
std::this_thread::yield();
} else {
break;
}
}
}
void suspend() {
std::lock_guard<std::recursive_mutex> lock(_mutex);
_suspended = true;
}
void resume() {
std::lock_guard<std::recursive_mutex> lock(_mutex);
if (_suspended) {
_suspended = false;
_start_next_operation_if_needed();
}
}
private:
operation _current_operation = nullptr;
std::vector<std::deque<operation>> _operations;
bool _suspended = false;
mutable std::recursive_mutex _mutex;
void _start_next_operation_if_needed() {
std::lock_guard<std::recursive_mutex> lock(_mutex);
if (!_current_operation && !_suspended) {
operation op{nullptr};
for (auto &dq : _operations) {
if (!dq.empty()) {
op = dq.front();
dq.pop_front();
break;
}
}
if (op) {
_current_operation = op;
auto weak_ope = to_weak(op);
auto weak_queue = to_weak(cast<operation_queue>());
std::thread thread{[weak_ope, weak_queue]() {
auto ope = weak_ope.lock();
if (ope) {
auto &ope_for_queue = static_cast<operation_controllable &>(ope);
ope_for_queue._execute();
if (auto queue = weak_queue.lock()) {
queue.impl_ptr<impl>()->_operation_did_finish(ope);
}
}
}};
thread.detach();
}
}
}
void _operation_did_finish(operation const &prev_op) {
std::lock_guard<std::recursive_mutex> lock(_mutex);
if (_current_operation == prev_op) {
_current_operation = nullptr;
}
_start_next_operation_if_needed();
}
};
operation_queue::operation_queue(size_t const count) : super_class(std::make_unique<impl>(count)) {
}
operation_queue::operation_queue(std::nullptr_t) : super_class(nullptr) {
}
void operation_queue::push_back(operation op) {
impl_ptr<impl>()->push_back(std::move(op));
}
void operation_queue::push_front(operation op) {
impl_ptr<impl>()->push_front(std::move(op));
}
void operation_queue::cancel(operation const &op) {
impl_ptr<impl>()->cancel(op);
}
void operation_queue::cancel() {
impl_ptr<impl>()->cancel();
}
void operation_queue::wait_until_all_operations_are_finished() {
impl_ptr<impl>()->wait_until_all_operations_are_finished();
}
void operation_queue::suspend() {
impl_ptr<impl>()->suspend();
}
void operation_queue::resume() {
impl_ptr<impl>()->resume();
}
<commit_msg>push cancel<commit_after>//
// yas_operation.cpp
//
#include <atomic>
#include <deque>
#include <mutex>
#include <thread>
#include <vector>
#include "yas_operation.h"
#include "yas_stl_utils.h"
using namespace yas;
#pragma mark - operation
class operation::impl : public base::impl {
public:
std::atomic<bool> canceled;
execution_f execution;
operation_option_t option;
impl(execution_f const &exe, operation_option_t &&option)
: canceled(false), execution(exe), option(std::move(option)) {
}
impl(execution_f &&exe, operation_option_t &&option)
: canceled(false), execution(std::move(exe)), option(std::move(option)) {
}
};
operation::operation(execution_f const &exe, operation_option_t option)
: super_class(std::make_unique<impl>(exe, std::move(option))) {
}
operation::operation(execution_f &&exe, operation_option_t opt)
: super_class(std::make_unique<impl>(std::move(exe), std::move(opt))) {
}
operation::operation(std::nullptr_t) : super_class(nullptr) {
}
void operation::cancel() {
_cancel();
}
bool operation::is_canceled() const {
return impl_ptr<impl>()->canceled;
}
operation_option_t const &operation::option() const {
return impl_ptr<impl>()->option;
}
void operation::_execute() {
if (auto &exe = impl_ptr<impl>()->execution) {
if (!is_canceled()) {
exe(*this);
}
}
}
void operation::_cancel() {
impl_ptr<impl>()->canceled = true;
}
#pragma mark - queue
class operation_queue::impl : public base::impl {
public:
impl(size_t const count) : _operations(count) {
}
~impl() {
cancel();
}
void push_back(operation &&op) {
std::lock_guard<std::recursive_mutex> lock(_mutex);
auto &cancel_id = op.option().push_cancel_id;
for (auto &dq : _operations) {
erase_if(dq, [&cancel_id](auto const &value) { return value.option().push_cancel_id == cancel_id; });
}
if (_current_operation) {
if (_current_operation.option().push_cancel_id == cancel_id) {
_current_operation.cancel();
}
}
auto &dq = _operations.at(op.option().priority);
dq.emplace_back(std::move(op));
_start_next_operation_if_needed();
}
void push_front(operation &&op) {
std::lock_guard<std::recursive_mutex> lock(_mutex);
auto &cancel_id = op.option().push_cancel_id;
for (auto &dq : _operations) {
erase_if(dq, [&cancel_id](auto const &value) { return value.option().push_cancel_id == cancel_id; });
}
if (_current_operation) {
if (_current_operation.option().push_cancel_id == cancel_id) {
_current_operation.cancel();
}
}
auto &dq = _operations.at(op.option().priority);
dq.emplace_front(std::move(op));
_start_next_operation_if_needed();
}
void cancel(operation const &operation) {
std::lock_guard<std::recursive_mutex> lock(_mutex);
for (auto &dq : _operations) {
for (auto &op : dq) {
if (operation == op) {
op.cancel();
}
}
}
if (_current_operation) {
if (_current_operation == operation) {
_current_operation.cancel();
}
}
}
void cancel() {
std::lock_guard<std::recursive_mutex> lock(_mutex);
for (auto &dq : _operations) {
for (auto &op : dq) {
op.cancel();
}
dq.clear();
}
if (_current_operation) {
_current_operation.cancel();
}
}
void wait_until_all_operations_are_finished() {
while (true) {
std::lock_guard<std::recursive_mutex> lock(_mutex);
bool op_exists = _current_operation != nullptr;
if (!op_exists) {
for (auto &dq : _operations) {
if (dq.size() > 0) {
op_exists = true;
}
}
}
if (op_exists) {
if (_suspended) {
throw "operation_queue is suspended.";
}
std::this_thread::yield();
} else {
break;
}
}
}
void suspend() {
std::lock_guard<std::recursive_mutex> lock(_mutex);
_suspended = true;
}
void resume() {
std::lock_guard<std::recursive_mutex> lock(_mutex);
if (_suspended) {
_suspended = false;
_start_next_operation_if_needed();
}
}
private:
operation _current_operation = nullptr;
std::vector<std::deque<operation>> _operations;
bool _suspended = false;
mutable std::recursive_mutex _mutex;
void _start_next_operation_if_needed() {
std::lock_guard<std::recursive_mutex> lock(_mutex);
if (!_current_operation && !_suspended) {
operation op{nullptr};
for (auto &dq : _operations) {
if (!dq.empty()) {
op = dq.front();
dq.pop_front();
break;
}
}
if (op) {
_current_operation = op;
auto weak_ope = to_weak(op);
auto weak_queue = to_weak(cast<operation_queue>());
std::thread thread{[weak_ope, weak_queue]() {
auto ope = weak_ope.lock();
if (ope) {
auto &ope_for_queue = static_cast<operation_controllable &>(ope);
ope_for_queue._execute();
if (auto queue = weak_queue.lock()) {
queue.impl_ptr<impl>()->_operation_did_finish(ope);
}
}
}};
thread.detach();
}
}
}
void _operation_did_finish(operation const &prev_op) {
std::lock_guard<std::recursive_mutex> lock(_mutex);
if (_current_operation == prev_op) {
_current_operation = nullptr;
}
_start_next_operation_if_needed();
}
};
operation_queue::operation_queue(size_t const count) : super_class(std::make_unique<impl>(count)) {
}
operation_queue::operation_queue(std::nullptr_t) : super_class(nullptr) {
}
void operation_queue::push_back(operation op) {
impl_ptr<impl>()->push_back(std::move(op));
}
void operation_queue::push_front(operation op) {
impl_ptr<impl>()->push_front(std::move(op));
}
void operation_queue::cancel(operation const &op) {
impl_ptr<impl>()->cancel(op);
}
void operation_queue::cancel() {
impl_ptr<impl>()->cancel();
}
void operation_queue::wait_until_all_operations_are_finished() {
impl_ptr<impl>()->wait_until_all_operations_are_finished();
}
void operation_queue::suspend() {
impl_ptr<impl>()->suspend();
}
void operation_queue::resume() {
impl_ptr<impl>()->resume();
}
<|endoftext|> |
<commit_before>/*Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include "paddle/fluid/operators/detection/density_prior_box_op.h"
namespace paddle {
namespace operators {
class DensityPriorBoxOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext* ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("Input"),
"Input(Input) of DensityPriorBoxOp should not be null.");
PADDLE_ENFORCE(ctx->HasInput("Image"),
"Input(Image) of DensityPriorBoxOp should not be null.");
auto image_dims = ctx->GetInputDim("Image");
auto input_dims = ctx->GetInputDim("Input");
PADDLE_ENFORCE(image_dims.size() == 4, "The layout of image is NCHW.");
PADDLE_ENFORCE(input_dims.size() == 4, "The layout of input is NCHW.");
PADDLE_ENFORCE_LT(input_dims[2], image_dims[2],
"The height of input must smaller than image.");
PADDLE_ENFORCE_LT(input_dims[3], image_dims[3],
"The width of input must smaller than image.");
auto variances = ctx->Attrs().Get<std::vector<float>>("variances");
auto fixed_sizes = ctx->Attrs().Get<std::vector<float>>("fixed_sizes");
auto fixed_ratios = ctx->Attrs().Get<std::vector<float>>("fixed_ratios");
auto densities = ctx->Attrs().Get<std::vector<int>>("densities");
bool flatten = ctx->Attrs().Get<bool>("flatten_to_2d");
PADDLE_ENFORCE_EQ(fixed_sizes.size(), densities.size(),
"The number of fixed_sizes and densities must be equal.");
size_t num_priors = 0;
for (size_t i = 0; i < densities.size(); ++i) {
num_priors += (fixed_ratios.size()) * (pow(densities[i], 2));
}
if (!flatten) {
std::vector<int64_t> dim_vec(4);
dim_vec[0] = input_dims[2];
dim_vec[1] = input_dims[3];
dim_vec[2] = num_priors;
dim_vec[3] = 4;
ctx->SetOutputDim("Boxes", framework::make_ddim(dim_vec));
ctx->SetOutputDim("Variances", framework::make_ddim(dim_vec));
} else {
int64_t dim0 = input_dims[2] * input_dims[3] * num_priors;
ctx->SetOutputDim("Boxes", {dim0, 4});
ctx->SetOutputDim("Variances", {dim0, 4});
}
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext& ctx) const override {
return framework::OpKernelType(
OperatorWithKernel::IndicateVarDataType(ctx, "Input"), ctx.GetPlace());
}
};
class DensityPriorBoxOpMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput(
"Input",
"(Tensor, default Tensor<float>), "
"the input feature data of DensityPriorBoxOp, the layout is NCHW.");
AddInput("Image",
"(Tensor, default Tensor<float>), "
"the input image data of DensityPriorBoxOp, the layout is NCHW.");
AddOutput("Boxes",
"(Tensor, default Tensor<float>), the output prior boxes of "
"DensityPriorBoxOp. The layout is [H, W, num_priors, 4]. "
"H is the height of input, W is the width of input, num_priors "
"is the box count of each position.");
AddOutput("Variances",
"(Tensor, default Tensor<float>), the expanded variances of "
"DensityPriorBoxOp. The layout is [H, W, num_priors, 4]. "
"H is the height of input, W is the width of input, num_priors "
"is the box count of each position.");
AddAttr<std::vector<float>>("variances",
"(vector<float>) List of variances to be "
"encoded in density prior boxes.")
.AddCustomChecker([](const std::vector<float>& variances) {
PADDLE_ENFORCE_EQ(variances.size(), 4,
"Must and only provide 4 variance.");
for (size_t i = 0; i < variances.size(); ++i) {
PADDLE_ENFORCE_GT(variances[i], 0.0,
"variance[%d] must be greater than 0.", i);
}
});
AddAttr<bool>("clip", "(bool) Whether to clip out-of-boundary boxes.")
.SetDefault(true);
AddAttr<bool>("flatten_to_2d",
"(bool) Whether to flatten to 2D and "
"the second dim is 4.")
.SetDefault(false);
AddAttr<float>(
"step_w",
"Density prior boxes step across width, 0.0 for auto calculation.")
.SetDefault(0.0)
.AddCustomChecker([](const float& step_w) {
PADDLE_ENFORCE_GE(step_w, 0.0, "step_w should be larger than 0.");
});
AddAttr<float>(
"step_h",
"Density prior boxes step across height, 0.0 for auto calculation.")
.SetDefault(0.0)
.AddCustomChecker([](const float& step_h) {
PADDLE_ENFORCE_GE(step_h, 0.0, "step_h should be larger than 0.");
});
AddAttr<float>("offset",
"(float) "
"Density prior boxes center offset.")
.SetDefault(0.5);
AddAttr<std::vector<float>>("fixed_sizes",
"(vector<float>) List of fixed sizes "
"of generated density prior boxes.")
.SetDefault(std::vector<float>{})
.AddCustomChecker([](const std::vector<float>& fixed_sizes) {
for (size_t i = 0; i < fixed_sizes.size(); ++i) {
PADDLE_ENFORCE_GT(fixed_sizes[i], 0.0,
"fixed_sizes[%d] should be larger than 0.", i);
}
});
AddAttr<std::vector<float>>("fixed_ratios",
"(vector<float>) List of fixed ratios "
"of generated density prior boxes.")
.SetDefault(std::vector<float>{})
.AddCustomChecker([](const std::vector<float>& fixed_ratios) {
for (size_t i = 0; i < fixed_ratios.size(); ++i) {
PADDLE_ENFORCE_GT(fixed_ratios[i], 0.0,
"fixed_ratios[%d] should be larger than 0.", i);
}
});
AddAttr<std::vector<int>>("densities",
"(vector<float>) List of densities "
"of generated density prior boxes.")
.SetDefault(std::vector<int>{})
.AddCustomChecker([](const std::vector<int>& densities) {
for (size_t i = 0; i < densities.size(); ++i) {
PADDLE_ENFORCE_GT(densities[i], 0,
"densities[%d] should be larger than 0.", i);
}
});
AddComment(R"DOC(
Density Prior box operator
Each position of the input produce N density prior boxes, N is determined by
the count of fixed_ratios, densities, the calculation of N is as follows:
for density in densities:
N += size(fixed_ratios)*density^2
)DOC");
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OPERATOR(
density_prior_box, ops::DensityPriorBoxOp, ops::DensityPriorBoxOpMaker,
paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>,
paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>);
REGISTER_OP_CPU_KERNEL(density_prior_box, ops::DensityPriorBoxOpKernel<float>,
ops::DensityPriorBoxOpKernel<double>);
<commit_msg>fix shape check in density_prior_box, test=develop (#21414)<commit_after>/*Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include "paddle/fluid/operators/detection/density_prior_box_op.h"
namespace paddle {
namespace operators {
class DensityPriorBoxOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext* ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("Input"),
"Input(Input) of DensityPriorBoxOp should not be null.");
PADDLE_ENFORCE(ctx->HasInput("Image"),
"Input(Image) of DensityPriorBoxOp should not be null.");
auto image_dims = ctx->GetInputDim("Image");
auto input_dims = ctx->GetInputDim("Input");
PADDLE_ENFORCE(image_dims.size() == 4, "The layout of image is NCHW.");
PADDLE_ENFORCE(input_dims.size() == 4, "The layout of input is NCHW.");
if (ctx->IsRuntime()) {
PADDLE_ENFORCE_LT(
input_dims[2], image_dims[2],
platform::errors::InvalidArgument(
"The input tensor Input's height"
"of DensityPriorBoxOp should be smaller than input tensor Image's"
"hight. But received Input's height = %d, Image's height = %d",
input_dims[2], image_dims[2]));
PADDLE_ENFORCE_LT(
input_dims[3], image_dims[3],
platform::errors::InvalidArgument(
"The input tensor Input's width"
"of DensityPriorBoxOp should be smaller than input tensor Image's"
"width. But received Input's width = %d, Image's width = %d",
input_dims[3], image_dims[3]));
}
auto variances = ctx->Attrs().Get<std::vector<float>>("variances");
auto fixed_sizes = ctx->Attrs().Get<std::vector<float>>("fixed_sizes");
auto fixed_ratios = ctx->Attrs().Get<std::vector<float>>("fixed_ratios");
auto densities = ctx->Attrs().Get<std::vector<int>>("densities");
bool flatten = ctx->Attrs().Get<bool>("flatten_to_2d");
PADDLE_ENFORCE_EQ(fixed_sizes.size(), densities.size(),
"The number of fixed_sizes and densities must be equal.");
size_t num_priors = 0;
for (size_t i = 0; i < densities.size(); ++i) {
num_priors += (fixed_ratios.size()) * (pow(densities[i], 2));
}
if (!flatten) {
std::vector<int64_t> dim_vec(4);
dim_vec[0] = input_dims[2];
dim_vec[1] = input_dims[3];
dim_vec[2] = num_priors;
dim_vec[3] = 4;
ctx->SetOutputDim("Boxes", framework::make_ddim(dim_vec));
ctx->SetOutputDim("Variances", framework::make_ddim(dim_vec));
} else if (ctx->IsRuntime()) {
int64_t dim0 = input_dims[2] * input_dims[3] * num_priors;
ctx->SetOutputDim("Boxes", {dim0, 4});
ctx->SetOutputDim("Variances", {dim0, 4});
} else {
ctx->SetOutputDim("Boxes", {-1, 4});
ctx->SetOutputDim("Variances", {-1, 4});
}
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext& ctx) const override {
return framework::OpKernelType(
OperatorWithKernel::IndicateVarDataType(ctx, "Input"), ctx.GetPlace());
}
};
class DensityPriorBoxOpMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput(
"Input",
"(Tensor, default Tensor<float>), "
"the input feature data of DensityPriorBoxOp, the layout is NCHW.");
AddInput("Image",
"(Tensor, default Tensor<float>), "
"the input image data of DensityPriorBoxOp, the layout is NCHW.");
AddOutput("Boxes",
"(Tensor, default Tensor<float>), the output prior boxes of "
"DensityPriorBoxOp. The layout is [H, W, num_priors, 4]. "
"H is the height of input, W is the width of input, num_priors "
"is the box count of each position.");
AddOutput("Variances",
"(Tensor, default Tensor<float>), the expanded variances of "
"DensityPriorBoxOp. The layout is [H, W, num_priors, 4]. "
"H is the height of input, W is the width of input, num_priors "
"is the box count of each position.");
AddAttr<std::vector<float>>("variances",
"(vector<float>) List of variances to be "
"encoded in density prior boxes.")
.AddCustomChecker([](const std::vector<float>& variances) {
PADDLE_ENFORCE_EQ(variances.size(), 4,
"Must and only provide 4 variance.");
for (size_t i = 0; i < variances.size(); ++i) {
PADDLE_ENFORCE_GT(variances[i], 0.0,
"variance[%d] must be greater than 0.", i);
}
});
AddAttr<bool>("clip", "(bool) Whether to clip out-of-boundary boxes.")
.SetDefault(true);
AddAttr<bool>("flatten_to_2d",
"(bool) Whether to flatten to 2D and "
"the second dim is 4.")
.SetDefault(false);
AddAttr<float>(
"step_w",
"Density prior boxes step across width, 0.0 for auto calculation.")
.SetDefault(0.0)
.AddCustomChecker([](const float& step_w) {
PADDLE_ENFORCE_GE(step_w, 0.0, "step_w should be larger than 0.");
});
AddAttr<float>(
"step_h",
"Density prior boxes step across height, 0.0 for auto calculation.")
.SetDefault(0.0)
.AddCustomChecker([](const float& step_h) {
PADDLE_ENFORCE_GE(step_h, 0.0, "step_h should be larger than 0.");
});
AddAttr<float>("offset",
"(float) "
"Density prior boxes center offset.")
.SetDefault(0.5);
AddAttr<std::vector<float>>("fixed_sizes",
"(vector<float>) List of fixed sizes "
"of generated density prior boxes.")
.SetDefault(std::vector<float>{})
.AddCustomChecker([](const std::vector<float>& fixed_sizes) {
for (size_t i = 0; i < fixed_sizes.size(); ++i) {
PADDLE_ENFORCE_GT(fixed_sizes[i], 0.0,
"fixed_sizes[%d] should be larger than 0.", i);
}
});
AddAttr<std::vector<float>>("fixed_ratios",
"(vector<float>) List of fixed ratios "
"of generated density prior boxes.")
.SetDefault(std::vector<float>{})
.AddCustomChecker([](const std::vector<float>& fixed_ratios) {
for (size_t i = 0; i < fixed_ratios.size(); ++i) {
PADDLE_ENFORCE_GT(fixed_ratios[i], 0.0,
"fixed_ratios[%d] should be larger than 0.", i);
}
});
AddAttr<std::vector<int>>("densities",
"(vector<float>) List of densities "
"of generated density prior boxes.")
.SetDefault(std::vector<int>{})
.AddCustomChecker([](const std::vector<int>& densities) {
for (size_t i = 0; i < densities.size(); ++i) {
PADDLE_ENFORCE_GT(densities[i], 0,
"densities[%d] should be larger than 0.", i);
}
});
AddComment(R"DOC(
Density Prior box operator
Each position of the input produce N density prior boxes, N is determined by
the count of fixed_ratios, densities, the calculation of N is as follows:
for density in densities:
N += size(fixed_ratios)*density^2
)DOC");
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OPERATOR(
density_prior_box, ops::DensityPriorBoxOp, ops::DensityPriorBoxOpMaker,
paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>,
paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>);
REGISTER_OP_CPU_KERNEL(density_prior_box, ops::DensityPriorBoxOpKernel<float>,
ops::DensityPriorBoxOpKernel<double>);
<|endoftext|> |
<commit_before>#ifndef CmdLineInterface_hpp
#define CmdLineInterface_hpp
#include "AppConfig.hpp"
class CmdLineInterface
{
private:
//void printUsage(std::string name);
AppConfig config;
public:
CmdLineInterface(int argc, char *argv[]);
AppConfig getConfig();
};
#endif /* CmdLineInterface_hpp */
<commit_msg>Deleting old files<commit_after><|endoftext|> |
<commit_before>#ifndef INCLUDE_ACKWARD_CORE_DETAIL_TUPLE_HPP
#define INCLUDE_ACKWARD_CORE_DETAIL_TUPLE_HPP
#include <boost/preprocessor/repetition/enum.hpp>
#include <boost/preprocessor/repetition/repeat_from_to.hpp>
#include <boost/python/extract.hpp>
#include <ackward/core/Util.hpp>
namespace ackward {
namespace core {
namespace detail {
/* These are the details of the tuple conversion process. See
* ackward/core/Tuple.hpp for the public functions.
*/
template <typename T, int Length>
class ConvertTuple {};
template <typename T>
struct ConvertTuple<T, 2>
{
T operator()(boost::python::tuple t)
{
return boost::make_tuple(
boost::python::extract<typename boost::tuples::element<0, T>::type>(
t[0])(),
boost::python::extract<typename boost::tuples::element<1, T>::type>(
t[1])());
}
boost::python::tuple operator()(const T& t)
{
return boost::python::make_tuple(
boost::tuples::get<0>(t),
boost::tuples::get<1>(t));
}
};
template <typename T>
struct ConvertTuple<T, 3>
{
T operator()(boost::python::tuple t)
{
return boost::make_tuple(
boost::python::extract<typename boost::tuples::element<0, T>::type>(
t[0])(),
boost::python::extract<typename boost::tuples::element<1, T>::type>(
t[1])(),
boost::python::extract<typename boost::tuples::element<2, T>::type>(
t[2])());
}
boost::python::tuple operator()(const T& t)
{
return boost::python::make_tuple(
boost::tuples::get<0>(t),
boost::tuples::get<1>(t),
boost::tuples::get<2>(t));
}
};
template <typename T>
struct ConvertTuple<T, 6>
{
T operator()(boost::python::tuple t)
{
return boost::make_tuple(
boost::python::extract<typename boost::tuples::element<0, T>::type>(
t[0])(),
boost::python::extract<typename boost::tuples::element<1, T>::type>(
t[1])(),
boost::python::extract<typename boost::tuples::element<2, T>::type>(
t[2])(),
boost::python::extract<typename boost::tuples::element<3, T>::type>(
t[3])(),
boost::python::extract<typename boost::tuples::element<4, T>::type>(
t[4])(),
boost::python::extract<typename boost::tuples::element<5, T>::type>(
t[5])());
}
boost::python::tuple operator()(const T& t)
{
return boost::python::make_tuple(
boost::tuples::get<0>(t),
boost::tuples::get<1>(t),
boost::tuples::get<2>(t),
boost::tuples::get<3>(t),
boost::tuples::get<4>(t),
boost::tuples::get<5>(t));
}
};
template <typename Tuple, int Size>
struct convert_tuple {
static PyObject* convert(const Tuple& t);
};
#define ACKWARD_CORE_TUPLE_CONVERT_ELEMENT_TO(z, n, _) boost::get<n>(t)
#define ACKWARD_CORE_TUPLE_CHECK_ELEMENT_CONVERTIBLE(z, n, _) \
{ \
PyObject* elem_ptr = PyTuple_GetItem(obj_ptr, n); \
\
if (!fromPythonConvertible<typename boost::tuples::element<n, Tuple>::type>(elem_ptr)) \
return 0; \
}
#define ACKWARD_CORE_TUPLE_CONVERT_ELEMENT_FROM(z, n, _) \
extract<typename boost::tuples::element<n, Tuple>::type>(object(handle<>(borrowed(PyTuple_GetItem(obj_ptr, n)))))
#define ACKWARD_CORE_CONVERT_TUPLE(z, size, _) \
template <typename Tuple> \
struct convert_tuple<Tuple, size> { \
static PyObject* convert(const Tuple& t) { \
using namespace boost::python; \
\
tuple rval = \
make_tuple( \
BOOST_PP_ENUM(size, ACKWARD_CORE_TUPLE_CONVERT_ELEMENT_TO, _) \
); \
\
return incref(rval.ptr()); \
} \
\
static void* convertible(PyObject* obj_ptr) { \
using namespace boost::python; \
\
if (!PyTuple_Check(obj_ptr)) return 0; \
if (!PyTuple_Size(obj_ptr) == size) return 0; \
\
BOOST_PP_REPEAT(size, ACKWARD_CORE_TUPLE_CHECK_ELEMENT_CONVERTIBLE, _) \
\
return obj_ptr; \
} \
\
static void construct( \
PyObject* obj_ptr, \
boost::python::converter::rvalue_from_python_stage1_data* data) \
{ \
using namespace boost::python; \
\
void* storage = ( \
(converter::rvalue_from_python_storage<Tuple>*) \
data)->storage.bytes; \
\
new (storage) Tuple( \
BOOST_PP_ENUM(size, ACKWARD_CORE_TUPLE_CONVERT_ELEMENT_FROM, _) \
); \
\
data->convertible = storage; \
} \
};
#ifndef ACKWARD_CORE_TUPLE_CONVERTER_SIZE_LIMIT
#define ACKWARD_CORE_TUPLE_CONVERTER_SIZE_LIMIT 11
#endif
BOOST_PP_REPEAT_FROM_TO(1, ACKWARD_CORE_TUPLE_CONVERTER_SIZE_LIMIT, ACKWARD_CORE_CONVERT_TUPLE, _)
} // namespace detail
} // namespace core
} // namespace ackward
#endif
<commit_msg>cleanup<commit_after>#ifndef INCLUDE_ACKWARD_CORE_DETAIL_TUPLE_HPP
#define INCLUDE_ACKWARD_CORE_DETAIL_TUPLE_HPP
#include <boost/preprocessor/repetition/enum.hpp>
#include <boost/preprocessor/repetition/repeat_from_to.hpp>
#include <boost/python/extract.hpp>
#include <ackward/core/Util.hpp>
namespace ackward {
namespace core {
namespace detail {
#ifndef ACKWARD_CORE_TUPLE_CONVERTER_SIZE_LIMIT
#define ACKWARD_CORE_TUPLE_CONVERTER_SIZE_LIMIT 11
#endif
#define ACKWARD_CORE_DETAIL_TUPLE_CONVERT_ELEMENT_FROM_PYOBJECT(z, n, _) \
extract<typename boost::tuples::element<n, Tuple>::type>(object(handle<>(borrowed(PyTuple_GetItem(obj_ptr, n)))))
#define ACKWARD_CORE_DETAIL_GET_TUPLE_ELEMENT_CPP(z, n, _) boost::get<n>(t)
/* These are the details of the tuple conversion process. See
* ackward/core/Tuple.hpp for the public functions.
*/
template <typename T, int Length>
class ConvertTuple {};
template <typename T>
struct ConvertTuple<T, 2>
{
T operator()(boost::python::tuple t)
{
return boost::make_tuple(
boost::python::extract<typename boost::tuples::element<0, T>::type>(
t[0])(),
boost::python::extract<typename boost::tuples::element<1, T>::type>(
t[1])());
}
boost::python::tuple operator()(const T& t)
{
return boost::python::make_tuple(
boost::tuples::get<0>(t),
boost::tuples::get<1>(t));
}
};
template <typename T>
struct ConvertTuple<T, 3>
{
T operator()(boost::python::tuple t)
{
return boost::make_tuple(
boost::python::extract<typename boost::tuples::element<0, T>::type>(
t[0])(),
boost::python::extract<typename boost::tuples::element<1, T>::type>(
t[1])(),
boost::python::extract<typename boost::tuples::element<2, T>::type>(
t[2])());
}
boost::python::tuple operator()(const T& t)
{
return boost::python::make_tuple(
boost::tuples::get<0>(t),
boost::tuples::get<1>(t),
boost::tuples::get<2>(t));
}
};
template <typename T>
struct ConvertTuple<T, 6>
{
T operator()(boost::python::tuple t)
{
return boost::make_tuple(
boost::python::extract<typename boost::tuples::element<0, T>::type>(
t[0])(),
boost::python::extract<typename boost::tuples::element<1, T>::type>(
t[1])(),
boost::python::extract<typename boost::tuples::element<2, T>::type>(
t[2])(),
boost::python::extract<typename boost::tuples::element<3, T>::type>(
t[3])(),
boost::python::extract<typename boost::tuples::element<4, T>::type>(
t[4])(),
boost::python::extract<typename boost::tuples::element<5, T>::type>(
t[5])());
}
boost::python::tuple operator()(const T& t)
{
return boost::python::make_tuple(
boost::tuples::get<0>(t),
boost::tuples::get<1>(t),
boost::tuples::get<2>(t),
boost::tuples::get<3>(t),
boost::tuples::get<4>(t),
boost::tuples::get<5>(t));
}
};
template <typename Tuple, int Size>
struct convert_tuple {
static PyObject* convert(const Tuple& t);
};
#define ACKWARD_CORE_DETAIL_TUPLE_CHECK_ELEMENT_CONVERTIBLE(z, n, _) \
{ \
PyObject* elem_ptr = PyTuple_GetItem(obj_ptr, n); \
\
if (!fromPythonConvertible<typename boost::tuples::element<n, Tuple>::type>(elem_ptr)) \
return 0; \
}
#define ACKWARD_CORE_DETAIL_AUTO_CONVERT_TUPLE(z, size, _) \
template <typename Tuple> \
struct convert_tuple<Tuple, size> { \
static PyObject* convert(const Tuple& t) { \
using namespace boost::python; \
\
tuple rval = \
make_tuple( \
BOOST_PP_ENUM(size, ACKWARD_CORE_DETAIL_GET_TUPLE_ELEMENT_CPP, _) \
); \
\
return incref(rval.ptr()); \
} \
\
static void* convertible(PyObject* obj_ptr) { \
using namespace boost::python; \
\
if (!PyTuple_Check(obj_ptr)) return 0; \
if (!PyTuple_Size(obj_ptr) == size) return 0; \
\
BOOST_PP_REPEAT(size, ACKWARD_CORE_DETAIL_TUPLE_CHECK_ELEMENT_CONVERTIBLE, _) \
\
return obj_ptr; \
} \
\
static void construct( \
PyObject* obj_ptr, \
boost::python::converter::rvalue_from_python_stage1_data* data) \
{ \
using namespace boost::python; \
\
void* storage = ( \
(converter::rvalue_from_python_storage<Tuple>*) \
data)->storage.bytes; \
\
new (storage) Tuple( \
BOOST_PP_ENUM(size, ACKWARD_CORE_DETAIL_TUPLE_CONVERT_ELEMENT_FROM_PYOBJECT, _) \
); \
\
data->convertible = storage; \
} \
};
BOOST_PP_REPEAT_FROM_TO(1, ACKWARD_CORE_TUPLE_CONVERTER_SIZE_LIMIT, ACKWARD_CORE_DETAIL_AUTO_CONVERT_TUPLE, _)
} // namespace detail
} // namespace core
} // namespace ackward
#endif
<|endoftext|> |
<commit_before>/* opendatacon
*
* Copyright (c) 2014:
*
* DCrip3fJguWgVCLrZFfA7sIGgvx1Ou3fHfCxnrz4svAi
* yxeOtDhDCXf1Z4ApgXvX5ahqQmzRfJ2DoX8S05SqHA==
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* DataConcentrator.cpp
*
* Created on: 15/07/2014
* Author: Neil Stephens <[email protected]>
*/
#include <dlfcn.h>
#include <thread>
#include <asio.hpp>
#include <opendnp3/LogLevels.h>
#include "DataConcentrator.h"
#include "Console.h"
#include <asiodnp3/ConsoleLogger.h>
#include "logging_cmds.h"
#include "DNP3OutstationPort.h"
#include "DNP3MasterPort.h"
#include "../JSONPort/JSONClientPort.h"
#include "NullPort.h"
DataConcentrator::DataConcentrator(std::string FileName):
DNP3Mgr(std::thread::hardware_concurrency()),
LOG_LEVEL(opendnp3::levels::NORMAL),
AdvConsoleLog(asiodnp3::ConsoleLogger::Instance(),LOG_LEVEL),
FileLog("datacon_log"),
AdvFileLog(FileLog,LOG_LEVEL),
IOS(std::thread::hardware_concurrency()),
ios_working(new asio::io_service::work(IOS))
{
//fire up some worker threads
for(size_t i=0; i < std::thread::hardware_concurrency(); ++i)
std::thread([&](){IOS.run();}).detach();
AdvConsoleLog.AddIngoreAlways(".*"); //silence all console messages by default
DNP3Mgr.AddLogSubscriber(&AdvConsoleLog);
DNP3Mgr.AddLogSubscriber(&AdvFileLog);
//Parse the configs and create all the ports and connections
ProcessFile(FileName);
for(auto& port : DataPorts)
{
port.second->AddLogSubscriber(&AdvConsoleLog);
port.second->AddLogSubscriber(&AdvFileLog);
port.second->SetIOS(&IOS);
port.second->SetLogLevel(LOG_LEVEL);
}
for(auto& conn : DataConnectors)
{
conn.second->AddLogSubscriber(&AdvConsoleLog);
conn.second->AddLogSubscriber(&AdvFileLog);
conn.second->SetIOS(&IOS);
conn.second->SetLogLevel(LOG_LEVEL);
}
}
DataConcentrator::~DataConcentrator()
{
//turn everything off
this->Shutdown();
DNP3Mgr.Shutdown();
//tell the io service to let it's run functions return once there's no handlers left (letting our threads end)
ios_working.reset();
//help finish any work
IOS.run();
}
void DataConcentrator::ProcessElements(const Json::Value& JSONRoot)
{
if(!JSONRoot["LogFileSizekB"].isNull())
FileLog.SetLogFileSizekB(JSONRoot["LogFileSizekB"].asUInt());
if(!JSONRoot["NumLogFiles"].isNull())
FileLog.SetNumLogFiles(JSONRoot["NumLogFiles"].asUInt());
if(!JSONRoot["LogName"].isNull())
FileLog.SetLogName(JSONRoot["LogName"].asString());
if(!JSONRoot["LOG_LEVEL"].isNull())
{
std::string value = JSONRoot["LOG_LEVEL"].asString();
if(value == "ALL")
LOG_LEVEL = opendnp3::levels::ALL;
else if(value == "ALL_COMMS")
LOG_LEVEL = opendnp3::levels::ALL_COMMS;
else if(value == "NORMAL")
LOG_LEVEL = opendnp3::levels::NORMAL;
else if(value == "NOTHING")
LOG_LEVEL = opendnp3::levels::NOTHING;
else
std::cout << "Warning: invalid LOG_LEVEL setting: '" << value << "' : ignoring and using 'NORMAL' log level." << std::endl;
AdvFileLog.SetLogLevel(LOG_LEVEL);
AdvConsoleLog.SetLogLevel(LOG_LEVEL);
}
if(!JSONRoot["Ports"].isNull())
{
const Json::Value Ports = JSONRoot["Ports"];
for(Json::Value::ArrayIndex n = 0; n < Ports.size(); ++n)
{
if(Ports[n]["Type"].isNull() || Ports[n]["Name"].isNull() || Ports[n]["ConfFilename"].isNull())
{
std::cout<<"Warning: invalid port config: need at least Type, Name, ConfFilename: \n'"<<Ports[n].toStyledString()<<"\n' : ignoring"<<std::endl;
}
if(Ports[n]["Type"].asString() == "DNP3Outstation")
{
DataPorts[Ports[n]["Name"].asString()] = std::unique_ptr<DataPort>(new DNP3OutstationPort(Ports[n]["Name"].asString(), Ports[n]["ConfFilename"].asString(), Ports[n]["ConfOverrides"].asString()));
}
else if(Ports[n]["Type"].asString() == "DNP3Master")
{
DataPorts[Ports[n]["Name"].asString()] = std::unique_ptr<DataPort>(new DNP3MasterPort(Ports[n]["Name"].asString(), Ports[n]["ConfFilename"].asString(), Ports[n]["ConfOverrides"].asString()));
}
else if(Ports[n]["Type"].asString() == "Null")
{
DataPorts[Ports[n]["Name"].asString()] = std::unique_ptr<DataPort>(new NullPort(Ports[n]["Name"].asString(), Ports[n]["ConfFilename"].asString(), Ports[n]["ConfOverrides"].asString()));
}
else
{
std::string libname;
if(Ports[n]["Library"].isNull())
{
libname = "lib"+Ports[n]["Type"].asString()+"Port.so";
}
else
{
libname = "lib"+Ports[n]["Library"].asString()+".so";
}
void* portlib = dlopen(libname.c_str(),RTLD_LAZY);
if(portlib == nullptr)
{
std::cout << "Warning: failed to load library '"<<libname<<"' skipping port..."<<std::endl;
continue;
}
std::string new_funcname = "new_"+Ports[n]["Type"].asString()+"Port";
auto new_port_func = (DataPort*(*)(std::string,std::string,std::string))dlsym(portlib, new_funcname.c_str());
if(new_port_func == nullptr)
{
std::cout << "Warning: failed to load symbol '"<<new_funcname<<"' for port type '"<<Ports[n]["Type"].asString()<<"' skipping port..."<<std::endl;
continue;
}
DataPorts[Ports[n]["Name"].asString()] = std::unique_ptr<DataPort>(new_port_func(Ports[n]["Name"].asString(), Ports[n]["ConfFilename"].asString(), Ports[n]["ConfOverrides"].asString()));
}
}
}
if(!JSONRoot["Connectors"].isNull())
{
const Json::Value Connectors = JSONRoot["Connectors"];
for(Json::Value::ArrayIndex n = 0; n < Connectors.size(); ++n)
{
if(Connectors[n]["Name"].isNull() || Connectors[n]["ConfFilename"].isNull())
{
std::cout<<"Warning: invalid Connector config: need at least Name, ConfFilename: \n'"<<Connectors[n].toStyledString()<<"\n' : ignoring"<<std::endl;
}
DataConnectors[Connectors[n]["Name"].asString()] = std::unique_ptr<DataConnector>(new DataConnector(Connectors[n]["Name"].asString(), Connectors[n]["ConfFilename"].asString(), Connectors[n]["ConfOverrides"].asString()));
}
}
}
void DataConcentrator::BuildOrRebuild()
{
for(auto& Name_n_Port : DataPorts)
{
Name_n_Port.second->BuildOrRebuild(DNP3Mgr,LOG_LEVEL);
}
for(auto& Name_n_Conn : DataConnectors)
{
Name_n_Conn.second->BuildOrRebuild(DNP3Mgr,LOG_LEVEL);
}
}
void DataConcentrator::Run()
{
for(auto& Name_n_Conn : DataConnectors)
{
IOS.post([=]()
{
Name_n_Conn.second->Enable();
});
}
for(auto& Name_n_Port : DataPorts)
{
IOS.post([=]()
{
Name_n_Port.second->Enable();
});
}
Console console("odc> ");
std::function<void (std::stringstream&)> bound_func;
//console logging control
bound_func = std::bind(cmd_ignore_message,std::placeholders::_1,std::ref(AdvConsoleLog));
console.AddCmd("ignore_message",bound_func,"Enter regex to silence matching messages from the console logger.");
bound_func = std::bind(cmd_unignore_message,std::placeholders::_1,std::ref(AdvConsoleLog));
console.AddCmd("unignore_message",bound_func,"Enter regex to remove from the console ignore list.");
bound_func = std::bind(cmd_show_ignored,std::placeholders::_1,std::ref(AdvConsoleLog));
console.AddCmd("show_ignored",bound_func,"Shows all console message ignore regexes and how many messages they've matched.");
//file logging control
bound_func = std::bind(cmd_ignore_message,std::placeholders::_1,std::ref(AdvFileLog));
console.AddCmd("ignore_file_message",bound_func,"Enter regex to silence matching messages from the file logger.");
bound_func = std::bind(cmd_unignore_message,std::placeholders::_1,std::ref(AdvFileLog));
console.AddCmd("unignore_file_message",bound_func,"Enter regex to remove from the file ignore list.");
bound_func = std::bind(cmd_show_ignored,std::placeholders::_1,std::ref(AdvFileLog));
console.AddCmd("show_file_ignored",bound_func,"Shows all file message ignore regexes and how many messages they've matched.");
console.run();
Shutdown();
}
void DataConcentrator::Shutdown()
{
for(auto& Name_n_Port : DataPorts)
{
Name_n_Port.second->Disable();
}
for(auto& Name_n_Conn : DataConnectors)
{
Name_n_Conn.second->Disable();
}
}
<commit_msg>Added some comments to the dynamic loading of DataPort libs<commit_after>/* opendatacon
*
* Copyright (c) 2014:
*
* DCrip3fJguWgVCLrZFfA7sIGgvx1Ou3fHfCxnrz4svAi
* yxeOtDhDCXf1Z4ApgXvX5ahqQmzRfJ2DoX8S05SqHA==
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* DataConcentrator.cpp
*
* Created on: 15/07/2014
* Author: Neil Stephens <[email protected]>
*/
#include <dlfcn.h>
#include <thread>
#include <asio.hpp>
#include <opendnp3/LogLevels.h>
#include "DataConcentrator.h"
#include "Console.h"
#include <asiodnp3/ConsoleLogger.h>
#include "logging_cmds.h"
#include "DNP3OutstationPort.h"
#include "DNP3MasterPort.h"
#include "../JSONPort/JSONClientPort.h"
#include "NullPort.h"
DataConcentrator::DataConcentrator(std::string FileName):
DNP3Mgr(std::thread::hardware_concurrency()),
LOG_LEVEL(opendnp3::levels::NORMAL),
AdvConsoleLog(asiodnp3::ConsoleLogger::Instance(),LOG_LEVEL),
FileLog("datacon_log"),
AdvFileLog(FileLog,LOG_LEVEL),
IOS(std::thread::hardware_concurrency()),
ios_working(new asio::io_service::work(IOS))
{
//fire up some worker threads
for(size_t i=0; i < std::thread::hardware_concurrency(); ++i)
std::thread([&](){IOS.run();}).detach();
AdvConsoleLog.AddIngoreAlways(".*"); //silence all console messages by default
DNP3Mgr.AddLogSubscriber(&AdvConsoleLog);
DNP3Mgr.AddLogSubscriber(&AdvFileLog);
//Parse the configs and create all the ports and connections
ProcessFile(FileName);
for(auto& port : DataPorts)
{
port.second->AddLogSubscriber(&AdvConsoleLog);
port.second->AddLogSubscriber(&AdvFileLog);
port.second->SetIOS(&IOS);
port.second->SetLogLevel(LOG_LEVEL);
}
for(auto& conn : DataConnectors)
{
conn.second->AddLogSubscriber(&AdvConsoleLog);
conn.second->AddLogSubscriber(&AdvFileLog);
conn.second->SetIOS(&IOS);
conn.second->SetLogLevel(LOG_LEVEL);
}
}
DataConcentrator::~DataConcentrator()
{
//turn everything off
this->Shutdown();
DNP3Mgr.Shutdown();
//tell the io service to let it's run functions return once there's no handlers left (letting our threads end)
ios_working.reset();
//help finish any work
IOS.run();
}
void DataConcentrator::ProcessElements(const Json::Value& JSONRoot)
{
if(!JSONRoot["LogFileSizekB"].isNull())
FileLog.SetLogFileSizekB(JSONRoot["LogFileSizekB"].asUInt());
if(!JSONRoot["NumLogFiles"].isNull())
FileLog.SetNumLogFiles(JSONRoot["NumLogFiles"].asUInt());
if(!JSONRoot["LogName"].isNull())
FileLog.SetLogName(JSONRoot["LogName"].asString());
if(!JSONRoot["LOG_LEVEL"].isNull())
{
std::string value = JSONRoot["LOG_LEVEL"].asString();
if(value == "ALL")
LOG_LEVEL = opendnp3::levels::ALL;
else if(value == "ALL_COMMS")
LOG_LEVEL = opendnp3::levels::ALL_COMMS;
else if(value == "NORMAL")
LOG_LEVEL = opendnp3::levels::NORMAL;
else if(value == "NOTHING")
LOG_LEVEL = opendnp3::levels::NOTHING;
else
std::cout << "Warning: invalid LOG_LEVEL setting: '" << value << "' : ignoring and using 'NORMAL' log level." << std::endl;
AdvFileLog.SetLogLevel(LOG_LEVEL);
AdvConsoleLog.SetLogLevel(LOG_LEVEL);
}
if(!JSONRoot["Ports"].isNull())
{
const Json::Value Ports = JSONRoot["Ports"];
for(Json::Value::ArrayIndex n = 0; n < Ports.size(); ++n)
{
if(Ports[n]["Type"].isNull() || Ports[n]["Name"].isNull() || Ports[n]["ConfFilename"].isNull())
{
std::cout<<"Warning: invalid port config: need at least Type, Name, ConfFilename: \n'"<<Ports[n].toStyledString()<<"\n' : ignoring"<<std::endl;
}
if(Ports[n]["Type"].asString() == "DNP3Outstation")
{
DataPorts[Ports[n]["Name"].asString()] = std::unique_ptr<DataPort>(new DNP3OutstationPort(Ports[n]["Name"].asString(), Ports[n]["ConfFilename"].asString(), Ports[n]["ConfOverrides"].asString()));
}
else if(Ports[n]["Type"].asString() == "DNP3Master")
{
DataPorts[Ports[n]["Name"].asString()] = std::unique_ptr<DataPort>(new DNP3MasterPort(Ports[n]["Name"].asString(), Ports[n]["ConfFilename"].asString(), Ports[n]["ConfOverrides"].asString()));
}
else if(Ports[n]["Type"].asString() == "Null")
{
DataPorts[Ports[n]["Name"].asString()] = std::unique_ptr<DataPort>(new NullPort(Ports[n]["Name"].asString(), Ports[n]["ConfFilename"].asString(), Ports[n]["ConfOverrides"].asString()));
}
else
{
//Looks for a specific library (for libs that implement more than one class)
std::string libname;
if(!Ports[n]["Library"].isNull())
{
libname = "lib"+Ports[n]["Library"].asString()+".so";
}
//Otherwise use the naming convention lib<Type>Port.so to find the default lib that implements a type of port
else
{
libname = "lib"+Ports[n]["Type"].asString()+"Port.so";
}
//try to load the lib
void* portlib = dlopen(libname.c_str(),RTLD_LAZY);
if(portlib == nullptr)
{
std::cout << "Warning: failed to load library '"<<libname<<"' skipping port..."<<std::endl;
continue;
}
//Our API says the library should export a creation function: DataPort* new_<Type>Port(Name, Filename, Overrides)
//it should return a pointer to a heap allocated instance of a descendant of DataPort
std::string new_funcname = "new_"+Ports[n]["Type"].asString()+"Port";
auto new_port_func = (DataPort*(*)(std::string,std::string,std::string))dlsym(portlib, new_funcname.c_str());
if(new_port_func == nullptr)
{
std::cout << "Warning: failed to load symbol '"<<new_funcname<<"' for port type '"<<Ports[n]["Type"].asString()<<"' skipping port..."<<std::endl;
continue;
}
//call the creation function and wrap the returned pointer to a new port
DataPorts[Ports[n]["Name"].asString()] = std::unique_ptr<DataPort>(new_port_func(Ports[n]["Name"].asString(), Ports[n]["ConfFilename"].asString(), Ports[n]["ConfOverrides"].asString()));
}
}
}
if(!JSONRoot["Connectors"].isNull())
{
const Json::Value Connectors = JSONRoot["Connectors"];
for(Json::Value::ArrayIndex n = 0; n < Connectors.size(); ++n)
{
if(Connectors[n]["Name"].isNull() || Connectors[n]["ConfFilename"].isNull())
{
std::cout<<"Warning: invalid Connector config: need at least Name, ConfFilename: \n'"<<Connectors[n].toStyledString()<<"\n' : ignoring"<<std::endl;
}
DataConnectors[Connectors[n]["Name"].asString()] = std::unique_ptr<DataConnector>(new DataConnector(Connectors[n]["Name"].asString(), Connectors[n]["ConfFilename"].asString(), Connectors[n]["ConfOverrides"].asString()));
}
}
}
void DataConcentrator::BuildOrRebuild()
{
for(auto& Name_n_Port : DataPorts)
{
Name_n_Port.second->BuildOrRebuild(DNP3Mgr,LOG_LEVEL);
}
for(auto& Name_n_Conn : DataConnectors)
{
Name_n_Conn.second->BuildOrRebuild(DNP3Mgr,LOG_LEVEL);
}
}
void DataConcentrator::Run()
{
for(auto& Name_n_Conn : DataConnectors)
{
IOS.post([=]()
{
Name_n_Conn.second->Enable();
});
}
for(auto& Name_n_Port : DataPorts)
{
IOS.post([=]()
{
Name_n_Port.second->Enable();
});
}
Console console("odc> ");
std::function<void (std::stringstream&)> bound_func;
//console logging control
bound_func = std::bind(cmd_ignore_message,std::placeholders::_1,std::ref(AdvConsoleLog));
console.AddCmd("ignore_message",bound_func,"Enter regex to silence matching messages from the console logger.");
bound_func = std::bind(cmd_unignore_message,std::placeholders::_1,std::ref(AdvConsoleLog));
console.AddCmd("unignore_message",bound_func,"Enter regex to remove from the console ignore list.");
bound_func = std::bind(cmd_show_ignored,std::placeholders::_1,std::ref(AdvConsoleLog));
console.AddCmd("show_ignored",bound_func,"Shows all console message ignore regexes and how many messages they've matched.");
//file logging control
bound_func = std::bind(cmd_ignore_message,std::placeholders::_1,std::ref(AdvFileLog));
console.AddCmd("ignore_file_message",bound_func,"Enter regex to silence matching messages from the file logger.");
bound_func = std::bind(cmd_unignore_message,std::placeholders::_1,std::ref(AdvFileLog));
console.AddCmd("unignore_file_message",bound_func,"Enter regex to remove from the file ignore list.");
bound_func = std::bind(cmd_show_ignored,std::placeholders::_1,std::ref(AdvFileLog));
console.AddCmd("show_file_ignored",bound_func,"Shows all file message ignore regexes and how many messages they've matched.");
console.run();
Shutdown();
}
void DataConcentrator::Shutdown()
{
for(auto& Name_n_Port : DataPorts)
{
Name_n_Port.second->Disable();
}
for(auto& Name_n_Conn : DataConnectors)
{
Name_n_Conn.second->Disable();
}
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "rvdbg.h"
BOOLEAN tDSend;
static void HandleSSE()
{
if (r_registers.bxmm0 == 1)
__asm movsd xmm0, r_registers.dxmm0;
else if (r_registers.bxmm0 == 2)
__asm movss xmm0, r_registers.xmm0;
if (r_registers.bxmm1)
__asm movsd xmm1, r_registers.dxmm1;
else if (r_registers.bxmm1 == 2)
__asm movss xmm1, r_registers.xmm1;
if (r_registers.bxmm2)
__asm movsd xmm2, r_registers.dxmm2;
else if (r_registers.bxmm2 == 2)
__asm movss xmm2, r_registers.xmm2;
if (r_registers.bxmm3)
__asm movsd xmm3, r_registers.dxmm3;
else if (r_registers.bxmm3 == 2)
__asm movss xmm3, r_registers.xmm3;
if (r_registers.bxmm4)
__asm movsd xmm4, r_registers.dxmm4;
else if (r_registers.bxmm4 == 2)
__asm movss xmm4, r_registers.xmm4;
if (r_registers.bxmm5)
__asm movsd xmm5, r_registers.dxmm5;
else if (r_registers.bxmm5 == 2)
__asm movss xmm5, r_registers.xmm5;
if (r_registers.bxmm6)
__asm movsd xmm6, r_registers.dxmm6;
else if (r_registers.bxmm6 == 2)
__asm movss xmm6, r_registers.xmm6;
if (r_registers.bxmm7)
__asm movsd xmm7, r_registers.dxmm7;
else if (r_registers.bxmm7 == 2)
__asm movss xmm7, r_registers.xmm7;
r_registers.bxmm0 = 0;
r_registers.bxmm1 = 0;
r_registers.bxmm2 = 0;
r_registers.bxmm3 = 0;
r_registers.bxmm4 = 0;
r_registers.bxmm5 = 0;
r_registers.bxmm6 = 0;
r_registers.bxmm7 = 0;
}
static PVOID CallChain()
{
size_t ExceptionElement = SearchSector(Sector, 128, ExceptionComparator);
if (ExceptionElement > 128)
{
if (ExceptionMode == 2)
{
SuspendThreads(GetCurrentProcessId(), GetCurrentThreadId());
DWORD swap_ad = SwapAccess(AccessException, AccessException);
if (!swap_ad)
{
ChunkExecutable = FALSE;
return NULL;
}
Swaps.push_back((PVOID)swap_ad);
return (PVOID)swap_ad;
}
return NULL;
}
SuspendThreads(GetCurrentProcessId(), GetCurrentThreadId());
Debugger = TRUE;
tDSend = TRUE;
for (size_t iterator = 0; iterator < sizeof(Threads); iterator++)
{
if (Threads[iterator] != NULL)
ResumeThread(Threads[iterator]);
}
Sector[ExceptionElement].ExceptionCode = ExceptionCode;
PVOID ReturnException = HandleException(Sector[ExceptionElement], Sector[ExceptionElement].ModuleName);
r_registers.eip = ReturnException;
Sector[ExceptionElement].Thread = GetCurrentThread();
Sector[ExceptionElement].IsAEHPresent = TRUE;
Sector[ExceptionElement].ReturnAddress = r_registers.ReturnAddress;
CurrentPool = Sector[ExceptionElement];
EnterCriticalSection(&RunLock);
SleepConditionVariableCS(&Runnable, &RunLock, INFINITE);
LeaveCriticalSection(&RunLock);
ResumeThreads(GetCurrentProcessId(), GetCurrentThreadId());
UnlockSector(Sector, ExceptionElement);
return r_registers.eip;
}
static __declspec(naked) VOID NTAPI KiUserExceptionDispatcher(PEXCEPTION_RECORD ExceptionRecord, PCONTEXT Context)
{
__asm
{
movss r_registers.xmm0, xmm0;
movss r_registers.xmm1, xmm1;
movss r_registers.xmm2, xmm2;
movss r_registers.xmm3, xmm3;
movss r_registers.xmm4, xmm4;
movss r_registers.xmm5, xmm5;
movss r_registers.xmm6, xmm6;
movss r_registers.xmm7, xmm7;
movsd r_registers.dxmm0, xmm0;
movsd r_registers.dxmm1, xmm1;
movsd r_registers.dxmm2, xmm2;
movsd r_registers.dxmm3, xmm3;
movsd r_registers.dxmm4, xmm4;
movsd r_registers.dxmm5, xmm5;
movsd r_registers.dxmm6, xmm6;
movsd r_registers.dxmm7, xmm7;
mov r_registers.eax, eax;
mov r_registers.ebx, ebx;
mov r_registers.ecx, ecx;
mov r_registers.edx, edx;
mov r_registers.esi, esi;
mov r_registers.edi, edi;
mov r_registers.ebp, ebp;
mov eax, [esp + 0x11c]; // Reserved former esp
mov r_registers.esp, eax;
mov eax, [eax];
mov r_registers.ReturnAddress, eax;
mov eax, [esp + 0x14]; // [esp + 0x14] contains the exception address
mov[ExceptionComparator], eax; // move into the exception comparator, aka the address to be compared with the exception address
mov eax, [esp + 0x08]; // [esp + 0x0C] contains the exception code
mov[ExceptionCode], eax; // move into the ExceptionCode global.
mov eax, [esp + 20]; // when access exceptions are enabled, move the accessed memoryh ere
mov[AccessException], eax;
}
Decision = (PVOID)CallChain(); // Initiate the CallChain function
if (!Decision) // if the decision is null, then jump back to the real dispatcher
{
__asm
{
mov eax, r_registers.eax;
mov ecx, [esp + 04];
mov ebx, [esp];
jmp KiUserRealDispatcher;
}
}
if (r_registers.SSESet == TRUE)
HandleSSE();
r_registers.SSESet = FALSE;
__asm
{
mov eax, r_registers.eax;
mov ebx, r_registers.ebx;
mov ecx, r_registers.ecx;
mov edx, r_registers.edx;
mov esi, r_registers.esi;
mov edi, r_registers.edi;
mov esp, r_registers.esp; // [esp + 0x11c] contains stack initation information such as the return address, arguments, etc...
jmp Decision; // jump to the catch block
}
}
static void SetKiUser()
{
KiUser = (PVOID)GetProcAddress(GetModuleHandleA("ntdll.dll"), "KiUserExceptionDispatcher"); // Hook, tampered exception dispatcher later
KiUserRealDispatcher = (PVOID)GetProcAddress(GetModuleHandleA("ntdll.dll"), "KiUserExceptionDispatcher"); // If something fails, will jump back to the real dispatcher
DWORD KiUserRealDispatcher2 = (DWORD)KiUserRealDispatcher + 8;
DWORD KiUser2 = (DWORD)KiUser + 1;
KiUser = (PVOID)KiUser2;
KiUserRealDispatcher = (PVOID)KiUserRealDispatcher2;
}
static IMP_AT GetIAT(LPCSTR ModuleName)
{
HMODULE mod = GetModuleHandleA(ModuleName);
PIMAGE_DOS_HEADER img_dos_headers = (PIMAGE_DOS_HEADER)mod;
PIMAGE_NT_HEADERS img_nt_headers = (PIMAGE_NT_HEADERS)((BYTE*)img_dos_headers + img_dos_headers->e_lfanew);
PIMAGE_IMPORT_DESCRIPTOR img_import_desc = (PIMAGE_IMPORT_DESCRIPTOR)((BYTE*)img_dos_headers +
img_nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress);
DWORD IATSize = (img_nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size * 4);
IMP_AT Retn;
Retn.Size = IATSize;
Retn.Address = (PVOID)((DWORD)mod + img_import_desc->FirstThunk - 0x1DC);
return Retn;
}
static void SetImportAddressTable(const char* ModuleName)
{
DWORD OldProtect;
MEMORY_BASIC_INFORMATION inf;
IMP_AT CopyModule = GetIAT(0);
IMP_AT SelfModule = GetIAT(ModuleName);
printf("_iat: %p\n", CopyModule.Address);
printf("iat: %p\n", SelfModule.Address);
VirtualProtect(SelfModule.Address, 1, PAGE_EXECUTE_READWRITE, &OldProtect);
printf("Error1: %d\n", GetLastError());
VirtualQuery(SelfModule.Address, &inf, sizeof(inf));
memcpy(SelfModule.Address, CopyModule.Address, inf.RegionSize);
VirtualProtect(SelfModule.Address, 1, OldProtect, &OldProtect);
}
int WaitOptModule(const char* OptModuleName)
{
if (!UseModule)
return -1;
volatile PVOID ModPtr = NULL;
while (!ModPtr)
ModPtr = (PVOID)GetModuleHandleA(OptModuleName);
SetImportAddressTable(OptModuleName);
return 0;
}
void SetModule(BOOLEAN use)
{
UseModule = use;
}
int AssignThread(HANDLE Thread)
{
for (size_t iterator = 0; iterator < sizeof(Threads); iterator++)
{
if (Threads[iterator] == NULL)
{
Threads[iterator] = Thread;
return iterator;
}
}
return -1;
}
void RemoveThread(HANDLE Thread)
{
for (size_t iterator = 0; iterator < sizeof(Threads); iterator++)
{
if (Threads[iterator] == Thread)
{
CloseHandle(Threads[iterator]);
Threads[iterator] = NULL;
return;
}
}
}
void AttachRVDbg()
{
InitializeConditionVariable(&Runnable);
InitializeCriticalSection(&RunLock);
SetKiUser();
HookFunction(KiUser, (PVOID)KiUserExceptionDispatcher, "ntdll.dll:KiUserExceptionDispatcher");
}
void DetachRVDbg()
{
UnhookFunction(KiUser, (PVOID)KiUserExceptionDispatcher, "ntdll.dll:KiUserExceptionDispatcher");
}
void ContinueDebugger()
{
WakeConditionVariable(&Runnable);
}
BOOLEAN IsAEHPresent()
{
return CurrentPool.IsAEHPresent;
}
void SetRegister(DWORD Register, DWORD Value)
{
switch (Register)
{
case GPRegisters::EAX:
r_registers.eax = Value;
return;
case GPRegisters::EBX:
r_registers.ebx = Value;
return;
case GPRegisters::ECX:
r_registers.ecx = Value;
return;
case GPRegisters::EDX:
r_registers.edx = Value;
return;
case GPRegisters::ESI:
r_registers.esi = Value;
return;
case GPRegisters::EDI:
r_registers.edi = Value;
return;
case GPRegisters::EBP:
r_registers.ebp = Value;
return;
case GPRegisters::ESP:
r_registers.esp = Value;
return;
case GPRegisters::EIP:
r_registers.eip = (PVOID)Value;
}
}
void SetRegisterFP(DWORD Register, BOOLEAN Precision, double Value)
{
r_registers.SSESet = TRUE;
switch (Register)
{
case SSERegisters::xmm0:
if (Precision)
{
r_registers.bxmm0 = 1;
r_registers.dxmm0 = Value;
return;
}
r_registers.bxmm0 = 2;
r_registers.xmm0 = (float)Value;
return;
case SSERegisters::xmm1:
if (Precision)
{
r_registers.bxmm1 = 1;
r_registers.dxmm1 = Value;
return;
}
r_registers.bxmm1 = 2;
r_registers.xmm1 = (float)Value;
return;
case SSERegisters::xmm2:
if (Precision)
{
r_registers.bxmm2 = 1;
r_registers.dxmm2 = Value;
return;
}
r_registers.bxmm2 = 2;
r_registers.xmm2 = (float)Value;
return;
case SSERegisters::xmm3:
if (Precision)
{
r_registers.bxmm3 = 1;
r_registers.dxmm3 = Value;
return;
}
r_registers.bxmm3 = 2;
r_registers.xmm3 = (float)Value;
return;
case SSERegisters::xmm4:
if (Precision)
{
r_registers.bxmm4 = 1;
r_registers.dxmm4 = Value;
return;
}
r_registers.bxmm4 = 2;
r_registers.xmm4 = (float)Value;
return;
case SSERegisters::xmm5:
if (Precision)
{
r_registers.bxmm5 = 1;
r_registers.dxmm5 = Value;
return;
}
r_registers.bxmm5 = 2;
r_registers.xmm5 = (float)Value;
return;
case SSERegisters::xmm6:
if (Precision)
{
r_registers.bxmm6 = 1;
r_registers.dxmm6 = Value;
return;
}
r_registers.bxmm6 = 2;
r_registers.xmm6 = (float)Value;
return;
case SSERegisters::xmm7:
if (Precision)
{
r_registers.bxmm7 = 1;
r_registers.dxmm7 = Value;
return;
}
r_registers.bxmm7 = 2;
r_registers.xmm7 = (float)Value;
return;
}
}
void SetExceptionMode(BOOLEAN lExceptionMode)
{
ExceptionMode = lExceptionMode;
}
BOOLEAN GetExceptionMode()
{
return ExceptionMode;
}
DWORD GetExceptionAddress()
{
return CurrentPool.ExceptionAddress;
}
VirtualRegisters GetRegisters()
{
return r_registers;
}
PoolSect GetPool()
{
return CurrentPool;
}
PoolSect* GetSector()
{
return Sector;
}
int GetSectorSize()
{
return sizeof(Sector) / sizeof(PoolSect);
}
<commit_msg>Update rvdbg.cpp<commit_after>#include "stdafx.h"
#include "rvdbg.h"
BOOLEAN tDSend;
CRITICAL_SECTION repr;
CONDITION_VARIABLE reprcondition;
static void HandleSSE()
{
if (r_registers.bxmm0 == 1)
__asm movsd xmm0, r_registers.dxmm0;
else if (r_registers.bxmm0 == 2)
__asm movss xmm0, r_registers.xmm0;
if (r_registers.bxmm1)
__asm movsd xmm1, r_registers.dxmm1;
else if (r_registers.bxmm1 == 2)
__asm movss xmm1, r_registers.xmm1;
if (r_registers.bxmm2)
__asm movsd xmm2, r_registers.dxmm2;
else if (r_registers.bxmm2 == 2)
__asm movss xmm2, r_registers.xmm2;
if (r_registers.bxmm3)
__asm movsd xmm3, r_registers.dxmm3;
else if (r_registers.bxmm3 == 2)
__asm movss xmm3, r_registers.xmm3;
if (r_registers.bxmm4)
__asm movsd xmm4, r_registers.dxmm4;
else if (r_registers.bxmm4 == 2)
__asm movss xmm4, r_registers.xmm4;
if (r_registers.bxmm5)
__asm movsd xmm5, r_registers.dxmm5;
else if (r_registers.bxmm5 == 2)
__asm movss xmm5, r_registers.xmm5;
if (r_registers.bxmm6)
__asm movsd xmm6, r_registers.dxmm6;
else if (r_registers.bxmm6 == 2)
__asm movss xmm6, r_registers.xmm6;
if (r_registers.bxmm7)
__asm movsd xmm7, r_registers.dxmm7;
else if (r_registers.bxmm7 == 2)
__asm movss xmm7, r_registers.xmm7;
r_registers.bxmm0 = 0;
r_registers.bxmm1 = 0;
r_registers.bxmm2 = 0;
r_registers.bxmm3 = 0;
r_registers.bxmm4 = 0;
r_registers.bxmm5 = 0;
r_registers.bxmm6 = 0;
r_registers.bxmm7 = 0;
}
static PVOID CallChain()
{
size_t ExceptionElement = SearchSector(Sector, 128, ExceptionComparator);
if (ExceptionElement > 128)
{
if (ExceptionMode == 2)
{
SuspendThreads(GetCurrentProcessId(), GetCurrentThreadId());
DWORD swap_ad = SwapAccess(AccessException, AccessException);
if (!swap_ad)
{
ChunkExecutable = FALSE;
return NULL;
}
Swaps.push_back((PVOID)swap_ad);
return (PVOID)swap_ad;
}
return NULL;
}
SuspendThreads(GetCurrentProcessId(), GetCurrentThreadId());
Debugger = TRUE;
tDSend = TRUE;
for (size_t iterator = 0; iterator < sizeof(Threads); iterator++)
{
if (Threads[iterator] != NULL)
ResumeThread(Threads[iterator]);
}
Sector[ExceptionElement].ExceptionCode = ExceptionCode;
PVOID ReturnException = HandleException(Sector[ExceptionElement], Sector[ExceptionElement].ModuleName);
r_registers.eip = ReturnException;
Sector[ExceptionElement].Thread = GetCurrentThread();
Sector[ExceptionElement].IsAEHPresent = TRUE;
Sector[ExceptionElement].ReturnAddress = r_registers.ReturnAddress;
CurrentPool = Sector[ExceptionElement];
EnterCriticalSection(&RunLock);
SleepConditionVariableCS(&Runnable, &RunLock, INFINITE);
LeaveCriticalSection(&RunLock);
ResumeThreads(GetCurrentProcessId(), GetCurrentThreadId());
UnlockSector(Sector, ExceptionElement);
return r_registers.eip;
}
static __declspec(naked) VOID NTAPI KiUserExceptionDispatcher(PEXCEPTION_RECORD ExceptionRecord, PCONTEXT Context)
{
__asm
{
movss r_registers.xmm0, xmm0;
movss r_registers.xmm1, xmm1;
movss r_registers.xmm2, xmm2;
movss r_registers.xmm3, xmm3;
movss r_registers.xmm4, xmm4;
movss r_registers.xmm5, xmm5;
movss r_registers.xmm6, xmm6;
movss r_registers.xmm7, xmm7;
movsd r_registers.dxmm0, xmm0;
movsd r_registers.dxmm1, xmm1;
movsd r_registers.dxmm2, xmm2;
movsd r_registers.dxmm3, xmm3;
movsd r_registers.dxmm4, xmm4;
movsd r_registers.dxmm5, xmm5;
movsd r_registers.dxmm6, xmm6;
movsd r_registers.dxmm7, xmm7;
mov r_registers.eax, eax;
mov r_registers.ebx, ebx;
mov r_registers.ecx, ecx;
mov r_registers.edx, edx;
mov r_registers.esi, esi;
mov r_registers.edi, edi;
mov r_registers.ebp, ebp;
mov eax, [esp + 0x11c]; // Reserved former esp
mov r_registers.esp, eax;
mov eax, [eax];
mov r_registers.ReturnAddress, eax;
mov eax, [esp + 0x14]; // [esp + 0x14] contains the exception address
mov[ExceptionComparator], eax; // move into the exception comparator, aka the address to be compared with the exception address
mov eax, [esp + 0x08]; // [esp + 0x0C] contains the exception code
mov[ExceptionCode], eax; // move into the ExceptionCode global.
mov eax, [esp + 20]; // when access exceptions are enabled, move the accessed memoryh ere
mov[AccessException], eax;
}
Decision = (PVOID)CallChain(); // Initiate the CallChain function
if (!Decision) // if the decision is null, then jump back to the real dispatcher
{
__asm
{
mov eax, r_registers.eax;
mov ecx, [esp + 04];
mov ebx, [esp];
jmp KiUserRealDispatcher;
}
}
if (r_registers.SSESet == TRUE)
HandleSSE();
r_registers.SSESet = FALSE;
__asm
{
mov eax, r_registers.eax;
mov ebx, r_registers.ebx;
mov ecx, r_registers.ecx;
mov edx, r_registers.edx;
mov esi, r_registers.esi;
mov edi, r_registers.edi;
mov esp, r_registers.esp; // [esp + 0x11c] contains stack initation information such as the return address, arguments, etc...
jmp Decision; // jump to the catch block
}
}
static void SetKiUser()
{
KiUser = (PVOID)GetProcAddress(GetModuleHandleA("ntdll.dll"), "KiUserExceptionDispatcher"); // Hook, tampered exception dispatcher later
KiUserRealDispatcher = (PVOID)GetProcAddress(GetModuleHandleA("ntdll.dll"), "KiUserExceptionDispatcher"); // If something fails, will jump back to the real dispatcher
DWORD KiUserRealDispatcher2 = (DWORD)KiUserRealDispatcher + 8;
DWORD KiUser2 = (DWORD)KiUser + 1;
KiUser = (PVOID)KiUser2;
KiUserRealDispatcher = (PVOID)KiUserRealDispatcher2;
}
static IMP_AT GetIAT(LPCSTR ModuleName)
{
HMODULE mod = GetModuleHandleA(ModuleName);
PIMAGE_DOS_HEADER img_dos_headers = (PIMAGE_DOS_HEADER)mod;
PIMAGE_NT_HEADERS img_nt_headers = (PIMAGE_NT_HEADERS)((BYTE*)img_dos_headers + img_dos_headers->e_lfanew);
PIMAGE_IMPORT_DESCRIPTOR img_import_desc = (PIMAGE_IMPORT_DESCRIPTOR)((BYTE*)img_dos_headers +
img_nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress);
DWORD IATSize = (img_nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size * 4);
IMP_AT Retn;
Retn.Size = IATSize;
Retn.Address = (PVOID)((DWORD)mod + img_import_desc->FirstThunk - 0x1DC);
return Retn;
}
static void SetImportAddressTable(const char* ModuleName)
{
DWORD OldProtect;
MEMORY_BASIC_INFORMATION inf;
IMP_AT CopyModule = GetIAT(0);
IMP_AT SelfModule = GetIAT(ModuleName);
printf("_iat: %p\n", CopyModule.Address);
printf("iat: %p\n", SelfModule.Address);
VirtualProtect(SelfModule.Address, 1, PAGE_EXECUTE_READWRITE, &OldProtect);
printf("Error1: %d\n", GetLastError());
VirtualQuery(SelfModule.Address, &inf, sizeof(inf));
memcpy(SelfModule.Address, CopyModule.Address, inf.RegionSize);
VirtualProtect(SelfModule.Address, 1, OldProtect, &OldProtect);
}
int WaitOptModule(const char* OptModuleName)
{
if (!UseModule)
return -1;
volatile PVOID ModPtr = NULL;
while (!ModPtr)
ModPtr = (PVOID)GetModuleHandleA(OptModuleName);
SetImportAddressTable(OptModuleName);
return 0;
}
void SetModule(BOOLEAN use)
{
UseModule = use;
}
int AssignThread(HANDLE Thread)
{
for (size_t iterator = 0; iterator < sizeof(Threads); iterator++)
{
if (Threads[iterator] == NULL)
{
Threads[iterator] = Thread;
return iterator;
}
}
return -1;
}
void RemoveThread(HANDLE Thread)
{
for (size_t iterator = 0; iterator < sizeof(Threads); iterator++)
{
if (Threads[iterator] == Thread)
{
CloseHandle(Threads[iterator]);
Threads[iterator] = NULL;
return;
}
}
}
void AttachRVDbg()
{
InitializeConditionVariable(&Runnable);
InitializeCriticalSection(&RunLock);
SetKiUser();
HookFunction(KiUser, (PVOID)KiUserExceptionDispatcher, "ntdll.dll:KiUserExceptionDispatcher");
}
void DetachRVDbg()
{
UnhookFunction(KiUser, (PVOID)KiUserExceptionDispatcher, "ntdll.dll:KiUserExceptionDispatcher");
}
void ContinueDebugger()
{
WakeConditionVariable(&Runnable);
}
BOOLEAN IsAEHPresent()
{
return CurrentPool.IsAEHPresent;
}
void SetRegister(DWORD Register, DWORD Value)
{
switch (Register)
{
case GPRegisters::EAX:
r_registers.eax = Value;
return;
case GPRegisters::EBX:
r_registers.ebx = Value;
return;
case GPRegisters::ECX:
r_registers.ecx = Value;
return;
case GPRegisters::EDX:
r_registers.edx = Value;
return;
case GPRegisters::ESI:
r_registers.esi = Value;
return;
case GPRegisters::EDI:
r_registers.edi = Value;
return;
case GPRegisters::EBP:
r_registers.ebp = Value;
return;
case GPRegisters::ESP:
r_registers.esp = Value;
return;
case GPRegisters::EIP:
r_registers.eip = (PVOID)Value;
}
}
void SetRegisterFP(DWORD Register, BOOLEAN Precision, double Value)
{
r_registers.SSESet = TRUE;
switch (Register)
{
case SSERegisters::xmm0:
if (Precision)
{
r_registers.bxmm0 = 1;
r_registers.dxmm0 = Value;
return;
}
r_registers.bxmm0 = 2;
r_registers.xmm0 = (float)Value;
return;
case SSERegisters::xmm1:
if (Precision)
{
r_registers.bxmm1 = 1;
r_registers.dxmm1 = Value;
return;
}
r_registers.bxmm1 = 2;
r_registers.xmm1 = (float)Value;
return;
case SSERegisters::xmm2:
if (Precision)
{
r_registers.bxmm2 = 1;
r_registers.dxmm2 = Value;
return;
}
r_registers.bxmm2 = 2;
r_registers.xmm2 = (float)Value;
return;
case SSERegisters::xmm3:
if (Precision)
{
r_registers.bxmm3 = 1;
r_registers.dxmm3 = Value;
return;
}
r_registers.bxmm3 = 2;
r_registers.xmm3 = (float)Value;
return;
case SSERegisters::xmm4:
if (Precision)
{
r_registers.bxmm4 = 1;
r_registers.dxmm4 = Value;
return;
}
r_registers.bxmm4 = 2;
r_registers.xmm4 = (float)Value;
return;
case SSERegisters::xmm5:
if (Precision)
{
r_registers.bxmm5 = 1;
r_registers.dxmm5 = Value;
return;
}
r_registers.bxmm5 = 2;
r_registers.xmm5 = (float)Value;
return;
case SSERegisters::xmm6:
if (Precision)
{
r_registers.bxmm6 = 1;
r_registers.dxmm6 = Value;
return;
}
r_registers.bxmm6 = 2;
r_registers.xmm6 = (float)Value;
return;
case SSERegisters::xmm7:
if (Precision)
{
r_registers.bxmm7 = 1;
r_registers.dxmm7 = Value;
return;
}
r_registers.bxmm7 = 2;
r_registers.xmm7 = (float)Value;
return;
}
}
void SetExceptionMode(BOOLEAN lExceptionMode)
{
ExceptionMode = lExceptionMode;
}
BOOLEAN GetExceptionMode()
{
return ExceptionMode;
}
DWORD GetExceptionAddress()
{
return CurrentPool.ExceptionAddress;
}
VirtualRegisters GetRegisters()
{
return r_registers;
}
PoolSect GetPool()
{
return CurrentPool;
}
PoolSect* GetSector()
{
return Sector;
}
int GetSectorSize()
{
return sizeof(Sector) / sizeof(PoolSect);
}
<|endoftext|> |
<commit_before>#include "server/user_manage.h"
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/lexical_cast.hpp>
#include <string>
#include <sstream>
#include "common/logging.h"
#include "common/timer.h"
#include "leveldb/write_batch.h"
#include "storage/utils.h"
namespace galaxy {
namespace ins {
const std::string user_dbname = "userdb";
const std::string root_name = "root";
std::string UserManager::CalcUuid(const std::string& name) {
boost::uuids::uuid uuid_namespace = boost::uuids::random_generator()();
boost::uuids::uuid uuid = boost::uuids::name_generator(uuid_namespace)(name);
std::stringstream uuids;
uuids << uuid;
return uuids.str();
}
UserManager::UserManager(const std::string& data_dir,
const UserInfo& root) : data_dir_(data_dir) {
bool ok = ins_common::Mkdirs(data_dir.c_str());
if (!ok) {
LOG(FATAL, "failed to create dir :%s", data_dir.c_str());
abort();
}
std::string full_name = data_dir + "/" + user_dbname;
leveldb::Options options;
options.create_if_missing = true;
leveldb::Status status = leveldb::DB::Open(options, full_name, &user_db_);
assert(status.ok());
if (root.has_username() && root.has_passwd()) {
assert(WriteToDatabase(root));
}
RecoverFromDatabase();
}
Status UserManager::Login(const std::string& name,
const std::string& password,
std::string* uuid) {
MutexLock lock(&mu_);
std::map<std::string, UserInfo>::iterator user_it = user_list_.find(name);
if (user_it == user_list_.end()) {
LOG(WARNING, "Inexist user tried to login :%s", name.c_str());
return kUnknownUser;
}
if (user_it->second.passwd() != password) {
LOG(WARNING, "Password error for logging :%s", name.c_str());
return kPasswordError;
}
const std::string& newuuid = CalcUuid(name);
logged_users_[newuuid] = name;
if (uuid != NULL) {
*uuid = newuuid;
}
return kOk;
}
Status UserManager::Logout(const std::string& uuid) {
MutexLock lock(&mu_);
std::map<std::string, std::string>::iterator online_it = logged_users_.find(uuid);
if (online_it == logged_users_.end()) {
LOG(WARNING, "Logout for an inexist user :%s", uuid.c_str());
return kUnknownUser;
}
logged_users_.erase(online_it);
return kOk;
}
Status UserManager::Register(const std::string& name, const std::string& password) {
MutexLock lock(&mu_);
if (name.empty()) {
LOG(WARNING, "Cannot register a user without username");
// Return `exist' status since empty user is consider as default in storage
return kUserExists;
}
std::map<std::string, UserInfo>::iterator user_it = user_list_.find(name);
if (user_it != user_list_.end()) {
LOG(WARNING, "Try to register an exist user :%s", name.c_str());
return kUserExists;
}
if (!WriteToDatabase(name, password)) {
return kError;
}
user_list_[name].set_username(name);
user_list_[name].set_passwd(password);
return kOk;
}
Status UserManager::ForceOffline(const std::string& myid, const std::string& name) {
MutexLock lock(&mu_);
std::map<std::string, std::string>::const_iterator online_it = logged_users_.find(myid);
if (online_it == logged_users_.end()) {
return kUnknownUser;
}
std::map<std::string, UserInfo>::const_iterator user_it = user_list_.find(name);
if (user_it == user_list_.end()) {
return kUnknownUser;
}
if (online_it->second != root_name && online_it->second != name) {
return kPermissionDenied;
}
std::map<std::string, std::string>::iterator it = logged_users_.begin();
while (it != logged_users_.end()) {
if (it->second == name) {
logged_users_.erase(it++);
} else {
++it;
}
}
return kOk;
}
Status UserManager::DeleteUser(const std::string& myid, const std::string& name) {
MutexLock lock(&mu_);
std::map<std::string, std::string>::const_iterator online_it = logged_users_.find(myid);
if (online_it == logged_users_.end()) {
return kUnknownUser;
}
if (online_it->second != root_name && online_it->second != name) {
return kPermissionDenied;
}
std::map<std::string, UserInfo>::iterator user_it = user_list_.find(name);
if (user_it == user_list_.end()) {
LOG(WARNING, "Try to delete an inexist user :%s", name.c_str());
return kNotFound;
}
if (!DeleteUserFromDatabase(name)) {
return kError;
}
std::map<std::string, std::string>::iterator it = logged_users_.begin();
while (it != logged_users_.end()) {
if (it->second == name) {
logged_users_.erase(it++);
} else {
++it;
}
}
user_list_.erase(user_it);
return kOk;
}
bool UserManager::IsLoggedIn(const std::string& uuid) {
MutexLock lock(&mu_);
return logged_users_.find(uuid) != logged_users_.end();
}
bool UserManager::IsValidUser(const std::string& name) {
MutexLock lock(&mu_);
return user_list_.find(name) != user_list_.end();
}
Status UserManager::TruncateOnlineUsers(const std::string& myid) {
MutexLock lock(&mu_);
std::map<std::string, std::string>::const_iterator online_it = logged_users_.find(myid);
if (online_it == logged_users_.end()) {
return kUnknownUser;
}
if (online_it->second != root_name) {
return kPermissionDenied;
}
std::map<std::string, std::string>::iterator it = logged_users_.begin();
while (it != logged_users_.end()) {
if (it->second != root_name) {
logged_users_.erase(it++);
} else {
++it;
}
}
return kOk;
}
Status UserManager::TruncateAllUsers(const std::string& myid) {
UserInfo root;
root.set_username(root_name);
{
MutexLock lock(&mu_);
std::map<std::string, std::string>::const_iterator online_it = logged_users_.find(myid);
if (online_it == logged_users_.end()) {
return kUnknownUser;
}
if (online_it->second != root_name) {
return kPermissionDenied;
}
root.set_passwd(user_list_[root_name].passwd());
}
if (!TruncateDatabase()) {
return kError;
}
if (!WriteToDatabase(root)) {
return kError;
}
MutexLock lock(&mu_);
std::map<std::string, std::string>::iterator it = logged_users_.begin();
while (it != logged_users_.end()) {
if (it->second != root_name) {
logged_users_.erase(it++);
} else {
++it;
}
}
user_list_.clear();
user_list_[root_name].set_username(root_name);
user_list_[root_name].set_passwd(root.passwd());
return kOk;
}
std::string UserManager::GetUsernameFromUuid(const std::string& uuid) {
if (IsLoggedIn(uuid)) {
return logged_users_[uuid];
}
return "";
}
bool UserManager::WriteToDatabase(const UserInfo& user) {
if (!user.has_username() || !user.has_passwd()) {
return false;
}
leveldb::Status status = user_db_->Put(leveldb::WriteOptions(),
user.username(),
user.passwd());
return status.ok();
}
bool UserManager::WriteToDatabase(const std::string& name, const std::string& password) {
leveldb::Status status = user_db_->Put(leveldb::WriteOptions(), name, password);
return status.ok();
}
bool UserManager::DeleteUserFromDatabase(const std::string& name) {
leveldb::Status status = user_db_->Delete(leveldb::WriteOptions(), name);
return status.ok();
}
bool UserManager::TruncateDatabase() {
leveldb::Iterator* it = user_db_->NewIterator(leveldb::ReadOptions());
leveldb::WriteBatch batch;
for (it->SeekToFirst(); it->Valid(); it->Next()) {
batch.Delete(it->key().ToString());
}
if (!it->status().ok()) {
return false;
}
leveldb::Status status = user_db_->Write(leveldb::WriteOptions(), &batch);
return status.ok();
}
bool UserManager::RecoverFromDatabase() {
leveldb::Iterator* it = user_db_->NewIterator(leveldb::ReadOptions());
for (it->SeekToFirst(); it->Valid(); it->Next()) {
const std::string& name = it->key().ToString();
user_list_[name].set_username(name);
user_list_[name].set_passwd(it->value().ToString());
}
return it->status().ok();
}
}
}
<commit_msg>add log for register, fix lock miss<commit_after>#include "server/user_manage.h"
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/lexical_cast.hpp>
#include <string>
#include <sstream>
#include "common/logging.h"
#include "common/timer.h"
#include "leveldb/write_batch.h"
#include "storage/utils.h"
namespace galaxy {
namespace ins {
const std::string user_dbname = "userdb";
const std::string root_name = "root";
std::string UserManager::CalcUuid(const std::string& name) {
boost::uuids::uuid uuid_namespace = boost::uuids::random_generator()();
boost::uuids::uuid uuid = boost::uuids::name_generator(uuid_namespace)(name);
std::stringstream uuids;
uuids << uuid;
return uuids.str();
}
UserManager::UserManager(const std::string& data_dir,
const UserInfo& root) : data_dir_(data_dir) {
bool ok = ins_common::Mkdirs(data_dir.c_str());
if (!ok) {
LOG(FATAL, "failed to create dir :%s", data_dir.c_str());
abort();
}
std::string full_name = data_dir + "/" + user_dbname;
leveldb::Options options;
options.create_if_missing = true;
leveldb::Status status = leveldb::DB::Open(options, full_name, &user_db_);
assert(status.ok());
if (root.has_username() && root.has_passwd()) {
assert(WriteToDatabase(root));
}
RecoverFromDatabase();
}
Status UserManager::Login(const std::string& name,
const std::string& password,
std::string* uuid) {
MutexLock lock(&mu_);
std::map<std::string, UserInfo>::iterator user_it = user_list_.find(name);
if (user_it == user_list_.end()) {
LOG(WARNING, "Inexist user tried to login :%s", name.c_str());
return kUnknownUser;
}
if (user_it->second.passwd() != password) {
LOG(WARNING, "Password error for logging :%s", name.c_str());
return kPasswordError;
}
const std::string& newuuid = CalcUuid(name);
logged_users_[newuuid] = name;
if (uuid != NULL) {
*uuid = newuuid;
}
return kOk;
}
Status UserManager::Logout(const std::string& uuid) {
MutexLock lock(&mu_);
std::map<std::string, std::string>::iterator online_it = logged_users_.find(uuid);
if (online_it == logged_users_.end()) {
LOG(WARNING, "Logout for an inexist user :%s", uuid.c_str());
return kUnknownUser;
}
logged_users_.erase(online_it);
return kOk;
}
Status UserManager::Register(const std::string& name, const std::string& password) {
MutexLock lock(&mu_);
if (name.empty()) {
LOG(WARNING, "Cannot register a user without username");
// Return `exist' status since empty user is consider as default in storage
return kUserExists;
}
std::map<std::string, UserInfo>::iterator user_it = user_list_.find(name);
if (user_it != user_list_.end()) {
LOG(WARNING, "Try to register an exist user :%s", name.c_str());
return kUserExists;
}
if (!WriteToDatabase(name, password)) {
return kError;
}
user_list_[name].set_username(name);
user_list_[name].set_passwd(password);
LOG(INFO, "%s registered ok.", name.c_str());
return kOk;
}
Status UserManager::ForceOffline(const std::string& myid, const std::string& name) {
MutexLock lock(&mu_);
std::map<std::string, std::string>::const_iterator online_it = logged_users_.find(myid);
if (online_it == logged_users_.end()) {
return kUnknownUser;
}
std::map<std::string, UserInfo>::const_iterator user_it = user_list_.find(name);
if (user_it == user_list_.end()) {
return kUnknownUser;
}
if (online_it->second != root_name && online_it->second != name) {
return kPermissionDenied;
}
std::map<std::string, std::string>::iterator it = logged_users_.begin();
while (it != logged_users_.end()) {
if (it->second == name) {
logged_users_.erase(it++);
} else {
++it;
}
}
return kOk;
}
Status UserManager::DeleteUser(const std::string& myid, const std::string& name) {
MutexLock lock(&mu_);
std::map<std::string, std::string>::const_iterator online_it = logged_users_.find(myid);
if (online_it == logged_users_.end()) {
return kUnknownUser;
}
if (online_it->second != root_name && online_it->second != name) {
return kPermissionDenied;
}
std::map<std::string, UserInfo>::iterator user_it = user_list_.find(name);
if (user_it == user_list_.end()) {
LOG(WARNING, "Try to delete an inexist user :%s", name.c_str());
return kNotFound;
}
if (!DeleteUserFromDatabase(name)) {
return kError;
}
std::map<std::string, std::string>::iterator it = logged_users_.begin();
while (it != logged_users_.end()) {
if (it->second == name) {
logged_users_.erase(it++);
} else {
++it;
}
}
user_list_.erase(user_it);
return kOk;
}
bool UserManager::IsLoggedIn(const std::string& uuid) {
MutexLock lock(&mu_);
return logged_users_.find(uuid) != logged_users_.end();
}
bool UserManager::IsValidUser(const std::string& name) {
MutexLock lock(&mu_);
return user_list_.find(name) != user_list_.end();
}
Status UserManager::TruncateOnlineUsers(const std::string& myid) {
MutexLock lock(&mu_);
std::map<std::string, std::string>::const_iterator online_it = logged_users_.find(myid);
if (online_it == logged_users_.end()) {
return kUnknownUser;
}
if (online_it->second != root_name) {
return kPermissionDenied;
}
std::map<std::string, std::string>::iterator it = logged_users_.begin();
while (it != logged_users_.end()) {
if (it->second != root_name) {
logged_users_.erase(it++);
} else {
++it;
}
}
return kOk;
}
Status UserManager::TruncateAllUsers(const std::string& myid) {
UserInfo root;
root.set_username(root_name);
{
MutexLock lock(&mu_);
std::map<std::string, std::string>::const_iterator online_it = logged_users_.find(myid);
if (online_it == logged_users_.end()) {
return kUnknownUser;
}
if (online_it->second != root_name) {
return kPermissionDenied;
}
root.set_passwd(user_list_[root_name].passwd());
}
if (!TruncateDatabase()) {
return kError;
}
if (!WriteToDatabase(root)) {
return kError;
}
MutexLock lock(&mu_);
std::map<std::string, std::string>::iterator it = logged_users_.begin();
while (it != logged_users_.end()) {
if (it->second != root_name) {
logged_users_.erase(it++);
} else {
++it;
}
}
user_list_.clear();
user_list_[root_name].set_username(root_name);
user_list_[root_name].set_passwd(root.passwd());
return kOk;
}
std::string UserManager::GetUsernameFromUuid(const std::string& uuid) {
MutexLock lock(&mu_);
if (logged_users_.find(uuid) != logged_users_.end()){
return logged_users_[uuid];
}
return "";
}
bool UserManager::WriteToDatabase(const UserInfo& user) {
if (!user.has_username() || !user.has_passwd()) {
return false;
}
leveldb::Status status = user_db_->Put(leveldb::WriteOptions(),
user.username(),
user.passwd());
return status.ok();
}
bool UserManager::WriteToDatabase(const std::string& name, const std::string& password) {
leveldb::Status status = user_db_->Put(leveldb::WriteOptions(), name, password);
return status.ok();
}
bool UserManager::DeleteUserFromDatabase(const std::string& name) {
leveldb::Status status = user_db_->Delete(leveldb::WriteOptions(), name);
return status.ok();
}
bool UserManager::TruncateDatabase() {
leveldb::Iterator* it = user_db_->NewIterator(leveldb::ReadOptions());
leveldb::WriteBatch batch;
for (it->SeekToFirst(); it->Valid(); it->Next()) {
batch.Delete(it->key().ToString());
}
if (!it->status().ok()) {
return false;
}
leveldb::Status status = user_db_->Write(leveldb::WriteOptions(), &batch);
return status.ok();
}
bool UserManager::RecoverFromDatabase() {
leveldb::Iterator* it = user_db_->NewIterator(leveldb::ReadOptions());
for (it->SeekToFirst(); it->Valid(); it->Next()) {
const std::string& name = it->key().ToString();
user_list_[name].set_username(name);
user_list_[name].set_passwd(it->value().ToString());
}
return it->status().ok();
}
}
}
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#define BOOST_TEST_MODULE TServerIntegrationTest
#include <boost/test/auto_unit_test.hpp>
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include <thrift/server/TSimpleServer.h>
#include <thrift/server/TThreadPoolServer.h>
#include <thrift/server/TThreadedServer.h>
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/transport/TServerSocket.h>
#include <thrift/transport/TSocket.h>
#include <thrift/transport/TTransport.h>
#include "gen-cpp/ParentService.h"
#include "TestPortFixture.h"
#include <vector>
using apache::thrift::concurrency::Guard;
using apache::thrift::concurrency::Monitor;
using apache::thrift::concurrency::Mutex;
using apache::thrift::concurrency::Synchronized;
using apache::thrift::protocol::TBinaryProtocol;
using apache::thrift::protocol::TBinaryProtocolFactory;
using apache::thrift::protocol::TProtocol;
using apache::thrift::protocol::TProtocolFactory;
using apache::thrift::transport::TServerSocket;
using apache::thrift::transport::TServerTransport;
using apache::thrift::transport::TSocket;
using apache::thrift::transport::TTransport;
using apache::thrift::transport::TTransportException;
using apache::thrift::transport::TTransportFactory;
using apache::thrift::server::TServer;
using apache::thrift::server::TServerEventHandler;
using apache::thrift::server::TSimpleServer;
using apache::thrift::server::TThreadPoolServer;
using apache::thrift::server::TThreadedServer;
using apache::thrift::test::ParentServiceClient;
using apache::thrift::test::ParentServiceIf;
using apache::thrift::test::ParentServiceIfFactory;
using apache::thrift::test::ParentServiceIfSingletonFactory;
using apache::thrift::test::ParentServiceProcessor;
using apache::thrift::test::ParentServiceProcessorFactory;
using apache::thrift::TProcessor;
using apache::thrift::TProcessorFactory;
using boost::posix_time::milliseconds;
/**
* preServe runs after listen() is successful, when we can connect
*/
class TServerReadyEventHandler : public TServerEventHandler, public Monitor {
public:
TServerReadyEventHandler() : isListening_(false), accepted_(0) {}
virtual ~TServerReadyEventHandler() {}
virtual void preServe() {
Synchronized sync(*this);
isListening_ = true;
notify();
}
virtual void* createContext(boost::shared_ptr<TProtocol> input,
boost::shared_ptr<TProtocol> output) {
Synchronized sync(*this);
++accepted_;
notify();
(void)input;
(void)output;
return NULL;
}
bool isListening() const { return isListening_; }
uint64_t acceptedCount() const { return accepted_; }
private:
bool isListening_;
uint64_t accepted_;
};
/**
* Reusing another generated test, just something to serve up
*/
class ParentHandler : public ParentServiceIf {
public:
ParentHandler() : generation_(0) {}
int32_t incrementGeneration() {
Guard g(mutex_);
return ++generation_;
}
int32_t getGeneration() {
Guard g(mutex_);
return generation_;
}
void addString(const std::string& s) {
Guard g(mutex_);
strings_.push_back(s);
}
void getStrings(std::vector<std::string>& _return) {
Guard g(mutex_);
_return = strings_;
}
void getDataWait(std::string& _return, const int32_t length) {
THRIFT_UNUSED_VARIABLE(_return);
THRIFT_UNUSED_VARIABLE(length);
}
void onewayWait() {}
void exceptionWait(const std::string& message) { THRIFT_UNUSED_VARIABLE(message); }
void unexpectedExceptionWait(const std::string& message) { THRIFT_UNUSED_VARIABLE(message); }
protected:
Mutex mutex_;
int32_t generation_;
std::vector<std::string> strings_;
};
void autoSocketCloser(TSocket* pSock) {
pSock->close();
delete pSock;
}
template <class TServerType>
class TServerIntegrationTestFixture : public TestPortFixture {
public:
TServerIntegrationTestFixture(const boost::shared_ptr<TProcessorFactory>& _processorFactory)
: pServer(new TServerType(_processorFactory,
boost::shared_ptr<TServerTransport>(
new TServerSocket("localhost", m_serverPort)),
boost::shared_ptr<TTransportFactory>(new TTransportFactory),
boost::shared_ptr<TProtocolFactory>(new TBinaryProtocolFactory))),
pEventHandler(boost::shared_ptr<TServerReadyEventHandler>(new TServerReadyEventHandler)) {
pServer->setServerEventHandler(pEventHandler);
}
TServerIntegrationTestFixture(const boost::shared_ptr<TProcessor>& _processor)
: pServer(
new TServerType(_processor,
boost::shared_ptr<TServerTransport>(new TServerSocket("localhost", 0)),
boost::shared_ptr<TTransportFactory>(new TTransportFactory),
boost::shared_ptr<TProtocolFactory>(new TBinaryProtocolFactory))),
pEventHandler(boost::shared_ptr<TServerReadyEventHandler>(new TServerReadyEventHandler)) {
pServer->setServerEventHandler(pEventHandler);
}
void startServer() {
pServerThread.reset(new boost::thread(boost::bind(&TServerType::serve, pServer.get())));
// block until listen() completes so clients will be able to connect
Synchronized sync(*(pEventHandler.get()));
while (!pEventHandler->isListening()) {
pEventHandler->wait();
}
BOOST_TEST_MESSAGE("server is listening");
}
void blockUntilAccepted(uint64_t numAccepted) {
Synchronized sync(*(pEventHandler.get()));
while (pEventHandler->acceptedCount() < numAccepted) {
pEventHandler->wait();
}
BOOST_TEST_MESSAGE(boost::format("server has accepted %1%") % numAccepted);
}
void stopServer() {
if (pServerThread) {
pServer->stop();
BOOST_TEST_MESSAGE("server stop completed");
pServerThread->join();
BOOST_TEST_MESSAGE("server thread joined");
pServerThread.reset();
}
}
~TServerIntegrationTestFixture() { stopServer(); }
int getServerPort() {
TServerSocket* pSock = dynamic_cast<TServerSocket*>(pServer->getServerTransport().get());
return pSock->getPort();
}
void delayClose(boost::shared_ptr<TTransport> toClose, boost::posix_time::time_duration after) {
boost::this_thread::sleep(after);
toClose->close();
}
void baseline(int64_t numToMake, int64_t expectedHWM) {
startServer();
std::vector<boost::shared_ptr<TSocket> > holdSockets;
std::vector<boost::shared_ptr<boost::thread> > holdThreads;
for (int64_t i = 0; i < numToMake; ++i) {
boost::shared_ptr<TSocket> pClientSock(new TSocket("localhost", getServerPort()),
autoSocketCloser);
holdSockets.push_back(pClientSock);
boost::shared_ptr<TProtocol> pClientProtocol(new TBinaryProtocol(pClientSock));
ParentServiceClient client(pClientProtocol);
pClientSock->open();
client.incrementGeneration();
holdThreads.push_back(boost::shared_ptr<boost::thread>(
new boost::thread(boost::bind(&TServerIntegrationTestFixture::delayClose,
this,
pClientSock,
milliseconds(100 * numToMake)))));
}
BOOST_CHECK_EQUAL(expectedHWM, pServer->getConcurrentClientCountHWM());
stopServer();
BOOST_FOREACH (boost::shared_ptr<boost::thread> pThread, holdThreads) { pThread->join(); }
holdThreads.clear();
holdSockets.clear();
}
boost::shared_ptr<TServerType> pServer;
boost::shared_ptr<TServerReadyEventHandler> pEventHandler;
boost::shared_ptr<boost::thread> pServerThread;
};
template <class TServerType>
class TServerIntegrationProcessorFactoryTestFixture
: public TServerIntegrationTestFixture<TServerType> {
public:
TServerIntegrationProcessorFactoryTestFixture()
: TServerIntegrationTestFixture<TServerType>(boost::make_shared<ParentServiceProcessorFactory>(
boost::make_shared<ParentServiceIfSingletonFactory>(
boost::make_shared<ParentHandler>()))) {}
};
template <class TServerType>
class TServerIntegrationProcessorTestFixture : public TServerIntegrationTestFixture<TServerType> {
public:
TServerIntegrationProcessorTestFixture()
: TServerIntegrationTestFixture<TServerType>(
boost::make_shared<ParentServiceProcessor>(boost::make_shared<ParentHandler>())) {}
};
BOOST_AUTO_TEST_SUITE(constructors)
BOOST_FIXTURE_TEST_CASE(test_simple_factory,
TServerIntegrationProcessorFactoryTestFixture<TSimpleServer>) {
baseline(3, 1);
}
BOOST_FIXTURE_TEST_CASE(test_simple, TServerIntegrationProcessorTestFixture<TSimpleServer>) {
baseline(3, 1);
}
BOOST_FIXTURE_TEST_CASE(test_threaded_factory,
TServerIntegrationProcessorFactoryTestFixture<TThreadedServer>) {
baseline(10, 10);
}
BOOST_FIXTURE_TEST_CASE(test_threaded, TServerIntegrationProcessorTestFixture<TThreadedServer>) {
baseline(10, 10);
}
BOOST_FIXTURE_TEST_CASE(test_threaded_bound,
TServerIntegrationProcessorTestFixture<TThreadedServer>) {
pServer->setConcurrentClientLimit(4);
baseline(10, 4);
}
BOOST_FIXTURE_TEST_CASE(test_threadpool_factory,
TServerIntegrationProcessorFactoryTestFixture<TThreadPoolServer>) {
pServer->getThreadManager()->threadFactory(
boost::shared_ptr<apache::thrift::concurrency::ThreadFactory>(
new apache::thrift::concurrency::PlatformThreadFactory));
pServer->getThreadManager()->start();
// thread factory has 4 threads as a default
// thread factory however is a bad way to limit concurrent clients
// as accept() will be called to grab a 5th client socket, in this case
// and then the thread factory will block adding the thread to manage
// that client.
baseline(10, 5);
}
BOOST_FIXTURE_TEST_CASE(test_threadpool,
TServerIntegrationProcessorTestFixture<TThreadPoolServer>) {
pServer->getThreadManager()->threadFactory(
boost::shared_ptr<apache::thrift::concurrency::ThreadFactory>(
new apache::thrift::concurrency::PlatformThreadFactory));
pServer->getThreadManager()->start();
// thread factory has 4 threads as a default
// thread factory however is a bad way to limit concurrent clients
// as accept() will be called to grab a 5th client socket, in this case
// and then the thread factory will block adding the thread to manage
// that client.
baseline(10, 5);
}
BOOST_FIXTURE_TEST_CASE(test_threadpool_bound,
TServerIntegrationProcessorTestFixture<TThreadPoolServer>) {
pServer->getThreadManager()->threadFactory(
boost::shared_ptr<apache::thrift::concurrency::ThreadFactory>(
new apache::thrift::concurrency::PlatformThreadFactory));
pServer->getThreadManager()->start();
pServer->setConcurrentClientLimit(4);
baseline(10, 4);
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_FIXTURE_TEST_SUITE(TServerIntegrationTest,
TServerIntegrationProcessorTestFixture<TThreadedServer>)
BOOST_AUTO_TEST_CASE(test_stop_with_interruptable_clients_connected) {
// This tests THRIFT-2441 new behavior: stopping the server disconnects clients
startServer();
boost::shared_ptr<TSocket> pClientSock1(new TSocket("localhost", getServerPort()),
autoSocketCloser);
pClientSock1->open();
boost::shared_ptr<TSocket> pClientSock2(new TSocket("localhost", getServerPort()),
autoSocketCloser);
pClientSock2->open();
// Ensure they have been accepted
blockUntilAccepted(2);
// The test fixture destructor will force the sockets to disconnect
// Prior to THRIFT-2441, pServer->stop() would hang until clients disconnected
stopServer();
// extra proof the server end disconnected the clients
uint8_t buf[1];
BOOST_CHECK_EQUAL(0, pClientSock1->read(&buf[0], 1)); // 0 = disconnected
BOOST_CHECK_EQUAL(0, pClientSock2->read(&buf[0], 1)); // 0 = disconnected
}
BOOST_AUTO_TEST_CASE(test_stop_with_uninterruptable_clients_connected) {
// This tests pre-THRIFT-2441 behavior: stopping the server blocks until clients
// disconnect.
boost::dynamic_pointer_cast<TServerSocket>(pServer->getServerTransport())
->setInterruptableChildren(false); // returns to pre-THRIFT-2441 behavior
startServer();
boost::shared_ptr<TSocket> pClientSock1(new TSocket("localhost", getServerPort()),
autoSocketCloser);
pClientSock1->open();
boost::shared_ptr<TSocket> pClientSock2(new TSocket("localhost", getServerPort()),
autoSocketCloser);
pClientSock2->open();
// Ensure they have been accepted
blockUntilAccepted(2);
boost::thread t1(boost::bind(&TServerIntegrationTestFixture::delayClose,
this,
pClientSock1,
milliseconds(250)));
boost::thread t2(boost::bind(&TServerIntegrationTestFixture::delayClose,
this,
pClientSock2,
milliseconds(250)));
// Once the clients disconnect the server will stop
stopServer();
t1.join();
t2.join();
}
BOOST_AUTO_TEST_CASE(test_concurrent_client_limit) {
startServer();
BOOST_CHECK_EQUAL(INT64_MAX, pServer->getConcurrentClientLimit());
pServer->setConcurrentClientLimit(2);
BOOST_CHECK_EQUAL(0, pServer->getConcurrentClientCount());
BOOST_CHECK_EQUAL(2, pServer->getConcurrentClientLimit());
boost::shared_ptr<TSocket> pClientSock1(new TSocket("localhost", getServerPort()),
autoSocketCloser);
pClientSock1->open();
blockUntilAccepted(1);
BOOST_CHECK_EQUAL(1, pServer->getConcurrentClientCount());
boost::shared_ptr<TSocket> pClientSock2(new TSocket("localhost", getServerPort()),
autoSocketCloser);
pClientSock2->open();
blockUntilAccepted(2);
BOOST_CHECK_EQUAL(2, pServer->getConcurrentClientCount());
// a third client cannot connect until one of the other two closes
boost::thread t2(boost::bind(&TServerIntegrationTestFixture::delayClose,
this,
pClientSock2,
milliseconds(250)));
boost::shared_ptr<TSocket> pClientSock3(new TSocket("localhost", getServerPort()),
autoSocketCloser);
pClientSock2->open();
blockUntilAccepted(2);
BOOST_CHECK_EQUAL(2, pServer->getConcurrentClientCount());
BOOST_CHECK_EQUAL(2, pServer->getConcurrentClientCountHWM());
stopServer();
t2.join();
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>THRIFT-3628 Fix lib/cpp/test/TServerIntegrationTest.cpp to use ephemeral ports. Client: Test (C++) Patch: John Sirois<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#define BOOST_TEST_MODULE TServerIntegrationTest
#include <boost/test/auto_unit_test.hpp>
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include <thrift/server/TSimpleServer.h>
#include <thrift/server/TThreadPoolServer.h>
#include <thrift/server/TThreadedServer.h>
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/transport/TServerSocket.h>
#include <thrift/transport/TSocket.h>
#include <thrift/transport/TTransport.h>
#include "gen-cpp/ParentService.h"
#include <vector>
using apache::thrift::concurrency::Guard;
using apache::thrift::concurrency::Monitor;
using apache::thrift::concurrency::Mutex;
using apache::thrift::concurrency::Synchronized;
using apache::thrift::protocol::TBinaryProtocol;
using apache::thrift::protocol::TBinaryProtocolFactory;
using apache::thrift::protocol::TProtocol;
using apache::thrift::protocol::TProtocolFactory;
using apache::thrift::transport::TServerSocket;
using apache::thrift::transport::TServerTransport;
using apache::thrift::transport::TSocket;
using apache::thrift::transport::TTransport;
using apache::thrift::transport::TTransportException;
using apache::thrift::transport::TTransportFactory;
using apache::thrift::server::TServer;
using apache::thrift::server::TServerEventHandler;
using apache::thrift::server::TSimpleServer;
using apache::thrift::server::TThreadPoolServer;
using apache::thrift::server::TThreadedServer;
using apache::thrift::test::ParentServiceClient;
using apache::thrift::test::ParentServiceIf;
using apache::thrift::test::ParentServiceIfFactory;
using apache::thrift::test::ParentServiceIfSingletonFactory;
using apache::thrift::test::ParentServiceProcessor;
using apache::thrift::test::ParentServiceProcessorFactory;
using apache::thrift::TProcessor;
using apache::thrift::TProcessorFactory;
using boost::posix_time::milliseconds;
/**
* preServe runs after listen() is successful, when we can connect
*/
class TServerReadyEventHandler : public TServerEventHandler, public Monitor {
public:
TServerReadyEventHandler() : isListening_(false), accepted_(0) {}
virtual ~TServerReadyEventHandler() {}
virtual void preServe() {
Synchronized sync(*this);
isListening_ = true;
notify();
}
virtual void* createContext(boost::shared_ptr<TProtocol> input,
boost::shared_ptr<TProtocol> output) {
Synchronized sync(*this);
++accepted_;
notify();
(void)input;
(void)output;
return NULL;
}
bool isListening() const { return isListening_; }
uint64_t acceptedCount() const { return accepted_; }
private:
bool isListening_;
uint64_t accepted_;
};
/**
* Reusing another generated test, just something to serve up
*/
class ParentHandler : public ParentServiceIf {
public:
ParentHandler() : generation_(0) {}
int32_t incrementGeneration() {
Guard g(mutex_);
return ++generation_;
}
int32_t getGeneration() {
Guard g(mutex_);
return generation_;
}
void addString(const std::string& s) {
Guard g(mutex_);
strings_.push_back(s);
}
void getStrings(std::vector<std::string>& _return) {
Guard g(mutex_);
_return = strings_;
}
void getDataWait(std::string& _return, const int32_t length) {
THRIFT_UNUSED_VARIABLE(_return);
THRIFT_UNUSED_VARIABLE(length);
}
void onewayWait() {}
void exceptionWait(const std::string& message) { THRIFT_UNUSED_VARIABLE(message); }
void unexpectedExceptionWait(const std::string& message) { THRIFT_UNUSED_VARIABLE(message); }
protected:
Mutex mutex_;
int32_t generation_;
std::vector<std::string> strings_;
};
void autoSocketCloser(TSocket* pSock) {
pSock->close();
delete pSock;
}
template <class TServerType>
class TServerIntegrationTestFixture {
public:
TServerIntegrationTestFixture(const boost::shared_ptr<TProcessorFactory>& _processorFactory)
: pServer(new TServerType(_processorFactory,
boost::shared_ptr<TServerTransport>(
new TServerSocket("localhost", 0)),
boost::shared_ptr<TTransportFactory>(new TTransportFactory),
boost::shared_ptr<TProtocolFactory>(new TBinaryProtocolFactory))),
pEventHandler(boost::shared_ptr<TServerReadyEventHandler>(new TServerReadyEventHandler)) {
pServer->setServerEventHandler(pEventHandler);
}
TServerIntegrationTestFixture(const boost::shared_ptr<TProcessor>& _processor)
: pServer(
new TServerType(_processor,
boost::shared_ptr<TServerTransport>(new TServerSocket("localhost", 0)),
boost::shared_ptr<TTransportFactory>(new TTransportFactory),
boost::shared_ptr<TProtocolFactory>(new TBinaryProtocolFactory))),
pEventHandler(boost::shared_ptr<TServerReadyEventHandler>(new TServerReadyEventHandler)) {
pServer->setServerEventHandler(pEventHandler);
}
void startServer() {
pServerThread.reset(new boost::thread(boost::bind(&TServerType::serve, pServer.get())));
// block until listen() completes so clients will be able to connect
Synchronized sync(*(pEventHandler.get()));
while (!pEventHandler->isListening()) {
pEventHandler->wait();
}
BOOST_TEST_MESSAGE("server is listening");
}
void blockUntilAccepted(uint64_t numAccepted) {
Synchronized sync(*(pEventHandler.get()));
while (pEventHandler->acceptedCount() < numAccepted) {
pEventHandler->wait();
}
BOOST_TEST_MESSAGE(boost::format("server has accepted %1%") % numAccepted);
}
void stopServer() {
if (pServerThread) {
pServer->stop();
BOOST_TEST_MESSAGE("server stop completed");
pServerThread->join();
BOOST_TEST_MESSAGE("server thread joined");
pServerThread.reset();
}
}
~TServerIntegrationTestFixture() { stopServer(); }
int getServerPort() {
TServerSocket* pSock = dynamic_cast<TServerSocket*>(pServer->getServerTransport().get());
return pSock->getPort();
}
void delayClose(boost::shared_ptr<TTransport> toClose, boost::posix_time::time_duration after) {
boost::this_thread::sleep(after);
toClose->close();
}
void baseline(int64_t numToMake, int64_t expectedHWM) {
startServer();
std::vector<boost::shared_ptr<TSocket> > holdSockets;
std::vector<boost::shared_ptr<boost::thread> > holdThreads;
for (int64_t i = 0; i < numToMake; ++i) {
boost::shared_ptr<TSocket> pClientSock(new TSocket("localhost", getServerPort()),
autoSocketCloser);
holdSockets.push_back(pClientSock);
boost::shared_ptr<TProtocol> pClientProtocol(new TBinaryProtocol(pClientSock));
ParentServiceClient client(pClientProtocol);
pClientSock->open();
client.incrementGeneration();
holdThreads.push_back(boost::shared_ptr<boost::thread>(
new boost::thread(boost::bind(&TServerIntegrationTestFixture::delayClose,
this,
pClientSock,
milliseconds(100 * numToMake)))));
}
BOOST_CHECK_EQUAL(expectedHWM, pServer->getConcurrentClientCountHWM());
stopServer();
BOOST_FOREACH (boost::shared_ptr<boost::thread> pThread, holdThreads) { pThread->join(); }
holdThreads.clear();
holdSockets.clear();
}
boost::shared_ptr<TServerType> pServer;
boost::shared_ptr<TServerReadyEventHandler> pEventHandler;
boost::shared_ptr<boost::thread> pServerThread;
};
template <class TServerType>
class TServerIntegrationProcessorFactoryTestFixture
: public TServerIntegrationTestFixture<TServerType> {
public:
TServerIntegrationProcessorFactoryTestFixture()
: TServerIntegrationTestFixture<TServerType>(boost::make_shared<ParentServiceProcessorFactory>(
boost::make_shared<ParentServiceIfSingletonFactory>(
boost::make_shared<ParentHandler>()))) {}
};
template <class TServerType>
class TServerIntegrationProcessorTestFixture : public TServerIntegrationTestFixture<TServerType> {
public:
TServerIntegrationProcessorTestFixture()
: TServerIntegrationTestFixture<TServerType>(
boost::make_shared<ParentServiceProcessor>(boost::make_shared<ParentHandler>())) {}
};
BOOST_AUTO_TEST_SUITE(constructors)
BOOST_FIXTURE_TEST_CASE(test_simple_factory,
TServerIntegrationProcessorFactoryTestFixture<TSimpleServer>) {
baseline(3, 1);
}
BOOST_FIXTURE_TEST_CASE(test_simple, TServerIntegrationProcessorTestFixture<TSimpleServer>) {
baseline(3, 1);
}
BOOST_FIXTURE_TEST_CASE(test_threaded_factory,
TServerIntegrationProcessorFactoryTestFixture<TThreadedServer>) {
baseline(10, 10);
}
BOOST_FIXTURE_TEST_CASE(test_threaded, TServerIntegrationProcessorTestFixture<TThreadedServer>) {
baseline(10, 10);
}
BOOST_FIXTURE_TEST_CASE(test_threaded_bound,
TServerIntegrationProcessorTestFixture<TThreadedServer>) {
pServer->setConcurrentClientLimit(4);
baseline(10, 4);
}
BOOST_FIXTURE_TEST_CASE(test_threadpool_factory,
TServerIntegrationProcessorFactoryTestFixture<TThreadPoolServer>) {
pServer->getThreadManager()->threadFactory(
boost::shared_ptr<apache::thrift::concurrency::ThreadFactory>(
new apache::thrift::concurrency::PlatformThreadFactory));
pServer->getThreadManager()->start();
// thread factory has 4 threads as a default
// thread factory however is a bad way to limit concurrent clients
// as accept() will be called to grab a 5th client socket, in this case
// and then the thread factory will block adding the thread to manage
// that client.
baseline(10, 5);
}
BOOST_FIXTURE_TEST_CASE(test_threadpool,
TServerIntegrationProcessorTestFixture<TThreadPoolServer>) {
pServer->getThreadManager()->threadFactory(
boost::shared_ptr<apache::thrift::concurrency::ThreadFactory>(
new apache::thrift::concurrency::PlatformThreadFactory));
pServer->getThreadManager()->start();
// thread factory has 4 threads as a default
// thread factory however is a bad way to limit concurrent clients
// as accept() will be called to grab a 5th client socket, in this case
// and then the thread factory will block adding the thread to manage
// that client.
baseline(10, 5);
}
BOOST_FIXTURE_TEST_CASE(test_threadpool_bound,
TServerIntegrationProcessorTestFixture<TThreadPoolServer>) {
pServer->getThreadManager()->threadFactory(
boost::shared_ptr<apache::thrift::concurrency::ThreadFactory>(
new apache::thrift::concurrency::PlatformThreadFactory));
pServer->getThreadManager()->start();
pServer->setConcurrentClientLimit(4);
baseline(10, 4);
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_FIXTURE_TEST_SUITE(TServerIntegrationTest,
TServerIntegrationProcessorTestFixture<TThreadedServer>)
BOOST_AUTO_TEST_CASE(test_stop_with_interruptable_clients_connected) {
// This tests THRIFT-2441 new behavior: stopping the server disconnects clients
startServer();
boost::shared_ptr<TSocket> pClientSock1(new TSocket("localhost", getServerPort()),
autoSocketCloser);
pClientSock1->open();
boost::shared_ptr<TSocket> pClientSock2(new TSocket("localhost", getServerPort()),
autoSocketCloser);
pClientSock2->open();
// Ensure they have been accepted
blockUntilAccepted(2);
// The test fixture destructor will force the sockets to disconnect
// Prior to THRIFT-2441, pServer->stop() would hang until clients disconnected
stopServer();
// extra proof the server end disconnected the clients
uint8_t buf[1];
BOOST_CHECK_EQUAL(0, pClientSock1->read(&buf[0], 1)); // 0 = disconnected
BOOST_CHECK_EQUAL(0, pClientSock2->read(&buf[0], 1)); // 0 = disconnected
}
BOOST_AUTO_TEST_CASE(test_stop_with_uninterruptable_clients_connected) {
// This tests pre-THRIFT-2441 behavior: stopping the server blocks until clients
// disconnect.
boost::dynamic_pointer_cast<TServerSocket>(pServer->getServerTransport())
->setInterruptableChildren(false); // returns to pre-THRIFT-2441 behavior
startServer();
boost::shared_ptr<TSocket> pClientSock1(new TSocket("localhost", getServerPort()),
autoSocketCloser);
pClientSock1->open();
boost::shared_ptr<TSocket> pClientSock2(new TSocket("localhost", getServerPort()),
autoSocketCloser);
pClientSock2->open();
// Ensure they have been accepted
blockUntilAccepted(2);
boost::thread t1(boost::bind(&TServerIntegrationTestFixture::delayClose,
this,
pClientSock1,
milliseconds(250)));
boost::thread t2(boost::bind(&TServerIntegrationTestFixture::delayClose,
this,
pClientSock2,
milliseconds(250)));
// Once the clients disconnect the server will stop
stopServer();
t1.join();
t2.join();
}
BOOST_AUTO_TEST_CASE(test_concurrent_client_limit) {
startServer();
BOOST_CHECK_EQUAL(INT64_MAX, pServer->getConcurrentClientLimit());
pServer->setConcurrentClientLimit(2);
BOOST_CHECK_EQUAL(0, pServer->getConcurrentClientCount());
BOOST_CHECK_EQUAL(2, pServer->getConcurrentClientLimit());
boost::shared_ptr<TSocket> pClientSock1(new TSocket("localhost", getServerPort()),
autoSocketCloser);
pClientSock1->open();
blockUntilAccepted(1);
BOOST_CHECK_EQUAL(1, pServer->getConcurrentClientCount());
boost::shared_ptr<TSocket> pClientSock2(new TSocket("localhost", getServerPort()),
autoSocketCloser);
pClientSock2->open();
blockUntilAccepted(2);
BOOST_CHECK_EQUAL(2, pServer->getConcurrentClientCount());
// a third client cannot connect until one of the other two closes
boost::thread t2(boost::bind(&TServerIntegrationTestFixture::delayClose,
this,
pClientSock2,
milliseconds(250)));
boost::shared_ptr<TSocket> pClientSock3(new TSocket("localhost", getServerPort()),
autoSocketCloser);
pClientSock2->open();
blockUntilAccepted(2);
BOOST_CHECK_EQUAL(2, pServer->getConcurrentClientCount());
BOOST_CHECK_EQUAL(2, pServer->getConcurrentClientCountHWM());
stopServer();
t2.join();
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>#include "TopkHeader.h"
double inline ori_absdiff(double a, double b) {
double v = a - b;
if (v < 0) {
v = v * -1;
}
return v;
}
void original_topk_sim_join_plain_impl(const Table& ltoken_vector, const Table& rtoken_vector,
CandSet& cand_set, PrefixHeap& prefix_events,
Heap& topk_heap, const unsigned int output_size) {
long int total_compared_pairs = 0;
CandSet compared_set;
InvertedIndex l_inverted_index, r_inverted_index;
PrefixEvent event;
int table_indicator, l_rec_idx, r_rec_idx, l_tok_idx, r_tok_idx, token, overlap;
unsigned long l_len, r_len;
double sim;
while (prefix_events.size() > 0) {
if (topk_heap.size() == output_size && (topk_heap.top().sim >= prefix_events.top().threshold ||
ori_absdiff(topk_heap.top().sim, prefix_events.top().threshold) <= 1e-6)) {
break;
}
event = prefix_events.top();
prefix_events.pop();
table_indicator = event.table_indicator;
if (table_indicator == 0) {
l_rec_idx = event.rec_idx;
l_tok_idx = event.tok_idx;
token = ltoken_vector[l_rec_idx][l_tok_idx];
l_len = ltoken_vector[l_rec_idx].size();
if (r_inverted_index.count(token)) {
set<pair<int, int> > r_records = r_inverted_index[token];
for (set<pair<int, int> >::iterator it = r_records.begin(); it != r_records.end(); ++it) {
pair<int, int> r_rec_tuple = *it;
r_rec_idx = r_rec_tuple.first;
r_tok_idx = r_rec_tuple.second;
r_len = rtoken_vector[r_rec_idx].size();
if (topk_heap.size() == output_size && (l_len < topk_heap.top().sim * r_len || l_len > r_len / topk_heap.top().sim)) {
continue;
}
if (cand_set.count(l_rec_idx) && cand_set[l_rec_idx].count(r_rec_idx)) {
continue;
}
if (compared_set.count(l_rec_idx) && compared_set[l_rec_idx].count(r_rec_idx)) {
continue;
}
overlap = original_plain_get_overlap(ltoken_vector[l_rec_idx], rtoken_vector[r_rec_idx]);
sim = overlap * 1.0 / (l_len + r_len - overlap);
if (topk_heap.size() == output_size) {
if (topk_heap.top().sim < sim) {
topk_heap.pop();
topk_heap.push(TopPair(sim, l_rec_idx, r_rec_idx));
}
} else {
topk_heap.push(TopPair(sim, l_rec_idx, r_rec_idx));
}
++total_compared_pairs;
if (!compared_set.count(l_rec_idx)) {
compared_set[l_rec_idx] = set<int>();
}
compared_set[l_rec_idx].insert(r_rec_idx);
}
}
double topk_heap_sim_index = 0.0;
if (topk_heap.size() == output_size) {
topk_heap_sim_index = topk_heap.top().sim;
}
double index_threshold = 1.0;
int numer_index = l_len - l_tok_idx;
int denom_index = l_len + l_tok_idx;
if (denom_index > 0) {
index_threshold = numer_index * 1.0 / denom_index;
}
if (index_threshold >= topk_heap_sim_index) {
if (!l_inverted_index.count(token)) {
l_inverted_index[token] = set<pair<int, int> >();
}
l_inverted_index[token].insert(pair<int, int>(l_rec_idx, l_tok_idx));
}
} else {
r_rec_idx = event.rec_idx;
r_tok_idx = event.tok_idx;
token = rtoken_vector[r_rec_idx][r_tok_idx];
r_len = rtoken_vector[r_rec_idx].size();
if (l_inverted_index.count(token)) {
set<pair<int, int> > l_records = l_inverted_index[token];
for (set<pair<int, int> >::iterator it = l_records.begin(); it != l_records.end(); ++it) {
pair<int, int> l_rec_tuple = *it;
l_rec_idx = l_rec_tuple.first;
l_tok_idx = l_rec_tuple.second;
l_len = ltoken_vector[l_rec_idx].size();
if (topk_heap.size() == output_size && (l_len < topk_heap.top().sim * r_len || l_len > r_len / topk_heap.top().sim)) {
continue;
}
if (cand_set.count(l_rec_idx) && cand_set[l_rec_idx].count(r_rec_idx)) {
continue;
}
if (compared_set.count(l_rec_idx) && compared_set[l_rec_idx].count(r_rec_idx)) {
continue;
}
overlap = original_plain_get_overlap(ltoken_vector[l_rec_idx], rtoken_vector[r_rec_idx]);
sim = overlap * 1.0 / (l_len + r_len - overlap);
if (topk_heap.size() == output_size) {
if (topk_heap.top().sim < sim) {
topk_heap.pop();
topk_heap.push(TopPair(sim, l_rec_idx, r_rec_idx));
}
} else {
topk_heap.push(TopPair(sim, l_rec_idx, r_rec_idx));
}
++total_compared_pairs;
if (!compared_set.count(l_rec_idx)) {
compared_set[l_rec_idx] = set<int>();
}
compared_set[l_rec_idx].insert(r_rec_idx);
}
}
double topk_heap_sim_index = 0.0;
if (topk_heap.size() == output_size) {
topk_heap_sim_index = topk_heap.top().sim;
}
double index_threshold = 1.0;
int numer_index = r_len - r_tok_idx;
int denom_index = r_len + r_tok_idx;
if (denom_index > 0) {
index_threshold = numer_index * 1.0 / denom_index;
}
if (index_threshold >= topk_heap_sim_index) {
if (!r_inverted_index.count(token)) {
r_inverted_index[token] = set<pair<int, int> >();
}
r_inverted_index[token].insert(pair<int, int>(r_rec_idx, r_tok_idx));
}
}
}
//printf("number of compared pairs: %ld\n", total_compared_pairs);
}
Heap original_topk_sim_join_plain(const Table& ltoken_vector, const Table& rtoken_vector,
CandSet& cand_set, const unsigned int output_size) {
//cout << "In original topk sim plain" << endl;
PrefixHeap prefix_events;
original_generate_prefix_events(ltoken_vector, rtoken_vector, prefix_events);
Heap topk_heap;
original_topk_sim_join_plain_impl(ltoken_vector, rtoken_vector, cand_set, prefix_events, topk_heap, output_size);
return topk_heap;
}
<commit_msg>remove unused print info<commit_after>#include "TopkHeader.h"
double inline ori_absdiff(double a, double b) {
double v = a - b;
if (v < 0) {
v = v * -1;
}
return v;
}
void original_topk_sim_join_plain_impl(const Table& ltoken_vector, const Table& rtoken_vector,
CandSet& cand_set, PrefixHeap& prefix_events,
Heap& topk_heap, const unsigned int output_size) {
long int total_compared_pairs = 0;
CandSet compared_set;
InvertedIndex l_inverted_index, r_inverted_index;
PrefixEvent event;
int table_indicator, l_rec_idx, r_rec_idx, l_tok_idx, r_tok_idx, token, overlap;
unsigned long l_len, r_len;
double sim;
while (prefix_events.size() > 0) {
if (topk_heap.size() == output_size && (topk_heap.top().sim >= prefix_events.top().threshold ||
ori_absdiff(topk_heap.top().sim, prefix_events.top().threshold) <= 1e-6)) {
break;
}
event = prefix_events.top();
prefix_events.pop();
table_indicator = event.table_indicator;
if (table_indicator == 0) {
l_rec_idx = event.rec_idx;
l_tok_idx = event.tok_idx;
token = ltoken_vector[l_rec_idx][l_tok_idx];
l_len = ltoken_vector[l_rec_idx].size();
if (r_inverted_index.count(token)) {
set<pair<int, int> > r_records = r_inverted_index[token];
for (set<pair<int, int> >::iterator it = r_records.begin(); it != r_records.end(); ++it) {
pair<int, int> r_rec_tuple = *it;
r_rec_idx = r_rec_tuple.first;
r_tok_idx = r_rec_tuple.second;
r_len = rtoken_vector[r_rec_idx].size();
if (topk_heap.size() == output_size && (l_len < topk_heap.top().sim * r_len || l_len > r_len / topk_heap.top().sim)) {
continue;
}
if (cand_set.count(l_rec_idx) && cand_set[l_rec_idx].count(r_rec_idx)) {
continue;
}
if (compared_set.count(l_rec_idx) && compared_set[l_rec_idx].count(r_rec_idx)) {
continue;
}
overlap = original_plain_get_overlap(ltoken_vector[l_rec_idx], rtoken_vector[r_rec_idx]);
sim = overlap * 1.0 / (l_len + r_len - overlap);
if (topk_heap.size() == output_size) {
if (topk_heap.top().sim < sim) {
topk_heap.pop();
topk_heap.push(TopPair(sim, l_rec_idx, r_rec_idx));
}
} else {
topk_heap.push(TopPair(sim, l_rec_idx, r_rec_idx));
}
++total_compared_pairs;
if (!compared_set.count(l_rec_idx)) {
compared_set[l_rec_idx] = set<int>();
}
compared_set[l_rec_idx].insert(r_rec_idx);
}
}
double topk_heap_sim_index = 0.0;
if (topk_heap.size() == output_size) {
topk_heap_sim_index = topk_heap.top().sim;
}
double index_threshold = 1.0;
int numer_index = l_len - l_tok_idx;
int denom_index = l_len + l_tok_idx;
if (denom_index > 0) {
index_threshold = numer_index * 1.0 / denom_index;
}
if (index_threshold >= topk_heap_sim_index) {
if (!l_inverted_index.count(token)) {
l_inverted_index[token] = set<pair<int, int> >();
}
l_inverted_index[token].insert(pair<int, int>(l_rec_idx, l_tok_idx));
}
} else {
r_rec_idx = event.rec_idx;
r_tok_idx = event.tok_idx;
token = rtoken_vector[r_rec_idx][r_tok_idx];
r_len = rtoken_vector[r_rec_idx].size();
if (l_inverted_index.count(token)) {
set<pair<int, int> > l_records = l_inverted_index[token];
for (set<pair<int, int> >::iterator it = l_records.begin(); it != l_records.end(); ++it) {
pair<int, int> l_rec_tuple = *it;
l_rec_idx = l_rec_tuple.first;
l_tok_idx = l_rec_tuple.second;
l_len = ltoken_vector[l_rec_idx].size();
if (topk_heap.size() == output_size && (l_len < topk_heap.top().sim * r_len || l_len > r_len / topk_heap.top().sim)) {
continue;
}
if (cand_set.count(l_rec_idx) && cand_set[l_rec_idx].count(r_rec_idx)) {
continue;
}
if (compared_set.count(l_rec_idx) && compared_set[l_rec_idx].count(r_rec_idx)) {
continue;
}
overlap = original_plain_get_overlap(ltoken_vector[l_rec_idx], rtoken_vector[r_rec_idx]);
sim = overlap * 1.0 / (l_len + r_len - overlap);
if (topk_heap.size() == output_size) {
if (topk_heap.top().sim < sim) {
topk_heap.pop();
topk_heap.push(TopPair(sim, l_rec_idx, r_rec_idx));
}
} else {
topk_heap.push(TopPair(sim, l_rec_idx, r_rec_idx));
}
++total_compared_pairs;
if (!compared_set.count(l_rec_idx)) {
compared_set[l_rec_idx] = set<int>();
}
compared_set[l_rec_idx].insert(r_rec_idx);
}
}
double topk_heap_sim_index = 0.0;
if (topk_heap.size() == output_size) {
topk_heap_sim_index = topk_heap.top().sim;
}
double index_threshold = 1.0;
int numer_index = r_len - r_tok_idx;
int denom_index = r_len + r_tok_idx;
if (denom_index > 0) {
index_threshold = numer_index * 1.0 / denom_index;
}
if (index_threshold >= topk_heap_sim_index) {
if (!r_inverted_index.count(token)) {
r_inverted_index[token] = set<pair<int, int> >();
}
r_inverted_index[token].insert(pair<int, int>(r_rec_idx, r_tok_idx));
}
}
}
}
Heap original_topk_sim_join_plain(const Table& ltoken_vector, const Table& rtoken_vector,
CandSet& cand_set, const unsigned int output_size) {
PrefixHeap prefix_events;
original_generate_prefix_events(ltoken_vector, rtoken_vector, prefix_events);
Heap topk_heap;
original_topk_sim_join_plain_impl(ltoken_vector, rtoken_vector, cand_set, prefix_events, topk_heap, output_size);
return topk_heap;
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* Copyright 2017, 2018 MINRES Technologies GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
/*
* configurer.cpp
*
* Created on: 27.09.2017
* Author: eyck
*/
#include "scc/configurer.h"
#include "scc/report.h"
#include <cci_configuration>
#include <cci_utils/broker.h>
#include <boost/algorithm/string/predicate.hpp>
#include <fstream>
scc::configurer::configurer(const std::string &filename)
: base_type("configurer")
, cci_originator("configurer")
, cci_broker(cci::cci_get_global_broker(cci_originator)) {
if (filename.length() > 0) {
std::ifstream is(filename);
if (is.is_open()) {
try {
is >> root;
configure_cci_hierarchical(root, "");
config_valid=true;
} catch (Json::RuntimeError &e) {
LOG(ERROR) << "Could not parse input file " << filename << ", reason: " << e.what();
}
} else {
LOG(ERROR) << "Could not open input file " << filename;
}
}
}
void scc::configurer::dump_hierarchy(std::ostream &os, sc_core::sc_object *obj) {
if (obj) {
os << obj->name() << " of type " << typeid(*obj).name() << "\n";
for (auto *o : obj->get_child_objects()) dump_hierarchy(os);
} else {
for (auto *o : sc_core::sc_get_top_level_objects(sc_core::sc_curr_simcontext)) dump_hierarchy(os, o);
}
}
inline const std::vector<sc_core::sc_object *> &get_sc_objects(sc_core::sc_object *obj = nullptr) {
if (obj)
return obj->get_child_objects();
else
return sc_core::sc_get_top_level_objects(sc_core::sc_curr_simcontext);
}
void scc::configurer::dump_configuration(std::ostream &os, sc_core::sc_object *obj) {
Json::Value root{Json::objectValue};
for (auto *o : get_sc_objects(obj)) {
dump_configuration(o, root);
}
// For convenience, use `writeString()` with a specialized builder.
Json::StreamWriterBuilder wbuilder;
wbuilder["indentation"] = "\t";
wbuilder["enableYAMLCompatibility"] = true;
wbuilder["commentStyle"] ="None";
wbuilder.newStreamWriter()->write(root, &os);
// another (default) option:
// os << root;
}
#define CHECK_N_ASSIGN_VAL(TYPE, ATTR) \
{ \
auto *a = dynamic_cast<sc_core::sc_attribute<TYPE> *>(ATTR); \
if (a != nullptr) { \
node[a->name()] = a->value; \
continue; \
} \
}
void scc::configurer::dump_configuration(sc_core::sc_object *obj, Json::Value &parent) {
auto mod = dynamic_cast<sc_core::sc_module *>(obj);
Json::Value node{Json::objectValue};
for (sc_core::sc_attr_base *attr_base : obj->attr_cltn()) {
CHECK_N_ASSIGN_VAL(int, attr_base);
CHECK_N_ASSIGN_VAL(unsigned, attr_base);
CHECK_N_ASSIGN_VAL(int64_t, attr_base);
CHECK_N_ASSIGN_VAL(uint64_t, attr_base);
CHECK_N_ASSIGN_VAL(bool, attr_base);
CHECK_N_ASSIGN_VAL(float, attr_base);
CHECK_N_ASSIGN_VAL(double, attr_base);
CHECK_N_ASSIGN_VAL(std::string, attr_base);
CHECK_N_ASSIGN_VAL(char *, attr_base);
}
const std::string hier_name{obj->name()};
cci::cci_param_predicate pred{[hier_name](cci::cci_param_untyped_handle h) -> bool {
std::string h_name {h.name()};
auto sep = hier_name.length();
return h_name.compare(0, sep-1, hier_name)==0 && // begins with hier_name
h_name[sep]=='.' && // has additional part
h_name.substr(sep+1).find('.')==h_name.npos; // but no other hierarchy separator
}};
auto handles = cci_broker.get_param_handles(pred);
for (auto &h : handles) {
auto value = h.get_cci_value();
auto paramname = std::string{h.name()};
auto basename = paramname.substr(paramname.find_last_of('.') + 1);
if (value.is_bool())
node[basename] = value.get_bool();
else if (value.is_int())
node[basename] = value.get_int();
else if (value.is_int64())
node[basename] = static_cast<int64_t>(value.get_int64());
else if (value.is_uint())
node[basename] = value.get_uint();
else if (value.is_uint64())
node[basename] = static_cast<uint64_t>(value.get_uint64());
else if (value.is_double())
node[basename] = value.get_double();
else if (value.is_string())
node[basename] = value.get_string().c_str();
}
for (auto *o : get_sc_objects(obj)) dump_configuration(o, node);
if (!node.empty()) parent[obj->basename()] = node;
}
void scc::configurer::configure() {
if(config_valid)
for (auto *o : sc_core::sc_get_top_level_objects(sc_core::sc_curr_simcontext)) {
Json::Value &val = root[o->name()];
if (!val.isNull())
configure_sc_attribute_hierarchical(o, val);
}
}
void scc::configurer::configure_sc_attribute_hierarchical(sc_core::sc_object *obj, Json::Value &hier_val) {
for (auto *attr : obj->attr_cltn()) {
Json::Value &val = hier_val[attr->name()];
if (!val.isNull()) set_value(attr, val);
}
for (auto *o : obj->get_child_objects()) {
Json::Value &val = hier_val[o->basename()];
if (!val.isNull()) configure_sc_attribute_hierarchical(o, val);
}
}
#define CHECK_N_ASSIGN(TYPE, ATTR, VAL) \
{ \
auto *a = dynamic_cast<sc_core::sc_attribute<TYPE> *>(ATTR); \
if (a != nullptr) { \
a->value = VAL; \
return; \
} \
}
void scc::configurer::set_value(sc_core::sc_attr_base *attr_base, Json::Value &hier_val) {
CHECK_N_ASSIGN(int, attr_base, hier_val.asInt());
CHECK_N_ASSIGN(unsigned, attr_base, hier_val.asUInt());
CHECK_N_ASSIGN(int64_t, attr_base, hier_val.asInt64());
CHECK_N_ASSIGN(uint64_t, attr_base, hier_val.asUInt64());
CHECK_N_ASSIGN(bool, attr_base, hier_val.asBool());
CHECK_N_ASSIGN(float, attr_base, hier_val.asFloat());
CHECK_N_ASSIGN(double, attr_base, hier_val.asDouble());
CHECK_N_ASSIGN(std::string, attr_base, hier_val.asString());
CHECK_N_ASSIGN(char *, attr_base, strdup(hier_val.asCString()));
}
Json::Value &scc::configurer::get_value_from_hierarchy(const std::string &hier_name) {
size_t npos = hier_name.find_first_of('.');
Json::Value &val = root[hier_name.substr(0, npos)];
if (val.isNull() || npos == hier_name.size()) return val;
return get_value_from_hierarchy(hier_name.substr(npos + 1, hier_name.size()), val);
}
Json::Value &scc::configurer::get_value_from_hierarchy(const std::string &hier_name, Json::Value &value) {
size_t npos = hier_name.find_first_of('.');
Json::Value &val = value[hier_name.substr(0, npos)];
if (val.isNull() || npos == std::string::npos || !val.isObject()) return val;
return get_value_from_hierarchy(hier_name.substr(npos + 1, hier_name.size()), val);
}
void scc::configurer::set_configuration_value(sc_core::sc_attr_base *attr_base, sc_core::sc_object *owner) {
std::string name(owner->name());
name += ".";
name += attr_base->name();
Json::Value &val = get_value_from_hierarchy(name);
if (!val.isNull()) set_value(attr_base, val);
}
void scc::configurer::configure_cci_hierarchical(const Json::Value &node, std::string prefix) {
if (node.size() > 0) {
for (Json::Value::const_iterator itr = node.begin(); itr != node.end(); ++itr) {
if (!itr.key().isString()) return;
std::string key_name = itr.key().asString();
std::string hier_name{prefix.size() ? prefix + "." + key_name : key_name};
Json::Value val = node[key_name];
if (val.isNull() || val.isArray())
return;
else if (val.isObject())
configure_cci_hierarchical(*itr, hier_name);
else {
cci::cci_param_handle param_handle = cci_broker.get_param_handle(hier_name);
if (param_handle.is_valid()) {
if (val.isString()) {
param_handle.set_cci_value(cci::cci_value(val.asString()));
} else if (val.isBool()) {
param_handle.set_cci_value(cci::cci_value(val.asBool()));
} else if (val.isInt()) {
param_handle.set_cci_value(cci::cci_value(val.asInt()));
} else if (val.isInt64()) {
param_handle.set_cci_value(cci::cci_value(val.asInt64()));
} else if (val.isUInt()) {
param_handle.set_cci_value(cci::cci_value(val.asUInt()));
} else if (val.isUInt64()) {
param_handle.set_cci_value(cci::cci_value(val.asUInt64()));
} else if (val.isDouble()) {
param_handle.set_cci_value(cci::cci_value(val.asDouble()));
}
} else {
if (val.isString()) {
cci_broker.set_preset_cci_value(hier_name, cci::cci_value(val.asString()));
} else if (val.isBool()) {
cci_broker.set_preset_cci_value(hier_name, cci::cci_value(val.asBool()));
} else if (val.isInt()) {
cci_broker.set_preset_cci_value(hier_name, cci::cci_value(val.asInt()));
} else if (val.isInt64()) {
cci_broker.set_preset_cci_value(hier_name, cci::cci_value(val.asInt64()));
} else if (val.isUInt()) {
cci_broker.set_preset_cci_value(hier_name, cci::cci_value(val.asUInt()));
} else if (val.isUInt64()) {
cci_broker.set_preset_cci_value(hier_name, cci::cci_value(val.asUInt64()));
} else if (val.isDouble()) {
cci_broker.set_preset_cci_value(hier_name, cci::cci_value(val.asDouble()));
}
}
}
}
}
}
void scc::init_cci(std::string name) {
cci::cci_register_broker(new cci_utils::broker("Global Broker"));
}
<commit_msg>Fixed cci parameter filtering<commit_after>/*******************************************************************************
* Copyright 2017, 2018 MINRES Technologies GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
/*
* configurer.cpp
*
* Created on: 27.09.2017
* Author: eyck
*/
#include "scc/configurer.h"
#include "scc/report.h"
#include <cci_configuration>
#include <cci_utils/broker.h>
#include <boost/algorithm/string/predicate.hpp>
#include <fstream>
scc::configurer::configurer(const std::string &filename)
: base_type("configurer")
, cci_originator("configurer")
, cci_broker(cci::cci_get_global_broker(cci_originator)) {
if (filename.length() > 0) {
std::ifstream is(filename);
if (is.is_open()) {
try {
is >> root;
configure_cci_hierarchical(root, "");
config_valid=true;
} catch (Json::RuntimeError &e) {
LOG(ERROR) << "Could not parse input file " << filename << ", reason: " << e.what();
}
} else {
LOG(ERROR) << "Could not open input file " << filename;
}
}
}
void scc::configurer::dump_hierarchy(std::ostream &os, sc_core::sc_object *obj) {
if (obj) {
os << obj->name() << " of type " << typeid(*obj).name() << "\n";
for (auto *o : obj->get_child_objects()) dump_hierarchy(os);
} else {
for (auto *o : sc_core::sc_get_top_level_objects(sc_core::sc_curr_simcontext)) dump_hierarchy(os, o);
}
}
inline const std::vector<sc_core::sc_object *> &get_sc_objects(sc_core::sc_object *obj = nullptr) {
if (obj)
return obj->get_child_objects();
else
return sc_core::sc_get_top_level_objects(sc_core::sc_curr_simcontext);
}
void scc::configurer::dump_configuration(std::ostream &os, sc_core::sc_object *obj) {
Json::Value root{Json::objectValue};
for (auto *o : get_sc_objects(obj)) {
dump_configuration(o, root);
}
// For convenience, use `writeString()` with a specialized builder.
Json::StreamWriterBuilder wbuilder;
wbuilder["indentation"] = "\t";
wbuilder["enableYAMLCompatibility"] = true;
wbuilder["commentStyle"] ="None";
wbuilder.newStreamWriter()->write(root, &os);
// another (default) option:
// os << root;
}
#define CHECK_N_ASSIGN_VAL(TYPE, ATTR) \
{ \
auto *a = dynamic_cast<sc_core::sc_attribute<TYPE> *>(ATTR); \
if (a != nullptr) { \
node[a->name()] = a->value; \
continue; \
} \
}
void scc::configurer::dump_configuration(sc_core::sc_object *obj, Json::Value &parent) {
auto mod = dynamic_cast<sc_core::sc_module *>(obj);
Json::Value node{Json::objectValue};
for (sc_core::sc_attr_base *attr_base : obj->attr_cltn()) {
CHECK_N_ASSIGN_VAL(int, attr_base);
CHECK_N_ASSIGN_VAL(unsigned, attr_base);
CHECK_N_ASSIGN_VAL(int64_t, attr_base);
CHECK_N_ASSIGN_VAL(uint64_t, attr_base);
CHECK_N_ASSIGN_VAL(bool, attr_base);
CHECK_N_ASSIGN_VAL(float, attr_base);
CHECK_N_ASSIGN_VAL(double, attr_base);
CHECK_N_ASSIGN_VAL(std::string, attr_base);
CHECK_N_ASSIGN_VAL(char *, attr_base);
}
const std::string hier_name{obj->name()};
cci::cci_param_predicate pred{[hier_name](cci::cci_param_untyped_handle h) -> bool {
std::string h_name {h.name()};
auto sep = hier_name.length();
if(h_name.length()>hier_name.length()){
auto path_match = h_name.compare(0, sep, hier_name)==0; // begins with hier_name
auto sep_match = h_name[sep]=='.' ; // has additional part
auto tail_nomatch = h_name.substr(sep+1).find('.')==h_name.npos; // but no other hierarchy separator
return path_match && sep_match && tail_nomatch;
} else
return false;
}};
auto handles = cci_broker.get_param_handles(pred);
for (auto &h : handles) {
auto value = h.get_cci_value();
auto paramname = std::string{h.name()};
auto basename = paramname.substr(paramname.find_last_of('.') + 1);
if (value.is_bool())
node[basename] = value.get_bool();
else if (value.is_int())
node[basename] = value.get_int();
else if (value.is_int64())
node[basename] = static_cast<int64_t>(value.get_int64());
else if (value.is_uint())
node[basename] = value.get_uint();
else if (value.is_uint64())
node[basename] = static_cast<uint64_t>(value.get_uint64());
else if (value.is_double())
node[basename] = value.get_double();
else if (value.is_string())
node[basename] = value.get_string().c_str();
}
for (auto *o : get_sc_objects(obj)) dump_configuration(o, node);
if (!node.empty()) parent[obj->basename()] = node;
}
void scc::configurer::configure() {
if(config_valid)
for (auto *o : sc_core::sc_get_top_level_objects(sc_core::sc_curr_simcontext)) {
Json::Value &val = root[o->name()];
if (!val.isNull())
configure_sc_attribute_hierarchical(o, val);
}
}
void scc::configurer::configure_sc_attribute_hierarchical(sc_core::sc_object *obj, Json::Value &hier_val) {
for (auto *attr : obj->attr_cltn()) {
Json::Value &val = hier_val[attr->name()];
if (!val.isNull()) set_value(attr, val);
}
for (auto *o : obj->get_child_objects()) {
Json::Value &val = hier_val[o->basename()];
if (!val.isNull()) configure_sc_attribute_hierarchical(o, val);
}
}
#define CHECK_N_ASSIGN(TYPE, ATTR, VAL) \
{ \
auto *a = dynamic_cast<sc_core::sc_attribute<TYPE> *>(ATTR); \
if (a != nullptr) { \
a->value = VAL; \
return; \
} \
}
void scc::configurer::set_value(sc_core::sc_attr_base *attr_base, Json::Value &hier_val) {
CHECK_N_ASSIGN(int, attr_base, hier_val.asInt());
CHECK_N_ASSIGN(unsigned, attr_base, hier_val.asUInt());
CHECK_N_ASSIGN(int64_t, attr_base, hier_val.asInt64());
CHECK_N_ASSIGN(uint64_t, attr_base, hier_val.asUInt64());
CHECK_N_ASSIGN(bool, attr_base, hier_val.asBool());
CHECK_N_ASSIGN(float, attr_base, hier_val.asFloat());
CHECK_N_ASSIGN(double, attr_base, hier_val.asDouble());
CHECK_N_ASSIGN(std::string, attr_base, hier_val.asString());
CHECK_N_ASSIGN(char *, attr_base, strdup(hier_val.asCString()));
}
Json::Value &scc::configurer::get_value_from_hierarchy(const std::string &hier_name) {
size_t npos = hier_name.find_first_of('.');
Json::Value &val = root[hier_name.substr(0, npos)];
if (val.isNull() || npos == hier_name.size()) return val;
return get_value_from_hierarchy(hier_name.substr(npos + 1, hier_name.size()), val);
}
Json::Value &scc::configurer::get_value_from_hierarchy(const std::string &hier_name, Json::Value &value) {
size_t npos = hier_name.find_first_of('.');
Json::Value &val = value[hier_name.substr(0, npos)];
if (val.isNull() || npos == std::string::npos || !val.isObject()) return val;
return get_value_from_hierarchy(hier_name.substr(npos + 1, hier_name.size()), val);
}
void scc::configurer::set_configuration_value(sc_core::sc_attr_base *attr_base, sc_core::sc_object *owner) {
std::string name(owner->name());
name += ".";
name += attr_base->name();
Json::Value &val = get_value_from_hierarchy(name);
if (!val.isNull()) set_value(attr_base, val);
}
void scc::configurer::configure_cci_hierarchical(const Json::Value &node, std::string prefix) {
if (node.size() > 0) {
for (Json::Value::const_iterator itr = node.begin(); itr != node.end(); ++itr) {
if (!itr.key().isString()) return;
std::string key_name = itr.key().asString();
std::string hier_name{prefix.size() ? prefix + "." + key_name : key_name};
Json::Value val = node[key_name];
if (val.isNull() || val.isArray())
return;
else if (val.isObject())
configure_cci_hierarchical(*itr, hier_name);
else {
cci::cci_param_handle param_handle = cci_broker.get_param_handle(hier_name);
if (param_handle.is_valid()) {
if (val.isString()) {
param_handle.set_cci_value(cci::cci_value(val.asString()));
} else if (val.isBool()) {
param_handle.set_cci_value(cci::cci_value(val.asBool()));
} else if (val.isInt()) {
param_handle.set_cci_value(cci::cci_value(val.asInt()));
} else if (val.isInt64()) {
param_handle.set_cci_value(cci::cci_value(val.asInt64()));
} else if (val.isUInt()) {
param_handle.set_cci_value(cci::cci_value(val.asUInt()));
} else if (val.isUInt64()) {
param_handle.set_cci_value(cci::cci_value(val.asUInt64()));
} else if (val.isDouble()) {
param_handle.set_cci_value(cci::cci_value(val.asDouble()));
}
} else {
if (val.isString()) {
cci_broker.set_preset_cci_value(hier_name, cci::cci_value(val.asString()));
} else if (val.isBool()) {
cci_broker.set_preset_cci_value(hier_name, cci::cci_value(val.asBool()));
} else if (val.isInt()) {
cci_broker.set_preset_cci_value(hier_name, cci::cci_value(val.asInt()));
} else if (val.isInt64()) {
cci_broker.set_preset_cci_value(hier_name, cci::cci_value(val.asInt64()));
} else if (val.isUInt()) {
cci_broker.set_preset_cci_value(hier_name, cci::cci_value(val.asUInt()));
} else if (val.isUInt64()) {
cci_broker.set_preset_cci_value(hier_name, cci::cci_value(val.asUInt64()));
} else if (val.isDouble()) {
cci_broker.set_preset_cci_value(hier_name, cci::cci_value(val.asDouble()));
}
}
}
}
}
}
void scc::init_cci(std::string name) {
cci::cci_register_broker(new cci_utils::broker("Global Broker"));
}
<|endoftext|> |
<commit_before> /*
NUI3 - C++ cross-platform GUI framework for OpenGL based applications
Copyright (C) 2002-2003 Sebastien Metrot
licence: see nui3/LICENCE.TXT
*/
#include "nui.h"
nuiTextLine::nuiTextLine(const nuiTextLayout& rLayout, float X, float Y)
: mLayout(rLayout), mX(X), mY(Y)
{
}
nuiTextLine::~nuiTextLine()
{
for (uint32 i = 0; i < mpRuns.size(); i++)
mpRuns[i]->Release();
}
const std::vector<nuiTextRun*>& nuiTextLine::GetGlyphRuns() const
{
return mpRuns;
}
float nuiTextLine::GetX() const
{
return mX;
}
float nuiTextLine::GetY() const
{
return mY;
}
void nuiTextLine::SetPosition(float X, float Y)
{
mX = X;
mY = Y;
}
void nuiTextLine::AddRun(nuiTextRun* pRun)
{
pRun->Acquire();
mpRuns.push_back(pRun);
}
int32 nuiTextLine::GetRunCount() const
{
return mpRuns.size();
}
nuiTextRun* nuiTextLine::GetRun(int32 index) const
{
return mpRuns[index];
}
float nuiTextLine::GetAdvanceY() const
{
float y = 0;
for (uint32 i = 0; i < mpRuns.size(); i++)
{
y = MAX(y, mpRuns[i]->GetAdvanceY());
}
return y;
}
float nuiTextLine::GetAdvanceX() const
{
float x = 0;
for (uint32 i = 0; i < mpRuns.size(); i++)
{
x += mpRuns[i]->GetAdvanceX();
}
return x;
}
float nuiTextLine::GetAscender() const
{
float v = 0;
for (uint32 i = 0; i < mpRuns.size(); i++)
{
v = MAX(v, mpRuns[i]->GetAscender());
}
return v;
}
float nuiTextLine::GetDescender() const
{
float v = 0;
for (uint32 i = 0; i < mpRuns.size(); i++)
{
v = MIN(v, mpRuns[i]->GetAscender());
}
return v;
}
int32 nuiTextLine::GetGlyphCount() const
{
int32 count = 0;
for (uint32 i = 0; i < mpRuns.size(); i++)
{
count += mpRuns[i]->GetGlyphCount();
}
return count;
}
const nuiTextGlyph* nuiTextLine::GetGlyph(int32 Offset) const
{
for (uint32 i = 0; i < mpRuns.size(); i++)
{
int32 s = mpRuns[i]->GetGlyphCount();
if (Offset < s)
return mpRuns[i]->GetGlyph(Offset);
Offset -= s;
}
return NULL;
}
const nuiTextGlyph* nuiTextLine::GetGlyphAt(float X, float Y) const
{
X -= mX;
Y -= mY;
for (uint32 i = 0; i < mpRuns.size(); i++)
{
const nuiTextGlyph* pGlyph = mpRuns[i]->GetGlyphAt(X, Y);
if (pGlyph)
return pGlyph;
}
return NULL;
}
float LayoutDirect(float PenX, float PenY, float globalwidth, float sublinewidth, float spacewidth, std::list<nuiTextRun*>& subline, nuiRect& globalrect)
{
float h = 0;
float x = 0;
float y = 0;
for (nuiTextRun* pRun : subline)
{
nuiFontBase* pFont = pRun->GetFont();
nuiFontInfo finfo;
if (pFont)
pFont->GetInfo(finfo);
std::vector<nuiTextGlyph>& rGlyphs(pRun->GetGlyphs());
// Prepare glyphs:
for (int32 g = 0; g < rGlyphs.size(); g++)
{
nuiTextGlyph& rGlyph(rGlyphs.at(g));
pFont->PrepareGlyph(PenX + x, PenY + y, rGlyph);
const nuiSize W = rGlyph.AdvanceX;
const nuiSize X = rGlyph.mX + rGlyph.BearingX;
const nuiSize Y = rGlyph.mY - finfo.Ascender;
const nuiSize H = finfo.Height;
h = MAX(h, H);
nuiRect rr(globalrect);
globalrect.Union(rr, nuiRect(PenX + x + X, PenY + y + Y, W, H));
}
x += pRun->GetAdvanceX();
}
return h;
}
float LayoutJustify(float PenX, float PenY, float globalwidth, float sublinewidth, float spacewidth, std::list<nuiTextRun*>& subline, nuiRect& globalrect)
{
float h = 0;
float x = 0;
float y = 0;
float ratio = (globalwidth - (sublinewidth - spacewidth)) / spacewidth;
for (nuiTextRun* pRun : subline)
{
nuiFontBase* pFont = pRun->GetFont();
nuiFontInfo finfo;
if (pFont)
pFont->GetInfo(finfo);
std::vector<nuiTextGlyph>& rGlyphs(pRun->GetGlyphs());
// Prepare glyphs:
for (int32 g = 0; g < rGlyphs.size(); g++)
{
nuiTextGlyph& rGlyph(rGlyphs.at(g));
pFont->PrepareGlyph(PenX + x, PenY + y, rGlyph);
const nuiSize W = rGlyph.AdvanceX;
const nuiSize X = rGlyph.mX + rGlyph.BearingX;
const nuiSize Y = rGlyph.mY - finfo.Ascender;
const nuiSize H = finfo.Height;
h = MAX(h, H);
nuiRect rr(globalrect);
globalrect.Union(rr, nuiRect(PenX + x + X, PenY + y + Y, W, H));
}
if (pRun->IsDummy())
{
x += pRun->GetAdvanceX() * ratio;
}
else
{
x += pRun->GetAdvanceX();
}
}
return h;
}
float LayoutLeft(float PenX, float PenY, float globalwidth, float sublinewidth, float spacewidth, std::list<nuiTextRun*>& subline, nuiRect& globalrect)
{
return LayoutDirect(PenX, PenY, globalwidth, sublinewidth, spacewidth, subline, globalrect);
}
float LayoutRight(float PenX, float PenY, float globalwidth, float sublinewidth, float spacewidth, std::list<nuiTextRun*>& subline, nuiRect& globalrect)
{
float x = globalwidth - sublinewidth;
return LayoutDirect(PenX + x, PenY, globalwidth, sublinewidth, spacewidth, subline, globalrect);
}
float LayoutCenter(float PenX, float PenY, float globalwidth, float sublinewidth, float spacewidth, std::list<nuiTextRun*>& subline, nuiRect& globalrect)
{
float x = (globalwidth - sublinewidth) / 2;
return LayoutDirect(PenX + x, PenY, globalwidth, sublinewidth, spacewidth, subline, globalrect);
}
float nuiTextLine::Layout(float PenX, float PenY, float width, nuiRect& globalrect)
{
SetPosition(PenX, PenY);
PenX = 0;
float x = 0;
float y = 0;
std::vector< std::list <nuiTextRun*> > sublines;
sublines.resize(1);
bool sublinestart = true;
// Prepare sublines:
for (uint32 r = 0; r < GetRunCount(); r++)
{
nuiTextRun* pRun = GetRun(r);
if (pRun->IsWrapStart())
sublines.resize(sublines.size() + 1);
sublines.back().push_back(pRun);
}
// Trim the dummy runs:
for (int l = 0; l < sublines.size(); l++)
{
// Remove dummy text runs from the start of the lines (except the first line):
bool skip = false;
if (sublines[l].front()->GetStyle().GetMode() == nuiTextLayoutJustify && l == 0)
skip = true;
if (!skip)
{
while (!sublines.empty() && sublines[l].front()->IsDummy())
sublines[l].pop_front();
}
// Remove dummy text runs from the end of the lines:
while (!sublines.empty() && sublines[l].back()->IsDummy())
sublines[l].pop_back();
}
// Now position each run inside each subline:
for (int l = 0; l < sublines.size(); l++)
{
float w = 0;
float space = 0;
for (nuiTextRun* pRun : sublines[l])
{
float a = pRun->GetAdvanceX();
w += a;
if (pRun->IsDummy())
space += a;
}
float h = 0;
switch (sublines[l].front()->GetStyle().GetMode())
{
case nuiTextLayoutLeft:
h = LayoutLeft(PenX, PenY, width, w, space, sublines[l], globalrect);
break;
case nuiTextLayoutRight:
h = LayoutRight(PenX, PenY, width, w, space, sublines[l], globalrect);
break;
case nuiTextLayoutJustify:
h = LayoutJustify(PenX, PenY, width, w, space, sublines[l], globalrect);
break;
case nuiTextLayoutCenter:
h = LayoutCenter(PenX, PenY, width, w, space, sublines[l], globalrect);
break;
}
PenY += h;
}
return PenY;
}
<commit_msg>fixed corner cases crashes<commit_after> /*
NUI3 - C++ cross-platform GUI framework for OpenGL based applications
Copyright (C) 2002-2003 Sebastien Metrot
licence: see nui3/LICENCE.TXT
*/
#include "nui.h"
nuiTextLine::nuiTextLine(const nuiTextLayout& rLayout, float X, float Y)
: mLayout(rLayout), mX(X), mY(Y)
{
}
nuiTextLine::~nuiTextLine()
{
for (uint32 i = 0; i < mpRuns.size(); i++)
mpRuns[i]->Release();
}
const std::vector<nuiTextRun*>& nuiTextLine::GetGlyphRuns() const
{
return mpRuns;
}
float nuiTextLine::GetX() const
{
return mX;
}
float nuiTextLine::GetY() const
{
return mY;
}
void nuiTextLine::SetPosition(float X, float Y)
{
mX = X;
mY = Y;
}
void nuiTextLine::AddRun(nuiTextRun* pRun)
{
pRun->Acquire();
mpRuns.push_back(pRun);
}
int32 nuiTextLine::GetRunCount() const
{
return mpRuns.size();
}
nuiTextRun* nuiTextLine::GetRun(int32 index) const
{
return mpRuns[index];
}
float nuiTextLine::GetAdvanceY() const
{
float y = 0;
for (uint32 i = 0; i < mpRuns.size(); i++)
{
y = MAX(y, mpRuns[i]->GetAdvanceY());
}
return y;
}
float nuiTextLine::GetAdvanceX() const
{
float x = 0;
for (uint32 i = 0; i < mpRuns.size(); i++)
{
x += mpRuns[i]->GetAdvanceX();
}
return x;
}
float nuiTextLine::GetAscender() const
{
float v = 0;
for (uint32 i = 0; i < mpRuns.size(); i++)
{
v = MAX(v, mpRuns[i]->GetAscender());
}
return v;
}
float nuiTextLine::GetDescender() const
{
float v = 0;
for (uint32 i = 0; i < mpRuns.size(); i++)
{
v = MIN(v, mpRuns[i]->GetAscender());
}
return v;
}
int32 nuiTextLine::GetGlyphCount() const
{
int32 count = 0;
for (uint32 i = 0; i < mpRuns.size(); i++)
{
count += mpRuns[i]->GetGlyphCount();
}
return count;
}
const nuiTextGlyph* nuiTextLine::GetGlyph(int32 Offset) const
{
for (uint32 i = 0; i < mpRuns.size(); i++)
{
int32 s = mpRuns[i]->GetGlyphCount();
if (Offset < s)
return mpRuns[i]->GetGlyph(Offset);
Offset -= s;
}
return NULL;
}
const nuiTextGlyph* nuiTextLine::GetGlyphAt(float X, float Y) const
{
X -= mX;
Y -= mY;
for (uint32 i = 0; i < mpRuns.size(); i++)
{
const nuiTextGlyph* pGlyph = mpRuns[i]->GetGlyphAt(X, Y);
if (pGlyph)
return pGlyph;
}
return NULL;
}
float LayoutDirect(float PenX, float PenY, float globalwidth, float sublinewidth, float spacewidth, std::list<nuiTextRun*>& subline, nuiRect& globalrect)
{
float h = 0;
float x = 0;
float y = 0;
for (nuiTextRun* pRun : subline)
{
nuiFontBase* pFont = pRun->GetFont();
nuiFontInfo finfo;
if (pFont)
pFont->GetInfo(finfo);
std::vector<nuiTextGlyph>& rGlyphs(pRun->GetGlyphs());
// Prepare glyphs:
for (int32 g = 0; g < rGlyphs.size(); g++)
{
nuiTextGlyph& rGlyph(rGlyphs.at(g));
pFont->PrepareGlyph(PenX + x, PenY + y, rGlyph);
const nuiSize W = rGlyph.AdvanceX;
const nuiSize X = rGlyph.mX + rGlyph.BearingX;
const nuiSize Y = rGlyph.mY - finfo.Ascender;
const nuiSize H = finfo.Height;
h = MAX(h, H);
nuiRect rr(globalrect);
globalrect.Union(rr, nuiRect(PenX + x + X, PenY + y + Y, W, H));
}
x += pRun->GetAdvanceX();
}
return h;
}
float LayoutJustify(float PenX, float PenY, float globalwidth, float sublinewidth, float spacewidth, std::list<nuiTextRun*>& subline, nuiRect& globalrect)
{
float h = 0;
float x = 0;
float y = 0;
float ratio = (globalwidth - (sublinewidth - spacewidth)) / spacewidth;
for (nuiTextRun* pRun : subline)
{
nuiFontBase* pFont = pRun->GetFont();
nuiFontInfo finfo;
if (pFont)
pFont->GetInfo(finfo);
std::vector<nuiTextGlyph>& rGlyphs(pRun->GetGlyphs());
// Prepare glyphs:
for (int32 g = 0; g < rGlyphs.size(); g++)
{
nuiTextGlyph& rGlyph(rGlyphs.at(g));
pFont->PrepareGlyph(PenX + x, PenY + y, rGlyph);
const nuiSize W = rGlyph.AdvanceX;
const nuiSize X = rGlyph.mX + rGlyph.BearingX;
const nuiSize Y = rGlyph.mY - finfo.Ascender;
const nuiSize H = finfo.Height;
h = MAX(h, H);
nuiRect rr(globalrect);
globalrect.Union(rr, nuiRect(PenX + x + X, PenY + y + Y, W, H));
}
if (pRun->IsDummy())
{
x += pRun->GetAdvanceX() * ratio;
}
else
{
x += pRun->GetAdvanceX();
}
}
return h;
}
float LayoutLeft(float PenX, float PenY, float globalwidth, float sublinewidth, float spacewidth, std::list<nuiTextRun*>& subline, nuiRect& globalrect)
{
return LayoutDirect(PenX, PenY, globalwidth, sublinewidth, spacewidth, subline, globalrect);
}
float LayoutRight(float PenX, float PenY, float globalwidth, float sublinewidth, float spacewidth, std::list<nuiTextRun*>& subline, nuiRect& globalrect)
{
float x = globalwidth - sublinewidth;
return LayoutDirect(PenX + x, PenY, globalwidth, sublinewidth, spacewidth, subline, globalrect);
}
float LayoutCenter(float PenX, float PenY, float globalwidth, float sublinewidth, float spacewidth, std::list<nuiTextRun*>& subline, nuiRect& globalrect)
{
float x = (globalwidth - sublinewidth) / 2;
return LayoutDirect(PenX + x, PenY, globalwidth, sublinewidth, spacewidth, subline, globalrect);
}
float nuiTextLine::Layout(float PenX, float PenY, float width, nuiRect& globalrect)
{
SetPosition(PenX, PenY);
PenX = 0;
float x = 0;
float y = 0;
std::vector< std::list <nuiTextRun*> > sublines;
sublines.resize(1);
bool sublinestart = true;
// Prepare sublines:
for (uint32 r = 0; r < GetRunCount(); r++)
{
nuiTextRun* pRun = GetRun(r);
if (pRun->IsWrapStart())
sublines.resize(sublines.size() + 1);
sublines.back().push_back(pRun);
}
// Trim the dummy runs:
for (int l = 0; l < sublines.size(); l++)
{
// Remove dummy text runs from the start of the lines (except the first line):
bool skip = false;
if (!sublines[l].empty() && sublines[l].front()->GetStyle().GetMode() == nuiTextLayoutJustify && l == 0)
skip = true;
if (!skip)
{
while (!sublines.empty() && !sublines[l].empty() && sublines[l].front()->IsDummy())
sublines[l].pop_front();
}
// Remove dummy text runs from the end of the lines:
while (!sublines.empty() && !sublines[l].empty() && sublines[l].back()->IsDummy())
sublines[l].pop_back();
}
// Now position each run inside each subline:
for (int l = 0; l < sublines.size(); l++)
{
float w = 0;
float space = 0;
for (nuiTextRun* pRun : sublines[l])
{
float a = pRun->GetAdvanceX();
w += a;
if (pRun->IsDummy())
space += a;
}
float h = 0;
if (!sublines[l].empty())
{
switch (sublines[l].front()->GetStyle().GetMode())
{
case nuiTextLayoutLeft:
h = LayoutLeft(PenX, PenY, width, w, space, sublines[l], globalrect);
break;
case nuiTextLayoutRight:
h = LayoutRight(PenX, PenY, width, w, space, sublines[l], globalrect);
break;
case nuiTextLayoutJustify:
h = LayoutJustify(PenX, PenY, width, w, space, sublines[l], globalrect);
break;
case nuiTextLayoutCenter:
h = LayoutCenter(PenX, PenY, width, w, space, sublines[l], globalrect);
break;
}
}
PenY += h;
}
return PenY;
}
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright (C) 2015 ScyllaDB
*
* Modified by ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla 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.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "bytes.hh"
#include "schema.hh"
#include "query-result-reader.hh"
#include "cql3/column_specification.hh"
#include "exceptions/exceptions.hh"
#include "cql3/selection/raw_selector.hh"
#include "cql3/selection/selector_factories.hh"
#include "cql3/restrictions/statement_restrictions.hh"
#include "unimplemented.hh"
namespace cql3 {
class result_set;
class metadata;
namespace selection {
class selectors {
public:
virtual ~selectors() {}
virtual bool is_aggregate() = 0;
/**
* Adds the current row of the specified <code>ResultSetBuilder</code>.
*
* @param rs the <code>ResultSetBuilder</code>
* @throws InvalidRequestException
*/
virtual void add_input_row(cql_serialization_format sf, result_set_builder& rs) = 0;
virtual std::vector<bytes_opt> get_output_row(cql_serialization_format sf) = 0;
virtual void reset() = 0;
};
class selection {
private:
schema_ptr _schema;
std::vector<const column_definition*> _columns;
::shared_ptr<metadata> _metadata;
const bool _collect_timestamps;
const bool _collect_TTLs;
const bool _contains_static_columns;
bool _is_trivial;
protected:
using trivial = bool_class<class trivial_tag>;
selection(schema_ptr schema,
std::vector<const column_definition*> columns,
std::vector<::shared_ptr<column_specification>> metadata_,
bool collect_timestamps,
bool collect_TTLs, trivial is_trivial = trivial::no);
virtual ~selection() {}
public:
// Overriden by SimpleSelection when appropriate.
virtual bool is_wildcard() const {
return false;
}
/**
* Checks if this selection contains static columns.
* @return <code>true</code> if this selection contains static columns, <code>false</code> otherwise;
*/
bool contains_static_columns() const {
return _contains_static_columns;
}
/**
* Checks if this selection contains only static columns.
* @return <code>true</code> if this selection contains only static columns, <code>false</code> otherwise;
*/
bool contains_only_static_columns() const {
if (!contains_static_columns()) {
return false;
}
if (is_wildcard()) {
return false;
}
for (auto&& def : _columns) {
if (!def->is_partition_key() && !def->is_static()) {
return false;
}
}
return true;
}
/**
* Checks if this selection contains a collection.
*
* @return <code>true</code> if this selection contains a collection, <code>false</code> otherwise.
*/
bool contains_a_collection() const {
if (!_schema->has_multi_cell_collections()) {
return false;
}
return std::any_of(_columns.begin(), _columns.end(), [] (auto&& def) {
return def->type->is_collection() && def->type->is_multi_cell();
});
}
/**
* Returns the index of the specified column.
*
* @param def the column definition
* @return the index of the specified column
*/
int32_t index_of(const column_definition& def) const {
auto i = std::find(_columns.begin(), _columns.end(), &def);
if (i == _columns.end()) {
return -1;
}
return std::distance(_columns.begin(), i);
}
bool has_column(const column_definition& def) const {
return std::find(_columns.begin(), _columns.end(), &def) != _columns.end();
}
::shared_ptr<const metadata> get_result_metadata() const {
return _metadata;
}
static ::shared_ptr<selection> wildcard(schema_ptr schema);
static ::shared_ptr<selection> for_columns(schema_ptr schema, std::vector<const column_definition*> columns);
virtual uint32_t add_column_for_ordering(const column_definition& c);
virtual bool uses_function(const sstring &ks_name, const sstring& function_name) const {
return false;
}
query::partition_slice::option_set get_query_options();
private:
static bool processes_selection(const std::vector<::shared_ptr<raw_selector>>& raw_selectors) {
return std::any_of(raw_selectors.begin(), raw_selectors.end(),
[] (auto&& s) { return s->processes_selection(); });
}
static std::vector<::shared_ptr<column_specification>> collect_metadata(schema_ptr schema,
const std::vector<::shared_ptr<raw_selector>>& raw_selectors, const selector_factories& factories);
public:
static ::shared_ptr<selection> from_selectors(database& db, schema_ptr schema, const std::vector<::shared_ptr<raw_selector>>& raw_selectors);
virtual std::unique_ptr<selectors> new_selectors() const = 0;
/**
* Returns a range of CQL3 columns this selection needs.
*/
auto const& get_columns() const {
return _columns;
}
uint32_t get_column_count() const {
return _columns.size();
}
virtual bool is_aggregate() const = 0;
/**
* Checks that selectors are either all aggregates or that none of them is.
*
* @param selectors the selectors to test.
* @param messageTemplate the error message template
* @param messageArgs the error message arguments
* @throws InvalidRequestException if some of the selectors are aggregate but not all of them
*/
template<typename... Args>
static void validate_selectors(const std::vector<::shared_ptr<selector>>& selectors, const sstring& msg, Args&&... args) {
int32_t aggregates = 0;
for (auto&& s : selectors) {
if (s->is_aggregate()) {
++aggregates;
}
}
if (aggregates != 0 && aggregates != selectors.size()) {
throw exceptions::invalid_request_exception(sprint(msg, std::forward<Args>(args)...));
}
}
/**
* Returns true if the selection is trivial, i.e. there are no function
* selectors (including casts or aggregates).
*/
bool is_trivial() const { return _is_trivial; }
friend class result_set_builder;
};
class result_set_builder {
private:
std::unique_ptr<result_set> _result_set;
std::unique_ptr<selectors> _selectors;
public:
std::experimental::optional<std::vector<bytes_opt>> current;
private:
std::vector<api::timestamp_type> _timestamps;
std::vector<int32_t> _ttls;
const gc_clock::time_point _now;
cql_serialization_format _cql_serialization_format;
public:
class nop_filter {
public:
inline bool operator()(const selection&, const std::vector<bytes>&, const std::vector<bytes>&, const query::result_row_view&, const query::result_row_view&) const {
return true;
}
void reset() {
}
};
class restrictions_filter {
::shared_ptr<restrictions::statement_restrictions> _restrictions;
const query_options& _options;
mutable bool _current_partition_key_does_not_match = false;
mutable bool _current_static_row_does_not_match = false;
public:
restrictions_filter() = default;
explicit restrictions_filter(::shared_ptr<restrictions::statement_restrictions> restrictions, const query_options& options) : _restrictions(restrictions), _options(options) {}
bool operator()(const selection& selection, const std::vector<bytes>& pk, const std::vector<bytes>& ck, const query::result_row_view& static_row, const query::result_row_view& row) const;
void reset() {
_current_partition_key_does_not_match = false;
_current_static_row_does_not_match = false;
}
};
result_set_builder(const selection& s, gc_clock::time_point now, cql_serialization_format sf);
void add_empty();
void add(bytes_opt value);
void add(const column_definition& def, const query::result_atomic_cell_view& c);
void add_collection(const column_definition& def, bytes_view c);
void new_row();
std::unique_ptr<result_set> build();
api::timestamp_type timestamp_of(size_t idx);
int32_t ttl_of(size_t idx);
// Implements ResultVisitor concept from query.hh
template<typename Filter = nop_filter>
class visitor {
protected:
result_set_builder& _builder;
const schema& _schema;
const selection& _selection;
uint32_t _row_count;
std::vector<bytes> _partition_key;
std::vector<bytes> _clustering_key;
Filter _filter;
public:
visitor(cql3::selection::result_set_builder& builder, const schema& s,
const selection& selection, Filter filter = Filter())
: _builder(builder)
, _schema(s)
, _selection(selection)
, _row_count(0)
, _filter(filter)
{}
visitor(visitor&&) = default;
void add_value(const column_definition& def, query::result_row_view::iterator_type& i) {
if (def.type->is_multi_cell()) {
auto cell = i.next_collection_cell();
if (!cell) {
_builder.add_empty();
return;
}
_builder.add_collection(def, cell->linearize());
} else {
auto cell = i.next_atomic_cell();
if (!cell) {
_builder.add_empty();
return;
}
_builder.add(def, *cell);
}
}
void accept_new_partition(const partition_key& key, uint32_t row_count) {
_partition_key = key.explode(_schema);
_row_count = row_count;
_filter.reset();
}
void accept_new_partition(uint32_t row_count) {
_row_count = row_count;
_filter.reset();
}
void accept_new_row(const clustering_key& key, const query::result_row_view& static_row, const query::result_row_view& row) {
_clustering_key = key.explode(_schema);
accept_new_row(static_row, row);
}
void accept_new_row(const query::result_row_view& static_row, const query::result_row_view& row) {
auto static_row_iterator = static_row.iterator();
auto row_iterator = row.iterator();
if (!_filter(_selection, _partition_key, _clustering_key, static_row, row)) {
return;
}
_builder.new_row();
for (auto&& def : _selection.get_columns()) {
switch (def->kind) {
case column_kind::partition_key:
_builder.add(_partition_key[def->component_index()]);
break;
case column_kind::clustering_key:
if (_clustering_key.size() > def->component_index()) {
_builder.add(_clustering_key[def->component_index()]);
} else {
_builder.add({});
}
break;
case column_kind::regular_column:
add_value(*def, row_iterator);
break;
case column_kind::static_column:
add_value(*def, static_row_iterator);
break;
default:
assert(0);
}
}
}
void accept_partition_end(const query::result_row_view& static_row) {
if (_row_count == 0) {
_builder.new_row();
auto static_row_iterator = static_row.iterator();
for (auto&& def : _selection.get_columns()) {
if (def->is_partition_key()) {
_builder.add(_partition_key[def->component_index()]);
} else if (def->is_static()) {
add_value(*def, static_row_iterator);
} else {
_builder.add_empty();
}
}
}
}
};
private:
bytes_opt get_value(data_type t, query::result_atomic_cell_view c);
};
}
}
<commit_msg>cql3: add non-const get_result_metadata method<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright (C) 2015 ScyllaDB
*
* Modified by ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla 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.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "bytes.hh"
#include "schema.hh"
#include "query-result-reader.hh"
#include "cql3/column_specification.hh"
#include "exceptions/exceptions.hh"
#include "cql3/selection/raw_selector.hh"
#include "cql3/selection/selector_factories.hh"
#include "cql3/restrictions/statement_restrictions.hh"
#include "unimplemented.hh"
namespace cql3 {
class result_set;
class metadata;
namespace selection {
class selectors {
public:
virtual ~selectors() {}
virtual bool is_aggregate() = 0;
/**
* Adds the current row of the specified <code>ResultSetBuilder</code>.
*
* @param rs the <code>ResultSetBuilder</code>
* @throws InvalidRequestException
*/
virtual void add_input_row(cql_serialization_format sf, result_set_builder& rs) = 0;
virtual std::vector<bytes_opt> get_output_row(cql_serialization_format sf) = 0;
virtual void reset() = 0;
};
class selection {
private:
schema_ptr _schema;
std::vector<const column_definition*> _columns;
::shared_ptr<metadata> _metadata;
const bool _collect_timestamps;
const bool _collect_TTLs;
const bool _contains_static_columns;
bool _is_trivial;
protected:
using trivial = bool_class<class trivial_tag>;
selection(schema_ptr schema,
std::vector<const column_definition*> columns,
std::vector<::shared_ptr<column_specification>> metadata_,
bool collect_timestamps,
bool collect_TTLs, trivial is_trivial = trivial::no);
virtual ~selection() {}
public:
// Overriden by SimpleSelection when appropriate.
virtual bool is_wildcard() const {
return false;
}
/**
* Checks if this selection contains static columns.
* @return <code>true</code> if this selection contains static columns, <code>false</code> otherwise;
*/
bool contains_static_columns() const {
return _contains_static_columns;
}
/**
* Checks if this selection contains only static columns.
* @return <code>true</code> if this selection contains only static columns, <code>false</code> otherwise;
*/
bool contains_only_static_columns() const {
if (!contains_static_columns()) {
return false;
}
if (is_wildcard()) {
return false;
}
for (auto&& def : _columns) {
if (!def->is_partition_key() && !def->is_static()) {
return false;
}
}
return true;
}
/**
* Checks if this selection contains a collection.
*
* @return <code>true</code> if this selection contains a collection, <code>false</code> otherwise.
*/
bool contains_a_collection() const {
if (!_schema->has_multi_cell_collections()) {
return false;
}
return std::any_of(_columns.begin(), _columns.end(), [] (auto&& def) {
return def->type->is_collection() && def->type->is_multi_cell();
});
}
/**
* Returns the index of the specified column.
*
* @param def the column definition
* @return the index of the specified column
*/
int32_t index_of(const column_definition& def) const {
auto i = std::find(_columns.begin(), _columns.end(), &def);
if (i == _columns.end()) {
return -1;
}
return std::distance(_columns.begin(), i);
}
bool has_column(const column_definition& def) const {
return std::find(_columns.begin(), _columns.end(), &def) != _columns.end();
}
::shared_ptr<const metadata> get_result_metadata() const {
return _metadata;
}
::shared_ptr<metadata> get_result_metadata() {
return _metadata;
}
static ::shared_ptr<selection> wildcard(schema_ptr schema);
static ::shared_ptr<selection> for_columns(schema_ptr schema, std::vector<const column_definition*> columns);
virtual uint32_t add_column_for_ordering(const column_definition& c);
virtual bool uses_function(const sstring &ks_name, const sstring& function_name) const {
return false;
}
query::partition_slice::option_set get_query_options();
private:
static bool processes_selection(const std::vector<::shared_ptr<raw_selector>>& raw_selectors) {
return std::any_of(raw_selectors.begin(), raw_selectors.end(),
[] (auto&& s) { return s->processes_selection(); });
}
static std::vector<::shared_ptr<column_specification>> collect_metadata(schema_ptr schema,
const std::vector<::shared_ptr<raw_selector>>& raw_selectors, const selector_factories& factories);
public:
static ::shared_ptr<selection> from_selectors(database& db, schema_ptr schema, const std::vector<::shared_ptr<raw_selector>>& raw_selectors);
virtual std::unique_ptr<selectors> new_selectors() const = 0;
/**
* Returns a range of CQL3 columns this selection needs.
*/
auto const& get_columns() const {
return _columns;
}
uint32_t get_column_count() const {
return _columns.size();
}
virtual bool is_aggregate() const = 0;
/**
* Checks that selectors are either all aggregates or that none of them is.
*
* @param selectors the selectors to test.
* @param messageTemplate the error message template
* @param messageArgs the error message arguments
* @throws InvalidRequestException if some of the selectors are aggregate but not all of them
*/
template<typename... Args>
static void validate_selectors(const std::vector<::shared_ptr<selector>>& selectors, const sstring& msg, Args&&... args) {
int32_t aggregates = 0;
for (auto&& s : selectors) {
if (s->is_aggregate()) {
++aggregates;
}
}
if (aggregates != 0 && aggregates != selectors.size()) {
throw exceptions::invalid_request_exception(sprint(msg, std::forward<Args>(args)...));
}
}
/**
* Returns true if the selection is trivial, i.e. there are no function
* selectors (including casts or aggregates).
*/
bool is_trivial() const { return _is_trivial; }
friend class result_set_builder;
};
class result_set_builder {
private:
std::unique_ptr<result_set> _result_set;
std::unique_ptr<selectors> _selectors;
public:
std::experimental::optional<std::vector<bytes_opt>> current;
private:
std::vector<api::timestamp_type> _timestamps;
std::vector<int32_t> _ttls;
const gc_clock::time_point _now;
cql_serialization_format _cql_serialization_format;
public:
class nop_filter {
public:
inline bool operator()(const selection&, const std::vector<bytes>&, const std::vector<bytes>&, const query::result_row_view&, const query::result_row_view&) const {
return true;
}
void reset() {
}
};
class restrictions_filter {
::shared_ptr<restrictions::statement_restrictions> _restrictions;
const query_options& _options;
mutable bool _current_partition_key_does_not_match = false;
mutable bool _current_static_row_does_not_match = false;
public:
restrictions_filter() = default;
explicit restrictions_filter(::shared_ptr<restrictions::statement_restrictions> restrictions, const query_options& options) : _restrictions(restrictions), _options(options) {}
bool operator()(const selection& selection, const std::vector<bytes>& pk, const std::vector<bytes>& ck, const query::result_row_view& static_row, const query::result_row_view& row) const;
void reset() {
_current_partition_key_does_not_match = false;
_current_static_row_does_not_match = false;
}
};
result_set_builder(const selection& s, gc_clock::time_point now, cql_serialization_format sf);
void add_empty();
void add(bytes_opt value);
void add(const column_definition& def, const query::result_atomic_cell_view& c);
void add_collection(const column_definition& def, bytes_view c);
void new_row();
std::unique_ptr<result_set> build();
api::timestamp_type timestamp_of(size_t idx);
int32_t ttl_of(size_t idx);
// Implements ResultVisitor concept from query.hh
template<typename Filter = nop_filter>
class visitor {
protected:
result_set_builder& _builder;
const schema& _schema;
const selection& _selection;
uint32_t _row_count;
std::vector<bytes> _partition_key;
std::vector<bytes> _clustering_key;
Filter _filter;
public:
visitor(cql3::selection::result_set_builder& builder, const schema& s,
const selection& selection, Filter filter = Filter())
: _builder(builder)
, _schema(s)
, _selection(selection)
, _row_count(0)
, _filter(filter)
{}
visitor(visitor&&) = default;
void add_value(const column_definition& def, query::result_row_view::iterator_type& i) {
if (def.type->is_multi_cell()) {
auto cell = i.next_collection_cell();
if (!cell) {
_builder.add_empty();
return;
}
_builder.add_collection(def, cell->linearize());
} else {
auto cell = i.next_atomic_cell();
if (!cell) {
_builder.add_empty();
return;
}
_builder.add(def, *cell);
}
}
void accept_new_partition(const partition_key& key, uint32_t row_count) {
_partition_key = key.explode(_schema);
_row_count = row_count;
_filter.reset();
}
void accept_new_partition(uint32_t row_count) {
_row_count = row_count;
_filter.reset();
}
void accept_new_row(const clustering_key& key, const query::result_row_view& static_row, const query::result_row_view& row) {
_clustering_key = key.explode(_schema);
accept_new_row(static_row, row);
}
void accept_new_row(const query::result_row_view& static_row, const query::result_row_view& row) {
auto static_row_iterator = static_row.iterator();
auto row_iterator = row.iterator();
if (!_filter(_selection, _partition_key, _clustering_key, static_row, row)) {
return;
}
_builder.new_row();
for (auto&& def : _selection.get_columns()) {
switch (def->kind) {
case column_kind::partition_key:
_builder.add(_partition_key[def->component_index()]);
break;
case column_kind::clustering_key:
if (_clustering_key.size() > def->component_index()) {
_builder.add(_clustering_key[def->component_index()]);
} else {
_builder.add({});
}
break;
case column_kind::regular_column:
add_value(*def, row_iterator);
break;
case column_kind::static_column:
add_value(*def, static_row_iterator);
break;
default:
assert(0);
}
}
}
void accept_partition_end(const query::result_row_view& static_row) {
if (_row_count == 0) {
_builder.new_row();
auto static_row_iterator = static_row.iterator();
for (auto&& def : _selection.get_columns()) {
if (def->is_partition_key()) {
_builder.add(_partition_key[def->component_index()]);
} else if (def->is_static()) {
add_value(*def, static_row_iterator);
} else {
_builder.add_empty();
}
}
}
}
};
private:
bytes_opt get_value(data_type t, query::result_atomic_cell_view c);
};
}
}
<|endoftext|> |
<commit_before>#ifndef VSMC_INTERNAL_COMPILER_INTEL_HPP
#define VSMC_INTERNAL_COMPILER_INTEL_HPP
#define VSMC_INTEL_NONEXIST 1000000UL
#define VSMC_GNUC_NONEXIST 1000000UL
#if defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L
#if defined(__GNUC__) && defined (__GNUNC_MINOR__)
// C++11 language features
#if __INTEL_COMPILER >= VSMC_INTEL_NONEXIST
#ifndef VSMC_HAS_CXX11_ACCESS_CONTROL_SFINAE
#define VSMC_HAS_CXX11_ACCESS_CONTROL_SFINAE 1
#endif
#endif
#if __INTEL_COMPILER >= 1210 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 7
#ifndef VSMC_HAS_CXX11_ALIAS_TEMPLATES
#define VSMC_HAS_CXX11_ALIAS_TEMPLATES 1
#endif
#endif
#if __INTEL_COMPILER >= VSMC_INTEL_NONEXIST
#ifndef VSMC_HAS_CXX11_ALIGNAS
#define VSMC_HAS_CXX11_ALIGNAS 1
#endif
#endif
#if __INTEL_COMPILER >= 1210 && __GNUC__ >= VSMC_NUGC_NONEXIST
#ifndef VSMC_HAS_CXX11_ATTRIBUTES
#define VSMC_HAS_CXX11_ATTRIBUTES 1
#endif
#endif
#if __INTEL_COMPILER >= 1100 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 4
#ifndef VSMC_HAS_CXX11_AUTO_TYPE
#define VSMC_HAS_CXX11_AUTO_TYPE 1
#endif
#endif
#if __INTEL_COMPILER >= 1300 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 6
#ifndef VSMC_HAS_CXX11_CONSTEXPR
#define VSMC_HAS_CXX11_CONSTEXPR 1
#endif
#endif
#if __INTEL_COMPILER >= 1100 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 3
#ifndef VSMC_HAS_CXX11_DECLTYPE
#define VSMC_HAS_CXX11_DECLTYPE 1
#endif
#endif
#if __INTEL_COMPILER >= 1210 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 3
#ifndef VSMC_HAS_CXX11_DEFAULT_FUNCTION_TEMPLATE_ARGS
#define VSMC_HAS_CXX11_DEFAULT_FUNCTION_TEMPLATE_ARGS 1
#endif
#endif
#if __INTEL_COMPILER >= 1200 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 4
#ifndef VSMC_HAS_CXX11_DEFAULTED_FUNCTIONS
#define VSMC_HAS_CXX11_DEFAULTED_FUNCTIONS 1
#endif
#endif
#if __INTEL_COMPILER >= VSMC_INTEL_NONEXIST
#ifndef VSMC_HAS_CXX11_DELEGATING_CONSTRUCTORS
#define VSMC_HAS_CXX11_DELEGATING_CONSTRUCTORS 1
#endif
#endif
#if __INTEL_COMPILER >= 1200 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 4
#ifndef VSMC_HAS_CXX11_DELETED_FUNCTIONS
#define VSMC_HAS_CXX11_DELETED_FUNCTIONS 1
#endif
#endif
#if __INTEL_COMPILER >= 1300 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 5
#ifndef VSMC_HAS_CXX11_EXPLICIT_CONVERSIONS
#define VSMC_HAS_CXX11_EXPLICIT_CONVERSIONS 1
#endif
#endif
#if __INTEL_COMPILER >= 1300 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 6
#ifndef VSMC_HAS_CXX11_GENERALIZED_INITIALIZERS
#define VSMC_HAS_CXX11_GENERALIZED_INITIALIZERS 1
#endif
#endif
#if __INTEL_COMPILER >= VSMC_INTEL_NONEXIST
#ifndef VSMC_HAS_CXX11_IMPLICIT_MOVES
#define VSMC_HAS_CXX11_IMPLICIT_MOVES 1
#endif
#endif
#if __INTEL_COMPILER >= VSMC_INTEL_NONEXIST
#ifndef VSMC_HAS_CXX11_INHERITING_CONSTRUCTORS
#define VSMC_HAS_CXX11_INHERITING_CONSTRUCTORS 1
#endif
#endif
#if __INTEL_COMPILER >= VSMC_INTEL_NONEXIST
#ifndef VSMC_HAS_CXX11_INLINE_NAMESPACES
#define VSMC_HAS_CXX11_INLINE_NAMESPACES 1
#endif
#endif
#if __INTEL_COMPILER >= 1200 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 5
#ifndef VSMC_HAS_CXX11_LAMBDAS
#define VSMC_HAS_CXX11_LAMBDAS 1
#endif
#endif
#if __INTEL_COMPILER >= 1200 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 5
#ifndef VSMC_HAS_CXX11_LOCAL_TYPE_TEMPLATE_ARGS
#define VSMC_HAS_CXX11_LOCAL_TYPE_TEMPLATE_ARGS 1
#endif
#endif
#if __INTEL_COMPILER >= 1300 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 6
#ifndef VSMC_HAS_CXX11_NOEXCEPT
#define VSMC_HAS_CXX11_NOEXCEPT 1
#endif
#endif
#if __INTEL_COMPILER >= VSMC_INTEL_NONEXIST
#ifndef VSMC_HAS_CXX11_NONSTATIC_MEMBER_INIT
#define VSMC_HAS_CXX11_NONSTATIC_MEMBER_INIT 1
#endif
#endif
#if __INTEL_COMPILER >= 1210 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 6
#ifndef VSMC_HAS_CXX11_NULLPTR
#define VSMC_HAS_CXX11_NULLPTR 1
#endif
#endif
#if __INTEL_COMPILER >= VSMC_INTEL_NONEXIST
#ifndef VSMC_HAS_CXX11_OVERRIDE_CONTROL
#define VSMC_HAS_CXX11_OVERRIDE_CONTROL 1
#endif
#endif
#if __INTEL_COMPILER >= 1300 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 6
#ifndef VSMC_HAS_CXX11_RANGE_FOR
#define VSMC_HAS_CXX11_RANGE_FOR 1
#endif
#endif
#if __INTEL_COMPILER >= VSMC_INTEL_NONEXIST
#ifndef VSMC_HAS_CXX11_RAW_STRING_LITERALS
#define VSMC_HAS_CXX11_RAW_STRING_LITERALS 1
#endif
#endif
#if __INTEL_COMPILER >= VSMC_INTEL_NONEXIST
#ifndef VSMC_HAS_CXX11_REFERENCE_QUALIFIED_FUNCTIONS
#define VSMC_HAS_CXX11_REFERENCE_QUALIFIED_FUNCTIONS 1
#endif
#endif
#if __INTEL_COMPILER >= 1200 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 3
#ifndef VSMC_HAS_CXX11_RVALUE_REFERENCES
#define VSMC_HAS_CXX11_RVALUE_REFERENCES 1
#endif
#endif
#if __INTEL_COMPILER >= 1100 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 3
#ifndef VSMC_HAS_CXX11_STATIC_ASSERT
#define VSMC_HAS_CXX11_STATIC_ASSERT 1
#endif
#endif
#if __INTEL_COMPILER >= 1200 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 4
#ifndef VSMC_HAS_CXX11_STRONG_ENUMS
#define VSMC_HAS_CXX11_STRONG_ENUMS 1
#endif
#endif
#if __INTEL_COMPILER >= 1200 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 4
#ifndef VSMC_HAS_CXX11_TRAILING_RETURN
#define VSMC_HAS_CXX11_TRAILING_RETURN 1
#endif
#endif
#if __INTEL_COMPILER >= 1100 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 5
#ifndef VSMC_HAS_CXX11_UNICODE_LITERALS
#define VSMC_HAS_CXX11_UNICODE_LITERALS 1
#endif
#endif
#if __INTEL_COMPILER >= VSMC_INTEL_NONEXIST
#ifndef VSMC_HAS_CXX11_UNRESTRICTED_UNIONS
#define VSMC_HAS_CXX11_UNRESTRICTED_UNIONS 1
#endif
#endif
#if __INTEL_COMPILER >= VSMC_INTEL_NONEXIST
#ifndef VSMC_HAS_CXX11_USER_LITERALS
#define VSMC_HAS_CXX11_USER_LITERALS 1
#endif
#endif
#if __INTEL_COMPILER >= 1300 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 7
#ifndef VSMC_HAS_CXX11_VARIADIC_TEMPLATES
#define VSMC_HAS_CXX11_VARIADIC_TEMPLATES 1
#endif
#endif
// C++11 library features
#if __GNUC__ >= 4 && __GNUC_MINOR__ >= 4
#ifndef VSMC_HAS_CXX11LIB_CHRONO
#define VSMC_HAS_CXX11LIB_CHRONO 1
#endif
#endif
#if __GNUC__ >= 4 && __GNUC_MINOR__ >= 4
#ifndef VSMC_HAS_CXX11LIB_FUNCTIONAL
#define VSMC_HAS_CXX11LIB_FUNCTIONAL 1
#endif
#endif
#if __GNUC__ >= 4 && __GNUC_MINOR__ >= 7
#ifndef VSMC_HAS_CXX11LIB_FUTURE
#define VSMC_HAS_CXX11LIB_FUTURE 1
#endif
#endif
#if __GNUC__ >= 4 && __GNUC_MINOR__ >= 5
#ifndef VSMC_HAS_CXX11LIB_RANDOM
#define VSMC_HAS_CXX11LIB_RANDOM 1
#endif
#endif
#endif // defined(__GNUC__) && defined (__GNUNC_MINOR__)
#endif // defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L
#endif // VSMC_INTERNAL_COMPILER_INTEL_HPP
<commit_msg>fix typo<commit_after>#ifndef VSMC_INTERNAL_COMPILER_INTEL_HPP
#define VSMC_INTERNAL_COMPILER_INTEL_HPP
#define VSMC_INTEL_NONEXIST 1000000UL
#define VSMC_GNUC_NONEXIST 1000000UL
#if defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L
#if defined(__GNUC__) && defined(__GNUC_MINOR__)
// C++11 language features
#if __INTEL_COMPILER >= VSMC_INTEL_NONEXIST
#ifndef VSMC_HAS_CXX11_ACCESS_CONTROL_SFINAE
#define VSMC_HAS_CXX11_ACCESS_CONTROL_SFINAE 1
#endif
#endif
#if __INTEL_COMPILER >= 1210 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 7
#ifndef VSMC_HAS_CXX11_ALIAS_TEMPLATES
#define VSMC_HAS_CXX11_ALIAS_TEMPLATES 1
#endif
#endif
#if __INTEL_COMPILER >= VSMC_INTEL_NONEXIST
#ifndef VSMC_HAS_CXX11_ALIGNAS
#define VSMC_HAS_CXX11_ALIGNAS 1
#endif
#endif
#if __INTEL_COMPILER >= 1210 && __GNUC__ >= VSMC_NUGC_NONEXIST
#ifndef VSMC_HAS_CXX11_ATTRIBUTES
#define VSMC_HAS_CXX11_ATTRIBUTES 1
#endif
#endif
#if __INTEL_COMPILER >= 1100 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 4
#ifndef VSMC_HAS_CXX11_AUTO_TYPE
#define VSMC_HAS_CXX11_AUTO_TYPE 1
#endif
#endif
#if __INTEL_COMPILER >= 1300 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 6
#ifndef VSMC_HAS_CXX11_CONSTEXPR
#define VSMC_HAS_CXX11_CONSTEXPR 1
#endif
#endif
#if __INTEL_COMPILER >= 1100 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 3
#ifndef VSMC_HAS_CXX11_DECLTYPE
#define VSMC_HAS_CXX11_DECLTYPE 1
#endif
#endif
#if __INTEL_COMPILER >= 1210 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 3
#ifndef VSMC_HAS_CXX11_DEFAULT_FUNCTION_TEMPLATE_ARGS
#define VSMC_HAS_CXX11_DEFAULT_FUNCTION_TEMPLATE_ARGS 1
#endif
#endif
#if __INTEL_COMPILER >= 1200 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 4
#ifndef VSMC_HAS_CXX11_DEFAULTED_FUNCTIONS
#define VSMC_HAS_CXX11_DEFAULTED_FUNCTIONS 1
#endif
#endif
#if __INTEL_COMPILER >= VSMC_INTEL_NONEXIST
#ifndef VSMC_HAS_CXX11_DELEGATING_CONSTRUCTORS
#define VSMC_HAS_CXX11_DELEGATING_CONSTRUCTORS 1
#endif
#endif
#if __INTEL_COMPILER >= 1200 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 4
#ifndef VSMC_HAS_CXX11_DELETED_FUNCTIONS
#define VSMC_HAS_CXX11_DELETED_FUNCTIONS 1
#endif
#endif
#if __INTEL_COMPILER >= 1300 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 5
#ifndef VSMC_HAS_CXX11_EXPLICIT_CONVERSIONS
#define VSMC_HAS_CXX11_EXPLICIT_CONVERSIONS 1
#endif
#endif
#if __INTEL_COMPILER >= 1300 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 6
#ifndef VSMC_HAS_CXX11_GENERALIZED_INITIALIZERS
#define VSMC_HAS_CXX11_GENERALIZED_INITIALIZERS 1
#endif
#endif
#if __INTEL_COMPILER >= VSMC_INTEL_NONEXIST
#ifndef VSMC_HAS_CXX11_IMPLICIT_MOVES
#define VSMC_HAS_CXX11_IMPLICIT_MOVES 1
#endif
#endif
#if __INTEL_COMPILER >= VSMC_INTEL_NONEXIST
#ifndef VSMC_HAS_CXX11_INHERITING_CONSTRUCTORS
#define VSMC_HAS_CXX11_INHERITING_CONSTRUCTORS 1
#endif
#endif
#if __INTEL_COMPILER >= VSMC_INTEL_NONEXIST
#ifndef VSMC_HAS_CXX11_INLINE_NAMESPACES
#define VSMC_HAS_CXX11_INLINE_NAMESPACES 1
#endif
#endif
#if __INTEL_COMPILER >= 1200 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 5
#ifndef VSMC_HAS_CXX11_LAMBDAS
#define VSMC_HAS_CXX11_LAMBDAS 1
#endif
#endif
#if __INTEL_COMPILER >= 1200 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 5
#ifndef VSMC_HAS_CXX11_LOCAL_TYPE_TEMPLATE_ARGS
#define VSMC_HAS_CXX11_LOCAL_TYPE_TEMPLATE_ARGS 1
#endif
#endif
#if __INTEL_COMPILER >= 1300 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 6
#ifndef VSMC_HAS_CXX11_NOEXCEPT
#define VSMC_HAS_CXX11_NOEXCEPT 1
#endif
#endif
#if __INTEL_COMPILER >= VSMC_INTEL_NONEXIST
#ifndef VSMC_HAS_CXX11_NONSTATIC_MEMBER_INIT
#define VSMC_HAS_CXX11_NONSTATIC_MEMBER_INIT 1
#endif
#endif
#if __INTEL_COMPILER >= 1210 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 6
#ifndef VSMC_HAS_CXX11_NULLPTR
#define VSMC_HAS_CXX11_NULLPTR 1
#endif
#endif
#if __INTEL_COMPILER >= VSMC_INTEL_NONEXIST
#ifndef VSMC_HAS_CXX11_OVERRIDE_CONTROL
#define VSMC_HAS_CXX11_OVERRIDE_CONTROL 1
#endif
#endif
#if __INTEL_COMPILER >= 1300 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 6
#ifndef VSMC_HAS_CXX11_RANGE_FOR
#define VSMC_HAS_CXX11_RANGE_FOR 1
#endif
#endif
#if __INTEL_COMPILER >= VSMC_INTEL_NONEXIST
#ifndef VSMC_HAS_CXX11_RAW_STRING_LITERALS
#define VSMC_HAS_CXX11_RAW_STRING_LITERALS 1
#endif
#endif
#if __INTEL_COMPILER >= VSMC_INTEL_NONEXIST
#ifndef VSMC_HAS_CXX11_REFERENCE_QUALIFIED_FUNCTIONS
#define VSMC_HAS_CXX11_REFERENCE_QUALIFIED_FUNCTIONS 1
#endif
#endif
#if __INTEL_COMPILER >= 1200 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 3
#ifndef VSMC_HAS_CXX11_RVALUE_REFERENCES
#define VSMC_HAS_CXX11_RVALUE_REFERENCES 1
#endif
#endif
#if __INTEL_COMPILER >= 1100 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 3
#ifndef VSMC_HAS_CXX11_STATIC_ASSERT
#define VSMC_HAS_CXX11_STATIC_ASSERT 1
#endif
#endif
#if __INTEL_COMPILER >= 1200 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 4
#ifndef VSMC_HAS_CXX11_STRONG_ENUMS
#define VSMC_HAS_CXX11_STRONG_ENUMS 1
#endif
#endif
#if __INTEL_COMPILER >= 1200 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 4
#ifndef VSMC_HAS_CXX11_TRAILING_RETURN
#define VSMC_HAS_CXX11_TRAILING_RETURN 1
#endif
#endif
#if __INTEL_COMPILER >= 1100 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 5
#ifndef VSMC_HAS_CXX11_UNICODE_LITERALS
#define VSMC_HAS_CXX11_UNICODE_LITERALS 1
#endif
#endif
#if __INTEL_COMPILER >= VSMC_INTEL_NONEXIST
#ifndef VSMC_HAS_CXX11_UNRESTRICTED_UNIONS
#define VSMC_HAS_CXX11_UNRESTRICTED_UNIONS 1
#endif
#endif
#if __INTEL_COMPILER >= VSMC_INTEL_NONEXIST
#ifndef VSMC_HAS_CXX11_USER_LITERALS
#define VSMC_HAS_CXX11_USER_LITERALS 1
#endif
#endif
#if __INTEL_COMPILER >= 1300 && __GNUC__ >= 4 && __GNUC_MINOR__ >= 7
#ifndef VSMC_HAS_CXX11_VARIADIC_TEMPLATES
#define VSMC_HAS_CXX11_VARIADIC_TEMPLATES 1
#endif
#endif
// C++11 library features
#if __GNUC__ >= 4 && __GNUC_MINOR__ >= 4
#ifndef VSMC_HAS_CXX11LIB_CHRONO
#define VSMC_HAS_CXX11LIB_CHRONO 1
#endif
#endif
#if __GNUC__ >= 4 && __GNUC_MINOR__ >= 4
#ifndef VSMC_HAS_CXX11LIB_FUNCTIONAL
#define VSMC_HAS_CXX11LIB_FUNCTIONAL 1
#endif
#endif
#if __GNUC__ >= 4 && __GNUC_MINOR__ >= 7
#ifndef VSMC_HAS_CXX11LIB_FUTURE
#define VSMC_HAS_CXX11LIB_FUTURE 1
#endif
#endif
#if __GNUC__ >= 4 && __GNUC_MINOR__ >= 5
#ifndef VSMC_HAS_CXX11LIB_RANDOM
#define VSMC_HAS_CXX11LIB_RANDOM 1
#endif
#endif
#endif // defined(__GNUC__) && defined(__GNUC_MINOR__)
#endif // defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L
#endif // VSMC_INTERNAL_COMPILER_INTEL_HPP
<|endoftext|> |
<commit_before>/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkCpu.h"
#include "SkOnce.h"
#if !defined(__has_include)
#define __has_include(x) 0
#endif
#if defined(SK_CPU_X86)
#if defined(SK_BUILD_FOR_WIN32)
#include <intrin.h>
static void cpuid (uint32_t abcd[4]) { __cpuid ((int*)abcd, 1); }
static void cpuid7(uint32_t abcd[4]) { __cpuidex((int*)abcd, 7, 0); }
static uint64_t xgetbv(uint32_t xcr) { return _xgetbv(xcr); }
#else
#include <cpuid.h>
#if !defined(__cpuid_count) // Old Mac Clang doesn't have this defined.
#define __cpuid_count(eax, ecx, a, b, c, d) \
__asm__("cpuid" : "=a"(a), "=b"(b), "=c"(c), "=d"(d) : "0"(eax), "2"(ecx))
#endif
static void cpuid (uint32_t abcd[4]) { __get_cpuid(1, abcd+0, abcd+1, abcd+2, abcd+3); }
static void cpuid7(uint32_t abcd[4]) {
__cpuid_count(7, 0, abcd[0], abcd[1], abcd[2], abcd[3]);
}
static uint64_t xgetbv(uint32_t xcr) {
uint32_t eax, edx;
__asm__ __volatile__ ( "xgetbv" : "=a"(eax), "=d"(edx) : "c"(xcr));
return (uint64_t)(edx) << 32 | eax;
}
#endif
static uint32_t read_cpu_features() {
uint32_t features = 0;
uint32_t abcd[4] = {0,0,0,0};
// You might want to refer to http://www.sandpile.org/x86/cpuid.htm
cpuid(abcd);
if (abcd[3] & (1<<25)) { features |= SkCpu:: SSE1; }
if (abcd[3] & (1<<26)) { features |= SkCpu:: SSE2; }
if (abcd[2] & (1<< 0)) { features |= SkCpu:: SSE3; }
if (abcd[2] & (1<< 9)) { features |= SkCpu::SSSE3; }
if (abcd[2] & (1<<19)) { features |= SkCpu::SSE41; }
if (abcd[2] & (1<<20)) { features |= SkCpu::SSE42; }
if ((abcd[2] & (3<<26)) == (3<<26) // XSAVE + OSXSAVE
&& (xgetbv(0) & (3<<1)) == (3<<1)) { // XMM and YMM state enabled.
if (abcd[2] & (1<<28)) { features |= SkCpu:: AVX; }
if (abcd[2] & (1<<29)) { features |= SkCpu::F16C; }
if (abcd[2] & (1<<12)) { features |= SkCpu:: FMA; }
cpuid7(abcd);
if (abcd[1] & (1<<5)) { features |= SkCpu::AVX2; }
if (abcd[1] & (1<<3)) { features |= SkCpu::BMI1; }
if (abcd[1] & (1<<8)) { features |= SkCpu::BMI2; }
if ((xgetbv(0) & (7<<5)) == (7<<5)) { // All ZMM state bits enabled too.
if (abcd[1] & (1<<16)) { features |= SkCpu::AVX512F; }
if (abcd[1] & (1<<17)) { features |= SkCpu::AVX512DQ; }
if (abcd[1] & (1<<21)) { features |= SkCpu::AVX512IFMA; }
if (abcd[1] & (1<<26)) { features |= SkCpu::AVX512PF; }
if (abcd[1] & (1<<27)) { features |= SkCpu::AVX512ER; }
if (abcd[1] & (1<<28)) { features |= SkCpu::AVX512CD; }
if (abcd[1] & (1<<30)) { features |= SkCpu::AVX512BW; }
if (abcd[1] & (1<<31)) { features |= SkCpu::AVX512VL; }
}
}
return features;
}
#elif defined(SK_CPU_ARM64) && __has_include(<sys/auxv.h>)
#include <sys/auxv.h>
static uint32_t read_cpu_features() {
const uint32_t kHWCAP_CRC32 = (1<<7);
uint32_t features = 0;
uint32_t hwcaps = getauxval(AT_HWCAP);
if (hwcaps & kHWCAP_CRC32) { features |= SkCpu::CRC32; }
return features;
}
#elif defined(SK_CPU_ARM32) && __has_include(<sys/auxv.h>)
// sys/auxv.h won't be present on NDK builds before API v21.
#include <sys/auxv.h>
static uint32_t read_cpu_features() {
const uint32_t kHWCAP_NEON = (1<<12);
const uint32_t kHWCAP_VFPv4 = (1<<16);
uint32_t features = 0;
uint32_t hwcaps = getauxval(AT_HWCAP);
if (hwcaps & kHWCAP_NEON ) {
features |= SkCpu::NEON;
if (hwcaps & kHWCAP_VFPv4) { features |= SkCpu::NEON_FMA|SkCpu::VFP_FP16; }
}
return features;
}
#elif defined(SK_CPU_ARM32) && __has_include(<cpu-features.h>)
#include <cpu-features.h>
static uint32_t read_cpu_features() {
uint32_t features = 0;
uint64_t cpu_features = android_getCpuFeatures();
if (cpu_features & ANDROID_CPU_ARM_FEATURE_NEON) { features |= SkCpu::NEON; }
if (cpu_features & ANDROID_CPU_ARM_FEATURE_NEON_FMA) { features |= SkCpu::NEON_FMA; }
if (cpu_features & ANDROID_CPU_ARM_FEATURE_VFP_FP16) { features |= SkCpu::VFP_FP16; }
return features;
}
#else
static uint32_t read_cpu_features() {
return 0;
}
#endif
uint32_t SkCpu::gCachedFeatures = 0;
void SkCpu::CacheRuntimeFeatures() {
static SkOnce once;
once([] { gCachedFeatures = read_cpu_features(); });
}
<commit_msg>Make Skia compatible with Android NDK r16<commit_after>/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkCpu.h"
#include "SkOnce.h"
#if !defined(__has_include)
#define __has_include(x) 0
#endif
#if defined(SK_CPU_X86)
#if defined(SK_BUILD_FOR_WIN32)
#include <intrin.h>
static void cpuid (uint32_t abcd[4]) { __cpuid ((int*)abcd, 1); }
static void cpuid7(uint32_t abcd[4]) { __cpuidex((int*)abcd, 7, 0); }
static uint64_t xgetbv(uint32_t xcr) { return _xgetbv(xcr); }
#else
#include <cpuid.h>
#if !defined(__cpuid_count) // Old Mac Clang doesn't have this defined.
#define __cpuid_count(eax, ecx, a, b, c, d) \
__asm__("cpuid" : "=a"(a), "=b"(b), "=c"(c), "=d"(d) : "0"(eax), "2"(ecx))
#endif
static void cpuid (uint32_t abcd[4]) { __get_cpuid(1, abcd+0, abcd+1, abcd+2, abcd+3); }
static void cpuid7(uint32_t abcd[4]) {
__cpuid_count(7, 0, abcd[0], abcd[1], abcd[2], abcd[3]);
}
static uint64_t xgetbv(uint32_t xcr) {
uint32_t eax, edx;
__asm__ __volatile__ ( "xgetbv" : "=a"(eax), "=d"(edx) : "c"(xcr));
return (uint64_t)(edx) << 32 | eax;
}
#endif
static uint32_t read_cpu_features() {
uint32_t features = 0;
uint32_t abcd[4] = {0,0,0,0};
// You might want to refer to http://www.sandpile.org/x86/cpuid.htm
cpuid(abcd);
if (abcd[3] & (1<<25)) { features |= SkCpu:: SSE1; }
if (abcd[3] & (1<<26)) { features |= SkCpu:: SSE2; }
if (abcd[2] & (1<< 0)) { features |= SkCpu:: SSE3; }
if (abcd[2] & (1<< 9)) { features |= SkCpu::SSSE3; }
if (abcd[2] & (1<<19)) { features |= SkCpu::SSE41; }
if (abcd[2] & (1<<20)) { features |= SkCpu::SSE42; }
if ((abcd[2] & (3<<26)) == (3<<26) // XSAVE + OSXSAVE
&& (xgetbv(0) & (3<<1)) == (3<<1)) { // XMM and YMM state enabled.
if (abcd[2] & (1<<28)) { features |= SkCpu:: AVX; }
if (abcd[2] & (1<<29)) { features |= SkCpu::F16C; }
if (abcd[2] & (1<<12)) { features |= SkCpu:: FMA; }
cpuid7(abcd);
if (abcd[1] & (1<<5)) { features |= SkCpu::AVX2; }
if (abcd[1] & (1<<3)) { features |= SkCpu::BMI1; }
if (abcd[1] & (1<<8)) { features |= SkCpu::BMI2; }
if ((xgetbv(0) & (7<<5)) == (7<<5)) { // All ZMM state bits enabled too.
if (abcd[1] & (1<<16)) { features |= SkCpu::AVX512F; }
if (abcd[1] & (1<<17)) { features |= SkCpu::AVX512DQ; }
if (abcd[1] & (1<<21)) { features |= SkCpu::AVX512IFMA; }
if (abcd[1] & (1<<26)) { features |= SkCpu::AVX512PF; }
if (abcd[1] & (1<<27)) { features |= SkCpu::AVX512ER; }
if (abcd[1] & (1<<28)) { features |= SkCpu::AVX512CD; }
if (abcd[1] & (1<<30)) { features |= SkCpu::AVX512BW; }
if (abcd[1] & (1<<31)) { features |= SkCpu::AVX512VL; }
}
}
return features;
}
#elif defined(SK_CPU_ARM64) && __has_include(<sys/auxv.h>)
#include <sys/auxv.h>
static uint32_t read_cpu_features() {
const uint32_t kHWCAP_CRC32 = (1<<7);
uint32_t features = 0;
uint32_t hwcaps = getauxval(AT_HWCAP);
if (hwcaps & kHWCAP_CRC32) { features |= SkCpu::CRC32; }
return features;
}
#elif defined(SK_CPU_ARM32) && __has_include(<sys/auxv.h>) && \
(!defined(__ANDROID_API__) || __ANDROID_API__ >= 18)
// sys/auxv.h will always be present in the Android NDK due to unified
//headers, but getauxval is only defined for API >= 18.
#include <sys/auxv.h>
static uint32_t read_cpu_features() {
const uint32_t kHWCAP_NEON = (1<<12);
const uint32_t kHWCAP_VFPv4 = (1<<16);
uint32_t features = 0;
uint32_t hwcaps = getauxval(AT_HWCAP);
if (hwcaps & kHWCAP_NEON ) {
features |= SkCpu::NEON;
if (hwcaps & kHWCAP_VFPv4) { features |= SkCpu::NEON_FMA|SkCpu::VFP_FP16; }
}
return features;
}
#elif defined(SK_CPU_ARM32) && __has_include(<cpu-features.h>)
#include <cpu-features.h>
static uint32_t read_cpu_features() {
uint32_t features = 0;
uint64_t cpu_features = android_getCpuFeatures();
if (cpu_features & ANDROID_CPU_ARM_FEATURE_NEON) { features |= SkCpu::NEON; }
if (cpu_features & ANDROID_CPU_ARM_FEATURE_NEON_FMA) { features |= SkCpu::NEON_FMA; }
if (cpu_features & ANDROID_CPU_ARM_FEATURE_VFP_FP16) { features |= SkCpu::VFP_FP16; }
return features;
}
#else
static uint32_t read_cpu_features() {
return 0;
}
#endif
uint32_t SkCpu::gCachedFeatures = 0;
void SkCpu::CacheRuntimeFeatures() {
static SkOnce once;
once([] { gCachedFeatures = read_cpu_features(); });
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: prevloc.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: pjunck $ $Date: 2004-10-28 09:57:00 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SC_PREVLOC_HXX
#define SC_PREVLOC_HXX
#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif
#ifndef _LIST_HXX
#include <tools/list.hxx>
#endif
#ifndef _SV_MAPMOD_HXX
#include <vcl/mapmod.hxx>
#endif
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#define SC_PREVIEW_MAXRANGES 4
#define SC_PREVIEW_RANGE_EDGE 0
#define SC_PREVIEW_RANGE_REPCOL 1
#define SC_PREVIEW_RANGE_REPROW 2
#define SC_PREVIEW_RANGE_TAB 3
class OutputDevice;
class String;
class Point;
class Rectangle;
class ScAddress;
class ScRange;
class ScDocument;
struct ScPreviewColRowInfo
{
BOOL bIsHeader;
SCCOLROW nDocIndex;
long nPixelStart;
long nPixelEnd;
void Set( BOOL bHeader, SCCOLROW nIndex, long nStart, long nEnd )
{
bIsHeader = bHeader;
nDocIndex = nIndex;
nPixelStart = nStart;
nPixelEnd = nEnd;
}
};
class ScPreviewTableInfo
{
SCTAB nTab;
SCCOL nCols;
SCROW nRows;
ScPreviewColRowInfo* pColInfo;
ScPreviewColRowInfo* pRowInfo;
public:
ScPreviewTableInfo();
~ScPreviewTableInfo();
SCTAB GetTab() const { return nTab; }
SCCOL GetCols() const { return nCols; }
SCROW GetRows() const { return nRows; }
const ScPreviewColRowInfo* GetColInfo() const { return pColInfo; }
const ScPreviewColRowInfo* GetRowInfo() const { return pRowInfo; }
void SetTab( SCTAB nNewTab );
void SetColInfo( SCCOL nCount, ScPreviewColRowInfo* pNewInfo );
void SetRowInfo( SCROW nCount, ScPreviewColRowInfo* pNewInfo );
void LimitToArea( const Rectangle& rPixelArea );
};
class ScPreviewLocationData
{
OutputDevice* pWindow;
ScDocument* pDoc;
MapMode aCellMapMode;
MapMode aDrawMapMode[SC_PREVIEW_MAXRANGES];
Rectangle aDrawRectangle[SC_PREVIEW_MAXRANGES];
sal_uInt8 aDrawRangeId[SC_PREVIEW_MAXRANGES];
USHORT nDrawRanges;
SCTAB nPrintTab;
List aEntries;
ScAddress GetCellFromRange( const Size& rOffsetPixel, const ScRange& rRange ) const;
Rectangle GetOffsetPixel( const ScAddress& rCellPos, const ScRange& rRange ) const;
public:
ScPreviewLocationData( ScDocument* pDocument, OutputDevice* pWin );
~ScPreviewLocationData();
void SetCellMapMode( const MapMode& rMapMode );
void SetPrintTab( SCTAB nNew );
void Clear();
void AddCellRange( const Rectangle& rRect, const ScRange& rRange, BOOL bRepCol, BOOL bRepRow,
const MapMode& rDrawMap );
void AddColHeaders( const Rectangle& rRect, SCCOL nStartCol, SCCOL nEndCol, BOOL bRepCol );
void AddRowHeaders( const Rectangle& rRect, SCROW nStartRow, SCROW nEndRow, BOOL bRepRow );
void AddHeaderFooter( const Rectangle& rRect, BOOL bHeader, BOOL bLeft );
void AddNoteMark( const Rectangle& rRect, const ScAddress& rPos );
void AddNoteText( const Rectangle& rRect, const ScAddress& rPos );
SCTAB GetPrintTab() const { return nPrintTab; }
// Get info on visible columns/rows in the visible area
void GetTableInfo( const Rectangle& rVisiblePixel, ScPreviewTableInfo& rInfo ) const;
USHORT GetDrawRanges() const { return nDrawRanges; }
void GetDrawRange( USHORT nPos, Rectangle& rPixelRect, MapMode& rMapMode, sal_uInt8& rRangeId ) const;
BOOL GetHeaderPosition( Rectangle& rHeaderRect ) const;
BOOL GetFooterPosition( Rectangle& rFooterRect ) const;
BOOL IsHeaderLeft() const;
BOOL IsFooterLeft() const;
long GetNoteCountInRange( const Rectangle& rVisiblePixel, BOOL bNoteMarks ) const;
BOOL GetNoteInRange( const Rectangle& rVisiblePixel, long nIndex, BOOL bNoteMarks,
ScAddress& rCellPos, Rectangle& rNoteRect ) const;
Rectangle GetNoteInRangeOutputRect(const Rectangle& rVisiblePixel, BOOL bNoteMarks,
const ScAddress& aCellPos) const;
// Check if any cells (including column/row headers) are in the visible area
BOOL HasCellsInRange( const Rectangle& rVisiblePixel ) const;
BOOL GetCell( const Point& rPos, ScAddress& rCellPos, Rectangle& rCellRect ) const;
BOOL GetCellPosition( const ScAddress& rCellPos, Rectangle& rCellRect ) const;
// returns the rectangle where the EditEngine draws the text of a Header Cell
// if bColHeader is true it returns the rectangle of the header of the column in rCellPos
// otherwise of the header of the row in rCellPos
Rectangle GetHeaderCellOutputRect(const Rectangle& rVisRect, const ScAddress& rCellPos, sal_Bool bColHeader) const;
Rectangle GetCellOutputRect(const ScAddress& rCellPos) const;
// Query the range and rectangle of the main (non-repeat) cell range.
// Returns FALSE if not contained.
BOOL GetMainCellRange( ScRange& rRange, Rectangle& rPixRect ) const;
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.10.274); FILE MERGED 2005/09/05 15:05:42 rt 1.10.274.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: prevloc.hxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: rt $ $Date: 2005-09-08 21:45:04 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SC_PREVLOC_HXX
#define SC_PREVLOC_HXX
#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif
#ifndef _LIST_HXX
#include <tools/list.hxx>
#endif
#ifndef _SV_MAPMOD_HXX
#include <vcl/mapmod.hxx>
#endif
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#define SC_PREVIEW_MAXRANGES 4
#define SC_PREVIEW_RANGE_EDGE 0
#define SC_PREVIEW_RANGE_REPCOL 1
#define SC_PREVIEW_RANGE_REPROW 2
#define SC_PREVIEW_RANGE_TAB 3
class OutputDevice;
class String;
class Point;
class Rectangle;
class ScAddress;
class ScRange;
class ScDocument;
struct ScPreviewColRowInfo
{
BOOL bIsHeader;
SCCOLROW nDocIndex;
long nPixelStart;
long nPixelEnd;
void Set( BOOL bHeader, SCCOLROW nIndex, long nStart, long nEnd )
{
bIsHeader = bHeader;
nDocIndex = nIndex;
nPixelStart = nStart;
nPixelEnd = nEnd;
}
};
class ScPreviewTableInfo
{
SCTAB nTab;
SCCOL nCols;
SCROW nRows;
ScPreviewColRowInfo* pColInfo;
ScPreviewColRowInfo* pRowInfo;
public:
ScPreviewTableInfo();
~ScPreviewTableInfo();
SCTAB GetTab() const { return nTab; }
SCCOL GetCols() const { return nCols; }
SCROW GetRows() const { return nRows; }
const ScPreviewColRowInfo* GetColInfo() const { return pColInfo; }
const ScPreviewColRowInfo* GetRowInfo() const { return pRowInfo; }
void SetTab( SCTAB nNewTab );
void SetColInfo( SCCOL nCount, ScPreviewColRowInfo* pNewInfo );
void SetRowInfo( SCROW nCount, ScPreviewColRowInfo* pNewInfo );
void LimitToArea( const Rectangle& rPixelArea );
};
class ScPreviewLocationData
{
OutputDevice* pWindow;
ScDocument* pDoc;
MapMode aCellMapMode;
MapMode aDrawMapMode[SC_PREVIEW_MAXRANGES];
Rectangle aDrawRectangle[SC_PREVIEW_MAXRANGES];
sal_uInt8 aDrawRangeId[SC_PREVIEW_MAXRANGES];
USHORT nDrawRanges;
SCTAB nPrintTab;
List aEntries;
ScAddress GetCellFromRange( const Size& rOffsetPixel, const ScRange& rRange ) const;
Rectangle GetOffsetPixel( const ScAddress& rCellPos, const ScRange& rRange ) const;
public:
ScPreviewLocationData( ScDocument* pDocument, OutputDevice* pWin );
~ScPreviewLocationData();
void SetCellMapMode( const MapMode& rMapMode );
void SetPrintTab( SCTAB nNew );
void Clear();
void AddCellRange( const Rectangle& rRect, const ScRange& rRange, BOOL bRepCol, BOOL bRepRow,
const MapMode& rDrawMap );
void AddColHeaders( const Rectangle& rRect, SCCOL nStartCol, SCCOL nEndCol, BOOL bRepCol );
void AddRowHeaders( const Rectangle& rRect, SCROW nStartRow, SCROW nEndRow, BOOL bRepRow );
void AddHeaderFooter( const Rectangle& rRect, BOOL bHeader, BOOL bLeft );
void AddNoteMark( const Rectangle& rRect, const ScAddress& rPos );
void AddNoteText( const Rectangle& rRect, const ScAddress& rPos );
SCTAB GetPrintTab() const { return nPrintTab; }
// Get info on visible columns/rows in the visible area
void GetTableInfo( const Rectangle& rVisiblePixel, ScPreviewTableInfo& rInfo ) const;
USHORT GetDrawRanges() const { return nDrawRanges; }
void GetDrawRange( USHORT nPos, Rectangle& rPixelRect, MapMode& rMapMode, sal_uInt8& rRangeId ) const;
BOOL GetHeaderPosition( Rectangle& rHeaderRect ) const;
BOOL GetFooterPosition( Rectangle& rFooterRect ) const;
BOOL IsHeaderLeft() const;
BOOL IsFooterLeft() const;
long GetNoteCountInRange( const Rectangle& rVisiblePixel, BOOL bNoteMarks ) const;
BOOL GetNoteInRange( const Rectangle& rVisiblePixel, long nIndex, BOOL bNoteMarks,
ScAddress& rCellPos, Rectangle& rNoteRect ) const;
Rectangle GetNoteInRangeOutputRect(const Rectangle& rVisiblePixel, BOOL bNoteMarks,
const ScAddress& aCellPos) const;
// Check if any cells (including column/row headers) are in the visible area
BOOL HasCellsInRange( const Rectangle& rVisiblePixel ) const;
BOOL GetCell( const Point& rPos, ScAddress& rCellPos, Rectangle& rCellRect ) const;
BOOL GetCellPosition( const ScAddress& rCellPos, Rectangle& rCellRect ) const;
// returns the rectangle where the EditEngine draws the text of a Header Cell
// if bColHeader is true it returns the rectangle of the header of the column in rCellPos
// otherwise of the header of the row in rCellPos
Rectangle GetHeaderCellOutputRect(const Rectangle& rVisRect, const ScAddress& rCellPos, sal_Bool bColHeader) const;
Rectangle GetCellOutputRect(const ScAddress& rCellPos) const;
// Query the range and rectangle of the main (non-repeat) cell range.
// Returns FALSE if not contained.
BOOL GetMainCellRange( ScRange& rRange, Rectangle& rPixRect ) const;
};
#endif
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.