text
stringlengths 54
60.6k
|
|---|
<commit_before>//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2014 Michael Fink
//
/// \file ImagePropertyView.cpp View for image properties
//
// includes
#include "stdafx.h"
#include "resource.h"
#include "ImagePropertyView.hpp"
#include "IPhotoModeViewHost.hpp"
#include "ImageProperty.hpp"
#include "ViewFinderView.hpp"
bool ImagePropertyView::Init()
{
m_spRemoteReleaseControl = m_host.StartRemoteReleaseControl(true);
if (m_spRemoteReleaseControl == nullptr)
{
AtlMessageBox(m_hWnd, _T("Couldn't start remote release control."), IDR_MAINFRAME, MB_OK);
DestroyWindow();
return false;
}
m_iPropertyEventId = m_spRemoteReleaseControl->AddPropertyEventHandler(
std::bind(&ImagePropertyView::OnPropertyChanged, this, std::placeholders::_1, std::placeholders::_2));
InsertColumn(columnName, _T("Name"), LVCFMT_LEFT, 300);
InsertColumn(columnValue, _T("Value"), LVCFMT_LEFT, 300);
InsertColumn(columnType, _T("Type"), LVCFMT_LEFT, 100);
InsertColumn(columnReadOnly, _T("Read-only"), LVCFMT_LEFT, 80);
InsertColumn(columnId, _T("Id"), LVCFMT_LEFT, 80);
InsertColumn(columnRaw, _T("Raw"), LVCFMT_LEFT, 80);
DWORD dwExStyle = LVS_EX_GRIDLINES | LVS_EX_FULLROWSELECT;
SetExtendedListViewStyle(dwExStyle, dwExStyle);
RefreshList();
return true;
}
void ImagePropertyView::DestroyView()
{
if (m_iPropertyEventId != -1 && m_spRemoteReleaseControl != nullptr)
m_spRemoteReleaseControl->RemovePropertyEventHandler(m_iPropertyEventId);
ATLVERIFY(TRUE == DestroyWindow());
}
void ImagePropertyView::OnPropertyChanged(RemoteReleaseControl::T_enPropertyEvent /*enPropertyEvent*/, unsigned int uiPropertyId)
{
if (uiPropertyId == 0)
PostMessage(WM_RELEASECONTROL_ALL_PROPERTIES_CHANGED);
else
PostMessage(WM_RELEASECONTROL_PROPERTY_CHANGED, uiPropertyId);
}
void ImagePropertyView::UpdateProperty(unsigned int uiImagePropertyId)
{
ATLASSERT(m_spRemoteReleaseControl != nullptr);
RemoteReleaseControl& rrc = *m_spRemoteReleaseControl;
SetRedraw(FALSE);
// find property by item data
for (int iIndex=0, iMax = GetItemCount(); iIndex<iMax; iIndex++)
{
unsigned int uiPropertyId = GetItemData(iIndex);
if (uiPropertyId != uiImagePropertyId)
continue;
ImageProperty ip = rrc.GetImageProperty(uiPropertyId);
SetItemText(iIndex, columnValue, ip.AsString());
SetItemText(iIndex, columnReadOnly, ip.IsReadOnly() ? _T("yes") : _T("no"));
SetItemText(iIndex, columnRaw, ip.Value().ToString());
}
SetRedraw(TRUE);
}
void ImagePropertyView::RefreshList()
{
ATLASSERT(m_spRemoteReleaseControl != nullptr);
RemoteReleaseControl& rrc = *m_spRemoteReleaseControl;
SetRedraw(FALSE);
DeleteAllItems();
// disable viewfinder while refreshing list
ViewFinderView* pViewfinder = m_host.GetViewFinderView();
if (pViewfinder != NULL)
pViewfinder->EnableUpdate(false);
std::vector<unsigned int> vecImagePropertyIds;
vecImagePropertyIds = rrc.EnumImageProperties();
for (size_t i=0, iMax = vecImagePropertyIds.size(); i<iMax; i++)
{
unsigned int uiPropertyId = vecImagePropertyIds[i];
ImageProperty ip = rrc.GetImageProperty(uiPropertyId);
int iIndex = InsertItem(GetItemCount(), ip.Name());
SetItemData(iIndex, uiPropertyId);
SetItemText(iIndex, columnValue, ip.AsString());
SetItemText(iIndex, columnType, Variant::TypeAsString(ip.Value().Type()));
SetItemText(iIndex, columnReadOnly, ip.IsReadOnly() ? _T("yes") : _T("no"));
CString cszId;
cszId.Format(_T("0x%04x"), uiPropertyId);
SetItemText(iIndex, columnId, cszId);
SetItemText(iIndex, columnRaw, ip.Value().ToString());
}
if (pViewfinder != NULL)
pViewfinder->EnableUpdate(true);
SetRedraw(TRUE);
}
<commit_msg>added try-catch handler for image property view<commit_after>//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2014 Michael Fink
//
/// \file ImagePropertyView.cpp View for image properties
//
// includes
#include "stdafx.h"
#include "resource.h"
#include "ImagePropertyView.hpp"
#include "IPhotoModeViewHost.hpp"
#include "ImageProperty.hpp"
#include "ViewFinderView.hpp"
#include "CameraException.hpp"
bool ImagePropertyView::Init()
{
m_spRemoteReleaseControl = m_host.StartRemoteReleaseControl(true);
if (m_spRemoteReleaseControl == nullptr)
{
AtlMessageBox(m_hWnd, _T("Couldn't start remote release control."), IDR_MAINFRAME, MB_OK);
DestroyWindow();
return false;
}
m_iPropertyEventId = m_spRemoteReleaseControl->AddPropertyEventHandler(
std::bind(&ImagePropertyView::OnPropertyChanged, this, std::placeholders::_1, std::placeholders::_2));
InsertColumn(columnName, _T("Name"), LVCFMT_LEFT, 300);
InsertColumn(columnValue, _T("Value"), LVCFMT_LEFT, 300);
InsertColumn(columnType, _T("Type"), LVCFMT_LEFT, 100);
InsertColumn(columnReadOnly, _T("Read-only"), LVCFMT_LEFT, 80);
InsertColumn(columnId, _T("Id"), LVCFMT_LEFT, 80);
InsertColumn(columnRaw, _T("Raw"), LVCFMT_LEFT, 80);
DWORD dwExStyle = LVS_EX_GRIDLINES | LVS_EX_FULLROWSELECT;
SetExtendedListViewStyle(dwExStyle, dwExStyle);
RefreshList();
return true;
}
void ImagePropertyView::DestroyView()
{
if (m_iPropertyEventId != -1 && m_spRemoteReleaseControl != nullptr)
m_spRemoteReleaseControl->RemovePropertyEventHandler(m_iPropertyEventId);
ATLVERIFY(TRUE == DestroyWindow());
}
void ImagePropertyView::OnPropertyChanged(RemoteReleaseControl::T_enPropertyEvent /*enPropertyEvent*/, unsigned int uiPropertyId)
{
if (uiPropertyId == 0)
PostMessage(WM_RELEASECONTROL_ALL_PROPERTIES_CHANGED);
else
PostMessage(WM_RELEASECONTROL_PROPERTY_CHANGED, uiPropertyId);
}
void ImagePropertyView::UpdateProperty(unsigned int uiImagePropertyId)
{
ATLASSERT(m_spRemoteReleaseControl != nullptr);
RemoteReleaseControl& rrc = *m_spRemoteReleaseControl;
SetRedraw(FALSE);
// find property by item data
for (int iIndex=0, iMax = GetItemCount(); iIndex<iMax; iIndex++)
{
unsigned int uiPropertyId = GetItemData(iIndex);
if (uiPropertyId != uiImagePropertyId)
continue;
try
{
ImageProperty ip = rrc.GetImageProperty(uiPropertyId);
SetItemText(iIndex, columnValue, ip.AsString());
SetItemText(iIndex, columnReadOnly, ip.IsReadOnly() ? _T("yes") : _T("no"));
SetItemText(iIndex, columnRaw, ip.Value().ToString());
}
catch (const CameraException& ex)
{
SetItemText(iIndex, columnValue, ex.Message());
}
}
SetRedraw(TRUE);
}
void ImagePropertyView::RefreshList()
{
ATLASSERT(m_spRemoteReleaseControl != nullptr);
RemoteReleaseControl& rrc = *m_spRemoteReleaseControl;
SetRedraw(FALSE);
DeleteAllItems();
// disable viewfinder while refreshing list
ViewFinderView* pViewfinder = m_host.GetViewFinderView();
if (pViewfinder != NULL)
pViewfinder->EnableUpdate(false);
std::vector<unsigned int> vecImagePropertyIds;
vecImagePropertyIds = rrc.EnumImageProperties();
for (size_t i=0, iMax = vecImagePropertyIds.size(); i<iMax; i++)
{
unsigned int uiPropertyId = vecImagePropertyIds[i];
try
{
ImageProperty ip = rrc.GetImageProperty(uiPropertyId);
int iIndex = InsertItem(GetItemCount(), ip.Name());
SetItemData(iIndex, uiPropertyId);
SetItemText(iIndex, columnValue, ip.AsString());
SetItemText(iIndex, columnType, Variant::TypeAsString(ip.Value().Type()));
SetItemText(iIndex, columnReadOnly, ip.IsReadOnly() ? _T("yes") : _T("no"));
CString cszId;
cszId.Format(_T("0x%08x"), uiPropertyId);
SetItemText(iIndex, columnId, cszId);
SetItemText(iIndex, columnRaw, ip.Value().ToString());
}
catch (const CameraException& ex)
{
int iIndex = InsertItem(GetItemCount(), _T("???"));
SetItemText(iIndex, columnValue, ex.Message());
}
}
if (pViewfinder != NULL)
pViewfinder->EnableUpdate(true);
SetRedraw(TRUE);
}
<|endoftext|>
|
<commit_before>/****************************************************************************
*
* (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
#include "InitialConnectStateMachine.h"
#include "Vehicle.h"
#include "QGCCorePlugin.h"
#include "QGCOptions.h"
#include "FirmwarePlugin.h"
#include "ParameterManager.h"
#include "ComponentInformationManager.h"
#include "MissionManager.h"
QGC_LOGGING_CATEGORY(InitialConnectStateMachineLog, "InitialConnectStateMachineLog")
const StateMachine::StateFn InitialConnectStateMachine::_rgStates[] = {
InitialConnectStateMachine::_stateRequestCapabilities,
InitialConnectStateMachine::_stateRequestProtocolVersion,
InitialConnectStateMachine::_stateRequestCompInfo,
InitialConnectStateMachine::_stateRequestParameters,
InitialConnectStateMachine::_stateRequestMission,
InitialConnectStateMachine::_stateRequestGeoFence,
InitialConnectStateMachine::_stateRequestRallyPoints,
InitialConnectStateMachine::_stateSignalInitialConnectComplete
};
const int InitialConnectStateMachine::_cStates = sizeof(InitialConnectStateMachine::_rgStates) / sizeof(InitialConnectStateMachine::_rgStates[0]);
InitialConnectStateMachine::InitialConnectStateMachine(Vehicle* vehicle)
: _vehicle(vehicle)
{
}
int InitialConnectStateMachine::stateCount(void) const
{
return _cStates;
}
const InitialConnectStateMachine::StateFn* InitialConnectStateMachine::rgStates(void) const
{
return &_rgStates[0];
}
void InitialConnectStateMachine::statesCompleted(void) const
{
}
void InitialConnectStateMachine::_stateRequestCapabilities(StateMachine* stateMachine)
{
InitialConnectStateMachine* connectMachine = static_cast<InitialConnectStateMachine*>(stateMachine);
Vehicle* vehicle = connectMachine->_vehicle;
WeakLinkInterfacePtr weakLink = vehicle->vehicleLinkManager()->primaryLink();
if (weakLink.expired()) {
qCDebug(InitialConnectStateMachineLog) << "_stateRequestCapabilities Skipping capability request due to no primary link";
connectMachine->advance();
} else {
SharedLinkInterfacePtr sharedLink = weakLink.lock();
if (sharedLink->linkConfiguration()->isHighLatency() || sharedLink->isPX4Flow() || sharedLink->isLogReplay()) {
qCDebug(InitialConnectStateMachineLog) << "Skipping capability request due to link type";
connectMachine->advance();
} else {
qCDebug(InitialConnectStateMachineLog) << "Requesting capabilities";
vehicle->_waitForMavlinkMessage(_waitForAutopilotVersionResultHandler, connectMachine, MAVLINK_MSG_ID_AUTOPILOT_VERSION, 1000);
vehicle->sendMavCommandWithHandler(_capabilitiesCmdResultHandler,
connectMachine,
MAV_COMP_ID_AUTOPILOT1,
MAV_CMD_REQUEST_AUTOPILOT_CAPABILITIES,
1); // Request firmware version
}
}
}
void InitialConnectStateMachine::_capabilitiesCmdResultHandler(void* resultHandlerData, int /*compId*/, MAV_RESULT result, Vehicle::MavCmdResultFailureCode_t failureCode)
{
InitialConnectStateMachine* connectMachine = static_cast<InitialConnectStateMachine*>(resultHandlerData);
Vehicle* vehicle = connectMachine->_vehicle;
if (result != MAV_RESULT_ACCEPTED) {
switch (failureCode) {
case Vehicle::MavCmdResultCommandResultOnly:
qCDebug(InitialConnectStateMachineLog) << QStringLiteral("MAV_CMD_REQUEST_AUTOPILOT_CAPABILITIES error(%1)").arg(result);
break;
case Vehicle::MavCmdResultFailureNoResponseToCommand:
qCDebug(InitialConnectStateMachineLog) << "MAV_CMD_REQUEST_AUTOPILOT_CAPABILITIES no response from vehicle";
break;
case Vehicle::MavCmdResultFailureDuplicateCommand:
qCDebug(InitialConnectStateMachineLog) << "Internal Error: MAV_CMD_REQUEST_AUTOPILOT_CAPABILITIES could not be sent due to duplicate command";
break;
}
qCDebug(InitialConnectStateMachineLog) << "Setting no capabilities";
vehicle->_setCapabilities(0);
vehicle->_waitForMavlinkMessageClear();
connectMachine->advance();
}
}
void InitialConnectStateMachine::_waitForAutopilotVersionResultHandler(void* resultHandlerData, bool noResponsefromVehicle, const mavlink_message_t& message)
{
InitialConnectStateMachine* connectMachine = static_cast<InitialConnectStateMachine*>(resultHandlerData);
Vehicle* vehicle = connectMachine->_vehicle;
if (noResponsefromVehicle) {
qCDebug(InitialConnectStateMachineLog) << "AUTOPILOT_VERSION timeout";
qCDebug(InitialConnectStateMachineLog) << "Setting no capabilities";
vehicle->_setCapabilities(0);
} else {
qCDebug(InitialConnectStateMachineLog) << "AUTOPILOT_VERSION received";
mavlink_autopilot_version_t autopilotVersion;
mavlink_msg_autopilot_version_decode(&message, &autopilotVersion);
vehicle->_uid = (quint64)autopilotVersion.uid;
emit vehicle->vehicleUIDChanged();
if (autopilotVersion.flight_sw_version != 0) {
int majorVersion, minorVersion, patchVersion;
FIRMWARE_VERSION_TYPE versionType;
majorVersion = (autopilotVersion.flight_sw_version >> (8*3)) & 0xFF;
minorVersion = (autopilotVersion.flight_sw_version >> (8*2)) & 0xFF;
patchVersion = (autopilotVersion.flight_sw_version >> (8*1)) & 0xFF;
versionType = (FIRMWARE_VERSION_TYPE)((autopilotVersion.flight_sw_version >> (8*0)) & 0xFF);
vehicle->setFirmwareVersion(majorVersion, minorVersion, patchVersion, versionType);
}
if (vehicle->px4Firmware()) {
// Lower 3 bytes is custom version
int majorVersion, minorVersion, patchVersion;
majorVersion = autopilotVersion.flight_custom_version[2];
minorVersion = autopilotVersion.flight_custom_version[1];
patchVersion = autopilotVersion.flight_custom_version[0];
vehicle->setFirmwareCustomVersion(majorVersion, minorVersion, patchVersion);
// PX4 Firmware stores the first 16 characters of the git hash as binary, with the individual bytes in reverse order
vehicle->_gitHash = "";
for (int i = 7; i >= 0; i--) {
vehicle->_gitHash.append(QString("%1").arg(autopilotVersion.flight_custom_version[i], 2, 16, QChar('0')));
}
} else {
// APM Firmware stores the first 8 characters of the git hash as an ASCII character string
char nullStr[9];
strncpy(nullStr, (char*)autopilotVersion.flight_custom_version, 8);
nullStr[8] = 0;
vehicle->_gitHash = nullStr;
}
if (vehicle->_toolbox->corePlugin()->options()->checkFirmwareVersion() && !vehicle->_checkLatestStableFWDone) {
vehicle->_checkLatestStableFWDone = true;
vehicle->_firmwarePlugin->checkIfIsLatestStable(vehicle);
}
emit vehicle->gitHashChanged(vehicle->_gitHash);
vehicle->_setCapabilities(autopilotVersion.capabilities);
}
connectMachine->advance();
}
void InitialConnectStateMachine::_stateRequestProtocolVersion(StateMachine* stateMachine)
{
InitialConnectStateMachine* connectMachine = static_cast<InitialConnectStateMachine*>(stateMachine);
Vehicle* vehicle = connectMachine->_vehicle;
WeakLinkInterfacePtr weakLink = vehicle->vehicleLinkManager()->primaryLink();
if (weakLink.expired()) {
qCDebug(InitialConnectStateMachineLog) << "_stateRequestProtocolVersion Skipping protocol version request due to no primary link";
connectMachine->advance();
} else {
SharedLinkInterfacePtr sharedLink = weakLink.lock();
if (sharedLink->linkConfiguration()->isHighLatency() || sharedLink->isPX4Flow() || sharedLink->isLogReplay()) {
qCDebug(InitialConnectStateMachineLog) << "_stateRequestProtocolVersion Skipping protocol version request due to link type";
connectMachine->advance();
} else {
qCDebug(InitialConnectStateMachineLog) << "_stateRequestProtocolVersion Requesting protocol version";
vehicle->_waitForMavlinkMessage(_waitForProtocolVersionResultHandler, connectMachine, MAVLINK_MSG_ID_PROTOCOL_VERSION, 1000);
vehicle->sendMavCommandWithHandler(_protocolVersionCmdResultHandler,
connectMachine,
MAV_COMP_ID_AUTOPILOT1,
MAV_CMD_REQUEST_PROTOCOL_VERSION,
1); // Request protocol version
}
}
}
void InitialConnectStateMachine::_protocolVersionCmdResultHandler(void* resultHandlerData, int /*compId*/, MAV_RESULT result, Vehicle::MavCmdResultFailureCode_t failureCode)
{
if (result != MAV_RESULT_ACCEPTED) {
InitialConnectStateMachine* connectMachine = static_cast<InitialConnectStateMachine*>(resultHandlerData);
Vehicle* vehicle = connectMachine->_vehicle;
switch (failureCode) {
case Vehicle::MavCmdResultCommandResultOnly:
qCDebug(InitialConnectStateMachineLog) << QStringLiteral("MAV_CMD_REQUEST_PROTOCOL_VERSION error(%1)").arg(result);
break;
case Vehicle::MavCmdResultFailureNoResponseToCommand:
qCDebug(InitialConnectStateMachineLog) << "MAV_CMD_REQUEST_PROTOCOL_VERSION no response from vehicle";
break;
case Vehicle::MavCmdResultFailureDuplicateCommand:
qCDebug(InitialConnectStateMachineLog) << "Internal Error: MAV_CMD_REQUEST_PROTOCOL_VERSION could not be sent due to duplicate command";
break;
}
// _mavlinkProtocolRequestMaxProtoVersion stays at 0 to indicate unknown
vehicle->_mavlinkProtocolRequestComplete = true;
vehicle->_setMaxProtoVersionFromBothSources();
vehicle->_waitForMavlinkMessageClear();
connectMachine->advance();
}
}
void InitialConnectStateMachine::_waitForProtocolVersionResultHandler(void* resultHandlerData, bool noResponsefromVehicle, const mavlink_message_t& message)
{
InitialConnectStateMachine* connectMachine = static_cast<InitialConnectStateMachine*>(resultHandlerData);
Vehicle* vehicle = connectMachine->_vehicle;
if (noResponsefromVehicle) {
qCDebug(InitialConnectStateMachineLog) << "PROTOCOL_VERSION timeout";
// The PROTOCOL_VERSION message didn't make it through the pipe from Vehicle->QGC.
// This means although the vehicle may support mavlink 2, the pipe does not.
qCDebug(InitialConnectStateMachineLog) << QStringLiteral("Setting _maxProtoVersion to 100 due to timeout on receiving PROTOCOL_VERSION message.");
vehicle->_mavlinkProtocolRequestMaxProtoVersion = 100;
vehicle->_mavlinkProtocolRequestComplete = true;
vehicle->_setMaxProtoVersionFromBothSources();
} else {
mavlink_protocol_version_t protoVersion;
mavlink_msg_protocol_version_decode(&message, &protoVersion);
qCDebug(InitialConnectStateMachineLog) << "PROTOCOL_VERSION received mav_version:" << protoVersion.max_version;
vehicle->_mavlinkProtocolRequestMaxProtoVersion = protoVersion.max_version;
vehicle->_mavlinkProtocolRequestComplete = true;
vehicle->_setMaxProtoVersionFromBothSources();
}
connectMachine->advance();
}
void InitialConnectStateMachine::_stateRequestCompInfo(StateMachine* stateMachine)
{
InitialConnectStateMachine* connectMachine = static_cast<InitialConnectStateMachine*>(stateMachine);
Vehicle* vehicle = connectMachine->_vehicle;
qCDebug(InitialConnectStateMachineLog) << "_stateRequestCompInfo";
vehicle->_componentInformationManager->requestAllComponentInformation(_stateRequestCompInfoComplete, connectMachine);
}
void InitialConnectStateMachine::_stateRequestCompInfoComplete(void* requestAllCompleteFnData)
{
InitialConnectStateMachine* connectMachine = static_cast<InitialConnectStateMachine*>(requestAllCompleteFnData);
connectMachine->advance();
}
void InitialConnectStateMachine::_stateRequestParameters(StateMachine* stateMachine)
{
InitialConnectStateMachine* connectMachine = static_cast<InitialConnectStateMachine*>(stateMachine);
Vehicle* vehicle = connectMachine->_vehicle;
qCDebug(InitialConnectStateMachineLog) << "_stateRequestParameters";
vehicle->_parameterManager->refreshAllParameters();
}
void InitialConnectStateMachine::_stateRequestMission(StateMachine* stateMachine)
{
InitialConnectStateMachine* connectMachine = static_cast<InitialConnectStateMachine*>(stateMachine);
Vehicle* vehicle = connectMachine->_vehicle;
WeakLinkInterfacePtr weakLink = vehicle->vehicleLinkManager()->primaryLink();
if (weakLink.expired()) {
qCDebug(InitialConnectStateMachineLog) << "_stateRequestMission: Skipping first mission load request due to no primary link";
connectMachine->advance();
} else {
SharedLinkInterfacePtr sharedLink = weakLink.lock();
if (sharedLink->linkConfiguration()->isHighLatency() || sharedLink->isPX4Flow() || sharedLink->isLogReplay()) {
qCDebug(InitialConnectStateMachineLog) << "_stateRequestMission: Skipping first mission load request due to link type";
vehicle->_firstMissionLoadComplete();
} else {
qCDebug(InitialConnectStateMachineLog) << "_stateRequestMission";
vehicle->_missionManager->loadFromVehicle();
}
}
}
void InitialConnectStateMachine::_stateRequestGeoFence(StateMachine* stateMachine)
{
InitialConnectStateMachine* connectMachine = static_cast<InitialConnectStateMachine*>(stateMachine);
Vehicle* vehicle = connectMachine->_vehicle;
qCDebug(InitialConnectStateMachineLog) << "_stateRequestGeoFence";
if (vehicle->_geoFenceManager->supported()) {
vehicle->_geoFenceManager->loadFromVehicle();
} else {
qCDebug(InitialConnectStateMachineLog) << "_stateRequestGeoFence: skipped due to no support";
vehicle->_firstGeoFenceLoadComplete();
}
}
void InitialConnectStateMachine::_stateRequestRallyPoints(StateMachine* stateMachine)
{
InitialConnectStateMachine* connectMachine = static_cast<InitialConnectStateMachine*>(stateMachine);
Vehicle* vehicle = connectMachine->_vehicle;
qCDebug(InitialConnectStateMachineLog) << "_stateRequestRallyPoints";
if (vehicle->_rallyPointManager->supported()) {
vehicle->_rallyPointManager->loadFromVehicle();
} else {
qCDebug(InitialConnectStateMachineLog) << "_stateRequestRallyPoints: skipping due to no support";
vehicle->_firstRallyPointLoadComplete();
}
}
void InitialConnectStateMachine::_stateSignalInitialConnectComplete(StateMachine* stateMachine)
{
InitialConnectStateMachine* connectMachine = static_cast<InitialConnectStateMachine*>(stateMachine);
Vehicle* vehicle = connectMachine->_vehicle;
qCDebug(InitialConnectStateMachineLog) << "Signalling initialConnectComplete";
emit vehicle->initialConnectComplete();
}
<commit_msg>Don't query fence/rally on high latency links (#9262)<commit_after>/****************************************************************************
*
* (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
#include "InitialConnectStateMachine.h"
#include "Vehicle.h"
#include "QGCCorePlugin.h"
#include "QGCOptions.h"
#include "FirmwarePlugin.h"
#include "ParameterManager.h"
#include "ComponentInformationManager.h"
#include "MissionManager.h"
QGC_LOGGING_CATEGORY(InitialConnectStateMachineLog, "InitialConnectStateMachineLog")
const StateMachine::StateFn InitialConnectStateMachine::_rgStates[] = {
InitialConnectStateMachine::_stateRequestCapabilities,
InitialConnectStateMachine::_stateRequestProtocolVersion,
InitialConnectStateMachine::_stateRequestCompInfo,
InitialConnectStateMachine::_stateRequestParameters,
InitialConnectStateMachine::_stateRequestMission,
InitialConnectStateMachine::_stateRequestGeoFence,
InitialConnectStateMachine::_stateRequestRallyPoints,
InitialConnectStateMachine::_stateSignalInitialConnectComplete
};
const int InitialConnectStateMachine::_cStates = sizeof(InitialConnectStateMachine::_rgStates) / sizeof(InitialConnectStateMachine::_rgStates[0]);
InitialConnectStateMachine::InitialConnectStateMachine(Vehicle* vehicle)
: _vehicle(vehicle)
{
}
int InitialConnectStateMachine::stateCount(void) const
{
return _cStates;
}
const InitialConnectStateMachine::StateFn* InitialConnectStateMachine::rgStates(void) const
{
return &_rgStates[0];
}
void InitialConnectStateMachine::statesCompleted(void) const
{
}
void InitialConnectStateMachine::_stateRequestCapabilities(StateMachine* stateMachine)
{
InitialConnectStateMachine* connectMachine = static_cast<InitialConnectStateMachine*>(stateMachine);
Vehicle* vehicle = connectMachine->_vehicle;
WeakLinkInterfacePtr weakLink = vehicle->vehicleLinkManager()->primaryLink();
if (weakLink.expired()) {
qCDebug(InitialConnectStateMachineLog) << "_stateRequestCapabilities Skipping capability request due to no primary link";
connectMachine->advance();
} else {
SharedLinkInterfacePtr sharedLink = weakLink.lock();
if (sharedLink->linkConfiguration()->isHighLatency() || sharedLink->isPX4Flow() || sharedLink->isLogReplay()) {
qCDebug(InitialConnectStateMachineLog) << "Skipping capability request due to link type";
connectMachine->advance();
} else {
qCDebug(InitialConnectStateMachineLog) << "Requesting capabilities";
vehicle->_waitForMavlinkMessage(_waitForAutopilotVersionResultHandler, connectMachine, MAVLINK_MSG_ID_AUTOPILOT_VERSION, 1000);
vehicle->sendMavCommandWithHandler(_capabilitiesCmdResultHandler,
connectMachine,
MAV_COMP_ID_AUTOPILOT1,
MAV_CMD_REQUEST_AUTOPILOT_CAPABILITIES,
1); // Request firmware version
}
}
}
void InitialConnectStateMachine::_capabilitiesCmdResultHandler(void* resultHandlerData, int /*compId*/, MAV_RESULT result, Vehicle::MavCmdResultFailureCode_t failureCode)
{
InitialConnectStateMachine* connectMachine = static_cast<InitialConnectStateMachine*>(resultHandlerData);
Vehicle* vehicle = connectMachine->_vehicle;
if (result != MAV_RESULT_ACCEPTED) {
switch (failureCode) {
case Vehicle::MavCmdResultCommandResultOnly:
qCDebug(InitialConnectStateMachineLog) << QStringLiteral("MAV_CMD_REQUEST_AUTOPILOT_CAPABILITIES error(%1)").arg(result);
break;
case Vehicle::MavCmdResultFailureNoResponseToCommand:
qCDebug(InitialConnectStateMachineLog) << "MAV_CMD_REQUEST_AUTOPILOT_CAPABILITIES no response from vehicle";
break;
case Vehicle::MavCmdResultFailureDuplicateCommand:
qCDebug(InitialConnectStateMachineLog) << "Internal Error: MAV_CMD_REQUEST_AUTOPILOT_CAPABILITIES could not be sent due to duplicate command";
break;
}
qCDebug(InitialConnectStateMachineLog) << "Setting no capabilities";
vehicle->_setCapabilities(0);
vehicle->_waitForMavlinkMessageClear();
connectMachine->advance();
}
}
void InitialConnectStateMachine::_waitForAutopilotVersionResultHandler(void* resultHandlerData, bool noResponsefromVehicle, const mavlink_message_t& message)
{
InitialConnectStateMachine* connectMachine = static_cast<InitialConnectStateMachine*>(resultHandlerData);
Vehicle* vehicle = connectMachine->_vehicle;
if (noResponsefromVehicle) {
qCDebug(InitialConnectStateMachineLog) << "AUTOPILOT_VERSION timeout";
qCDebug(InitialConnectStateMachineLog) << "Setting no capabilities";
vehicle->_setCapabilities(0);
} else {
qCDebug(InitialConnectStateMachineLog) << "AUTOPILOT_VERSION received";
mavlink_autopilot_version_t autopilotVersion;
mavlink_msg_autopilot_version_decode(&message, &autopilotVersion);
vehicle->_uid = (quint64)autopilotVersion.uid;
emit vehicle->vehicleUIDChanged();
if (autopilotVersion.flight_sw_version != 0) {
int majorVersion, minorVersion, patchVersion;
FIRMWARE_VERSION_TYPE versionType;
majorVersion = (autopilotVersion.flight_sw_version >> (8*3)) & 0xFF;
minorVersion = (autopilotVersion.flight_sw_version >> (8*2)) & 0xFF;
patchVersion = (autopilotVersion.flight_sw_version >> (8*1)) & 0xFF;
versionType = (FIRMWARE_VERSION_TYPE)((autopilotVersion.flight_sw_version >> (8*0)) & 0xFF);
vehicle->setFirmwareVersion(majorVersion, minorVersion, patchVersion, versionType);
}
if (vehicle->px4Firmware()) {
// Lower 3 bytes is custom version
int majorVersion, minorVersion, patchVersion;
majorVersion = autopilotVersion.flight_custom_version[2];
minorVersion = autopilotVersion.flight_custom_version[1];
patchVersion = autopilotVersion.flight_custom_version[0];
vehicle->setFirmwareCustomVersion(majorVersion, minorVersion, patchVersion);
// PX4 Firmware stores the first 16 characters of the git hash as binary, with the individual bytes in reverse order
vehicle->_gitHash = "";
for (int i = 7; i >= 0; i--) {
vehicle->_gitHash.append(QString("%1").arg(autopilotVersion.flight_custom_version[i], 2, 16, QChar('0')));
}
} else {
// APM Firmware stores the first 8 characters of the git hash as an ASCII character string
char nullStr[9];
strncpy(nullStr, (char*)autopilotVersion.flight_custom_version, 8);
nullStr[8] = 0;
vehicle->_gitHash = nullStr;
}
if (vehicle->_toolbox->corePlugin()->options()->checkFirmwareVersion() && !vehicle->_checkLatestStableFWDone) {
vehicle->_checkLatestStableFWDone = true;
vehicle->_firmwarePlugin->checkIfIsLatestStable(vehicle);
}
emit vehicle->gitHashChanged(vehicle->_gitHash);
vehicle->_setCapabilities(autopilotVersion.capabilities);
}
connectMachine->advance();
}
void InitialConnectStateMachine::_stateRequestProtocolVersion(StateMachine* stateMachine)
{
InitialConnectStateMachine* connectMachine = static_cast<InitialConnectStateMachine*>(stateMachine);
Vehicle* vehicle = connectMachine->_vehicle;
WeakLinkInterfacePtr weakLink = vehicle->vehicleLinkManager()->primaryLink();
if (weakLink.expired()) {
qCDebug(InitialConnectStateMachineLog) << "_stateRequestProtocolVersion Skipping protocol version request due to no primary link";
connectMachine->advance();
} else {
SharedLinkInterfacePtr sharedLink = weakLink.lock();
if (sharedLink->linkConfiguration()->isHighLatency() || sharedLink->isPX4Flow() || sharedLink->isLogReplay()) {
qCDebug(InitialConnectStateMachineLog) << "_stateRequestProtocolVersion Skipping protocol version request due to link type";
connectMachine->advance();
} else {
qCDebug(InitialConnectStateMachineLog) << "_stateRequestProtocolVersion Requesting protocol version";
vehicle->_waitForMavlinkMessage(_waitForProtocolVersionResultHandler, connectMachine, MAVLINK_MSG_ID_PROTOCOL_VERSION, 1000);
vehicle->sendMavCommandWithHandler(_protocolVersionCmdResultHandler,
connectMachine,
MAV_COMP_ID_AUTOPILOT1,
MAV_CMD_REQUEST_PROTOCOL_VERSION,
1); // Request protocol version
}
}
}
void InitialConnectStateMachine::_protocolVersionCmdResultHandler(void* resultHandlerData, int /*compId*/, MAV_RESULT result, Vehicle::MavCmdResultFailureCode_t failureCode)
{
if (result != MAV_RESULT_ACCEPTED) {
InitialConnectStateMachine* connectMachine = static_cast<InitialConnectStateMachine*>(resultHandlerData);
Vehicle* vehicle = connectMachine->_vehicle;
switch (failureCode) {
case Vehicle::MavCmdResultCommandResultOnly:
qCDebug(InitialConnectStateMachineLog) << QStringLiteral("MAV_CMD_REQUEST_PROTOCOL_VERSION error(%1)").arg(result);
break;
case Vehicle::MavCmdResultFailureNoResponseToCommand:
qCDebug(InitialConnectStateMachineLog) << "MAV_CMD_REQUEST_PROTOCOL_VERSION no response from vehicle";
break;
case Vehicle::MavCmdResultFailureDuplicateCommand:
qCDebug(InitialConnectStateMachineLog) << "Internal Error: MAV_CMD_REQUEST_PROTOCOL_VERSION could not be sent due to duplicate command";
break;
}
// _mavlinkProtocolRequestMaxProtoVersion stays at 0 to indicate unknown
vehicle->_mavlinkProtocolRequestComplete = true;
vehicle->_setMaxProtoVersionFromBothSources();
vehicle->_waitForMavlinkMessageClear();
connectMachine->advance();
}
}
void InitialConnectStateMachine::_waitForProtocolVersionResultHandler(void* resultHandlerData, bool noResponsefromVehicle, const mavlink_message_t& message)
{
InitialConnectStateMachine* connectMachine = static_cast<InitialConnectStateMachine*>(resultHandlerData);
Vehicle* vehicle = connectMachine->_vehicle;
if (noResponsefromVehicle) {
qCDebug(InitialConnectStateMachineLog) << "PROTOCOL_VERSION timeout";
// The PROTOCOL_VERSION message didn't make it through the pipe from Vehicle->QGC.
// This means although the vehicle may support mavlink 2, the pipe does not.
qCDebug(InitialConnectStateMachineLog) << QStringLiteral("Setting _maxProtoVersion to 100 due to timeout on receiving PROTOCOL_VERSION message.");
vehicle->_mavlinkProtocolRequestMaxProtoVersion = 100;
vehicle->_mavlinkProtocolRequestComplete = true;
vehicle->_setMaxProtoVersionFromBothSources();
} else {
mavlink_protocol_version_t protoVersion;
mavlink_msg_protocol_version_decode(&message, &protoVersion);
qCDebug(InitialConnectStateMachineLog) << "PROTOCOL_VERSION received mav_version:" << protoVersion.max_version;
vehicle->_mavlinkProtocolRequestMaxProtoVersion = protoVersion.max_version;
vehicle->_mavlinkProtocolRequestComplete = true;
vehicle->_setMaxProtoVersionFromBothSources();
}
connectMachine->advance();
}
void InitialConnectStateMachine::_stateRequestCompInfo(StateMachine* stateMachine)
{
InitialConnectStateMachine* connectMachine = static_cast<InitialConnectStateMachine*>(stateMachine);
Vehicle* vehicle = connectMachine->_vehicle;
qCDebug(InitialConnectStateMachineLog) << "_stateRequestCompInfo";
vehicle->_componentInformationManager->requestAllComponentInformation(_stateRequestCompInfoComplete, connectMachine);
}
void InitialConnectStateMachine::_stateRequestCompInfoComplete(void* requestAllCompleteFnData)
{
InitialConnectStateMachine* connectMachine = static_cast<InitialConnectStateMachine*>(requestAllCompleteFnData);
connectMachine->advance();
}
void InitialConnectStateMachine::_stateRequestParameters(StateMachine* stateMachine)
{
InitialConnectStateMachine* connectMachine = static_cast<InitialConnectStateMachine*>(stateMachine);
Vehicle* vehicle = connectMachine->_vehicle;
qCDebug(InitialConnectStateMachineLog) << "_stateRequestParameters";
vehicle->_parameterManager->refreshAllParameters();
}
void InitialConnectStateMachine::_stateRequestMission(StateMachine* stateMachine)
{
InitialConnectStateMachine* connectMachine = static_cast<InitialConnectStateMachine*>(stateMachine);
Vehicle* vehicle = connectMachine->_vehicle;
WeakLinkInterfacePtr weakLink = vehicle->vehicleLinkManager()->primaryLink();
if (weakLink.expired()) {
qCDebug(InitialConnectStateMachineLog) << "_stateRequestMission: Skipping first mission load request due to no primary link";
connectMachine->advance();
} else {
SharedLinkInterfacePtr sharedLink = weakLink.lock();
if (sharedLink->linkConfiguration()->isHighLatency() || sharedLink->isPX4Flow() || sharedLink->isLogReplay()) {
qCDebug(InitialConnectStateMachineLog) << "_stateRequestMission: Skipping first mission load request due to link type";
vehicle->_firstMissionLoadComplete();
} else {
qCDebug(InitialConnectStateMachineLog) << "_stateRequestMission";
vehicle->_missionManager->loadFromVehicle();
}
}
}
void InitialConnectStateMachine::_stateRequestGeoFence(StateMachine* stateMachine)
{
InitialConnectStateMachine* connectMachine = static_cast<InitialConnectStateMachine*>(stateMachine);
Vehicle* vehicle = connectMachine->_vehicle;
WeakLinkInterfacePtr weakLink = vehicle->vehicleLinkManager()->primaryLink();
if (weakLink.expired()) {
qCDebug(InitialConnectStateMachineLog) << "_stateRequestGeoFence: Skipping first geofence load request due to no primary link";
connectMachine->advance();
} else {
SharedLinkInterfacePtr sharedLink = weakLink.lock();
if (sharedLink->linkConfiguration()->isHighLatency() || sharedLink->isPX4Flow() || sharedLink->isLogReplay()) {
qCDebug(InitialConnectStateMachineLog) << "_stateRequestGeoFence: Skipping first geofence load request due to link type";
vehicle->_firstGeoFenceLoadComplete();
} else {
if (vehicle->_geoFenceManager->supported()) {
qCDebug(InitialConnectStateMachineLog) << "_stateRequestGeoFence";
vehicle->_geoFenceManager->loadFromVehicle();
} else {
qCDebug(InitialConnectStateMachineLog) << "_stateRequestGeoFence: skipped due to no support";
vehicle->_firstGeoFenceLoadComplete();
}
}
}
}
void InitialConnectStateMachine::_stateRequestRallyPoints(StateMachine* stateMachine)
{
InitialConnectStateMachine* connectMachine = static_cast<InitialConnectStateMachine*>(stateMachine);
Vehicle* vehicle = connectMachine->_vehicle;
WeakLinkInterfacePtr weakLink = vehicle->vehicleLinkManager()->primaryLink();
if (weakLink.expired()) {
qCDebug(InitialConnectStateMachineLog) << "_stateRequestRallyPoints: Skipping first rally point load request due to no primary link";
connectMachine->advance();
} else {
SharedLinkInterfacePtr sharedLink = weakLink.lock();
if (sharedLink->linkConfiguration()->isHighLatency() || sharedLink->isPX4Flow() || sharedLink->isLogReplay()) {
qCDebug(InitialConnectStateMachineLog) << "_stateRequestRallyPoints: Skipping first rally point load request due to link type";
vehicle->_firstRallyPointLoadComplete();
} else {
if (vehicle->_rallyPointManager->supported()) {
vehicle->_rallyPointManager->loadFromVehicle();
} else {
qCDebug(InitialConnectStateMachineLog) << "_stateRequestRallyPoints: skipping due to no support";
vehicle->_firstRallyPointLoadComplete();
}
}
}
}
void InitialConnectStateMachine::_stateSignalInitialConnectComplete(StateMachine* stateMachine)
{
InitialConnectStateMachine* connectMachine = static_cast<InitialConnectStateMachine*>(stateMachine);
Vehicle* vehicle = connectMachine->_vehicle;
qCDebug(InitialConnectStateMachineLog) << "Signalling initialConnectComplete";
emit vehicle->initialConnectComplete();
}
<|endoftext|>
|
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "query.h"
#include "blueprintbuilder.h"
#include "matchdatareservevisitor.h"
#include "resolveviewvisitor.h"
#include "termdataextractor.h"
#include "sameelementmodifier.h"
#include "unpacking_iterators_optimizer.h"
#include <vespa/document/datatype/positiondatatype.h>
#include <vespa/searchlib/common/location.h>
#include <vespa/searchlib/parsequery/stackdumpiterator.h>
#include <vespa/searchlib/query/tree/point.h>
#include <vespa/searchlib/query/tree/rectangle.h>
#include <vespa/searchlib/queryeval/intermediate_blueprints.h>
#include <vespa/log/log.h>
LOG_SETUP(".proton.matching.query");
#include <vespa/searchlib/query/tree/querytreecreator.h>
using document::PositionDataType;
using search::SimpleQueryStackDumpIterator;
using search::fef::IIndexEnvironment;
using search::fef::ITermData;
using search::fef::MatchData;
using search::fef::MatchDataLayout;
using search::fef::Location;
using search::query::Node;
using search::query::QueryTreeCreator;
using search::query::Weight;
using search::queryeval::AndBlueprint;
using search::queryeval::AndNotBlueprint;
using search::queryeval::RankBlueprint;
using search::queryeval::IntermediateBlueprint;
using search::queryeval::Blueprint;
using search::queryeval::IRequestContext;
using search::queryeval::SearchIterator;
using vespalib::string;
using std::vector;
namespace proton::matching {
namespace {
Node::UP
inject(Node::UP query, Node::UP to_inject) {
if (auto * my_and = dynamic_cast<search::query::And *>(query.get())) {
my_and->append(std::move(to_inject));
} else if (dynamic_cast<search::query::Rank *>(query.get()) || dynamic_cast<search::query::AndNot *>(query.get())) {
search::query::Intermediate & root = static_cast<search::query::Intermediate &>(*query);
root.prepend(inject(root.stealFirst(), std::move(to_inject)));
} else {
auto new_root = std::make_unique<ProtonAnd>();
new_root->append(std::move(query));
new_root->append(std::move(to_inject));
query = std::move(new_root);
}
return query;
}
void
addLocationNode(const string &location_str, Node::UP &query_tree, Location &fef_location) {
if (location_str.empty()) {
return;
}
string::size_type pos = location_str.find(':');
if (pos == string::npos) {
LOG(warning, "Location string lacks attribute vector specification. loc='%s'", location_str.c_str());
return;
}
const string view = PositionDataType::getZCurveFieldName(location_str.substr(0, pos));
const string loc = location_str.substr(pos + 1);
search::common::Location locationSpec;
if (!locationSpec.parse(loc)) {
LOG(warning, "Location parse error (location: '%s'): %s", location_str.c_str(), locationSpec.getParseError());
return;
}
int32_t id = -1;
Weight weight(100);
if (locationSpec.getRankOnDistance()) {
query_tree = inject(std::move(query_tree), std::make_unique<ProtonLocationTerm>(loc, view, id, weight));
fef_location.setAttribute(view);
fef_location.setXPosition(locationSpec.getX());
fef_location.setYPosition(locationSpec.getY());
fef_location.setXAspect(locationSpec.getXAspect());
fef_location.setValid(true);
} else if (locationSpec.getPruneOnDistance()) {
query_tree = inject(std::move(query_tree), std::make_unique<ProtonLocationTerm>(loc, view, id, weight));
}
}
IntermediateBlueprint *
asRankOrAndNot(Blueprint * blueprint) {
IntermediateBlueprint * rankOrAndNot = dynamic_cast<RankBlueprint*>(blueprint);
if (rankOrAndNot == nullptr) {
rankOrAndNot = dynamic_cast<AndNotBlueprint*>(blueprint);
}
return rankOrAndNot;
}
IntermediateBlueprint *
lastConsequtiveRankOrAndNot(Blueprint * blueprint) {
IntermediateBlueprint * prev = nullptr;
IntermediateBlueprint * curr = asRankOrAndNot(blueprint);
while (curr != nullptr) {
prev = curr;
curr = asRankOrAndNot(&curr->getChild(0));
}
return prev;
}
} // namespace
Query::Query() = default;
Query::~Query() = default;
bool
Query::buildTree(vespalib::stringref stack, const string &location,
const ViewResolver &resolver, const IIndexEnvironment &indexEnv,
bool split_unpacking_iterators, bool delay_unpacking_iterators)
{
SimpleQueryStackDumpIterator stack_dump_iterator(stack);
_query_tree = QueryTreeCreator<ProtonNodeTypes>::create(stack_dump_iterator);
if (_query_tree) {
SameElementModifier prefixSameElementSubIndexes;
_query_tree->accept(prefixSameElementSubIndexes);
addLocationNode(location, _query_tree, _location);
_query_tree = UnpackingIteratorsOptimizer::optimize(std::move(_query_tree),
bool(_whiteListBlueprint), split_unpacking_iterators, delay_unpacking_iterators);
ResolveViewVisitor resolve_visitor(resolver, indexEnv);
_query_tree->accept(resolve_visitor);
return true;
} else {
// TODO(havardpe): log warning or pass message upwards
return false;
}
}
void
Query::extractTerms(vector<const ITermData *> &terms)
{
TermDataExtractor::extractTerms(*_query_tree, terms);
}
void
Query::extractLocations(vector<const Location *> &locations)
{
locations.clear();
locations.push_back(&_location);
}
void
Query::setWhiteListBlueprint(Blueprint::UP whiteListBlueprint)
{
_whiteListBlueprint = std::move(whiteListBlueprint);
}
void
Query::reserveHandles(const IRequestContext & requestContext, ISearchContext &context, MatchDataLayout &mdl)
{
MatchDataReserveVisitor reserve_visitor(mdl);
_query_tree->accept(reserve_visitor);
_blueprint = BlueprintBuilder::build(requestContext, *_query_tree, context);
LOG(debug, "original blueprint:\n%s\n", _blueprint->asString().c_str());
if (_whiteListBlueprint) {
auto andBlueprint = std::make_unique<AndBlueprint>();
IntermediateBlueprint * rankOrAndNot = lastConsequtiveRankOrAndNot(_blueprint.get());
if (rankOrAndNot != nullptr) {
(*andBlueprint)
.addChild(rankOrAndNot->removeChild(0))
.addChild(std::move(_whiteListBlueprint));
rankOrAndNot->insertChild(0, std::move(andBlueprint));
} else {
(*andBlueprint)
.addChild(std::move(_blueprint))
.addChild(std::move(_whiteListBlueprint));
_blueprint = std::move(andBlueprint);
}
_blueprint->setDocIdLimit(context.getDocIdLimit());
LOG(debug, "blueprint after white listing:\n%s\n", _blueprint->asString().c_str());
}
}
void
Query::optimize()
{
_blueprint = Blueprint::optimize(std::move(_blueprint));
LOG(debug, "optimized blueprint:\n%s\n", _blueprint->asString().c_str());
}
void
Query::fetchPostings()
{
_blueprint->fetchPostings(search::queryeval::ExecuteInfo::create(true, 1.0));
}
void
Query::freeze()
{
_blueprint->freeze();
}
Blueprint::HitEstimate
Query::estimate() const
{
return _blueprint->getState().estimate();
}
SearchIterator::UP
Query::createSearch(MatchData &md) const
{
return _blueprint->createSearch(md, true);
}
}
<commit_msg>actually call set_global_filter (with empty SP for now)<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "query.h"
#include "blueprintbuilder.h"
#include "matchdatareservevisitor.h"
#include "resolveviewvisitor.h"
#include "termdataextractor.h"
#include "sameelementmodifier.h"
#include "unpacking_iterators_optimizer.h"
#include <vespa/document/datatype/positiondatatype.h>
#include <vespa/searchlib/common/location.h>
#include <vespa/searchlib/parsequery/stackdumpiterator.h>
#include <vespa/searchlib/query/tree/point.h>
#include <vespa/searchlib/query/tree/rectangle.h>
#include <vespa/searchlib/queryeval/intermediate_blueprints.h>
#include <vespa/log/log.h>
LOG_SETUP(".proton.matching.query");
#include <vespa/searchlib/query/tree/querytreecreator.h>
using document::PositionDataType;
using search::SimpleQueryStackDumpIterator;
using search::fef::IIndexEnvironment;
using search::fef::ITermData;
using search::fef::MatchData;
using search::fef::MatchDataLayout;
using search::fef::Location;
using search::query::Node;
using search::query::QueryTreeCreator;
using search::query::Weight;
using search::queryeval::AndBlueprint;
using search::queryeval::AndNotBlueprint;
using search::queryeval::RankBlueprint;
using search::queryeval::IntermediateBlueprint;
using search::queryeval::Blueprint;
using search::queryeval::IRequestContext;
using search::queryeval::SearchIterator;
using vespalib::string;
using std::vector;
namespace proton::matching {
namespace {
Node::UP
inject(Node::UP query, Node::UP to_inject) {
if (auto * my_and = dynamic_cast<search::query::And *>(query.get())) {
my_and->append(std::move(to_inject));
} else if (dynamic_cast<search::query::Rank *>(query.get()) || dynamic_cast<search::query::AndNot *>(query.get())) {
search::query::Intermediate & root = static_cast<search::query::Intermediate &>(*query);
root.prepend(inject(root.stealFirst(), std::move(to_inject)));
} else {
auto new_root = std::make_unique<ProtonAnd>();
new_root->append(std::move(query));
new_root->append(std::move(to_inject));
query = std::move(new_root);
}
return query;
}
void
addLocationNode(const string &location_str, Node::UP &query_tree, Location &fef_location) {
if (location_str.empty()) {
return;
}
string::size_type pos = location_str.find(':');
if (pos == string::npos) {
LOG(warning, "Location string lacks attribute vector specification. loc='%s'", location_str.c_str());
return;
}
const string view = PositionDataType::getZCurveFieldName(location_str.substr(0, pos));
const string loc = location_str.substr(pos + 1);
search::common::Location locationSpec;
if (!locationSpec.parse(loc)) {
LOG(warning, "Location parse error (location: '%s'): %s", location_str.c_str(), locationSpec.getParseError());
return;
}
int32_t id = -1;
Weight weight(100);
if (locationSpec.getRankOnDistance()) {
query_tree = inject(std::move(query_tree), std::make_unique<ProtonLocationTerm>(loc, view, id, weight));
fef_location.setAttribute(view);
fef_location.setXPosition(locationSpec.getX());
fef_location.setYPosition(locationSpec.getY());
fef_location.setXAspect(locationSpec.getXAspect());
fef_location.setValid(true);
} else if (locationSpec.getPruneOnDistance()) {
query_tree = inject(std::move(query_tree), std::make_unique<ProtonLocationTerm>(loc, view, id, weight));
}
}
IntermediateBlueprint *
asRankOrAndNot(Blueprint * blueprint) {
IntermediateBlueprint * rankOrAndNot = dynamic_cast<RankBlueprint*>(blueprint);
if (rankOrAndNot == nullptr) {
rankOrAndNot = dynamic_cast<AndNotBlueprint*>(blueprint);
}
return rankOrAndNot;
}
IntermediateBlueprint *
lastConsequtiveRankOrAndNot(Blueprint * blueprint) {
IntermediateBlueprint * prev = nullptr;
IntermediateBlueprint * curr = asRankOrAndNot(blueprint);
while (curr != nullptr) {
prev = curr;
curr = asRankOrAndNot(&curr->getChild(0));
}
return prev;
}
} // namespace
Query::Query() = default;
Query::~Query() = default;
bool
Query::buildTree(vespalib::stringref stack, const string &location,
const ViewResolver &resolver, const IIndexEnvironment &indexEnv,
bool split_unpacking_iterators, bool delay_unpacking_iterators)
{
SimpleQueryStackDumpIterator stack_dump_iterator(stack);
_query_tree = QueryTreeCreator<ProtonNodeTypes>::create(stack_dump_iterator);
if (_query_tree) {
SameElementModifier prefixSameElementSubIndexes;
_query_tree->accept(prefixSameElementSubIndexes);
addLocationNode(location, _query_tree, _location);
_query_tree = UnpackingIteratorsOptimizer::optimize(std::move(_query_tree),
bool(_whiteListBlueprint), split_unpacking_iterators, delay_unpacking_iterators);
ResolveViewVisitor resolve_visitor(resolver, indexEnv);
_query_tree->accept(resolve_visitor);
return true;
} else {
// TODO(havardpe): log warning or pass message upwards
return false;
}
}
void
Query::extractTerms(vector<const ITermData *> &terms)
{
TermDataExtractor::extractTerms(*_query_tree, terms);
}
void
Query::extractLocations(vector<const Location *> &locations)
{
locations.clear();
locations.push_back(&_location);
}
void
Query::setWhiteListBlueprint(Blueprint::UP whiteListBlueprint)
{
_whiteListBlueprint = std::move(whiteListBlueprint);
}
void
Query::reserveHandles(const IRequestContext & requestContext, ISearchContext &context, MatchDataLayout &mdl)
{
MatchDataReserveVisitor reserve_visitor(mdl);
_query_tree->accept(reserve_visitor);
_blueprint = BlueprintBuilder::build(requestContext, *_query_tree, context);
LOG(debug, "original blueprint:\n%s\n", _blueprint->asString().c_str());
if (_whiteListBlueprint) {
auto andBlueprint = std::make_unique<AndBlueprint>();
IntermediateBlueprint * rankOrAndNot = lastConsequtiveRankOrAndNot(_blueprint.get());
if (rankOrAndNot != nullptr) {
(*andBlueprint)
.addChild(rankOrAndNot->removeChild(0))
.addChild(std::move(_whiteListBlueprint));
rankOrAndNot->insertChild(0, std::move(andBlueprint));
} else {
(*andBlueprint)
.addChild(std::move(_blueprint))
.addChild(std::move(_whiteListBlueprint));
_blueprint = std::move(andBlueprint);
}
_blueprint->setDocIdLimit(context.getDocIdLimit());
LOG(debug, "blueprint after white listing:\n%s\n", _blueprint->asString().c_str());
}
}
void
Query::optimize()
{
_blueprint = Blueprint::optimize(std::move(_blueprint));
if (_blueprint->getState().want_global_filter()) {
// XXX we need to somehow compute a real global filter
std::shared_ptr<search::BitVector> empty_global_filter;
_blueprint->set_global_filter(empty_global_filter);
// optimized order may change after accounting for global filter:
_blueprint = Blueprint::optimize(std::move(_blueprint));
}
LOG(debug, "optimized blueprint:\n%s\n", _blueprint->asString().c_str());
}
void
Query::fetchPostings()
{
_blueprint->fetchPostings(search::queryeval::ExecuteInfo::create(true, 1.0));
}
void
Query::freeze()
{
_blueprint->freeze();
}
Blueprint::HitEstimate
Query::estimate() const
{
return _blueprint->getState().estimate();
}
SearchIterator::UP
Query::createSearch(MatchData &md) const
{
return _blueprint->createSearch(md, true);
}
}
<|endoftext|>
|
<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/fastos/fastos.h>
#include "postingchange.h"
#include "multivaluemapping.h"
#include "postinglistattribute.h"
#include <vespa/searchlib/common/bitvector.h>
#include <map>
namespace search {
namespace
{
void
removeDupAdditions(PostingChange<AttributePosting>::A &additions)
{
typedef PostingChange<AttributePosting>::A::iterator Iterator;
if (additions.empty())
return;
if (additions.size() == 1)
return;
std::sort(additions.begin(), additions.end());
Iterator i = additions.begin();
Iterator ie = additions.end();
Iterator d = i;
for (++i; i != ie; ++i, ++d) {
if (d->_key == i->_key)
break;
}
if (i == ie)
return; // no dups found
for (++i; i != ie; ++i) {
if (d->_key != i->_key) {
++d;
*d = *i;
}
}
additions.resize(d - additions.begin() + 1);
}
void
removeDupAdditions(PostingChange<AttributeWeightPosting>::A &additions)
{
typedef PostingChange<AttributeWeightPosting>::A::iterator Iterator;
if (additions.empty())
return;
if (additions.size() == 1u)
return;
std::sort(additions.begin(), additions.end());
Iterator i = additions.begin();
Iterator ie = additions.end();
Iterator d = i;
for (++i; i != ie; ++i, ++d) {
if (d->_key == i->_key)
break;
}
if (i == ie)
return; // no dups found
// sum weights together
d->setData(d->getData() + i->getData());
for (++i; i != ie; ++i) {
if (d->_key != i->_key) {
++d;
*d = *i;
} else {
// sum weights together
d->setData(d->getData() + i->getData());
}
}
additions.resize(d - additions.begin() + 1);
}
void
removeDupRemovals(std::vector<uint32_t> &removals)
{
typedef std::vector<uint32_t>::iterator Iterator;
if (removals.empty())
return;
if (removals.size() == 1u)
return;
std::sort(removals.begin(), removals.end());
Iterator i = removals.begin();
Iterator ie = removals.end();
Iterator d = i;
for (++i; i != ie; ++i, ++d) {
if (*d == *i)
break;
}
if (i == ie)
return; // no dups found
for (++i; i != ie; ++i) {
if (*d != *i) {
++d;
*d = *i;
}
}
removals.resize(d - removals.begin() + 1);
}
}
EnumStoreBase::Index
EnumIndexMapper::map(EnumStoreBase::Index original, const EnumStoreComparator & compare) const
{
(void) compare;
return original;
}
template <>
void
PostingChange<AttributePosting>::removeDups(void)
{
removeDupAdditions(_additions);
removeDupRemovals(_removals);
}
template <>
void
PostingChange<AttributeWeightPosting>::removeDups(void)
{
removeDupAdditions(_additions);
removeDupRemovals(_removals);
}
template <typename P>
void
PostingChange<P>::apply(GrowableBitVector &bv)
{
P *a = &_additions[0];
P *ae = &_additions[0] + _additions.size();
uint32_t *r = &_removals[0];
uint32_t *re = &_removals[0] + _removals.size();
while (a != ae || r != re) {
if (r != re && (a == ae || *r < a->_key)) {
// remove
assert(*r < bv.size());
bv.slowClearBit(*r);
++r;
} else {
if (r != re && !(a->_key < *r)) {
// update or add
assert(a->_key < bv.size());
bv.slowSetBit(a->_key);
++r;
} else {
assert(a->_key < bv.size());
bv.slowSetBit(a->_key);
}
++a;
}
}
}
template <typename WeightedIndex>
class ActualChangeComputer {
public:
using EnumIndex = EnumStoreBase::Index;
using AlwaysWeightedIndexVector = std::vector<multivalue::WeightedValue<EnumIndex>>;
using WeightedIndexVector = std::vector<WeightedIndex>;
void compute(const WeightedIndex * entriesNew, size_t szNew,
const WeightedIndex * entriesOld, size_t szOld,
AlwaysWeightedIndexVector & added, AlwaysWeightedIndexVector & changed, AlwaysWeightedIndexVector & removed);
ActualChangeComputer(const EnumStoreComparator &compare,
const EnumIndexMapper &mapper)
: _oldEntries(),
_newEntries(),
_cachedMapping(),
_compare(compare),
_mapper(mapper),
_hasFold(mapper.hasFold())
{
}
private:
WeightedIndexVector _oldEntries;
WeightedIndexVector _newEntries;
vespalib::hash_map<uint32_t, uint32_t> _cachedMapping;
const EnumStoreComparator &_compare;
const EnumIndexMapper &_mapper;
const bool _hasFold;
static void copyFast(WeightedIndexVector &dst, const WeightedIndex *src, size_t sz)
{
dst.insert(dst.begin(), src, src + sz);
}
EnumIndex mapEnumIndex(EnumIndex unmapped) {
auto itr = _cachedMapping.insert(std::make_pair(unmapped.ref(), 0));
if (itr.second) {
itr.first->second = _mapper.map(unmapped, _compare).ref();
}
return EnumIndex(itr.first->second);
}
void copyMapped(WeightedIndexVector &dst, const WeightedIndex *src, size_t sz)
{
const WeightedIndex *srce = src + sz;
for (const WeightedIndex *i = src; i < srce; ++i) {
dst.emplace_back(mapEnumIndex(i->value()), i->weight());
}
}
void copyEntries(WeightedIndexVector &dst, const WeightedIndex *src, size_t sz)
{
dst.reserve(sz);
dst.clear();
if (_hasFold) {
copyMapped(dst, src, sz);
} else {
copyFast(dst, src, sz);
}
std::sort(dst.begin(), dst.end());
}
};
template <typename WeightedIndex>
class MergeDupIterator {
using InnerIter = typename std::vector<WeightedIndex>::const_iterator;
using EnumIndex = EnumStoreBase::Index;
using Entry = multivalue::WeightedValue<EnumIndex>;
InnerIter _cur;
InnerIter _end;
Entry _entry;
bool _valid;
void merge() {
EnumIndex idx = _cur->value();
int32_t weight = _cur->weight();
++_cur;
while (_cur != _end && _cur->value() == idx) {
// sum weights together. Overflow is not handled.
weight += _cur->weight();
++_cur;
}
_entry = Entry(idx, weight);
}
public:
MergeDupIterator(const std::vector<WeightedIndex> &vec)
: _cur(vec.begin()),
_end(vec.end()),
_entry(),
_valid(_cur != _end)
{
if (_valid) {
merge();
}
}
bool valid() const { return _valid; }
const Entry &entry() const { return _entry; }
EnumIndex value() const { return _entry.value(); }
int32_t weight() const { return _entry.weight(); }
void next() {
if (_cur != _end) {
merge();
} else {
_valid = false;
}
}
};
template <typename WeightedIndex>
void
ActualChangeComputer<WeightedIndex>::compute(const WeightedIndex * entriesNew, size_t szNew,
const WeightedIndex * entriesOld, size_t szOld,
AlwaysWeightedIndexVector & added,
AlwaysWeightedIndexVector & changed,
AlwaysWeightedIndexVector & removed)
{
copyEntries(_newEntries, entriesNew, szNew);
copyEntries(_oldEntries, entriesOld, szOld);
MergeDupIterator<WeightedIndex> oldIt(_oldEntries);
MergeDupIterator<WeightedIndex> newIt(_newEntries);
while (newIt.valid() && oldIt.valid()) {
if (newIt.value() == oldIt.value()) {
if (newIt.weight() != oldIt.weight()) {
changed.push_back(newIt.entry());
}
newIt.next();
oldIt.next();
} else if (newIt.value() < oldIt.value()) {
added.push_back(newIt.entry());
newIt.next();
} else {
removed.push_back(oldIt.entry());
oldIt.next();
}
}
while (newIt.valid()) {
added.push_back(newIt.entry());
newIt.next();
}
while (oldIt.valid()) {
removed.push_back(oldIt.entry());
oldIt.next();
}
}
template <typename WeightedIndex, typename PostingMap>
template <typename MultivalueMapping>
PostingMap
PostingChangeComputerT<WeightedIndex, PostingMap>::
compute(const MultivalueMapping & mvm, const DocIndices & docIndices,
const EnumStoreComparator & compare, const EnumIndexMapper & mapper)
{
typedef ActualChangeComputer<WeightedIndex> AC;
AC actualChange(compare, mapper);
typename AC::AlwaysWeightedIndexVector added, changed, removed;
PostingMap changePost;
// generate add postings and remove postings
for (const auto & docIndex : docIndices) {
const WeightedIndex * oldIndices = NULL;
uint32_t valueCount = mvm.get(docIndex.first, oldIndices);
added.clear(), changed.clear(), removed.clear();
actualChange.compute(&docIndex.second[0], docIndex.second.size(), oldIndices, valueCount,
added, changed, removed);
for (const auto & wi : added) {
changePost[EnumPostingPair(wi.value(), &compare)].add(docIndex.first, wi.weight());
}
for (const auto & wi : removed) {
changePost[EnumPostingPair(wi.value(), &compare)].remove(docIndex.first);
}
for (const auto & wi : changed) {
changePost[EnumPostingPair(wi.value(), &compare)].remove(docIndex.first).add(docIndex.first, wi.weight());
}
}
return changePost;
}
template class PostingChange<AttributePosting>;
template class PostingChange<AttributeWeightPosting>;
typedef PostingChange<btree::BTreeKeyData<unsigned int, int> > WeightedPostingChange;
typedef std::map<EnumPostingPair, WeightedPostingChange> WeightedPostingChangeMap;
typedef EnumStoreBase::Index EnumIndex;
typedef multivalue::WeightedValue<EnumIndex> WeightedIndex;
typedef multivalue::Value<EnumIndex> ValueIndex;
typedef MultiValueMappingT<WeightedIndex, multivalue::Index32> NormalWeightedMultiValueMapping;
typedef MultiValueMappingT<WeightedIndex, multivalue::Index64> HugeWeightedMultiValueMapping;
typedef MultiValueMappingT<ValueIndex, multivalue::Index32> NormalValueMultiValueMapping;
typedef MultiValueMappingT<ValueIndex, multivalue::Index64> HugeValueMultiValueMapping;
typedef std::vector<std::pair<uint32_t, std::vector<WeightedIndex>>> DocIndicesWeighted;
typedef std::vector<std::pair<uint32_t, std::vector<ValueIndex>>> DocIndicesValue;
template WeightedPostingChangeMap PostingChangeComputerT<WeightedIndex, WeightedPostingChangeMap>
::compute<NormalWeightedMultiValueMapping>(const NormalWeightedMultiValueMapping &,
const DocIndicesWeighted &,
const EnumStoreComparator &,
const EnumIndexMapper &);
template WeightedPostingChangeMap PostingChangeComputerT<WeightedIndex, WeightedPostingChangeMap>
::compute<HugeWeightedMultiValueMapping>(const HugeWeightedMultiValueMapping &,
const DocIndicesWeighted &,
const EnumStoreComparator &,
const EnumIndexMapper &);
template WeightedPostingChangeMap PostingChangeComputerT<ValueIndex, WeightedPostingChangeMap>
::compute<NormalValueMultiValueMapping>(const NormalValueMultiValueMapping &,
const DocIndicesValue &,
const EnumStoreComparator &,
const EnumIndexMapper &);
template WeightedPostingChangeMap PostingChangeComputerT<ValueIndex, WeightedPostingChangeMap>
::compute<HugeValueMultiValueMapping>(const HugeValueMultiValueMapping &,
const DocIndicesValue &,
const EnumStoreComparator &,
const EnumIndexMapper &);
}
<commit_msg>Use new API to get values from multi value mapping when calculating posting change.<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/fastos/fastos.h>
#include "postingchange.h"
#include "multivaluemapping.h"
#include "postinglistattribute.h"
#include <vespa/searchlib/common/bitvector.h>
#include <map>
namespace search {
namespace
{
void
removeDupAdditions(PostingChange<AttributePosting>::A &additions)
{
typedef PostingChange<AttributePosting>::A::iterator Iterator;
if (additions.empty())
return;
if (additions.size() == 1)
return;
std::sort(additions.begin(), additions.end());
Iterator i = additions.begin();
Iterator ie = additions.end();
Iterator d = i;
for (++i; i != ie; ++i, ++d) {
if (d->_key == i->_key)
break;
}
if (i == ie)
return; // no dups found
for (++i; i != ie; ++i) {
if (d->_key != i->_key) {
++d;
*d = *i;
}
}
additions.resize(d - additions.begin() + 1);
}
void
removeDupAdditions(PostingChange<AttributeWeightPosting>::A &additions)
{
typedef PostingChange<AttributeWeightPosting>::A::iterator Iterator;
if (additions.empty())
return;
if (additions.size() == 1u)
return;
std::sort(additions.begin(), additions.end());
Iterator i = additions.begin();
Iterator ie = additions.end();
Iterator d = i;
for (++i; i != ie; ++i, ++d) {
if (d->_key == i->_key)
break;
}
if (i == ie)
return; // no dups found
// sum weights together
d->setData(d->getData() + i->getData());
for (++i; i != ie; ++i) {
if (d->_key != i->_key) {
++d;
*d = *i;
} else {
// sum weights together
d->setData(d->getData() + i->getData());
}
}
additions.resize(d - additions.begin() + 1);
}
void
removeDupRemovals(std::vector<uint32_t> &removals)
{
typedef std::vector<uint32_t>::iterator Iterator;
if (removals.empty())
return;
if (removals.size() == 1u)
return;
std::sort(removals.begin(), removals.end());
Iterator i = removals.begin();
Iterator ie = removals.end();
Iterator d = i;
for (++i; i != ie; ++i, ++d) {
if (*d == *i)
break;
}
if (i == ie)
return; // no dups found
for (++i; i != ie; ++i) {
if (*d != *i) {
++d;
*d = *i;
}
}
removals.resize(d - removals.begin() + 1);
}
}
EnumStoreBase::Index
EnumIndexMapper::map(EnumStoreBase::Index original, const EnumStoreComparator & compare) const
{
(void) compare;
return original;
}
template <>
void
PostingChange<AttributePosting>::removeDups(void)
{
removeDupAdditions(_additions);
removeDupRemovals(_removals);
}
template <>
void
PostingChange<AttributeWeightPosting>::removeDups(void)
{
removeDupAdditions(_additions);
removeDupRemovals(_removals);
}
template <typename P>
void
PostingChange<P>::apply(GrowableBitVector &bv)
{
P *a = &_additions[0];
P *ae = &_additions[0] + _additions.size();
uint32_t *r = &_removals[0];
uint32_t *re = &_removals[0] + _removals.size();
while (a != ae || r != re) {
if (r != re && (a == ae || *r < a->_key)) {
// remove
assert(*r < bv.size());
bv.slowClearBit(*r);
++r;
} else {
if (r != re && !(a->_key < *r)) {
// update or add
assert(a->_key < bv.size());
bv.slowSetBit(a->_key);
++r;
} else {
assert(a->_key < bv.size());
bv.slowSetBit(a->_key);
}
++a;
}
}
}
template <typename WeightedIndex>
class ActualChangeComputer {
public:
using EnumIndex = EnumStoreBase::Index;
using AlwaysWeightedIndexVector = std::vector<multivalue::WeightedValue<EnumIndex>>;
using WeightedIndexVector = std::vector<WeightedIndex>;
void compute(const WeightedIndex * entriesNew, size_t szNew,
const WeightedIndex * entriesOld, size_t szOld,
AlwaysWeightedIndexVector & added, AlwaysWeightedIndexVector & changed, AlwaysWeightedIndexVector & removed);
ActualChangeComputer(const EnumStoreComparator &compare,
const EnumIndexMapper &mapper)
: _oldEntries(),
_newEntries(),
_cachedMapping(),
_compare(compare),
_mapper(mapper),
_hasFold(mapper.hasFold())
{
}
private:
WeightedIndexVector _oldEntries;
WeightedIndexVector _newEntries;
vespalib::hash_map<uint32_t, uint32_t> _cachedMapping;
const EnumStoreComparator &_compare;
const EnumIndexMapper &_mapper;
const bool _hasFold;
static void copyFast(WeightedIndexVector &dst, const WeightedIndex *src, size_t sz)
{
dst.insert(dst.begin(), src, src + sz);
}
EnumIndex mapEnumIndex(EnumIndex unmapped) {
auto itr = _cachedMapping.insert(std::make_pair(unmapped.ref(), 0));
if (itr.second) {
itr.first->second = _mapper.map(unmapped, _compare).ref();
}
return EnumIndex(itr.first->second);
}
void copyMapped(WeightedIndexVector &dst, const WeightedIndex *src, size_t sz)
{
const WeightedIndex *srce = src + sz;
for (const WeightedIndex *i = src; i < srce; ++i) {
dst.emplace_back(mapEnumIndex(i->value()), i->weight());
}
}
void copyEntries(WeightedIndexVector &dst, const WeightedIndex *src, size_t sz)
{
dst.reserve(sz);
dst.clear();
if (_hasFold) {
copyMapped(dst, src, sz);
} else {
copyFast(dst, src, sz);
}
std::sort(dst.begin(), dst.end());
}
};
template <typename WeightedIndex>
class MergeDupIterator {
using InnerIter = typename std::vector<WeightedIndex>::const_iterator;
using EnumIndex = EnumStoreBase::Index;
using Entry = multivalue::WeightedValue<EnumIndex>;
InnerIter _cur;
InnerIter _end;
Entry _entry;
bool _valid;
void merge() {
EnumIndex idx = _cur->value();
int32_t weight = _cur->weight();
++_cur;
while (_cur != _end && _cur->value() == idx) {
// sum weights together. Overflow is not handled.
weight += _cur->weight();
++_cur;
}
_entry = Entry(idx, weight);
}
public:
MergeDupIterator(const std::vector<WeightedIndex> &vec)
: _cur(vec.begin()),
_end(vec.end()),
_entry(),
_valid(_cur != _end)
{
if (_valid) {
merge();
}
}
bool valid() const { return _valid; }
const Entry &entry() const { return _entry; }
EnumIndex value() const { return _entry.value(); }
int32_t weight() const { return _entry.weight(); }
void next() {
if (_cur != _end) {
merge();
} else {
_valid = false;
}
}
};
template <typename WeightedIndex>
void
ActualChangeComputer<WeightedIndex>::compute(const WeightedIndex * entriesNew, size_t szNew,
const WeightedIndex * entriesOld, size_t szOld,
AlwaysWeightedIndexVector & added,
AlwaysWeightedIndexVector & changed,
AlwaysWeightedIndexVector & removed)
{
copyEntries(_newEntries, entriesNew, szNew);
copyEntries(_oldEntries, entriesOld, szOld);
MergeDupIterator<WeightedIndex> oldIt(_oldEntries);
MergeDupIterator<WeightedIndex> newIt(_newEntries);
while (newIt.valid() && oldIt.valid()) {
if (newIt.value() == oldIt.value()) {
if (newIt.weight() != oldIt.weight()) {
changed.push_back(newIt.entry());
}
newIt.next();
oldIt.next();
} else if (newIt.value() < oldIt.value()) {
added.push_back(newIt.entry());
newIt.next();
} else {
removed.push_back(oldIt.entry());
oldIt.next();
}
}
while (newIt.valid()) {
added.push_back(newIt.entry());
newIt.next();
}
while (oldIt.valid()) {
removed.push_back(oldIt.entry());
oldIt.next();
}
}
template <typename WeightedIndex, typename PostingMap>
template <typename MultivalueMapping>
PostingMap
PostingChangeComputerT<WeightedIndex, PostingMap>::
compute(const MultivalueMapping & mvm, const DocIndices & docIndices,
const EnumStoreComparator & compare, const EnumIndexMapper & mapper)
{
typedef ActualChangeComputer<WeightedIndex> AC;
AC actualChange(compare, mapper);
typename AC::AlwaysWeightedIndexVector added, changed, removed;
PostingMap changePost;
// generate add postings and remove postings
for (const auto & docIndex : docIndices) {
vespalib::ConstArrayRef<WeightedIndex> oldIndices(mvm.get(docIndex.first));
added.clear(), changed.clear(), removed.clear();
actualChange.compute(&docIndex.second[0], docIndex.second.size(), &oldIndices[0], oldIndices.size(),
added, changed, removed);
for (const auto & wi : added) {
changePost[EnumPostingPair(wi.value(), &compare)].add(docIndex.first, wi.weight());
}
for (const auto & wi : removed) {
changePost[EnumPostingPair(wi.value(), &compare)].remove(docIndex.first);
}
for (const auto & wi : changed) {
changePost[EnumPostingPair(wi.value(), &compare)].remove(docIndex.first).add(docIndex.first, wi.weight());
}
}
return changePost;
}
template class PostingChange<AttributePosting>;
template class PostingChange<AttributeWeightPosting>;
typedef PostingChange<btree::BTreeKeyData<unsigned int, int> > WeightedPostingChange;
typedef std::map<EnumPostingPair, WeightedPostingChange> WeightedPostingChangeMap;
typedef EnumStoreBase::Index EnumIndex;
typedef multivalue::WeightedValue<EnumIndex> WeightedIndex;
typedef multivalue::Value<EnumIndex> ValueIndex;
typedef MultiValueMappingT<WeightedIndex, multivalue::Index32> NormalWeightedMultiValueMapping;
typedef MultiValueMappingT<WeightedIndex, multivalue::Index64> HugeWeightedMultiValueMapping;
typedef MultiValueMappingT<ValueIndex, multivalue::Index32> NormalValueMultiValueMapping;
typedef MultiValueMappingT<ValueIndex, multivalue::Index64> HugeValueMultiValueMapping;
typedef std::vector<std::pair<uint32_t, std::vector<WeightedIndex>>> DocIndicesWeighted;
typedef std::vector<std::pair<uint32_t, std::vector<ValueIndex>>> DocIndicesValue;
template WeightedPostingChangeMap PostingChangeComputerT<WeightedIndex, WeightedPostingChangeMap>
::compute<NormalWeightedMultiValueMapping>(const NormalWeightedMultiValueMapping &,
const DocIndicesWeighted &,
const EnumStoreComparator &,
const EnumIndexMapper &);
template WeightedPostingChangeMap PostingChangeComputerT<WeightedIndex, WeightedPostingChangeMap>
::compute<HugeWeightedMultiValueMapping>(const HugeWeightedMultiValueMapping &,
const DocIndicesWeighted &,
const EnumStoreComparator &,
const EnumIndexMapper &);
template WeightedPostingChangeMap PostingChangeComputerT<ValueIndex, WeightedPostingChangeMap>
::compute<NormalValueMultiValueMapping>(const NormalValueMultiValueMapping &,
const DocIndicesValue &,
const EnumStoreComparator &,
const EnumIndexMapper &);
template WeightedPostingChangeMap PostingChangeComputerT<ValueIndex, WeightedPostingChangeMap>
::compute<HugeValueMultiValueMapping>(const HugeValueMultiValueMapping &,
const DocIndicesValue &,
const EnumStoreComparator &,
const EnumIndexMapper &);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 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 "chrome/renderer/paint_aggregator.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
// ----------------------------------------------------------------------------
// ALGORITHM NOTES
//
// We attempt to maintain a scroll rect in the presence of invalidations that
// are contained within the scroll rect. If an invalidation crosses a scroll
// rect, then we just treat the scroll rect as an invalidation rect.
//
// For invalidations performed prior to scrolling and contained within the
// scroll rect, we offset the invalidation rects to account for the fact that
// the consumer will perform scrolling before painting.
//
// We only support scrolling along one axis at a time. A diagonal scroll will
// therefore be treated as an invalidation.
// ----------------------------------------------------------------------------
// If the combined area of paint rects contained within the scroll rect grows
// too large, then we might as well just treat the scroll rect as a paint rect.
// This constant sets the max ratio of paint rect area to scroll rect area that
// we will tolerate before dograding the scroll into a repaint.
static const float kMaxRedundantPaintToScrollArea = 0.8f;
// The maximum number of paint rects. If we exceed this limit, then we'll
// start combining paint rects (see CombinePaintRects). This limiting is
// important since the WebKit code associated with deciding what to paint given
// a paint rect can be significant.
static const size_t kMaxPaintRects = 5;
// If the combined area of paint rects divided by the area of the union of all
// paint rects exceeds this threshold, then we will combine the paint rects.
static const float kMaxPaintRectsAreaRatio = 0.3f;
PaintAggregator::PendingUpdate::PendingUpdate() {}
PaintAggregator::PendingUpdate::~PendingUpdate() {}
gfx::Rect PaintAggregator::PendingUpdate::GetScrollDamage() const {
// Should only be scrolling in one direction at a time.
DCHECK(!(scroll_delta.x() && scroll_delta.y()));
gfx::Rect damaged_rect;
// Compute the region we will expose by scrolling, and paint that into a
// shared memory section.
if (scroll_delta.x()) {
int dx = scroll_delta.x();
damaged_rect.set_y(scroll_rect.y());
damaged_rect.set_height(scroll_rect.height());
if (dx > 0) {
damaged_rect.set_x(scroll_rect.x());
damaged_rect.set_width(dx);
} else {
damaged_rect.set_x(scroll_rect.right() + dx);
damaged_rect.set_width(-dx);
}
} else {
int dy = scroll_delta.y();
damaged_rect.set_x(scroll_rect.x());
damaged_rect.set_width(scroll_rect.width());
if (dy > 0) {
damaged_rect.set_y(scroll_rect.y());
damaged_rect.set_height(dy);
} else {
damaged_rect.set_y(scroll_rect.bottom() + dy);
damaged_rect.set_height(-dy);
}
}
// In case the scroll offset exceeds the width/height of the scroll rect
return scroll_rect.Intersect(damaged_rect);
}
gfx::Rect PaintAggregator::PendingUpdate::GetPaintBounds() const {
gfx::Rect bounds;
for (size_t i = 0; i < paint_rects.size(); ++i)
bounds = bounds.Union(paint_rects[i]);
return bounds;
}
bool PaintAggregator::HasPendingUpdate() const {
return !update_.scroll_rect.IsEmpty() || !update_.paint_rects.empty();
}
void PaintAggregator::ClearPendingUpdate() {
update_ = PendingUpdate();
}
void PaintAggregator::PopPendingUpdate(PendingUpdate* update) {
// Combine paint rects if their combined area is not sufficiently less than
// the area of the union of all paint rects. We skip this if there is a
// scroll rect since scrolling benefits from smaller paint rects.
if (update_.scroll_rect.IsEmpty() && update_.paint_rects.size() > 1) {
int paint_area = 0;
gfx::Rect union_rect;
for (size_t i = 0; i < update_.paint_rects.size(); ++i) {
paint_area += update_.paint_rects[i].size().GetArea();
union_rect = union_rect.Union(update_.paint_rects[i]);
}
int union_area = union_rect.size().GetArea();
if (float(paint_area) / float(union_area) > kMaxPaintRectsAreaRatio)
CombinePaintRects();
}
*update = update_;
ClearPendingUpdate();
}
void PaintAggregator::InvalidateRect(const gfx::Rect& rect) {
// Combine overlapping paints using smallest bounding box.
for (size_t i = 0; i < update_.paint_rects.size(); ++i) {
const gfx::Rect& existing_rect = update_.paint_rects[i];
if (existing_rect.Contains(rect)) // Optimize out redundancy.
return;
if (rect.Intersects(existing_rect) || rect.SharesEdgeWith(existing_rect)) {
// Re-invalidate in case the union intersects other paint rects.
gfx::Rect combined_rect = existing_rect.Union(rect);
update_.paint_rects.erase(update_.paint_rects.begin() + i);
InvalidateRect(combined_rect);
return;
}
}
// Add a non-overlapping paint.
update_.paint_rects.push_back(rect);
// If the new paint overlaps with a scroll, then it forces an invalidation of
// the scroll. If the new paint is contained by a scroll, then trim off the
// scroll damage to avoid redundant painting.
if (!update_.scroll_rect.IsEmpty()) {
if (ShouldInvalidateScrollRect(rect)) {
InvalidateScrollRect();
} else if (update_.scroll_rect.Contains(rect)) {
update_.paint_rects[update_.paint_rects.size() - 1] =
rect.Subtract(update_.GetScrollDamage());
if (update_.paint_rects[update_.paint_rects.size() - 1].IsEmpty())
update_.paint_rects.erase(update_.paint_rects.end() - 1);
}
}
if (update_.paint_rects.size() > kMaxPaintRects)
CombinePaintRects();
// Track how large the paint_rects vector grows during an invalidation
// sequence. Note: A subsequent invalidation may end up being combined
// with all existing paints, which means that tracking the size of
// paint_rects at the time when PopPendingUpdate() is called may mask
// certain performance problems.
HISTOGRAM_COUNTS_100("MPArch.RW_IntermediatePaintRectCount",
update_.paint_rects.size());
}
void PaintAggregator::ScrollRect(int dx, int dy, const gfx::Rect& clip_rect) {
// We only support scrolling along one axis at a time.
if (dx != 0 && dy != 0) {
InvalidateRect(clip_rect);
return;
}
// We can only scroll one rect at a time.
if (!update_.scroll_rect.IsEmpty() &&
!update_.scroll_rect.Equals(clip_rect)) {
InvalidateRect(clip_rect);
return;
}
// Again, we only support scrolling along one axis at a time. Make sure this
// update doesn't scroll on a different axis than any existing one.
if ((dx && update_.scroll_delta.y()) || (dy && update_.scroll_delta.x())) {
InvalidateRect(clip_rect);
return;
}
// The scroll rect is new or isn't changing (though the scroll amount may
// be changing).
update_.scroll_rect = clip_rect;
update_.scroll_delta.Offset(dx, dy);
// We might have just wiped out a pre-existing scroll.
if (update_.scroll_delta == gfx::Point()) {
update_.scroll_rect = gfx::Rect();
return;
}
// Adjust any contained paint rects and check for any overlapping paints.
for (size_t i = 0; i < update_.paint_rects.size(); ++i) {
if (update_.scroll_rect.Contains(update_.paint_rects[i])) {
update_.paint_rects[i] = ScrollPaintRect(update_.paint_rects[i], dx, dy);
// The rect may have been scrolled out of view.
if (update_.paint_rects[i].IsEmpty()) {
update_.paint_rects.erase(update_.paint_rects.begin() + i);
i--;
}
} else if (update_.scroll_rect.Intersects(update_.paint_rects[i])) {
InvalidateScrollRect();
return;
}
}
// If the new scroll overlaps too much with contained paint rects, then force
// an invalidation of the scroll.
if (ShouldInvalidateScrollRect(gfx::Rect()))
InvalidateScrollRect();
}
gfx::Rect PaintAggregator::ScrollPaintRect(const gfx::Rect& paint_rect,
int dx, int dy) const {
gfx::Rect result = paint_rect;
result.Offset(dx, dy);
result = update_.scroll_rect.Intersect(result);
// Subtract out the scroll damage rect to avoid redundant painting.
return result.Subtract(update_.GetScrollDamage());
}
bool PaintAggregator::ShouldInvalidateScrollRect(const gfx::Rect& rect) const {
if (!rect.IsEmpty()) {
if (!update_.scroll_rect.Intersects(rect))
return false;
if (!update_.scroll_rect.Contains(rect))
return true;
}
// Check if the combined area of all contained paint rects plus this new
// rect comes too close to the area of the scroll_rect. If so, then we
// might as well invalidate the scroll rect.
int paint_area = rect.size().GetArea();
for (size_t i = 0; i < update_.paint_rects.size(); ++i) {
const gfx::Rect& existing_rect = update_.paint_rects[i];
if (update_.scroll_rect.Contains(existing_rect))
paint_area += existing_rect.size().GetArea();
}
int scroll_area = update_.scroll_rect.size().GetArea();
if (float(paint_area) / float(scroll_area) > kMaxRedundantPaintToScrollArea)
return true;
return false;
}
void PaintAggregator::InvalidateScrollRect() {
gfx::Rect scroll_rect = update_.scroll_rect;
update_.scroll_rect = gfx::Rect();
update_.scroll_delta = gfx::Point();
InvalidateRect(scroll_rect);
}
void PaintAggregator::CombinePaintRects() {
// Combine paint rects do to at most two rects: one inside the scroll_rect
// and one outside the scroll_rect. If there is no scroll_rect, then just
// use the smallest bounding box for all paint rects.
//
// NOTE: This is a fairly simple algorithm. We could get fancier by only
// combining two rects to get us under the kMaxPaintRects limit, but if we
// reach this method then it means we're hitting a rare case, so there's no
// need to over-optimize it.
//
if (update_.scroll_rect.IsEmpty()) {
gfx::Rect bounds = update_.GetPaintBounds();
update_.paint_rects.clear();
update_.paint_rects.push_back(bounds);
} else {
gfx::Rect inner, outer;
for (size_t i = 0; i < update_.paint_rects.size(); ++i) {
const gfx::Rect& existing_rect = update_.paint_rects[i];
if (update_.scroll_rect.Contains(existing_rect)) {
inner = inner.Union(existing_rect);
} else {
outer = outer.Union(existing_rect);
}
}
update_.paint_rects.clear();
update_.paint_rects.push_back(inner);
update_.paint_rects.push_back(outer);
}
}
<commit_msg>Boldly increase the paint aggregation threshold. It turns out my previous value of 0.5 worked OK and I read the PLT graphs wrong. If this introduces a PLT regression, the number should be changed back to 0.5.<commit_after>// Copyright (c) 2009 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 "chrome/renderer/paint_aggregator.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
// ----------------------------------------------------------------------------
// ALGORITHM NOTES
//
// We attempt to maintain a scroll rect in the presence of invalidations that
// are contained within the scroll rect. If an invalidation crosses a scroll
// rect, then we just treat the scroll rect as an invalidation rect.
//
// For invalidations performed prior to scrolling and contained within the
// scroll rect, we offset the invalidation rects to account for the fact that
// the consumer will perform scrolling before painting.
//
// We only support scrolling along one axis at a time. A diagonal scroll will
// therefore be treated as an invalidation.
// ----------------------------------------------------------------------------
// If the combined area of paint rects contained within the scroll rect grows
// too large, then we might as well just treat the scroll rect as a paint rect.
// This constant sets the max ratio of paint rect area to scroll rect area that
// we will tolerate before dograding the scroll into a repaint.
static const float kMaxRedundantPaintToScrollArea = 0.8f;
// The maximum number of paint rects. If we exceed this limit, then we'll
// start combining paint rects (see CombinePaintRects). This limiting is
// important since the WebKit code associated with deciding what to paint given
// a paint rect can be significant.
static const size_t kMaxPaintRects = 5;
// If the combined area of paint rects divided by the area of the union of all
// paint rects exceeds this threshold, then we will combine the paint rects.
static const float kMaxPaintRectsAreaRatio = 0.7f;
PaintAggregator::PendingUpdate::PendingUpdate() {}
PaintAggregator::PendingUpdate::~PendingUpdate() {}
gfx::Rect PaintAggregator::PendingUpdate::GetScrollDamage() const {
// Should only be scrolling in one direction at a time.
DCHECK(!(scroll_delta.x() && scroll_delta.y()));
gfx::Rect damaged_rect;
// Compute the region we will expose by scrolling, and paint that into a
// shared memory section.
if (scroll_delta.x()) {
int dx = scroll_delta.x();
damaged_rect.set_y(scroll_rect.y());
damaged_rect.set_height(scroll_rect.height());
if (dx > 0) {
damaged_rect.set_x(scroll_rect.x());
damaged_rect.set_width(dx);
} else {
damaged_rect.set_x(scroll_rect.right() + dx);
damaged_rect.set_width(-dx);
}
} else {
int dy = scroll_delta.y();
damaged_rect.set_x(scroll_rect.x());
damaged_rect.set_width(scroll_rect.width());
if (dy > 0) {
damaged_rect.set_y(scroll_rect.y());
damaged_rect.set_height(dy);
} else {
damaged_rect.set_y(scroll_rect.bottom() + dy);
damaged_rect.set_height(-dy);
}
}
// In case the scroll offset exceeds the width/height of the scroll rect
return scroll_rect.Intersect(damaged_rect);
}
gfx::Rect PaintAggregator::PendingUpdate::GetPaintBounds() const {
gfx::Rect bounds;
for (size_t i = 0; i < paint_rects.size(); ++i)
bounds = bounds.Union(paint_rects[i]);
return bounds;
}
bool PaintAggregator::HasPendingUpdate() const {
return !update_.scroll_rect.IsEmpty() || !update_.paint_rects.empty();
}
void PaintAggregator::ClearPendingUpdate() {
update_ = PendingUpdate();
}
void PaintAggregator::PopPendingUpdate(PendingUpdate* update) {
// Combine paint rects if their combined area is not sufficiently less than
// the area of the union of all paint rects. We skip this if there is a
// scroll rect since scrolling benefits from smaller paint rects.
if (update_.scroll_rect.IsEmpty() && update_.paint_rects.size() > 1) {
int paint_area = 0;
gfx::Rect union_rect;
for (size_t i = 0; i < update_.paint_rects.size(); ++i) {
paint_area += update_.paint_rects[i].size().GetArea();
union_rect = union_rect.Union(update_.paint_rects[i]);
}
int union_area = union_rect.size().GetArea();
if (float(paint_area) / float(union_area) > kMaxPaintRectsAreaRatio)
CombinePaintRects();
}
*update = update_;
ClearPendingUpdate();
}
void PaintAggregator::InvalidateRect(const gfx::Rect& rect) {
// Combine overlapping paints using smallest bounding box.
for (size_t i = 0; i < update_.paint_rects.size(); ++i) {
const gfx::Rect& existing_rect = update_.paint_rects[i];
if (existing_rect.Contains(rect)) // Optimize out redundancy.
return;
if (rect.Intersects(existing_rect) || rect.SharesEdgeWith(existing_rect)) {
// Re-invalidate in case the union intersects other paint rects.
gfx::Rect combined_rect = existing_rect.Union(rect);
update_.paint_rects.erase(update_.paint_rects.begin() + i);
InvalidateRect(combined_rect);
return;
}
}
// Add a non-overlapping paint.
update_.paint_rects.push_back(rect);
// If the new paint overlaps with a scroll, then it forces an invalidation of
// the scroll. If the new paint is contained by a scroll, then trim off the
// scroll damage to avoid redundant painting.
if (!update_.scroll_rect.IsEmpty()) {
if (ShouldInvalidateScrollRect(rect)) {
InvalidateScrollRect();
} else if (update_.scroll_rect.Contains(rect)) {
update_.paint_rects[update_.paint_rects.size() - 1] =
rect.Subtract(update_.GetScrollDamage());
if (update_.paint_rects[update_.paint_rects.size() - 1].IsEmpty())
update_.paint_rects.erase(update_.paint_rects.end() - 1);
}
}
if (update_.paint_rects.size() > kMaxPaintRects)
CombinePaintRects();
// Track how large the paint_rects vector grows during an invalidation
// sequence. Note: A subsequent invalidation may end up being combined
// with all existing paints, which means that tracking the size of
// paint_rects at the time when PopPendingUpdate() is called may mask
// certain performance problems.
HISTOGRAM_COUNTS_100("MPArch.RW_IntermediatePaintRectCount",
update_.paint_rects.size());
}
void PaintAggregator::ScrollRect(int dx, int dy, const gfx::Rect& clip_rect) {
// We only support scrolling along one axis at a time.
if (dx != 0 && dy != 0) {
InvalidateRect(clip_rect);
return;
}
// We can only scroll one rect at a time.
if (!update_.scroll_rect.IsEmpty() &&
!update_.scroll_rect.Equals(clip_rect)) {
InvalidateRect(clip_rect);
return;
}
// Again, we only support scrolling along one axis at a time. Make sure this
// update doesn't scroll on a different axis than any existing one.
if ((dx && update_.scroll_delta.y()) || (dy && update_.scroll_delta.x())) {
InvalidateRect(clip_rect);
return;
}
// The scroll rect is new or isn't changing (though the scroll amount may
// be changing).
update_.scroll_rect = clip_rect;
update_.scroll_delta.Offset(dx, dy);
// We might have just wiped out a pre-existing scroll.
if (update_.scroll_delta == gfx::Point()) {
update_.scroll_rect = gfx::Rect();
return;
}
// Adjust any contained paint rects and check for any overlapping paints.
for (size_t i = 0; i < update_.paint_rects.size(); ++i) {
if (update_.scroll_rect.Contains(update_.paint_rects[i])) {
update_.paint_rects[i] = ScrollPaintRect(update_.paint_rects[i], dx, dy);
// The rect may have been scrolled out of view.
if (update_.paint_rects[i].IsEmpty()) {
update_.paint_rects.erase(update_.paint_rects.begin() + i);
i--;
}
} else if (update_.scroll_rect.Intersects(update_.paint_rects[i])) {
InvalidateScrollRect();
return;
}
}
// If the new scroll overlaps too much with contained paint rects, then force
// an invalidation of the scroll.
if (ShouldInvalidateScrollRect(gfx::Rect()))
InvalidateScrollRect();
}
gfx::Rect PaintAggregator::ScrollPaintRect(const gfx::Rect& paint_rect,
int dx, int dy) const {
gfx::Rect result = paint_rect;
result.Offset(dx, dy);
result = update_.scroll_rect.Intersect(result);
// Subtract out the scroll damage rect to avoid redundant painting.
return result.Subtract(update_.GetScrollDamage());
}
bool PaintAggregator::ShouldInvalidateScrollRect(const gfx::Rect& rect) const {
if (!rect.IsEmpty()) {
if (!update_.scroll_rect.Intersects(rect))
return false;
if (!update_.scroll_rect.Contains(rect))
return true;
}
// Check if the combined area of all contained paint rects plus this new
// rect comes too close to the area of the scroll_rect. If so, then we
// might as well invalidate the scroll rect.
int paint_area = rect.size().GetArea();
for (size_t i = 0; i < update_.paint_rects.size(); ++i) {
const gfx::Rect& existing_rect = update_.paint_rects[i];
if (update_.scroll_rect.Contains(existing_rect))
paint_area += existing_rect.size().GetArea();
}
int scroll_area = update_.scroll_rect.size().GetArea();
if (float(paint_area) / float(scroll_area) > kMaxRedundantPaintToScrollArea)
return true;
return false;
}
void PaintAggregator::InvalidateScrollRect() {
gfx::Rect scroll_rect = update_.scroll_rect;
update_.scroll_rect = gfx::Rect();
update_.scroll_delta = gfx::Point();
InvalidateRect(scroll_rect);
}
void PaintAggregator::CombinePaintRects() {
// Combine paint rects do to at most two rects: one inside the scroll_rect
// and one outside the scroll_rect. If there is no scroll_rect, then just
// use the smallest bounding box for all paint rects.
//
// NOTE: This is a fairly simple algorithm. We could get fancier by only
// combining two rects to get us under the kMaxPaintRects limit, but if we
// reach this method then it means we're hitting a rare case, so there's no
// need to over-optimize it.
//
if (update_.scroll_rect.IsEmpty()) {
gfx::Rect bounds = update_.GetPaintBounds();
update_.paint_rects.clear();
update_.paint_rects.push_back(bounds);
} else {
gfx::Rect inner, outer;
for (size_t i = 0; i < update_.paint_rects.size(); ++i) {
const gfx::Rect& existing_rect = update_.paint_rects[i];
if (update_.scroll_rect.Contains(existing_rect)) {
inner = inner.Union(existing_rect);
} else {
outer = outer.Union(existing_rect);
}
}
update_.paint_rects.clear();
update_.paint_rects.push_back(inner);
update_.paint_rects.push_back(outer);
}
}
<|endoftext|>
|
<commit_before>/* OpenSceneGraph example, osgtexture3D.
*
* 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 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 <osg/Node>
#include <osg/Geometry>
#include <osg/Notify>
#include <osg/Texture1D>
#include <osg/Texture2D>
#include <osg/Texture3D>
#include <osg/TextureRectangle>
#include <osg/ImageSequence>
#include <osg/Geode>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgViewer/Viewer>
#include <iostream>
//
// A simple demo demonstrating how to set on an animated texture using an osg::ImageSequence
//
osg::StateSet* createState(osg::ArgumentParser& arguments)
{
osg::ref_ptr<osg::ImageSequence> imageSequence = new osg::ImageSequence;
if (arguments.argc()>1)
{
for(unsigned int i=1; i<arguments.argc(); ++i)
{
osg::ref_ptr<osg::Image> image = osgDB::readImageFile(arguments[i]);
if (image.valid())
{
imageSequence->addImage(image.get());
}
}
imageSequence->setLength(float(imageSequence->getImages().size())*0.1f);
}
else
{
imageSequence->setLength(4.0);
imageSequence->addImage(osgDB::readImageFile("Cubemap_axis/posx.png"));
imageSequence->addImage(osgDB::readImageFile("Cubemap_axis/negx.png"));
imageSequence->addImage(osgDB::readImageFile("Cubemap_axis/posy.png"));
imageSequence->addImage(osgDB::readImageFile("Cubemap_axis/negy.png"));
imageSequence->addImage(osgDB::readImageFile("Cubemap_axis/posz.png"));
imageSequence->addImage(osgDB::readImageFile("Cubemap_axis/negz.png"));
}
// start the image sequence playing
imageSequence->play();
#if 1
osg::Texture2D* texture = new osg::Texture2D;
texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
texture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
texture->setWrap(osg::Texture::WRAP_R,osg::Texture::REPEAT);
texture->setResizeNonPowerOfTwoHint(false);
texture->setImage(imageSequence.get());
//texture->setTextureSize(512,512);
//texture->setUpdateCallback(new osg::ImageSequence::UpdateCallback);
#else
osg::TextureRectangle* texture = new osg::TextureRectangle;
texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
texture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
texture->setWrap(osg::Texture::WRAP_R,osg::Texture::REPEAT);
// texture->setResizeNonPowerOfTwoHint(false);
texture->setImage(imageSequence.get());
//texture->setTextureSize(512,512);
//texture->setUpdateCallback(new osg::ImageSequence::UpdateCallback);
#endif
// create the StateSet to store the texture data
osg::StateSet* stateset = new osg::StateSet;
stateset->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
return stateset;
}
osg::Node* createModel(osg::ArgumentParser& arguments)
{
// create the geometry of the model, just a simple 2d quad right now.
osg::Geode* geode = new osg::Geode;
geode->addDrawable(osg::createTexturedQuadGeometry(osg::Vec3(0.0f,0.0f,0.0), osg::Vec3(1.0f,0.0f,0.0), osg::Vec3(0.0f,0.0f,1.0f)));
geode->setStateSet(createState(arguments));
return geode;
}
osg::ImageStream* s_imageStream = 0;
class MovieEventHandler : public osgGA::GUIEventHandler
{
public:
MovieEventHandler():_trackMouse(false),_playToggle(true) {}
void setMouseTracking(bool track) { _trackMouse = track; }
bool getMouseTracking() const { return _trackMouse; }
void set(osg::Node* node);
virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa, osg::Object*, osg::NodeVisitor* nv);
virtual void getUsage(osg::ApplicationUsage& usage) const;
typedef std::vector< osg::observer_ptr<osg::ImageStream> > ImageStreamList;
protected:
virtual ~MovieEventHandler() {}
class FindImageStreamsVisitor : public osg::NodeVisitor
{
public:
FindImageStreamsVisitor(ImageStreamList& imageStreamList):
_imageStreamList(imageStreamList) {}
virtual void apply(osg::Geode& geode)
{
apply(geode.getStateSet());
for(unsigned int i=0;i<geode.getNumDrawables();++i)
{
apply(geode.getDrawable(i)->getStateSet());
}
traverse(geode);
}
virtual void apply(osg::Node& node)
{
apply(node.getStateSet());
traverse(node);
}
inline void apply(osg::StateSet* stateset)
{
if (!stateset) return;
osg::StateAttribute* attr = stateset->getTextureAttribute(0,osg::StateAttribute::TEXTURE);
if (attr)
{
osg::Texture2D* texture2D = dynamic_cast<osg::Texture2D*>(attr);
if (texture2D) apply(dynamic_cast<osg::ImageStream*>(texture2D->getImage()));
osg::TextureRectangle* textureRec = dynamic_cast<osg::TextureRectangle*>(attr);
if (textureRec) apply(dynamic_cast<osg::ImageStream*>(textureRec->getImage()));
}
}
inline void apply(osg::ImageStream* imagestream)
{
if (imagestream)
{
_imageStreamList.push_back(imagestream);
s_imageStream = imagestream;
}
}
ImageStreamList& _imageStreamList;
};
bool _playToggle;
bool _trackMouse;
ImageStreamList _imageStreamList;
};
void MovieEventHandler::set(osg::Node* node)
{
_imageStreamList.clear();
if (node)
{
FindImageStreamsVisitor fisv(_imageStreamList);
node->accept(fisv);
}
}
bool MovieEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa, osg::Object*, osg::NodeVisitor* nv)
{
switch(ea.getEventType())
{
case(osgGA::GUIEventAdapter::KEYDOWN):
{
if (ea.getKey()=='p')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
if ((*itr)->getStatus()==osg::ImageStream::PLAYING)
{
// playing, so pause
std::cout<<"Pause"<<std::endl;
(*itr)->pause();
}
else
{
// playing, so pause
std::cout<<"Play"<<std::endl;
(*itr)->play();
}
}
return true;
}
else if (ea.getKey()=='r')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
std::cout<<"Restart"<<std::endl;
(*itr)->rewind();
}
return true;
}
else if (ea.getKey()=='L')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
if ( (*itr)->getLoopingMode() == osg::ImageStream::LOOPING)
{
std::cout<<"Toggle Looping Off"<<std::endl;
(*itr)->setLoopingMode( osg::ImageStream::NO_LOOPING );
}
else
{
std::cout<<"Toggle Looping On"<<std::endl;
(*itr)->setLoopingMode( osg::ImageStream::LOOPING );
}
}
return true;
}
return false;
}
default:
return false;
}
return false;
}
void MovieEventHandler::getUsage(osg::ApplicationUsage& usage) const
{
usage.addKeyboardMouseBinding("p","Play/Pause movie");
usage.addKeyboardMouseBinding("r","Restart movie");
usage.addKeyboardMouseBinding("l","Toggle looping of movie");
}
int main(int argc, char **argv)
{
osg::ArgumentParser arguments(&argc,argv);
// construct the viewer.
osgViewer::Viewer viewer(arguments);
std::string filename;
arguments.read("-o",filename);
// create a model from the images and pass it to the viewer.
viewer.setSceneData(createModel(arguments));
// pass the model to the MovieEventHandler so it can pick out ImageStream's to manipulate.
MovieEventHandler* meh = new MovieEventHandler();
meh->set( viewer.getSceneData() );
viewer.addEventHandler( meh );
if (!filename.empty())
{
osgDB::writeNodeFile(*viewer.getSceneData(),filename);
}
return viewer.run();
}
<commit_msg>Added stats handler<commit_after>/* OpenSceneGraph example, osgtexture3D.
*
* 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 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 <osg/Node>
#include <osg/Geometry>
#include <osg/Notify>
#include <osg/Texture1D>
#include <osg/Texture2D>
#include <osg/Texture3D>
#include <osg/TextureRectangle>
#include <osg/ImageSequence>
#include <osg/Geode>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <iostream>
//
// A simple demo demonstrating how to set on an animated texture using an osg::ImageSequence
//
osg::StateSet* createState(osg::ArgumentParser& arguments)
{
osg::ref_ptr<osg::ImageSequence> imageSequence = new osg::ImageSequence;
if (arguments.argc()>1)
{
for(unsigned int i=1; i<arguments.argc(); ++i)
{
osg::ref_ptr<osg::Image> image = osgDB::readImageFile(arguments[i]);
if (image.valid())
{
imageSequence->addImage(image.get());
}
}
imageSequence->setLength(float(imageSequence->getImages().size())*0.1f);
}
else
{
imageSequence->setLength(4.0);
imageSequence->addImage(osgDB::readImageFile("Cubemap_axis/posx.png"));
imageSequence->addImage(osgDB::readImageFile("Cubemap_axis/negx.png"));
imageSequence->addImage(osgDB::readImageFile("Cubemap_axis/posy.png"));
imageSequence->addImage(osgDB::readImageFile("Cubemap_axis/negy.png"));
imageSequence->addImage(osgDB::readImageFile("Cubemap_axis/posz.png"));
imageSequence->addImage(osgDB::readImageFile("Cubemap_axis/negz.png"));
}
// start the image sequence playing
imageSequence->play();
#if 1
osg::Texture2D* texture = new osg::Texture2D;
texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
texture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
texture->setWrap(osg::Texture::WRAP_R,osg::Texture::REPEAT);
texture->setResizeNonPowerOfTwoHint(false);
texture->setImage(imageSequence.get());
//texture->setTextureSize(512,512);
//texture->setUpdateCallback(new osg::ImageSequence::UpdateCallback);
#else
osg::TextureRectangle* texture = new osg::TextureRectangle;
texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
texture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
texture->setWrap(osg::Texture::WRAP_R,osg::Texture::REPEAT);
// texture->setResizeNonPowerOfTwoHint(false);
texture->setImage(imageSequence.get());
//texture->setTextureSize(512,512);
//texture->setUpdateCallback(new osg::ImageSequence::UpdateCallback);
#endif
// create the StateSet to store the texture data
osg::StateSet* stateset = new osg::StateSet;
stateset->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
return stateset;
}
osg::Node* createModel(osg::ArgumentParser& arguments)
{
// create the geometry of the model, just a simple 2d quad right now.
osg::Geode* geode = new osg::Geode;
geode->addDrawable(osg::createTexturedQuadGeometry(osg::Vec3(0.0f,0.0f,0.0), osg::Vec3(1.0f,0.0f,0.0), osg::Vec3(0.0f,0.0f,1.0f)));
geode->setStateSet(createState(arguments));
return geode;
}
osg::ImageStream* s_imageStream = 0;
class MovieEventHandler : public osgGA::GUIEventHandler
{
public:
MovieEventHandler():_trackMouse(false),_playToggle(true) {}
void setMouseTracking(bool track) { _trackMouse = track; }
bool getMouseTracking() const { return _trackMouse; }
void set(osg::Node* node);
virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa, osg::Object*, osg::NodeVisitor* nv);
virtual void getUsage(osg::ApplicationUsage& usage) const;
typedef std::vector< osg::observer_ptr<osg::ImageStream> > ImageStreamList;
protected:
virtual ~MovieEventHandler() {}
class FindImageStreamsVisitor : public osg::NodeVisitor
{
public:
FindImageStreamsVisitor(ImageStreamList& imageStreamList):
_imageStreamList(imageStreamList) {}
virtual void apply(osg::Geode& geode)
{
apply(geode.getStateSet());
for(unsigned int i=0;i<geode.getNumDrawables();++i)
{
apply(geode.getDrawable(i)->getStateSet());
}
traverse(geode);
}
virtual void apply(osg::Node& node)
{
apply(node.getStateSet());
traverse(node);
}
inline void apply(osg::StateSet* stateset)
{
if (!stateset) return;
osg::StateAttribute* attr = stateset->getTextureAttribute(0,osg::StateAttribute::TEXTURE);
if (attr)
{
osg::Texture2D* texture2D = dynamic_cast<osg::Texture2D*>(attr);
if (texture2D) apply(dynamic_cast<osg::ImageStream*>(texture2D->getImage()));
osg::TextureRectangle* textureRec = dynamic_cast<osg::TextureRectangle*>(attr);
if (textureRec) apply(dynamic_cast<osg::ImageStream*>(textureRec->getImage()));
}
}
inline void apply(osg::ImageStream* imagestream)
{
if (imagestream)
{
_imageStreamList.push_back(imagestream);
s_imageStream = imagestream;
}
}
ImageStreamList& _imageStreamList;
};
bool _playToggle;
bool _trackMouse;
ImageStreamList _imageStreamList;
};
void MovieEventHandler::set(osg::Node* node)
{
_imageStreamList.clear();
if (node)
{
FindImageStreamsVisitor fisv(_imageStreamList);
node->accept(fisv);
}
}
bool MovieEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa, osg::Object*, osg::NodeVisitor* nv)
{
switch(ea.getEventType())
{
case(osgGA::GUIEventAdapter::KEYDOWN):
{
if (ea.getKey()=='p')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
if ((*itr)->getStatus()==osg::ImageStream::PLAYING)
{
// playing, so pause
std::cout<<"Pause"<<std::endl;
(*itr)->pause();
}
else
{
// playing, so pause
std::cout<<"Play"<<std::endl;
(*itr)->play();
}
}
return true;
}
else if (ea.getKey()=='r')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
std::cout<<"Restart"<<std::endl;
(*itr)->rewind();
}
return true;
}
else if (ea.getKey()=='L')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
if ( (*itr)->getLoopingMode() == osg::ImageStream::LOOPING)
{
std::cout<<"Toggle Looping Off"<<std::endl;
(*itr)->setLoopingMode( osg::ImageStream::NO_LOOPING );
}
else
{
std::cout<<"Toggle Looping On"<<std::endl;
(*itr)->setLoopingMode( osg::ImageStream::LOOPING );
}
}
return true;
}
return false;
}
default:
return false;
}
return false;
}
void MovieEventHandler::getUsage(osg::ApplicationUsage& usage) const
{
usage.addKeyboardMouseBinding("p","Play/Pause movie");
usage.addKeyboardMouseBinding("r","Restart movie");
usage.addKeyboardMouseBinding("l","Toggle looping of movie");
}
int main(int argc, char **argv)
{
osg::ArgumentParser arguments(&argc,argv);
// construct the viewer.
osgViewer::Viewer viewer(arguments);
std::string filename;
arguments.read("-o",filename);
// create a model from the images and pass it to the viewer.
viewer.setSceneData(createModel(arguments));
// pass the model to the MovieEventHandler so it can pick out ImageStream's to manipulate.
MovieEventHandler* meh = new MovieEventHandler();
meh->set( viewer.getSceneData() );
viewer.addEventHandler( meh );
viewer.addEventHandler( new osgViewer::StatsHandler());
if (!filename.empty())
{
osgDB::writeNodeFile(*viewer.getSceneData(),filename);
}
return viewer.run();
}
<|endoftext|>
|
<commit_before>// This is free and unencumbered software released into the public domain.
// For more information, please refer to <http://unlicense.org/>
#include "results_pane.h"
#include "models/base/helper.h"
#include "wx/xrc/xmlres.h"
#include "edit_pane.h"
#include "span.h"
#include "span_analyzer_app.h"
#include "span_analyzer_doc.h"
#include "span_analyzer_view.h"
BEGIN_EVENT_TABLE(ResultsPane, wxPanel)
EVT_CHOICE(XRCID("choice_sagtension_weathercase"), ResultsPane::OnChoiceWeathercase)
EVT_CHOICE(XRCID("choice_sagtension_condition"), ResultsPane::OnChoiceCondition)
END_EVENT_TABLE()
ResultsPane::ResultsPane(wxWindow* parent, SpanAnalyzerView* view) {
// loads dialog from virtual xrc file system
wxXmlResource::Get()->LoadPanel(this, parent, "results_pane");
// saves view reference
view_ = view;
// fills the reloaded condition
wxChoice* choice = XRCCTRL(*parent, "choice_sagtension_condition", wxChoice);
choice->Append("Initial");
choice->Append("Final-Load");
}
ResultsPane::~ResultsPane() {
}
void ResultsPane::Update(wxObject* hint) {
if (hint == nullptr) {
return;
}
// gets weathercases
SpanAnalyzerDoc* doc = (SpanAnalyzerDoc*)view_->GetDocument();
const std::vector<WeatherLoadCase>& weathercases = *doc->weathercases();
wxChoice* choice = nullptr;
wxString str_choice;
// updates sag-tension weathercase choice and selection
choice = XRCCTRL(*view_->GetFrame(), "choice_sagtension_weathercase",
wxChoice);
str_choice = choice->GetString(choice->GetSelection());
choice->Clear();
for (auto iter = weathercases.cbegin(); iter != weathercases.cend();
iter++) {
const WeatherLoadCase& weathercase = *iter;
choice->Append(weathercase.description);
}
choice->SetSelection(choice->FindString(str_choice));
// gets activated span
Span* span = view_->pane_edit()->ActivatedSpan();
if (span != nullptr) {
reloader_.set_line_cable(&span->linecable);
}
reloader_.set_length_unloaded_unstretched_adjustment(0);
UpdateSagTensionResults();
}
void ResultsPane::SetUnitsStaticText(const units::UnitSystem& units) {
/// \todo
/// wxWidgets seems to have a bug when editing labels. The StaticText
/// controls are not re-sized
//wxStaticText* statictext = nullptr;
//wxString str;
//if (model_->units_ == units::UnitSystem::kMetric) {
// statictext = XRCCTRL(*frame_,
// "statictext_constraint_spacing_horizontal_units",
// wxStaticText);
// statictext->SetLabel("[???]");
// statictext = XRCCTRL(*frame_,
// "statictext_constraint_spacing_vertical_units",
// wxStaticText);
// statictext->SetLabel("[???]");
// statictext = XRCCTRL(*frame_, "statictext_tension_horizontal_units",
// wxStaticText);
// statictext->SetLabel("[???]");
// statictext = XRCCTRL(*frame_, "statictext_catenary_constant_units",
// wxStaticText);
// statictext->SetLabel("[???]");
// statictext = XRCCTRL(*frame_, "statictext_tension_horizontal_shell_units",
// wxStaticText);
// statictext->SetLabel("[???]");
// statictext = XRCCTRL(*frame_, "statictext_tension_horizontal_core_units",
// wxStaticText);
// statictext->SetLabel("[???]");
//} else if (model_->units_ == units::UnitSystem::kImperial) {
// statictext = XRCCTRL(*frame_,
// "statictext_constraint_spacing_horizontal_units",
// wxStaticText);
// statictext->SetLabel("[ft]");
// statictext = XRCCTRL(*frame_,
// "statictext_constraint_spacing_vertical_units",
// wxStaticText);
// statictext->SetLabel("[ft]");
// statictext = XRCCTRL(*frame_, "statictext_tension_horizontal_units",
// wxStaticText);
// statictext->SetLabel("[lbs]");
// statictext = XRCCTRL(*frame_, "statictext_catenary_constant_units",
// wxStaticText);
// statictext->SetLabel("[ft]");
// statictext = XRCCTRL(*frame_, "statictext_tension_horizontal_shell_units",
// wxStaticText);
// statictext->SetLabel("[lbs]");
// statictext = XRCCTRL(*frame_, "statictext_tension_horizontal_core_units",
// wxStaticText);
// statictext->SetLabel("[lbs]");
//}
}
void ResultsPane::OnChoiceWeathercase(wxCommandEvent& event) {
// gets weathercases
SpanAnalyzerDoc* doc = (SpanAnalyzerDoc*)view_->GetDocument();
const std::vector<WeatherLoadCase>& weathercases = *doc->weathercases();
// gets selection and updates reloader
wxChoice* choice = XRCCTRL(*view_->GetFrame(),
"choice_sagtension_weathercase", wxChoice);
const int index_selection = choice->GetSelection();
const WeatherLoadCase& weathercase = weathercases.at(index_selection);
reloader_.set_weathercase_reloaded(&weathercase);
// updates sag-tension results
UpdateSagTensionResults();
}
void ResultsPane::OnChoiceCondition(wxCommandEvent& event) {
// gets condition selection and updates reloader
wxChoice* choice = XRCCTRL(*view_->GetFrame(),
"choice_sagtension_condition", wxChoice);
const wxString str_selection = choice->GetStringSelection();
if (str_selection == "Initial") {
reloader_.set_condition_reloaded(CableConditionType::kInitial);
} else if (str_selection == "Final-Load") {
reloader_.set_condition_reloaded(CableConditionType::kLoad);
}
// updates sag-tension results
UpdateSagTensionResults();
}
void ResultsPane::UpdateSagTensionResults() {
wxStaticText* statictext = nullptr;
double value = 0;
wxString str;
// validates reloader
std::list<ErrorMessage> messages;
bool status_validate = reloader_.Validate(false, &messages);
statictext = XRCCTRL(*view_->GetFrame(),
"statictext_tension_horizontal_value",
wxStaticText);
if (status_validate == false) {
statictext->SetLabel("");
} else if (status_validate == true) {
value = reloader_.TensionHorizontal();
str = helper::DoubleToFormattedString(value, 1);
statictext->SetLabel(str);
}
statictext = XRCCTRL(*view_->GetFrame(), "statictext_catenary_constant_value",
wxStaticText);
if (status_validate == false) {
statictext->SetLabel("");
} else if (status_validate == true) {
value = reloader_.CatenaryReloaded().Constant();
str = helper::DoubleToFormattedString(value, 1);
statictext->SetLabel(str);
}
statictext = XRCCTRL(*view_->GetFrame(), "statictext_tension_horizontal_shell_value",
wxStaticText);
if (status_validate == false) {
statictext->SetLabel("");
} else if (status_validate == true) {
value = reloader_.TensionHorizontalComponent(
CableElongationModel::ComponentType::kShell);
str = helper::DoubleToFormattedString(value, 1);
statictext->SetLabel(str);
}
statictext = XRCCTRL(*view_->GetFrame(), "statictext_tension_horizontal_core_value",
wxStaticText);
if (status_validate == false) {
statictext->SetLabel("");
} else if (status_validate == true) {
value = reloader_.TensionHorizontalComponent(
CableElongationModel::ComponentType::kCore);
str = helper::DoubleToFormattedString(value, 1);
statictext->SetLabel(str);
}
}
//std::vector<std::string> columns;
//columns.push_back("Weathercase");
//columns.push_back("Vertical");
//columns.push_back("Transverse");
//columns.push_back("Resultant");
//columns.push_back("Horizontal Tension");
//columns.push_back("Core Tension");
//columns.push_back("Shell Tension");
//columns.push_back("H/w");
//columns.push_back("Sag");
//std::vector<ReportRow> rows;
//const std::vector<WeatherLoadCase>& weathercases = model_->weathercases_;
//LineCableReloader reloader;
//reloader.set_line_cable(&model_->line_cable_);
//reloader.set_length_unloaded_unstretched_adjustment(0);
//reloader.set_condition_reloaded(CableConditionType::kInitial);
//for (auto iter = weathercases.cbegin(); iter != weathercases.cend();
// iter++) {
// const WeatherLoadCase& weathercase = *iter;
//
// // updates reloader
// reloader.set_weathercase_reloaded(&weathercase);
// Catenary3d catenary = reloader.CatenaryReloaded();
// // calculate row values
// ReportRow row;
// double value;
// std::string str;
// str = weathercase.description;
// row.values.push_back(str);
// value = catenary.weight_unit().z();
// str = helper::DoubleToFormattedString(value, 3);
// row.values.push_back(str);
// value = catenary.weight_unit().y();
// str = helper::DoubleToFormattedString(value, 3);
// row.values.push_back(str);
// value = catenary.weight_unit().Magnitude();
// str = helper::DoubleToFormattedString(value, 3);
// row.values.push_back(str);
// value = reloader.TensionHorizontal();
// str = helper::DoubleToFormattedString(value, 1);
// row.values.push_back(str);
// value = reloader.TensionHorizontalComponent(
// CableElongationModel::ComponentType::kCore);
// str = helper::DoubleToFormattedString(value, 1);
// row.values.push_back(str);
// value = reloader.TensionHorizontalComponent(
// CableElongationModel::ComponentType::kShell);
// str = helper::DoubleToFormattedString(value, 1);
// row.values.push_back(str);
// value = catenary.Constant();
// str = helper::DoubleToFormattedString(value, 1);
// row.values.push_back(str);
// value = catenary.Sag();
// str = helper::DoubleToFormattedString(value, 1);
// row.values.push_back(str);
// rows.push_back(row);
//}
//ReportDialog report(frame_, &columns, &rows);
//report.ShowModal();
//}
<commit_msg>Modifed interaction with document for weathercases and spans.<commit_after>// This is free and unencumbered software released into the public domain.
// For more information, please refer to <http://unlicense.org/>
#include "results_pane.h"
#include "models/base/helper.h"
#include "wx/xrc/xmlres.h"
#include "edit_pane.h"
#include "span.h"
#include "span_analyzer_app.h"
#include "span_analyzer_doc.h"
#include "span_analyzer_view.h"
BEGIN_EVENT_TABLE(ResultsPane, wxPanel)
EVT_CHOICE(XRCID("choice_sagtension_weathercase"), ResultsPane::OnChoiceWeathercase)
EVT_CHOICE(XRCID("choice_sagtension_condition"), ResultsPane::OnChoiceCondition)
END_EVENT_TABLE()
ResultsPane::ResultsPane(wxWindow* parent, SpanAnalyzerView* view) {
// loads dialog from virtual xrc file system
wxXmlResource::Get()->LoadPanel(this, parent, "results_pane");
// saves view reference
view_ = view;
// fills the reloaded condition
wxChoice* choice = XRCCTRL(*parent, "choice_sagtension_condition", wxChoice);
choice->Append("Initial");
choice->Append("Final-Load");
}
ResultsPane::~ResultsPane() {
}
void ResultsPane::Update(wxObject* hint) {
if (hint == nullptr) {
return;
}
// gets weathercases
SpanAnalyzerDoc* doc = (SpanAnalyzerDoc*)view_->GetDocument();
const std::vector<WeatherLoadCase>& weathercases = doc->weathercases();
wxChoice* choice = nullptr;
wxString str_choice;
// updates sag-tension weathercase choice and selection
choice = XRCCTRL(*view_->GetFrame(), "choice_sagtension_weathercase",
wxChoice);
str_choice = choice->GetString(choice->GetSelection());
choice->Clear();
for (auto iter = weathercases.cbegin(); iter != weathercases.cend();
iter++) {
const WeatherLoadCase& weathercase = *iter;
choice->Append(weathercase.description);
}
choice->SetSelection(choice->FindString(str_choice));
// gets activated span
const Span* span = view_->pane_edit()->ActivatedSpan();
if (span != nullptr) {
reloader_.set_line_cable(&span->linecable);
}
reloader_.set_length_unloaded_unstretched_adjustment(0);
UpdateSagTensionResults();
}
void ResultsPane::SetUnitsStaticText(const units::UnitSystem& units) {
/// \todo
/// wxWidgets seems to have a bug when editing labels. The StaticText
/// controls are not re-sized
//wxStaticText* statictext = nullptr;
//wxString str;
//if (model_->units_ == units::UnitSystem::kMetric) {
// statictext = XRCCTRL(*frame_,
// "statictext_constraint_spacing_horizontal_units",
// wxStaticText);
// statictext->SetLabel("[???]");
// statictext = XRCCTRL(*frame_,
// "statictext_constraint_spacing_vertical_units",
// wxStaticText);
// statictext->SetLabel("[???]");
// statictext = XRCCTRL(*frame_, "statictext_tension_horizontal_units",
// wxStaticText);
// statictext->SetLabel("[???]");
// statictext = XRCCTRL(*frame_, "statictext_catenary_constant_units",
// wxStaticText);
// statictext->SetLabel("[???]");
// statictext = XRCCTRL(*frame_, "statictext_tension_horizontal_shell_units",
// wxStaticText);
// statictext->SetLabel("[???]");
// statictext = XRCCTRL(*frame_, "statictext_tension_horizontal_core_units",
// wxStaticText);
// statictext->SetLabel("[???]");
//} else if (model_->units_ == units::UnitSystem::kImperial) {
// statictext = XRCCTRL(*frame_,
// "statictext_constraint_spacing_horizontal_units",
// wxStaticText);
// statictext->SetLabel("[ft]");
// statictext = XRCCTRL(*frame_,
// "statictext_constraint_spacing_vertical_units",
// wxStaticText);
// statictext->SetLabel("[ft]");
// statictext = XRCCTRL(*frame_, "statictext_tension_horizontal_units",
// wxStaticText);
// statictext->SetLabel("[lbs]");
// statictext = XRCCTRL(*frame_, "statictext_catenary_constant_units",
// wxStaticText);
// statictext->SetLabel("[ft]");
// statictext = XRCCTRL(*frame_, "statictext_tension_horizontal_shell_units",
// wxStaticText);
// statictext->SetLabel("[lbs]");
// statictext = XRCCTRL(*frame_, "statictext_tension_horizontal_core_units",
// wxStaticText);
// statictext->SetLabel("[lbs]");
//}
}
void ResultsPane::OnChoiceWeathercase(wxCommandEvent& event) {
// gets weathercases
SpanAnalyzerDoc* doc = (SpanAnalyzerDoc*)view_->GetDocument();
const std::vector<WeatherLoadCase>& weathercases = doc->weathercases();
// gets selection and updates reloader
wxChoice* choice = XRCCTRL(*view_->GetFrame(),
"choice_sagtension_weathercase", wxChoice);
const int index_selection = choice->GetSelection();
const WeatherLoadCase& weathercase = weathercases.at(index_selection);
reloader_.set_weathercase_reloaded(&weathercase);
// updates sag-tension results
UpdateSagTensionResults();
}
void ResultsPane::OnChoiceCondition(wxCommandEvent& event) {
// gets condition selection and updates reloader
wxChoice* choice = XRCCTRL(*view_->GetFrame(),
"choice_sagtension_condition", wxChoice);
const wxString str_selection = choice->GetStringSelection();
if (str_selection == "Initial") {
reloader_.set_condition_reloaded(CableConditionType::kInitial);
} else if (str_selection == "Final-Load") {
reloader_.set_condition_reloaded(CableConditionType::kLoad);
}
// updates sag-tension results
UpdateSagTensionResults();
}
void ResultsPane::UpdateSagTensionResults() {
wxStaticText* statictext = nullptr;
double value = 0;
wxString str;
// validates reloader
std::list<ErrorMessage> messages;
bool status_validate = reloader_.Validate(false, &messages);
statictext = XRCCTRL(*view_->GetFrame(),
"statictext_tension_horizontal_value",
wxStaticText);
if (status_validate == false) {
statictext->SetLabel("");
} else if (status_validate == true) {
value = reloader_.TensionHorizontal();
str = helper::DoubleToFormattedString(value, 1);
statictext->SetLabel(str);
}
statictext = XRCCTRL(*view_->GetFrame(), "statictext_catenary_constant_value",
wxStaticText);
if (status_validate == false) {
statictext->SetLabel("");
} else if (status_validate == true) {
value = reloader_.CatenaryReloaded().Constant();
str = helper::DoubleToFormattedString(value, 1);
statictext->SetLabel(str);
}
statictext = XRCCTRL(*view_->GetFrame(), "statictext_tension_horizontal_shell_value",
wxStaticText);
if (status_validate == false) {
statictext->SetLabel("");
} else if (status_validate == true) {
value = reloader_.TensionHorizontalComponent(
CableElongationModel::ComponentType::kShell);
str = helper::DoubleToFormattedString(value, 1);
statictext->SetLabel(str);
}
statictext = XRCCTRL(*view_->GetFrame(), "statictext_tension_horizontal_core_value",
wxStaticText);
if (status_validate == false) {
statictext->SetLabel("");
} else if (status_validate == true) {
value = reloader_.TensionHorizontalComponent(
CableElongationModel::ComponentType::kCore);
str = helper::DoubleToFormattedString(value, 1);
statictext->SetLabel(str);
}
}
//std::vector<std::string> columns;
//columns.push_back("Weathercase");
//columns.push_back("Vertical");
//columns.push_back("Transverse");
//columns.push_back("Resultant");
//columns.push_back("Horizontal Tension");
//columns.push_back("Core Tension");
//columns.push_back("Shell Tension");
//columns.push_back("H/w");
//columns.push_back("Sag");
//std::vector<ReportRow> rows;
//const std::vector<WeatherLoadCase>& weathercases = model_->weathercases_;
//LineCableReloader reloader;
//reloader.set_line_cable(&model_->line_cable_);
//reloader.set_length_unloaded_unstretched_adjustment(0);
//reloader.set_condition_reloaded(CableConditionType::kInitial);
//for (auto iter = weathercases.cbegin(); iter != weathercases.cend();
// iter++) {
// const WeatherLoadCase& weathercase = *iter;
//
// // updates reloader
// reloader.set_weathercase_reloaded(&weathercase);
// Catenary3d catenary = reloader.CatenaryReloaded();
// // calculate row values
// ReportRow row;
// double value;
// std::string str;
// str = weathercase.description;
// row.values.push_back(str);
// value = catenary.weight_unit().z();
// str = helper::DoubleToFormattedString(value, 3);
// row.values.push_back(str);
// value = catenary.weight_unit().y();
// str = helper::DoubleToFormattedString(value, 3);
// row.values.push_back(str);
// value = catenary.weight_unit().Magnitude();
// str = helper::DoubleToFormattedString(value, 3);
// row.values.push_back(str);
// value = reloader.TensionHorizontal();
// str = helper::DoubleToFormattedString(value, 1);
// row.values.push_back(str);
// value = reloader.TensionHorizontalComponent(
// CableElongationModel::ComponentType::kCore);
// str = helper::DoubleToFormattedString(value, 1);
// row.values.push_back(str);
// value = reloader.TensionHorizontalComponent(
// CableElongationModel::ComponentType::kShell);
// str = helper::DoubleToFormattedString(value, 1);
// row.values.push_back(str);
// value = catenary.Constant();
// str = helper::DoubleToFormattedString(value, 1);
// row.values.push_back(str);
// value = catenary.Sag();
// str = helper::DoubleToFormattedString(value, 1);
// row.values.push_back(str);
// rows.push_back(row);
//}
//ReportDialog report(frame_, &columns, &rows);
//report.ShowModal();
//}
<|endoftext|>
|
<commit_before>/********************************************************************
* Copyright © 2017 Computational Molecular Biology Group, *
* Freie Universität Berlin (GER) *
* *
* This file is part of ReaDDy. *
* *
* ReaDDy 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. *
* *
* 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 Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General *
* Public License along with this program. If not, see *
* <http://www.gnu.org/licenses/>. *
********************************************************************/
/**
* << detailed description >>
*
* @file ExportKernelContext.cpp
* @brief << brief description >>
* @author clonker
* @date 20.09.17
* @copyright GNU Lesser General Public License v3.0
*/
#include <pybind11/pybind11.h>
#include <pybind11/stl_bind.h>
#include <pybind11/stl.h>
#include <pybind11/functional.h>
#include <readdy/model/Context.h>
#include <readdy/common/boundary_condition_operations.h>
namespace py = pybind11;
using rvp = py::return_value_policy;
using KernelContext = readdy::model::Context;
using ParticleTypeRegistry = readdy::model::ParticleTypeRegistry;
using ReactionRegistry = readdy::model::reactions::ReactionRegistry;
using PotentialRegistry = readdy::model::potentials::PotentialRegistry;
using TopologyRegistry = readdy::model::top::TopologyRegistry;
using CompartmentRegistry = readdy::model::compartments::CompartmentRegistry;
void exportKernelContext(py::module &module) {
using namespace readdy;
using namespace py::literals;
py::class_<ReactionRegistry>(module, "ReactionRegistry")
.def("add", &ReactionRegistry::add)
.def("add_conversion", (ReactionRegistry::ReactionId(ReactionRegistry::*)(
const std::string &, const std::string &, const std::string &, scalar)) &ReactionRegistry::addConversion)
.def("add_enzymatic", (ReactionRegistry::ReactionId(ReactionRegistry::*)(
const std::string &, const std::string &, const std::string &, const std::string &, scalar, scalar)) &ReactionRegistry::addEnzymatic)
.def("add_fission", (ReactionRegistry::ReactionId(ReactionRegistry::*)(
const std::string &, const std::string &, const std::string &, const std::string &, scalar, scalar, scalar, scalar)) &ReactionRegistry::addFission)
.def("add_fusion", (ReactionRegistry::ReactionId(ReactionRegistry::*)(
const std::string &, const std::string &, const std::string &, const std::string &, scalar, scalar, scalar, scalar)) &ReactionRegistry::addFusion)
.def("add_decay", (ReactionRegistry::ReactionId(ReactionRegistry::*)(
const std::string &, const std::string &, scalar)) &ReactionRegistry::addDecay);
py::class_<ParticleTypeRegistry>(module, "ParticleTypeRegistry")
.def("id_of", &ParticleTypeRegistry::idOf)
.def("add", &ParticleTypeRegistry::add, "name"_a, "diffusion_constant"_a, "flavor"_a = 0)
.def("diffusion_constant_of", [](const ParticleTypeRegistry &self, const std::string &type) {
return self.diffusionConstantOf(type);
})
.def("set_diffusion_constant_of", [](ParticleTypeRegistry &self, const std::string &type, scalar value){
self.diffusionConstantOf(type) = value;
})
.def("n_types", &ParticleTypeRegistry::nTypes)
.def("name_of", &ParticleTypeRegistry::nameOf)
.def_property_readonly("type_mapping", &ParticleTypeRegistry::typeMapping, rvp::reference_internal);
py::class_<PotentialRegistry>(module, "PotentialRegistry")
.def("add_box",
[](PotentialRegistry &self, const std::string &particleType, scalar forceConstant, const Vec3 &origin,
const Vec3 &extent) {
return self.addBox(particleType, forceConstant, origin, extent);
})
.def("add_harmonic_repulsion",
[](PotentialRegistry &self, const std::string &type1, const std::string &type2, scalar forceConstant, scalar interactionDistance) {
return self.addHarmonicRepulsion(type1, type2, forceConstant, interactionDistance);
})
.def("add_weak_interaction_piecewise_harmonic",
[](PotentialRegistry &self, const std::string &type1, const std::string &type2,
scalar forceConstant, scalar desiredDist, scalar depth, scalar cutoff) {
return self.addWeakInteractionPiecewiseHarmonic(type1, type2, forceConstant, desiredDist, depth,
cutoff);
})
.def("add_lennard_jones",
[](PotentialRegistry &self, const std::string &type1, const std::string &type2, unsigned int m,
unsigned int n,
scalar cutoff, bool shift, scalar epsilon, scalar sigma) {
return self.addLennardJones(type1, type2, m, n, cutoff, shift, epsilon, sigma);
})
.def("add_screened_electrostatics",
[](PotentialRegistry &self, const std::string &type1, const std::string &type2,
scalar electrostaticStrength, scalar inverseScreeningDepth,
scalar repulsionStrength, scalar repulsionDistance, unsigned int exponent,
scalar cutoff) {
return self.addScreenedElectrostatics(type1, type2, electrostaticStrength, inverseScreeningDepth,
repulsionStrength, repulsionDistance, exponent, cutoff);
})
.def("add_sphere_out",
[](PotentialRegistry &self, const std::string &particleType, scalar forceConstant, const Vec3 &origin,
scalar radius) {
return self.addSphereOut(particleType, forceConstant, origin, radius);
})
.def("add_sphere_in",
[](PotentialRegistry &self, const std::string &particleType, scalar forceConstant, const Vec3 &origin,
scalar radius) {
return self.addSphereIn(particleType, forceConstant, origin, radius);
})
.def("add_spherical_barrier",
[](PotentialRegistry &self, const std::string &particleType, scalar height, scalar width,
const Vec3 &origin, scalar radius) {
return self.addSphericalBarrier(particleType, height, width, origin, radius);
})
.def("add_external_order1", [](PotentialRegistry& self, readdy::model::potentials::PotentialOrder1* pot) {
return self.addUserDefined(pot);
}, py::keep_alive<1, 2>())
.def("add_external_order2", [](PotentialRegistry& self, readdy::model::potentials::PotentialOrder2* pot) {
return self.addUserDefined(pot);
}, py::keep_alive<1, 2>());
py::class_<readdy::api::Bond>(module, "BondedPotentialConfiguration")
.def(py::init([](scalar forceConstant, scalar length, const std::string &type) {
if(type != "harmonic") {
throw std::invalid_argument("only suppoted type: \"harmonic\"");
}
readdy::api::Bond bond {forceConstant, length, readdy::api::BondType::HARMONIC};
return bond;
}), "force_constant"_a, "length"_a, "type"_a="harmonic");
py::class_<readdy::api::Angle>(module, "AnglePotentialConfiguration")
.def(py::init([](scalar forceConstant, scalar equilibriumAngle, const std::string &type) {
if(type != "harmonic") {
throw std::invalid_argument("only suppoted type: \"harmonic\"");
}
readdy::api::Angle angle {forceConstant, equilibriumAngle, readdy::api::AngleType::HARMONIC};
return angle;
}), "force_constant"_a, "equilibrium_angle"_a, "type"_a="harmonic");
py::class_<readdy::api::TorsionAngle>(module, "TorsionPotentialConfiguration")
.def(py::init([](scalar forceConstant, scalar multiplicity, scalar phi0, const std::string &type) {
if(type != "cos_dihedral") {
throw std::invalid_argument("only supported type: \"cos_dihedral\"");
}
readdy::api::TorsionAngle angle {forceConstant, multiplicity, phi0, readdy::api::TorsionType::COS_DIHEDRAL};
return angle;
}), "force_constant"_a, "multiplicity"_a, "phi0"_a, "type"_a="cos_dihedral");
py::class_<TopologyRegistry>(module, "TopologyRegistry")
.def("add_type", [](TopologyRegistry &self, const std::string &type) { return self.addType(type); })
.def("add_structural_reaction", [](TopologyRegistry &self, const std::string &type,
const readdy::model::top::reactions::StructuralTopologyReaction &reaction) {
self.addStructuralReaction(type, reaction);
})
.def("add_spatial_reaction",
[](TopologyRegistry &self, const std::string &descriptor, scalar rate, scalar radius) {
self.addSpatialReaction(descriptor, rate, radius);
})
.def("configure_bond_potential", &TopologyRegistry::configureBondPotential)
.def("configure_angle_potential", &TopologyRegistry::configureAnglePotential)
.def("configure_torsion_potential", &TopologyRegistry::configureTorsionPotential);
py::class_<CompartmentRegistry>(module, "CompartmentRegistry")
.def("add_sphere", [](CompartmentRegistry &self,
const readdy::model::compartments::Compartment::label_conversion_map &conversions,
const std::string &uniqueName,
const Vec3 &origin, scalar radius, bool largerOrLess) {
return self.addSphere(conversions, uniqueName, origin, radius, largerOrLess);
})
.def("add_plane", [](CompartmentRegistry &self,
const readdy::model::compartments::Compartment::label_conversion_map &conversions,
const std::string &uniqueName,
const Vec3 &normalCoefficients, scalar distance, bool largerOrLess) {
return self.addPlane(conversions, uniqueName, normalCoefficients, distance, largerOrLess);
});
py::class_<KernelContext>(module, "Context")
.def(py::init<>())
.def_property("kbt", [](const KernelContext &self) { return self.kBT(); },
[](KernelContext &self, scalar kbt) { self.kBT() = kbt; })
.def("box_volume", &KernelContext::boxVolume)
.def_property("box_size", [](const KernelContext &self) { return self.boxSize(); },
[](KernelContext &self, KernelContext::BoxSize boxSize) { self.boxSize() = boxSize; })
.def_property("pbc", [](const KernelContext &self) { return self.periodicBoundaryConditions(); },
[](KernelContext &self, KernelContext::PeriodicBoundaryConditions pbc) {
self.periodicBoundaryConditions() = pbc;
})
.def("describe", &KernelContext::describe)
.def("validate", &KernelContext::validate)
.def("bounding_box_vertices", &KernelContext::getBoxBoundingVertices)
.def("calculate_max_cutoff", &KernelContext::calculateMaxCutoff)
.def_property("record_reactions_with_positions",
[](const KernelContext &self) { return self.recordReactionsWithPositions(); },
[](KernelContext &self, bool value) { self.recordReactionsWithPositions() = value; })
.def_property("record_reaction_counts",
[](const KernelContext &self) { return self.recordReactionCounts(); },
[](KernelContext &self, bool value) { self.recordReactionCounts() = value; })
.def("set_kernel_configuration", &KernelContext::setKernelConfiguration)
.def_property_readonly("particle_types", [](KernelContext &self) -> ParticleTypeRegistry& { return self.particleTypes(); }, rvp::reference_internal)
.def_property_readonly("reactions", [](KernelContext &self) -> ReactionRegistry& { return self.reactions(); }, rvp::reference_internal)
.def_property_readonly("potentials", [](KernelContext &self) -> PotentialRegistry& { return self.potentials(); }, rvp::reference_internal)
.def_property_readonly("topologies", [](KernelContext &self) -> TopologyRegistry& { return self.topologyRegistry(); }, rvp::reference_internal)
.def_property_readonly("compartments", [](KernelContext &self) -> CompartmentRegistry& { return self.compartments(); }, rvp::reference_internal)
.def_property_readonly("shortest_difference_fun", [](const KernelContext &self) -> std::function<Vec3(const Vec3&, const Vec3 &)> {
return [&self](const Vec3 &v1, const Vec3 &v2) {
return bcs::shortestDifference(v1, v2, self.boxSize(), self.periodicBoundaryConditions());
};
})
.def_property_readonly("fix_position_fun", [](const KernelContext &self) -> std::function<void(Vec3 &)> {
return [&self](Vec3 &position) {
return bcs::fixPosition(position, self.boxSize(), self.periodicBoundaryConditions());
};
})
.def_property_readonly("dist_squared_fun", [](const KernelContext &self) -> std::function<scalar(const Vec3 &, const Vec3 &)> {
return [&self](const Vec3 &p1, const Vec3 &p2) {
return bcs::distSquared(p1, p2, self.boxSize(), self.periodicBoundaryConditions());
};
});
}
<commit_msg>binding for base class potentials<commit_after>/********************************************************************
* Copyright © 2017 Computational Molecular Biology Group, *
* Freie Universität Berlin (GER) *
* *
* This file is part of ReaDDy. *
* *
* ReaDDy 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. *
* *
* 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 Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General *
* Public License along with this program. If not, see *
* <http://www.gnu.org/licenses/>. *
********************************************************************/
/**
* << detailed description >>
*
* @file ExportKernelContext.cpp
* @brief << brief description >>
* @author clonker
* @date 20.09.17
* @copyright GNU Lesser General Public License v3.0
*/
#include <pybind11/pybind11.h>
#include <pybind11/stl_bind.h>
#include <pybind11/stl.h>
#include <pybind11/functional.h>
#include <readdy/model/Context.h>
#include <readdy/common/boundary_condition_operations.h>
namespace py = pybind11;
using rvp = py::return_value_policy;
using KernelContext = readdy::model::Context;
using ParticleTypeRegistry = readdy::model::ParticleTypeRegistry;
using ReactionRegistry = readdy::model::reactions::ReactionRegistry;
using PotentialRegistry = readdy::model::potentials::PotentialRegistry;
using TopologyRegistry = readdy::model::top::TopologyRegistry;
using CompartmentRegistry = readdy::model::compartments::CompartmentRegistry;
void exportKernelContext(py::module &module) {
using namespace readdy;
using namespace py::literals;
py::class_<ReactionRegistry>(module, "ReactionRegistry")
.def("add", &ReactionRegistry::add)
.def("add_conversion", (ReactionRegistry::ReactionId(ReactionRegistry::*)(
const std::string &, const std::string &, const std::string &, scalar)) &ReactionRegistry::addConversion)
.def("add_enzymatic", (ReactionRegistry::ReactionId(ReactionRegistry::*)(
const std::string &, const std::string &, const std::string &, const std::string &, scalar, scalar)) &ReactionRegistry::addEnzymatic)
.def("add_fission", (ReactionRegistry::ReactionId(ReactionRegistry::*)(
const std::string &, const std::string &, const std::string &, const std::string &, scalar, scalar, scalar, scalar)) &ReactionRegistry::addFission)
.def("add_fusion", (ReactionRegistry::ReactionId(ReactionRegistry::*)(
const std::string &, const std::string &, const std::string &, const std::string &, scalar, scalar, scalar, scalar)) &ReactionRegistry::addFusion)
.def("add_decay", (ReactionRegistry::ReactionId(ReactionRegistry::*)(
const std::string &, const std::string &, scalar)) &ReactionRegistry::addDecay);
py::class_<ParticleTypeRegistry>(module, "ParticleTypeRegistry")
.def("id_of", &ParticleTypeRegistry::idOf)
.def("add", &ParticleTypeRegistry::add, "name"_a, "diffusion_constant"_a, "flavor"_a = 0)
.def("diffusion_constant_of", [](const ParticleTypeRegistry &self, const std::string &type) {
return self.diffusionConstantOf(type);
})
.def("set_diffusion_constant_of", [](ParticleTypeRegistry &self, const std::string &type, scalar value){
self.diffusionConstantOf(type) = value;
})
.def("n_types", &ParticleTypeRegistry::nTypes)
.def("name_of", &ParticleTypeRegistry::nameOf)
.def_property_readonly("type_mapping", &ParticleTypeRegistry::typeMapping, rvp::reference_internal);
py::class_<PotentialRegistry>(module, "PotentialRegistry")
.def("add_box",
[](PotentialRegistry &self, const std::string &particleType, scalar forceConstant, const Vec3 &origin,
const Vec3 &extent) {
return self.addBox(particleType, forceConstant, origin, extent);
})
.def("add_harmonic_repulsion",
[](PotentialRegistry &self, const std::string &type1, const std::string &type2, scalar forceConstant, scalar interactionDistance) {
return self.addHarmonicRepulsion(type1, type2, forceConstant, interactionDistance);
})
.def("add_weak_interaction_piecewise_harmonic",
[](PotentialRegistry &self, const std::string &type1, const std::string &type2,
scalar forceConstant, scalar desiredDist, scalar depth, scalar cutoff) {
return self.addWeakInteractionPiecewiseHarmonic(type1, type2, forceConstant, desiredDist, depth,
cutoff);
})
.def("add_lennard_jones",
[](PotentialRegistry &self, const std::string &type1, const std::string &type2, unsigned int m,
unsigned int n,
scalar cutoff, bool shift, scalar epsilon, scalar sigma) {
return self.addLennardJones(type1, type2, m, n, cutoff, shift, epsilon, sigma);
})
.def("add_screened_electrostatics",
[](PotentialRegistry &self, const std::string &type1, const std::string &type2,
scalar electrostaticStrength, scalar inverseScreeningDepth,
scalar repulsionStrength, scalar repulsionDistance, unsigned int exponent,
scalar cutoff) {
return self.addScreenedElectrostatics(type1, type2, electrostaticStrength, inverseScreeningDepth,
repulsionStrength, repulsionDistance, exponent, cutoff);
})
.def("add_sphere_out",
[](PotentialRegistry &self, const std::string &particleType, scalar forceConstant, const Vec3 &origin,
scalar radius) {
return self.addSphereOut(particleType, forceConstant, origin, radius);
})
.def("add_sphere_in",
[](PotentialRegistry &self, const std::string &particleType, scalar forceConstant, const Vec3 &origin,
scalar radius) {
return self.addSphereIn(particleType, forceConstant, origin, radius);
})
.def("add_spherical_barrier",
[](PotentialRegistry &self, const std::string &particleType, scalar height, scalar width,
const Vec3 &origin, scalar radius) {
return self.addSphericalBarrier(particleType, height, width, origin, radius);
})
.def("add_external_order1", [](PotentialRegistry& self, readdy::model::potentials::PotentialOrder1* pot) {
return self.addUserDefined(pot);
}, py::keep_alive<1, 2>())
.def("add_external_order2", [](PotentialRegistry& self, readdy::model::potentials::PotentialOrder2* pot) {
return self.addUserDefined(pot);
}, py::keep_alive<1, 2>());
py::class_<readdy::model::potentials::PotentialOrder1>(module, "PotentialOrder1");
py::class_<readdy::model::potentials::PotentialOrder2>(module, "PotentialOrder2");
py::class_<readdy::api::Bond>(module, "BondedPotentialConfiguration")
.def(py::init([](scalar forceConstant, scalar length, const std::string &type) {
if(type != "harmonic") {
throw std::invalid_argument("only suppoted type: \"harmonic\"");
}
readdy::api::Bond bond {forceConstant, length, readdy::api::BondType::HARMONIC};
return bond;
}), "force_constant"_a, "length"_a, "type"_a="harmonic");
py::class_<readdy::api::Angle>(module, "AnglePotentialConfiguration")
.def(py::init([](scalar forceConstant, scalar equilibriumAngle, const std::string &type) {
if(type != "harmonic") {
throw std::invalid_argument("only suppoted type: \"harmonic\"");
}
readdy::api::Angle angle {forceConstant, equilibriumAngle, readdy::api::AngleType::HARMONIC};
return angle;
}), "force_constant"_a, "equilibrium_angle"_a, "type"_a="harmonic");
py::class_<readdy::api::TorsionAngle>(module, "TorsionPotentialConfiguration")
.def(py::init([](scalar forceConstant, scalar multiplicity, scalar phi0, const std::string &type) {
if(type != "cos_dihedral") {
throw std::invalid_argument("only supported type: \"cos_dihedral\"");
}
readdy::api::TorsionAngle angle {forceConstant, multiplicity, phi0, readdy::api::TorsionType::COS_DIHEDRAL};
return angle;
}), "force_constant"_a, "multiplicity"_a, "phi0"_a, "type"_a="cos_dihedral");
py::class_<TopologyRegistry>(module, "TopologyRegistry")
.def("add_type", [](TopologyRegistry &self, const std::string &type) { return self.addType(type); })
.def("add_structural_reaction", [](TopologyRegistry &self, const std::string &type,
const readdy::model::top::reactions::StructuralTopologyReaction &reaction) {
self.addStructuralReaction(type, reaction);
})
.def("add_spatial_reaction",
[](TopologyRegistry &self, const std::string &descriptor, scalar rate, scalar radius) {
self.addSpatialReaction(descriptor, rate, radius);
})
.def("configure_bond_potential", &TopologyRegistry::configureBondPotential)
.def("configure_angle_potential", &TopologyRegistry::configureAnglePotential)
.def("configure_torsion_potential", &TopologyRegistry::configureTorsionPotential);
py::class_<CompartmentRegistry>(module, "CompartmentRegistry")
.def("add_sphere", [](CompartmentRegistry &self,
const readdy::model::compartments::Compartment::label_conversion_map &conversions,
const std::string &uniqueName,
const Vec3 &origin, scalar radius, bool largerOrLess) {
return self.addSphere(conversions, uniqueName, origin, radius, largerOrLess);
})
.def("add_plane", [](CompartmentRegistry &self,
const readdy::model::compartments::Compartment::label_conversion_map &conversions,
const std::string &uniqueName,
const Vec3 &normalCoefficients, scalar distance, bool largerOrLess) {
return self.addPlane(conversions, uniqueName, normalCoefficients, distance, largerOrLess);
});
py::class_<KernelContext>(module, "Context")
.def(py::init<>())
.def_property("kbt", [](const KernelContext &self) { return self.kBT(); },
[](KernelContext &self, scalar kbt) { self.kBT() = kbt; })
.def("box_volume", &KernelContext::boxVolume)
.def_property("box_size", [](const KernelContext &self) { return self.boxSize(); },
[](KernelContext &self, KernelContext::BoxSize boxSize) { self.boxSize() = boxSize; })
.def_property("pbc", [](const KernelContext &self) { return self.periodicBoundaryConditions(); },
[](KernelContext &self, KernelContext::PeriodicBoundaryConditions pbc) {
self.periodicBoundaryConditions() = pbc;
})
.def("describe", &KernelContext::describe)
.def("validate", &KernelContext::validate)
.def("bounding_box_vertices", &KernelContext::getBoxBoundingVertices)
.def("calculate_max_cutoff", &KernelContext::calculateMaxCutoff)
.def_property("record_reactions_with_positions",
[](const KernelContext &self) { return self.recordReactionsWithPositions(); },
[](KernelContext &self, bool value) { self.recordReactionsWithPositions() = value; })
.def_property("record_reaction_counts",
[](const KernelContext &self) { return self.recordReactionCounts(); },
[](KernelContext &self, bool value) { self.recordReactionCounts() = value; })
.def("set_kernel_configuration", &KernelContext::setKernelConfiguration)
.def_property_readonly("particle_types", [](KernelContext &self) -> ParticleTypeRegistry& { return self.particleTypes(); }, rvp::reference_internal)
.def_property_readonly("reactions", [](KernelContext &self) -> ReactionRegistry& { return self.reactions(); }, rvp::reference_internal)
.def_property_readonly("potentials", [](KernelContext &self) -> PotentialRegistry& { return self.potentials(); }, rvp::reference_internal)
.def_property_readonly("topologies", [](KernelContext &self) -> TopologyRegistry& { return self.topologyRegistry(); }, rvp::reference_internal)
.def_property_readonly("compartments", [](KernelContext &self) -> CompartmentRegistry& { return self.compartments(); }, rvp::reference_internal)
.def_property_readonly("shortest_difference_fun", [](const KernelContext &self) -> std::function<Vec3(const Vec3&, const Vec3 &)> {
return [&self](const Vec3 &v1, const Vec3 &v2) {
return bcs::shortestDifference(v1, v2, self.boxSize(), self.periodicBoundaryConditions());
};
})
.def_property_readonly("fix_position_fun", [](const KernelContext &self) -> std::function<void(Vec3 &)> {
return [&self](Vec3 &position) {
return bcs::fixPosition(position, self.boxSize(), self.periodicBoundaryConditions());
};
})
.def_property_readonly("dist_squared_fun", [](const KernelContext &self) -> std::function<scalar(const Vec3 &, const Vec3 &)> {
return [&self](const Vec3 &p1, const Vec3 &p2) {
return bcs::distSquared(p1, p2, self.boxSize(), self.periodicBoundaryConditions());
};
});
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLIndexTitleTemplateContext.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: hr $ $Date: 2007-06-27 16:01:58 $
*
* 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_xmloff.hxx"
#ifndef _XMLOFF_XMLINDEXTITLETEMPLATECONTEXT_HXX_
#include "XMLIndexTitleTemplateContext.hxx"
#endif
#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
using ::rtl::OUString;
using ::rtl::OUStringBuffer;
using ::com::sun::star::beans::XPropertySet;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::xml::sax::XAttributeList;
using ::xmloff::token::IsXMLToken;
using ::xmloff::token::XML_STYLE_NAME;
const sal_Char sAPI_Title[] = "Title";
const sal_Char sAPI_ParaStyleHeading[] = "ParaStyleHeading";
TYPEINIT1( XMLIndexTitleTemplateContext, SvXMLImportContext );
XMLIndexTitleTemplateContext::XMLIndexTitleTemplateContext(
SvXMLImport& rImport,
Reference<XPropertySet> & rPropSet,
sal_uInt16 nPrfx,
const OUString& rLocalName)
: SvXMLImportContext(rImport, nPrfx, rLocalName)
, sTitle(RTL_CONSTASCII_USTRINGPARAM(sAPI_Title))
, sParaStyleHeading(RTL_CONSTASCII_USTRINGPARAM(sAPI_ParaStyleHeading))
, bStyleNameOK(sal_False)
, rTOCPropertySet(rPropSet)
{
}
XMLIndexTitleTemplateContext::~XMLIndexTitleTemplateContext()
{
}
void XMLIndexTitleTemplateContext::StartElement(
const Reference<XAttributeList> & xAttrList)
{
// there's only one attribute: style-name
sal_Int16 nLength = xAttrList->getLength();
for(sal_Int16 nAttr = 0; nAttr < nLength; nAttr++)
{
OUString sLocalName;
sal_uInt16 nPrefix = GetImport().GetNamespaceMap().
GetKeyByAttrName( xAttrList->getNameByIndex(nAttr),
&sLocalName );
if ( (XML_NAMESPACE_TEXT == nPrefix) &&
(IsXMLToken(sLocalName, XML_STYLE_NAME)) )
{
sStyleName = xAttrList->getValueByIndex(nAttr);
bStyleNameOK = sal_True;
}
}
}
void XMLIndexTitleTemplateContext::EndElement()
{
Any aAny;
aAny <<= sContent.makeStringAndClear();
rTOCPropertySet->setPropertyValue(sTitle, aAny);
if (bStyleNameOK)
{
aAny <<= GetImport().GetStyleDisplayName(
XML_STYLE_FAMILY_TEXT_PARAGRAPH,
sStyleName );
rTOCPropertySet->setPropertyValue(sParaStyleHeading, aAny);
}
}
void XMLIndexTitleTemplateContext::Characters(
const OUString& sString)
{
sContent.append(sString);
}
<commit_msg>INTEGRATION: CWS sw8u10bf01 (1.8.80); FILE MERGED 2007/11/07 14:59:53 ama 1.8.80.1: Fix #i82443#i82902#: Check style name (display names)<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLIndexTitleTemplateContext.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: kz $ $Date: 2007-12-12 13:15:41 $
*
* 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_xmloff.hxx"
#ifndef _XMLOFF_XMLINDEXTITLETEMPLATECONTEXT_HXX_
#include "XMLIndexTitleTemplateContext.hxx"
#endif
#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
using ::rtl::OUString;
using ::rtl::OUStringBuffer;
using ::com::sun::star::beans::XPropertySet;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::xml::sax::XAttributeList;
using ::xmloff::token::IsXMLToken;
using ::xmloff::token::XML_STYLE_NAME;
const sal_Char sAPI_Title[] = "Title";
const sal_Char sAPI_ParaStyleHeading[] = "ParaStyleHeading";
TYPEINIT1( XMLIndexTitleTemplateContext, SvXMLImportContext );
XMLIndexTitleTemplateContext::XMLIndexTitleTemplateContext(
SvXMLImport& rImport,
Reference<XPropertySet> & rPropSet,
sal_uInt16 nPrfx,
const OUString& rLocalName)
: SvXMLImportContext(rImport, nPrfx, rLocalName)
, sTitle(RTL_CONSTASCII_USTRINGPARAM(sAPI_Title))
, sParaStyleHeading(RTL_CONSTASCII_USTRINGPARAM(sAPI_ParaStyleHeading))
, bStyleNameOK(sal_False)
, rTOCPropertySet(rPropSet)
{
}
XMLIndexTitleTemplateContext::~XMLIndexTitleTemplateContext()
{
}
void XMLIndexTitleTemplateContext::StartElement(
const Reference<XAttributeList> & xAttrList)
{
// there's only one attribute: style-name
sal_Int16 nLength = xAttrList->getLength();
for(sal_Int16 nAttr = 0; nAttr < nLength; nAttr++)
{
OUString sLocalName;
sal_uInt16 nPrefix = GetImport().GetNamespaceMap().
GetKeyByAttrName( xAttrList->getNameByIndex(nAttr),
&sLocalName );
if ( (XML_NAMESPACE_TEXT == nPrefix) &&
(IsXMLToken(sLocalName, XML_STYLE_NAME)) )
{
sStyleName = xAttrList->getValueByIndex(nAttr);
OUString sDisplayStyleName = GetImport().GetStyleDisplayName(
XML_STYLE_FAMILY_TEXT_PARAGRAPH, sStyleName );
const Reference < ::com::sun::star::container::XNameContainer >&
rStyles = GetImport().GetTextImport()->GetParaStyles();
bStyleNameOK = rStyles.is() && rStyles->hasByName( sDisplayStyleName );
}
}
}
void XMLIndexTitleTemplateContext::EndElement()
{
Any aAny;
aAny <<= sContent.makeStringAndClear();
rTOCPropertySet->setPropertyValue(sTitle, aAny);
if (bStyleNameOK)
{
aAny <<= GetImport().GetStyleDisplayName(
XML_STYLE_FAMILY_TEXT_PARAGRAPH,
sStyleName );
rTOCPropertySet->setPropertyValue(sParaStyleHeading, aAny);
}
}
void XMLIndexTitleTemplateContext::Characters(
const OUString& sString)
{
sContent.append(sString);
}
<|endoftext|>
|
<commit_before>// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#ifndef HAVE_CPP_STDLIB
// Unfortunately as of 04/27/2021 the fix is NOT in the vcpkg snapshot of Google Test.
// Remove above `#ifdef` once the GMock fix for C++20 is in the mainline.
//
// Please refer to this GitHub issue for additional details:
// https://github.com/google/googletest/issues/2914
// https://github.com/google/googletest/commit/61f010d703b32de9bfb20ab90ece38ab2f25977f
//
// If we compile using Visual Studio 2019 with `c++latest` (C++20) without the GMock fix,
// then the compilation here fails in `gmock-actions.h` from:
// .\tools\vcpkg\installed\x64-windows\include\gmock\gmock-actions.h(819):
// error C2653: 'result_of': is not a class or namespace name
//
// That is because `std::result_of` has been removed in C++20.
# include "opentelemetry/exporters/otlp/otlp_grpc_exporter.h"
# include "opentelemetry/exporters/otlp/protobuf_include_prefix.h"
// Problematic code that pulls in Gmock and breaks with vs2019/c++latest :
# include "opentelemetry/proto/collector/trace/v1/trace_service_mock.grpc.pb.h"
# include "opentelemetry/exporters/otlp/protobuf_include_suffix.h"
# include "opentelemetry/sdk/trace/simple_processor.h"
# include "opentelemetry/sdk/trace/tracer_provider.h"
# include "opentelemetry/trace/provider.h"
# include <gtest/gtest.h>
using namespace testing;
OPENTELEMETRY_BEGIN_NAMESPACE
namespace exporter
{
namespace otlp
{
class OtlpGrpcExporterTestPeer : public ::testing::Test
{
public:
std::unique_ptr<sdk::trace::SpanExporter> GetExporter(
std::unique_ptr<proto::collector::trace::v1::TraceService::StubInterface> &stub_interface)
{
return std::unique_ptr<sdk::trace::SpanExporter>(
new OtlpGrpcExporter(std::move(stub_interface)));
}
// Get the options associated with the given exporter.
const OtlpGrpcExporterOptions &GetOptions(std::unique_ptr<OtlpGrpcExporter> &exporter)
{
return exporter->options_;
}
};
// Call Export() directly
TEST_F(OtlpGrpcExporterTestPeer, ExportUnitTest)
{
auto mock_stub = new proto::collector::trace::v1::MockTraceServiceStub();
std::unique_ptr<proto::collector::trace::v1::TraceService::StubInterface> stub_interface(
mock_stub);
auto exporter = GetExporter(stub_interface);
auto recordable_1 = exporter->MakeRecordable();
recordable_1->SetName("Test span 1");
auto recordable_2 = exporter->MakeRecordable();
recordable_2->SetName("Test span 2");
// Test successful RPC
nostd::span<std::unique_ptr<sdk::trace::Recordable>> batch_1(&recordable_1, 1);
EXPECT_CALL(*mock_stub, Export(_, _, _)).Times(Exactly(1)).WillOnce(Return(grpc::Status::OK));
auto result = exporter->Export(batch_1);
EXPECT_EQ(sdk::common::ExportResult::kSuccess, result);
// Test failed RPC
nostd::span<std::unique_ptr<sdk::trace::Recordable>> batch_2(&recordable_2, 1);
EXPECT_CALL(*mock_stub, Export(_, _, _))
.Times(Exactly(1))
.WillOnce(Return(grpc::Status::CANCELLED));
result = exporter->Export(batch_2);
EXPECT_EQ(sdk::common::ExportResult::kFailure, result);
}
// Create spans, let processor call Export()
TEST_F(OtlpGrpcExporterTestPeer, ExportIntegrationTest)
{
auto mock_stub = new proto::collector::trace::v1::MockTraceServiceStub();
std::unique_ptr<proto::collector::trace::v1::TraceService::StubInterface> stub_interface(
mock_stub);
auto exporter = GetExporter(stub_interface);
auto processor = std::unique_ptr<sdk::trace::SpanProcessor>(
new sdk::trace::SimpleSpanProcessor(std::move(exporter)));
auto provider = nostd::shared_ptr<trace::TracerProvider>(
new sdk::trace::TracerProvider(std::move(processor)));
auto tracer = provider->GetTracer("test");
EXPECT_CALL(*mock_stub, Export(_, _, _))
.Times(AtLeast(1))
.WillRepeatedly(Return(grpc::Status::OK));
auto parent_span = tracer->StartSpan("Test parent span");
auto child_span = tracer->StartSpan("Test child span");
child_span->End();
parent_span->End();
}
// Test exporter configuration options
TEST_F(OtlpGrpcExporterTestPeer, ConfigTest)
{
OtlpGrpcExporterOptions opts;
opts.endpoint = "localhost:45454";
std::unique_ptr<OtlpGrpcExporter> exporter(new OtlpGrpcExporter(opts));
EXPECT_EQ(GetOptions(exporter).endpoint, "localhost:45454");
}
// Test exporter configuration options with use_ssl_credentials
TEST_F(OtlpGrpcExporterTestPeer, ConfigSslCredentialsTest)
{
std::string cacert_str = "--begin and end fake cert--";
OtlpGrpcExporterOptions opts;
opts.use_ssl_credentials = true;
opts.ssl_credentials_cacert_as_string = cacert_str;
std::unique_ptr<OtlpGrpcExporter> exporter(new OtlpGrpcExporter(opts));
EXPECT_EQ(GetOptions(exporter).ssl_credentials_cacert_as_string, cacert_str);
EXPECT_EQ(GetOptions(exporter).use_ssl_credentials, true);
}
# ifndef NO_GETENV
// Test exporter configuration options with use_ssl_credentials
TEST_F(OtlpGrpcExporterTestPeer, ConfigFromEnv)
{
const std::string cacert_str = "--begin and end fake cert--";
const std::string cacert_env = "OTEL_EXPORTER_OTLP_GRPC_SSL_CERTIFICATE=" + cacert_str;
putenv(const_cast<char *>(cacert_env.data()));
char ssl_enable_env[] = "OTEL_EXPORTER_OTLP_GRPC_SSL_ENABLE=True";
putenv(ssl_enable_env);
const std::string endpoint = "http://localhost:9999";
const std::string endpoint_env = "OTEL_EXPORTER_OTLP_GRPC_ENDPOINT=" + endpoint;
putenv(const_cast<char *>(endpoint_env.data()));
std::unique_ptr<OtlpGrpcExporter> exporter(new OtlpGrpcExporter());
EXPECT_EQ(GetOptions(exporter).ssl_credentials_cacert_as_string, cacert_str);
EXPECT_EQ(GetOptions(exporter).use_ssl_credentials, true);
EXPECT_EQ(GetOptions(exporter).endpoint, endpoint);
# if defined(_MSC_VER)
putenv("OTEL_EXPORTER_OTLP_GRPC_ENDPOINT=");
putenv("OTEL_EXPORTER_OTLP_GRPC_SSL_CERTIFICATE=");
putenv("OTEL_EXPORTER_OTLP_GRPC_SSL_ENABLE=");
# else
unsetenv("OTEL_EXPORTER_OTLP_GRPC_ENDPOINT");
unsetenv("OTEL_EXPORTER_OTLP_GRPC_SSL_CERTIFICATE");
unsetenv("OTEL_EXPORTER_OTLP_GRPC_SSL_ENABLE");
# endif
}
# endif
} // namespace otlp
} // namespace exporter
OPENTELEMETRY_END_NAMESPACE
#endif
<commit_msg>Fix warning of deprecation of putenv for MSVC (#935)<commit_after>// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#ifndef HAVE_CPP_STDLIB
// Unfortunately as of 04/27/2021 the fix is NOT in the vcpkg snapshot of Google Test.
// Remove above `#ifdef` once the GMock fix for C++20 is in the mainline.
//
// Please refer to this GitHub issue for additional details:
// https://github.com/google/googletest/issues/2914
// https://github.com/google/googletest/commit/61f010d703b32de9bfb20ab90ece38ab2f25977f
//
// If we compile using Visual Studio 2019 with `c++latest` (C++20) without the GMock fix,
// then the compilation here fails in `gmock-actions.h` from:
// .\tools\vcpkg\installed\x64-windows\include\gmock\gmock-actions.h(819):
// error C2653: 'result_of': is not a class or namespace name
//
// That is because `std::result_of` has been removed in C++20.
# include "opentelemetry/exporters/otlp/otlp_grpc_exporter.h"
# include "opentelemetry/exporters/otlp/protobuf_include_prefix.h"
// Problematic code that pulls in Gmock and breaks with vs2019/c++latest :
# include "opentelemetry/proto/collector/trace/v1/trace_service_mock.grpc.pb.h"
# include "opentelemetry/exporters/otlp/protobuf_include_suffix.h"
# include "opentelemetry/sdk/trace/simple_processor.h"
# include "opentelemetry/sdk/trace/tracer_provider.h"
# include "opentelemetry/trace/provider.h"
# include <gtest/gtest.h>
# if defined(_MSC_VER)
# define putenv _putenv
# endif
using namespace testing;
OPENTELEMETRY_BEGIN_NAMESPACE
namespace exporter
{
namespace otlp
{
class OtlpGrpcExporterTestPeer : public ::testing::Test
{
public:
std::unique_ptr<sdk::trace::SpanExporter> GetExporter(
std::unique_ptr<proto::collector::trace::v1::TraceService::StubInterface> &stub_interface)
{
return std::unique_ptr<sdk::trace::SpanExporter>(
new OtlpGrpcExporter(std::move(stub_interface)));
}
// Get the options associated with the given exporter.
const OtlpGrpcExporterOptions &GetOptions(std::unique_ptr<OtlpGrpcExporter> &exporter)
{
return exporter->options_;
}
};
// Call Export() directly
TEST_F(OtlpGrpcExporterTestPeer, ExportUnitTest)
{
auto mock_stub = new proto::collector::trace::v1::MockTraceServiceStub();
std::unique_ptr<proto::collector::trace::v1::TraceService::StubInterface> stub_interface(
mock_stub);
auto exporter = GetExporter(stub_interface);
auto recordable_1 = exporter->MakeRecordable();
recordable_1->SetName("Test span 1");
auto recordable_2 = exporter->MakeRecordable();
recordable_2->SetName("Test span 2");
// Test successful RPC
nostd::span<std::unique_ptr<sdk::trace::Recordable>> batch_1(&recordable_1, 1);
EXPECT_CALL(*mock_stub, Export(_, _, _)).Times(Exactly(1)).WillOnce(Return(grpc::Status::OK));
auto result = exporter->Export(batch_1);
EXPECT_EQ(sdk::common::ExportResult::kSuccess, result);
// Test failed RPC
nostd::span<std::unique_ptr<sdk::trace::Recordable>> batch_2(&recordable_2, 1);
EXPECT_CALL(*mock_stub, Export(_, _, _))
.Times(Exactly(1))
.WillOnce(Return(grpc::Status::CANCELLED));
result = exporter->Export(batch_2);
EXPECT_EQ(sdk::common::ExportResult::kFailure, result);
}
// Create spans, let processor call Export()
TEST_F(OtlpGrpcExporterTestPeer, ExportIntegrationTest)
{
auto mock_stub = new proto::collector::trace::v1::MockTraceServiceStub();
std::unique_ptr<proto::collector::trace::v1::TraceService::StubInterface> stub_interface(
mock_stub);
auto exporter = GetExporter(stub_interface);
auto processor = std::unique_ptr<sdk::trace::SpanProcessor>(
new sdk::trace::SimpleSpanProcessor(std::move(exporter)));
auto provider = nostd::shared_ptr<trace::TracerProvider>(
new sdk::trace::TracerProvider(std::move(processor)));
auto tracer = provider->GetTracer("test");
EXPECT_CALL(*mock_stub, Export(_, _, _))
.Times(AtLeast(1))
.WillRepeatedly(Return(grpc::Status::OK));
auto parent_span = tracer->StartSpan("Test parent span");
auto child_span = tracer->StartSpan("Test child span");
child_span->End();
parent_span->End();
}
// Test exporter configuration options
TEST_F(OtlpGrpcExporterTestPeer, ConfigTest)
{
OtlpGrpcExporterOptions opts;
opts.endpoint = "localhost:45454";
std::unique_ptr<OtlpGrpcExporter> exporter(new OtlpGrpcExporter(opts));
EXPECT_EQ(GetOptions(exporter).endpoint, "localhost:45454");
}
// Test exporter configuration options with use_ssl_credentials
TEST_F(OtlpGrpcExporterTestPeer, ConfigSslCredentialsTest)
{
std::string cacert_str = "--begin and end fake cert--";
OtlpGrpcExporterOptions opts;
opts.use_ssl_credentials = true;
opts.ssl_credentials_cacert_as_string = cacert_str;
std::unique_ptr<OtlpGrpcExporter> exporter(new OtlpGrpcExporter(opts));
EXPECT_EQ(GetOptions(exporter).ssl_credentials_cacert_as_string, cacert_str);
EXPECT_EQ(GetOptions(exporter).use_ssl_credentials, true);
}
# ifndef NO_GETENV
// Test exporter configuration options with use_ssl_credentials
TEST_F(OtlpGrpcExporterTestPeer, ConfigFromEnv)
{
const std::string cacert_str = "--begin and end fake cert--";
const std::string cacert_env = "OTEL_EXPORTER_OTLP_GRPC_SSL_CERTIFICATE=" + cacert_str;
putenv(const_cast<char *>(cacert_env.data()));
char ssl_enable_env[] = "OTEL_EXPORTER_OTLP_GRPC_SSL_ENABLE=True";
putenv(ssl_enable_env);
const std::string endpoint = "http://localhost:9999";
const std::string endpoint_env = "OTEL_EXPORTER_OTLP_GRPC_ENDPOINT=" + endpoint;
putenv(const_cast<char *>(endpoint_env.data()));
std::unique_ptr<OtlpGrpcExporter> exporter(new OtlpGrpcExporter());
EXPECT_EQ(GetOptions(exporter).ssl_credentials_cacert_as_string, cacert_str);
EXPECT_EQ(GetOptions(exporter).use_ssl_credentials, true);
EXPECT_EQ(GetOptions(exporter).endpoint, endpoint);
# if defined(_MSC_VER)
putenv("OTEL_EXPORTER_OTLP_GRPC_ENDPOINT=");
putenv("OTEL_EXPORTER_OTLP_GRPC_SSL_CERTIFICATE=");
putenv("OTEL_EXPORTER_OTLP_GRPC_SSL_ENABLE=");
# else
unsetenv("OTEL_EXPORTER_OTLP_GRPC_ENDPOINT");
unsetenv("OTEL_EXPORTER_OTLP_GRPC_SSL_CERTIFICATE");
unsetenv("OTEL_EXPORTER_OTLP_GRPC_SSL_ENABLE");
# endif
}
# endif
} // namespace otlp
} // namespace exporter
OPENTELEMETRY_END_NAMESPACE
#endif
<|endoftext|>
|
<commit_before>#include <metaSMT/DirectSolver_Context.hpp>
#include <metaSMT/API/Stack.hpp>
#include <metaSMT/backend/Z3_Backend.hpp>
typedef metaSMT::DirectSolver_Context<metaSMT::Stack<metaSMT::solver::Z3_Backend> > ContextType;
#include "main.cpp"
<commit_msg>removed stack emulation from Z3_Backend SMT-LIB2 evaluator<commit_after>#include <metaSMT/DirectSolver_Context.hpp>
#include <metaSMT/backend/Z3_Backend.hpp>
typedef metaSMT::DirectSolver_Context< metaSMT::solver::Z3_Backend > ContextType;
#include "main.cpp"
<|endoftext|>
|
<commit_before>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation //
// //
// 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 <stdarg.h>
#include <vector>
#include <cstring>
#include "SeismicHorizonFile.h"
SeismicHorizonFile::SeismicHorizonFile(const std::string &filename) :
filename(filename),
scale(ospray::vec3f(1.f)),
verbose(true)
{
}
OSPGeometry SeismicHorizonFile::importTriangleMesh(OSPGeometry triangleMesh)
{
// Get scaling parameter if provided.
ospGetVec3f(triangleMesh, "scale", (osp::vec3f *)&scale);
// Open seismic data file and populate attributes.
exitOnCondition(openSeismicDataFile(triangleMesh) != true,
"unable to open file '" + filename + "'");
// Import the horizon data from the file into the triangle mesh.
exitOnCondition(importHorizonData(triangleMesh) != true,
"error importing horizon data.");
// Return the triangle mesh.
return triangleMesh;
}
std::string SeismicHorizonFile::toString() const
{
return("ospray_module_seismic::SeismicHorizonFile");
}
bool SeismicHorizonFile::openSeismicDataFile(OSPGeometry /*triangleMesh*/)
{
// Open seismic data file, keeping trace header information. //
// Sample types int, short, long, float, and double will be converted to float.
inputBinTag = cddx_in2("in", filename.c_str(), "seismic");
exitOnCondition(inputBinTag < 0, "could not open data file " + filename);
// Get horizon volume dimensions.
exitOnCondition(cdds_scanf("size.axis(1)", "%d", &dimensions.x) != 1,
"could not find size of dimension 1");
exitOnCondition(cdds_scanf("size.axis(2)", "%d", &dimensions.y) != 1,
"could not find size of dimension 2");
exitOnCondition(cdds_scanf("size.axis(3)", "%d", &dimensions.z) != 1,
"could not find size of dimension 3");
if(verbose) {
std::cout << toString() << " " << dimensions.z
<< " horizons, dimensions = " << dimensions.x
<< " " << dimensions.y << std::endl;
}
// Get voxel spacing (deltas).
exitOnCondition(cdds_scanf("delta.axis(1)", "%f", &deltas.x) != 1,
"could not find delta of dimension 1");
exitOnCondition(cdds_scanf("delta.axis(2)", "%f", &deltas.y) != 1,
"could not find delta of dimension 2");
exitOnCondition(cdds_scanf("delta.axis(3)", "%f", &deltas.z) != 1,
"could not find delta of dimension 3");
if(verbose) {
std::cout << toString() << " volume deltas = "
<< deltas.x << " " << deltas.y << " " << deltas.z << std::endl;
}
// Get trace header information.
FIELD_TAG traceSamplesTag = cdds_member(inputBinTag, 0, "Samples");
traceHeaderSize = cdds_index(inputBinTag, traceSamplesTag, DDS_FLOAT);
exitOnCondition(traceSamplesTag == -1 || traceHeaderSize == -1,
"could not get trace header information");
if(verbose) {
std::cout << toString() << " trace header size = " << traceHeaderSize
<< std::endl;
}
// Check that horizon dimensions are valid.
exitOnCondition(dimensions.x <= 1 || dimensions.y <= 1,
"improper horizon dimensions found");
// Need at least one horizon.
exitOnCondition(dimensions.x < 1, "no horizons found");
return true;
}
bool SeismicHorizonFile::importHorizonData(OSPGeometry triangleMesh)
{
// Allocate memory for all traces.
size_t memSize = dimensions.x*dimensions.y*dimensions.z * sizeof(float);
float *volumeBuffer = (float *)malloc(memSize);
exitOnCondition(volumeBuffer == NULL, "failed to allocate volume buffer");
// Allocate trace array; the trace length is given by the trace header size
// and the first dimension. Note that FreeDDS converts all trace data to
// floats.
memSize = (traceHeaderSize + dimensions.x) * sizeof(float);
float *traceBuffer = (float *)malloc(memSize);
exitOnCondition(traceBuffer == NULL, "failed to allocate trace buffer");
// Read all traces and copy them into the volume buffer.
for(long i3=0; i3<dimensions.z; i3++) {
for(long i2=0; i2<dimensions.y; i2++) {
// Read trace.
exitOnCondition(cddx_read(inputBinTag, traceBuffer, 1) != 1,
"unable to read trace");
// Copy trace into the volume buffer.
memcpy((void *)&volumeBuffer[i3*dimensions.y*dimensions.x+i2*dimensions.x],
(const void *) &traceBuffer[traceHeaderSize],
dimensions.x * sizeof(float));
}
}
// Generate triangle mesh for each horizon.
std::vector<ospray::vec3fa> vertices;
std::vector<ospray::vec3fa> vertexNormals;
std::vector<ospray::vec3i> triangles;
for(long h=0; h<dimensions.z; h++) {
// Generate vertices and vertex colors for this horizon.
for(long i2=0; i2<dimensions.y; i2++) {
for(long i1=0; i1<dimensions.x; i1++) {
long index = h*dimensions.y*dimensions.x + i2*dimensions.x + i1;
ospray::vec3fa vertex(volumeBuffer[index] * deltas.z, i1 * deltas.x,
i2 * deltas.y);
// Apply scaling.
vertex *= scale;
vertices.push_back(vertex);
vertexNormals.push_back(ospray::vec3fa(0.f));
}
}
// Generate triangles and vertex normals for this horizon.
for(long i2=0; i2<dimensions.y-1; i2++) {
for(long i1=0; i1<dimensions.x-1; i1++) {
long v0 = h*dimensions.x*dimensions.y + i2 *dimensions.x + i1 ;
long v1 = h*dimensions.x*dimensions.y + i2 *dimensions.x + (i1+1);
long v2 = h*dimensions.x*dimensions.y + (i2+1)*dimensions.x + (i1+1);
long v3 = h*dimensions.x*dimensions.y + (i2+1)*dimensions.x + i1 ;
// Assume horizon height coordinate must be > 0 to be valid.
if (std::min(std::min(vertices[v0].x,
vertices[v1].x),
vertices[v2].x) > 0.f) {
triangles.push_back(ospray::vec3i(v0, v1, v2));
ospray::vec3fa triangleNormal = cross(vertices[v1] - vertices[v0],
vertices[v2] - vertices[v0]);
vNormals[v0] += triangleNormal;
vNormals[v1] += triangleNormal;
vNormals[v2] += triangleNormal;
}
if (std::min(std::min(vertices[v2].x,
vertices[v3].x),
vertices[v0].x) > 0.f) {
triangles.push_back(ospray::vec3i(v2, v3, v0));
ospray::vec3fa triangleNormal = cross(vertices[v3] - vertices[v2],
vertices[v0] - vertices[v2]);
vNormals[v2] += triangleNormal;
vNormals[v3] += triangleNormal;
vNormals[v0] += triangleNormal;
}
}
}
}
// Normalize vertex normals.
for(long i=0; i<vertexNormals.size(); i++)
vertexNormals[i] = normalize(vertexNormals[i]);
// Set data on triangle mesh.
OSPData vertexData = ospNewData(vertices.size(), OSP_FLOAT3A, &vertices[0].x);
ospSetData(triangleMesh, "vertex", vertexData);
OSPData vertexNormalData = ospNewData(vertexNormals.size(),
OSP_FLOAT3A,
&vertexNormals[0].x);
ospSetData(triangleMesh, "vertex.normal", vertexNormalData);
OSPData indexData = ospNewData(triangles.size(), OSP_INT3, &triangles[0].x);
ospSetData(triangleMesh, "index", indexData);
// Clean up.
free(volumeBuffer);
free(traceBuffer);
// Close the seismic data file.
cdds_close(inputBinTag);
return true;
}
<commit_msg>Fix seismic build<commit_after>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation //
// //
// 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 <stdarg.h>
#include <vector>
#include <cstring>
#include "SeismicHorizonFile.h"
SeismicHorizonFile::SeismicHorizonFile(const std::string &filename) :
filename(filename),
scale(ospray::vec3f(1.f)),
verbose(true)
{
}
OSPGeometry SeismicHorizonFile::importTriangleMesh(OSPGeometry triangleMesh)
{
// Get scaling parameter if provided.
ospGetVec3f(triangleMesh, "scale", (osp::vec3f *)&scale);
// Open seismic data file and populate attributes.
exitOnCondition(openSeismicDataFile(triangleMesh) != true,
"unable to open file '" + filename + "'");
// Import the horizon data from the file into the triangle mesh.
exitOnCondition(importHorizonData(triangleMesh) != true,
"error importing horizon data.");
// Return the triangle mesh.
return triangleMesh;
}
std::string SeismicHorizonFile::toString() const
{
return("ospray_module_seismic::SeismicHorizonFile");
}
bool SeismicHorizonFile::openSeismicDataFile(OSPGeometry /*triangleMesh*/)
{
// Open seismic data file, keeping trace header information. //
// Sample types int, short, long, float, and double will be converted to float.
inputBinTag = cddx_in2("in", filename.c_str(), "seismic");
exitOnCondition(inputBinTag < 0, "could not open data file " + filename);
// Get horizon volume dimensions.
exitOnCondition(cdds_scanf("size.axis(1)", "%d", &dimensions.x) != 1,
"could not find size of dimension 1");
exitOnCondition(cdds_scanf("size.axis(2)", "%d", &dimensions.y) != 1,
"could not find size of dimension 2");
exitOnCondition(cdds_scanf("size.axis(3)", "%d", &dimensions.z) != 1,
"could not find size of dimension 3");
if(verbose) {
std::cout << toString() << " " << dimensions.z
<< " horizons, dimensions = " << dimensions.x
<< " " << dimensions.y << std::endl;
}
// Get voxel spacing (deltas).
exitOnCondition(cdds_scanf("delta.axis(1)", "%f", &deltas.x) != 1,
"could not find delta of dimension 1");
exitOnCondition(cdds_scanf("delta.axis(2)", "%f", &deltas.y) != 1,
"could not find delta of dimension 2");
exitOnCondition(cdds_scanf("delta.axis(3)", "%f", &deltas.z) != 1,
"could not find delta of dimension 3");
if(verbose) {
std::cout << toString() << " volume deltas = "
<< deltas.x << " " << deltas.y << " " << deltas.z << std::endl;
}
// Get trace header information.
FIELD_TAG traceSamplesTag = cdds_member(inputBinTag, 0, "Samples");
traceHeaderSize = cdds_index(inputBinTag, traceSamplesTag, DDS_FLOAT);
exitOnCondition(traceSamplesTag == -1 || traceHeaderSize == -1,
"could not get trace header information");
if(verbose) {
std::cout << toString() << " trace header size = " << traceHeaderSize
<< std::endl;
}
// Check that horizon dimensions are valid.
exitOnCondition(dimensions.x <= 1 || dimensions.y <= 1,
"improper horizon dimensions found");
// Need at least one horizon.
exitOnCondition(dimensions.x < 1, "no horizons found");
return true;
}
bool SeismicHorizonFile::importHorizonData(OSPGeometry triangleMesh)
{
// Allocate memory for all traces.
size_t memSize = dimensions.x*dimensions.y*dimensions.z * sizeof(float);
float *volumeBuffer = (float *)malloc(memSize);
exitOnCondition(volumeBuffer == NULL, "failed to allocate volume buffer");
// Allocate trace array; the trace length is given by the trace header size
// and the first dimension. Note that FreeDDS converts all trace data to
// floats.
memSize = (traceHeaderSize + dimensions.x) * sizeof(float);
float *traceBuffer = (float *)malloc(memSize);
exitOnCondition(traceBuffer == NULL, "failed to allocate trace buffer");
// Read all traces and copy them into the volume buffer.
for(long i3=0; i3<dimensions.z; i3++) {
for(long i2=0; i2<dimensions.y; i2++) {
// Read trace.
exitOnCondition(cddx_read(inputBinTag, traceBuffer, 1) != 1,
"unable to read trace");
// Copy trace into the volume buffer.
memcpy((void *)&volumeBuffer[i3*dimensions.y*dimensions.x+i2*dimensions.x],
(const void *) &traceBuffer[traceHeaderSize],
dimensions.x * sizeof(float));
}
}
// Generate triangle mesh for each horizon.
std::vector<ospray::vec3fa> vertices;
std::vector<ospray::vec3fa> vertexNormals;
std::vector<ospray::vec3i> triangles;
for(long h=0; h<dimensions.z; h++) {
// Generate vertices and vertex colors for this horizon.
for(long i2=0; i2<dimensions.y; i2++) {
for(long i1=0; i1<dimensions.x; i1++) {
long index = h*dimensions.y*dimensions.x + i2*dimensions.x + i1;
ospray::vec3fa vertex(volumeBuffer[index] * deltas.z, i1 * deltas.x,
i2 * deltas.y);
// Apply scaling.
vertex *= scale;
vertices.push_back(vertex);
vertexNormals.push_back(ospray::vec3fa(0.f));
}
}
// Generate triangles and vertex normals for this horizon.
for(long i2=0; i2<dimensions.y-1; i2++) {
for(long i1=0; i1<dimensions.x-1; i1++) {
long v0 = h*dimensions.x*dimensions.y + i2 *dimensions.x + i1 ;
long v1 = h*dimensions.x*dimensions.y + i2 *dimensions.x + (i1+1);
long v2 = h*dimensions.x*dimensions.y + (i2+1)*dimensions.x + (i1+1);
long v3 = h*dimensions.x*dimensions.y + (i2+1)*dimensions.x + i1 ;
// Assume horizon height coordinate must be > 0 to be valid.
if (std::min(std::min(vertices[v0].x,
vertices[v1].x),
vertices[v2].x) > 0.f) {
triangles.push_back(ospray::vec3i(v0, v1, v2));
ospray::vec3fa triangleNormal = cross(vertices[v1] - vertices[v0],
vertices[v2] - vertices[v0]);
vertexNormals[v0] += triangleNormal;
vertexNormals[v1] += triangleNormal;
vertexNormals[v2] += triangleNormal;
}
if (std::min(std::min(vertices[v2].x,
vertices[v3].x),
vertices[v0].x) > 0.f) {
triangles.push_back(ospray::vec3i(v2, v3, v0));
ospray::vec3fa triangleNormal = cross(vertices[v3] - vertices[v2],
vertices[v0] - vertices[v2]);
vertexNormals[v2] += triangleNormal;
vertexNormals[v3] += triangleNormal;
vertexNormals[v0] += triangleNormal;
}
}
}
}
// Normalize vertex normals.
for(long i=0; i<vertexNormals.size(); i++)
vertexNormals[i] = normalize(vertexNormals[i]);
// Set data on triangle mesh.
OSPData vertexData = ospNewData(vertices.size(), OSP_FLOAT3A, &vertices[0].x);
ospSetData(triangleMesh, "vertex", vertexData);
OSPData vertexNormalData = ospNewData(vertexNormals.size(),
OSP_FLOAT3A,
&vertexNormals[0].x);
ospSetData(triangleMesh, "vertex.normal", vertexNormalData);
OSPData indexData = ospNewData(triangles.size(), OSP_INT3, &triangles[0].x);
ospSetData(triangleMesh, "index", indexData);
// Clean up.
free(volumeBuffer);
free(traceBuffer);
// Close the seismic data file.
cdds_close(inputBinTag);
return true;
}
<|endoftext|>
|
<commit_before>#include "Component.h"
#include "Simulation.h"
#include "ComponentPostProcessor.h"
unsigned int Component::subdomain_ids = 0;
unsigned int Component::bc_ids = 0;
template<>
InputParameters validParams<Component>()
{
InputParameters params = validParams<R7Object>();
params.addPrivateParam<Simulation *>("_sim");
params.addParam<std::string>("physics_input_file", "Input file with physics");
return params;
}
static unsigned int comp_id = 0;
std::string
Component::genName(const std::string & prefix, unsigned int id, const std::string & suffix)
{
std::stringstream ss;
ss << prefix << id << suffix;
return ss.str();
}
std::string
Component::genName(const std::string & prefix, const std::string & suffix)
{
std::stringstream ss;
ss << prefix << ":" << suffix;
return ss.str();
}
Component::Component(const std::string & name, InputParameters parameters) :
R7Object(name, parameters),
_id(comp_id++),
_sim(*getParam<Simulation *>("_sim")),
_mesh(_sim.mesh()),
_model_type(_sim.getParam<Model::EModelType>("model_type")),
_input_file_name(getParam<std::string>("physics_input_file"))
{
}
Component::~Component()
{
}
void
Component::init()
{
/*
{
InputParameters params = validParams<ComponentPostProcessor>();
params.set<Component*>("Component") = this;
params.set<std::string>("output") = "none";
params.set<std::string>("execute_on") = "residual";
_sim.addPostprocessor("ComponentPostProcessor", genName("ComponentPPS_", _id, "_onResidual"), params);
}
{
InputParameters params = validParams<ComponentPostProcessor>();
params.set<Component*>("Component") = this;
params.set<std::string>("output") = "none";
params.set<std::string>("execute_on") = "timestep_begin";
_sim.addPostprocessor("ComponentPostProcessor", genName("ComponentPPS_", _id, "_onTimestepBegin"), params);
}
{
InputParameters params = validParams<ComponentPostProcessor>();
params.set<Component*>("Component") = this;
params.set<std::string>("output") = "none";
params.set<std::string>("execute_on") = "timestep";
_sim.addPostprocessor("ComponentPostProcessor", genName("ComponentPPS_", _id, "_onTimestepEnd"), params);
}
*/
}
void
Component::parseInput()
{
if (!_input_file_name.empty())
{
// TODO: parse local input file
}
}
unsigned int
Component::getNextSubdomainId()
{
unsigned int sd_id = subdomain_ids++;
_subdomains.push_back(sd_id);
return sd_id;
}
unsigned int
Component::getNextBCId()
{
unsigned int id = bc_ids++;
return id;
}
<commit_msg>Making RELAP-7 compatible with Peacock + dropping its parser (no longer needed)<commit_after>#include "Component.h"
#include "Simulation.h"
#include "ComponentPostProcessor.h"
unsigned int Component::subdomain_ids = 0;
unsigned int Component::bc_ids = 0;
template<>
InputParameters validParams<Component>()
{
InputParameters params = validParams<R7Object>();
params.addPrivateParam<Simulation *>("_sim");
params.addParam<std::string>("physics_input_file", "Input file with physics");
params.addPrivateParam<std::string>("built_by_action", "add_component");
return params;
}
static unsigned int comp_id = 0;
std::string
Component::genName(const std::string & prefix, unsigned int id, const std::string & suffix)
{
std::stringstream ss;
ss << prefix << id << suffix;
return ss.str();
}
std::string
Component::genName(const std::string & prefix, const std::string & suffix)
{
std::stringstream ss;
ss << prefix << ":" << suffix;
return ss.str();
}
Component::Component(const std::string & name, InputParameters parameters) :
R7Object(name, parameters),
_id(comp_id++),
_sim(*getParam<Simulation *>("_sim")),
_mesh(_sim.mesh()),
_model_type(_sim.getParam<Model::EModelType>("model_type")),
_input_file_name(getParam<std::string>("physics_input_file"))
{
}
Component::~Component()
{
}
void
Component::init()
{
/*
{
InputParameters params = validParams<ComponentPostProcessor>();
params.set<Component*>("Component") = this;
params.set<std::string>("output") = "none";
params.set<std::string>("execute_on") = "residual";
_sim.addPostprocessor("ComponentPostProcessor", genName("ComponentPPS_", _id, "_onResidual"), params);
}
{
InputParameters params = validParams<ComponentPostProcessor>();
params.set<Component*>("Component") = this;
params.set<std::string>("output") = "none";
params.set<std::string>("execute_on") = "timestep_begin";
_sim.addPostprocessor("ComponentPostProcessor", genName("ComponentPPS_", _id, "_onTimestepBegin"), params);
}
{
InputParameters params = validParams<ComponentPostProcessor>();
params.set<Component*>("Component") = this;
params.set<std::string>("output") = "none";
params.set<std::string>("execute_on") = "timestep";
_sim.addPostprocessor("ComponentPostProcessor", genName("ComponentPPS_", _id, "_onTimestepEnd"), params);
}
*/
}
void
Component::parseInput()
{
if (!_input_file_name.empty())
{
// TODO: parse local input file
}
}
unsigned int
Component::getNextSubdomainId()
{
unsigned int sd_id = subdomain_ids++;
_subdomains.push_back(sd_id);
return sd_id;
}
unsigned int
Component::getNextBCId()
{
unsigned int id = bc_ids++;
return id;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ldapuserprof.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-09-16 12:57:38 $
*
* 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_extensions.hxx"
#ifndef EXTENSIONS_CONFIG_LDAP_LDAPUSERPROF_HXX_
#include "ldapuserprof.hxx"
#endif // EXTENSIONS_CONFIG_LDAP_LDAPUSERPROF_HXX_
namespace extensions { namespace config { namespace ldap {
//==============================================================================
//------------------------------------------------------------------------------
/**
Finds the next line in a buffer and returns it, along with a
modified version of the buffer with the line removed.
@param aString string to extract the next line from
@param aLine next line
@return sal_True if a line has been extracted, sal_False otherwise
*/
static sal_Bool getNextLine(rtl::OString& aString,
rtl::OString& aLine)
{
aString = aString.trim() ;
const sal_Char *currentChar = aString ;
const sal_Char *endChar = currentChar + aString.getLength() ;
sal_Int32 lineThreshold = 0 ;
while (currentChar < endChar &&
*currentChar != '\r' && *currentChar != '\n') { ++ currentChar ; }
lineThreshold = currentChar - static_cast<const sal_Char *>(aString) ;
if (lineThreshold == 0) { return sal_False ; }
aLine = aString.copy(0, lineThreshold) ;
aString = aString.copy(lineThreshold) ;
return sal_True ;
}
//------------------------------------------------------------------------------
LdapUserProfileMap::~LdapUserProfileMap(void)
{
// No need to delete the contents of the mAttributes array,
// since they refer to rtl::OStrings stored in the mLdapAttributes
// array.
if (mAttributes != NULL)
{
delete [] mAttributes ;
}
}
//------------------------------------------------------------------------------
void LdapUserProfileMap::source(const rtl::OString& aMap)
{
if (mAttributes != NULL)
{
delete [] mAttributes ; mAttributes = NULL ;
mMapping.clear() ;
}
rtl::OString currentLine ;
rtl::OString buffer = aMap ;
std::set<rtl::OString> attributes ;
rtl::OString prefix ;
// First, parse the buffer to find all the mapping definitions.
// While we're at it, we collect the list of unique LDAP attributes
// involved in the mapping.
while (getNextLine(buffer, currentLine))
{
addNewMapping(currentLine, attributes, prefix) ;
}
// Now we use the list of attributes to build mAttributes
mAttributes = new const sal_Char * [attributes.size() + 1] ;
std::set<rtl::OString>::const_iterator attribute ;
sal_Int32 i = 0 ;
for (attribute = attributes.begin() ;
attribute != attributes.end() ; ++ attribute)
{
mAttributes [i ++] = static_cast<const sal_Char *>(*attribute) ;
}
mAttributes [i] = NULL ;
}
//------------------------------------------------------------------------------
void LdapUserProfileMap::ldapToUserProfile(LDAP *aConnection,
LDAPMessage *aEntry,
LdapUserProfile& aProfile) const
{
if (aEntry == NULL) { return ; }
// Ensure return value has proper size
aProfile.mProfile.resize(mMapping.size()) ;
sal_Char **values = NULL ;
for (sal_uInt32 i = 0 ; i < mMapping.size() ; ++ i)
{
aProfile.mProfile [i].mAttribute = rtl::OStringToOUString(
mMapping [i].mProfileElement,
RTL_TEXTENCODING_ASCII_US);
rtl::OUString debugStr = aProfile.mProfile [i].mAttribute;
for (sal_uInt32 j = 0 ;
j < mMapping [i].mLdapAttributes.size() ; ++ j)
{
values = ldap_get_values(aConnection, aEntry,
mMapping [i].mLdapAttributes [j]) ;
if (values != NULL)
{
aProfile.mProfile[i].mValue = rtl::OStringToOUString(
*values, RTL_TEXTENCODING_UTF8);
ldap_value_free(values);
break;
}
}
}
}
//------------------------------------------------------------------------------
void LdapUserProfileMap::addNewMapping(const rtl::OString& aLine,
std::set<rtl::OString>& aLdapAttributes,
rtl::OString& aPrefix)
{
if (aLine.getStr() [0] == '#') { return ; }
sal_Int32 prefixLength = aPrefix.getLength() ;
if (prefixLength == 0)
{
sal_Int32 firstSlash = aLine.indexOf('/') ;
if (firstSlash == -1) { return ; }
sal_Int32 secondSlash = aLine.indexOf('/', firstSlash + 1) ;
if (secondSlash == -1){ return; }
mComponentName =
rtl::OUString::createFromAscii(aLine.copy(0, firstSlash)) ;
mGroupName =
rtl::OUString::createFromAscii(aLine.copy(firstSlash + 1,
secondSlash - firstSlash - 1)) ;
aPrefix = aLine.copy(0, secondSlash + 1) ;
prefixLength = secondSlash + 1 ;
}
else if (aLine.compareTo(aPrefix, prefixLength) != 0)
{
return ;
}
mMapping.push_back(Mapping()) ;
if (!mMapping.back().parse(aLine.copy(prefixLength)))
{
mMapping.pop_back() ;
}
else
{
const std::vector<rtl::OString>& attributes =
mMapping.back().mLdapAttributes ;
std::vector<rtl::OString>::const_iterator ldapAttribute ;
for (ldapAttribute = attributes.begin() ;
ldapAttribute != attributes.end() ; ++ ldapAttribute)
{
aLdapAttributes.insert(*ldapAttribute) ;
}
}
}
//------------------------------------------------------------------------------
static sal_Char kMappingSeparator = '=' ;
static sal_Char kLdapMapSeparator = ',' ;
sal_Bool LdapUserProfileMap::Mapping::parse(const rtl::OString& aLine)
{
sal_Int32 index = aLine.indexOf(kMappingSeparator) ;
if (index == -1)
{
// Imparsable line
return sal_False ;
}
sal_Int32 oldIndex = index + 1 ;
mProfileElement = aLine.copy(0, index).trim() ;
mLdapAttributes.clear() ;
index = aLine.indexOf(kLdapMapSeparator, oldIndex) ;
while (index != -1)
{
mLdapAttributes.push_back(
aLine.copy(oldIndex, index - oldIndex).trim()) ;
oldIndex = index + 1 ;
index = aLine.indexOf(kLdapMapSeparator, oldIndex) ;
}
rtl::OString endOfLine = aLine.copy(oldIndex).trim() ;
if (endOfLine.getLength() > 0)
{
mLdapAttributes.push_back(endOfLine) ;
}
return sal_True ;
}
//------------------------------------------------------------------------------
} } } // extensiond.config.ldap
<commit_msg>INTEGRATION: CWS changefileheader (1.5.276); FILE MERGED 2008/04/01 12:29:42 thb 1.5.276.2: #i85898# Stripping all external header guards 2008/03/31 12:31:25 rt 1.5.276.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: ldapuserprof.cxx,v $
* $Revision: 1.6 $
*
* 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_extensions.hxx"
#include "ldapuserprof.hxx"
namespace extensions { namespace config { namespace ldap {
//==============================================================================
//------------------------------------------------------------------------------
/**
Finds the next line in a buffer and returns it, along with a
modified version of the buffer with the line removed.
@param aString string to extract the next line from
@param aLine next line
@return sal_True if a line has been extracted, sal_False otherwise
*/
static sal_Bool getNextLine(rtl::OString& aString,
rtl::OString& aLine)
{
aString = aString.trim() ;
const sal_Char *currentChar = aString ;
const sal_Char *endChar = currentChar + aString.getLength() ;
sal_Int32 lineThreshold = 0 ;
while (currentChar < endChar &&
*currentChar != '\r' && *currentChar != '\n') { ++ currentChar ; }
lineThreshold = currentChar - static_cast<const sal_Char *>(aString) ;
if (lineThreshold == 0) { return sal_False ; }
aLine = aString.copy(0, lineThreshold) ;
aString = aString.copy(lineThreshold) ;
return sal_True ;
}
//------------------------------------------------------------------------------
LdapUserProfileMap::~LdapUserProfileMap(void)
{
// No need to delete the contents of the mAttributes array,
// since they refer to rtl::OStrings stored in the mLdapAttributes
// array.
if (mAttributes != NULL)
{
delete [] mAttributes ;
}
}
//------------------------------------------------------------------------------
void LdapUserProfileMap::source(const rtl::OString& aMap)
{
if (mAttributes != NULL)
{
delete [] mAttributes ; mAttributes = NULL ;
mMapping.clear() ;
}
rtl::OString currentLine ;
rtl::OString buffer = aMap ;
std::set<rtl::OString> attributes ;
rtl::OString prefix ;
// First, parse the buffer to find all the mapping definitions.
// While we're at it, we collect the list of unique LDAP attributes
// involved in the mapping.
while (getNextLine(buffer, currentLine))
{
addNewMapping(currentLine, attributes, prefix) ;
}
// Now we use the list of attributes to build mAttributes
mAttributes = new const sal_Char * [attributes.size() + 1] ;
std::set<rtl::OString>::const_iterator attribute ;
sal_Int32 i = 0 ;
for (attribute = attributes.begin() ;
attribute != attributes.end() ; ++ attribute)
{
mAttributes [i ++] = static_cast<const sal_Char *>(*attribute) ;
}
mAttributes [i] = NULL ;
}
//------------------------------------------------------------------------------
void LdapUserProfileMap::ldapToUserProfile(LDAP *aConnection,
LDAPMessage *aEntry,
LdapUserProfile& aProfile) const
{
if (aEntry == NULL) { return ; }
// Ensure return value has proper size
aProfile.mProfile.resize(mMapping.size()) ;
sal_Char **values = NULL ;
for (sal_uInt32 i = 0 ; i < mMapping.size() ; ++ i)
{
aProfile.mProfile [i].mAttribute = rtl::OStringToOUString(
mMapping [i].mProfileElement,
RTL_TEXTENCODING_ASCII_US);
rtl::OUString debugStr = aProfile.mProfile [i].mAttribute;
for (sal_uInt32 j = 0 ;
j < mMapping [i].mLdapAttributes.size() ; ++ j)
{
values = ldap_get_values(aConnection, aEntry,
mMapping [i].mLdapAttributes [j]) ;
if (values != NULL)
{
aProfile.mProfile[i].mValue = rtl::OStringToOUString(
*values, RTL_TEXTENCODING_UTF8);
ldap_value_free(values);
break;
}
}
}
}
//------------------------------------------------------------------------------
void LdapUserProfileMap::addNewMapping(const rtl::OString& aLine,
std::set<rtl::OString>& aLdapAttributes,
rtl::OString& aPrefix)
{
if (aLine.getStr() [0] == '#') { return ; }
sal_Int32 prefixLength = aPrefix.getLength() ;
if (prefixLength == 0)
{
sal_Int32 firstSlash = aLine.indexOf('/') ;
if (firstSlash == -1) { return ; }
sal_Int32 secondSlash = aLine.indexOf('/', firstSlash + 1) ;
if (secondSlash == -1){ return; }
mComponentName =
rtl::OUString::createFromAscii(aLine.copy(0, firstSlash)) ;
mGroupName =
rtl::OUString::createFromAscii(aLine.copy(firstSlash + 1,
secondSlash - firstSlash - 1)) ;
aPrefix = aLine.copy(0, secondSlash + 1) ;
prefixLength = secondSlash + 1 ;
}
else if (aLine.compareTo(aPrefix, prefixLength) != 0)
{
return ;
}
mMapping.push_back(Mapping()) ;
if (!mMapping.back().parse(aLine.copy(prefixLength)))
{
mMapping.pop_back() ;
}
else
{
const std::vector<rtl::OString>& attributes =
mMapping.back().mLdapAttributes ;
std::vector<rtl::OString>::const_iterator ldapAttribute ;
for (ldapAttribute = attributes.begin() ;
ldapAttribute != attributes.end() ; ++ ldapAttribute)
{
aLdapAttributes.insert(*ldapAttribute) ;
}
}
}
//------------------------------------------------------------------------------
static sal_Char kMappingSeparator = '=' ;
static sal_Char kLdapMapSeparator = ',' ;
sal_Bool LdapUserProfileMap::Mapping::parse(const rtl::OString& aLine)
{
sal_Int32 index = aLine.indexOf(kMappingSeparator) ;
if (index == -1)
{
// Imparsable line
return sal_False ;
}
sal_Int32 oldIndex = index + 1 ;
mProfileElement = aLine.copy(0, index).trim() ;
mLdapAttributes.clear() ;
index = aLine.indexOf(kLdapMapSeparator, oldIndex) ;
while (index != -1)
{
mLdapAttributes.push_back(
aLine.copy(oldIndex, index - oldIndex).trim()) ;
oldIndex = index + 1 ;
index = aLine.indexOf(kLdapMapSeparator, oldIndex) ;
}
rtl::OString endOfLine = aLine.copy(oldIndex).trim() ;
if (endOfLine.getLength() > 0)
{
mLdapAttributes.push_back(endOfLine) ;
}
return sal_True ;
}
//------------------------------------------------------------------------------
} } } // extensiond.config.ldap
<|endoftext|>
|
<commit_before>// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html
#include "cap_mfx_common.hpp"
// Linux specific
#ifdef __linux__
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#endif
using namespace std;
using namespace cv;
bool DeviceHandler::init(MFXVideoSession &session)
{
mfxStatus res = MFX_ERR_NONE;
mfxIMPL impl = MFX_IMPL_AUTO;
mfxVersion ver = { {19, 1} };
res = session.Init(impl, &ver);
DBG(cout << "MFX SessionInit: " << res << endl);
res = session.QueryIMPL(&impl);
DBG(cout << "MFX QueryIMPL: " << res << " => " << asHex(impl) << endl);
res = session.QueryVersion(&ver);
DBG(cout << "MFX QueryVersion: " << res << " => " << ver.Major << "." << ver.Minor << endl);
if (res != MFX_ERR_NONE)
return false;
return initDeviceSession(session);
}
//==================================================================================================
#ifdef __linux__
VAHandle::VAHandle() {
// TODO: provide a way of modifying this path
const string filename = "/dev/dri/card0";
file = open(filename.c_str(), O_RDWR);
if (file < 0)
CV_Error(Error::StsError, "Can't open file: " + filename);
display = vaGetDisplayDRM(file);
}
VAHandle::~VAHandle() {
if (display) {
vaTerminate(display);
}
if (file >= 0) {
close(file);
}
}
bool VAHandle::initDeviceSession(MFXVideoSession &session) {
int majorVer = 0, minorVer = 0;
VAStatus va_res = vaInitialize(display, &majorVer, &minorVer);
DBG(cout << "vaInitialize: " << va_res << endl << majorVer << '.' << minorVer << endl);
if (va_res == VA_STATUS_SUCCESS) {
mfxStatus mfx_res = session.SetHandle(static_cast<mfxHandleType>(MFX_HANDLE_VA_DISPLAY), display);
DBG(cout << "MFX SetHandle: " << mfx_res << endl);
if (mfx_res == MFX_ERR_NONE) {
return true;
}
}
return false;
}
#endif // __linux__
DeviceHandler * createDeviceHandler()
{
#if defined __linux__
return new VAHandle();
#elif defined _WIN32
return new DXHandle();
#else
return 0;
#endif
}
//==================================================================================================
SurfacePool::SurfacePool(ushort width_, ushort height_, ushort count, const mfxFrameInfo &frameInfo, uchar bpp)
: width(alignSize(width_, 32)),
height(alignSize(height_, 32)),
oneSize(width * height * bpp / 8),
buffers(count * oneSize),
surfaces(count)
{
for(int i = 0; i < count; ++i)
{
mfxFrameSurface1 &surface = surfaces[i];
uint8_t * dataPtr = buffers + oneSize * i;
memset(&surface, 0, sizeof(mfxFrameSurface1));
surface.Info = frameInfo;
surface.Data.Y = dataPtr;
surface.Data.UV = dataPtr + width * height;
surface.Data.PitchLow = width & 0xFFFF;
surface.Data.PitchHigh = (width >> 16) & 0xFFFF;
DBG(cout << "allocate surface " << (void*)&surface << ", Y = " << (void*)dataPtr << " (" << width << "x" << height << ")" << endl);
}
DBG(cout << "Allocated: " << endl
<< "- surface data: " << buffers.size() << " bytes" << endl
<< "- surface headers: " << surfaces.size() * sizeof(mfxFrameSurface1) << " bytes" << endl);
}
SurfacePool::~SurfacePool()
{
}
mfxFrameSurface1 *SurfacePool::getFreeSurface()
{
for(std::vector<mfxFrameSurface1>::iterator i = surfaces.begin(); i != surfaces.end(); ++i)
if (!i->Data.Locked)
return &(*i);
return 0;
}
//==================================================================================================
ReadBitstream::ReadBitstream(const char *filename, size_t maxSize) : drain(false)
{
input.open(filename, std::ios::in | std::ios::binary);
DBG(cout << "Open " << filename << " -> " << input.is_open() << std::endl);
memset(&stream, 0, sizeof(stream));
stream.MaxLength = (mfxU32)maxSize;
stream.Data = new mfxU8[stream.MaxLength];
CV_Assert(stream.Data);
}
ReadBitstream::~ReadBitstream()
{
delete[] stream.Data;
}
bool ReadBitstream::isOpened() const
{
return input.is_open();
}
bool ReadBitstream::isDone() const
{
return input.eof();
}
bool ReadBitstream::read()
{
memmove(stream.Data, stream.Data + stream.DataOffset, stream.DataLength);
stream.DataOffset = 0;
input.read((char*)(stream.Data + stream.DataLength), stream.MaxLength - stream.DataLength);
if (input.eof() || input.good())
{
mfxU32 bytesRead = (mfxU32)input.gcount();
if (bytesRead > 0)
{
stream.DataLength += bytesRead;
DBG(cout << "read " << bytesRead << " bytes" << endl);
return true;
}
}
return false;
}
//==================================================================================================
WriteBitstream::WriteBitstream(const char * filename, size_t maxSize)
{
output.open(filename, std::ios::out | std::ios::binary);
DBG(cout << "BS Open " << filename << " -> " << output.is_open() << std::endl);
memset(&stream, 0, sizeof(stream));
stream.MaxLength = (mfxU32)maxSize;
stream.Data = new mfxU8[stream.MaxLength];
DBG(cout << "BS Allocate " << maxSize << " bytes (" << ((float)maxSize / (1 << 20)) << " Mb)" << endl);
CV_Assert(stream.Data);
}
WriteBitstream::~WriteBitstream()
{
delete[] stream.Data;
}
bool WriteBitstream::write()
{
output.write((char*)(stream.Data + stream.DataOffset), stream.DataLength);
stream.DataLength = 0;
return output.good();
}
bool WriteBitstream::isOpened() const
{
return output.is_open();
}
//==================================================================================================
<commit_msg>Changed VA device in MediaSDK session initialization<commit_after>// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html
#include "cap_mfx_common.hpp"
// Linux specific
#ifdef __linux__
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#endif
using namespace std;
using namespace cv;
bool DeviceHandler::init(MFXVideoSession &session)
{
mfxStatus res = MFX_ERR_NONE;
mfxIMPL impl = MFX_IMPL_AUTO;
mfxVersion ver = { {19, 1} };
res = session.Init(impl, &ver);
DBG(cout << "MFX SessionInit: " << res << endl);
res = session.QueryIMPL(&impl);
DBG(cout << "MFX QueryIMPL: " << res << " => " << asHex(impl) << endl);
res = session.QueryVersion(&ver);
DBG(cout << "MFX QueryVersion: " << res << " => " << ver.Major << "." << ver.Minor << endl);
if (res != MFX_ERR_NONE)
return false;
return initDeviceSession(session);
}
//==================================================================================================
#ifdef __linux__
VAHandle::VAHandle() {
// TODO: provide a way of modifying this path
const string filename = "/dev/dri/renderD128";
file = open(filename.c_str(), O_RDWR);
if (file < 0)
CV_Error(Error::StsError, "Can't open file: " + filename);
display = vaGetDisplayDRM(file);
}
VAHandle::~VAHandle() {
if (display) {
vaTerminate(display);
}
if (file >= 0) {
close(file);
}
}
bool VAHandle::initDeviceSession(MFXVideoSession &session) {
int majorVer = 0, minorVer = 0;
VAStatus va_res = vaInitialize(display, &majorVer, &minorVer);
DBG(cout << "vaInitialize: " << va_res << endl << majorVer << '.' << minorVer << endl);
if (va_res == VA_STATUS_SUCCESS) {
mfxStatus mfx_res = session.SetHandle(static_cast<mfxHandleType>(MFX_HANDLE_VA_DISPLAY), display);
DBG(cout << "MFX SetHandle: " << mfx_res << endl);
if (mfx_res == MFX_ERR_NONE) {
return true;
}
}
return false;
}
#endif // __linux__
DeviceHandler * createDeviceHandler()
{
#if defined __linux__
return new VAHandle();
#elif defined _WIN32
return new DXHandle();
#else
return 0;
#endif
}
//==================================================================================================
SurfacePool::SurfacePool(ushort width_, ushort height_, ushort count, const mfxFrameInfo &frameInfo, uchar bpp)
: width(alignSize(width_, 32)),
height(alignSize(height_, 32)),
oneSize(width * height * bpp / 8),
buffers(count * oneSize),
surfaces(count)
{
for(int i = 0; i < count; ++i)
{
mfxFrameSurface1 &surface = surfaces[i];
uint8_t * dataPtr = buffers + oneSize * i;
memset(&surface, 0, sizeof(mfxFrameSurface1));
surface.Info = frameInfo;
surface.Data.Y = dataPtr;
surface.Data.UV = dataPtr + width * height;
surface.Data.PitchLow = width & 0xFFFF;
surface.Data.PitchHigh = (width >> 16) & 0xFFFF;
DBG(cout << "allocate surface " << (void*)&surface << ", Y = " << (void*)dataPtr << " (" << width << "x" << height << ")" << endl);
}
DBG(cout << "Allocated: " << endl
<< "- surface data: " << buffers.size() << " bytes" << endl
<< "- surface headers: " << surfaces.size() * sizeof(mfxFrameSurface1) << " bytes" << endl);
}
SurfacePool::~SurfacePool()
{
}
mfxFrameSurface1 *SurfacePool::getFreeSurface()
{
for(std::vector<mfxFrameSurface1>::iterator i = surfaces.begin(); i != surfaces.end(); ++i)
if (!i->Data.Locked)
return &(*i);
return 0;
}
//==================================================================================================
ReadBitstream::ReadBitstream(const char *filename, size_t maxSize) : drain(false)
{
input.open(filename, std::ios::in | std::ios::binary);
DBG(cout << "Open " << filename << " -> " << input.is_open() << std::endl);
memset(&stream, 0, sizeof(stream));
stream.MaxLength = (mfxU32)maxSize;
stream.Data = new mfxU8[stream.MaxLength];
CV_Assert(stream.Data);
}
ReadBitstream::~ReadBitstream()
{
delete[] stream.Data;
}
bool ReadBitstream::isOpened() const
{
return input.is_open();
}
bool ReadBitstream::isDone() const
{
return input.eof();
}
bool ReadBitstream::read()
{
memmove(stream.Data, stream.Data + stream.DataOffset, stream.DataLength);
stream.DataOffset = 0;
input.read((char*)(stream.Data + stream.DataLength), stream.MaxLength - stream.DataLength);
if (input.eof() || input.good())
{
mfxU32 bytesRead = (mfxU32)input.gcount();
if (bytesRead > 0)
{
stream.DataLength += bytesRead;
DBG(cout << "read " << bytesRead << " bytes" << endl);
return true;
}
}
return false;
}
//==================================================================================================
WriteBitstream::WriteBitstream(const char * filename, size_t maxSize)
{
output.open(filename, std::ios::out | std::ios::binary);
DBG(cout << "BS Open " << filename << " -> " << output.is_open() << std::endl);
memset(&stream, 0, sizeof(stream));
stream.MaxLength = (mfxU32)maxSize;
stream.Data = new mfxU8[stream.MaxLength];
DBG(cout << "BS Allocate " << maxSize << " bytes (" << ((float)maxSize / (1 << 20)) << " Mb)" << endl);
CV_Assert(stream.Data);
}
WriteBitstream::~WriteBitstream()
{
delete[] stream.Data;
}
bool WriteBitstream::write()
{
output.write((char*)(stream.Data + stream.DataOffset), stream.DataLength);
stream.DataLength = 0;
return output.good();
}
bool WriteBitstream::isOpened() const
{
return output.is_open();
}
//==================================================================================================
<|endoftext|>
|
<commit_before>#include <sstream> // ostringstream
#include <iomanip> // std::setw
#include <stdio.h> // printf
#include "allocore/math/al_Constants.hpp"
#include "allocore/system/al_Time.hpp"
/* Windows */
#if defined(AL_WINDOWS)
#include <windows.h>
/*
Info on Windows timing:
http://windowstimestamp.com/description
*/
/*
// singleton object to force init/quit of timing
static struct TimeSingleton{
TimeSingleton(){ timeBeginPeriod(1); }
~TimeSingleton(){ timeEndPeriod(1); }
} timeSingleton;
// interface to Windows API
static DWORD time_ms(){ return timeGetTime(); }
static void sleep_ms(unsigned long long ms){ Sleep(DWORD(ms)); }
// allocore definitions
al_sec al_time(){ return time_ms() * 1e-3; }
al_nsec al_time_nsec(){ return al_nsec(time_ms()) * al_nsec(1e6); }
void al_sleep(al_sec v){ sleep_ms(v * 1e3); }
void al_sleep_nsec(al_nsec v){ sleep_ms(v / 1e6); }
//*/
//*
static void sleep_ms(unsigned long long ms){ Sleep(DWORD(ms)); }
// Method to supposedly get microsecond sleep
// From: http://blogs.msdn.com/b/cellfish/archive/2008/09/17/sleep-less-than-one-millisecond.aspx
/*
#include <Winsock2.h> // SOCKET
static int sleep_us(long usec){
static bool first = true;
if(first){
first = false;
WORD wVersionRequested = MAKEWORD(1,0);
WSADATA wsaData;
WSAStartup(wVersionRequested, &wsaData);
}
struct timeval tv;
fd_set dummy;
SOCKET s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
FD_ZERO(&dummy);
FD_SET(s, &dummy);
tv.tv_sec = usec/1000000L;
tv.tv_usec = usec%1000000L;
return select(0, 0, 0, &dummy, &tv);
}*/
// system time as 100-nanosecond interval
al_nsec system_time_100ns(){
SYSTEMTIME st;
GetSystemTime(&st);
//printf("%d/%d/%d %d:%d:%d\n", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
FILETIME time;
SystemTimeToFileTime(&st, &time);
//GetSystemTimeAsFileTime(&time);
ULARGE_INTEGER timeULI = {{time.dwLowDateTime, time.dwHighDateTime}};
al_nsec res = timeULI.QuadPart; // in 100-nanosecond intervals
res -= al_nsec(116444736000000000); // convert epoch from 1601 to 1970
return res;
}
al_nsec steady_time_us(){
// Windows 10 and above
//PULONGLONG time;
//QueryInterruptTimePrecise(&time);
LARGE_INTEGER freq; // ticks/second
LARGE_INTEGER time; // tick count
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&time);
// convert ticks to microseconds
time.QuadPart *= 1000000;
time.QuadPart /= freq.QuadPart;
return al_nsec(time.QuadPart);
}
al_sec al_system_time(){ return system_time_100ns() * 1e-7; }
al_nsec al_system_time_nsec(){ return system_time_100ns() * al_nsec(100); }
al_sec al_steady_time(){ return steady_time_us() * 1e-6; }
al_nsec al_steady_time_nsec(){ return steady_time_us() * al_nsec(1e3); }
void al_sleep(al_sec v){ sleep_ms(v * 1e3); }
void al_sleep_nsec(al_nsec v){ sleep_ms(v / 1e6); }
//void al_sleep(al_sec v){ sleep_us(v * 1e6); }
//void al_sleep_nsec(al_nsec v){ sleep_us(v / 1e3); }
//*/
/* Posix (Mac, Linux) */
#else
#include <time.h> // nanosleep, clock_gettime
#include <sys/time.h> // gettimeofday
#include <unistd.h> // _POSIX_TIMERS
al_sec al_system_time(){
timeval t;
gettimeofday(&t, NULL);
return al_sec(t.tv_sec) + al_sec(t.tv_usec) * 1e-6;
}
al_nsec al_system_time_nsec(){
timeval t;
gettimeofday(&t, NULL);
return al_nsec(t.tv_sec) * al_nsec(1e9) + al_nsec(t.tv_usec) * al_nsec(1e3);
}
#ifdef AL_OSX
#include <mach/mach_time.h>
// Code from:
// http://stackoverflow.com/questions/23378063/how-can-i-use-mach-absolute-time-without-overflowing
al_sec al_steady_time(){
return al_steady_time_nsec() * 1e-9;
}
al_nsec al_steady_time_nsec(){
uint64_t now = mach_absolute_time();
static struct Data {
Data(uint64_t bias_) : bias(bias_) {
mach_timebase_info(&tb);
if (tb.denom > 1024) {
double frac = (double)tb.numer/tb.denom;
tb.denom = 1024;
tb.numer = tb.denom * frac + 0.5;
}
}
mach_timebase_info_data_t tb;
uint64_t bias;
} data(now);
return (now - data.bias) * data.tb.numer / data.tb.denom;
}
// Posix timers available?
#elif _POSIX_TIMERS > 0 && defined(_POSIX_MONOTONIC_CLOCK)
al_sec al_steady_time(){
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return al_sec(t.tv_sec) + al_sec(t.tv_nsec) * 1e-9;
}
al_nsec al_steady_time_nsec(){
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return al_nsec(t.tv_sec) * al_nsec(1e9) + al_nsec(t.tv_nsec);
}
// Otherwise fallback to system time
#else
al_sec al_steady_time(){
return al_system_time();
}
al_nsec al_steady_time_nsec(){
return al_system_time_nsec();
}
#endif
void al_sleep(al_sec v) {
time_t sec = time_t(v);
al_nsec nsec = al_time_s2ns * (v - al_sec(sec));
timespec tspec = { sec, long(nsec) };
while (nanosleep(&tspec, &tspec) == -1)
continue;
}
void al_sleep_nsec(al_nsec v) {
al_sleep(al_sec(v) * al_time_ns2s);
}
#endif
/* end platform specific */
void al_sleep_until(al_sec target) {
al_sec dt = target - al_time();
if (dt > 0) al_sleep(dt);
}
al_sec al_time(){ return al_system_time(); }
al_nsec al_time_nsec(){ return al_system_time_nsec(); }
namespace al {
std::string toTimecode(al_nsec t, const std::string& format){
unsigned day = t/(al_nsec(1000000000) * 60 * 60 * 24); // basically for overflow
unsigned hrs = t/(al_nsec(1000000000) * 60 * 60) % 24;
unsigned min = t/(al_nsec(1000000000) * 60) % 60;
unsigned sec = t/(al_nsec(1000000000)) % 60;
unsigned msc = t/(al_nsec(1000000)) % 1000;
unsigned usc = t/(al_nsec(1000)) % 1000;
std::ostringstream s;
s.fill('0');
for(unsigned i=0; i<format.size(); ++i){
const auto c = format[i];
switch(c){
case 'D': s << day; break;
case 'H': s << std::setw(2) << hrs; break;
case 'M': s << std::setw(2) << min; break;
case 'S': s << std::setw(2) << sec; break;
case 'm': s << std::setw(3) << msc; break;
case 'u': s << std::setw(3) << usc; break;
default: s << c;
}
}
return s.str();
}
std::string timecodeNow(const std::string& format){
return toTimecode(al_system_time_nsec(), format);
}
void Timer::print() const {
auto t = getTime();
auto dt = t-mStart;
double dtSec = al_time_ns2s * dt;
printf("%g sec (%g ms) elapsed\n", dtSec, dtSec*1000.);
}
void DelayLockedLoop :: setBandwidth(double bandwidth) {
double F = 1./tperiod; // step rate
double omega = M_PI * 2.8 * bandwidth/F;
mB = omega * sqrt(2.); // 1st-order weight
mC = omega * omega; // 2nd-order weight
}
void DelayLockedLoop :: step(al_sec realtime) {
if (mReset) {
// The first iteration sets initial conditions.
// init loop
t2 = tperiod;
t0 = realtime;
t1 = t0 + t2; // t1 is ideally the timestamp of the next block start
// subsequent iterations use the other branch:
mReset = false;
} else {
// read timer and calculate loop error
// e.g. if t1 underestimated, terr will be
al_sec terr = realtime - t1;
// update loop
t0 = t1; // 0th-order (distance)
t1 += mB * terr + t2; // integration of 1st-order (velocity)
t2 += mC * terr; // integration of 2nd-order (acceleration)
}
// // now t0 is the current system time, and t1 is the estimated system time at the next step
// //
// al_sec tper_estimate = t1-t0; // estimated real duration between this step & the next one
// double factor = tperiod/tper_estimate; // <1 if we are too slow, >1 if we are too fast
// double real_rate = 1./tper_estimate;
// al_sec tper_estimate2 = t2; // estimated real duration between this step & the next one
// double factor2 = 1./t2; // <1 if we are too slow, >1 if we are too fast
// printf("factor %f %f rate %f\n", factor, factor2, real_rate);
}
} // al::
<commit_msg>Change timecode 'D' field from epoch days to YYYYMMDD<commit_after>#include <sstream> // ostringstream
#include <iomanip> // std::setw
#include <stdio.h> // printf
#include "allocore/math/al_Constants.hpp"
#include "allocore/system/al_Time.hpp"
/* Windows */
#if defined(AL_WINDOWS)
#include <windows.h>
/*
Info on Windows timing:
http://windowstimestamp.com/description
*/
/*
// singleton object to force init/quit of timing
static struct TimeSingleton{
TimeSingleton(){ timeBeginPeriod(1); }
~TimeSingleton(){ timeEndPeriod(1); }
} timeSingleton;
// interface to Windows API
static DWORD time_ms(){ return timeGetTime(); }
static void sleep_ms(unsigned long long ms){ Sleep(DWORD(ms)); }
// allocore definitions
al_sec al_time(){ return time_ms() * 1e-3; }
al_nsec al_time_nsec(){ return al_nsec(time_ms()) * al_nsec(1e6); }
void al_sleep(al_sec v){ sleep_ms(v * 1e3); }
void al_sleep_nsec(al_nsec v){ sleep_ms(v / 1e6); }
//*/
//*
static void sleep_ms(unsigned long long ms){ Sleep(DWORD(ms)); }
// Method to supposedly get microsecond sleep
// From: http://blogs.msdn.com/b/cellfish/archive/2008/09/17/sleep-less-than-one-millisecond.aspx
/*
#include <Winsock2.h> // SOCKET
static int sleep_us(long usec){
static bool first = true;
if(first){
first = false;
WORD wVersionRequested = MAKEWORD(1,0);
WSADATA wsaData;
WSAStartup(wVersionRequested, &wsaData);
}
struct timeval tv;
fd_set dummy;
SOCKET s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
FD_ZERO(&dummy);
FD_SET(s, &dummy);
tv.tv_sec = usec/1000000L;
tv.tv_usec = usec%1000000L;
return select(0, 0, 0, &dummy, &tv);
}*/
// system time as 100-nanosecond interval
al_nsec system_time_100ns(){
SYSTEMTIME st;
GetSystemTime(&st);
//printf("%d/%d/%d %d:%d:%d\n", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
FILETIME time;
SystemTimeToFileTime(&st, &time);
//GetSystemTimeAsFileTime(&time);
ULARGE_INTEGER timeULI = {{time.dwLowDateTime, time.dwHighDateTime}};
al_nsec res = timeULI.QuadPart; // in 100-nanosecond intervals
res -= al_nsec(116444736000000000); // convert epoch from 1601 to 1970
return res;
}
al_nsec steady_time_us(){
// Windows 10 and above
//PULONGLONG time;
//QueryInterruptTimePrecise(&time);
LARGE_INTEGER freq; // ticks/second
LARGE_INTEGER time; // tick count
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&time);
// convert ticks to microseconds
time.QuadPart *= 1000000;
time.QuadPart /= freq.QuadPart;
return al_nsec(time.QuadPart);
}
al_sec al_system_time(){ return system_time_100ns() * 1e-7; }
al_nsec al_system_time_nsec(){ return system_time_100ns() * al_nsec(100); }
al_sec al_steady_time(){ return steady_time_us() * 1e-6; }
al_nsec al_steady_time_nsec(){ return steady_time_us() * al_nsec(1e3); }
void al_sleep(al_sec v){ sleep_ms(v * 1e3); }
void al_sleep_nsec(al_nsec v){ sleep_ms(v / 1e6); }
//void al_sleep(al_sec v){ sleep_us(v * 1e6); }
//void al_sleep_nsec(al_nsec v){ sleep_us(v / 1e3); }
//*/
/* Posix (Mac, Linux) */
#else
#include <time.h> // nanosleep, clock_gettime
#include <sys/time.h> // gettimeofday
#include <unistd.h> // _POSIX_TIMERS
al_sec al_system_time(){
timeval t;
gettimeofday(&t, NULL);
return al_sec(t.tv_sec) + al_sec(t.tv_usec) * 1e-6;
}
al_nsec al_system_time_nsec(){
timeval t;
gettimeofday(&t, NULL);
return al_nsec(t.tv_sec) * al_nsec(1e9) + al_nsec(t.tv_usec) * al_nsec(1e3);
}
#ifdef AL_OSX
#include <mach/mach_time.h>
// Code from:
// http://stackoverflow.com/questions/23378063/how-can-i-use-mach-absolute-time-without-overflowing
al_sec al_steady_time(){
return al_steady_time_nsec() * 1e-9;
}
al_nsec al_steady_time_nsec(){
uint64_t now = mach_absolute_time();
static struct Data {
Data(uint64_t bias_) : bias(bias_) {
mach_timebase_info(&tb);
if (tb.denom > 1024) {
double frac = (double)tb.numer/tb.denom;
tb.denom = 1024;
tb.numer = tb.denom * frac + 0.5;
}
}
mach_timebase_info_data_t tb;
uint64_t bias;
} data(now);
return (now - data.bias) * data.tb.numer / data.tb.denom;
}
// Posix timers available?
#elif _POSIX_TIMERS > 0 && defined(_POSIX_MONOTONIC_CLOCK)
al_sec al_steady_time(){
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return al_sec(t.tv_sec) + al_sec(t.tv_nsec) * 1e-9;
}
al_nsec al_steady_time_nsec(){
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return al_nsec(t.tv_sec) * al_nsec(1e9) + al_nsec(t.tv_nsec);
}
// Otherwise fallback to system time
#else
al_sec al_steady_time(){
return al_system_time();
}
al_nsec al_steady_time_nsec(){
return al_system_time_nsec();
}
#endif
void al_sleep(al_sec v) {
time_t sec = time_t(v);
al_nsec nsec = al_time_s2ns * (v - al_sec(sec));
timespec tspec = { sec, long(nsec) };
while (nanosleep(&tspec, &tspec) == -1)
continue;
}
void al_sleep_nsec(al_nsec v) {
al_sleep(al_sec(v) * al_time_ns2s);
}
#endif
/* end platform specific */
void al_sleep_until(al_sec target) {
al_sec dt = target - al_time();
if (dt > 0) al_sleep(dt);
}
al_sec al_time(){ return al_system_time(); }
al_nsec al_time_nsec(){ return al_system_time_nsec(); }
namespace al {
struct Date{
int year, month, day;
};
// z is number of days since 1970-01-01
// From http://howardhinnant.github.io/date_algorithms.html
Date daysToDate(int z){
Date date;
auto &y = date.year, &m = date.month, &d = date.day;
z += 719468;
const int era = (z >= 0 ? z : z - 146096) / 146097;
const unsigned doe = static_cast<unsigned>(z - era * 146097); // [0, 146096]
const unsigned yoe = (doe - doe/1460 + doe/36524 - doe/146096) / 365; // [0, 399]
y = static_cast<int>(yoe) + era * 400;
const unsigned doy = doe - (365*yoe + yoe/4 - yoe/100); // [0, 365]
const unsigned mp = (5*doy + 2)/153; // [0, 11]
d = doy - (153*mp+2)/5 + 1; // [1, 31]
m = mp + (mp < 10 ? 3 : -9); // [1, 12]
y = y + (m <= 2);
return date;
}
std::string toTimecode(al_nsec t, const std::string& format){
unsigned day = t/(al_nsec(1000000000) * 60 * 60 * 24); // basically for overflow
unsigned hrs = t/(al_nsec(1000000000) * 60 * 60) % 24;
unsigned min = t/(al_nsec(1000000000) * 60) % 60;
unsigned sec = t/(al_nsec(1000000000)) % 60;
unsigned msc = t/(al_nsec(1000000)) % 1000;
unsigned usc = t/(al_nsec(1000)) % 1000;
std::ostringstream s;
s.fill('0');
for(unsigned i=0; i<format.size(); ++i){
const auto c = format[i];
switch(c){
case 'D':{
auto date = daysToDate(day);
s << std::setw(4) << date.year;
s << std::setw(2) << date.month;
s << std::setw(2) << date.day;
} break;
case 'H': s << std::setw(2) << hrs; break;
case 'M': s << std::setw(2) << min; break;
case 'S': s << std::setw(2) << sec; break;
case 'm': s << std::setw(3) << msc; break;
case 'u': s << std::setw(3) << usc; break;
default: s << c; // delimiter
}
}
return s.str();
}
std::string timecodeNow(const std::string& format){
return toTimecode(al_system_time_nsec(), format);
}
void Timer::print() const {
auto t = getTime();
auto dt = t-mStart;
double dtSec = al_time_ns2s * dt;
printf("%g sec (%g ms) elapsed\n", dtSec, dtSec*1000.);
}
void DelayLockedLoop :: setBandwidth(double bandwidth) {
double F = 1./tperiod; // step rate
double omega = M_PI * 2.8 * bandwidth/F;
mB = omega * sqrt(2.); // 1st-order weight
mC = omega * omega; // 2nd-order weight
}
void DelayLockedLoop :: step(al_sec realtime) {
if (mReset) {
// The first iteration sets initial conditions.
// init loop
t2 = tperiod;
t0 = realtime;
t1 = t0 + t2; // t1 is ideally the timestamp of the next block start
// subsequent iterations use the other branch:
mReset = false;
} else {
// read timer and calculate loop error
// e.g. if t1 underestimated, terr will be
al_sec terr = realtime - t1;
// update loop
t0 = t1; // 0th-order (distance)
t1 += mB * terr + t2; // integration of 1st-order (velocity)
t2 += mC * terr; // integration of 2nd-order (acceleration)
}
// // now t0 is the current system time, and t1 is the estimated system time at the next step
// //
// al_sec tper_estimate = t1-t0; // estimated real duration between this step & the next one
// double factor = tperiod/tper_estimate; // <1 if we are too slow, >1 if we are too fast
// double real_rate = 1./tper_estimate;
// al_sec tper_estimate2 = t2; // estimated real duration between this step & the next one
// double factor2 = 1./t2; // <1 if we are too slow, >1 if we are too fast
// printf("factor %f %f rate %f\n", factor, factor2, real_rate);
}
} // al::
<|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/basictypes.h"
#include "base/file_util.h"
#include "base/string_util.h"
#include "net/disk_cache/disk_cache_test_base.h"
#include "net/disk_cache/disk_cache_test_util.h"
#include "net/disk_cache/mapped_file.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
int g_cache_tests_max_id;
volatile int g_cache_tests_received;
volatile bool g_cache_tests_error;
// Implementation of FileIOCallback for the tests.
class FileCallbackTest: public disk_cache::FileIOCallback {
public:
explicit FileCallbackTest(int id) : id_(id), reuse_(0) {}
explicit FileCallbackTest(int id, bool reuse)
: id_(id), reuse_(reuse_ ? 0 : 1) {}
~FileCallbackTest() {}
virtual void OnFileIOComplete(int bytes_copied);
private:
int id_;
int reuse_;
};
void FileCallbackTest::OnFileIOComplete(int bytes_copied) {
if (id_ > g_cache_tests_max_id) {
NOTREACHED();
g_cache_tests_error = true;
} else if (reuse_) {
DCHECK(1 == reuse_);
if (2 == reuse_)
g_cache_tests_error = true;
reuse_++;
}
g_cache_tests_received++;
}
// Wait up to 2 secs without callbacks, or until we receive expected callbacks.
void WaitForCallbacks(int expected) {
if (!expected)
return;
#if defined(OS_WIN)
int iterations = 0;
int last = 0;
while (iterations < 40) {
SleepEx(50, TRUE);
if (expected == g_cache_tests_received)
return;
if (last == g_cache_tests_received)
iterations++;
else
iterations = 0;
}
#elif defined(OS_POSIX)
// TODO(rvargas): Do something when async IO is implemented.
#endif
}
} // namespace
TEST_F(DiskCacheTest, MappedFile_SyncIO) {
FilePath filename = GetCacheFilePath().AppendASCII("a_test");
scoped_refptr<disk_cache::MappedFile> file(new disk_cache::MappedFile);
ASSERT_TRUE(CreateCacheTestFile(filename));
ASSERT_TRUE(file->Init(filename, 8192));
char buffer1[20];
char buffer2[20];
CacheTestFillBuffer(buffer1, sizeof(buffer1), false);
base::strlcpy(buffer1, "the data", arraysize(buffer1));
EXPECT_TRUE(file->Write(buffer1, sizeof(buffer1), 8192));
EXPECT_TRUE(file->Read(buffer2, sizeof(buffer2), 8192));
EXPECT_STREQ(buffer1, buffer2);
}
TEST_F(DiskCacheTest, MappedFile_AsyncIO) {
FilePath filename = GetCacheFilePath().AppendASCII("a_test");
scoped_refptr<disk_cache::MappedFile> file(new disk_cache::MappedFile);
ASSERT_TRUE(CreateCacheTestFile(filename));
ASSERT_TRUE(file->Init(filename, 8192));
FileCallbackTest callback(1);
g_cache_tests_error = false;
g_cache_tests_max_id = 0;
g_cache_tests_received = 0;
MessageLoopHelper helper;
char buffer1[20];
char buffer2[20];
CacheTestFillBuffer(buffer1, sizeof(buffer1), false);
base::strlcpy(buffer1, "the data", arraysize(buffer1));
bool completed;
EXPECT_TRUE(file->Write(buffer1, sizeof(buffer1), 1024 * 1024, &callback,
&completed));
int expected = completed ? 0 : 1;
g_cache_tests_max_id = 1;
helper.WaitUntilCacheIoFinished(expected);
EXPECT_TRUE(file->Read(buffer2, sizeof(buffer2), 1024 * 1024, &callback,
&completed));
if (!completed)
expected++;
helper.WaitUntilCacheIoFinished(expected);
EXPECT_EQ(expected, g_cache_tests_received);
EXPECT_FALSE(g_cache_tests_error);
EXPECT_STREQ(buffer1, buffer2);
}
<commit_msg>Disk cache: Remove some dead code.<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/basictypes.h"
#include "base/file_util.h"
#include "base/string_util.h"
#include "net/disk_cache/disk_cache_test_base.h"
#include "net/disk_cache/disk_cache_test_util.h"
#include "net/disk_cache/mapped_file.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
int g_cache_tests_max_id;
volatile int g_cache_tests_received;
volatile bool g_cache_tests_error;
// Implementation of FileIOCallback for the tests.
class FileCallbackTest: public disk_cache::FileIOCallback {
public:
explicit FileCallbackTest(int id) : id_(id) {}
~FileCallbackTest() {}
virtual void OnFileIOComplete(int bytes_copied);
private:
int id_;
};
void FileCallbackTest::OnFileIOComplete(int bytes_copied) {
if (id_ > g_cache_tests_max_id) {
NOTREACHED();
g_cache_tests_error = true;
}
g_cache_tests_received++;
}
// Wait up to 2 secs without callbacks, or until we receive expected callbacks.
void WaitForCallbacks(int expected) {
if (!expected)
return;
#if defined(OS_WIN)
int iterations = 0;
int last = 0;
while (iterations < 40) {
SleepEx(50, TRUE);
if (expected == g_cache_tests_received)
return;
if (last == g_cache_tests_received)
iterations++;
else
iterations = 0;
}
#elif defined(OS_POSIX)
// TODO(rvargas): Do something when async IO is implemented.
#endif
}
} // namespace
TEST_F(DiskCacheTest, MappedFile_SyncIO) {
FilePath filename = GetCacheFilePath().AppendASCII("a_test");
scoped_refptr<disk_cache::MappedFile> file(new disk_cache::MappedFile);
ASSERT_TRUE(CreateCacheTestFile(filename));
ASSERT_TRUE(file->Init(filename, 8192));
char buffer1[20];
char buffer2[20];
CacheTestFillBuffer(buffer1, sizeof(buffer1), false);
base::strlcpy(buffer1, "the data", arraysize(buffer1));
EXPECT_TRUE(file->Write(buffer1, sizeof(buffer1), 8192));
EXPECT_TRUE(file->Read(buffer2, sizeof(buffer2), 8192));
EXPECT_STREQ(buffer1, buffer2);
}
TEST_F(DiskCacheTest, MappedFile_AsyncIO) {
FilePath filename = GetCacheFilePath().AppendASCII("a_test");
scoped_refptr<disk_cache::MappedFile> file(new disk_cache::MappedFile);
ASSERT_TRUE(CreateCacheTestFile(filename));
ASSERT_TRUE(file->Init(filename, 8192));
FileCallbackTest callback(1);
g_cache_tests_error = false;
g_cache_tests_max_id = 0;
g_cache_tests_received = 0;
MessageLoopHelper helper;
char buffer1[20];
char buffer2[20];
CacheTestFillBuffer(buffer1, sizeof(buffer1), false);
base::strlcpy(buffer1, "the data", arraysize(buffer1));
bool completed;
EXPECT_TRUE(file->Write(buffer1, sizeof(buffer1), 1024 * 1024, &callback,
&completed));
int expected = completed ? 0 : 1;
g_cache_tests_max_id = 1;
helper.WaitUntilCacheIoFinished(expected);
EXPECT_TRUE(file->Read(buffer2, sizeof(buffer2), 1024 * 1024, &callback,
&completed));
if (!completed)
expected++;
helper.WaitUntilCacheIoFinished(expected);
EXPECT_EQ(expected, g_cache_tests_received);
EXPECT_FALSE(g_cache_tests_error);
EXPECT_STREQ(buffer1, buffer2);
}
<|endoftext|>
|
<commit_before>#include "ofMain.h"
#include "ofxSmartOscSender.h"
#include "ofxMultiOscSender.h"
using namespace bbb::ofxOscMessageStreamOperators;
class ofxSmartOscSenderExampleApp : public ofBaseApp {
ofxMultiOscSender sender;
ofxOscReceiver receiver;
public:
void setup() {
sender.addTarget("localhost", 9006);
sender.addTarget("localhost", 9005);
receiver.setup(9006);
}
void update() {
ofxOscMessage m;
if(ofGetFrameNum() % 60 == 0) {
sender.sendAsSimpleFormat("/framerate", ofGetFrameNum(), "aaa");
char c = rand();
sender.sendAsStrictFormat("/random", c);
m.setAddress("/stream");
m << '0' << 1 << 2l << 3.0f << 4.0 << "5";
sender.sendMessage(m);
}
while(receiver.hasWaitingMessages()) {
receiver.getNextMessage(m);
const string &address = m.getAddress();
if(address == "/framerate") {
std::cout << address << ": "
<< m.getArgTypeName(0) << ":" << m.getArgAsInt32(0) << ", "
<< m.getArgTypeName(1) << ":" << m.getArgAsString(1)
<< std::endl;
}
else if(address == "/random") {
std::cout << address << ": "
<< m.getArgTypeName(0) << ":" << (int)m.getArgAsChar(0)
<< std::endl;
}
else if(address == "/stream") {
std::cout << address << ": "
<< m.getArgTypeName(0) << ":" << (int)m.getArgAsChar(0) << ", "
<< m.getArgTypeName(1) << ":" << m.getArgAsInt32(1) << ", "
<< m.getArgTypeName(2) << ":" << m.getArgAsInt64(2) << ", "
<< m.getArgTypeName(3) << ":" << m.getArgAsFloat(3) << ", "
<< m.getArgTypeName(4) << ":" << m.getArgAsDouble(4) << ", "
<< m.getArgTypeName(5) << ":" << m.getArgAsString(5) << ", "
<< std::endl;
}
}
}
};
int main() {
ofSetupOpenGL(1280, 720, OF_WINDOW);
ofRunApp(new ofxSmartOscSenderExampleApp);
}
<commit_msg>update example<commit_after>#include "ofMain.h"
#include "ofxSmartOscSender.h"
#include "ofxMultiOscSender.h"
using namespace bbb::ofxOscMessageStrictStreamOperators;
class ofxSmartOscSenderExampleApp : public ofBaseApp {
ofxMultiOscSender sender;
ofxOscReceiver receiver;
public:
void setup() {
sender.addTarget("localhost", 9006);
sender.addTarget("localhost", 9005);
receiver.setup(9006);
}
void update() {
ofxOscMessage m;
if(ofGetFrameNum() % 60 == 0) {
sender.sendAsSimpleFormat("/framerate", ofGetFrameNum(), "aaa");
char c = rand();
sender.sendAsStrictFormat("/random", c);
m.setAddress("/stream");
m << '0' << 1 << 2l << 3.0f << 4.0 << "5";
sender.sendMessage(m);
sender.setUsingStrictFormat(true);
sender("/sender_stream") << '0' << 1 << 2l << 3.0f << 4.0 << "5" << bbb::send;
sender.setUsingStrictFormat(false);
sender << '0' << 1 << 2l << 3.0f << 4.0 << "5" << bbb::send("/sender_stream2");
}
while(receiver.hasWaitingMessages()) {
receiver.getNextMessage(m);
const string &address = m.getAddress();
if(address == "/framerate") {
std::cout << address << ": "
<< m.getArgTypeName(0) << ":" << m.getArgAsInt32(0) << ", "
<< m.getArgTypeName(1) << ":" << m.getArgAsString(1)
<< std::endl;
}
else if(address == "/random") {
std::cout << address << ": "
<< m.getArgTypeName(0) << ":" << (int)m.getArgAsChar(0)
<< std::endl;
}
else if(address == "/stream" || address == "/sender_stream") {
std::cout << address << ": "
<< m.getArgTypeName(0) << ":" << (int)m.getArgAsChar(0) << ", "
<< m.getArgTypeName(1) << ":" << m.getArgAsInt32(1) << ", "
<< m.getArgTypeName(2) << ":" << m.getArgAsInt64(2) << ", "
<< m.getArgTypeName(3) << ":" << m.getArgAsFloat(3) << ", "
<< m.getArgTypeName(4) << ":" << m.getArgAsDouble(4) << ", "
<< m.getArgTypeName(5) << ":" << m.getArgAsString(5)
<< std::endl;
}
else if(address == "/sender_stream2") {
std::cout << address << ": "
<< m.getArgTypeName(0) << ":" << m.getArgAsInt32(0) << ", "
<< m.getArgTypeName(1) << ":" << m.getArgAsInt32(1) << ", "
<< m.getArgTypeName(2) << ":" << m.getArgAsInt32(2) << ", "
<< m.getArgTypeName(3) << ":" << m.getArgAsFloat(3) << ", "
<< m.getArgTypeName(4) << ":" << m.getArgAsFloat(4) << ", "
<< m.getArgTypeName(5) << ":" << m.getArgAsString(5)
<< std::endl;
}
}
}
};
int main() {
ofSetupOpenGL(1280, 720, OF_WINDOW);
ofRunApp(new ofxSmartOscSenderExampleApp);
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
#include "oox/drawingml/textparagraph.hxx"
#include "oox/drawingml/drawingmltypes.hxx"
#include "oox/drawingml/textcharacterproperties.hxx"
#include <rtl/ustring.hxx>
#include "oox/helper/propertyset.hxx"
#include <com/sun/star/text/XText.hpp>
#include <com/sun/star/text/XTextCursor.hpp>
#include <com/sun/star/text/ControlCharacter.hpp>
using ::rtl::OUString;
using namespace ::com::sun::star::text;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::frame;
namespace oox { namespace drawingml {
TextParagraph::TextParagraph()
{
}
TextParagraph::~TextParagraph()
{
}
void TextParagraph::insertAt(
const ::oox::core::XmlFilterBase& rFilterBase,
const Reference < XText > &xText,
const Reference < XTextCursor > &xAt,
const TextCharacterProperties& rTextStyleProperties,
const TextListStyle& rTextListStyle, bool bFirst) const
{
try {
sal_Int32 nParagraphSize = 0;
Reference< XTextRange > xStart( xAt, UNO_QUERY );
sal_Int16 nLevel = maProperties.getLevel();
SAL_INFO("oox", "TextParagraph::insertAt() - level " << nLevel);
const TextParagraphPropertiesVector& rListStyle = rTextListStyle.getListStyle();
if ( nLevel >= static_cast< sal_Int16 >( rListStyle.size() ) )
nLevel = 0;
TextParagraphPropertiesPtr pTextParagraphStyle;
if ( rListStyle.size() )
pTextParagraphStyle = rListStyle[ nLevel ];
TextCharacterProperties aTextCharacterStyle;
if ( pTextParagraphStyle.get() )
aTextCharacterStyle.assignUsed( pTextParagraphStyle->getTextCharacterProperties() );
aTextCharacterStyle.assignUsed( rTextStyleProperties );
aTextCharacterStyle.assignUsed( maProperties.getTextCharacterProperties() );
if( !bFirst )
{
xText->insertControlCharacter( xStart, ControlCharacter::APPEND_PARAGRAPH, sal_False );
xAt->gotoEnd( sal_True );
}
sal_Int32 nCharHeight = 0;
if ( maRuns.begin() == maRuns.end() )
{
PropertySet aPropSet( xStart );
TextCharacterProperties aTextCharacterProps( aTextCharacterStyle );
aTextCharacterProps.assignUsed( maEndProperties );
if ( aTextCharacterProps.moHeight.has() )
nCharHeight = aTextCharacterProps.moHeight.get();
aTextCharacterProps.pushToPropSet( aPropSet, rFilterBase );
}
else
{
for( TextRunVector::const_iterator aIt = maRuns.begin(), aEnd = maRuns.end(); aIt != aEnd; ++aIt )
{
sal_Int32 nLen = (*aIt)->getText().getLength();
// n#759180: Force use, maEndProperties for the last segment
// This is currently applied to only empty runs
if( !nLen && ( ( aIt + 1 ) == aEnd ) )
(*aIt)->getTextCharacterProperties().assignUsed( maEndProperties );
nCharHeight = std::max< sal_Int32 >( nCharHeight, (*aIt)->insertAt( rFilterBase, xText, xAt, aTextCharacterStyle ) );
nParagraphSize += nLen;
}
}
xAt->gotoEnd( sal_True );
PropertyMap aioBulletList;
Reference< XPropertySet > xProps( xStart, UNO_QUERY);
float fCharacterSize = nCharHeight > 0 ? GetFontHeight( nCharHeight ) : 18;
if ( pTextParagraphStyle.get() )
{
pTextParagraphStyle->pushToPropSet( &rFilterBase, xProps, aioBulletList, NULL, sal_True, fCharacterSize, true );
fCharacterSize = pTextParagraphStyle->getCharHeightPoints( fCharacterSize );
// bullets have same color as following texts by default
if( !aioBulletList.hasProperty( PROP_BulletColor ) && maRuns.size() > 0
&& (*maRuns.begin())->getTextCharacterProperties().maCharColor.isUsed() )
aioBulletList[ PROP_BulletColor ] <<= (*maRuns.begin())->getTextCharacterProperties().maCharColor.getColor( rFilterBase.getGraphicHelper() );
maProperties.pushToPropSet( &rFilterBase, xProps, aioBulletList, &pTextParagraphStyle->getBulletList(), sal_True, fCharacterSize );
}
// empty paragraphs do not have bullets in ppt
if ( !nParagraphSize )
{
const OUString sNumberingLevel( CREATE_OUSTRING( "NumberingLevel" ) );
xProps->setPropertyValue( sNumberingLevel, Any( static_cast< sal_Int16 >( -1 ) ) );
}
else if ( nLevel > 1 )
{
// Even more UGLY HACK
const OUString sNumberingLevel( CREATE_OUSTRING( "NumberingLevel" ) );
xProps->setPropertyValue( sNumberingLevel, Any( static_cast< sal_Int16 >( nLevel-1 ) ) );
}
// FIXME this is causing a lot of dispruption (ie does not work). I wonder what to do -- Hub
// Reference< XTextRange > xEnd( xAt, UNO_QUERY );
// Reference< XPropertySet > xProps2( xEnd, UNO_QUERY );
// mpEndProperties->pushToPropSet( xProps2 );
}
catch( Exception & )
{
SAL_INFO("oox", "exception in TextParagraph::insertAt");
}
}
} }
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>n760019: removing problematic code that disrupts numbering level<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
#include "oox/drawingml/textparagraph.hxx"
#include "oox/drawingml/drawingmltypes.hxx"
#include "oox/drawingml/textcharacterproperties.hxx"
#include <rtl/ustring.hxx>
#include "oox/helper/propertyset.hxx"
#include <com/sun/star/text/XText.hpp>
#include <com/sun/star/text/XTextCursor.hpp>
#include <com/sun/star/text/ControlCharacter.hpp>
using ::rtl::OUString;
using namespace ::com::sun::star::text;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::frame;
namespace oox { namespace drawingml {
TextParagraph::TextParagraph()
{
}
TextParagraph::~TextParagraph()
{
}
void TextParagraph::insertAt(
const ::oox::core::XmlFilterBase& rFilterBase,
const Reference < XText > &xText,
const Reference < XTextCursor > &xAt,
const TextCharacterProperties& rTextStyleProperties,
const TextListStyle& rTextListStyle, bool bFirst) const
{
try {
sal_Int32 nParagraphSize = 0;
Reference< XTextRange > xStart( xAt, UNO_QUERY );
sal_Int16 nLevel = maProperties.getLevel();
SAL_INFO("oox", "TextParagraph::insertAt() - level " << nLevel);
const TextParagraphPropertiesVector& rListStyle = rTextListStyle.getListStyle();
if ( nLevel >= static_cast< sal_Int16 >( rListStyle.size() ) )
nLevel = 0;
TextParagraphPropertiesPtr pTextParagraphStyle;
if ( rListStyle.size() )
pTextParagraphStyle = rListStyle[ nLevel ];
TextCharacterProperties aTextCharacterStyle;
if ( pTextParagraphStyle.get() )
aTextCharacterStyle.assignUsed( pTextParagraphStyle->getTextCharacterProperties() );
aTextCharacterStyle.assignUsed( rTextStyleProperties );
aTextCharacterStyle.assignUsed( maProperties.getTextCharacterProperties() );
if( !bFirst )
{
xText->insertControlCharacter( xStart, ControlCharacter::APPEND_PARAGRAPH, sal_False );
xAt->gotoEnd( sal_True );
}
sal_Int32 nCharHeight = 0;
if ( maRuns.begin() == maRuns.end() )
{
PropertySet aPropSet( xStart );
TextCharacterProperties aTextCharacterProps( aTextCharacterStyle );
aTextCharacterProps.assignUsed( maEndProperties );
if ( aTextCharacterProps.moHeight.has() )
nCharHeight = aTextCharacterProps.moHeight.get();
aTextCharacterProps.pushToPropSet( aPropSet, rFilterBase );
}
else
{
for( TextRunVector::const_iterator aIt = maRuns.begin(), aEnd = maRuns.end(); aIt != aEnd; ++aIt )
{
sal_Int32 nLen = (*aIt)->getText().getLength();
// n#759180: Force use, maEndProperties for the last segment
// This is currently applied to only empty runs
if( !nLen && ( ( aIt + 1 ) == aEnd ) )
(*aIt)->getTextCharacterProperties().assignUsed( maEndProperties );
nCharHeight = std::max< sal_Int32 >( nCharHeight, (*aIt)->insertAt( rFilterBase, xText, xAt, aTextCharacterStyle ) );
nParagraphSize += nLen;
}
}
xAt->gotoEnd( sal_True );
PropertyMap aioBulletList;
Reference< XPropertySet > xProps( xStart, UNO_QUERY);
float fCharacterSize = nCharHeight > 0 ? GetFontHeight( nCharHeight ) : 18;
if ( pTextParagraphStyle.get() )
{
pTextParagraphStyle->pushToPropSet( &rFilterBase, xProps, aioBulletList, NULL, sal_True, fCharacterSize, true );
fCharacterSize = pTextParagraphStyle->getCharHeightPoints( fCharacterSize );
// bullets have same color as following texts by default
if( !aioBulletList.hasProperty( PROP_BulletColor ) && maRuns.size() > 0
&& (*maRuns.begin())->getTextCharacterProperties().maCharColor.isUsed() )
aioBulletList[ PROP_BulletColor ] <<= (*maRuns.begin())->getTextCharacterProperties().maCharColor.getColor( rFilterBase.getGraphicHelper() );
maProperties.pushToPropSet( &rFilterBase, xProps, aioBulletList, &pTextParagraphStyle->getBulletList(), sal_True, fCharacterSize );
}
// empty paragraphs do not have bullets in ppt
if ( !nParagraphSize )
{
const OUString sNumberingLevel( CREATE_OUSTRING( "NumberingLevel" ) );
xProps->setPropertyValue( sNumberingLevel, Any( static_cast< sal_Int16 >( -1 ) ) );
}
// FIXME this is causing a lot of dispruption (ie does not work). I wonder what to do -- Hub
// Reference< XTextRange > xEnd( xAt, UNO_QUERY );
// Reference< XPropertySet > xProps2( xEnd, UNO_QUERY );
// mpEndProperties->pushToPropSet( xProps2 );
}
catch( Exception & )
{
SAL_INFO("oox", "exception in TextParagraph::insertAt");
}
}
} }
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* 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: textparagraph.cxx,v $
* $Revision: 1.5 $
*
* 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.
*
************************************************************************/
#include "oox/drawingml/textparagraph.hxx"
#include <rtl/ustring.hxx>
#include <com/sun/star/text/XText.hpp>
#include <com/sun/star/text/XTextCursor.hpp>
#include <com/sun/star/text/ControlCharacter.hpp>
#include <comphelper/processfactory.hxx>
using ::rtl::OUString;
using namespace ::com::sun::star::text;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::frame;
namespace oox { namespace drawingml {
TextParagraph::TextParagraph()
: mpProperties( new TextParagraphProperties )
, mpEndProperties( new TextParagraphProperties )
{
}
TextParagraph::~TextParagraph()
{
}
void TextParagraph::insertAt(
const ::oox::core::XmlFilterBase& rFilterBase,
const Reference < XText > &xText,
const Reference < XTextCursor > &xAt,
const TextListStylePtr& rTextStyleList, bool bFirst)
{
try {
sal_Int32 nParagraphSize = 0;
Reference< XTextRange > xStart( xAt, UNO_QUERY );
sal_Int16 nLevel = mpProperties->getLevel();
TextParagraphPropertiesVector& rListStyle = rTextStyleList->getListStyle();
if ( nLevel >= static_cast< sal_Int16 >( rListStyle.size() ) )
nLevel = 0;
TextParagraphPropertiesPtr pTextParagraphStyle;
TextCharacterPropertiesPtr pTextCharacterStyle;
if ( rListStyle.size() )
pTextParagraphStyle = rListStyle[ nLevel ];
if ( pTextParagraphStyle.get() )
pTextCharacterStyle = pTextParagraphStyle->getTextCharacterProperties();
if( !bFirst )
{
xText->insertControlCharacter( xStart, ControlCharacter::APPEND_PARAGRAPH, sal_False );
xAt->gotoEnd(true);
}
TextRunVector::iterator begin( maRuns.begin() );
while( begin != maRuns.end() )
{
(*begin)->insertAt( rFilterBase, xText, xAt, pTextCharacterStyle );
nParagraphSize += (*begin++)->getText().getLength();
}
xAt->gotoEnd(true);
PropertyMap aioBulletList;
Reference< XPropertySet > xProps( xStart, UNO_QUERY);
if ( pTextParagraphStyle.get() )
pTextParagraphStyle->pushToPropSet( rFilterBase, xProps, aioBulletList, sal_False );
mpProperties->pushToPropSet( rFilterBase, xProps, aioBulletList, sal_True );
// empty paragraphs do not have bullets in ppt
if ( !nParagraphSize )
{
const rtl::OUString sIsNumbering( CREATE_OUSTRING( "IsNumbering" ) );
xProps->setPropertyValue( sIsNumbering, Any( sal_False ) );
}
// FIXME this is causing a lot of dispruption (ie does not work). I wonder what to do -- Hub
// Reference< XTextRange > xEnd( xAt, UNO_QUERY );
// Reference< XPropertySet > xProps2( xEnd, UNO_QUERY );
// mpEndProperties->pushToPropSet( xProps2 );
}
catch( Exception & )
{
OSL_TRACE("OOX: exception in TextParagraph::insertAt");
}
}
} }
<commit_msg>INTEGRATION: CWS impress146 (1.5.14); FILE MERGED 2008/07/02 14:24:07 sj 1.5.14.3: #i90625# taking care of api changes 2008/07/02 11:04:43 sj 1.5.14.2: #i90625# taking care of api changes 2008/07/01 15:13:55 sj 1.5.14.1: #i90625# taking care of api changes<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: textparagraph.cxx,v $
* $Revision: 1.6 $
*
* 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.
*
************************************************************************/
#include "oox/drawingml/textparagraph.hxx"
#include <rtl/ustring.hxx>
#include <com/sun/star/text/XText.hpp>
#include <com/sun/star/text/XTextCursor.hpp>
#include <com/sun/star/text/ControlCharacter.hpp>
#include <comphelper/processfactory.hxx>
using ::rtl::OUString;
using namespace ::com::sun::star::text;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::frame;
namespace oox { namespace drawingml {
TextParagraph::TextParagraph()
: mpProperties( new TextParagraphProperties )
, mpEndProperties( new TextParagraphProperties )
{
}
TextParagraph::~TextParagraph()
{
}
void TextParagraph::insertAt(
const ::oox::core::XmlFilterBase& rFilterBase,
const Reference < XText > &xText,
const Reference < XTextCursor > &xAt,
const TextListStylePtr& rTextStyleList, bool bFirst)
{
try {
sal_Int32 nParagraphSize = 0;
Reference< XTextRange > xStart( xAt, UNO_QUERY );
sal_Int16 nLevel = mpProperties->getLevel();
TextParagraphPropertiesVector& rListStyle = rTextStyleList->getListStyle();
if ( nLevel >= static_cast< sal_Int16 >( rListStyle.size() ) )
nLevel = 0;
TextParagraphPropertiesPtr pTextParagraphStyle;
TextCharacterPropertiesPtr pTextCharacterStyle;
if ( rListStyle.size() )
pTextParagraphStyle = rListStyle[ nLevel ];
if ( pTextParagraphStyle.get() )
pTextCharacterStyle = pTextParagraphStyle->getTextCharacterProperties();
if( !bFirst )
{
xText->insertControlCharacter( xStart, ControlCharacter::APPEND_PARAGRAPH, sal_False );
xAt->gotoEnd(true);
}
TextRunVector::iterator begin( maRuns.begin() );
while( begin != maRuns.end() )
{
(*begin)->insertAt( rFilterBase, xText, xAt, pTextCharacterStyle );
nParagraphSize += (*begin++)->getText().getLength();
}
xAt->gotoEnd(true);
#ifdef DEBUG
if ( false )
{
if ( pTextParagraphStyle.get() )
pTextParagraphStyle->getTextParagraphPropertyMap().dump_debug("TextParagraph paragraph props");
}
#endif
PropertyMap aioBulletList;
Reference< XPropertySet > xProps( xStart, UNO_QUERY);
float fCharacterSize = 18;
if ( pTextParagraphStyle.get() )
{
pTextParagraphStyle->pushToPropSet( rFilterBase, xProps, aioBulletList, NULL, sal_False, fCharacterSize );
fCharacterSize = pTextParagraphStyle->getCharacterSize( 18 );
}
mpProperties->pushToPropSet( rFilterBase, xProps, aioBulletList, &pTextParagraphStyle->getBulletList(), sal_True, fCharacterSize );
// empty paragraphs do not have bullets in ppt
if ( !nParagraphSize )
{
const OUString sNumberingLevel( CREATE_OUSTRING( "NumberingLevel" ) );
xProps->setPropertyValue( sNumberingLevel, Any( static_cast< sal_Int16 >( -1 ) ) );
}
// FIXME this is causing a lot of dispruption (ie does not work). I wonder what to do -- Hub
// Reference< XTextRange > xEnd( xAt, UNO_QUERY );
// Reference< XPropertySet > xProps2( xEnd, UNO_QUERY );
// mpEndProperties->pushToPropSet( xProps2 );
}
catch( Exception & )
{
OSL_TRACE("OOX: exception in TextParagraph::insertAt");
}
}
} }
<|endoftext|>
|
<commit_before>// ======================================================================== //
// Copyright 2018-2019 Intel Corporation //
// //
// 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. //
// ======================================================================== //
// ospray_testing
#include "ospray_testing.h"
// stl
#include <iostream>
#include "example_common.h"
#include "GLFWOSPRayWindow.h"
using namespace ospray;
static std::string rendererType = "pathtracer";
static std::string builderType = "perlin_noise_volumes";
int main(int argc, const char *argv[])
{
initializeOSPRay(argc, argv);
for (int i = 1; i < argc; ++i) {
std::string arg = argv[i];
if (arg == "-r" || arg == "--renderer")
rendererType = argv[++i];
if (arg == "-s" || arg == "--scene")
builderType = argv[++i];
}
{
auto builder = testing::newBuilder(builderType);
testing::setParam(builder, "rendererType", rendererType);
testing::commit(builder);
auto world = testing::buildWorld(builder);
testing::release(builder);
world.commit();
cpp::Renderer renderer(rendererType);
renderer.commit();
// create a GLFW OSPRay window: this object will create and manage the
// OSPRay frame buffer and camera directly
auto glfwOSPRayWindow = std::unique_ptr<GLFWOSPRayWindow>(
new GLFWOSPRayWindow(vec2i(1024, 768), world, renderer));
// start the GLFW main loop, which will continuously render
glfwOSPRayWindow->mainLoop();
}
ospShutdown();
return 0;
}
<commit_msg>add help/usage text to ospExamples<commit_after>// ======================================================================== //
// Copyright 2018-2019 Intel Corporation //
// //
// 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. //
// ======================================================================== //
// ospray_testing
#include "ospray_testing.h"
// stl
#include <iostream>
#include "GLFWOSPRayWindow.h"
#include "example_common.h"
using namespace ospray;
static std::string rendererType = "pathtracer";
static std::string builderType = "perlin_noise_volumes";
void printHelp()
{
std::cout <<
R"description(
usage: ./ospExamples [-h | --help] [[-s | --scene] scene] [[r | --renderer] renderer_type]
scenes:
boxes
cornell_box
curves
cylinders
empty
gravity_spheres_volume
perlin_noise_volumes
random_spheres
streamlines
subdivision_cube
unstructured_volume
)description";
}
int main(int argc, const char *argv[])
{
initializeOSPRay(argc, argv);
for (int i = 1; i < argc; ++i) {
std::string arg = argv[i];
if (arg == "-h" || arg == "--help") {
printHelp();
return 0;
} else if (arg == "-r" || arg == "--renderer") {
rendererType = argv[++i];
} else if (arg == "-s" || arg == "--scene") {
builderType = argv[++i];
}
}
{
auto builder = testing::newBuilder(builderType);
testing::setParam(builder, "rendererType", rendererType);
testing::commit(builder);
auto world = testing::buildWorld(builder);
testing::release(builder);
world.commit();
cpp::Renderer renderer(rendererType);
renderer.commit();
// create a GLFW OSPRay window: this object will create and manage the
// OSPRay frame buffer and camera directly
auto glfwOSPRayWindow = std::unique_ptr<GLFWOSPRayWindow>(
new GLFWOSPRayWindow(vec2i(1024, 768), world, renderer));
// start the GLFW main loop, which will continuously render
glfwOSPRayWindow->mainLoop();
}
ospShutdown();
return 0;
}
<|endoftext|>
|
<commit_before>#include "cssysdef.h"
#include "awssktst.h"
#include "csutil/scfstr.h"
#include "iaws/awsparm.h"
#include <stdio.h>
static char *names[10] = { "Yellow", "Green", "Blue", "Orange", "Purple", "Red", "White", "Teal", "Black" };
static int namec = 0;
awsTestSink::awsTestSink():wmgr(NULL), sink(NULL), user(NULL), pass(NULL), test(NULL)
{
}
awsTestSink::~awsTestSink()
{
if (sink) sink->DecRef();
}
void
awsTestSink::SetSink(iAwsSink *s)
{
sink=s;
if (sink)
{
sink->IncRef();
sink->RegisterTrigger("RedClicked", &RedClicked);
sink->RegisterTrigger("BlueClicked", &BlueClicked);
sink->RegisterTrigger("GreenClicked", &GreenClicked);
sink->RegisterTrigger("SetUserName", &SetUser);
sink->RegisterTrigger("SetPassword", &SetPass);
sink->RegisterTrigger("Login", &Login);
sink->RegisterTrigger("FillListBox", &FillListBox);
}
}
void
awsTestSink::SetTestWin(iAwsWindow *testwin)
{
test=testwin;
}
void
awsTestSink::SetWindowManager(iAws *_wmgr)
{
wmgr=_wmgr;
}
void
awsTestSink::FillListBox(void *sk, iAwsSource *source)
{
awsTestSink *sink = (awsTestSink *)sk;
iAwsComponent *comp = source->GetComponent();
iAwsParmList *pl=0;
int parent;
printf("awstest: Filling list box.\n");
if (sink->wmgr)
pl = sink->wmgr->CreateParmList();
else
printf("awstest: window manager is null.\n");
if (pl==NULL)
{
printf("awstest: internal error, parameter list NULL.\n");
return;
}
// Setup first row
pl->AddString("text0", new scfString("Human"));
pl->AddString("text1", new scfString("Enabled"));
pl->AddBool("stateful1", true);
pl->AddString("text2", new scfString("Shenobi"));
// Add it into the list
comp->Execute("InsertItem", *pl);
pl->Clear();
//////////////////////////
// Setup second row
pl->AddString("text0", new scfString("Android"));
pl->AddString("text1", new scfString("Enabled"));
pl->AddBool("stateful1", true);
pl->AddBool("state1", true);
pl->AddString("text2", new scfString("Tenalt"));
// Add it into the list
comp->Execute("InsertItem", *pl);
// Get the id of the last item for hierarchical support.
pl->GetInt("id", &parent);
pl->Clear();
//////////////////////////
// Setup third row (hierarchical)
pl->AddString("text0", new scfString("Ship"));
pl->AddString("text1", new scfString("Active"));
pl->AddBool("stateful1", true);
pl->AddBool("state1", true);
pl->AddString("text2", new scfString("Daedalus"));
pl->AddInt("parent", parent);
// Add it into the list
comp->Execute("InsertItem", *pl);
pl->Clear();
//////////////////////////
// Setup fourth row (hierarchical)
pl->AddString("text0", new scfString("Ship"));
pl->AddString("text1", new scfString("Active"));
pl->AddBool("stateful1", true);
pl->AddBool("state1", false);
pl->AddString("text2", new scfString("Temtor"));
pl->AddInt("parent", parent);
// Add it into the list
comp->Execute("InsertItem", *pl);
pl->Clear();
pl->DecRef();
}
void
awsTestSink::RedClicked(void *sink, iAwsSource *source)
{
printf("awstest: red button clicked, source: %p, owner: %p, component: %p\n", source, sink, source->GetComponent());
namec++;
if (namec > 8) namec=0;
iAwsComponent *comp = source->GetComponent();
comp->SetProperty("Caption", new scfString(names[namec]));
}
void
awsTestSink::BlueClicked(void *sink, iAwsSource *source)
{
printf("awstest: blue button clicked, source: %p, owner: %p\n", source, sink);
}
void
awsTestSink::GreenClicked(void *sink, iAwsSource *source)
{
printf("awstest: green button clicked, source: %p, owner: %p\n", source, sink);
}
void
awsTestSink::SetPass(void *sk, iAwsSource *source)
{
awsTestSink *sink = (awsTestSink *)sk;
if (sink->pass) sink->pass->DecRef();
iAwsComponent *comp = source->GetComponent();
comp->GetProperty("Text", (void**)&sink->pass);
}
void
awsTestSink::SetUser(void *sk, iAwsSource *source)
{
awsTestSink *sink = (awsTestSink *)sk;
if (sink->user) sink->user->DecRef();
iAwsComponent *comp = source->GetComponent();
comp->GetProperty("Text", (void**)&sink->user);
}
void
awsTestSink::Login(void *sk, iAwsSource *source)
{
awsTestSink *sink = (awsTestSink *)sk;
if (sink->user==NULL || sink->pass==NULL)
printf("awstest: You must enter a username AND password.\n");
else {
printf("awstest: Logging in as %s with password: %s (not really.)\n", sink->user->GetData(), sink->pass->GetData());
iAwsComponent *comp = source->GetComponent();
if (sink->wmgr) {
iAwsParmList *pl = sink->wmgr->CreateParmList();
comp->Execute("HideWindow", *pl);
if (sink->test) sink->test->Show();
pl->DecRef();
}
}
}<commit_msg>Christopher:<commit_after>#include "cssysdef.h"
#include "awssktst.h"
#include "csutil/scfstr.h"
#include "iaws/awsparm.h"
#include <stdio.h>
static char *names[10] = { "Yellow", "Green", "Blue", "Orange", "Purple", "Red", "White", "Teal", "Black" };
static int namec = 0;
awsTestSink::awsTestSink():wmgr(NULL), sink(NULL), user(NULL), pass(NULL), test(NULL)
{
}
awsTestSink::~awsTestSink()
{
if (sink) sink->DecRef();
}
void
awsTestSink::SetSink(iAwsSink *s)
{
sink=s;
if (sink)
{
sink->IncRef();
sink->RegisterTrigger("RedClicked", &RedClicked);
sink->RegisterTrigger("BlueClicked", &BlueClicked);
sink->RegisterTrigger("GreenClicked", &GreenClicked);
sink->RegisterTrigger("SetUserName", &SetUser);
sink->RegisterTrigger("SetPassword", &SetPass);
sink->RegisterTrigger("Login", &Login);
sink->RegisterTrigger("FillListBox", &FillListBox);
}
}
void
awsTestSink::SetTestWin(iAwsWindow *testwin)
{
test=testwin;
}
void
awsTestSink::SetWindowManager(iAws *_wmgr)
{
wmgr=_wmgr;
}
void
awsTestSink::FillListBox(void *sk, iAwsSource *source)
{
awsTestSink *sink = (awsTestSink *)sk;
iAwsComponent *comp = source->GetComponent();
iAwsParmList *pl=0;
int parent;
printf("awstest: Filling list box.\n");
if (sink->wmgr)
pl = sink->wmgr->CreateParmList();
else
printf("awstest: window manager is null.\n");
if (pl==NULL)
{
printf("awstest: internal error, parameter list NULL.\n");
return;
}
// Setup first row
pl->AddString("text0", new scfString("Human"));
pl->AddString("text1", new scfString("Enabled"));
pl->AddBool("stateful1", true);
pl->AddString("text2", new scfString("Shenobi"));
// Add it into the list
comp->Execute("InsertItem", *pl);
pl->Clear();
//////////////////////////
// Setup second row
pl->AddString("text0", new scfString("Android"));
pl->AddString("text1", new scfString("Enabled"));
pl->AddBool("stateful1", true);
pl->AddBool("state1", true);
pl->AddString("text2", new scfString("Tenalt"));
// Add it into the list
comp->Execute("InsertItem", *pl);
// Get the id of the last item for hierarchical support.
pl->GetInt("id", &parent);
pl->Clear();
//////////////////////////
// Setup third row (hierarchical)
pl->AddString("text0", new scfString("Ship"));
pl->AddString("text1", new scfString("Active"));
pl->AddBool("stateful1", true);
pl->AddBool("groupstate1", true);
pl->AddBool("state1", true);
pl->AddString("text2", new scfString("Daedalus"));
pl->AddInt("parent", parent);
// Add it into the list
comp->Execute("InsertItem", *pl);
pl->Clear();
//////////////////////////
// Setup fourth row (hierarchical)
pl->AddString("text0", new scfString("Ship"));
pl->AddString("text1", new scfString("Active"));
pl->AddBool("stateful1", true);
pl->AddBool("groupstate1", true);
pl->AddBool("state1", false);
pl->AddString("text2", new scfString("Temtor"));
pl->AddInt("parent", parent);
// Add it into the list
comp->Execute("InsertItem", *pl);
// Get the id of the last item for hierarchical support.
pl->GetInt("id", &parent);
pl->Clear();
//////////////////////////
// Setup fifth row (hierarchical)
pl->AddString("text0", new scfString("TurboLaser"));
pl->AddString("text1", new scfString("Active"));
pl->AddBool("stateful1", true);
pl->AddBool("groupstate1", true);
pl->AddBool("state1", false);
pl->AddString("text2", new scfString("Johnny"));
pl->AddInt("parent", parent);
// Add it into the list
comp->Execute("InsertItem", *pl);
pl->Clear();
pl->DecRef();
}
void
awsTestSink::RedClicked(void *sink, iAwsSource *source)
{
printf("awstest: red button clicked, source: %p, owner: %p, component: %p\n", source, sink, source->GetComponent());
namec++;
if (namec > 8) namec=0;
iAwsComponent *comp = source->GetComponent();
comp->SetProperty("Caption", new scfString(names[namec]));
}
void
awsTestSink::BlueClicked(void *sink, iAwsSource *source)
{
printf("awstest: blue button clicked, source: %p, owner: %p\n", source, sink);
}
void
awsTestSink::GreenClicked(void *sink, iAwsSource *source)
{
printf("awstest: green button clicked, source: %p, owner: %p\n", source, sink);
}
void
awsTestSink::SetPass(void *sk, iAwsSource *source)
{
awsTestSink *sink = (awsTestSink *)sk;
if (sink->pass) sink->pass->DecRef();
iAwsComponent *comp = source->GetComponent();
comp->GetProperty("Text", (void**)&sink->pass);
}
void
awsTestSink::SetUser(void *sk, iAwsSource *source)
{
awsTestSink *sink = (awsTestSink *)sk;
if (sink->user) sink->user->DecRef();
iAwsComponent *comp = source->GetComponent();
comp->GetProperty("Text", (void**)&sink->user);
}
void
awsTestSink::Login(void *sk, iAwsSource *source)
{
awsTestSink *sink = (awsTestSink *)sk;
if (sink->user==NULL || sink->pass==NULL)
printf("awstest: You must enter a username AND password.\n");
else {
printf("awstest: Logging in as %s with password: %s (not really.)\n", sink->user->GetData(), sink->pass->GetData());
iAwsComponent *comp = source->GetComponent();
if (sink->wmgr) {
iAwsParmList *pl = sink->wmgr->CreateParmList();
comp->Execute("HideWindow", *pl);
if (sink->test) sink->test->Show();
pl->DecRef();
}
}
}<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ocompinstream.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 16:06:54 $
*
* 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 _INPUTCOMPSTREAM_HXX_
#define _INPUTCOMPSTREAM_HXX_
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_
#include <com/sun/star/io/XStream.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE4_HXX_
#include <cppuhelper/implbase4.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_H_
#include <cppuhelper/interfacecontainer.h>
#endif
#include "mutexholder.hxx"
struct OWriteStream_Impl;
class OInputCompStream : public cppu::WeakImplHelper4 < ::com::sun::star::io::XInputStream
,::com::sun::star::io::XStream
,::com::sun::star::lang::XComponent
,::com::sun::star::beans::XPropertySet >
{
protected:
OWriteStream_Impl* m_pImpl;
SotMutexHolderRef m_rMutexRef;
::com::sun::star::uno::Reference < ::com::sun::star::io::XInputStream > m_xStream;
::cppu::OInterfaceContainerHelper* m_pInterfaceContainer;
::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue > m_aProperties;
sal_Bool m_bDisposed;
OInputCompStream();
OInputCompStream( OWriteStream_Impl& pImpl );
public:
OInputCompStream( OWriteStream_Impl& pImpl,
::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > xStream,
const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aProps );
OInputCompStream( ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > xStream,
const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aProps );
virtual ~OInputCompStream();
void InternalDispose();
// XInputStream
virtual sal_Int32 SAL_CALL readBytes( ::com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead )
throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL readSomeBytes( ::com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead )
throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip )
throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL available( )
throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL closeInput( )
throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
//XStream
virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getInputStream( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream > SAL_CALL getOutputStream( ) throw (::com::sun::star::uno::RuntimeException);
//XComponent
virtual void SAL_CALL dispose( ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);
//XPropertySet
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() throw ( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw ( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException );
virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw ( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener ) throw ( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener ) throw ( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw ( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw ( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException );
};
#endif
<commit_msg>INTEGRATION: CWS opofxmlstorage (1.4.30); FILE MERGED 2006/05/12 08:23:41 mav 1.4.30.3: #i65306# hierarchical access 2006/05/11 16:38:34 mav 1.4.30.2: #i65306# hierarchical access to storagestreamss 2006/04/21 11:36:59 mav 1.4.30.1: #i64612# support OFOPXML format<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ocompinstream.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-10-13 11:49:01 $
*
* 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 _INPUTCOMPSTREAM_HXX_
#define _INPUTCOMPSTREAM_HXX_
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_
#include <com/sun/star/io/XStream.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XEXTENDEDSTORAGESTREAM_HPP_
#include <com/sun/star/embed/XExtendedStorageStream.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XRELATIONSHIPACCESS_HPP_
#include <com/sun/star/embed/XRelationshipAccess.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE4_HXX_
#include <cppuhelper/implbase4.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_H_
#include <cppuhelper/interfacecontainer.h>
#endif
#include "mutexholder.hxx"
struct OWriteStream_Impl;
class OInputCompStream : public cppu::WeakImplHelper4 < ::com::sun::star::io::XInputStream
,::com::sun::star::embed::XExtendedStorageStream
,::com::sun::star::embed::XRelationshipAccess
,::com::sun::star::beans::XPropertySet >
{
protected:
OWriteStream_Impl* m_pImpl;
SotMutexHolderRef m_rMutexRef;
::com::sun::star::uno::Reference < ::com::sun::star::io::XInputStream > m_xStream;
::cppu::OInterfaceContainerHelper* m_pInterfaceContainer;
::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue > m_aProperties;
sal_Bool m_bDisposed;
sal_Int16 m_nStorageType;
OInputCompStream( sal_Int16 nStorageType );
OInputCompStream( OWriteStream_Impl& pImpl, sal_Int16 nStorageType );
public:
OInputCompStream( OWriteStream_Impl& pImpl,
::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > xStream,
const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aProps,
sal_Int16 nStorageType );
OInputCompStream( ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > xStream,
const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aProps,
sal_Int16 nStorageType );
virtual ~OInputCompStream();
void InternalDispose();
// XInterface
virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& rType )
throw( ::com::sun::star::uno::RuntimeException );
// XInputStream
virtual sal_Int32 SAL_CALL readBytes( ::com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead )
throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL readSomeBytes( ::com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead )
throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip )
throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL available( )
throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL closeInput( )
throw(::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
//XStream
virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getInputStream( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream > SAL_CALL getOutputStream( ) throw (::com::sun::star::uno::RuntimeException);
//XComponent
virtual void SAL_CALL dispose( ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);
//XRelationshipAccess
virtual ::sal_Bool SAL_CALL hasByID( const ::rtl::OUString& sID ) throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getTargetByID( const ::rtl::OUString& sID ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getTypeByID( const ::rtl::OUString& sID ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::StringPair > SAL_CALL getRelationshipByID( const ::rtl::OUString& sID ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::beans::StringPair > > SAL_CALL getRelationshipsByType( const ::rtl::OUString& sType ) throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::beans::StringPair > > SAL_CALL getAllRelationships( ) throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL insertRelationshipByID( const ::rtl::OUString& sID, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::StringPair >& aEntry, ::sal_Bool bReplace ) throw (::com::sun::star::container::ElementExistException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeRelationshipByID( const ::rtl::OUString& sID ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL insertRelationships( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::beans::StringPair > >& aEntries, ::sal_Bool bReplace ) throw (::com::sun::star::container::ElementExistException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL clearRelationships( ) throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
//XPropertySet
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() throw ( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw ( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException );
virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw ( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener ) throw ( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener ) throw ( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw ( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw ( ::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException );
};
#endif
<|endoftext|>
|
<commit_before>/*
Servo Class
author : vincent JAUNET
mail : vincent.jaunet@hotmail.fr
date : 10-01-2013
Description:
the Servo class is a collection of routine used to control
the motors through the electronic speed controllers.
ESC and Servo use the same communication protocole: PWM. That is
the reason why the servoblaster module is being used here. This allows
to get rid of an external PIC controller to generate such PWM signal.
The routines in the Serco class do the follwing:
- open the /dev/servoblaster file in order to write in it
- initlaize the ESC by sending a PWM of 1ms (~ throttle = 0)
- write the desired PWM values
*/
#include "servo.h"
Servo ESC;
Servo::Servo()
{
m_servoId[0] = 0;
m_servoId[1] = 1;
m_servoId[2] = 2;
m_servoId[3] = 3;
fid_servo=NULL;
}
bool Servo::Is_open_blaster()
{
if(fid_servo==NULL) {
//printf("servoblaster not open !!!");
return false;
}
return true;
}
void Servo::open_blaster()
{
fid_servo=fopen("/dev/servoblaster","w");
if (fid_servo==NULL){
printf("Opening /dev/servoblaster failed \n");
exit(2);
}
}
void Servo::close_blaster()
{
if (fid_servo==NULL){
printf("/dev/servoblaster not opened \n");
return;
}
fclose(fid_servo);
fid_servo=NULL;
}
void Servo::init()
{
if(fid_servo==NULL) return;
//initialisation of ESC
for (int i=0;i<4;i++){
servoval[i]=SERVO_MIN;
};
setServo();
sleep(1);
}
void Servo::update(float throttle, float PIDoutput[DIM])
{
servoval[0] =(int)(throttle - PIDoutput[ROLL] - PIDoutput[YAW]);
servoval[1] =(int)(throttle + PIDoutput[ROLL] - PIDoutput[YAW]);
servoval[2] =(int)(throttle - PIDoutput[PITCH] + PIDoutput[YAW]);
servoval[3] =(int)(throttle + PIDoutput[PITCH] + PIDoutput[YAW]);
setServo();
}
void Servo::stopServo()
{
for (int i=0;i<4;i++){
servoval[i]=SERVO_MIN;
};
setServo();
}
void Servo::setServo()
{
if (Is_open_blaster()){
for (int i=0;i<4;i++){
fprintf(fid_servo, "%d=%dus\n",m_servoId[i], servoval[i]);
fflush(fid_servo);
}
} else {
printf("Servoblaster not opened \n");
}
}
<commit_msg>commit<commit_after>/*
Servo Class
author : vincent JAUNET
mail : vincent.jaunet@hotmail.fr
date : 10-01-2013
Description:
the Servo class is a collection of routine used to control
the motors through the electronic speed controllers.
ESC and Servo use the same communication protocole: PWM. That is
the reason why the servoblaster module is being used here. This allows
to get rid of an external PIC controller to generate such PWM signal.
The routines in the Serco class do the follwing:
- open the /dev/servoblaster file in order to write in it
- initlaize the ESC by sending a PWM of 1ms (~ throttle = 0)
- write the desired PWM values
*/
#include "servo.h"
Servo ESC;
Servo::Servo()
{
m_servoId[0] = 0;
m_servoId[1] = 1;
m_servoId[2] = 2;
m_servoId[3] = 3;
fid_servo=NULL;
}
bool Servo::Is_open_blaster()
{
if(fid_servo==NULL) {
//printf("servoblaster not open !!!");
return false;
}
return true;
}
void Servo::open_blaster()
{
fid_servo=fopen("/dev/servoblaster","w");
if (fid_servo==NULL){
printf("Opening /dev/servoblaster failed \n");
exit(2);
}
}
void Servo::close_blaster()
{
if (fid_servo==NULL){
printf("/dev/servoblaster not opened \n");
return;
}
fclose(fid_servo);
fid_servo=NULL;
}
void Servo::init()
{
if(fid_servo==NULL) return;
//initialisation of ESC
for (int i=0;i<4;i++){
servoval[i]=SERVO_MIN;
};
setServo();
sleep(1);
}
void Servo::update(float throttle, float PIDoutput[DIM])
{
servoval[0] =(int)(throttle - PIDoutput[ROLL] - PIDoutput[YAW]);
servoval[1] =(int)(throttle + PIDoutput[ROLL] - PIDoutput[YAW]);
servoval[2] =(int)(throttle - PIDoutput[PITCH] + PIDoutput[YAW]);
servoval[3] =(int)(throttle + PIDoutput[PITCH] + PIDoutput[YAW]);
setServo();
}
void Servo::stopServo()
{
for (int i=0;i<4;i++){
servoval[i]=SERVO_MIN;
};
setServo();
}
void Servo::setServo()
{
if (Is_open_blaster()){
for (int i=0;i<4;i++){
fprintf(fid_servo, "%d=%dus\n",m_servoId[i], servoval[i]);
fflush(fid_servo);
}
} else {
printf("Servoblaster not opened \n");
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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_chart2.hxx"
#include "ExplicitCategoriesProvider.hxx"
#include "DiagramHelper.hxx"
#include "CommonConverters.hxx"
#include "DataSourceHelper.hxx"
#include "ChartModelHelper.hxx"
#include "ContainerHelper.hxx"
#include "macros.hxx"
//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
using namespace ::com::sun::star::chart2;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::rtl::OUString;
using ::std::vector;
ExplicitCategoriesProvider::ExplicitCategoriesProvider( const Reference< chart2::XCoordinateSystem >& xCooSysModel
, const uno::Reference< frame::XModel >& xChartModel )
: m_bDirty(true)
, m_xCooSysModel( xCooSysModel )
, m_xOriginalCategories()
{
try
{
if( xCooSysModel.is() )
{
uno::Reference< XAxis > xAxis( xCooSysModel->getAxisByDimension(0,0) );
if( xAxis.is() )
m_xOriginalCategories = xAxis->getScaleData().Categories;
}
if( m_xOriginalCategories.is() )
{
Reference< chart2::XChartDocument > xChartDoc( xChartModel, uno::UNO_QUERY );
if( xChartDoc.is() )
{
uno::Reference< data::XDataProvider > xDataProvider( xChartDoc->getDataProvider() );
if( xDataProvider.is() )
{
OUString aCatgoriesRange( DataSourceHelper::getRangeFromValues( m_xOriginalCategories ) );
const bool bFirstCellAsLabel = false;
const bool bHasCategories = false;
const uno::Sequence< sal_Int32 > aSequenceMapping;
uno::Reference< data::XDataSource > xColumnCategoriesSource( xDataProvider->createDataSource(
DataSourceHelper::createArguments( aCatgoriesRange, aSequenceMapping, true /*bUseColumns*/
, bFirstCellAsLabel, bHasCategories ) ) );
uno::Reference< data::XDataSource > xRowCategoriesSource( xDataProvider->createDataSource(
DataSourceHelper::createArguments( aCatgoriesRange, aSequenceMapping, false /*bUseColumns*/
, bFirstCellAsLabel, bHasCategories ) ) );
if( xColumnCategoriesSource.is() && xRowCategoriesSource.is() )
{
Sequence< Reference< data::XLabeledDataSequence> > aColumns = xColumnCategoriesSource->getDataSequences();
Sequence< Reference< data::XLabeledDataSequence> > aRows = xRowCategoriesSource->getDataSequences();
sal_Int32 nColumnCount = aColumns.getLength();
sal_Int32 nRowCount = aRows.getLength();
if( nColumnCount>1 && nRowCount>1 )
{
//we have complex categories
//->split them in the direction of the first series
//detect whether the first series is a row or a column
bool bSeriesUsesColumns = true;
::std::vector< Reference< XDataSeries > > aSeries( ChartModelHelper::getDataSeries( xChartModel ) );
if( !aSeries.empty() )
{
uno::Reference< data::XDataSource > xSeriesSource( aSeries.front(), uno::UNO_QUERY );
::rtl::OUString aStringDummy;
bool bDummy;
uno::Sequence< sal_Int32 > aSeqDummy;
DataSourceHelper::readArguments( xDataProvider->detectArguments( xSeriesSource),
aStringDummy, aSeqDummy, bSeriesUsesColumns, bDummy, bDummy );
}
if( bSeriesUsesColumns )
m_aSplitCategoriesList=aColumns;
else
m_aSplitCategoriesList=aRows;
}
}
}
}
if( !m_aSplitCategoriesList.getLength() )
{
m_aSplitCategoriesList.realloc(1);
m_aSplitCategoriesList[0]=m_xOriginalCategories;
}
}
}
catch( const uno::Exception & ex )
{
ASSERT_EXCEPTION( ex );
}
}
ExplicitCategoriesProvider::~ExplicitCategoriesProvider()
{
}
const Sequence< Reference< data::XLabeledDataSequence> >& ExplicitCategoriesProvider::getSplitCategoriesList()
{
return m_aSplitCategoriesList;
}
bool ExplicitCategoriesProvider::hasComplexCategories() const
{
return m_aSplitCategoriesList.getLength() > 1;
}
sal_Int32 ExplicitCategoriesProvider::getCategoryLevelCount() const
{
sal_Int32 nCount = m_aSplitCategoriesList.getLength();
if(!nCount)
nCount = 1;
return nCount;
}
std::vector<sal_Int32> lcl_getLimitingBorders( const std::vector< ComplexCategory >& rComplexCategories )
{
std::vector<sal_Int32> aLimitingBorders;
std::vector< ComplexCategory >::const_iterator aIt( rComplexCategories.begin() );
std::vector< ComplexCategory >::const_iterator aEnd( rComplexCategories.end() );
sal_Int32 nBorderIndex = 0; /*border below the index*/
for( ; aIt != aEnd; ++aIt )
{
ComplexCategory aComplexCategory(*aIt);
nBorderIndex += aComplexCategory.Count;
aLimitingBorders.push_back(nBorderIndex);
}
return aLimitingBorders;
}
uno::Sequence< rtl::OUString > lcl_DataToStringSequence( const uno::Reference< data::XDataSequence >& xDataSequence )
{
uno::Sequence< rtl::OUString > aStrings;
OSL_ASSERT( xDataSequence.is());
if( !xDataSequence.is() )
return aStrings;
uno::Reference< data::XTextualDataSequence > xTextualDataSequence( xDataSequence, uno::UNO_QUERY );
if( xTextualDataSequence.is() )
{
aStrings = xTextualDataSequence->getTextualData();
}
else
{
uno::Sequence< uno::Any > aValues = xDataSequence->getData();
aStrings.realloc(aValues.getLength());
for(sal_Int32 nN=aValues.getLength();nN--;)
aValues[nN] >>= aStrings[nN];
}
return aStrings;
}
SplitCategoriesProvider::~SplitCategoriesProvider()
{
}
class SplitCategoriesProvider_ForLabeledDataSequences : public SplitCategoriesProvider
{
public:
explicit SplitCategoriesProvider_ForLabeledDataSequences( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference<
::com::sun::star::chart2::data::XLabeledDataSequence> >& rSplitCategoriesList )
: m_rSplitCategoriesList( rSplitCategoriesList )
{}
virtual ~SplitCategoriesProvider_ForLabeledDataSequences()
{}
virtual sal_Int32 getLevelCount() const;
virtual uno::Sequence< rtl::OUString > getStringsForLevel( sal_Int32 nIndex ) const;
private:
const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference<
::com::sun::star::chart2::data::XLabeledDataSequence> >& m_rSplitCategoriesList;
};
sal_Int32 SplitCategoriesProvider_ForLabeledDataSequences::getLevelCount() const
{
return m_rSplitCategoriesList.getLength();
}
uno::Sequence< rtl::OUString > SplitCategoriesProvider_ForLabeledDataSequences::getStringsForLevel( sal_Int32 nLevel ) const
{
uno::Sequence< rtl::OUString > aRet;
Reference< data::XLabeledDataSequence > xLabeledDataSequence( m_rSplitCategoriesList[nLevel] );
if( xLabeledDataSequence.is() )
aRet = lcl_DataToStringSequence( xLabeledDataSequence->getValues() );
return aRet;
}
std::vector< ComplexCategory > lcl_DataSequenceToComplexCategoryVector(
const uno::Sequence< rtl::OUString >& rStrings
, const std::vector<sal_Int32>& rLimitingBorders, bool bCreateSingleCategories )
{
std::vector< ComplexCategory > aResult;
sal_Int32 nMaxCount = rStrings.getLength();
OUString aPrevious;
sal_Int32 nCurrentCount=0;
for( sal_Int32 nN=0; nN<nMaxCount; nN++ )
{
OUString aCurrent = rStrings[nN];
if( bCreateSingleCategories || ::std::find( rLimitingBorders.begin(), rLimitingBorders.end(), nN ) != rLimitingBorders.end() )
{
aResult.push_back( ComplexCategory(aPrevious,nCurrentCount) );
nCurrentCount=1;
aPrevious = aCurrent;
}
else
{
if( aCurrent.getLength() && aPrevious != aCurrent )
{
aResult.push_back( ComplexCategory(aPrevious,nCurrentCount) );
nCurrentCount=1;
aPrevious = aCurrent;
}
else
nCurrentCount++;
}
}
if( nCurrentCount )
aResult.push_back( ComplexCategory(aPrevious,nCurrentCount) );
return aResult;
}
sal_Int32 lcl_getCategoryCount( std::vector< ComplexCategory >& rComplexCategories )
{
sal_Int32 nCount = 0;
std::vector< ComplexCategory >::iterator aIt( rComplexCategories.begin() );
std::vector< ComplexCategory >::const_iterator aEnd( rComplexCategories.end() );
for( ; aIt != aEnd; ++aIt )
nCount+=aIt->Count;
return nCount;
}
Sequence< OUString > lcl_getExplicitSimpleCategories(
const SplitCategoriesProvider& rSplitCategoriesProvider,
::std::vector< ::std::vector< ComplexCategory > >& rComplexCats )
{
Sequence< OUString > aRet;
rComplexCats.clear();
sal_Int32 nLCount = rSplitCategoriesProvider.getLevelCount();
for( sal_Int32 nL = 0; nL < nLCount; nL++ )
{
std::vector<sal_Int32> aLimitingBorders;
if(nL>0)
aLimitingBorders = lcl_getLimitingBorders( rComplexCats.back() );
rComplexCats.push_back( lcl_DataSequenceToComplexCategoryVector(
rSplitCategoriesProvider.getStringsForLevel(nL), aLimitingBorders, nL==(nLCount-1) ) );
}
std::vector< std::vector< ComplexCategory > >::iterator aOuterIt( rComplexCats.begin() );
std::vector< std::vector< ComplexCategory > >::const_iterator aOuterEnd( rComplexCats.end() );
//ensure that the category count is the same on each level
sal_Int32 nMaxCategoryCount = 0;
{
for( aOuterIt=rComplexCats.begin(); aOuterIt != aOuterEnd; ++aOuterIt )
{
sal_Int32 nCurrentCount = lcl_getCategoryCount( *aOuterIt );
nMaxCategoryCount = std::max( nCurrentCount, nMaxCategoryCount );
}
for( aOuterIt=rComplexCats.begin(); aOuterIt != aOuterEnd; ++aOuterIt )
{
sal_Int32 nCurrentCount = lcl_getCategoryCount( *aOuterIt );
if( nCurrentCount< nMaxCategoryCount )
{
ComplexCategory& rComplexCategory = aOuterIt->back();
rComplexCategory.Count += (nMaxCategoryCount-nCurrentCount);
}
}
}
//create a list with an element for every index
std::vector< std::vector< ComplexCategory > > aComplexCatsPerIndex;
for( aOuterIt=rComplexCats.begin() ; aOuterIt != aOuterEnd; ++aOuterIt )
{
std::vector< ComplexCategory > aSingleLevel;
std::vector< ComplexCategory >::iterator aIt( aOuterIt->begin() );
std::vector< ComplexCategory >::const_iterator aEnd( aOuterIt->end() );
for( ; aIt != aEnd; ++aIt )
{
ComplexCategory aComplexCategory( *aIt );
sal_Int32 nCount = aComplexCategory.Count;
while( nCount-- )
aSingleLevel.push_back(aComplexCategory);
}
aComplexCatsPerIndex.push_back( aSingleLevel );
}
if(nMaxCategoryCount)
{
aRet.realloc(nMaxCategoryCount);
aOuterEnd = aComplexCatsPerIndex.end();
OUString aSpace(C2U(" "));
for(sal_Int32 nN=0; nN<nMaxCategoryCount; nN++)
{
OUString aText;
for( aOuterIt=aComplexCatsPerIndex.begin() ; aOuterIt != aOuterEnd; ++aOuterIt )
{
OUString aAddText = (*aOuterIt)[nN].Text;
if( aAddText.getLength() )
{
if(aText.getLength())
aText += aSpace;
aText += aAddText;
}
}
aRet[nN]=aText;
}
}
return aRet;
}
//static
Sequence< OUString > ExplicitCategoriesProvider::getExplicitSimpleCategories(
const SplitCategoriesProvider& rSplitCategoriesProvider )
{
vector< vector< ComplexCategory > > aComplexCats;
return lcl_getExplicitSimpleCategories( rSplitCategoriesProvider, aComplexCats );
}
void ExplicitCategoriesProvider::init()
{
if( m_bDirty )
{
m_aExplicitCategories.realloc(0);
m_aComplexCats.clear();//not one per index
if( m_xOriginalCategories.is() )
{
if( !hasComplexCategories() )
m_aExplicitCategories = DataSequenceToStringSequence(m_xOriginalCategories->getValues());
else
m_aExplicitCategories = lcl_getExplicitSimpleCategories(
SplitCategoriesProvider_ForLabeledDataSequences( m_aSplitCategoriesList ), m_aComplexCats );
}
if(!m_aExplicitCategories.getLength())
m_aExplicitCategories = DiagramHelper::generateAutomaticCategoriesFromCooSys( m_xCooSysModel );
m_bDirty = false;
}
}
Sequence< ::rtl::OUString > ExplicitCategoriesProvider::getSimpleCategories()
{
init();
return m_aExplicitCategories;
}
std::vector< ComplexCategory > ExplicitCategoriesProvider::getCategoriesByLevel( sal_Int32 nLevel )
{
std::vector< ComplexCategory > aRet;
init();
sal_Int32 nMaxIndex = m_aComplexCats.size()-1;
if( nLevel >= 0 && nLevel <= nMaxIndex )
aRet = m_aComplexCats[nMaxIndex-nLevel];
return aRet;
}
// static
OUString ExplicitCategoriesProvider::getCategoryByIndex(
const Reference< XCoordinateSystem >& xCooSysModel
, const uno::Reference< frame::XModel >& xChartModel
, sal_Int32 nIndex )
{
if( xCooSysModel.is())
{
ExplicitCategoriesProvider aExplicitCategoriesProvider( xCooSysModel, xChartModel );
Sequence< OUString > aCategories( aExplicitCategoriesProvider.getSimpleCategories());
if( nIndex < aCategories.getLength())
return aCategories[ nIndex ];
}
return OUString();
}
//.............................................................................
} //namespace chart
//.............................................................................
<commit_msg>chart49: #i114735# fixed assertion during smoketest<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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_chart2.hxx"
#include "ExplicitCategoriesProvider.hxx"
#include "DiagramHelper.hxx"
#include "CommonConverters.hxx"
#include "DataSourceHelper.hxx"
#include "ChartModelHelper.hxx"
#include "ContainerHelper.hxx"
#include "macros.hxx"
//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
using namespace ::com::sun::star::chart2;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::rtl::OUString;
using ::std::vector;
ExplicitCategoriesProvider::ExplicitCategoriesProvider( const Reference< chart2::XCoordinateSystem >& xCooSysModel
, const uno::Reference< frame::XModel >& xChartModel )
: m_bDirty(true)
, m_xCooSysModel( xCooSysModel )
, m_xOriginalCategories()
{
try
{
if( xCooSysModel.is() )
{
uno::Reference< XAxis > xAxis( xCooSysModel->getAxisByDimension(0,0) );
if( xAxis.is() )
m_xOriginalCategories = xAxis->getScaleData().Categories;
}
if( m_xOriginalCategories.is() )
{
Reference< chart2::XChartDocument > xChartDoc( xChartModel, uno::UNO_QUERY );
if( xChartDoc.is() )
{
uno::Reference< data::XDataProvider > xDataProvider( xChartDoc->getDataProvider() );
OUString aCatgoriesRange( DataSourceHelper::getRangeFromValues( m_xOriginalCategories ) );
if( xDataProvider.is() && aCatgoriesRange.getLength() )
{
const bool bFirstCellAsLabel = false;
const bool bHasCategories = false;
const uno::Sequence< sal_Int32 > aSequenceMapping;
uno::Reference< data::XDataSource > xColumnCategoriesSource( xDataProvider->createDataSource(
DataSourceHelper::createArguments( aCatgoriesRange, aSequenceMapping, true /*bUseColumns*/
, bFirstCellAsLabel, bHasCategories ) ) );
uno::Reference< data::XDataSource > xRowCategoriesSource( xDataProvider->createDataSource(
DataSourceHelper::createArguments( aCatgoriesRange, aSequenceMapping, false /*bUseColumns*/
, bFirstCellAsLabel, bHasCategories ) ) );
if( xColumnCategoriesSource.is() && xRowCategoriesSource.is() )
{
Sequence< Reference< data::XLabeledDataSequence> > aColumns = xColumnCategoriesSource->getDataSequences();
Sequence< Reference< data::XLabeledDataSequence> > aRows = xRowCategoriesSource->getDataSequences();
sal_Int32 nColumnCount = aColumns.getLength();
sal_Int32 nRowCount = aRows.getLength();
if( nColumnCount>1 && nRowCount>1 )
{
//we have complex categories
//->split them in the direction of the first series
//detect whether the first series is a row or a column
bool bSeriesUsesColumns = true;
::std::vector< Reference< XDataSeries > > aSeries( ChartModelHelper::getDataSeries( xChartModel ) );
if( !aSeries.empty() )
{
uno::Reference< data::XDataSource > xSeriesSource( aSeries.front(), uno::UNO_QUERY );
::rtl::OUString aStringDummy;
bool bDummy;
uno::Sequence< sal_Int32 > aSeqDummy;
DataSourceHelper::readArguments( xDataProvider->detectArguments( xSeriesSource),
aStringDummy, aSeqDummy, bSeriesUsesColumns, bDummy, bDummy );
}
if( bSeriesUsesColumns )
m_aSplitCategoriesList=aColumns;
else
m_aSplitCategoriesList=aRows;
}
}
}
}
if( !m_aSplitCategoriesList.getLength() )
{
m_aSplitCategoriesList.realloc(1);
m_aSplitCategoriesList[0]=m_xOriginalCategories;
}
}
}
catch( const uno::Exception & ex )
{
ASSERT_EXCEPTION( ex );
}
}
ExplicitCategoriesProvider::~ExplicitCategoriesProvider()
{
}
const Sequence< Reference< data::XLabeledDataSequence> >& ExplicitCategoriesProvider::getSplitCategoriesList()
{
return m_aSplitCategoriesList;
}
bool ExplicitCategoriesProvider::hasComplexCategories() const
{
return m_aSplitCategoriesList.getLength() > 1;
}
sal_Int32 ExplicitCategoriesProvider::getCategoryLevelCount() const
{
sal_Int32 nCount = m_aSplitCategoriesList.getLength();
if(!nCount)
nCount = 1;
return nCount;
}
std::vector<sal_Int32> lcl_getLimitingBorders( const std::vector< ComplexCategory >& rComplexCategories )
{
std::vector<sal_Int32> aLimitingBorders;
std::vector< ComplexCategory >::const_iterator aIt( rComplexCategories.begin() );
std::vector< ComplexCategory >::const_iterator aEnd( rComplexCategories.end() );
sal_Int32 nBorderIndex = 0; /*border below the index*/
for( ; aIt != aEnd; ++aIt )
{
ComplexCategory aComplexCategory(*aIt);
nBorderIndex += aComplexCategory.Count;
aLimitingBorders.push_back(nBorderIndex);
}
return aLimitingBorders;
}
uno::Sequence< rtl::OUString > lcl_DataToStringSequence( const uno::Reference< data::XDataSequence >& xDataSequence )
{
uno::Sequence< rtl::OUString > aStrings;
OSL_ASSERT( xDataSequence.is());
if( !xDataSequence.is() )
return aStrings;
uno::Reference< data::XTextualDataSequence > xTextualDataSequence( xDataSequence, uno::UNO_QUERY );
if( xTextualDataSequence.is() )
{
aStrings = xTextualDataSequence->getTextualData();
}
else
{
uno::Sequence< uno::Any > aValues = xDataSequence->getData();
aStrings.realloc(aValues.getLength());
for(sal_Int32 nN=aValues.getLength();nN--;)
aValues[nN] >>= aStrings[nN];
}
return aStrings;
}
SplitCategoriesProvider::~SplitCategoriesProvider()
{
}
class SplitCategoriesProvider_ForLabeledDataSequences : public SplitCategoriesProvider
{
public:
explicit SplitCategoriesProvider_ForLabeledDataSequences( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference<
::com::sun::star::chart2::data::XLabeledDataSequence> >& rSplitCategoriesList )
: m_rSplitCategoriesList( rSplitCategoriesList )
{}
virtual ~SplitCategoriesProvider_ForLabeledDataSequences()
{}
virtual sal_Int32 getLevelCount() const;
virtual uno::Sequence< rtl::OUString > getStringsForLevel( sal_Int32 nIndex ) const;
private:
const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference<
::com::sun::star::chart2::data::XLabeledDataSequence> >& m_rSplitCategoriesList;
};
sal_Int32 SplitCategoriesProvider_ForLabeledDataSequences::getLevelCount() const
{
return m_rSplitCategoriesList.getLength();
}
uno::Sequence< rtl::OUString > SplitCategoriesProvider_ForLabeledDataSequences::getStringsForLevel( sal_Int32 nLevel ) const
{
uno::Sequence< rtl::OUString > aRet;
Reference< data::XLabeledDataSequence > xLabeledDataSequence( m_rSplitCategoriesList[nLevel] );
if( xLabeledDataSequence.is() )
aRet = lcl_DataToStringSequence( xLabeledDataSequence->getValues() );
return aRet;
}
std::vector< ComplexCategory > lcl_DataSequenceToComplexCategoryVector(
const uno::Sequence< rtl::OUString >& rStrings
, const std::vector<sal_Int32>& rLimitingBorders, bool bCreateSingleCategories )
{
std::vector< ComplexCategory > aResult;
sal_Int32 nMaxCount = rStrings.getLength();
OUString aPrevious;
sal_Int32 nCurrentCount=0;
for( sal_Int32 nN=0; nN<nMaxCount; nN++ )
{
OUString aCurrent = rStrings[nN];
if( bCreateSingleCategories || ::std::find( rLimitingBorders.begin(), rLimitingBorders.end(), nN ) != rLimitingBorders.end() )
{
aResult.push_back( ComplexCategory(aPrevious,nCurrentCount) );
nCurrentCount=1;
aPrevious = aCurrent;
}
else
{
if( aCurrent.getLength() && aPrevious != aCurrent )
{
aResult.push_back( ComplexCategory(aPrevious,nCurrentCount) );
nCurrentCount=1;
aPrevious = aCurrent;
}
else
nCurrentCount++;
}
}
if( nCurrentCount )
aResult.push_back( ComplexCategory(aPrevious,nCurrentCount) );
return aResult;
}
sal_Int32 lcl_getCategoryCount( std::vector< ComplexCategory >& rComplexCategories )
{
sal_Int32 nCount = 0;
std::vector< ComplexCategory >::iterator aIt( rComplexCategories.begin() );
std::vector< ComplexCategory >::const_iterator aEnd( rComplexCategories.end() );
for( ; aIt != aEnd; ++aIt )
nCount+=aIt->Count;
return nCount;
}
Sequence< OUString > lcl_getExplicitSimpleCategories(
const SplitCategoriesProvider& rSplitCategoriesProvider,
::std::vector< ::std::vector< ComplexCategory > >& rComplexCats )
{
Sequence< OUString > aRet;
rComplexCats.clear();
sal_Int32 nLCount = rSplitCategoriesProvider.getLevelCount();
for( sal_Int32 nL = 0; nL < nLCount; nL++ )
{
std::vector<sal_Int32> aLimitingBorders;
if(nL>0)
aLimitingBorders = lcl_getLimitingBorders( rComplexCats.back() );
rComplexCats.push_back( lcl_DataSequenceToComplexCategoryVector(
rSplitCategoriesProvider.getStringsForLevel(nL), aLimitingBorders, nL==(nLCount-1) ) );
}
std::vector< std::vector< ComplexCategory > >::iterator aOuterIt( rComplexCats.begin() );
std::vector< std::vector< ComplexCategory > >::const_iterator aOuterEnd( rComplexCats.end() );
//ensure that the category count is the same on each level
sal_Int32 nMaxCategoryCount = 0;
{
for( aOuterIt=rComplexCats.begin(); aOuterIt != aOuterEnd; ++aOuterIt )
{
sal_Int32 nCurrentCount = lcl_getCategoryCount( *aOuterIt );
nMaxCategoryCount = std::max( nCurrentCount, nMaxCategoryCount );
}
for( aOuterIt=rComplexCats.begin(); aOuterIt != aOuterEnd; ++aOuterIt )
{
sal_Int32 nCurrentCount = lcl_getCategoryCount( *aOuterIt );
if( nCurrentCount< nMaxCategoryCount )
{
ComplexCategory& rComplexCategory = aOuterIt->back();
rComplexCategory.Count += (nMaxCategoryCount-nCurrentCount);
}
}
}
//create a list with an element for every index
std::vector< std::vector< ComplexCategory > > aComplexCatsPerIndex;
for( aOuterIt=rComplexCats.begin() ; aOuterIt != aOuterEnd; ++aOuterIt )
{
std::vector< ComplexCategory > aSingleLevel;
std::vector< ComplexCategory >::iterator aIt( aOuterIt->begin() );
std::vector< ComplexCategory >::const_iterator aEnd( aOuterIt->end() );
for( ; aIt != aEnd; ++aIt )
{
ComplexCategory aComplexCategory( *aIt );
sal_Int32 nCount = aComplexCategory.Count;
while( nCount-- )
aSingleLevel.push_back(aComplexCategory);
}
aComplexCatsPerIndex.push_back( aSingleLevel );
}
if(nMaxCategoryCount)
{
aRet.realloc(nMaxCategoryCount);
aOuterEnd = aComplexCatsPerIndex.end();
OUString aSpace(C2U(" "));
for(sal_Int32 nN=0; nN<nMaxCategoryCount; nN++)
{
OUString aText;
for( aOuterIt=aComplexCatsPerIndex.begin() ; aOuterIt != aOuterEnd; ++aOuterIt )
{
OUString aAddText = (*aOuterIt)[nN].Text;
if( aAddText.getLength() )
{
if(aText.getLength())
aText += aSpace;
aText += aAddText;
}
}
aRet[nN]=aText;
}
}
return aRet;
}
//static
Sequence< OUString > ExplicitCategoriesProvider::getExplicitSimpleCategories(
const SplitCategoriesProvider& rSplitCategoriesProvider )
{
vector< vector< ComplexCategory > > aComplexCats;
return lcl_getExplicitSimpleCategories( rSplitCategoriesProvider, aComplexCats );
}
void ExplicitCategoriesProvider::init()
{
if( m_bDirty )
{
m_aExplicitCategories.realloc(0);
m_aComplexCats.clear();//not one per index
if( m_xOriginalCategories.is() )
{
if( !hasComplexCategories() )
m_aExplicitCategories = DataSequenceToStringSequence(m_xOriginalCategories->getValues());
else
m_aExplicitCategories = lcl_getExplicitSimpleCategories(
SplitCategoriesProvider_ForLabeledDataSequences( m_aSplitCategoriesList ), m_aComplexCats );
}
if(!m_aExplicitCategories.getLength())
m_aExplicitCategories = DiagramHelper::generateAutomaticCategoriesFromCooSys( m_xCooSysModel );
m_bDirty = false;
}
}
Sequence< ::rtl::OUString > ExplicitCategoriesProvider::getSimpleCategories()
{
init();
return m_aExplicitCategories;
}
std::vector< ComplexCategory > ExplicitCategoriesProvider::getCategoriesByLevel( sal_Int32 nLevel )
{
std::vector< ComplexCategory > aRet;
init();
sal_Int32 nMaxIndex = m_aComplexCats.size()-1;
if( nLevel >= 0 && nLevel <= nMaxIndex )
aRet = m_aComplexCats[nMaxIndex-nLevel];
return aRet;
}
// static
OUString ExplicitCategoriesProvider::getCategoryByIndex(
const Reference< XCoordinateSystem >& xCooSysModel
, const uno::Reference< frame::XModel >& xChartModel
, sal_Int32 nIndex )
{
if( xCooSysModel.is())
{
ExplicitCategoriesProvider aExplicitCategoriesProvider( xCooSysModel, xChartModel );
Sequence< OUString > aCategories( aExplicitCategoriesProvider.getSimpleCategories());
if( nIndex < aCategories.getLength())
return aCategories[ nIndex ];
}
return OUString();
}
//.............................................................................
} //namespace chart
//.............................................................................
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_tts_api.h"
#include "chrome/common/chrome_switches.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
// Needed for CreateFunctor.
#define GMOCK_MUTANT_INCLUDE_LATE_OBJECT_BINDING
#include "testing/gmock_mutant.h"
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/cros/cros_mock.h"
#endif
using ::testing::AnyNumber;
using ::testing::CreateFunctor;
using ::testing::DoAll;
using ::testing::InSequence;
using ::testing::InvokeWithoutArgs;
using ::testing::Return;
using ::testing::StrictMock;
using ::testing::_;
class MockExtensionTtsPlatformImpl : public ExtensionTtsPlatformImpl {
public:
MOCK_METHOD6(Speak,
bool(const std::string& utterance,
const std::string& locale,
const std::string& gender,
double rate,
double pitch,
double volume));
MOCK_METHOD0(StopSpeaking, bool(void));
MOCK_METHOD0(IsSpeaking, bool(void));
void SetErrorToEpicFail() {
set_error("epic fail");
}
};
class TtsApiTest : public ExtensionApiTest {
public:
virtual void SetUpCommandLine(CommandLine* command_line) {
ExtensionApiTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
}
virtual void SetUpInProcessBrowserTestFixture() {
ExtensionApiTest::SetUpInProcessBrowserTestFixture();
ExtensionTtsController::GetInstance()->SetPlatformImpl(
&mock_platform_impl_);
}
protected:
StrictMock<MockExtensionTtsPlatformImpl> mock_platform_impl_;
};
IN_PROC_BROWSER_TEST_F(TtsApiTest, PlatformSpeakFinishesImmediately) {
InSequence s;
EXPECT_CALL(mock_platform_impl_, StopSpeaking())
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, Speak(_, _, _, _, _, _))
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, IsSpeaking())
.WillOnce(Return(false));
ASSERT_TRUE(RunExtensionTest("tts/speak_once")) << message_;
}
IN_PROC_BROWSER_TEST_F(TtsApiTest, PlatformSpeakKeepsSpeakingTwice) {
InSequence s;
EXPECT_CALL(mock_platform_impl_, StopSpeaking())
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, Speak(_, _, _, _, _, _))
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, IsSpeaking())
.WillOnce(Return(true))
.WillOnce(Return(true))
.WillOnce(Return(false));
ASSERT_TRUE(RunExtensionTest("tts/speak_once")) << message_;
}
IN_PROC_BROWSER_TEST_F(TtsApiTest, PlatformSpeakInterrupt) {
// One utterances starts speaking, and then a second interrupts.
InSequence s;
EXPECT_CALL(mock_platform_impl_, StopSpeaking())
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, Speak("text 1", _, _, _, _, _))
.WillOnce(Return(true));
// Ensure that the first utterance keeps going until it's interrupted.
EXPECT_CALL(mock_platform_impl_, IsSpeaking())
.Times(AnyNumber())
.WillRepeatedly(Return(true));
// Expect the second utterance and allow it to continue for two calls to
// IsSpeaking and then finish successfully.
EXPECT_CALL(mock_platform_impl_, StopSpeaking())
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, Speak("text 2", _, _, _, _, _))
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, IsSpeaking())
.WillOnce(Return(true))
.WillOnce(Return(true))
.WillOnce(Return(false));
ASSERT_TRUE(RunExtensionTest("tts/interrupt")) << message_;
}
IN_PROC_BROWSER_TEST_F(TtsApiTest, PlatformSpeakQueueInterrupt) {
// In this test, two utterances are queued, and then a third
// interrupts. Speak() never gets called on the second utterance.
InSequence s;
EXPECT_CALL(mock_platform_impl_, StopSpeaking())
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, Speak("text 1", _, _, _, _, _))
.WillOnce(Return(true));
// Ensure that the first utterance keeps going until it's interrupted.
EXPECT_CALL(mock_platform_impl_, IsSpeaking())
.Times(AnyNumber())
.WillRepeatedly(Return(true));
// Expect the third utterance and allow it to continue for two calls to
// IsSpeaking and then finish successfully.
EXPECT_CALL(mock_platform_impl_, StopSpeaking())
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, Speak("text 3", _, _, _, _, _))
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, IsSpeaking())
.WillOnce(Return(true))
.WillOnce(Return(true))
.WillOnce(Return(false));
ASSERT_TRUE(RunExtensionTest("tts/queue_interrupt")) << message_;
}
IN_PROC_BROWSER_TEST_F(TtsApiTest, PlatformSpeakEnqueue) {
InSequence s;
EXPECT_CALL(mock_platform_impl_, StopSpeaking())
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, Speak("text 1", _, _, _, _, _))
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, IsSpeaking())
.WillOnce(Return(true))
.WillOnce(Return(true))
.WillOnce(Return(false));
EXPECT_CALL(mock_platform_impl_, Speak("text 2", _, _, _, _, _))
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, IsSpeaking())
.WillOnce(Return(true))
.WillOnce(Return(true))
.WillOnce(Return(false));
ASSERT_TRUE(RunExtensionTest("tts/enqueue")) << message_;
}
IN_PROC_BROWSER_TEST_F(TtsApiTest, PlatformSpeakError) {
InSequence s;
EXPECT_CALL(mock_platform_impl_, StopSpeaking())
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, Speak(_, _, _, _, _, _))
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, IsSpeaking())
.WillOnce(Return(false));
EXPECT_CALL(mock_platform_impl_, StopSpeaking())
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, Speak(_, _, _, _, _, _))
.WillOnce(DoAll(
InvokeWithoutArgs(
CreateFunctor(&mock_platform_impl_,
&MockExtensionTtsPlatformImpl::SetErrorToEpicFail)),
Return(false)));
EXPECT_CALL(mock_platform_impl_, StopSpeaking())
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, Speak(_, _, _, _, _, _))
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, IsSpeaking())
.WillOnce(Return(false));
ASSERT_TRUE(RunExtensionTest("tts/speak_error")) << message_;
}
IN_PROC_BROWSER_TEST_F(TtsApiTest, Provide) {
EXPECT_CALL(mock_platform_impl_, StopSpeaking())
.WillRepeatedly(Return(true));
EXPECT_CALL(mock_platform_impl_, IsSpeaking())
.WillRepeatedly(Return(false));
{
InSequence s;
EXPECT_CALL(mock_platform_impl_, Speak("native speech", _, _, _, _, _))
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, Speak("native speech 2", _, _, _, _, _))
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, Speak("native speech 3", _, _, _, _, _))
.WillOnce(Return(true));
}
ASSERT_TRUE(RunExtensionTest("tts/provide")) << message_;
}
#if defined(OS_CHROMEOS)
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TtsChromeOs) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
chromeos::CrosMock crosMock;
crosMock.InitMockSpeechSynthesisLibrary();
crosMock.SetSpeechSynthesisLibraryExpectations();
ASSERT_TRUE(RunExtensionTest("tts/chromeos")) << message_;
}
#endif
<commit_msg>Mark TtsApiTest.Provide as flaky on Windows.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_tts_api.h"
#include "chrome/common/chrome_switches.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
// Needed for CreateFunctor.
#define GMOCK_MUTANT_INCLUDE_LATE_OBJECT_BINDING
#include "testing/gmock_mutant.h"
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/cros/cros_mock.h"
#endif
using ::testing::AnyNumber;
using ::testing::CreateFunctor;
using ::testing::DoAll;
using ::testing::InSequence;
using ::testing::InvokeWithoutArgs;
using ::testing::Return;
using ::testing::StrictMock;
using ::testing::_;
class MockExtensionTtsPlatformImpl : public ExtensionTtsPlatformImpl {
public:
MOCK_METHOD6(Speak,
bool(const std::string& utterance,
const std::string& locale,
const std::string& gender,
double rate,
double pitch,
double volume));
MOCK_METHOD0(StopSpeaking, bool(void));
MOCK_METHOD0(IsSpeaking, bool(void));
void SetErrorToEpicFail() {
set_error("epic fail");
}
};
class TtsApiTest : public ExtensionApiTest {
public:
virtual void SetUpCommandLine(CommandLine* command_line) {
ExtensionApiTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
}
virtual void SetUpInProcessBrowserTestFixture() {
ExtensionApiTest::SetUpInProcessBrowserTestFixture();
ExtensionTtsController::GetInstance()->SetPlatformImpl(
&mock_platform_impl_);
}
protected:
StrictMock<MockExtensionTtsPlatformImpl> mock_platform_impl_;
};
IN_PROC_BROWSER_TEST_F(TtsApiTest, PlatformSpeakFinishesImmediately) {
InSequence s;
EXPECT_CALL(mock_platform_impl_, StopSpeaking())
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, Speak(_, _, _, _, _, _))
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, IsSpeaking())
.WillOnce(Return(false));
ASSERT_TRUE(RunExtensionTest("tts/speak_once")) << message_;
}
IN_PROC_BROWSER_TEST_F(TtsApiTest, PlatformSpeakKeepsSpeakingTwice) {
InSequence s;
EXPECT_CALL(mock_platform_impl_, StopSpeaking())
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, Speak(_, _, _, _, _, _))
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, IsSpeaking())
.WillOnce(Return(true))
.WillOnce(Return(true))
.WillOnce(Return(false));
ASSERT_TRUE(RunExtensionTest("tts/speak_once")) << message_;
}
IN_PROC_BROWSER_TEST_F(TtsApiTest, PlatformSpeakInterrupt) {
// One utterances starts speaking, and then a second interrupts.
InSequence s;
EXPECT_CALL(mock_platform_impl_, StopSpeaking())
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, Speak("text 1", _, _, _, _, _))
.WillOnce(Return(true));
// Ensure that the first utterance keeps going until it's interrupted.
EXPECT_CALL(mock_platform_impl_, IsSpeaking())
.Times(AnyNumber())
.WillRepeatedly(Return(true));
// Expect the second utterance and allow it to continue for two calls to
// IsSpeaking and then finish successfully.
EXPECT_CALL(mock_platform_impl_, StopSpeaking())
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, Speak("text 2", _, _, _, _, _))
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, IsSpeaking())
.WillOnce(Return(true))
.WillOnce(Return(true))
.WillOnce(Return(false));
ASSERT_TRUE(RunExtensionTest("tts/interrupt")) << message_;
}
IN_PROC_BROWSER_TEST_F(TtsApiTest, PlatformSpeakQueueInterrupt) {
// In this test, two utterances are queued, and then a third
// interrupts. Speak() never gets called on the second utterance.
InSequence s;
EXPECT_CALL(mock_platform_impl_, StopSpeaking())
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, Speak("text 1", _, _, _, _, _))
.WillOnce(Return(true));
// Ensure that the first utterance keeps going until it's interrupted.
EXPECT_CALL(mock_platform_impl_, IsSpeaking())
.Times(AnyNumber())
.WillRepeatedly(Return(true));
// Expect the third utterance and allow it to continue for two calls to
// IsSpeaking and then finish successfully.
EXPECT_CALL(mock_platform_impl_, StopSpeaking())
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, Speak("text 3", _, _, _, _, _))
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, IsSpeaking())
.WillOnce(Return(true))
.WillOnce(Return(true))
.WillOnce(Return(false));
ASSERT_TRUE(RunExtensionTest("tts/queue_interrupt")) << message_;
}
IN_PROC_BROWSER_TEST_F(TtsApiTest, PlatformSpeakEnqueue) {
InSequence s;
EXPECT_CALL(mock_platform_impl_, StopSpeaking())
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, Speak("text 1", _, _, _, _, _))
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, IsSpeaking())
.WillOnce(Return(true))
.WillOnce(Return(true))
.WillOnce(Return(false));
EXPECT_CALL(mock_platform_impl_, Speak("text 2", _, _, _, _, _))
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, IsSpeaking())
.WillOnce(Return(true))
.WillOnce(Return(true))
.WillOnce(Return(false));
ASSERT_TRUE(RunExtensionTest("tts/enqueue")) << message_;
}
IN_PROC_BROWSER_TEST_F(TtsApiTest, PlatformSpeakError) {
InSequence s;
EXPECT_CALL(mock_platform_impl_, StopSpeaking())
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, Speak(_, _, _, _, _, _))
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, IsSpeaking())
.WillOnce(Return(false));
EXPECT_CALL(mock_platform_impl_, StopSpeaking())
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, Speak(_, _, _, _, _, _))
.WillOnce(DoAll(
InvokeWithoutArgs(
CreateFunctor(&mock_platform_impl_,
&MockExtensionTtsPlatformImpl::SetErrorToEpicFail)),
Return(false)));
EXPECT_CALL(mock_platform_impl_, StopSpeaking())
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, Speak(_, _, _, _, _, _))
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, IsSpeaking())
.WillOnce(Return(false));
ASSERT_TRUE(RunExtensionTest("tts/speak_error")) << message_;
}
#if defined(OS_WIN)
// Flakily fails on Windows: http://crbug.com/70198
#define MAYBE_Provide FLAKY_Provide
#else
#define MAYBE_Provide Provide
#endif
IN_PROC_BROWSER_TEST_F(TtsApiTest, MAYBE_Provide) {
EXPECT_CALL(mock_platform_impl_, StopSpeaking())
.WillRepeatedly(Return(true));
EXPECT_CALL(mock_platform_impl_, IsSpeaking())
.WillRepeatedly(Return(false));
{
InSequence s;
EXPECT_CALL(mock_platform_impl_, Speak("native speech", _, _, _, _, _))
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, Speak("native speech 2", _, _, _, _, _))
.WillOnce(Return(true));
EXPECT_CALL(mock_platform_impl_, Speak("native speech 3", _, _, _, _, _))
.WillOnce(Return(true));
}
ASSERT_TRUE(RunExtensionTest("tts/provide")) << message_;
}
#if defined(OS_CHROMEOS)
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TtsChromeOs) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
chromeos::CrosMock crosMock;
crosMock.InitMockSpeechSynthesisLibrary();
crosMock.SetSpeechSynthesisLibraryExpectations();
ASSERT_TRUE(RunExtensionTest("tts/chromeos")) << message_;
}
#endif
<|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 <gtk/gtk.h>
#include "base/string_util.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/gtk/bookmark_editor_gtk.h"
#include "chrome/browser/gtk/bookmark_tree_model.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#include "chrome/test/testing_profile.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::Time;
using base::TimeDelta;
using bookmark_utils::GetTitleFromTreeIter;
// Base class for bookmark editor tests. This class is a copy from
// bookmark_editor_view_unittest.cc, and all the tests in this file are
// GTK-ifications of the corresponding views tests. Testing here is really
// important because on Linux, we make round trip copies from chrome's
// BookmarkModel class to GTK's native GtkTreeStore.
class BookmarkEditorGtkTest : public testing::Test {
public:
BookmarkEditorGtkTest() : model_(NULL) {
}
virtual void SetUp() {
profile_.reset(new TestingProfile());
profile_->set_has_history_service(true);
profile_->CreateBookmarkModel(true);
model_ = profile_->GetBookmarkModel();
AddTestData();
}
virtual void TearDown() {
}
protected:
MessageLoopForUI message_loop_;
BookmarkModel* model_;
scoped_ptr<TestingProfile> profile_;
std::string base_path() const { return "file:///c:/tmp/"; }
BookmarkNode* GetNode(const std::string& name) {
return model_->GetMostRecentlyAddedNodeForURL(GURL(base_path() + name));
}
private:
// Creates the following structure:
// bookmark bar node
// a
// F1
// f1a
// F11
// f11a
// F2
// other node
// oa
// OF1
// of1a
void AddTestData() {
std::string test_base = base_path();
model_->AddURL(model_->GetBookmarkBarNode(), 0, L"a",
GURL(test_base + "a"));
BookmarkNode* f1 = model_->AddGroup(model_->GetBookmarkBarNode(), 1, L"F1");
model_->AddURL(f1, 0, L"f1a", GURL(test_base + "f1a"));
BookmarkNode* f11 = model_->AddGroup(f1, 1, L"F11");
model_->AddURL(f11, 0, L"f11a", GURL(test_base + "f11a"));
model_->AddGroup(model_->GetBookmarkBarNode(), 2, L"F2");
// Children of the other node.
model_->AddURL(model_->other_node(), 0, L"oa",
GURL(test_base + "oa"));
BookmarkNode* of1 = model_->AddGroup(model_->other_node(), 1, L"OF1");
model_->AddURL(of1, 0, L"of1a", GURL(test_base + "of1a"));
}
};
// Makes sure the tree model matches that of the bookmark bar model.
// Disabled: See crbug.com/15436
TEST_F(BookmarkEditorGtkTest, DISABLED_ModelsMatch) {
BookmarkEditorGtk editor(NULL, profile_.get(), NULL, NULL,
BookmarkEditor::SHOW_TREE, NULL);
// The root should have two children, one for the bookmark bar node,
// the other for the 'other bookmarks' folder.
GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
GtkTreeIter toplevel;
ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &toplevel));
GtkTreeIter bookmark_bar_node = toplevel;
ASSERT_TRUE(gtk_tree_model_iter_next(store, &toplevel));
GtkTreeIter other_node = toplevel;
ASSERT_FALSE(gtk_tree_model_iter_next(store, &toplevel));
// The bookmark bar should have 2 nodes: folder F1 and F2.
GtkTreeIter f1_iter;
GtkTreeIter child;
ASSERT_EQ(2, gtk_tree_model_iter_n_children(store, &bookmark_bar_node));
ASSERT_TRUE(gtk_tree_model_iter_children(store, &child, &bookmark_bar_node));
f1_iter = child;
ASSERT_EQ(L"F1", GetTitleFromTreeIter(store, &child));
ASSERT_TRUE(gtk_tree_model_iter_next(store, &child));
ASSERT_EQ(L"F2", GetTitleFromTreeIter(store, &child));
ASSERT_FALSE(gtk_tree_model_iter_next(store, &child));
// F1 should have one child, F11
ASSERT_EQ(1, gtk_tree_model_iter_n_children(store, &f1_iter));
ASSERT_TRUE(gtk_tree_model_iter_children(store, &child, &f1_iter));
ASSERT_EQ(L"F11", GetTitleFromTreeIter(store, &child));
ASSERT_FALSE(gtk_tree_model_iter_next(store, &child));
// Other node should have one child (OF1).
ASSERT_EQ(1, gtk_tree_model_iter_n_children(store, &other_node));
ASSERT_TRUE(gtk_tree_model_iter_children(store, &child, &other_node));
ASSERT_EQ(L"OF1", GetTitleFromTreeIter(store, &child));
ASSERT_FALSE(gtk_tree_model_iter_next(store, &child));
}
// Changes the title and makes sure parent/visual order doesn't change.
TEST_F(BookmarkEditorGtkTest, EditTitleKeepsPosition) {
BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"),
BookmarkEditor::SHOW_TREE, NULL);
gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a");
GtkTreeIter bookmark_bar_node;
GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node));
editor.ApplyEdits(&bookmark_bar_node);
BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode();
ASSERT_EQ(L"new_a", bb_node->GetChild(0)->GetTitle());
// The URL shouldn't have changed.
ASSERT_TRUE(GURL(base_path() + "a") == bb_node->GetChild(0)->GetURL());
}
// Changes the url and makes sure parent/visual order doesn't change.
TEST_F(BookmarkEditorGtkTest, EditURLKeepsPosition) {
Time node_time = Time::Now() + TimeDelta::FromDays(2);
GetNode("a")->date_added_ = node_time;
BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"),
BookmarkEditor::SHOW_TREE, NULL);
gtk_entry_set_text(GTK_ENTRY(editor.url_entry_),
GURL(base_path() + "new_a").spec().c_str());
GtkTreeIter bookmark_bar_node;
GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node));
editor.ApplyEdits(&bookmark_bar_node);
BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode();
ASSERT_EQ(L"a", bb_node->GetChild(0)->GetTitle());
// The URL should have changed.
ASSERT_TRUE(GURL(base_path() + "new_a") == bb_node->GetChild(0)->GetURL());
ASSERT_TRUE(node_time == bb_node->GetChild(0)->date_added());
}
// Moves 'a' to be a child of the other node.
TEST_F(BookmarkEditorGtkTest, ChangeParent) {
BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"),
BookmarkEditor::SHOW_TREE, NULL);
GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
GtkTreeIter gtk_other_node;
ASSERT_TRUE(gtk_tree_model_get_iter_first(store, >k_other_node));
ASSERT_TRUE(gtk_tree_model_iter_next(store, >k_other_node));
editor.ApplyEdits(>k_other_node);
BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node();
ASSERT_EQ(L"a", other_node->GetChild(2)->GetTitle());
ASSERT_TRUE(GURL(base_path() + "a") == other_node->GetChild(2)->GetURL());
}
// Moves 'a' to be a child of the other node.
// Moves 'a' to be a child of the other node and changes its url to new_a.
TEST_F(BookmarkEditorGtkTest, ChangeParentAndURL) {
Time node_time = Time::Now() + TimeDelta::FromDays(2);
GetNode("a")->date_added_ = node_time;
BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"),
BookmarkEditor::SHOW_TREE, NULL);
gtk_entry_set_text(GTK_ENTRY(editor.url_entry_),
GURL(base_path() + "new_a").spec().c_str());
GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
GtkTreeIter gtk_other_node;
ASSERT_TRUE(gtk_tree_model_get_iter_first(store, >k_other_node));
ASSERT_TRUE(gtk_tree_model_iter_next(store, >k_other_node));
editor.ApplyEdits(>k_other_node);
BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node();
ASSERT_EQ(L"a", other_node->GetChild(2)->GetTitle());
ASSERT_TRUE(GURL(base_path() + "new_a") == other_node->GetChild(2)->GetURL());
ASSERT_TRUE(node_time == other_node->GetChild(2)->date_added());
}
// Creates a new folder and moves a node to it.
TEST_F(BookmarkEditorGtkTest, MoveToNewParent) {
BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"),
BookmarkEditor::SHOW_TREE, NULL);
GtkTreeIter bookmark_bar_node;
GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node));
// The bookmark bar should have 2 nodes: folder F1 and F2.
GtkTreeIter f2_iter;
ASSERT_EQ(2, gtk_tree_model_iter_n_children(store, &bookmark_bar_node));
ASSERT_TRUE(gtk_tree_model_iter_children(store, &f2_iter,
&bookmark_bar_node));
ASSERT_TRUE(gtk_tree_model_iter_next(store, &f2_iter));
// Create two nodes: "F21" as a child of "F2" and "F211" as a child of "F21".
GtkTreeIter f21_iter;
editor.AddNewGroup(&f2_iter, &f21_iter);
gtk_tree_store_set(editor.tree_store_, &f21_iter,
bookmark_utils::FOLDER_NAME, "F21", -1);
GtkTreeIter f211_iter;
editor.AddNewGroup(&f21_iter, &f211_iter);
gtk_tree_store_set(editor.tree_store_, &f211_iter,
bookmark_utils::FOLDER_NAME, "F211", -1);
ASSERT_EQ(1, gtk_tree_model_iter_n_children(store, &f2_iter));
editor.ApplyEdits(&f2_iter);
BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode();
BookmarkNode* mf2 = bb_node->GetChild(1);
// F2 in the model should have two children now: F21 and the node edited.
ASSERT_EQ(2, mf2->GetChildCount());
// F21 should be first.
ASSERT_EQ(L"F21", mf2->GetChild(0)->GetTitle());
// Then a.
ASSERT_EQ(L"a", mf2->GetChild(1)->GetTitle());
// F21 should have one child, F211.
BookmarkNode* mf21 = mf2->GetChild(0);
ASSERT_EQ(1, mf21->GetChildCount());
ASSERT_EQ(L"F211", mf21->GetChild(0)->GetTitle());
}
// Brings up the editor, creating a new URL on the bookmark bar.
TEST_F(BookmarkEditorGtkTest, NewURL) {
BookmarkEditorGtk editor(NULL, profile_.get(), NULL, NULL,
BookmarkEditor::SHOW_TREE, NULL);
gtk_entry_set_text(GTK_ENTRY(editor.url_entry_),
GURL(base_path() + "a").spec().c_str());
gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a");
GtkTreeIter bookmark_bar_node;
GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node));
editor.ApplyEdits(&bookmark_bar_node);
BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode();
ASSERT_EQ(4, bb_node->GetChildCount());
BookmarkNode* new_node = bb_node->GetChild(3);
EXPECT_EQ(L"new_a", new_node->GetTitle());
EXPECT_TRUE(GURL(base_path() + "a") == new_node->GetURL());
}
// Brings up the editor with no tree and modifies the url.
TEST_F(BookmarkEditorGtkTest, ChangeURLNoTree) {
BookmarkEditorGtk editor(NULL, profile_.get(), NULL,
model_->other_node()->GetChild(0),
BookmarkEditor::NO_TREE, NULL);
gtk_entry_set_text(GTK_ENTRY(editor.url_entry_),
GURL(base_path() + "a").spec().c_str());
gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a");
editor.ApplyEdits(NULL);
BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node();
ASSERT_EQ(2, other_node->GetChildCount());
BookmarkNode* new_node = other_node->GetChild(0);
EXPECT_EQ(L"new_a", new_node->GetTitle());
EXPECT_TRUE(GURL(base_path() + "a") == new_node->GetURL());
}
// Brings up the editor with no tree and modifies only the title.
TEST_F(BookmarkEditorGtkTest, ChangeTitleNoTree) {
BookmarkEditorGtk editor(NULL, profile_.get(), NULL,
model_->other_node()->GetChild(0),
BookmarkEditor::NO_TREE, NULL);
gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a");
editor.ApplyEdits();
BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node();
ASSERT_EQ(2, other_node->GetChildCount());
BookmarkNode* new_node = other_node->GetChild(0);
EXPECT_EQ(L"new_a", new_node->GetTitle());
}
<commit_msg>Fix breakage<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 <gtk/gtk.h>
#include "base/string_util.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/gtk/bookmark_editor_gtk.h"
#include "chrome/browser/gtk/bookmark_tree_model.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#include "chrome/test/testing_profile.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::Time;
using base::TimeDelta;
using bookmark_utils::GetTitleFromTreeIter;
// Base class for bookmark editor tests. This class is a copy from
// bookmark_editor_view_unittest.cc, and all the tests in this file are
// GTK-ifications of the corresponding views tests. Testing here is really
// important because on Linux, we make round trip copies from chrome's
// BookmarkModel class to GTK's native GtkTreeStore.
class BookmarkEditorGtkTest : public testing::Test {
public:
BookmarkEditorGtkTest() : model_(NULL) {
}
virtual void SetUp() {
profile_.reset(new TestingProfile());
profile_->set_has_history_service(true);
profile_->CreateBookmarkModel(true);
model_ = profile_->GetBookmarkModel();
AddTestData();
}
virtual void TearDown() {
}
protected:
MessageLoopForUI message_loop_;
BookmarkModel* model_;
scoped_ptr<TestingProfile> profile_;
std::string base_path() const { return "file:///c:/tmp/"; }
BookmarkNode* GetNode(const std::string& name) {
return model_->GetMostRecentlyAddedNodeForURL(GURL(base_path() + name));
}
private:
// Creates the following structure:
// bookmark bar node
// a
// F1
// f1a
// F11
// f11a
// F2
// other node
// oa
// OF1
// of1a
void AddTestData() {
std::string test_base = base_path();
model_->AddURL(model_->GetBookmarkBarNode(), 0, L"a",
GURL(test_base + "a"));
BookmarkNode* f1 = model_->AddGroup(model_->GetBookmarkBarNode(), 1, L"F1");
model_->AddURL(f1, 0, L"f1a", GURL(test_base + "f1a"));
BookmarkNode* f11 = model_->AddGroup(f1, 1, L"F11");
model_->AddURL(f11, 0, L"f11a", GURL(test_base + "f11a"));
model_->AddGroup(model_->GetBookmarkBarNode(), 2, L"F2");
// Children of the other node.
model_->AddURL(model_->other_node(), 0, L"oa",
GURL(test_base + "oa"));
BookmarkNode* of1 = model_->AddGroup(model_->other_node(), 1, L"OF1");
model_->AddURL(of1, 0, L"of1a", GURL(test_base + "of1a"));
}
};
// Makes sure the tree model matches that of the bookmark bar model.
// Disabled: See crbug.com/15436
#if 0
TEST_F(BookmarkEditorGtkTest, ModelsMatch) {
BookmarkEditorGtk editor(NULL, profile_.get(), NULL, NULL,
BookmarkEditor::SHOW_TREE, NULL);
// The root should have two children, one for the bookmark bar node,
// the other for the 'other bookmarks' folder.
GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
GtkTreeIter toplevel;
ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &toplevel));
GtkTreeIter bookmark_bar_node = toplevel;
ASSERT_TRUE(gtk_tree_model_iter_next(store, &toplevel));
GtkTreeIter other_node = toplevel;
ASSERT_FALSE(gtk_tree_model_iter_next(store, &toplevel));
// The bookmark bar should have 2 nodes: folder F1 and F2.
GtkTreeIter f1_iter;
GtkTreeIter child;
ASSERT_EQ(2, gtk_tree_model_iter_n_children(store, &bookmark_bar_node));
ASSERT_TRUE(gtk_tree_model_iter_children(store, &child, &bookmark_bar_node));
f1_iter = child;
ASSERT_EQ(L"F1", GetTitleFromTreeIter(store, &child));
ASSERT_TRUE(gtk_tree_model_iter_next(store, &child));
ASSERT_EQ(L"F2", GetTitleFromTreeIter(store, &child));
ASSERT_FALSE(gtk_tree_model_iter_next(store, &child));
// F1 should have one child, F11
ASSERT_EQ(1, gtk_tree_model_iter_n_children(store, &f1_iter));
ASSERT_TRUE(gtk_tree_model_iter_children(store, &child, &f1_iter));
ASSERT_EQ(L"F11", GetTitleFromTreeIter(store, &child));
ASSERT_FALSE(gtk_tree_model_iter_next(store, &child));
// Other node should have one child (OF1).
ASSERT_EQ(1, gtk_tree_model_iter_n_children(store, &other_node));
ASSERT_TRUE(gtk_tree_model_iter_children(store, &child, &other_node));
ASSERT_EQ(L"OF1", GetTitleFromTreeIter(store, &child));
ASSERT_FALSE(gtk_tree_model_iter_next(store, &child));
}
#endif
// Changes the title and makes sure parent/visual order doesn't change.
TEST_F(BookmarkEditorGtkTest, EditTitleKeepsPosition) {
BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"),
BookmarkEditor::SHOW_TREE, NULL);
gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a");
GtkTreeIter bookmark_bar_node;
GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node));
editor.ApplyEdits(&bookmark_bar_node);
BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode();
ASSERT_EQ(L"new_a", bb_node->GetChild(0)->GetTitle());
// The URL shouldn't have changed.
ASSERT_TRUE(GURL(base_path() + "a") == bb_node->GetChild(0)->GetURL());
}
// Changes the url and makes sure parent/visual order doesn't change.
TEST_F(BookmarkEditorGtkTest, EditURLKeepsPosition) {
Time node_time = Time::Now() + TimeDelta::FromDays(2);
GetNode("a")->date_added_ = node_time;
BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"),
BookmarkEditor::SHOW_TREE, NULL);
gtk_entry_set_text(GTK_ENTRY(editor.url_entry_),
GURL(base_path() + "new_a").spec().c_str());
GtkTreeIter bookmark_bar_node;
GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node));
editor.ApplyEdits(&bookmark_bar_node);
BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode();
ASSERT_EQ(L"a", bb_node->GetChild(0)->GetTitle());
// The URL should have changed.
ASSERT_TRUE(GURL(base_path() + "new_a") == bb_node->GetChild(0)->GetURL());
ASSERT_TRUE(node_time == bb_node->GetChild(0)->date_added());
}
// Moves 'a' to be a child of the other node.
TEST_F(BookmarkEditorGtkTest, ChangeParent) {
BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"),
BookmarkEditor::SHOW_TREE, NULL);
GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
GtkTreeIter gtk_other_node;
ASSERT_TRUE(gtk_tree_model_get_iter_first(store, >k_other_node));
ASSERT_TRUE(gtk_tree_model_iter_next(store, >k_other_node));
editor.ApplyEdits(>k_other_node);
BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node();
ASSERT_EQ(L"a", other_node->GetChild(2)->GetTitle());
ASSERT_TRUE(GURL(base_path() + "a") == other_node->GetChild(2)->GetURL());
}
// Moves 'a' to be a child of the other node.
// Moves 'a' to be a child of the other node and changes its url to new_a.
TEST_F(BookmarkEditorGtkTest, ChangeParentAndURL) {
Time node_time = Time::Now() + TimeDelta::FromDays(2);
GetNode("a")->date_added_ = node_time;
BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"),
BookmarkEditor::SHOW_TREE, NULL);
gtk_entry_set_text(GTK_ENTRY(editor.url_entry_),
GURL(base_path() + "new_a").spec().c_str());
GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
GtkTreeIter gtk_other_node;
ASSERT_TRUE(gtk_tree_model_get_iter_first(store, >k_other_node));
ASSERT_TRUE(gtk_tree_model_iter_next(store, >k_other_node));
editor.ApplyEdits(>k_other_node);
BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node();
ASSERT_EQ(L"a", other_node->GetChild(2)->GetTitle());
ASSERT_TRUE(GURL(base_path() + "new_a") == other_node->GetChild(2)->GetURL());
ASSERT_TRUE(node_time == other_node->GetChild(2)->date_added());
}
// Creates a new folder and moves a node to it.
TEST_F(BookmarkEditorGtkTest, MoveToNewParent) {
BookmarkEditorGtk editor(NULL, profile_.get(), NULL, GetNode("a"),
BookmarkEditor::SHOW_TREE, NULL);
GtkTreeIter bookmark_bar_node;
GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node));
// The bookmark bar should have 2 nodes: folder F1 and F2.
GtkTreeIter f2_iter;
ASSERT_EQ(2, gtk_tree_model_iter_n_children(store, &bookmark_bar_node));
ASSERT_TRUE(gtk_tree_model_iter_children(store, &f2_iter,
&bookmark_bar_node));
ASSERT_TRUE(gtk_tree_model_iter_next(store, &f2_iter));
// Create two nodes: "F21" as a child of "F2" and "F211" as a child of "F21".
GtkTreeIter f21_iter;
editor.AddNewGroup(&f2_iter, &f21_iter);
gtk_tree_store_set(editor.tree_store_, &f21_iter,
bookmark_utils::FOLDER_NAME, "F21", -1);
GtkTreeIter f211_iter;
editor.AddNewGroup(&f21_iter, &f211_iter);
gtk_tree_store_set(editor.tree_store_, &f211_iter,
bookmark_utils::FOLDER_NAME, "F211", -1);
ASSERT_EQ(1, gtk_tree_model_iter_n_children(store, &f2_iter));
editor.ApplyEdits(&f2_iter);
BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode();
BookmarkNode* mf2 = bb_node->GetChild(1);
// F2 in the model should have two children now: F21 and the node edited.
ASSERT_EQ(2, mf2->GetChildCount());
// F21 should be first.
ASSERT_EQ(L"F21", mf2->GetChild(0)->GetTitle());
// Then a.
ASSERT_EQ(L"a", mf2->GetChild(1)->GetTitle());
// F21 should have one child, F211.
BookmarkNode* mf21 = mf2->GetChild(0);
ASSERT_EQ(1, mf21->GetChildCount());
ASSERT_EQ(L"F211", mf21->GetChild(0)->GetTitle());
}
// Brings up the editor, creating a new URL on the bookmark bar.
TEST_F(BookmarkEditorGtkTest, NewURL) {
BookmarkEditorGtk editor(NULL, profile_.get(), NULL, NULL,
BookmarkEditor::SHOW_TREE, NULL);
gtk_entry_set_text(GTK_ENTRY(editor.url_entry_),
GURL(base_path() + "a").spec().c_str());
gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a");
GtkTreeIter bookmark_bar_node;
GtkTreeModel* store = GTK_TREE_MODEL(editor.tree_store_);
ASSERT_TRUE(gtk_tree_model_get_iter_first(store, &bookmark_bar_node));
editor.ApplyEdits(&bookmark_bar_node);
BookmarkNode* bb_node = profile_->GetBookmarkModel()->GetBookmarkBarNode();
ASSERT_EQ(4, bb_node->GetChildCount());
BookmarkNode* new_node = bb_node->GetChild(3);
EXPECT_EQ(L"new_a", new_node->GetTitle());
EXPECT_TRUE(GURL(base_path() + "a") == new_node->GetURL());
}
// Brings up the editor with no tree and modifies the url.
TEST_F(BookmarkEditorGtkTest, ChangeURLNoTree) {
BookmarkEditorGtk editor(NULL, profile_.get(), NULL,
model_->other_node()->GetChild(0),
BookmarkEditor::NO_TREE, NULL);
gtk_entry_set_text(GTK_ENTRY(editor.url_entry_),
GURL(base_path() + "a").spec().c_str());
gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a");
editor.ApplyEdits(NULL);
BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node();
ASSERT_EQ(2, other_node->GetChildCount());
BookmarkNode* new_node = other_node->GetChild(0);
EXPECT_EQ(L"new_a", new_node->GetTitle());
EXPECT_TRUE(GURL(base_path() + "a") == new_node->GetURL());
}
// Brings up the editor with no tree and modifies only the title.
TEST_F(BookmarkEditorGtkTest, ChangeTitleNoTree) {
BookmarkEditorGtk editor(NULL, profile_.get(), NULL,
model_->other_node()->GetChild(0),
BookmarkEditor::NO_TREE, NULL);
gtk_entry_set_text(GTK_ENTRY(editor.name_entry_), "new_a");
editor.ApplyEdits();
BookmarkNode* other_node = profile_->GetBookmarkModel()->other_node();
ASSERT_EQ(2, other_node->GetChildCount());
BookmarkNode* new_node = other_node->GetChild(0);
EXPECT_EQ(L"new_a", new_node->GetTitle());
}
<|endoftext|>
|
<commit_before>// Copyright 2014
// ville.kankainen@gmail.com
// ville.kankainen@kangain.com
//
// 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 "PixelCanvas.h"
namespace Gain {
static const char gVertexShader[] =
"attribute vec2 coord2d;\n"
"attribute vec2 texcoord;"
"varying vec2 f_texcoord;"
"uniform mat4 anim;"
"void main() {\n"
" gl_Position = anim * vec4(coord2d.x, -coord2d.y, 0.0, 1.0);"
" f_texcoord = texcoord;"
"}\n";
static const char gFragmentShader[] =
"precision mediump float;\n"
"varying vec2 f_texcoord;"
"uniform sampler2D mytexture;"
"uniform vec4 color;"
"void main(void) {"
" vec2 flipped_texcoord = vec2(f_texcoord.x, f_texcoord.y);"
" gl_FragColor = texture2D(mytexture, flipped_texcoord)*color;"
"}"
;
PixelCanvas::PixelCanvas(int x,int y, int width, int height) :
super(x,y,width,height, gVertexShader, gFragmentShader)
{
pBitmapWidth = width;
pBitmapHeight = height;
pMaxPixelBufferSize = pBitmapWidth*pBitmapHeight;
pBitmap = (unsigned char*)malloc(pMaxPixelBufferSize*4 + 4);
memset(pBitmap,0x00,pMaxPixelBufferSize*4);
}
PixelCanvas::PixelCanvas(int width, int height) :
super(0,0,width,height, gVertexShader, gFragmentShader)
{
pBitmapWidth = width;
pBitmapHeight = height;
pMaxPixelBufferSize = pBitmapWidth*pBitmapHeight;
pBitmap = (unsigned char*)malloc(pMaxPixelBufferSize*4 + 4);
memset(pBitmap,0x00,pMaxPixelBufferSize*4);
}
PixelCanvas::~PixelCanvas() {
}
bool PixelCanvas::initVariables()
{
if(!super::initVariables()) {
return false;
}
const char* attribute_name;
const char* uniform_name;
glGenTextures(1, &texture_id);
glBindTexture(GL_TEXTURE_2D, texture_id);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
GL_CLAMP_TO_EDGE);
//glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, /*GL10.GL_REPLACE*/ GL_MODULATE);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, // target
0, // level, 0 = base, no minimap,
GL_RGBA, // internalformat
pBitmapWidth, // width
pBitmapHeight, // height
0, // border, always 0 in OpenGL ES
GL_RGBA, // format
GL_UNSIGNED_BYTE, // type
pBitmap);
checkGlError("glTexImage2D");
updateBitmap = false;
GLfloat square_texcoords[] = {
// front
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
0.0, 1.0,
};
GL_EXT_FUNC glGenBuffers(1, &vbo_square_texcoords);
checkGlError("glGenBuffers");
GL_EXT_FUNC glBindBuffer(GL_ARRAY_BUFFER, vbo_square_texcoords);
checkGlError("glBindBuffer");
GL_EXT_FUNC glBufferData(GL_ARRAY_BUFFER, sizeof(square_texcoords), square_texcoords, GL_STATIC_DRAW);
checkGlError("glBufferData");
return true;
}
void PixelCanvas::enableAttributes() const
{
super::enableAttributes();
GL_EXT_FUNC glEnableVertexAttribArray(attribute_texcoord);
}
void PixelCanvas::disableAttributes() const
{
GL_EXT_FUNC glDisableVertexAttribArray(attribute_texcoord);
super::disableAttributes();
}
void PixelCanvas::updateG(float sec,float deltaSec)
{
super::updateG(sec,deltaSec);
if(updateBitmap)
{
GL_EXT_FUNC glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture_id);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
GL_CLAMP_TO_EDGE);
//glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, /*GL10.GL_REPLACE*/ GL_MODULATE);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, // target
0, // level, 0 = base, no minimap,
GL_RGBA, // internalformat
pBitmapWidth, // width
pBitmapHeight, // height
0, // border, always 0 in OpenGL ES
GL_RGBA, // format
GL_UNSIGNED_BYTE, // type
pBitmap);
updateBitmap = false;
GL_EXT_FUNC glUniform1i(uniform_mytexture, 0);
GL_EXT_FUNC glEnableVertexAttribArray(attribute_texcoord);
GL_EXT_FUNC glBindBuffer(GL_ARRAY_BUFFER, vbo_square_texcoords);
GL_EXT_FUNC glVertexAttribPointer(
attribute_texcoord, // attribute
2, // number of elements per vertex, here (x,y)
GL_FLOAT, // the type of each element
GL_FALSE, // take our values as-is
0, // no extra data between each position
0 // offset of first element
);
}
}
void PixelCanvas::clear()
{
memset(pBitmap,0x80,pMaxPixelBufferSize);
updateBitmap = true;
}
void PixelCanvas::setPixel(int x, int y, unsigned int abgr)
{
int width = pBitmapWidth;
unsigned int location = y*width + x;
unsigned int* buffer = (unsigned int*)pBitmap;
if(buffer && location < pMaxPixelBufferSize)
{
buffer[location] = abgr;
LOGI("pp");
}
updateBitmap = true;
}
void PixelCanvas::setPixel(int x, int y, char a,char b,char g,char r)
{
unsigned int value = a<<24 | b<<16 | g<<8 | r;
setPixel(x,y,value);
}
void PixelCanvas::getPixel(int x, int y, unsigned int *abgr)
{
int width = pBitmapWidth;
unsigned int location = y*width + x;
unsigned int* buffer = (unsigned int*)pBitmap;
if(buffer && location < pMaxPixelBufferSize)
{
*abgr = buffer[location];
}
}
void PixelCanvas::getPixel(int x, int y, char *a,char *b,char *g,char *r)
{
unsigned int value;
getPixel(x,y,&value);
// a<<24 | b<<16 | g<<8 | r;
*a = value >> 24;
*b = value >> 16;
*g = value >> 8;
*r = value;
}
} /* namespace Gain */
<commit_msg>pixel canvas fix<commit_after>// Copyright 2014
// ville.kankainen@gmail.com
// ville.kankainen@kangain.com
//
// 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 "PixelCanvas.h"
namespace Gain {
static const char gVertexShader[] =
"attribute vec2 coord2d;\n"
"attribute vec2 texcoord;"
"varying vec2 f_texcoord;"
"uniform mat4 anim;"
"void main() {\n"
" gl_Position = anim * vec4(coord2d.x, -coord2d.y, 0.0, 1.0);"
" f_texcoord = texcoord;"
"}\n";
static const char gFragmentShader[] =
"precision mediump float;\n"
"varying vec2 f_texcoord;"
"uniform sampler2D mytexture;"
"uniform vec4 color;"
"void main(void) {"
" vec2 flipped_texcoord = vec2(f_texcoord.x, f_texcoord.y);"
" gl_FragColor = texture2D(mytexture, flipped_texcoord)*color;"
"}"
;
PixelCanvas::PixelCanvas(int x,int y, int width, int height) :
super(x,y,width,height, gVertexShader, gFragmentShader)
{
pBitmapWidth = width;
pBitmapHeight = height;
pMaxPixelBufferSize = pBitmapWidth*pBitmapHeight;
pBitmap = (unsigned char*)malloc(pMaxPixelBufferSize*4 + 4);
memset(pBitmap,0x00,pMaxPixelBufferSize*4);
}
PixelCanvas::PixelCanvas(int width, int height) :
super(0,0,width,height, gVertexShader, gFragmentShader)
{
pBitmapWidth = width;
pBitmapHeight = height;
pMaxPixelBufferSize = pBitmapWidth*pBitmapHeight;
pBitmap = (unsigned char*)malloc(pMaxPixelBufferSize*4 + 4);
memset(pBitmap,0x00,pMaxPixelBufferSize*4);
}
PixelCanvas::~PixelCanvas() {
}
bool PixelCanvas::initVariables()
{
if(!super::initVariables()) {
return false;
}
const char* attribute_name;
const char* uniform_name;
glGenTextures(1, &texture_id);
glBindTexture(GL_TEXTURE_2D, texture_id);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
GL_CLAMP_TO_EDGE);
//glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, /*GL10.GL_REPLACE*/ GL_MODULATE);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, // target
0, // level, 0 = base, no minimap,
GL_RGBA, // internalformat
pBitmapWidth, // width
pBitmapHeight, // height
0, // border, always 0 in OpenGL ES
GL_RGBA, // format
GL_UNSIGNED_BYTE, // type
pBitmap);
checkGlError("glTexImage2D");
updateBitmap = false;
GLfloat square_texcoords[] = {
// front
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
0.0, 1.0,
};
GL_EXT_FUNC glGenBuffers(1, &vbo_square_texcoords);
checkGlError("glGenBuffers");
GL_EXT_FUNC glBindBuffer(GL_ARRAY_BUFFER, vbo_square_texcoords);
checkGlError("glBindBuffer");
GL_EXT_FUNC glBufferData(GL_ARRAY_BUFFER, sizeof(square_texcoords), square_texcoords, GL_STATIC_DRAW);
checkGlError("glBufferData");
return true;
}
void PixelCanvas::enableAttributes() const
{
super::enableAttributes();
GL_EXT_FUNC glEnableVertexAttribArray(attribute_texcoord);
}
void PixelCanvas::disableAttributes() const
{
GL_EXT_FUNC glDisableVertexAttribArray(attribute_texcoord);
super::disableAttributes();
}
void PixelCanvas::updateG(float sec,float deltaSec)
{
super::updateG(sec,deltaSec);
if(updateBitmap)
{
GL_EXT_FUNC glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture_id);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
GL_CLAMP_TO_EDGE);
//glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, /*GL10.GL_REPLACE*/ GL_MODULATE);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, // target
0, // level, 0 = base, no minimap,
GL_RGBA, // internalformat
pBitmapWidth, // width
pBitmapHeight, // height
0, // border, always 0 in OpenGL ES
GL_RGBA, // format
GL_UNSIGNED_BYTE, // type
pBitmap);
updateBitmap = false;
GL_EXT_FUNC glUniform1i(uniform_mytexture, 0);
GL_EXT_FUNC glEnableVertexAttribArray(attribute_texcoord);
GL_EXT_FUNC glBindBuffer(GL_ARRAY_BUFFER, vbo_square_texcoords);
GL_EXT_FUNC glVertexAttribPointer(
attribute_texcoord, // attribute
2, // number of elements per vertex, here (x,y)
GL_FLOAT, // the type of each element
GL_FALSE, // take our values as-is
0, // no extra data between each position
0 // offset of first element
);
}
}
void PixelCanvas::clear()
{
memset(pBitmap,0x00,pMaxPixelBufferSize*4);
updateBitmap = true;
}
void PixelCanvas::setPixel(int x, int y, unsigned int abgr)
{
int width = pBitmapWidth;
unsigned int location = y*width + x;
unsigned int* buffer = (unsigned int*)pBitmap;
if(buffer && location < pMaxPixelBufferSize)
{
buffer[location] = abgr;
LOGI("pp");
}
updateBitmap = true;
}
void PixelCanvas::setPixel(int x, int y, char a,char b,char g,char r)
{
unsigned int value = a<<24 | b<<16 | g<<8 | r;
setPixel(x,y,value);
}
void PixelCanvas::getPixel(int x, int y, unsigned int *abgr)
{
int width = pBitmapWidth;
unsigned int location = y*width + x;
unsigned int* buffer = (unsigned int*)pBitmap;
if(buffer && location < pMaxPixelBufferSize)
{
*abgr = buffer[location];
}
}
void PixelCanvas::getPixel(int x, int y, char *a,char *b,char *g,char *r)
{
unsigned int value;
getPixel(x,y,&value);
// a<<24 | b<<16 | g<<8 | r;
*a = value >> 24;
*b = value >> 16;
*g = value >> 8;
*r = value;
}
} /* namespace Gain */
<|endoftext|>
|
<commit_before>// Title : Implementation of Coroutine in Cpp
// Author : hanzh.xu@gmail.com
// Date : 11-21-2020
// License : MIT License
/*
Implementation of Coroutine in Cpp
Compiler:
// clang version 3.8.1-24+rpi1 (tags/RELEASE_381/final)
// Target: armv6--linux-gnueabihf
// Thread model: posix
// clang -std=c++0x -lstdc++
Usage:
// class MyGen : public Gen<Output type of the generator>
class OneMoreHanoiGen : public Gen<string> {
public:
// Local variables of the generator.
int n;
string a, b, c;
shared_ptr<Gen<string> > iter;
// Constructor of the generator.
OneMoreHanoiGen(int _n, string _a, string _b, string _c):
n(_n), a(_a), b(_b), c(_c) {}
// Write your code in the step method.
// It is very straight forward.
// You just need to replace all control statements with the MACRO in your generator.
// bool step(string& output);
// Args:
// output: the output of your generator, set the output before doing yield.
// Return:
// The return value is used by the framework.
// DO NOT return true or false by yourself, let the MACRO takes care of it.
bool step(string& output) {
// Declare all the control statements at first.
// IMPORTANT: You can NOT use a control MACRO without declaring its name.
// DEC_BEG : begin the declaration.
// DEF_IF(if_name) : declare a if statement named if_name.
// DEF_LOOP(loop_name) : declare a loop statement named loop_name.
// DEC_YIELD(yield_name) : declare a loop statement named yield_name.
// DEC_END : end the declaration.
DEC_BEG
DEC_IF(if1), DEC_LOOP(loop1), DEC_LOOP(loop2), DEC_LOOP(loop3),
DEC_YIELD(y1), DEC_YIELD(y2), DEC_YIELD(y3), DEC_YIELD(y4)
DEC_END
// Using the control MACRO to write the code.
// PRG_BEG -> Begin the program.
// IF(name, condition, true_block, false_block); -> A if statment with name.
// WHILE(name, condition loop_block); -> A while loop with name.
// BREAK(loop_name); -> Jump to the end of the loop named loop_name
// CONTINUE(loop_name); -> Jump to the begin of the loop named loop_name
// YIELD(name); -> A yield statement with name.
// RETURN(); -> Finish the generator.
// PRG_END -> End the program.
PRG_BEG
IF(if1, n == 1, {
output = a + " --> " + c;
YIELD(y1);
}, {
iter = make_shared<OneMoreHanoiGen>(n - 1, a, c, b);
WHILE(loop1, iter->next(output), YIELD(y2));
iter = make_shared<OneMoreHanoiGen>(1, a, b, c);
WHILE(loop2, iter->next(output), YIELD(y3));
iter = make_shared<OneMoreHanoiGen>(n - 1, b, a, c);
WHILE(loop3, iter->next(output), YIELD(y4));
});
PRG_END
}
};
int main() {
string output;
// Build a HanoiGen with Args (3, "A", "B", "C").
OneMoreHanoiGen hanoiGen(3, "A", "B", "C");
// Get the next output, until the generator returns false.
// bool isAlive = hanoiGen(output);
// if(isAlive) cout << output << endl;
while(hanoiGen(output)) cout << output << endl;
return 0;
}
// You also can create a coroutine having full functionality, if you want to do some interactive operations with the coroutine.
// The only difference is that the step method has an extra argument input now.
// The input argument represents the input variable that you pass into the Coroutine.
// See the example class GuessNumber to understand how to use it.
template<typename S, typename T>
class Coroutine : public std::enable_shared_from_this<Coroutine<S,T>> {
public:
virtual bool step(S& input, T& output) = 0;
*/
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <functional>
#include <memory>
#include <string>
#include <tuple>
#include <typeinfo>
#include <utility>
#include <vector>
using namespace std;
template<typename S>
class Source : public std::enable_shared_from_this<Source<S>> {
public:
virtual ~Source() {}
virtual bool operator()(S& output) = 0;
bool next(S& output) {
return (*this)(output);
}
shared_ptr<Source<S>> getPtr() { return this->shared_from_this(); }
};
template<typename S>
class Gen : public Source<S> {
public:
int state;
bool isAlive;
Gen() : state(0), isAlive(true) {}
virtual bool step(S& output) = 0;
bool operator()(S& output) {
while(!step(output));
return isAlive;
}
};
template<typename S, typename T>
class Coroutine : public std::enable_shared_from_this<Coroutine<S,T>> {
public:
int state;
bool isAlive;
Coroutine() : state(0), isAlive(true) {}
virtual ~Coroutine() {}
virtual bool step(S& input, T& output) = 0;
bool next(S& input, T& output) {
while(!step(input, output));
return isAlive;
}
bool operator()(S& input, T& output) {
return next(input, output);
}
shared_ptr<Coroutine<S,T>> getPtr() { return this->shared_from_this(); }
};
#define PRG_BEG \
switch(state) { \
case PBEG: {}
#define PRG_END \
case PEND: {} \
default: { isAlive = false; return true; } }
#define BEG(name) BEG_##name
#define ELSE(name) ELSE_##name
#define END(name) END_##name
#define IF(name,c,a,b) \
case BEG(name): { if(c) { {a;} state = END(name); return false; } else { state = ELSE(name); } } \
case ELSE(name): { b; } \
case END(name): {}
#define LOOP(name,s) \
case BEG(name): { {s;} state = BEG(name); return false; } \
case END(name): {}
#define WHILE(name,c,s) \
case BEG(name): { if(!(c)) { state = END(name); return false; } {s;} state = BEG(name); return false; } \
case END(name): {}
#define YIELD(name) \
case BEG(name): { state = END(name); isAlive = true; return true; } \
case END(name): {}
#define CONTINUE(loop) { state = BEG(loop); return false; }
#define BREAK(loop) { state = END(loop); return false; }
#define GOTO(label) { state = label; return false; }
#define RETURN() { state = PEND; return false; }
#define DEC_BEG enum { PBEG = 0, PEND,
#define DEC_IF(name) BEG(name), ELSE(name), END(name)
#define DEC_LOOP(name) BEG(name), END(name)
#define DEC_YIELD(name) BEG(name), END(name)
#define DEC_END };
/*
L: def prod_iter(s):
0: if len(s) == 0:
1: yield []
2: else:
3: x = 0
4: while true:
5: xs = []
6: iter = generator.create(prod_iter(s[1:]))
7: while true:
8: xs, isAlive = iter.resume()
9: if !isAlive:
10 break
11 yield [x] + xs
12 x += 1
13 if x >= s[0]:
14 break
-1 return
*/
class OneMoreProdGen : public Gen<vector<int> > {
public:
vector<unsigned int> s;
int x;
shared_ptr<Source<vector<int> > > iter;
vector<int> xs;
OneMoreProdGen(const vector<unsigned int>& _s) : s(_s) {}
bool step(vector<int>& output) {
DEC_BEG
DEC_IF(if1), DEC_IF(if2), DEC_IF(if3),
DEC_LOOP(loop1), DEC_LOOP(loop2),
DEC_YIELD(y1), DEC_YIELD(y2)
DEC_END
PRG_BEG
IF(if1, s.size()==0, {
output.clear();
YIELD(y1);
}, {
x = 0;
WHILE(loop1, true, {
IF(if3, x >= s[0], BREAK(loop1), {});
{
vector<unsigned int> ss(s.begin() + 1, s.end());
iter = make_shared<OneMoreProdGen>(ss);
}
WHILE(loop2, iter->next(xs), {
output.clear();
output.push_back(x);
output.insert(output.end(), xs.begin(), xs.end());
YIELD(y2);
});
x += 1;
})
});
PRG_END
}
};
/*
def hanoi(n, a, b, c):
if n == 1:
s = str(a) + ' --> ' + str(c)
yield s
else:
for s in hanoi(n - 1, a, c, b):
yield s
for s in hanoi(1 , a, b, c):
yield s
for s in hanoi(n - 1, b, a, c):
yield s
*/
class OneMoreHanoiGen : public Gen<string> {
public:
int n;
string a, b, c;
shared_ptr<Gen<string> > iter;
OneMoreHanoiGen(int _n, string _a, string _b, string _c):
n(_n), a(_a), b(_b), c(_c) {}
bool step(string& output) {
DEC_BEG
DEC_IF(if1), DEC_LOOP(loop1), DEC_LOOP(loop2), DEC_LOOP(loop3),
DEC_YIELD(y1), DEC_YIELD(y2), DEC_YIELD(y3), DEC_YIELD(y4)
DEC_END
PRG_BEG
IF(if1, n == 1, {
output = a + " --> " + c;
YIELD(y1);
}, {
iter = make_shared<OneMoreHanoiGen>(n - 1, a, c, b);
WHILE(loop1, iter->next(output), YIELD(y2));
iter = make_shared<OneMoreHanoiGen>(1, a, b, c);
WHILE(loop2, iter->next(output), YIELD(y3));
iter = make_shared<OneMoreHanoiGen>(n - 1, b, a, c);
WHILE(loop3, iter->next(output), YIELD(y4));
});
PRG_END
}
};
class PrimeGen : public Gen<int> {
public:
vector<int> primes;
int i, j;
PrimeGen() {}
bool step(int& output) {
DEC_BEG
DEC_IF(if1), DEC_IF(if2),
DEC_LOOP(loop1), DEC_LOOP(loop2),
DEC_YIELD(y1)
DEC_END
PRG_BEG
i = 2;
WHILE(loop1, true, {
j = 0;
WHILE(loop2, j < primes.size(), {
IF(if1, i % primes[j] == 0, {i++; CONTINUE(loop1);}, j++);
});
primes.push_back(i);
output = i;
YIELD(y1);
});
PRG_END
}
};
class GuessNumber : public Coroutine<int, int> {
public:
int t, num;
GuessNumber() {}
bool step(int& input, int& output) {
DEC_BEG
DEC_IF(if1), DEC_IF(if2),
DEC_LOOP(loop1), DEC_LOOP(loop2),
DEC_YIELD(y1), DEC_YIELD(y2)
DEC_END
PRG_BEG
t = 0;
srand(time(0));
cout << "Guess a number between 0 and 100!" << endl;
WHILE(loop1, true, {
cout << "Match " << t << endl;
num = rand() % 100;
cout << "input a number:";
YIELD(y1);
WHILE(loop2, input != num, {
IF(if2, input == -1, BREAK(loop1), {});
IF(if1, input < num, {
cout << "Too small!" << endl;
output = -1;
}, {
cout << "Too large!" << endl;
output = 1;
});
cout << "input a number agian:";
YIELD(y2);
});
cout << "Bingo! It's " << num << "!" << endl;
cout << "Let's play it again!" << endl;
t++;
output = 0;
});
cout << "ByeBye!" << endl;
PRG_END
}
};
template<typename T>
void print(vector<T>& vec) {
for(int i = 0; i < vec.size(); ++i) {
cout << vec[i] << " ";
}
cout << endl;
}
void testGuessNumber() {
GuessNumber guess;
int num, output;
guess(num, output);
do {
cin >> num;
} while(guess(num, output));
}
int main() {
cout << "HanoiGen" << endl;
string s;
OneMoreHanoiGen hanoiGen(3, "A", "B", "C");
while(hanoiGen(s)) cout << s << endl;
cout << "CartesianProduct" << endl;
vector<unsigned int> dimSize({2,3,4});
vector<int> output(dimSize.size());
OneMoreProdGen prodGen(dimSize);
while(prodGen(output)) print(output);
cout << "Prime numbers" << endl;
PrimeGen primeGen;
int p;
for(int i = 0; i < 30; ++i) {
primeGen(p);
cout << p << " ";
}
cout << endl;
testGuessNumber();
return 0;
}
<commit_msg>Update macro_yield.cpp<commit_after>// Title : Implementation of Coroutine in Cpp
// Author : hanzh.xu@gmail.com
// Date : 11-21-2020
// License : MIT License
/*
Implementation of Coroutine in Cpp
Compiler:
// clang version 3.8.1-24+rpi1 (tags/RELEASE_381/final)
// Target: armv6--linux-gnueabihf
// Thread model: posix
// clang -std=c++0x -lstdc++
Usage:
// class MyGen : public Gen<Output type of the generator>
class OneMoreHanoiGen : public Gen<string> {
public:
// Local variables of the generator.
int n;
string a, b, c;
shared_ptr<Gen<string> > iter;
// Constructor of the generator.
OneMoreHanoiGen(int _n, string _a, string _b, string _c):
n(_n), a(_a), b(_b), c(_c) {}
// Write your code in the step method.
// It is very straight forward.
// You just need to replace all control statements with the MACRO in your generator.
// bool step(string& output);
// Args:
// output: the output of your generator, set the output before doing yield.
// Return:
// The return value is used by the framework.
// DO NOT return true or false by yourself, let the MACRO takes care of it.
bool step(string& output) {
// Declare all the control statements at first.
// IMPORTANT: You can NOT use a control MACRO without declaring its name.
// DEC_BEG : begin the declaration.
// DEF_IF(if_name) : declare a if statement named if_name.
// DEF_LOOP(loop_name) : declare a loop statement named loop_name.
// DEC_YIELD(yield_name) : declare a loop statement named yield_name.
// DEC_END : end the declaration.
DEC_BEG
DEC_IF(if1), DEC_LOOP(loop1), DEC_LOOP(loop2), DEC_LOOP(loop3),
DEC_YIELD(y1), DEC_YIELD(y2), DEC_YIELD(y3), DEC_YIELD(y4)
DEC_END
// Using the control MACRO to write the code.
// PRG_BEG -> Begin the program.
// IF(name, condition, true_block, false_block); -> A if statment with name.
// WHILE(name, condition loop_block); -> A while loop with name.
// BREAK(loop_name); -> Jump to the end of the loop named loop_name
// CONTINUE(loop_name); -> Jump to the begin of the loop named loop_name
// YIELD(name); -> A yield statement with name.
// RETURN(); -> Finish the generator.
// PRG_END -> End the program.
PRG_BEG
IF(if1, n == 1, {
output = a + " --> " + c;
YIELD(y1);
}, {
iter = make_shared<OneMoreHanoiGen>(n - 1, a, c, b);
WHILE(loop1, iter->next(output), YIELD(y2));
iter = make_shared<OneMoreHanoiGen>(1, a, b, c);
WHILE(loop2, iter->next(output), YIELD(y3));
iter = make_shared<OneMoreHanoiGen>(n - 1, b, a, c);
WHILE(loop3, iter->next(output), YIELD(y4));
});
PRG_END
}
};
int main() {
string output;
// Build a HanoiGen with Args (3, "A", "B", "C").
OneMoreHanoiGen hanoiGen(3, "A", "B", "C");
// Get the next output, until the generator returns false.
// bool isAlive = hanoiGen(output);
// if(isAlive) cout << output << endl;
while(hanoiGen(output)) cout << output << endl;
return 0;
}
// You also can create a coroutine having full functionality, if you want to do some interactive operations with the coroutine.
// The only difference is that the step method has an extra argument input now.
// The input argument represents the input variable that you pass into the Coroutine.
// See the example class GuessNumber to understand how to use it.
template<typename S, typename T>
class Coroutine : public std::enable_shared_from_this<Coroutine<S,T>> {
public:
virtual bool step(S& input, T& output) = 0;
*/
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <functional>
#include <memory>
#include <string>
#include <tuple>
#include <typeinfo>
#include <utility>
#include <vector>
using namespace std;
template<typename S>
class Source : public std::enable_shared_from_this<Source<S>> {
public:
virtual ~Source() {}
virtual bool operator()(S& output) = 0;
bool next(S& output) {
return (*this)(output);
}
shared_ptr<Source<S>> getPtr() { return this->shared_from_this(); }
};
template<typename S>
class Gen : public Source<S> {
public:
int state;
bool isAlive;
Gen() : state(0), isAlive(true) {}
virtual bool step(S& output) = 0;
bool operator()(S& output) {
while(!step(output));
return isAlive;
}
};
template<typename S, typename T>
class Coroutine : public std::enable_shared_from_this<Coroutine<S,T>> {
public:
int state;
bool isAlive;
Coroutine() : state(0), isAlive(true) {}
virtual ~Coroutine() {}
virtual bool step(S& input, T& output) = 0;
bool next(S& input, T& output) {
while(!step(input, output));
return isAlive;
}
bool operator()(S& input, T& output) {
return next(input, output);
}
shared_ptr<Coroutine<S,T>> getPtr() { return this->shared_from_this(); }
};
#define PRG_BEG \
switch(state) { \
case PBEG: {}
#define PRG_END \
case PEND: {} \
default: { isAlive = false; return true; } }
#define BEG(name) BEG_##name
#define ELSE(name) ELSE_##name
#define END(name) END_##name
#define IF(name,c,a,b) \
case BEG(name): { if(c) { {a;} state = END(name); return false; } else { state = ELSE(name); } } \
case ELSE(name): { b; } \
case END(name): {}
#define LOOP(name,s) \
case BEG(name): { {s;} state = BEG(name); return false; } \
case END(name): {}
#define WHILE(name,c,s) \
case BEG(name): { if(!(c)) { state = END(name); return false; } {s;} state = BEG(name); return false; } \
case END(name): {}
#define YIELD(name) \
case BEG(name): { state = END(name); isAlive = true; return true; } \
case END(name): {}
#define CONTINUE(loop) { state = BEG(loop); return false; }
#define BREAK(loop) { state = END(loop); return false; }
#define GOTO(label) { state = label; return false; }
#define RETURN() { state = PEND; return false; }
#define DEC_BEG enum { PBEG = 0, PEND,
#define DEC_IF(name) BEG(name), ELSE(name), END(name)
#define DEC_LOOP(name) BEG(name), END(name)
#define DEC_YIELD(name) BEG(name), END(name)
#define DEC_END };
/*
L: def prod_iter(s):
0: if len(s) == 0:
1: yield []
2: else:
3: x = 0
4: while true:
5: xs = []
6: iter = generator.create(prod_iter(s[1:]))
7: while true:
8: xs, isAlive = iter.resume()
9: if !isAlive:
10 break
11 yield [x] + xs
12 x += 1
13 if x >= s[0]:
14 break
-1 return
*/
class OneMoreProdGen : public Gen<vector<int> > {
public:
vector<unsigned int> s;
int x;
shared_ptr<Source<vector<int> > > iter;
vector<int> xs;
OneMoreProdGen(const vector<unsigned int>& _s) : s(_s) {}
bool step(vector<int>& output) {
DEC_BEG
// declare 2 if statements, 2 loops, and 2 yields.
// the name of them are if1, if2, loop1, loop2, y1, y2.
DEC_IF(if1), DEC_IF(if2),
DEC_LOOP(loop1), DEC_LOOP(loop2),
DEC_YIELD(y1), DEC_YIELD(y2)
DEC_END
PRG_BEG
// the if_statement if1.
// if(s.size() == 0) {...} else {...}
IF(if1, s.size()==0, {
output.clear();
// the yield_statement y1.
// output = empty and yield.
YIELD(y1);
}, {
x = 0;
// the while_statement loop1.
// while(true) {...}
WHILE(loop1, true, {
// the if_statement if2.
// if(x >= s[0]) jump to loop1's end.
IF(if2, x >= s[0], BREAK(loop1), {});
{
// if we define local variables here, sometimes it gets an error.
// Luckly, for this one, we can use { } to solve the error.
vector<unsigned int> ss(s.begin() + 1, s.end());
iter = make_shared<OneMoreProdGen>(ss);
}
// the while_statement loop2.
// while(iter(xs)) {...}
WHILE(loop2, iter->next(xs), {
output.clear();
output.push_back(x);
output.insert(output.end(), xs.begin(), xs.end());
// the yield_statement y2.
// output = [x] + xs and yield.
YIELD(y2);
});
x += 1;
})
});
PRG_END
}
};
/*
def hanoi(n, a, b, c):
if n == 1:
s = str(a) + ' --> ' + str(c)
yield s
else:
for s in hanoi(n - 1, a, c, b):
yield s
for s in hanoi(1 , a, b, c):
yield s
for s in hanoi(n - 1, b, a, c):
yield s
*/
class OneMoreHanoiGen : public Gen<string> {
public:
int n;
string a, b, c;
shared_ptr<Gen<string> > iter;
OneMoreHanoiGen(int _n, string _a, string _b, string _c):
n(_n), a(_a), b(_b), c(_c) {}
bool step(string& output) {
DEC_BEG
DEC_IF(if1), DEC_LOOP(loop1), DEC_LOOP(loop2), DEC_LOOP(loop3),
DEC_YIELD(y1), DEC_YIELD(y2), DEC_YIELD(y3), DEC_YIELD(y4)
DEC_END
PRG_BEG
IF(if1, n == 1, {
output = a + " --> " + c;
YIELD(y1);
}, {
iter = make_shared<OneMoreHanoiGen>(n - 1, a, c, b);
WHILE(loop1, iter->next(output), YIELD(y2));
iter = make_shared<OneMoreHanoiGen>(1, a, b, c);
WHILE(loop2, iter->next(output), YIELD(y3));
iter = make_shared<OneMoreHanoiGen>(n - 1, b, a, c);
WHILE(loop3, iter->next(output), YIELD(y4));
});
PRG_END
}
};
class PrimeGen : public Gen<int> {
public:
vector<int> primes;
int i, j;
PrimeGen() {}
bool step(int& output) {
DEC_BEG
DEC_IF(if1), DEC_IF(if2),
DEC_LOOP(loop1), DEC_LOOP(loop2),
DEC_YIELD(y1)
DEC_END
PRG_BEG
i = 2;
WHILE(loop1, true, {
j = 0;
WHILE(loop2, j < primes.size(), {
IF(if1, i % primes[j] == 0, {i++; CONTINUE(loop1);}, j++);
});
primes.push_back(i);
output = i;
YIELD(y1);
});
PRG_END
}
};
class GuessNumber : public Coroutine<int, int> {
public:
int t, num;
GuessNumber() {}
bool step(int& input, int& output) {
DEC_BEG
DEC_IF(if1), DEC_IF(if2),
DEC_LOOP(loop1), DEC_LOOP(loop2),
DEC_YIELD(y1), DEC_YIELD(y2)
DEC_END
PRG_BEG
t = 0;
srand(time(0));
cout << "Guess a number between 0 and 100!" << endl;
WHILE(loop1, true, {
cout << "Match " << t << endl;
num = rand() % 100;
cout << "input a number:";
YIELD(y1);
WHILE(loop2, input != num, {
IF(if2, input == -1, BREAK(loop1), {});
IF(if1, input < num, {
cout << "Too small!" << endl;
output = -1;
}, {
cout << "Too large!" << endl;
output = 1;
});
cout << "input a number agian:";
YIELD(y2);
});
cout << "Bingo! It's " << num << "!" << endl;
cout << "Let's play it again!" << endl;
t++;
output = 0;
});
cout << "ByeBye!" << endl;
PRG_END
}
};
template<typename T>
void print(vector<T>& vec) {
for(int i = 0; i < vec.size(); ++i) {
cout << vec[i] << " ";
}
cout << endl;
}
void testGuessNumber() {
GuessNumber guess;
int num, output;
guess(num, output);
do {
cin >> num;
} while(guess(num, output));
}
int main() {
cout << "HanoiGen" << endl;
string s;
OneMoreHanoiGen hanoiGen(3, "A", "B", "C");
while(hanoiGen(s)) cout << s << endl;
cout << "CartesianProduct" << endl;
vector<unsigned int> dimSize({2,3,4});
vector<int> output(dimSize.size());
OneMoreProdGen prodGen(dimSize);
while(prodGen(output)) print(output);
cout << "Prime numbers" << endl;
PrimeGen primeGen;
int p;
for(int i = 0; i < 30; ++i) {
primeGen(p);
cout << p << " ";
}
cout << endl;
testGuessNumber();
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/core/Version.h>
#include <aws/core/utils/logging/LogMacros.h>
#include <aws/core/Aws.h>
#include <aws/core/utils/logging/AWSLogging.h>
#include <aws/core/utils/logging/DefaultLogSystem.h>
namespace Aws
{
static const char* ALLOCATION_TAG = "Aws_Init_Cleanup";
void InitAPI(const SDKOptions &options)
{
#ifdef USE_AWS_MEMORY_MANAGEMENT
if(options.memoryManagementOptions.memoryManager)
{
Aws::Utils::Memory::InitializeAWSMemorySystem(*options.memoryManagementOptions.memoryManager);
}
#endif // USE_AWS_MEMORY_MANAGEMENT
if(options.loggingOptions.logLevel != Aws::Utils::Logging::LogLevel::Off)
{
if(options.loggingOptions.logger_create_fn)
{
Aws::Utils::Logging::InitializeAWSLogging(options.loggingOptions.logger_create_fn());
}
else
{
Aws::Utils::Logging::InitializeAWSLogging(
Aws::MakeShared<Aws::Utils::Logging::DefaultLogSystem>(ALLOCATION_TAG, options.loggingOptions.logLevel, options.loggingOptions.defaultLogPrefix));
}
// For users to better debugging in case multiple versions of SDK installed
AWS_LOGSTREAM_INFO(ALLOCATION_TAG, "Initiate AWS SDK for C++ with Version:" << Aws::String(Aws::Version::GetVersionString()));
}
if(options.cryptoOptions.aes_CBCFactory_create_fn)
{
Aws::Utils::Crypto::SetAES_CBCFactory(options.cryptoOptions.aes_CBCFactory_create_fn());
}
if(options.cryptoOptions.aes_CTRFactory_create_fn)
{
Aws::Utils::Crypto::SetAES_CTRFactory(options.cryptoOptions.aes_CTRFactory_create_fn());
}
if(options.cryptoOptions.aes_GCMFactory_create_fn)
{
Aws::Utils::Crypto::SetAES_GCMFactory(options.cryptoOptions.aes_GCMFactory_create_fn());
}
if(options.cryptoOptions.md5Factory_create_fn)
{
Aws::Utils::Crypto::SetMD5Factory(options.cryptoOptions.md5Factory_create_fn());
}
if(options.cryptoOptions.sha256Factory_create_fn)
{
Aws::Utils::Crypto::SetSha256Factory(options.cryptoOptions.sha256Factory_create_fn());
}
if(options.cryptoOptions.sha256HMACFactory_create_fn)
{
Aws::Utils::Crypto::SetSha256HMACFactory(options.cryptoOptions.sha256HMACFactory_create_fn());
}
if (options.cryptoOptions.aes_KeyWrapFactory_create_fn)
{
Aws::Utils::Crypto::SetAES_KeyWrapFactory(options.cryptoOptions.aes_KeyWrapFactory_create_fn());
}
if(options.cryptoOptions.secureRandomFactory_create_fn)
{
Aws::Utils::Crypto::SetSecureRandomFactory(options.cryptoOptions.secureRandomFactory_create_fn());
}
Aws::Utils::Crypto::SetInitCleanupOpenSSLFlag(options.cryptoOptions.initAndCleanupOpenSSL);
Aws::Utils::Crypto::InitCrypto();
if(options.httpOptions.httpClientFactory_create_fn)
{
Aws::Http::SetHttpClientFactory(options.httpOptions.httpClientFactory_create_fn());
}
Aws::Http::SetInitCleanupCurlFlag(options.httpOptions.initAndCleanupCurl);
Aws::Http::InitHttp();
}
void ShutdownAPI(const SDKOptions& options)
{
Aws::Http::CleanupHttp();
Aws::Utils::Crypto::CleanupCrypto();
if(options.loggingOptions.logLevel != Aws::Utils::Logging::LogLevel::Off)
{
Aws::Utils::Logging::ShutdownAWSLogging();
}
#ifdef USE_AWS_MEMORY_MANAGEMENT
if(options.memoryManagementOptions.memoryManager)
{
Aws::Utils::Memory::ShutdownAWSMemorySystem();
}
#endif // USE_AWS_MEMORY_MANAGEMENT
}
}
<commit_msg>revert logging<commit_after>/*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/core/Version.h>
#include <aws/core/utils/logging/LogMacros.h>
#include <aws/core/Aws.h>
#include <aws/core/utils/logging/AWSLogging.h>
#include <aws/core/utils/logging/DefaultLogSystem.h>
namespace Aws
{
static const char* ALLOCATION_TAG = "Aws_Init_Cleanup";
void InitAPI(const SDKOptions &options)
{
#ifdef USE_AWS_MEMORY_MANAGEMENT
if(options.memoryManagementOptions.memoryManager)
{
Aws::Utils::Memory::InitializeAWSMemorySystem(*options.memoryManagementOptions.memoryManager);
}
#endif // USE_AWS_MEMORY_MANAGEMENT
if(options.loggingOptions.logLevel != Aws::Utils::Logging::LogLevel::Off)
{
if(options.loggingOptions.logger_create_fn)
{
Aws::Utils::Logging::InitializeAWSLogging(options.loggingOptions.logger_create_fn());
}
else
{
Aws::Utils::Logging::InitializeAWSLogging(
Aws::MakeShared<Aws::Utils::Logging::DefaultLogSystem>(ALLOCATION_TAG, options.loggingOptions.logLevel, options.loggingOptions.defaultLogPrefix));
}
}
if(options.cryptoOptions.aes_CBCFactory_create_fn)
{
Aws::Utils::Crypto::SetAES_CBCFactory(options.cryptoOptions.aes_CBCFactory_create_fn());
}
if(options.cryptoOptions.aes_CTRFactory_create_fn)
{
Aws::Utils::Crypto::SetAES_CTRFactory(options.cryptoOptions.aes_CTRFactory_create_fn());
}
if(options.cryptoOptions.aes_GCMFactory_create_fn)
{
Aws::Utils::Crypto::SetAES_GCMFactory(options.cryptoOptions.aes_GCMFactory_create_fn());
}
if(options.cryptoOptions.md5Factory_create_fn)
{
Aws::Utils::Crypto::SetMD5Factory(options.cryptoOptions.md5Factory_create_fn());
}
if(options.cryptoOptions.sha256Factory_create_fn)
{
Aws::Utils::Crypto::SetSha256Factory(options.cryptoOptions.sha256Factory_create_fn());
}
if(options.cryptoOptions.sha256HMACFactory_create_fn)
{
Aws::Utils::Crypto::SetSha256HMACFactory(options.cryptoOptions.sha256HMACFactory_create_fn());
}
if (options.cryptoOptions.aes_KeyWrapFactory_create_fn)
{
Aws::Utils::Crypto::SetAES_KeyWrapFactory(options.cryptoOptions.aes_KeyWrapFactory_create_fn());
}
if(options.cryptoOptions.secureRandomFactory_create_fn)
{
Aws::Utils::Crypto::SetSecureRandomFactory(options.cryptoOptions.secureRandomFactory_create_fn());
}
Aws::Utils::Crypto::SetInitCleanupOpenSSLFlag(options.cryptoOptions.initAndCleanupOpenSSL);
Aws::Utils::Crypto::InitCrypto();
if(options.httpOptions.httpClientFactory_create_fn)
{
Aws::Http::SetHttpClientFactory(options.httpOptions.httpClientFactory_create_fn());
}
Aws::Http::SetInitCleanupCurlFlag(options.httpOptions.initAndCleanupCurl);
Aws::Http::InitHttp();
}
void ShutdownAPI(const SDKOptions& options)
{
Aws::Http::CleanupHttp();
Aws::Utils::Crypto::CleanupCrypto();
if(options.loggingOptions.logLevel != Aws::Utils::Logging::LogLevel::Off)
{
Aws::Utils::Logging::ShutdownAWSLogging();
}
#ifdef USE_AWS_MEMORY_MANAGEMENT
if(options.memoryManagementOptions.memoryManager)
{
Aws::Utils::Memory::ShutdownAWSMemorySystem();
}
#endif // USE_AWS_MEMORY_MANAGEMENT
}
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkExtractUnstructuredGridPiece.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.
=========================================================================*/
#include "vtkExtractUnstructuredGridPiece.h"
#include "vtkCell.h"
#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkGenericCell.h"
#include "vtkIdList.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkIntArray.h"
#include "vtkNew.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkUnsignedCharArray.h"
#include "vtkUnstructuredGrid.h"
namespace
{
void determineMinMax(int piece, int numPieces, vtkIdType numCells,
vtkIdType& minCell, vtkIdType& maxCell)
{
const float fnumPieces = static_cast<float>(numPieces);
const float fminCell = (numCells/fnumPieces) * piece;
const float fmaxCell = fminCell + (numCells/fnumPieces);
//round up if over N.5
minCell = static_cast<vtkIdType>(fminCell + 0.5f);
maxCell = static_cast<vtkIdType>(fmaxCell + 0.5f);
}
}
vtkStandardNewMacro(vtkExtractUnstructuredGridPiece);
vtkExtractUnstructuredGridPiece::vtkExtractUnstructuredGridPiece()
{
this->CreateGhostCells = 1;
}
int vtkExtractUnstructuredGridPiece::RequestUpdateExtent(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *vtkNotUsed(outputVector))
{
// get the info object
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER(), 0);
inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES(), 1);
inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS(),
0);
return 1;
}
int vtkExtractUnstructuredGridPiece::RequestInformation(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **vtkNotUsed(inputVector),
vtkInformationVector *outputVector)
{
// get the info object
vtkInformation *outInfo = outputVector->GetInformationObject(0);
outInfo->Set(vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(),
-1);
return 1;
}
void vtkExtractUnstructuredGridPiece::ComputeCellTags(vtkIntArray *tags,
vtkIdList *pointOwnership,
int piece, int numPieces,
vtkUnstructuredGrid *input)
{
vtkIdType idx, ptId;
vtkIdType numCellPts;
vtkIdType numCells = input->GetNumberOfCells();
// Clear Point ownership. This is only necessary if we
// Are creating ghost points.
if (pointOwnership)
{
for (idx = 0; idx < input->GetNumberOfPoints(); ++idx)
{
pointOwnership->SetId(idx, -1);
}
}
//no point on tagging cells if we have no cells
if(numCells == 0)
{
return;
}
// Brute force division.
//mark all we own as zero and the rest as -1
vtkIdType minCell = 0;
vtkIdType maxCell = 0;
determineMinMax(piece,numPieces,numCells,minCell,maxCell);
for (idx = 0; idx < minCell; ++idx)
{
tags->SetValue(idx, -1);
}
for (idx = minCell; idx < maxCell; ++idx)
{
tags->SetValue(idx, 0);
}
for (idx = maxCell; idx < numCells; ++idx)
{
tags->SetValue(idx, -1);
}
vtkIdType* cellPointer = (input->GetCells() ? input->GetCells()->GetPointer() : 0);
if(pointOwnership && cellPointer)
{
for (idx = 0; idx < numCells; ++idx)
{
// Fill in point ownership mapping.
numCellPts = cellPointer[0];
vtkIdType* ids = cellPointer+1;
// Move to the next cell.
cellPointer += (1 + numCellPts);
for (int j = 0; j < numCellPts; ++j)
{
ptId = ids[j];
if (pointOwnership->GetId(ptId) == -1)
{
pointOwnership->SetId(ptId, idx);
}
}
}
}
}
int vtkExtractUnstructuredGridPiece::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// get the input and output
vtkUnstructuredGrid *input = vtkUnstructuredGrid::SafeDownCast(
inInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkUnstructuredGrid *output = vtkUnstructuredGrid::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkPointData *pd=input->GetPointData(), *outPD=output->GetPointData();
vtkCellData *cd=input->GetCellData(), *outCD=output->GetCellData();
unsigned char* cellTypes = (input->GetCellTypesArray() ? input->GetCellTypesArray()->GetPointer(0) : 0);
int cellType;
vtkIntArray *cellTags;
int ghostLevel, piece, numPieces;
vtkIdType cellId, newCellId;
vtkIdList *pointMap;
vtkIdList *newCellPts = vtkIdList::New();
vtkPoints *newPoints;
vtkUnsignedCharArray* cellGhostLevels = 0;
vtkIdList *pointOwnership = 0;
vtkUnsignedCharArray* pointGhostLevels = 0;
vtkIdType i, ptId, newId, numPts, numCells;
int numCellPts;
vtkIdType *cellPointer;
vtkIdType *ids;
double *x;
// Pipeline update piece will tell us what to generate.
ghostLevel = outInfo->Get(
vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS());
piece = outInfo->Get(
vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER());
numPieces = outInfo->Get(
vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES());
outPD->CopyAllocate(pd);
outCD->CopyAllocate(cd);
numPts = input->GetNumberOfPoints();
numCells = input->GetNumberOfCells();
if (ghostLevel > 0 && this->CreateGhostCells)
{
cellGhostLevels = vtkUnsignedCharArray::New();
cellGhostLevels->Allocate(numCells);
// We may want to create point ghost levels even
// if there are no ghost cells. Since it cost extra,
// and no filter really uses it, and the filter did not
// create a point ghost level array for this case before,
// I will leave it the way it was.
pointOwnership = vtkIdList::New();
pointOwnership->Allocate(numPts);
pointGhostLevels = vtkUnsignedCharArray::New();
pointGhostLevels->Allocate(numPts);
}
// Break up cells based on which piece they belong to.
cellTags = vtkIntArray::New();
cellTags->Allocate(input->GetNumberOfCells(), 1000);
// Cell tags end up being 0 for cells in piece and -1 for all others.
// Point ownership is the cell that owns the point.
this->ComputeCellTags(cellTags, pointOwnership, piece, numPieces, input);
// Find the layers of ghost cells.
if (this->CreateGhostCells && ghostLevel > 0)
{
this->AddFirstGhostLevel(input, cellTags, piece, numPieces);
for (i = 2; i <= ghostLevel; i++)
{
this->AddGhostLevel(input, cellTags, i);
}
}
// Filter the cells.
output->Allocate(input->GetNumberOfCells());
newPoints = vtkPoints::New();
newPoints->Allocate(numPts);
pointMap = vtkIdList::New(); //maps old point ids into new
pointMap->SetNumberOfIds(numPts);
for (i=0; i < numPts; i++)
{
pointMap->SetId(i,-1);
}
// Filter the cells
cellPointer = (input->GetCells() ? input->GetCells()->GetPointer() : 0);
for (cellId=0; cellId < numCells; cellId++)
{
// Direct access to cells.
cellType = cellTypes[cellId];
numCellPts = cellPointer[0];
ids = cellPointer+1;
// Move to the next cell.
cellPointer += (1 + *cellPointer);
if ( cellTags->GetValue(cellId) != -1) // satisfied thresholding
{
if (cellGhostLevels)
{
cellGhostLevels->InsertNextValue(
(unsigned char)(cellTags->GetValue(cellId)));
}
for (i=0; i < numCellPts; i++)
{
ptId = ids[i];
if ( (newId = pointMap->GetId(ptId)) < 0 )
{
x = input->GetPoint(ptId);
newId = newPoints->InsertNextPoint(x);
if (pointGhostLevels && pointOwnership)
{
pointGhostLevels->InsertNextValue(
cellTags->GetValue(pointOwnership->GetId(ptId)));
}
pointMap->SetId(ptId,newId);
outPD->CopyData(pd,ptId,newId);
}
newCellPts->InsertId(i,newId);
}
newCellId = output->InsertNextCell(cellType,newCellPts);
outCD->CopyData(cd,cellId,newCellId);
newCellPts->Reset();
} // satisfied thresholding
} // for all cells
// Split up points that are not used by cells,
// and have not been assigned to any piece.
// Count the number of unassigned points. This is an extra pass through
// the points, but the pieces will be better load balanced and
// more spatially coherent.
vtkIdType count = 0;
vtkIdType idx;
for (idx = 0; idx < input->GetNumberOfPoints(); ++idx)
{
if (pointMap->GetId(idx) == -1)
{
++count;
}
}
vtkIdType count2 = 0;
for (idx = 0; idx < input->GetNumberOfPoints(); ++idx)
{
if (pointMap->GetId(idx) == -1)
{
if ((count2++ * numPieces / count) == piece)
{
x = input->GetPoint(idx);
newId = newPoints->InsertNextPoint(x);
if (pointGhostLevels)
{
pointGhostLevels->InsertNextValue(0);
}
outPD->CopyData(pd,idx,newId);
}
}
}
vtkDebugMacro(<< "Extracted " << output->GetNumberOfCells()
<< " number of cells.");
// now clean up / update ourselves
pointMap->Delete();
newCellPts->Delete();
if (cellGhostLevels)
{
cellGhostLevels->SetName("vtkGhostLevels");
output->GetCellData()->AddArray(cellGhostLevels);
cellGhostLevels->Delete();
cellGhostLevels = 0;
}
if (pointGhostLevels)
{
pointGhostLevels->SetName("vtkGhostLevels");
output->GetPointData()->AddArray(pointGhostLevels);
pointGhostLevels->Delete();
pointGhostLevels = 0;
}
output->SetPoints(newPoints);
newPoints->Delete();
output->Squeeze();
cellTags->Delete();
if (pointOwnership)
{
pointOwnership->Delete();
pointOwnership = 0;
}
return 1;
}
void vtkExtractUnstructuredGridPiece::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Create Ghost Cells: "
<< (this->CreateGhostCells ? "On\n" : "Off\n");
}
void vtkExtractUnstructuredGridPiece::AddFirstGhostLevel(
vtkUnstructuredGrid *input,
vtkIntArray *cellTags,
int piece, int numPieces)
{
const vtkIdType numCells = input->GetNumberOfCells();
vtkNew<vtkIdList> cellPointIds;
vtkNew<vtkIdList> neighborIds;
//for level 1 we have an optimal implementation
//that can compute the subset of cells we need to check
vtkIdType minCell = 0;
vtkIdType maxCell = 0;
determineMinMax(piece,numPieces,numCells,minCell,maxCell);
for (vtkIdType idx = minCell; idx < maxCell; ++idx)
{
input->GetCellPoints(idx, cellPointIds.GetPointer());
const vtkIdType numCellPoints = cellPointIds->GetNumberOfIds();
for (vtkIdType j = 0; j < numCellPoints; j++)
{
const vtkIdType pointId = cellPointIds->GetId(j);
input->GetPointCells(pointId, neighborIds.GetPointer());
const vtkIdType numNeighbors = neighborIds->GetNumberOfIds();
for(vtkIdType k= 0; k < numNeighbors; ++k)
{
const vtkIdType neighborCellId = neighborIds->GetId(k);
if(cellTags->GetValue(neighborCellId) == -1)
{
cellTags->SetValue(neighborCellId, 1);
}
}
}
}
}
void vtkExtractUnstructuredGridPiece::AddGhostLevel(vtkUnstructuredGrid *input,
vtkIntArray *cellTags,
int level)
{
//for layers of ghost cells after the first we have to search
//the entire input dataset. in the future we can extend this
//function to return the list of cells that we set on our
//level so we only have to search that subset for neighbors
const vtkIdType numCells = input->GetNumberOfCells();
vtkNew<vtkIdList> cellPointIds;
vtkNew<vtkIdList> neighborIds;
for (vtkIdType idx = 0; idx < numCells; ++idx)
{
if(cellTags->GetValue(idx) == level - 1)
{
input->GetCellPoints(idx, cellPointIds.GetPointer());
const vtkIdType numCellPoints = cellPointIds->GetNumberOfIds();
for (vtkIdType j = 0; j < numCellPoints; j++)
{
const vtkIdType pointId = cellPointIds->GetId(j);
input->GetPointCells(pointId,neighborIds.GetPointer());
const vtkIdType numNeighbors= neighborIds->GetNumberOfIds();
for(vtkIdType k= 0; k < numNeighbors; ++k)
{
const vtkIdType neighborCellId = neighborIds->GetId(k);
if(cellTags->GetValue(neighborCellId) == -1)
{
cellTags->SetValue(neighborCellId, level);
}
}
}
}
}
}
<commit_msg>Process facestream in vtkExtractUnstructuredGridPiece::RequestData.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkExtractUnstructuredGridPiece.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.
=========================================================================*/
#include "vtkExtractUnstructuredGridPiece.h"
#include "vtkCell.h"
#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkGenericCell.h"
#include "vtkIdList.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkIntArray.h"
#include "vtkNew.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkUnsignedCharArray.h"
#include "vtkUnstructuredGrid.h"
namespace
{
void determineMinMax(int piece, int numPieces, vtkIdType numCells,
vtkIdType& minCell, vtkIdType& maxCell)
{
const float fnumPieces = static_cast<float>(numPieces);
const float fminCell = (numCells/fnumPieces) * piece;
const float fmaxCell = fminCell + (numCells/fnumPieces);
//round up if over N.5
minCell = static_cast<vtkIdType>(fminCell + 0.5f);
maxCell = static_cast<vtkIdType>(fmaxCell + 0.5f);
}
}
vtkStandardNewMacro(vtkExtractUnstructuredGridPiece);
vtkExtractUnstructuredGridPiece::vtkExtractUnstructuredGridPiece()
{
this->CreateGhostCells = 1;
}
int vtkExtractUnstructuredGridPiece::RequestUpdateExtent(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *vtkNotUsed(outputVector))
{
// get the info object
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER(), 0);
inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES(), 1);
inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS(),
0);
return 1;
}
int vtkExtractUnstructuredGridPiece::RequestInformation(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **vtkNotUsed(inputVector),
vtkInformationVector *outputVector)
{
// get the info object
vtkInformation *outInfo = outputVector->GetInformationObject(0);
outInfo->Set(vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(),
-1);
return 1;
}
void vtkExtractUnstructuredGridPiece::ComputeCellTags(vtkIntArray *tags,
vtkIdList *pointOwnership,
int piece, int numPieces,
vtkUnstructuredGrid *input)
{
vtkIdType idx, ptId;
vtkIdType numCellPts;
vtkIdType numCells = input->GetNumberOfCells();
// Clear Point ownership. This is only necessary if we
// Are creating ghost points.
if (pointOwnership)
{
for (idx = 0; idx < input->GetNumberOfPoints(); ++idx)
{
pointOwnership->SetId(idx, -1);
}
}
//no point on tagging cells if we have no cells
if(numCells == 0)
{
return;
}
// Brute force division.
//mark all we own as zero and the rest as -1
vtkIdType minCell = 0;
vtkIdType maxCell = 0;
determineMinMax(piece,numPieces,numCells,minCell,maxCell);
for (idx = 0; idx < minCell; ++idx)
{
tags->SetValue(idx, -1);
}
for (idx = minCell; idx < maxCell; ++idx)
{
tags->SetValue(idx, 0);
}
for (idx = maxCell; idx < numCells; ++idx)
{
tags->SetValue(idx, -1);
}
vtkIdType* cellPointer = (input->GetCells() ? input->GetCells()->GetPointer() : 0);
if(pointOwnership && cellPointer)
{
for (idx = 0; idx < numCells; ++idx)
{
// Fill in point ownership mapping.
numCellPts = cellPointer[0];
vtkIdType* ids = cellPointer+1;
// Move to the next cell.
cellPointer += (1 + numCellPts);
for (int j = 0; j < numCellPts; ++j)
{
ptId = ids[j];
if (pointOwnership->GetId(ptId) == -1)
{
pointOwnership->SetId(ptId, idx);
}
}
}
}
}
int vtkExtractUnstructuredGridPiece::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// get the input and output
vtkUnstructuredGrid *input = vtkUnstructuredGrid::SafeDownCast(
inInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkUnstructuredGrid *output = vtkUnstructuredGrid::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkPointData *pd=input->GetPointData(), *outPD=output->GetPointData();
vtkCellData *cd=input->GetCellData(), *outCD=output->GetCellData();
unsigned char* cellTypes = (input->GetCellTypesArray() ? input->GetCellTypesArray()->GetPointer(0) : 0);
int cellType;
vtkIntArray *cellTags;
int ghostLevel, piece, numPieces;
vtkIdType cellId, newCellId;
vtkIdList *pointMap;
vtkIdList *newCellPts = vtkIdList::New();
vtkPoints *newPoints;
vtkUnsignedCharArray* cellGhostLevels = 0;
vtkIdList *pointOwnership = 0;
vtkUnsignedCharArray* pointGhostLevels = 0;
vtkIdType i, ptId, newId, numPts, numCells;
int numCellPts;
vtkIdType *cellPointer;
vtkIdType *ids;
vtkIdType *faceStream;
vtkIdType numFaces;
vtkIdType numFacePts;
double *x;
// Pipeline update piece will tell us what to generate.
ghostLevel = outInfo->Get(
vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS());
piece = outInfo->Get(
vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER());
numPieces = outInfo->Get(
vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES());
outPD->CopyAllocate(pd);
outCD->CopyAllocate(cd);
numPts = input->GetNumberOfPoints();
numCells = input->GetNumberOfCells();
if (ghostLevel > 0 && this->CreateGhostCells)
{
cellGhostLevels = vtkUnsignedCharArray::New();
cellGhostLevels->Allocate(numCells);
// We may want to create point ghost levels even
// if there are no ghost cells. Since it cost extra,
// and no filter really uses it, and the filter did not
// create a point ghost level array for this case before,
// I will leave it the way it was.
pointOwnership = vtkIdList::New();
pointOwnership->Allocate(numPts);
pointGhostLevels = vtkUnsignedCharArray::New();
pointGhostLevels->Allocate(numPts);
}
// Break up cells based on which piece they belong to.
cellTags = vtkIntArray::New();
cellTags->Allocate(input->GetNumberOfCells(), 1000);
// Cell tags end up being 0 for cells in piece and -1 for all others.
// Point ownership is the cell that owns the point.
this->ComputeCellTags(cellTags, pointOwnership, piece, numPieces, input);
// Find the layers of ghost cells.
if (this->CreateGhostCells && ghostLevel > 0)
{
this->AddFirstGhostLevel(input, cellTags, piece, numPieces);
for (i = 2; i <= ghostLevel; i++)
{
this->AddGhostLevel(input, cellTags, i);
}
}
// Filter the cells.
output->Allocate(input->GetNumberOfCells());
newPoints = vtkPoints::New();
newPoints->Allocate(numPts);
pointMap = vtkIdList::New(); //maps old point ids into new
pointMap->SetNumberOfIds(numPts);
for (i=0; i < numPts; i++)
{
pointMap->SetId(i,-1);
}
// Filter the cells
cellPointer = (input->GetCells() ? input->GetCells()->GetPointer() : 0);
for (cellId=0; cellId < numCells; cellId++)
{
// Direct access to cells.
cellType = cellTypes[cellId];
numCellPts = cellPointer[0];
ids = cellPointer+1;
// Move to the next cell.
cellPointer += (1 + *cellPointer);
if ( cellTags->GetValue(cellId) != -1) // satisfied thresholding
{
if (cellGhostLevels)
{
cellGhostLevels->InsertNextValue(
(unsigned char)(cellTags->GetValue(cellId)));
}
if (cellType != VTK_POLYHEDRON)
{
for (i=0; i < numCellPts; i++)
{
ptId = ids[i];
if ( (newId = pointMap->GetId(ptId)) < 0 )
{
x = input->GetPoint(ptId);
newId = newPoints->InsertNextPoint(x);
if (pointGhostLevels && pointOwnership)
{
pointGhostLevels->InsertNextValue(
cellTags->GetValue(pointOwnership->GetId(ptId)));
}
pointMap->SetId(ptId,newId);
outPD->CopyData(pd,ptId,newId);
}
newCellPts->InsertId(i,newId);
}
}
else
{ // Polyhedron, need to process face stream.
faceStream = input->GetFaces(cellId);
numFaces = *faceStream++;
newCellPts->InsertNextId(numFaces);
for (vtkIdType face = 0; face < numFaces; ++face)
{
numFacePts = *faceStream++;
newCellPts->InsertNextId(numFacePts);
while (numFacePts-- > 0)
{
ptId = *faceStream++;
if ( (newId = pointMap->GetId(ptId)) < 0 )
{
x = input->GetPoint(ptId);
newId = newPoints->InsertNextPoint(x);
if (pointGhostLevels && pointOwnership)
{
pointGhostLevels->InsertNextValue(
cellTags->GetValue(pointOwnership->GetId(ptId)));
}
pointMap->SetId(ptId,newId);
outPD->CopyData(pd,ptId,newId);
}
newCellPts->InsertNextId(newId);
}
}
}
newCellId = output->InsertNextCell(cellType,newCellPts);
outCD->CopyData(cd,cellId,newCellId);
newCellPts->Reset();
} // satisfied thresholding
} // for all cells
// Split up points that are not used by cells,
// and have not been assigned to any piece.
// Count the number of unassigned points. This is an extra pass through
// the points, but the pieces will be better load balanced and
// more spatially coherent.
vtkIdType count = 0;
vtkIdType idx;
for (idx = 0; idx < input->GetNumberOfPoints(); ++idx)
{
if (pointMap->GetId(idx) == -1)
{
++count;
}
}
vtkIdType count2 = 0;
for (idx = 0; idx < input->GetNumberOfPoints(); ++idx)
{
if (pointMap->GetId(idx) == -1)
{
if ((count2++ * numPieces / count) == piece)
{
x = input->GetPoint(idx);
newId = newPoints->InsertNextPoint(x);
if (pointGhostLevels)
{
pointGhostLevels->InsertNextValue(0);
}
outPD->CopyData(pd,idx,newId);
}
}
}
vtkDebugMacro(<< "Extracted " << output->GetNumberOfCells()
<< " number of cells.");
// now clean up / update ourselves
pointMap->Delete();
newCellPts->Delete();
if (cellGhostLevels)
{
cellGhostLevels->SetName("vtkGhostLevels");
output->GetCellData()->AddArray(cellGhostLevels);
cellGhostLevels->Delete();
cellGhostLevels = 0;
}
if (pointGhostLevels)
{
pointGhostLevels->SetName("vtkGhostLevels");
output->GetPointData()->AddArray(pointGhostLevels);
pointGhostLevels->Delete();
pointGhostLevels = 0;
}
output->SetPoints(newPoints);
newPoints->Delete();
output->Squeeze();
cellTags->Delete();
if (pointOwnership)
{
pointOwnership->Delete();
pointOwnership = 0;
}
return 1;
}
void vtkExtractUnstructuredGridPiece::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Create Ghost Cells: "
<< (this->CreateGhostCells ? "On\n" : "Off\n");
}
void vtkExtractUnstructuredGridPiece::AddFirstGhostLevel(
vtkUnstructuredGrid *input,
vtkIntArray *cellTags,
int piece, int numPieces)
{
const vtkIdType numCells = input->GetNumberOfCells();
vtkNew<vtkIdList> cellPointIds;
vtkNew<vtkIdList> neighborIds;
//for level 1 we have an optimal implementation
//that can compute the subset of cells we need to check
vtkIdType minCell = 0;
vtkIdType maxCell = 0;
determineMinMax(piece,numPieces,numCells,minCell,maxCell);
for (vtkIdType idx = minCell; idx < maxCell; ++idx)
{
input->GetCellPoints(idx, cellPointIds.GetPointer());
const vtkIdType numCellPoints = cellPointIds->GetNumberOfIds();
for (vtkIdType j = 0; j < numCellPoints; j++)
{
const vtkIdType pointId = cellPointIds->GetId(j);
input->GetPointCells(pointId, neighborIds.GetPointer());
const vtkIdType numNeighbors = neighborIds->GetNumberOfIds();
for(vtkIdType k= 0; k < numNeighbors; ++k)
{
const vtkIdType neighborCellId = neighborIds->GetId(k);
if(cellTags->GetValue(neighborCellId) == -1)
{
cellTags->SetValue(neighborCellId, 1);
}
}
}
}
}
void vtkExtractUnstructuredGridPiece::AddGhostLevel(vtkUnstructuredGrid *input,
vtkIntArray *cellTags,
int level)
{
//for layers of ghost cells after the first we have to search
//the entire input dataset. in the future we can extend this
//function to return the list of cells that we set on our
//level so we only have to search that subset for neighbors
const vtkIdType numCells = input->GetNumberOfCells();
vtkNew<vtkIdList> cellPointIds;
vtkNew<vtkIdList> neighborIds;
for (vtkIdType idx = 0; idx < numCells; ++idx)
{
if(cellTags->GetValue(idx) == level - 1)
{
input->GetCellPoints(idx, cellPointIds.GetPointer());
const vtkIdType numCellPoints = cellPointIds->GetNumberOfIds();
for (vtkIdType j = 0; j < numCellPoints; j++)
{
const vtkIdType pointId = cellPointIds->GetId(j);
input->GetPointCells(pointId,neighborIds.GetPointer());
const vtkIdType numNeighbors= neighborIds->GetNumberOfIds();
for(vtkIdType k= 0; k < numNeighbors; ++k)
{
const vtkIdType neighborCellId = neighborIds->GetId(k);
if(cellTags->GetValue(neighborCellId) == -1)
{
cellTags->SetValue(neighborCellId, level);
}
}
}
}
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <cstdlib>
#include <utility>
using namespace std;
void printCrosswordBoard(vector<string> CrosswordBoard)
{
size_t boardSize=CrosswordBoard.size();
for(int row=0;row<boardSize;++row)
{
size_t rowSize=CrosswordBoard[row].size();
for(int column=0;column<rowSize;++column)
{
cout << CrosswordBoard[row][column] << " ";
}
cout << endl;
}
}
void solution(vector<string> CrosswordBoard, vector<string> & WordList)
{
printCrosswordBoard(CrosswordBoard);
cout << endl;
vector<vector<pair<int, int>>> horizontalSpotsForWords;
vector<vector<pair<int, int>>> verticalSpotsForWords;
size_t boardSize=CrosswordBoard.size();
vector<pair<int, int>> verticalWordSpot;
int column=0;
for(int count=0;count<boardSize;++count)
{
for(int row=0;row<boardSize;++row)
{
char currentCharacter=CrosswordBoard[row][column];
if(currentCharacter=='-')
{
if(row==0)
{
char nextCharacter=CrosswordBoard[row+1][column];
if(nextCharacter=='+')
{
verticalWordSpot.emplace_back(make_pair(row, column));
verticalSpotsForWords.emplace_back(verticalWordSpot);
verticalWordSpot.clear();
}
else
{
verticalWordSpot.emplace_back(make_pair(row, column));
}
}
if(row > 0 && row <= 8)
{
char previousCharacter=CrosswordBoard[row-1][column];
char nextCharacter=CrosswordBoard[row+1][column];
if(previousCharacter=='+' && nextCharacter=='+')
{
verticalWordSpot.emplace_back(make_pair(row, column));
verticalSpotsForWords.emplace_back(verticalWordSpot);
verticalWordSpot.clear();
}
else
{
verticalWordSpot.emplace_back(make_pair(row, column));
}
}
if(row > 8)
{
verticalWordSpot.emplace_back(make_pair(row, column));
}
}
}
verticalSpotsForWords.emplace_back(verticalWordSpot);
verticalWordSpot.clear();
++column;
}
for(int row=0;row<boardSize;++row)
{
vector<pair<int, int>> wordSpot;
size_t rowSize=CrosswordBoard[row].size();
for(int column=0;column<rowSize;++column)
{
char currentCharacter=CrosswordBoard[row][column];
if(currentCharacter=='-')
{
wordSpot.emplace_back(make_pair(row, column));
}
}
horizontalSpotsForWords.emplace_back(wordSpot);
}
sort(begin(WordList), end(WordList), [WordList] (const auto & First, const auto & Second){return First.size() > Second.size();});
sort(begin(horizontalSpotsForWords), end(horizontalSpotsForWords), [horizontalSpotsForWords] (const auto & First, const auto & Second){return First.size() > Second.size();});
sort(begin(verticalSpotsForWords), end(verticalSpotsForWords), [verticalSpotsForWords] (const auto & First, const auto & Second){return First.size() > Second.size();});
size_t horizontalSpotsForWordsSize=horizontalSpotsForWords.size();
size_t verticalSpotsForWordsSize=verticalSpotsForWords.size();
for(int spot=0;spot<verticalSpotsForWordsSize;++spot)
{
size_t spotSize=verticalSpotsForWords[spot].size();
auto word=find_if(begin(WordList), end(WordList), [WordList, spotSize] (const auto & w) {return w.size()==spotSize;});
if(word!=end(WordList))
{
string foundWord=*(word);
for(int index=0;index<spotSize;++index)
{
int column=verticalSpotsForWords[spot][index].first;
int row=verticalSpotsForWords[spot][index].second;
CrosswordBoard[column][row]=foundWord[index];
}
WordList.erase(remove_if(begin(WordList), end(WordList), [foundWord] (const auto & word){return word==foundWord;}), end(WordList));
}
}
for(int spot=0;spot<horizontalSpotsForWordsSize;++spot)
{
size_t spotSize=horizontalSpotsForWords[spot].size();
auto word=find_if(begin(WordList), end(WordList), [WordList, spotSize](const auto & w){return w.size()==spotSize;});
if(word!=end(WordList))
{
string foundWord=*(word);
for(int index=0;index<spotSize;++index)
{
int row=horizontalSpotsForWords[spot][index].first;
int column=horizontalSpotsForWords[spot][index].second;
CrosswordBoard[row][column]=foundWord[index];
}
WordList.erase(remove_if(begin(WordList), end(WordList), [foundWord] (const auto & word){return word==foundWord;}), end(WordList));
}
}
printCrosswordBoard(CrosswordBoard);
}<commit_msg>Removed non-essential printing of the crossword board<commit_after>#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <cstdlib>
#include <utility>
using namespace std;
void printCrosswordBoard(vector<string> CrosswordBoard)
{
size_t boardSize=CrosswordBoard.size();
for(int row=0;row<boardSize;++row)
{
size_t rowSize=CrosswordBoard[row].size();
for(int column=0;column<rowSize;++column)
{
cout << CrosswordBoard[row][column] << " ";
}
cout << endl;
}
}
void solution(vector<string> CrosswordBoard, vector<string> & WordList)
{
vector<vector<pair<int, int>>> horizontalSpotsForWords;
vector<vector<pair<int, int>>> verticalSpotsForWords;
size_t boardSize=CrosswordBoard.size();
vector<pair<int, int>> verticalWordSpot;
int column=0;
for(int count=0;count<boardSize;++count)
{
for(int row=0;row<boardSize;++row)
{
char currentCharacter=CrosswordBoard[row][column];
if(currentCharacter=='-')
{
if(row==0)
{
char nextCharacter=CrosswordBoard[row+1][column];
if(nextCharacter=='+')
{
verticalWordSpot.emplace_back(make_pair(row, column));
verticalSpotsForWords.emplace_back(verticalWordSpot);
verticalWordSpot.clear();
}
else
{
verticalWordSpot.emplace_back(make_pair(row, column));
}
}
if(row > 0 && row <= 8)
{
char previousCharacter=CrosswordBoard[row-1][column];
char nextCharacter=CrosswordBoard[row+1][column];
if(previousCharacter=='+' && nextCharacter=='+')
{
verticalWordSpot.emplace_back(make_pair(row, column));
verticalSpotsForWords.emplace_back(verticalWordSpot);
verticalWordSpot.clear();
}
else
{
verticalWordSpot.emplace_back(make_pair(row, column));
}
}
if(row > 8)
{
verticalWordSpot.emplace_back(make_pair(row, column));
}
}
}
verticalSpotsForWords.emplace_back(verticalWordSpot);
verticalWordSpot.clear();
++column;
}
for(int row=0;row<boardSize;++row)
{
vector<pair<int, int>> wordSpot;
size_t rowSize=CrosswordBoard[row].size();
for(int column=0;column<rowSize;++column)
{
char currentCharacter=CrosswordBoard[row][column];
if(currentCharacter=='-')
{
wordSpot.emplace_back(make_pair(row, column));
}
}
horizontalSpotsForWords.emplace_back(wordSpot);
}
sort(begin(WordList), end(WordList), [WordList] (const auto & First, const auto & Second){return First.size() > Second.size();});
sort(begin(horizontalSpotsForWords), end(horizontalSpotsForWords), [horizontalSpotsForWords] (const auto & First, const auto & Second){return First.size() > Second.size();});
sort(begin(verticalSpotsForWords), end(verticalSpotsForWords), [verticalSpotsForWords] (const auto & First, const auto & Second){return First.size() > Second.size();});
size_t horizontalSpotsForWordsSize=horizontalSpotsForWords.size();
size_t verticalSpotsForWordsSize=verticalSpotsForWords.size();
for(int spot=0;spot<verticalSpotsForWordsSize;++spot)
{
size_t spotSize=verticalSpotsForWords[spot].size();
auto word=find_if(begin(WordList), end(WordList), [WordList, spotSize] (const auto & w) {return w.size()==spotSize;});
if(word!=end(WordList))
{
string foundWord=*(word);
for(int index=0;index<spotSize;++index)
{
int column=verticalSpotsForWords[spot][index].first;
int row=verticalSpotsForWords[spot][index].second;
CrosswordBoard[column][row]=foundWord[index];
}
WordList.erase(remove_if(begin(WordList), end(WordList), [foundWord] (const auto & word){return word==foundWord;}), end(WordList));
}
}
for(int spot=0;spot<horizontalSpotsForWordsSize;++spot)
{
size_t spotSize=horizontalSpotsForWords[spot].size();
auto word=find_if(begin(WordList), end(WordList), [WordList, spotSize](const auto & w){return w.size()==spotSize;});
if(word!=end(WordList))
{
string foundWord=*(word);
for(int index=0;index<spotSize;++index)
{
int row=horizontalSpotsForWords[spot][index].first;
int column=horizontalSpotsForWords[spot][index].second;
CrosswordBoard[row][column]=foundWord[index];
}
WordList.erase(remove_if(begin(WordList), end(WordList), [foundWord] (const auto & word){return word==foundWord;}), end(WordList));
}
}
printCrosswordBoard(CrosswordBoard);
}<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: liImageRegistrationConsoleBase.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2001 Insight Consortium
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.
* The name of the Insight Consortium, nor the names of any consortium members,
nor of any contributors, may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=========================================================================*/
#include <liImageRegistrationConsoleBase.h>
/************************************
*
* Constructor
*
***********************************/
liImageRegistrationConsoleBase
::liImageRegistrationConsoleBase()
{
m_ImageLoaded = false;
m_Reader = ImageReaderType::New();
// The Target is indeed an adaptor
// from InputPixelType to PixelType
m_TargetImage = TargetType::New();
m_TargetImage->SetImage( m_Reader->GetOutput() );
m_ReferenceImage = ReferenceType::New();
m_MappedReferenceImage = MappedReferenceType::New();
m_TargetMapper = TargetMapperType::New();
m_ReferenceMapper = ReferenceMapperType::New();
m_MutualInformationMethod =
MutualInformationRegistrationMethodType::New();
m_MeansSquaresMethod =
MeanSquaresRegistrationMethodType::New();
m_PatternIntensityMethod =
PatternIntensityRegistrationMethodType::New();
m_NormalizedCorrelationMethod =
NormalizedCorrelationRegistrationMethodType::New();
m_SelectedMethod = meanSquares;
}
/************************************
*
* Destructor
*
***********************************/
liImageRegistrationConsoleBase
::~liImageRegistrationConsoleBase()
{
}
/************************************
*
* Load
*
***********************************/
void
liImageRegistrationConsoleBase
::Load( const char * filename )
{
if( !filename )
{
return;
}
m_Reader->SetFileToLoad( filename );
m_Reader->Update();
m_ImageLoaded = true;
}
/************************************
*
* Show Progress
*
***********************************/
void
liImageRegistrationConsoleBase
::ShowProgress( float )
{
}
/************************************
*
* Show Status
*
***********************************/
void
liImageRegistrationConsoleBase
::ShowStatus( const char * )
{
}
/************************************
*
* Generate reference image
*
***********************************/
void
liImageRegistrationConsoleBase
::GenerateReference( void )
{
this->ShowStatus("Transforming the original image...");
// Select to Process the whole image
m_TargetImage->SetRequestedRegion(
m_TargetImage->GetBufferedRegion() );
// Allocate the reference accordingly
m_ReferenceImage = ReferenceType::New();
m_ReferenceImage->SetLargestPossibleRegion(
m_TargetImage->GetLargestPossibleRegion() );
m_ReferenceImage->SetBufferedRegion(
m_TargetImage->GetBufferedRegion() );
m_ReferenceImage->SetRequestedRegion(
m_TargetImage->GetRequestedRegion() );
m_ReferenceImage->Allocate();
m_TargetMapper->SetDomain( m_TargetImage );
this->UpdateTransformParameters();
typedef ReferenceType::IndexType IndexType;
ReferenceIteratorType it( m_ReferenceImage,
m_ReferenceImage->GetRequestedRegion() );
float percent = 0.0;
const unsigned long totalPixels =
m_ReferenceImage->GetOffsetTable()[ImageDimension];
const unsigned long hundreth = totalPixels / 100;
unsigned long counter = 0;
it.Begin();
while( ! it.IsAtEnd() )
{
if( counter > hundreth )
{
counter = 0;
percent += 0.01;
this->ShowProgress( percent );
}
IndexType index = it.GetIndex();
PointType point;
for(unsigned int i=0; i<ImageDimension; i++)
{
point[i] = index[i];
}
PixelType value;
if( m_TargetMapper->IsInside( point ) )
{
value = m_TargetMapper->Evaluate();
}
else
{
value = 0.0;
}
it.Set( value );
++it;
++counter;
}
this->ShowProgress( 1.0 );
this->ShowStatus("Target Image Transformation done");
}
/************************************
*
* Stop Registration
*
***********************************/
void
liImageRegistrationConsoleBase
::Stop( void )
{
if( ! (m_ImageLoaded) )
{
this->ShowStatus("Please load an image first");
return;
}
switch( m_SelectedMethod )
{
case mutualInformation:
m_MutualInformationMethod->GetOptimizer()->StopOptimization();
break;
case normalizedCorrelation:
m_NormalizedCorrelationMethod->GetOptimizer()->StopOptimization();
break;
case patternIntensity:
m_PatternIntensityMethod->GetOptimizer()->StopOptimization();
break;
case meanSquares:
m_MeansSquaresMethod->GetOptimizer()->StopOptimization();
break;
}
}
/************************************
*
* Execute
*
***********************************/
void
liImageRegistrationConsoleBase
::Execute( void )
{
if( ! (m_ImageLoaded) )
{
this->ShowStatus("Please load an image first");
return;
}
const double translationScale = 1e4;
switch( m_SelectedMethod )
{
case mutualInformation:
{
m_MutualInformationMethod->SetReference( m_ReferenceImage );
m_MutualInformationMethod->SetTarget( m_TargetImage );
TargetType::SizeType size;
size = m_TargetImage->GetRequestedRegion().GetSize();
// set the transform centers
MutualInformationRegistrationMethodType::PointType transCenter;
for( unsigned int j = 0; j < ImageDimension; j++ )
{
transCenter[j] = double(size[j]) / 2;
}
// set optimization related parameters
m_MutualInformationMethod->SetNumberOfIterations( 1000 );
m_MutualInformationMethod->SetLearningRate( 0.2 );
// set metric related parameters
m_MutualInformationMethod->GetMetric()->SetTargetStandardDeviation( 20.0 );
m_MutualInformationMethod->GetMetric()->SetReferenceStandardDeviation( 20.0 );
m_MutualInformationMethod->GetMetric()->SetNumberOfSpatialSamples( 50 );
m_MutualInformationMethod->StartRegistration();
m_ReferenceMapper->GetTransform()->SetParameters(
m_MutualInformationMethod->GetOptimizer()->GetCurrentPosition() );
break;
}
case normalizedCorrelation:
{
m_NormalizedCorrelationMethod->SetReference( m_ReferenceImage );
m_NormalizedCorrelationMethod->SetTarget( m_TargetImage );
m_NormalizedCorrelationMethod->SetTranslationScale( translationScale );
m_NormalizedCorrelationMethod->StartRegistration();
m_ReferenceMapper->GetTransform()->SetParameters(
m_NormalizedCorrelationMethod->GetOptimizer()->GetCurrentPosition() );
break;
}
case patternIntensity:
{
m_PatternIntensityMethod->SetReference( m_ReferenceImage );
m_PatternIntensityMethod->SetTarget( m_TargetImage );
m_PatternIntensityMethod->SetTranslationScale( translationScale );
m_PatternIntensityMethod->StartRegistration();
m_ReferenceMapper->GetTransform()->SetParameters(
m_PatternIntensityMethod->GetOptimizer()->GetCurrentPosition() );
break;
}
case meanSquares:
{
m_MeansSquaresMethod->SetReference( m_ReferenceImage );
m_MeansSquaresMethod->SetTarget( m_TargetImage );
m_MeansSquaresMethod->SetTranslationScale( translationScale );
m_MeansSquaresMethod->GetOptimizer()->SetMaximumStepLength( 1.0 );
m_MeansSquaresMethod->GetOptimizer()->SetMinimumStepLength( 1e-3 );
m_MeansSquaresMethod->GetOptimizer()->SetGradientMagnitudeTolerance( 1e-8 );
m_MeansSquaresMethod->GetOptimizer()->SetMaximumNumberOfIterations( 200 );
m_MeansSquaresMethod->StartRegistration();
m_ReferenceMapper->GetTransform()->SetParameters(
m_MeansSquaresMethod->GetOptimizer()->GetCurrentPosition() );
break;
}
}
}
/************************************
*
* Generate Mapped Reference image
*
***********************************/
void
liImageRegistrationConsoleBase
::GenerateMappedReference( void )
{
this->ShowStatus("Transforming the reference image...");
// Allocate the reference accordingly
m_MappedReferenceImage = MappedReferenceType::New();
m_MappedReferenceImage->SetLargestPossibleRegion(
m_TargetImage->GetLargestPossibleRegion() );
m_MappedReferenceImage->SetBufferedRegion(
m_TargetImage->GetBufferedRegion() );
// Process all the buffered data
m_MappedReferenceImage->SetRequestedRegion(
m_TargetImage->GetBufferedRegion() );
m_MappedReferenceImage->Allocate();
m_ReferenceMapper->SetDomain( m_ReferenceImage );
this->UpdateTransformParameters();
typedef ReferenceType::IndexType IndexType;
ReferenceIteratorType it(
m_MappedReferenceImage,
m_MappedReferenceImage->GetRequestedRegion() );
float percent = 0.0;
const unsigned long totalPixels =
m_MappedReferenceImage->GetOffsetTable()[ImageDimension];
const unsigned long hundreth = totalPixels / 100;
unsigned long counter = 0;
it.Begin();
while( ! it.IsAtEnd() )
{
if( counter > hundreth )
{
counter = 0;
percent += 0.01;
this->ShowProgress( percent );
}
IndexType index = it.GetIndex();
PointType point;
for(unsigned int i=0; i<ImageDimension; i++)
{
point[i] = index[i];
}
PixelType value;
if( m_TargetMapper->IsInside( point ) )
{
value = m_ReferenceMapper->Evaluate();
}
else
{
value = 0.0;
}
it.Set( value );
++it;
++counter;
}
this->ShowProgress( 1.0 );
this->ShowStatus("Reference Image Transformation done");
}
/************************************
*
* Update the parameters of the
* Transform
*
***********************************/
void
liImageRegistrationConsoleBase
::UpdateTransformParameters( void )
{
}
/************************************
*
* Select the registration method
*
***********************************/
void
liImageRegistrationConsoleBase
::SelectRegistrationMethod( RegistrationMethodType method )
{
m_SelectedMethod = method;
}
<commit_msg>FIX: changes for new API<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: liImageRegistrationConsoleBase.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2001 Insight Consortium
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.
* The name of the Insight Consortium, nor the names of any consortium members,
nor of any contributors, may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=========================================================================*/
#include <liImageRegistrationConsoleBase.h>
/************************************
*
* Constructor
*
***********************************/
liImageRegistrationConsoleBase
::liImageRegistrationConsoleBase()
{
m_ImageLoaded = false;
m_Reader = ImageReaderType::New();
// The Target is indeed an adaptor
// from InputPixelType to PixelType
m_TargetImage = TargetType::New();
m_TargetImage->SetImage( m_Reader->GetOutput() );
m_ReferenceImage = ReferenceType::New();
m_MappedReferenceImage = MappedReferenceType::New();
m_TargetMapper = TargetMapperType::New();
m_ReferenceMapper = ReferenceMapperType::New();
m_MutualInformationMethod =
MutualInformationRegistrationMethodType::New();
m_MeansSquaresMethod =
MeanSquaresRegistrationMethodType::New();
m_PatternIntensityMethod =
PatternIntensityRegistrationMethodType::New();
m_NormalizedCorrelationMethod =
NormalizedCorrelationRegistrationMethodType::New();
m_SelectedMethod = meanSquares;
}
/************************************
*
* Destructor
*
***********************************/
liImageRegistrationConsoleBase
::~liImageRegistrationConsoleBase()
{
}
/************************************
*
* Load
*
***********************************/
void
liImageRegistrationConsoleBase
::Load( const char * filename )
{
if( !filename )
{
return;
}
m_Reader->SetFileName( filename );
m_Reader->Update();
m_ImageLoaded = true;
}
/************************************
*
* Show Progress
*
***********************************/
void
liImageRegistrationConsoleBase
::ShowProgress( float )
{
}
/************************************
*
* Show Status
*
***********************************/
void
liImageRegistrationConsoleBase
::ShowStatus( const char * )
{
}
/************************************
*
* Generate reference image
*
***********************************/
void
liImageRegistrationConsoleBase
::GenerateReference( void )
{
this->ShowStatus("Transforming the original image...");
// Select to Process the whole image
m_TargetImage->SetRequestedRegion(
m_TargetImage->GetBufferedRegion() );
// Allocate the reference accordingly
m_ReferenceImage = ReferenceType::New();
m_ReferenceImage->SetLargestPossibleRegion(
m_TargetImage->GetLargestPossibleRegion() );
m_ReferenceImage->SetBufferedRegion(
m_TargetImage->GetBufferedRegion() );
m_ReferenceImage->SetRequestedRegion(
m_TargetImage->GetRequestedRegion() );
m_ReferenceImage->Allocate();
m_TargetMapper->SetDomain( m_TargetImage );
this->UpdateTransformParameters();
typedef ReferenceType::IndexType IndexType;
ReferenceIteratorType it( m_ReferenceImage,
m_ReferenceImage->GetRequestedRegion() );
float percent = 0.0;
const unsigned long totalPixels =
m_ReferenceImage->GetOffsetTable()[ImageDimension];
const unsigned long hundreth = totalPixels / 100;
unsigned long counter = 0;
it.Begin();
while( ! it.IsAtEnd() )
{
if( counter > hundreth )
{
counter = 0;
percent += 0.01;
this->ShowProgress( percent );
}
IndexType index = it.GetIndex();
PointType point;
for(unsigned int i=0; i<ImageDimension; i++)
{
point[i] = index[i];
}
PixelType value;
if( m_TargetMapper->IsInside( point ) )
{
value = m_TargetMapper->Evaluate();
}
else
{
value = 0.0;
}
it.Set( value );
++it;
++counter;
}
this->ShowProgress( 1.0 );
this->ShowStatus("Target Image Transformation done");
}
/************************************
*
* Stop Registration
*
***********************************/
void
liImageRegistrationConsoleBase
::Stop( void )
{
if( ! (m_ImageLoaded) )
{
this->ShowStatus("Please load an image first");
return;
}
switch( m_SelectedMethod )
{
case mutualInformation:
m_MutualInformationMethod->GetOptimizer()->StopOptimization();
break;
case normalizedCorrelation:
m_NormalizedCorrelationMethod->GetOptimizer()->StopOptimization();
break;
case patternIntensity:
m_PatternIntensityMethod->GetOptimizer()->StopOptimization();
break;
case meanSquares:
m_MeansSquaresMethod->GetOptimizer()->StopOptimization();
break;
}
}
/************************************
*
* Execute
*
***********************************/
void
liImageRegistrationConsoleBase
::Execute( void )
{
if( ! (m_ImageLoaded) )
{
this->ShowStatus("Please load an image first");
return;
}
const double translationScale = 1e4;
switch( m_SelectedMethod )
{
case mutualInformation:
{
m_MutualInformationMethod->SetReference( m_ReferenceImage );
m_MutualInformationMethod->SetTarget( m_TargetImage );
TargetType::SizeType size;
size = m_TargetImage->GetRequestedRegion().GetSize();
// set the transform centers
MutualInformationRegistrationMethodType::PointType transCenter;
for( unsigned int j = 0; j < ImageDimension; j++ )
{
transCenter[j] = double(size[j]) / 2;
}
// set optimization related parameters
m_MutualInformationMethod->SetNumberOfIterations( 1000 );
m_MutualInformationMethod->SetLearningRate( 0.2 );
// set metric related parameters
m_MutualInformationMethod->GetMetric()->SetTargetStandardDeviation( 20.0 );
m_MutualInformationMethod->GetMetric()->SetReferenceStandardDeviation( 20.0 );
m_MutualInformationMethod->GetMetric()->SetNumberOfSpatialSamples( 50 );
m_MutualInformationMethod->StartRegistration();
m_ReferenceMapper->GetTransform()->SetParameters(
m_MutualInformationMethod->GetOptimizer()->GetCurrentPosition() );
break;
}
case normalizedCorrelation:
{
m_NormalizedCorrelationMethod->SetReference( m_ReferenceImage );
m_NormalizedCorrelationMethod->SetTarget( m_TargetImage );
m_NormalizedCorrelationMethod->SetTranslationScale( translationScale );
m_NormalizedCorrelationMethod->StartRegistration();
m_ReferenceMapper->GetTransform()->SetParameters(
m_NormalizedCorrelationMethod->GetOptimizer()->GetCurrentPosition() );
break;
}
case patternIntensity:
{
m_PatternIntensityMethod->SetReference( m_ReferenceImage );
m_PatternIntensityMethod->SetTarget( m_TargetImage );
m_PatternIntensityMethod->SetTranslationScale( translationScale );
m_PatternIntensityMethod->StartRegistration();
m_ReferenceMapper->GetTransform()->SetParameters(
m_PatternIntensityMethod->GetOptimizer()->GetCurrentPosition() );
break;
}
case meanSquares:
{
m_MeansSquaresMethod->SetReference( m_ReferenceImage );
m_MeansSquaresMethod->SetTarget( m_TargetImage );
m_MeansSquaresMethod->SetTranslationScale( translationScale );
m_MeansSquaresMethod->GetOptimizer()->SetMaximumStepLength( 1.0 );
m_MeansSquaresMethod->GetOptimizer()->SetMinimumStepLength( 1e-3 );
m_MeansSquaresMethod->GetOptimizer()->SetGradientMagnitudeTolerance( 1e-8 );
m_MeansSquaresMethod->GetOptimizer()->SetNumberOfIterations( 200 );
m_MeansSquaresMethod->StartRegistration();
m_ReferenceMapper->GetTransform()->SetParameters(
m_MeansSquaresMethod->GetOptimizer()->GetCurrentPosition() );
break;
}
}
}
/************************************
*
* Generate Mapped Reference image
*
***********************************/
void
liImageRegistrationConsoleBase
::GenerateMappedReference( void )
{
this->ShowStatus("Transforming the reference image...");
// Allocate the reference accordingly
m_MappedReferenceImage = MappedReferenceType::New();
m_MappedReferenceImage->SetLargestPossibleRegion(
m_TargetImage->GetLargestPossibleRegion() );
m_MappedReferenceImage->SetBufferedRegion(
m_TargetImage->GetBufferedRegion() );
// Process all the buffered data
m_MappedReferenceImage->SetRequestedRegion(
m_TargetImage->GetBufferedRegion() );
m_MappedReferenceImage->Allocate();
m_ReferenceMapper->SetDomain( m_ReferenceImage );
this->UpdateTransformParameters();
typedef ReferenceType::IndexType IndexType;
ReferenceIteratorType it(
m_MappedReferenceImage,
m_MappedReferenceImage->GetRequestedRegion() );
float percent = 0.0;
const unsigned long totalPixels =
m_MappedReferenceImage->GetOffsetTable()[ImageDimension];
const unsigned long hundreth = totalPixels / 100;
unsigned long counter = 0;
it.Begin();
while( ! it.IsAtEnd() )
{
if( counter > hundreth )
{
counter = 0;
percent += 0.01;
this->ShowProgress( percent );
}
IndexType index = it.GetIndex();
PointType point;
for(unsigned int i=0; i<ImageDimension; i++)
{
point[i] = index[i];
}
PixelType value;
if( m_TargetMapper->IsInside( point ) )
{
value = m_ReferenceMapper->Evaluate();
}
else
{
value = 0.0;
}
it.Set( value );
++it;
++counter;
}
this->ShowProgress( 1.0 );
this->ShowStatus("Reference Image Transformation done");
}
/************************************
*
* Update the parameters of the
* Transform
*
***********************************/
void
liImageRegistrationConsoleBase
::UpdateTransformParameters( void )
{
}
/************************************
*
* Select the registration method
*
***********************************/
void
liImageRegistrationConsoleBase
::SelectRegistrationMethod( RegistrationMethodType method )
{
m_SelectedMethod = method;
}
<|endoftext|>
|
<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
** disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
#include "DataApi.h"
#include "../dataformat/Tuple.h"
#include "../dataformat/TupleSet.h"
#include "../query_framework/Optional.h"
#include "ModelBase/src/nodes/Node.h"
namespace InformationScripting {
using namespace boost::python;
object value(const NamedProperty& self) {
return pythonObject(self.second);
}
object Tuple_getAttr(const Tuple& self, const QString& name) {
return pythonObject(self[name]);
}
uint Tuple_hash(const Tuple& self) {
return self.hashValue();
}
NamedProperty tuple_getItem(Tuple &t, int index)
{
if (index >= 0 && index < t.size())
return t[index];
else
{
PyErr_SetString(PyExc_IndexError, "index out of range");
throw_error_already_set();
}
return {};
}
std::shared_ptr<Tuple> makeTuple(list args) {
stl_input_iterator<NamedProperty> begin(args), end;
return std::make_shared<Tuple>(QList<NamedProperty>::fromStdList(std::list<NamedProperty>(begin, end)));
}
std::shared_ptr<TupleSet> makeTupleSet(list args) {
stl_input_iterator<Tuple> begin(args), end;
return std::make_shared<TupleSet>(QList<Tuple>::fromStdList(std::list<Tuple>(begin, end)));
}
BOOST_PYTHON_MODULE(DataApi) {
// This class exposure is just a workaround to make the name property of NamedProperty work.
// The problem is that if we just expose the NamedProperty::first as property,
// boost::python complains QString is not registered, even thought we specify a converter (I guess this is a bug)
// By registering as return by value this works.
// The second problem is that if we use print('{}'.format(namedproperty.name)) python somehow instantiates
// None.None(NamedProperty) but then complains it can't construct it since the base is not known, thus we expose it.
class_<QPair<QString, Property>, boost::noncopyable>("NamedPropertyBaseClass", no_init);
class_<NamedProperty, bases<QPair<QString, Property>>>("NamedProperty", init<QString, QString>())
.def(init<QString, Model::Node*>())
.def(init<QString, int>())
.add_property("name",
make_getter(&NamedProperty::first, return_value_policy<return_by_value>()),
make_setter(&NamedProperty::first))
.add_property("value", &value);
class_<Tuple>("Tuple", init<>())
.def("__init__", make_constructor(makeTuple))
.def("tupleTag", &Tuple::tag)
.def("add", &Tuple::add)
.def("__getattr__", &Tuple_getAttr)
.def("size", &Tuple::size)
.def("__getitem__", &tuple_getItem)
.def("__hash__", &Tuple_hash);
QSet<Tuple> (TupleSet::*tuplesAll)() const = &TupleSet::tuples;
QSet<Tuple> (TupleSet::*tuplesString)(const QString&) const = &TupleSet::tuples;
QSet<Tuple> (TupleSet::*take1)(const QString&) = &TupleSet::take;
void (TupleSet::*removeTuple)(const Tuple&) = &TupleSet::remove;
class_<TupleSet>("TupleSet", init<>())
.def("__init__", make_constructor(makeTupleSet))
.def("tuples", tuplesAll)
.def("tuples", tuplesString)
.def("take", take1)
.def("remove", removeTuple)
.def("add", &TupleSet::add);
class_<Optional<TupleSet>>("OptionalTupleSet", init<TupleSet>());
}
} /* namespace InformationScripting */
<commit_msg>Expose more TupleSet functionality to python<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
** disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
#include "DataApi.h"
#include "../dataformat/Tuple.h"
#include "../dataformat/TupleSet.h"
#include "../query_framework/Optional.h"
#include "ModelBase/src/nodes/Node.h"
namespace InformationScripting {
using namespace boost::python;
object value(const NamedProperty& self) {
return pythonObject(self.second);
}
object Tuple_getAttr(const Tuple& self, const QString& name) {
return pythonObject(self[name]);
}
uint Tuple_hash(const Tuple& self) {
return self.hashValue();
}
NamedProperty tuple_getItem(Tuple &t, int index)
{
if (index >= 0 && index < t.size())
return t[index];
else
{
PyErr_SetString(PyExc_IndexError, "index out of range");
throw_error_already_set();
}
return {};
}
std::shared_ptr<Tuple> makeTuple(list args) {
stl_input_iterator<NamedProperty> begin(args), end;
return std::make_shared<Tuple>(QList<NamedProperty>::fromStdList(std::list<NamedProperty>(begin, end)));
}
std::shared_ptr<TupleSet> makeTupleSet(list args) {
stl_input_iterator<Tuple> begin(args), end;
return std::make_shared<TupleSet>(QList<Tuple>::fromStdList(std::list<Tuple>(begin, end)));
}
BOOST_PYTHON_MODULE(DataApi) {
// This class exposure is just a workaround to make the name property of NamedProperty work.
// The problem is that if we just expose the NamedProperty::first as property,
// boost::python complains QString is not registered, even thought we specify a converter (I guess this is a bug)
// By registering as return by value this works.
// The second problem is that if we use print('{}'.format(namedproperty.name)) python somehow instantiates
// None.None(NamedProperty) but then complains it can't construct it since the base is not known, thus we expose it.
class_<QPair<QString, Property>, boost::noncopyable>("NamedPropertyBaseClass", no_init);
class_<NamedProperty, bases<QPair<QString, Property>>>("NamedProperty", init<QString, QString>())
.def(init<QString, Model::Node*>())
.def(init<QString, int>())
.add_property("name",
make_getter(&NamedProperty::first, return_value_policy<return_by_value>()),
make_setter(&NamedProperty::first))
.add_property("value", &value);
class_<Tuple>("Tuple", init<>())
.def("__init__", make_constructor(makeTuple))
.def("tupleTag", &Tuple::tag)
.def("add", &Tuple::add)
.def("__getattr__", &Tuple_getAttr)
.def("size", &Tuple::size)
.def("__getitem__", &tuple_getItem)
.def("__hash__", &Tuple_hash);
QSet<Tuple> (TupleSet::*tuplesAll)() const = &TupleSet::tuples;
QSet<Tuple> (TupleSet::*tuplesString)(const QString&) const = &TupleSet::tuples;
QSet<Tuple> (TupleSet::*take1)(const QString&) = &TupleSet::take;
void (TupleSet::*removeTuple)(const Tuple&) = &TupleSet::remove;
void (TupleSet::*removeTupleSet)(const TupleSet&) = &TupleSet::remove;
class_<TupleSet>("TupleSet", init<>())
.def("__init__", make_constructor(makeTupleSet))
.def("tuples", tuplesAll)
.def("tuples", tuplesString)
.def("add", &TupleSet::add)
.def("remove", removeTuple)
.def("remove", removeTupleSet)
.def("take", take1)
.def("takeAll", &TupleSet::takeAll)
.def("unite", &TupleSet::unite);
class_<Optional<TupleSet>>("OptionalTupleSet", init<TupleSet>());
}
} /* namespace InformationScripting */
<|endoftext|>
|
<commit_before>/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include <mitkIOUtil.h>
#include <mitkLabelSetImage.h>
#include <mitkTestFixture.h>
#include <mitkTestingMacros.h>
class mitkTransferLabelTestSuite : public mitk::TestFixture
{
CPPUNIT_TEST_SUITE(mitkTransferLabelTestSuite);
MITK_TEST(TestTransfer_defaults);
MITK_TEST(TestTransfer_Merge_RegardLocks);
MITK_TEST(TestTransfer_Merge_IgnoreLocks);
MITK_TEST(TestTransfer_Replace_RegardLocks);
MITK_TEST(TestTransfer_Replace_IgnoreLocks);
MITK_TEST(TestTransfer_multipleLabels);
CPPUNIT_TEST_SUITE_END();
private:
mitk::LabelSetImage::Pointer m_SourceImage;
mitk::LabelSetImage::PixelType m_LabelLocked1 = 1;
mitk::LabelSetImage::PixelType m_LabelLocked2 = 2;
mitk::LabelSetImage::PixelType m_LabelUnLocked1 = 3;
mitk::LabelSetImage::PixelType m_LabelUnLocked2 = 4;
public:
void setUp() override
{
m_SourceImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_source.nrrd"));
}
void tearDown() override
{
m_SourceImage = nullptr;
}
void TestTransfer_defaults()
{
auto destinationImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_destination.nrrd"));
auto destinationLockedExteriorImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_destination_lockedExterior.nrrd"));
auto refmage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_result_replace_regardLocks.nrrd"));
auto refLockedExteriorImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_result_replace_regardLocks_lockedExterior.nrrd"));
mitk::TransferLabelContent(m_SourceImage, destinationImage);
mitk::TransferLabelContent(m_SourceImage, destinationLockedExteriorImage);
CPPUNIT_ASSERT_MESSAGE("Transfer with default settings failed",
mitk::Equal(*(destinationImage.GetPointer()), *(refmage.GetPointer()), mitk::eps, false));
CPPUNIT_ASSERT_MESSAGE("Transfer with default settings + exterior lock failed",
mitk::Equal(*(destinationLockedExteriorImage.GetPointer()), *(refLockedExteriorImage.GetPointer()), mitk::eps, false));
}
void TestTransfer_Merge_RegardLocks()
{
auto destinationImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_destination.nrrd"));
auto destinationLockedExteriorImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_destination_lockedExterior.nrrd"));
auto refmage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_result_merge_regardLocks.nrrd"));
auto refLockedExteriorImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_result_merge_regardLocks_lockedExterior.nrrd"));
mitk::TransferLabelContent(m_SourceImage, destinationImage, { {1,1} }, mitk::MultiLabelSegmentation::MergeStyle::Merge, mitk::MultiLabelSegmentation::OverwriteStyle::RegardLocks);
mitk::TransferLabelContent(m_SourceImage, destinationLockedExteriorImage, { {1,1} }, mitk::MultiLabelSegmentation::MergeStyle::Merge, mitk::MultiLabelSegmentation::OverwriteStyle::RegardLocks);
CPPUNIT_ASSERT_MESSAGE("Transfer with merge + regardLocks settings failed",
mitk::Equal(*(destinationImage.GetPointer()), *(refmage.GetPointer()), mitk::eps, false));
CPPUNIT_ASSERT_MESSAGE("Transfer with merge + regardLocks + exterior lock settings failed",
mitk::Equal(*(destinationLockedExteriorImage.GetPointer()), *(refLockedExteriorImage.GetPointer()), mitk::eps, false));
}
void TestTransfer_Merge_IgnoreLocks()
{
auto destinationImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_destination.nrrd"));
auto destinationLockedExteriorImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_destination_lockedExterior.nrrd"));
auto refmage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_result_merge_ignoreLocks.nrrd"));
auto refLockedExteriorImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_result_merge_ignoreLocks_lockedExterior.nrrd"));
mitk::TransferLabelContent(m_SourceImage, destinationImage, { {1,1} }, mitk::MultiLabelSegmentation::MergeStyle::Merge, mitk::MultiLabelSegmentation::OverwriteStyle::IgnoreLocks);
mitk::TransferLabelContent(m_SourceImage, destinationLockedExteriorImage, { {1,1} }, mitk::MultiLabelSegmentation::MergeStyle::Merge, mitk::MultiLabelSegmentation::OverwriteStyle::IgnoreLocks);
CPPUNIT_ASSERT_MESSAGE("Transfer with merge + ignoreLocks settings failed",
mitk::Equal(*(destinationImage.GetPointer()), *(refmage.GetPointer()), mitk::eps, false));
CPPUNIT_ASSERT_MESSAGE("Transfer with merge + ignoreLocks + exterior lock settings failed",
mitk::Equal(*(destinationLockedExteriorImage.GetPointer()), *(refLockedExteriorImage.GetPointer()), mitk::eps, false));
}
void TestTransfer_Replace_RegardLocks()
{
auto destinationImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_destination.nrrd"));
auto destinationLockedExteriorImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_destination_lockedExterior.nrrd"));
auto refmage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_result_replace_regardLocks.nrrd"));
auto refLockedExteriorImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_result_replace_regardLocks_lockedExterior.nrrd"));
mitk::TransferLabelContent(m_SourceImage, destinationImage, { {1,1} }, mitk::MultiLabelSegmentation::MergeStyle::Replace, mitk::MultiLabelSegmentation::OverwriteStyle::RegardLocks);
mitk::TransferLabelContent(m_SourceImage, destinationLockedExteriorImage, { {1,1} }, mitk::MultiLabelSegmentation::MergeStyle::Replace, mitk::MultiLabelSegmentation::OverwriteStyle::RegardLocks);
CPPUNIT_ASSERT_MESSAGE("Transfer with replace + regardLocks settings failed",
mitk::Equal(*(destinationImage.GetPointer()), *(refmage.GetPointer()), mitk::eps, false));
CPPUNIT_ASSERT_MESSAGE("Transfer with replace + regardLocks + exterior lock settings failed",
mitk::Equal(*(destinationLockedExteriorImage.GetPointer()), *(refLockedExteriorImage.GetPointer()), mitk::eps, false));
}
void TestTransfer_Replace_IgnoreLocks()
{
auto destinationImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_destination.nrrd"));
auto destinationLockedExteriorImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_destination_lockedExterior.nrrd"));
auto refmage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_result_replace_ignoreLocks.nrrd"));
auto refLockedExteriorImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_result_replace_ignoreLocks_lockedExterior.nrrd"));
mitk::TransferLabelContent(m_SourceImage, destinationImage, { {1,1} }, mitk::MultiLabelSegmentation::MergeStyle::Replace, mitk::MultiLabelSegmentation::OverwriteStyle::IgnoreLocks);
mitk::TransferLabelContent(m_SourceImage, destinationLockedExteriorImage, { {1,1} }, mitk::MultiLabelSegmentation::MergeStyle::Replace, mitk::MultiLabelSegmentation::OverwriteStyle::IgnoreLocks);
CPPUNIT_ASSERT_MESSAGE("Transfer with replace + ignoreLocks settings failed",
mitk::Equal(*(destinationImage.GetPointer()), *(refmage.GetPointer()), mitk::eps, false));
CPPUNIT_ASSERT_MESSAGE("Transfer with replace + ignoreLocks + exterior lock settings failed",
mitk::Equal(*(destinationLockedExteriorImage.GetPointer()), *(refLockedExteriorImage.GetPointer()), mitk::eps, false));
}
void TestTransfer_multipleLabels()
{
auto destinationImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_destination.nrrd"));
auto destinationLockedExteriorImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_destination_lockedExterior.nrrd"));
auto refmage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_result_multipleLabels.nrrd"));
auto refLockedExteriorImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_result_multipleLabels_lockedExterior.nrrd"));
mitk::TransferLabelContent(m_SourceImage, destinationImage, { {1,1}, {3,1}, {2,4}, {4,2} }, mitk::MultiLabelSegmentation::MergeStyle::Replace, mitk::MultiLabelSegmentation::OverwriteStyle::IgnoreLocks);
mitk::TransferLabelContent(m_SourceImage, destinationLockedExteriorImage, { {1,1}, {3,1}, {2,4}, {4,2} }, mitk::MultiLabelSegmentation::MergeStyle::Replace, mitk::MultiLabelSegmentation::OverwriteStyle::IgnoreLocks);
CPPUNIT_ASSERT_MESSAGE("Transfer multiple labels (1->1, 3->1, 2->4, 4->2) with replace + ignoreLocks settings failed",
mitk::Equal(*(destinationImage.GetPointer()), *(refmage.GetPointer()), mitk::eps, false));
CPPUNIT_ASSERT_MESSAGE("Transfer multiple labels (1->1, 3->1, 2->4, 4->2) with replace + ignoreLocks + exterior lock settings failed",
mitk::Equal(*(destinationLockedExteriorImage.GetPointer()), *(refLockedExteriorImage.GetPointer()), mitk::eps, false));
}
};
MITK_TEST_SUITE_REGISTRATION(mitkTransferLabel)
<commit_msg>removed unused variables<commit_after>/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include <mitkIOUtil.h>
#include <mitkLabelSetImage.h>
#include <mitkTestFixture.h>
#include <mitkTestingMacros.h>
class mitkTransferLabelTestSuite : public mitk::TestFixture
{
CPPUNIT_TEST_SUITE(mitkTransferLabelTestSuite);
MITK_TEST(TestTransfer_defaults);
MITK_TEST(TestTransfer_Merge_RegardLocks);
MITK_TEST(TestTransfer_Merge_IgnoreLocks);
MITK_TEST(TestTransfer_Replace_RegardLocks);
MITK_TEST(TestTransfer_Replace_IgnoreLocks);
MITK_TEST(TestTransfer_multipleLabels);
CPPUNIT_TEST_SUITE_END();
private:
mitk::LabelSetImage::Pointer m_SourceImage;
public:
void setUp() override
{
m_SourceImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_source.nrrd"));
}
void tearDown() override
{
m_SourceImage = nullptr;
}
void TestTransfer_defaults()
{
auto destinationImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_destination.nrrd"));
auto destinationLockedExteriorImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_destination_lockedExterior.nrrd"));
auto refmage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_result_replace_regardLocks.nrrd"));
auto refLockedExteriorImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_result_replace_regardLocks_lockedExterior.nrrd"));
mitk::TransferLabelContent(m_SourceImage, destinationImage);
mitk::TransferLabelContent(m_SourceImage, destinationLockedExteriorImage);
CPPUNIT_ASSERT_MESSAGE("Transfer with default settings failed",
mitk::Equal(*(destinationImage.GetPointer()), *(refmage.GetPointer()), mitk::eps, false));
CPPUNIT_ASSERT_MESSAGE("Transfer with default settings + exterior lock failed",
mitk::Equal(*(destinationLockedExteriorImage.GetPointer()), *(refLockedExteriorImage.GetPointer()), mitk::eps, false));
}
void TestTransfer_Merge_RegardLocks()
{
auto destinationImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_destination.nrrd"));
auto destinationLockedExteriorImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_destination_lockedExterior.nrrd"));
auto refmage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_result_merge_regardLocks.nrrd"));
auto refLockedExteriorImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_result_merge_regardLocks_lockedExterior.nrrd"));
mitk::TransferLabelContent(m_SourceImage, destinationImage, { {1,1} }, mitk::MultiLabelSegmentation::MergeStyle::Merge, mitk::MultiLabelSegmentation::OverwriteStyle::RegardLocks);
mitk::TransferLabelContent(m_SourceImage, destinationLockedExteriorImage, { {1,1} }, mitk::MultiLabelSegmentation::MergeStyle::Merge, mitk::MultiLabelSegmentation::OverwriteStyle::RegardLocks);
CPPUNIT_ASSERT_MESSAGE("Transfer with merge + regardLocks settings failed",
mitk::Equal(*(destinationImage.GetPointer()), *(refmage.GetPointer()), mitk::eps, false));
CPPUNIT_ASSERT_MESSAGE("Transfer with merge + regardLocks + exterior lock settings failed",
mitk::Equal(*(destinationLockedExteriorImage.GetPointer()), *(refLockedExteriorImage.GetPointer()), mitk::eps, false));
}
void TestTransfer_Merge_IgnoreLocks()
{
auto destinationImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_destination.nrrd"));
auto destinationLockedExteriorImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_destination_lockedExterior.nrrd"));
auto refmage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_result_merge_ignoreLocks.nrrd"));
auto refLockedExteriorImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_result_merge_ignoreLocks_lockedExterior.nrrd"));
mitk::TransferLabelContent(m_SourceImage, destinationImage, { {1,1} }, mitk::MultiLabelSegmentation::MergeStyle::Merge, mitk::MultiLabelSegmentation::OverwriteStyle::IgnoreLocks);
mitk::TransferLabelContent(m_SourceImage, destinationLockedExteriorImage, { {1,1} }, mitk::MultiLabelSegmentation::MergeStyle::Merge, mitk::MultiLabelSegmentation::OverwriteStyle::IgnoreLocks);
CPPUNIT_ASSERT_MESSAGE("Transfer with merge + ignoreLocks settings failed",
mitk::Equal(*(destinationImage.GetPointer()), *(refmage.GetPointer()), mitk::eps, false));
CPPUNIT_ASSERT_MESSAGE("Transfer with merge + ignoreLocks + exterior lock settings failed",
mitk::Equal(*(destinationLockedExteriorImage.GetPointer()), *(refLockedExteriorImage.GetPointer()), mitk::eps, false));
}
void TestTransfer_Replace_RegardLocks()
{
auto destinationImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_destination.nrrd"));
auto destinationLockedExteriorImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_destination_lockedExterior.nrrd"));
auto refmage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_result_replace_regardLocks.nrrd"));
auto refLockedExteriorImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_result_replace_regardLocks_lockedExterior.nrrd"));
mitk::TransferLabelContent(m_SourceImage, destinationImage, { {1,1} }, mitk::MultiLabelSegmentation::MergeStyle::Replace, mitk::MultiLabelSegmentation::OverwriteStyle::RegardLocks);
mitk::TransferLabelContent(m_SourceImage, destinationLockedExteriorImage, { {1,1} }, mitk::MultiLabelSegmentation::MergeStyle::Replace, mitk::MultiLabelSegmentation::OverwriteStyle::RegardLocks);
CPPUNIT_ASSERT_MESSAGE("Transfer with replace + regardLocks settings failed",
mitk::Equal(*(destinationImage.GetPointer()), *(refmage.GetPointer()), mitk::eps, false));
CPPUNIT_ASSERT_MESSAGE("Transfer with replace + regardLocks + exterior lock settings failed",
mitk::Equal(*(destinationLockedExteriorImage.GetPointer()), *(refLockedExteriorImage.GetPointer()), mitk::eps, false));
}
void TestTransfer_Replace_IgnoreLocks()
{
auto destinationImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_destination.nrrd"));
auto destinationLockedExteriorImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_destination_lockedExterior.nrrd"));
auto refmage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_result_replace_ignoreLocks.nrrd"));
auto refLockedExteriorImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_result_replace_ignoreLocks_lockedExterior.nrrd"));
mitk::TransferLabelContent(m_SourceImage, destinationImage, { {1,1} }, mitk::MultiLabelSegmentation::MergeStyle::Replace, mitk::MultiLabelSegmentation::OverwriteStyle::IgnoreLocks);
mitk::TransferLabelContent(m_SourceImage, destinationLockedExteriorImage, { {1,1} }, mitk::MultiLabelSegmentation::MergeStyle::Replace, mitk::MultiLabelSegmentation::OverwriteStyle::IgnoreLocks);
CPPUNIT_ASSERT_MESSAGE("Transfer with replace + ignoreLocks settings failed",
mitk::Equal(*(destinationImage.GetPointer()), *(refmage.GetPointer()), mitk::eps, false));
CPPUNIT_ASSERT_MESSAGE("Transfer with replace + ignoreLocks + exterior lock settings failed",
mitk::Equal(*(destinationLockedExteriorImage.GetPointer()), *(refLockedExteriorImage.GetPointer()), mitk::eps, false));
}
void TestTransfer_multipleLabels()
{
auto destinationImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_destination.nrrd"));
auto destinationLockedExteriorImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_destination_lockedExterior.nrrd"));
auto refmage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_result_multipleLabels.nrrd"));
auto refLockedExteriorImage = mitk::IOUtil::Load<mitk::LabelSetImage>(GetTestDataFilePath("Multilabel/LabelTransferTest_result_multipleLabels_lockedExterior.nrrd"));
mitk::TransferLabelContent(m_SourceImage, destinationImage, { {1,1}, {3,1}, {2,4}, {4,2} }, mitk::MultiLabelSegmentation::MergeStyle::Replace, mitk::MultiLabelSegmentation::OverwriteStyle::IgnoreLocks);
mitk::TransferLabelContent(m_SourceImage, destinationLockedExteriorImage, { {1,1}, {3,1}, {2,4}, {4,2} }, mitk::MultiLabelSegmentation::MergeStyle::Replace, mitk::MultiLabelSegmentation::OverwriteStyle::IgnoreLocks);
CPPUNIT_ASSERT_MESSAGE("Transfer multiple labels (1->1, 3->1, 2->4, 4->2) with replace + ignoreLocks settings failed",
mitk::Equal(*(destinationImage.GetPointer()), *(refmage.GetPointer()), mitk::eps, false));
CPPUNIT_ASSERT_MESSAGE("Transfer multiple labels (1->1, 3->1, 2->4, 4->2) with replace + ignoreLocks + exterior lock settings failed",
mitk::Equal(*(destinationLockedExteriorImage.GetPointer()), *(refLockedExteriorImage.GetPointer()), mitk::eps, false));
}
};
MITK_TEST_SUITE_REGISTRATION(mitkTransferLabel)
<|endoftext|>
|
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include <direct.h>
#include "Foundation.h"
#include "ModuleManager.h"
#include "HttpUtilities.h"
#include "DebugOperatorNew.h"
#if defined(_MSC_VER) && defined(MEMORY_LEAK_CHECK)
// for reporting memory leaks upon debug exit
#include <crtdbg.h>
#endif
#if defined(_MSC_VER) && defined(_DMEMDUMP)
// For generating minidump
#include <dbghelp.h>
#include <shellapi.h>
#include <shlobj.h>
#pragma warning(push)
#pragma warning(disable : 4996)
#include <strsafe.h>
#pragma warning(pop)
#endif
#include "MemoryLeakCheck.h"
void setup(Foundation::Framework &fw);
int run(int argc, char **argv);
void options(int argc, char **argv, Foundation::Framework &fw);
#if defined(_MSC_VER) && defined(_DMEMDUMP)
int generate_dump(EXCEPTION_POINTERS* pExceptionPointers);
#endif
int main (int argc, char **argv)
{
int return_value = EXIT_SUCCESS;
// set up a debug flag for memory leaks. Output the results to file when the app exits.
// Note that this file is written to the same directory where the executable resides,
// so you can only use this in a development version where you have write access to
// that directory.
#if defined(_MSC_VER) && defined(MEMORY_LEAK_CHECK)
int tmpDbgFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF;
_CrtSetDbgFlag(tmpDbgFlag);
HANDLE hLogFile = CreateFileW(L"fullmemoryleaklog.txt", GENERIC_WRITE,
FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
#endif
#if defined(_MSC_VER) && defined(_DMEMDUMP)
__try
{
#endif
return_value = run(argc, argv);
#if defined(_MSC_VER) && defined(_DMEMDUMP)
}
__except(generate_dump(GetExceptionInformation()))
{
}
#endif
#if defined(_MSC_VER) && defined(MEMORY_LEAK_CHECK)
if (hLogFile != INVALID_HANDLE_VALUE)
{
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, hLogFile);
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ERROR, hLogFile);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ASSERT, hLogFile);
}
#endif
// Note: We cannot close the file handle manually here. Have to let the OS close it
// after it has printed out the list of leaks to the file.
// CloseHandle(hLogFile);
return return_value;
}
//! post init setup for framework
void setup (Foundation::Framework &fw)
{
// Exclude the login screen from loading
fw.GetModuleManager()->ExcludeModule("LoginScreenModule");
// Exclude window & rendering related stuff, if a fully headless server is desired
//fw.GetModuleManager()->ExcludeModule("ConsoleModule");
//fw.GetModuleManager()->ExcludeModule("QtInputModule");
//fw.GetModuleManager()->ExcludeModule("OgreRenderingModule");
//fw.GetModuleManager()->ExcludeModule("OpenALAudioModule");
//fw.GetModuleManager()->ExcludeModule("UiServiceModule");
}
std::string GetWorkingDirectory()
{
char *buffer = _getcwd( NULL, 0 );
if (buffer)
{
std::string s = buffer;
free(buffer);
return s;
}
return "(null)";
}
int run (int argc, char **argv)
{
int return_value = EXIT_SUCCESS;
printf("Starting up server. Current working directory: %s.\n", GetWorkingDirectory().c_str());
// Create application object
#if !defined(_DEBUG) || !defined (_MSC_VER)
try
#endif
{
HttpUtilities::InitializeHttp();
Foundation::Framework fw(argc, argv);
if (fw.Initialized())
{
setup (fw);
fw.Go();
}
HttpUtilities::UninitializeHttp();
}
#if !defined(_DEBUG) || !defined (_MSC_VER)
catch (std::exception& e)
{
Foundation::Platform::Message("An exception has occurred!", e.what());
#if defined(_DEBUG)
throw;
#else
return_value = EXIT_FAILURE;
#endif
}
#endif
return return_value;
}
#if defined(_MSC_VER) && defined(WINDOWS_APP)
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
// Parse Windows command line
std::vector<std::string> arguments;
std::string cmdLine(lpCmdLine);
unsigned i;
unsigned cmdStart = 0;
unsigned cmdEnd = 0;
bool cmd = false;
bool quote = false;
arguments.push_back("server");
for (i = 0; i < cmdLine.length(); ++i)
{
if (cmdLine[i] == '\"')
quote = !quote;
if ((cmdLine[i] == ' ') && (!quote))
{
if (cmd)
{
cmd = false;
cmdEnd = i;
arguments.push_back(cmdLine.substr(cmdStart, cmdEnd-cmdStart));
}
}
else
{
if (!cmd)
{
cmd = true;
cmdStart = i;
}
}
}
if (cmd)
arguments.push_back(cmdLine.substr(cmdStart, i-cmdStart));
std::vector<const char*> argv;
for (int i = 0; i < arguments.size(); ++i)
argv.push_back(arguments[i].c_str());
if (argv.size())
return main(argv.size(), (char**)&argv[0]);
else
return main(0, 0);
}
#endif
#if defined(_MSC_VER) && defined(_DMEMDUMP)
int generate_dump(EXCEPTION_POINTERS* pExceptionPointers)
{
BOOL bMiniDumpSuccessful;
WCHAR szPath[MAX_PATH];
WCHAR szFileName[MAX_PATH];
// Can't use Foundation::Application for application name and version,
// since it might have not been initialized yet, or it might have caused
// the exception in the first place
WCHAR* szAppName = L"realXtend";
WCHAR* szVersion = L"Tundra_v0.3.0";
DWORD dwBufferSize = MAX_PATH;
HANDLE hDumpFile;
SYSTEMTIME stLocalTime;
MINIDUMP_EXCEPTION_INFORMATION ExpParam;
GetLocalTime( &stLocalTime );
GetTempPathW( dwBufferSize, szPath );
StringCchPrintf( szFileName, MAX_PATH, L"%s%s", szPath, szAppName );
CreateDirectoryW( szFileName, 0 );
StringCchPrintf( szFileName, MAX_PATH, L"%s%s\\%s-%04d%02d%02d-%02d%02d%02d-%ld-%ld.dmp",
szPath, szAppName, szVersion,
stLocalTime.wYear, stLocalTime.wMonth, stLocalTime.wDay,
stLocalTime.wHour, stLocalTime.wMinute, stLocalTime.wSecond,
GetCurrentProcessId(), GetCurrentThreadId());
hDumpFile = CreateFileW(szFileName, GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_WRITE|FILE_SHARE_READ, 0, CREATE_ALWAYS, 0, 0);
ExpParam.ThreadId = GetCurrentThreadId();
ExpParam.ExceptionPointers = pExceptionPointers;
ExpParam.ClientPointers = TRUE;
bMiniDumpSuccessful = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(),
hDumpFile, MiniDumpWithDataSegs, &ExpParam, 0, 0);
std::wstring message(L"Program ");
message += szAppName;
message += L" encountered an unexpected error.\n\nCrashdump was saved to location:\n";
message += szFileName;
if (bMiniDumpSuccessful)
Foundation::Platform::Message(L"Minidump generated!", message);
else
Foundation::Platform::Message(szAppName, L"Unexpected error was encountered while generating minidump!");
return EXCEPTION_EXECUTE_HANDLER;
}
#endif
<commit_msg>Use QDir::currentPath for cwd in Server main.cpp.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "Foundation.h"
#include "ModuleManager.h"
#include "HttpUtilities.h"
#include "DebugOperatorNew.h"
#include <QDir>
#if defined(_MSC_VER) && defined(MEMORY_LEAK_CHECK)
// for reporting memory leaks upon debug exit
#include <crtdbg.h>
#endif
#if defined(_MSC_VER) && defined(_DMEMDUMP)
// For generating minidump
#include <dbghelp.h>
#include <shellapi.h>
#include <shlobj.h>
#pragma warning(push)
#pragma warning(disable : 4996)
#include <strsafe.h>
#pragma warning(pop)
#endif
#include "MemoryLeakCheck.h"
void setup(Foundation::Framework &fw);
int run(int argc, char **argv);
void options(int argc, char **argv, Foundation::Framework &fw);
#if defined(_MSC_VER) && defined(_DMEMDUMP)
int generate_dump(EXCEPTION_POINTERS* pExceptionPointers);
#endif
int main (int argc, char **argv)
{
int return_value = EXIT_SUCCESS;
// set up a debug flag for memory leaks. Output the results to file when the app exits.
// Note that this file is written to the same directory where the executable resides,
// so you can only use this in a development version where you have write access to
// that directory.
#if defined(_MSC_VER) && defined(MEMORY_LEAK_CHECK)
int tmpDbgFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF;
_CrtSetDbgFlag(tmpDbgFlag);
HANDLE hLogFile = CreateFileW(L"fullmemoryleaklog.txt", GENERIC_WRITE,
FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
#endif
#if defined(_MSC_VER) && defined(_DMEMDUMP)
__try
{
#endif
return_value = run(argc, argv);
#if defined(_MSC_VER) && defined(_DMEMDUMP)
}
__except(generate_dump(GetExceptionInformation()))
{
}
#endif
#if defined(_MSC_VER) && defined(MEMORY_LEAK_CHECK)
if (hLogFile != INVALID_HANDLE_VALUE)
{
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, hLogFile);
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ERROR, hLogFile);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ASSERT, hLogFile);
}
#endif
// Note: We cannot close the file handle manually here. Have to let the OS close it
// after it has printed out the list of leaks to the file.
// CloseHandle(hLogFile);
return return_value;
}
//! post init setup for framework
void setup (Foundation::Framework &fw)
{
// Exclude the login screen from loading
fw.GetModuleManager()->ExcludeModule("LoginScreenModule");
// Exclude window & rendering related stuff, if a fully headless server is desired
//fw.GetModuleManager()->ExcludeModule("ConsoleModule");
//fw.GetModuleManager()->ExcludeModule("QtInputModule");
//fw.GetModuleManager()->ExcludeModule("OgreRenderingModule");
//fw.GetModuleManager()->ExcludeModule("OpenALAudioModule");
//fw.GetModuleManager()->ExcludeModule("UiServiceModule");
}
int run (int argc, char **argv)
{
int return_value = EXIT_SUCCESS;
printf("Starting up server. Current working directory: %s.\n", QDir::currentPath().toStdString().c_str());
// Create application object
#if !defined(_DEBUG) || !defined (_MSC_VER)
try
#endif
{
HttpUtilities::InitializeHttp();
Foundation::Framework fw(argc, argv);
if (fw.Initialized())
{
setup (fw);
fw.Go();
}
HttpUtilities::UninitializeHttp();
}
#if !defined(_DEBUG) || !defined (_MSC_VER)
catch (std::exception& e)
{
Foundation::Platform::Message("An exception has occurred!", e.what());
#if defined(_DEBUG)
throw;
#else
return_value = EXIT_FAILURE;
#endif
}
#endif
return return_value;
}
#if defined(_MSC_VER) && defined(WINDOWS_APP)
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
// Parse Windows command line
std::vector<std::string> arguments;
std::string cmdLine(lpCmdLine);
unsigned i;
unsigned cmdStart = 0;
unsigned cmdEnd = 0;
bool cmd = false;
bool quote = false;
arguments.push_back("server");
for (i = 0; i < cmdLine.length(); ++i)
{
if (cmdLine[i] == '\"')
quote = !quote;
if ((cmdLine[i] == ' ') && (!quote))
{
if (cmd)
{
cmd = false;
cmdEnd = i;
arguments.push_back(cmdLine.substr(cmdStart, cmdEnd-cmdStart));
}
}
else
{
if (!cmd)
{
cmd = true;
cmdStart = i;
}
}
}
if (cmd)
arguments.push_back(cmdLine.substr(cmdStart, i-cmdStart));
std::vector<const char*> argv;
for (int i = 0; i < arguments.size(); ++i)
argv.push_back(arguments[i].c_str());
if (argv.size())
return main(argv.size(), (char**)&argv[0]);
else
return main(0, 0);
}
#endif
#if defined(_MSC_VER) && defined(_DMEMDUMP)
int generate_dump(EXCEPTION_POINTERS* pExceptionPointers)
{
BOOL bMiniDumpSuccessful;
WCHAR szPath[MAX_PATH];
WCHAR szFileName[MAX_PATH];
// Can't use Foundation::Application for application name and version,
// since it might have not been initialized yet, or it might have caused
// the exception in the first place
WCHAR* szAppName = L"realXtend";
WCHAR* szVersion = L"Tundra_v0.3.0";
DWORD dwBufferSize = MAX_PATH;
HANDLE hDumpFile;
SYSTEMTIME stLocalTime;
MINIDUMP_EXCEPTION_INFORMATION ExpParam;
GetLocalTime( &stLocalTime );
GetTempPathW( dwBufferSize, szPath );
StringCchPrintf( szFileName, MAX_PATH, L"%s%s", szPath, szAppName );
CreateDirectoryW( szFileName, 0 );
StringCchPrintf( szFileName, MAX_PATH, L"%s%s\\%s-%04d%02d%02d-%02d%02d%02d-%ld-%ld.dmp",
szPath, szAppName, szVersion,
stLocalTime.wYear, stLocalTime.wMonth, stLocalTime.wDay,
stLocalTime.wHour, stLocalTime.wMinute, stLocalTime.wSecond,
GetCurrentProcessId(), GetCurrentThreadId());
hDumpFile = CreateFileW(szFileName, GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_WRITE|FILE_SHARE_READ, 0, CREATE_ALWAYS, 0, 0);
ExpParam.ThreadId = GetCurrentThreadId();
ExpParam.ExceptionPointers = pExceptionPointers;
ExpParam.ClientPointers = TRUE;
bMiniDumpSuccessful = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(),
hDumpFile, MiniDumpWithDataSegs, &ExpParam, 0, 0);
std::wstring message(L"Program ");
message += szAppName;
message += L" encountered an unexpected error.\n\nCrashdump was saved to location:\n";
message += szFileName;
if (bMiniDumpSuccessful)
Foundation::Platform::Message(L"Minidump generated!", message);
else
Foundation::Platform::Message(szAppName, L"Unexpected error was encountered while generating minidump!");
return EXCEPTION_EXECUTE_HANDLER;
}
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "StubViewTree.h"
#include <glog/logging.h>
#include <react/debug/react_native_assert.h>
#ifdef STUB_VIEW_TREE_VERBOSE
#define STUB_VIEW_LOG(code) code
#else
#define STUB_VIEW_LOG(code)
#endif
namespace facebook {
namespace react {
StubViewTree::StubViewTree(ShadowView const &shadowView) {
auto view = std::make_shared<StubView>();
view->update(shadowView);
rootTag = shadowView.tag;
registry[shadowView.tag] = view;
}
StubView const &StubViewTree::getRootStubView() const {
return *registry.at(rootTag);
}
StubView const &StubViewTree::getStubView(Tag tag) const {
return *registry.at(tag);
}
size_t StubViewTree::size() const {
return registry.size();
}
void StubViewTree::mutate(ShadowViewMutationList const &mutations) {
STUB_VIEW_LOG({ LOG(ERROR) << "StubView: Mutating Begin"; });
for (auto const &mutation : mutations) {
switch (mutation.type) {
case ShadowViewMutation::Create: {
react_native_assert(mutation.parentShadowView == ShadowView{});
react_native_assert(mutation.oldChildShadowView == ShadowView{});
react_native_assert(mutation.newChildShadowView.props);
auto stubView = std::make_shared<StubView>();
stubView->update(mutation.newChildShadowView);
auto tag = mutation.newChildShadowView.tag;
STUB_VIEW_LOG({ LOG(ERROR) << "StubView: Create: " << tag; });
react_native_assert(registry.find(tag) == registry.end());
registry[tag] = stubView;
break;
}
case ShadowViewMutation::Delete: {
STUB_VIEW_LOG(
{ LOG(ERROR) << "Delete " << mutation.oldChildShadowView.tag; });
react_native_assert(mutation.parentShadowView == ShadowView{});
react_native_assert(mutation.newChildShadowView == ShadowView{});
auto tag = mutation.oldChildShadowView.tag;
/* Disable this assert until T76057501 is resolved.
react_native_assert(registry.find(tag) != registry.end());
auto stubView = registry[tag];
react_native_assert(
(ShadowView)(*stubView) == mutation.oldChildShadowView);
*/
registry.erase(tag);
break;
}
case ShadowViewMutation::Insert: {
react_native_assert(mutation.oldChildShadowView == ShadowView{});
auto parentTag = mutation.parentShadowView.tag;
react_native_assert(registry.find(parentTag) != registry.end());
auto parentStubView = registry[parentTag];
auto childTag = mutation.newChildShadowView.tag;
react_native_assert(registry.find(childTag) != registry.end());
auto childStubView = registry[childTag];
react_native_assert(childStubView->parentTag == NO_VIEW_TAG);
childStubView->update(mutation.newChildShadowView);
STUB_VIEW_LOG({
LOG(ERROR) << "StubView: Insert: " << childTag << " into "
<< parentTag << " at " << mutation.index << "("
<< parentStubView->children.size() << " children)";
});
react_native_assert(parentStubView->children.size() >= mutation.index);
childStubView->parentTag = parentTag;
parentStubView->children.insert(
parentStubView->children.begin() + mutation.index, childStubView);
break;
}
case ShadowViewMutation::Remove: {
react_native_assert(mutation.newChildShadowView == ShadowView{});
auto parentTag = mutation.parentShadowView.tag;
react_native_assert(registry.find(parentTag) != registry.end());
auto parentStubView = registry[parentTag];
auto childTag = mutation.oldChildShadowView.tag;
STUB_VIEW_LOG({
LOG(ERROR) << "StubView: Remove: " << childTag << " from "
<< parentTag << " at index " << mutation.index << " with "
<< parentStubView->children.size() << " children";
});
react_native_assert(parentStubView->children.size() > mutation.index);
react_native_assert(registry.find(childTag) != registry.end());
auto childStubView = registry[childTag];
react_native_assert(childStubView->parentTag == parentTag);
STUB_VIEW_LOG({
std::string strChildList = "";
int i = 0;
for (auto const &child : parentStubView->children) {
strChildList.append(std::to_string(i));
strChildList.append(":");
strChildList.append(std::to_string(child->tag));
strChildList.append(", ");
i++;
}
LOG(ERROR) << "StubView: BEFORE REMOVE: Children of " << parentTag
<< ": " << strChildList;
});
react_native_assert(
parentStubView->children.size() > mutation.index &&
parentStubView->children[mutation.index]->tag ==
childStubView->tag);
childStubView->parentTag = NO_VIEW_TAG;
parentStubView->children.erase(
parentStubView->children.begin() + mutation.index);
break;
}
case ShadowViewMutation::Update: {
STUB_VIEW_LOG({
LOG(ERROR) << "StubView: Update: " << mutation.newChildShadowView.tag;
});
react_native_assert(mutation.oldChildShadowView.tag != 0);
react_native_assert(mutation.newChildShadowView.tag != 0);
react_native_assert(mutation.newChildShadowView.props);
react_native_assert(
mutation.newChildShadowView.tag == mutation.oldChildShadowView.tag);
react_native_assert(
registry.find(mutation.newChildShadowView.tag) != registry.end());
auto oldStubView = registry[mutation.newChildShadowView.tag];
react_native_assert(oldStubView->tag != 0);
react_native_assert(
(ShadowView)(*oldStubView) == mutation.oldChildShadowView);
oldStubView->update(mutation.newChildShadowView);
break;
}
}
}
STUB_VIEW_LOG({ LOG(ERROR) << "StubView: Mutating End"; });
// For iOS especially: flush logs because some might be lost on iOS if an
// assert is hit right after this.
google::FlushLogFiles(google::INFO);
}
bool operator==(StubViewTree const &lhs, StubViewTree const &rhs) {
if (lhs.registry.size() != rhs.registry.size()) {
return false;
}
for (auto const &pair : lhs.registry) {
auto &lhsStubView = *lhs.registry.at(pair.first);
auto &rhsStubView = *rhs.registry.at(pair.first);
if (lhsStubView != rhsStubView) {
return false;
}
}
return true;
}
bool operator!=(StubViewTree const &lhs, StubViewTree const &rhs) {
return !(lhs == rhs);
}
} // namespace react
} // namespace facebook
<commit_msg>Format StubViewTree logs to be closer to other logs<commit_after>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "StubViewTree.h"
#include <glog/logging.h>
#include <react/debug/react_native_assert.h>
#ifdef STUB_VIEW_TREE_VERBOSE
#define STUB_VIEW_LOG(code) code
#else
#define STUB_VIEW_LOG(code)
#endif
namespace facebook {
namespace react {
StubViewTree::StubViewTree(ShadowView const &shadowView) {
auto view = std::make_shared<StubView>();
view->update(shadowView);
rootTag = shadowView.tag;
registry[shadowView.tag] = view;
}
StubView const &StubViewTree::getRootStubView() const {
return *registry.at(rootTag);
}
StubView const &StubViewTree::getStubView(Tag tag) const {
return *registry.at(tag);
}
size_t StubViewTree::size() const {
return registry.size();
}
void StubViewTree::mutate(ShadowViewMutationList const &mutations) {
STUB_VIEW_LOG({ LOG(ERROR) << "StubView: Mutating Begin"; });
for (auto const &mutation : mutations) {
switch (mutation.type) {
case ShadowViewMutation::Create: {
react_native_assert(mutation.parentShadowView == ShadowView{});
react_native_assert(mutation.oldChildShadowView == ShadowView{});
react_native_assert(mutation.newChildShadowView.props);
auto stubView = std::make_shared<StubView>();
stubView->update(mutation.newChildShadowView);
auto tag = mutation.newChildShadowView.tag;
STUB_VIEW_LOG({ LOG(ERROR) << "StubView: Create [" << tag << "]"; });
react_native_assert(registry.find(tag) == registry.end());
registry[tag] = stubView;
break;
}
case ShadowViewMutation::Delete: {
STUB_VIEW_LOG({
LOG(ERROR) << "Delete [" << mutation.oldChildShadowView.tag << "]";
});
react_native_assert(mutation.parentShadowView == ShadowView{});
react_native_assert(mutation.newChildShadowView == ShadowView{});
auto tag = mutation.oldChildShadowView.tag;
/* Disable this assert until T76057501 is resolved.
react_native_assert(registry.find(tag) != registry.end());
auto stubView = registry[tag];
react_native_assert(
(ShadowView)(*stubView) == mutation.oldChildShadowView);
*/
registry.erase(tag);
break;
}
case ShadowViewMutation::Insert: {
react_native_assert(mutation.oldChildShadowView == ShadowView{});
auto parentTag = mutation.parentShadowView.tag;
react_native_assert(registry.find(parentTag) != registry.end());
auto parentStubView = registry[parentTag];
auto childTag = mutation.newChildShadowView.tag;
react_native_assert(registry.find(childTag) != registry.end());
auto childStubView = registry[childTag];
react_native_assert(childStubView->parentTag == NO_VIEW_TAG);
childStubView->update(mutation.newChildShadowView);
STUB_VIEW_LOG({
LOG(ERROR) << "StubView: Insert [" << childTag << "] into ["
<< parentTag << "] @" << mutation.index << "("
<< parentStubView->children.size() << " children)";
});
react_native_assert(parentStubView->children.size() >= mutation.index);
childStubView->parentTag = parentTag;
parentStubView->children.insert(
parentStubView->children.begin() + mutation.index, childStubView);
break;
}
case ShadowViewMutation::Remove: {
react_native_assert(mutation.newChildShadowView == ShadowView{});
auto parentTag = mutation.parentShadowView.tag;
react_native_assert(registry.find(parentTag) != registry.end());
auto parentStubView = registry[parentTag];
auto childTag = mutation.oldChildShadowView.tag;
STUB_VIEW_LOG({
LOG(ERROR) << "StubView: Remove [" << childTag << "] from ["
<< parentTag << "] @" << mutation.index << " with "
<< parentStubView->children.size() << " children";
});
react_native_assert(parentStubView->children.size() > mutation.index);
react_native_assert(registry.find(childTag) != registry.end());
auto childStubView = registry[childTag];
react_native_assert(childStubView->parentTag == parentTag);
STUB_VIEW_LOG({
std::string strChildList = "";
int i = 0;
for (auto const &child : parentStubView->children) {
strChildList.append(std::to_string(i));
strChildList.append(":");
strChildList.append(std::to_string(child->tag));
strChildList.append(", ");
i++;
}
LOG(ERROR) << "StubView: BEFORE REMOVE: Children of " << parentTag
<< ": " << strChildList;
});
react_native_assert(
parentStubView->children.size() > mutation.index &&
parentStubView->children[mutation.index]->tag ==
childStubView->tag);
childStubView->parentTag = NO_VIEW_TAG;
parentStubView->children.erase(
parentStubView->children.begin() + mutation.index);
break;
}
case ShadowViewMutation::Update: {
STUB_VIEW_LOG({
LOG(ERROR) << "StubView: Update [" << mutation.newChildShadowView.tag
<< "]";
});
react_native_assert(mutation.oldChildShadowView.tag != 0);
react_native_assert(mutation.newChildShadowView.tag != 0);
react_native_assert(mutation.newChildShadowView.props);
react_native_assert(
mutation.newChildShadowView.tag == mutation.oldChildShadowView.tag);
react_native_assert(
registry.find(mutation.newChildShadowView.tag) != registry.end());
auto oldStubView = registry[mutation.newChildShadowView.tag];
react_native_assert(oldStubView->tag != 0);
react_native_assert(
(ShadowView)(*oldStubView) == mutation.oldChildShadowView);
oldStubView->update(mutation.newChildShadowView);
break;
}
}
}
STUB_VIEW_LOG({ LOG(ERROR) << "StubView: Mutating End"; });
// For iOS especially: flush logs because some might be lost on iOS if an
// assert is hit right after this.
google::FlushLogFiles(google::INFO);
}
bool operator==(StubViewTree const &lhs, StubViewTree const &rhs) {
if (lhs.registry.size() != rhs.registry.size()) {
return false;
}
for (auto const &pair : lhs.registry) {
auto &lhsStubView = *lhs.registry.at(pair.first);
auto &rhsStubView = *rhs.registry.at(pair.first);
if (lhsStubView != rhsStubView) {
return false;
}
}
return true;
}
bool operator!=(StubViewTree const &lhs, StubViewTree const &rhs) {
return !(lhs == rhs);
}
} // namespace react
} // namespace facebook
<|endoftext|>
|
<commit_before>#include "src/camera.h"
#include "src/math.h"
#include "src/timer.h"
#include "src/triangle.h"
#include "src/utils.h"
#include "3rdparty/mdl/mdl.h"
enum MDLDrawModeType
{
HALF_WIREFRAME, // textured screen on one half, wireframe on second half
FULLSCREEN, // fullscreen model
MDLDRAWMODE_CNT
};
enum ShamblerAnimations
{
IDLE = 0,
WALK,
RUN,
ATTACK1,
ATTACK2,
ATTACK3,
THUNDERBOLT,
HIT,
DEAD,
NUM_ANIMS
};
// MDL rendering test
void testMdl()
{
const char *animNames[NUM_ANIMS+1] = { "Idle", "Walk", "Run", "Attack1",
"Attack2", "Attack3", "Thunderbolt",
"Hit", "Dead", "Cycle" };
const int animFrames[NUM_ANIMS][2] = { {0, 16}, {17, 29}, {30, 35},
{36, 47}, {48, 58}, {59, 65},
{66, 74}, {75, 82}, {83, 94} };
const uint16_t *keysPressed;
uint32_t dt, now, last = 0;
int freezeFlipped = 0, drawModeFlipped = 0, animFlipped = 0;
int frameNum = 0, startFrame = 0, endFrame;
int currAnim = NUM_ANIMS;
int drawMode = HALF_WIREFRAME;
int freezeFrame = 0;
int frameTimeSkew = 25;
int mdlAnimated = 0;
float frameLerp = 0.f;
float t = 0.f;
gfx_Camera cam;
mth_Matrix4 modelViewProj;
mth_Matrix4 modelMatrix;
mdl_model_t mdl;
gfx_drawBuffer fullBuffer, halfBuffer;
gfx_drawBuffer wireFrameBuffer;
ALLOC_DRAWBUFFER(fullBuffer, SCREEN_WIDTH, SCREEN_HEIGHT, DB_COLOR | DB_DEPTH);
ASSERT(DRAWBUFFER_VALID(fullBuffer, DB_COLOR | DB_DEPTH), "Out of memory!\n");
ALLOC_DRAWBUFFER(halfBuffer, SCREEN_WIDTH >> 1, SCREEN_HEIGHT, DB_COLOR | DB_DEPTH);
ASSERT(DRAWBUFFER_VALID(halfBuffer, DB_COLOR | DB_DEPTH), "Out of memory!\n");
ALLOC_DRAWBUFFER(wireFrameBuffer, SCREEN_WIDTH >> 1, SCREEN_HEIGHT, DB_COLOR);
ASSERT(DRAWBUFFER_VALID(wireFrameBuffer, DB_COLOR), "Out of memory!\n");
mdl_load("images/shambler.mdl", &mdl);
fullBuffer.drawOpts.depthFunc = DF_LESS;
fullBuffer.drawOpts.cullMode = FC_BACK;
halfBuffer.drawOpts.depthFunc = DF_LESS;
halfBuffer.drawOpts.cullMode = FC_BACK;
wireFrameBuffer.drawOpts.drawMode = DM_WIREFRAME;
wireFrameBuffer.drawOpts.cullMode = FC_BACK;
endFrame = mdl.header.num_frames;
mdlAnimated = mdl.header.num_frames > 1;
// setup 1ms timer interrupt
tmr_start();
// setup camera
VEC4(cam.position, 0, 0, 30);
VEC4(cam.up, 0, 0, -1);
VEC4(cam.right, 0, 1, 0);
VEC4(cam.target, -1, 0, 0);
mth_matIdentity(&modelMatrix);
mth_matPerspective(&cam.projection, 75.f * M_PI /180.f, (float)halfBuffer.width / halfBuffer.height, 0.1f, 500.f);
gfx_setPalette8(mdl.skinTextures[0].palette);
do
{
now = tmr_getMs();
dt = now - last;
keysPressed = kbd_getInput();
t += 0.0005f * dt;
// animate model frames
if(mdlAnimated)
{
frameLerp += 0.0005f * dt * frameTimeSkew;
mdl_animate(startFrame, endFrame-1, &frameNum, &frameLerp);
}
// circular rotation around the model
modelMatrix.m[12] = ROUND(120 * sin(t));
modelMatrix.m[13] = ROUND(120 * cos(t));
cam.target.x = modelMatrix.m[12];
cam.target.y = modelMatrix.m[13];
mth_matView(&cam.view, &cam.position, &cam.target, &cam.up);
modelViewProj = mth_matMul(&cam.view, &cam.projection);
modelViewProj = mth_matMul(&modelMatrix, &modelViewProj);
if(keysPressed[KEY_SPACE] && !drawModeFlipped)
{
drawMode++;
if(drawMode == MDLDRAWMODE_CNT)
drawMode = HALF_WIREFRAME;
if(drawMode == HALF_WIREFRAME)
mth_matPerspective(&cam.projection, 75.f * M_PI /180.f, (float)halfBuffer.width / halfBuffer.height, 0.1f, 500.f);
else
mth_matPerspective(&cam.projection, 75.f * M_PI /180.f, (float)fullBuffer.width / fullBuffer.height, 0.1f, 500.f);
drawModeFlipped = 1;
}
else if(!keysPressed[KEY_SPACE]) drawModeFlipped = 0;
if(keysPressed[KEY_A] && !animFlipped)
{
if(currAnim == NUM_ANIMS)
currAnim = -1;
currAnim++;
if(currAnim != NUM_ANIMS)
{
startFrame = animFrames[currAnim][0];
endFrame = animFrames[currAnim][1];
}
else
{
startFrame = 0;
endFrame = mdl.header.num_frames;
}
frameNum = startFrame;
frameLerp = 0.f;
animFlipped = 1;
}
else if(!keysPressed[KEY_A]) animFlipped = 0;
if(keysPressed[KEY_F] && !freezeFlipped)
{
freezeFrame = !freezeFrame;
freezeFlipped = 1;
}
else if(!keysPressed[KEY_F]) freezeFlipped = 0;
if(keysPressed[KEY_PLUS])
{
frameTimeSkew += frameTimeSkew >= 100 ? 0 : 1;
}
if(keysPressed[KEY_MINUS])
{
frameTimeSkew -= frameTimeSkew <= 1 ? 0 : 1;
}
// clear buffers and render!
if(drawMode == HALF_WIREFRAME)
{
gfx_clrBufferColor(&wireFrameBuffer, 2);
gfx_clrBufferColor(&halfBuffer, 3);
gfx_clrBuffer(&halfBuffer, DB_DEPTH);
if(mdlAnimated)
{
mdl_renderFrameLerp(frameNum, frameLerp, &mdl, &modelViewProj, &halfBuffer);
mdl_renderFrameLerp(frameNum, frameLerp, &mdl, &modelViewProj, &wireFrameBuffer);
}
else
{
mdl_renderFrame(frameNum, &mdl, &modelViewProj, &halfBuffer);
mdl_renderFrame(frameNum, &mdl, &modelViewProj, &wireFrameBuffer);
}
gfx_blitBuffer(0, 0, &halfBuffer, &fullBuffer);
gfx_blitBuffer(SCREEN_WIDTH >> 1, 0, &wireFrameBuffer, &fullBuffer);
}
else
{
gfx_clrBufferColor(&fullBuffer, 3);
gfx_clrBuffer(&fullBuffer, DB_DEPTH);
if(mdlAnimated)
mdl_renderFrameLerp(frameNum, frameLerp, &mdl, &modelViewProj, &fullBuffer);
else
mdl_renderFrame(frameNum, &mdl, &modelViewProj, &fullBuffer);
}
utl_printf(&fullBuffer, 0, 1, 15, 0, "Frame : %03d/%03d @ %dx [+/-]", frameNum+1, mdl.header.num_frames, frameTimeSkew);
utl_printf(&fullBuffer, 0, 10, 15, 0, "[A]nim: %s", animNames[currAnim]);
gfx_updateScreen(&fullBuffer);
gfx_vSync();
last = now;
} while(!keysPressed[KEY_ESC]);
tmr_finish();
mdl_free(&mdl);
FREE_DRAWBUFFER(fullBuffer);
FREE_DRAWBUFFER(halfBuffer);
FREE_DRAWBUFFER(wireFrameBuffer);
}
<commit_msg>togglable MDL rotation<commit_after>#include "src/camera.h"
#include "src/math.h"
#include "src/timer.h"
#include "src/triangle.h"
#include "src/utils.h"
#include "3rdparty/mdl/mdl.h"
enum MDLDrawModeType
{
HALF_WIREFRAME, // textured screen on one half, wireframe on second half
FULLSCREEN, // fullscreen model
MDLDRAWMODE_CNT
};
enum ShamblerAnimations
{
IDLE = 0,
WALK,
RUN,
ATTACK1,
ATTACK2,
ATTACK3,
THUNDERBOLT,
HIT,
DEAD,
NUM_ANIMS
};
// MDL rendering test
void testMdl()
{
const char *animNames[NUM_ANIMS+1] = { "Idle", "Walk", "Run", "Attack1",
"Attack2", "Attack3", "Thunderbolt",
"Hit", "Dead", "Cycle" };
const int animFrames[NUM_ANIMS][2] = { {0, 16}, {17, 29}, {30, 35},
{36, 47}, {48, 58}, {59, 65},
{66, 74}, {75, 82}, {83, 94} };
const int distFromModel = 120;
const uint16_t *keysPressed;
uint32_t dt, now, last = 0;
int freezeFlipped = 0, drawModeFlipped = 0, animFlipped = 0;
int rotating = 1, rotFlipped = 0;
int frameNum = 0, startFrame = 0, endFrame;
int currAnim = NUM_ANIMS;
int drawMode = HALF_WIREFRAME;
int freezeFrame = 0;
int frameTimeSkew = 25;
int mdlAnimated = 0;
float frameLerp = 0.f;
float t = 0.f;
gfx_Camera cam;
mth_Matrix4 modelViewProj;
mth_Matrix4 modelMatrix;
mdl_model_t mdl;
gfx_drawBuffer fullBuffer, halfBuffer;
gfx_drawBuffer wireFrameBuffer;
ALLOC_DRAWBUFFER(fullBuffer, SCREEN_WIDTH, SCREEN_HEIGHT, DB_COLOR | DB_DEPTH);
ASSERT(DRAWBUFFER_VALID(fullBuffer, DB_COLOR | DB_DEPTH), "Out of memory!\n");
ALLOC_DRAWBUFFER(halfBuffer, SCREEN_WIDTH >> 1, SCREEN_HEIGHT, DB_COLOR | DB_DEPTH);
ASSERT(DRAWBUFFER_VALID(halfBuffer, DB_COLOR | DB_DEPTH), "Out of memory!\n");
ALLOC_DRAWBUFFER(wireFrameBuffer, SCREEN_WIDTH >> 1, SCREEN_HEIGHT, DB_COLOR);
ASSERT(DRAWBUFFER_VALID(wireFrameBuffer, DB_COLOR), "Out of memory!\n");
mdl_load("images/shambler.mdl", &mdl);
fullBuffer.drawOpts.depthFunc = DF_LESS;
fullBuffer.drawOpts.cullMode = FC_BACK;
halfBuffer.drawOpts.depthFunc = DF_LESS;
halfBuffer.drawOpts.cullMode = FC_BACK;
wireFrameBuffer.drawOpts.drawMode = DM_WIREFRAME;
wireFrameBuffer.drawOpts.cullMode = FC_BACK;
endFrame = mdl.header.num_frames;
mdlAnimated = mdl.header.num_frames > 1;
// setup 1ms timer interrupt
tmr_start();
// setup camera
VEC4(cam.position, 0, 0, 30);
VEC4(cam.up, 0, 0, -1);
VEC4(cam.right, 0, 1, 0);
VEC4(cam.target, -1, 0, 0);
mth_matIdentity(&modelMatrix);
mth_matPerspective(&cam.projection, 75.f * M_PI /180.f, (float)halfBuffer.width / halfBuffer.height, 0.1f, 500.f);
gfx_setPalette8(mdl.skinTextures[0].palette);
do
{
now = tmr_getMs();
dt = now - last;
keysPressed = kbd_getInput();
t += 0.0005f * dt;
// animate model frames
if(mdlAnimated)
{
frameLerp += 0.0005f * dt * frameTimeSkew;
mdl_animate(startFrame, endFrame-1, &frameNum, &frameLerp);
}
// circular rotation around the model
if(rotating)
{
modelMatrix.m[12] = distFromModel * sin(t);
modelMatrix.m[13] = distFromModel * cos(t);
cam.target.x = modelMatrix.m[12];
cam.target.y = modelMatrix.m[13];
mth_matView(&cam.view, &cam.position, &cam.target, &cam.up);
modelViewProj = mth_matMul(&cam.view, &cam.projection);
modelViewProj = mth_matMul(&modelMatrix, &modelViewProj);
}
if(keysPressed[KEY_SPACE] && !drawModeFlipped)
{
drawMode++;
if(drawMode == MDLDRAWMODE_CNT)
drawMode = HALF_WIREFRAME;
if(drawMode == HALF_WIREFRAME)
mth_matPerspective(&cam.projection, 75.f * M_PI /180.f, (float)halfBuffer.width / halfBuffer.height, 0.1f, 500.f);
else
mth_matPerspective(&cam.projection, 75.f * M_PI /180.f, (float)fullBuffer.width / fullBuffer.height, 0.1f, 500.f);
modelViewProj = mth_matMul(&cam.view, &cam.projection);
drawModeFlipped = 1;
}
else if(!keysPressed[KEY_SPACE]) drawModeFlipped = 0;
if(keysPressed[KEY_A] && !animFlipped)
{
if(currAnim == NUM_ANIMS)
currAnim = -1;
currAnim++;
if(currAnim != NUM_ANIMS)
{
startFrame = animFrames[currAnim][0];
endFrame = animFrames[currAnim][1];
}
else
{
startFrame = 0;
endFrame = mdl.header.num_frames;
}
frameNum = startFrame;
frameLerp = 0.f;
animFlipped = 1;
}
else if(!keysPressed[KEY_A]) animFlipped = 0;
if(keysPressed[KEY_F] && !freezeFlipped)
{
freezeFrame = !freezeFrame;
freezeFlipped = 1;
}
else if(!keysPressed[KEY_F]) freezeFlipped = 0;
if(keysPressed[KEY_R] && !rotFlipped)
{
rotating = !rotating;
if(!rotating)
{
mth_matIdentity(&modelMatrix);
VEC4(cam.position, distFromModel, 0, 30);
VEC4(cam.target, -1, 0, 0);
mth_matView(&cam.view, &cam.position, &cam.target, &cam.up);
modelViewProj = mth_matMul(&cam.view, &cam.projection);
}
else
{
t = 0.f;
VEC4(cam.position, 0, 0, 30);
}
rotFlipped = 1;
}
else if(!keysPressed[KEY_R]) rotFlipped = 0;
if(keysPressed[KEY_PLUS])
{
frameTimeSkew += frameTimeSkew >= 100 ? 0 : 1;
}
if(keysPressed[KEY_MINUS])
{
frameTimeSkew -= frameTimeSkew <= 1 ? 0 : 1;
}
// clear buffers and render!
if(drawMode == HALF_WIREFRAME)
{
gfx_clrBufferColor(&wireFrameBuffer, 2);
gfx_clrBufferColor(&halfBuffer, 3);
gfx_clrBuffer(&halfBuffer, DB_DEPTH);
if(mdlAnimated)
{
mdl_renderFrameLerp(frameNum, frameLerp, &mdl, &modelViewProj, &halfBuffer);
mdl_renderFrameLerp(frameNum, frameLerp, &mdl, &modelViewProj, &wireFrameBuffer);
}
else
{
mdl_renderFrame(frameNum, &mdl, &modelViewProj, &halfBuffer);
mdl_renderFrame(frameNum, &mdl, &modelViewProj, &wireFrameBuffer);
}
gfx_blitBuffer(0, 0, &halfBuffer, &fullBuffer);
gfx_blitBuffer(SCREEN_WIDTH >> 1, 0, &wireFrameBuffer, &fullBuffer);
}
else
{
gfx_clrBufferColor(&fullBuffer, 3);
gfx_clrBuffer(&fullBuffer, DB_DEPTH);
if(mdlAnimated)
mdl_renderFrameLerp(frameNum, frameLerp, &mdl, &modelViewProj, &fullBuffer);
else
mdl_renderFrame(frameNum, &mdl, &modelViewProj, &fullBuffer);
}
utl_printf(&fullBuffer, 0, 1, 15, 0, "Frame : %03d/%03d @ %dx [+/-]", frameNum+1, mdl.header.num_frames, frameTimeSkew);
utl_printf(&fullBuffer, 0, 10, 15, 0, "[A]nim: %s", animNames[currAnim]);
gfx_updateScreen(&fullBuffer);
gfx_vSync();
last = now;
} while(!keysPressed[KEY_ESC]);
tmr_finish();
mdl_free(&mdl);
FREE_DRAWBUFFER(fullBuffer);
FREE_DRAWBUFFER(halfBuffer);
FREE_DRAWBUFFER(wireFrameBuffer);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// @file
// Content script manager implementation.
#include "ceee/ie/plugin/scripting/content_script_manager.h"
#include "ceee/ie/common/ceee_module_util.h"
#include "ceee/ie/plugin/bho/dom_utils.h"
#include "ceee/ie/plugin/bho/frame_event_handler.h"
#include "ceee/ie/plugin/scripting/content_script_native_api.h"
#include "base/logging.h"
#include "base/resource_util.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "ceee/common/com_utils.h"
#include "toolband.h" // NOLINT
namespace {
// The list of bootstrap scripts we need to parse in a new scripting engine.
// We store our content scripts by name, in RT_HTML resources. This allows
// referring them by res: URLs, which makes debugging easier.
struct BootstrapScript {
const wchar_t* name;
// A named function to be called after the script is executed.
const wchar_t* function_name;
std::wstring url;
std::wstring content;
};
BootstrapScript bootstrap_scripts[] = {
{ L"base.js", NULL },
{ L"json.js", NULL },
{ L"ceee_bootstrap.js", L"ceee.startInit_" },
{ L"event_bindings.js", NULL },
{ L"renderer_extension_bindings.js", L"ceee.endInit_" }
};
bool bootstrap_scripts_loaded = false;
// Load the bootstrap javascript resources to our cache.
bool EnsureBoostrapScriptsLoaded() {
if (bootstrap_scripts_loaded)
return true;
ceee_module_util::AutoLock lock;
if (bootstrap_scripts_loaded)
return true;
HMODULE module = _AtlBaseModule.GetResourceInstance();
// And construct the base URL.
std::wstring base_url(L"ceee-content://bootstrap/");
// Retrieve the resources one by one and convert them to Unicode.
for (int i = 0; i < arraysize(bootstrap_scripts); ++i) {
const wchar_t* name = bootstrap_scripts[i].name;
HRSRC hres_info = ::FindResource(module, name, MAKEINTRESOURCE(RT_HTML));
if (hres_info == NULL)
return false;
DWORD data_size = ::SizeofResource(module, hres_info);
HGLOBAL hres = ::LoadResource(module, hres_info);
if (!hres)
return false;
void* resource = ::LockResource(hres);
if (!resource)
return false;
bool converted = UTF8ToWide(reinterpret_cast<const char*>(resource),
data_size,
&bootstrap_scripts[i].content);
if (!converted)
return false;
bootstrap_scripts[i].url = StringPrintf(L"%ls%ls", base_url.c_str(), name);
}
bootstrap_scripts_loaded = true;
return true;
}
HRESULT InvokeNamedFunction(IScriptHost* script_host,
const wchar_t* function_name,
VARIANT* args,
size_t num_args) {
// Get the named function.
CComVariant function_var;
HRESULT hr = script_host->RunExpression(function_name, &function_var);
if (FAILED(hr))
return hr;
// And invoke it with the the params.
if (V_VT(&function_var) != VT_DISPATCH)
return E_UNEXPECTED;
// Take over the IDispatch pointer.
CComDispatchDriver function_disp;
function_disp.Attach(V_DISPATCH(&function_var));
V_VT(&function_var) = VT_EMPTY;
V_DISPATCH(&function_var) = NULL;
return function_disp.InvokeN(static_cast<DISPID>(DISPID_VALUE),
args,
num_args);
}
} // namespace
ContentScriptManager::ContentScriptManager() : require_all_frames_(false) {
}
ContentScriptManager::~ContentScriptManager() {
// TODO(siggi@chromium.org): This mandates teardown prior to
// deletion, is that necessary?
DCHECK(script_host_ == NULL);
}
HRESULT ContentScriptManager::GetOrCreateScriptHost(
IHTMLDocument2* document, IScriptHost** host) {
if (script_host_ == NULL) {
HRESULT hr = CreateScriptHost(&script_host_);
if (FAILED(hr)) {
LOG(ERROR) << "Failed to create script host " << com::LogHr(hr);
return hr;
}
hr = InitializeScriptHost(document, script_host_);
if (FAILED(hr)) {
LOG(ERROR) << "Failed to initialize script host " << com::LogHr(hr);
script_host_.Release();
return hr;
}
CComQIPtr<IObjectWithSite> script_host_with_site(script_host_);
// Our implementation of script host must always implement IObjectWithSite.
DCHECK(script_host_with_site != NULL);
hr = script_host_with_site->SetSite(document);
DCHECK(SUCCEEDED(hr));
}
DCHECK(script_host_ != NULL);
return script_host_.CopyTo(host);
}
HRESULT ContentScriptManager::CreateScriptHost(IScriptHost** script_host) {
return ScriptHost::CreateInitializedIID(IID_IScriptHost, script_host);
}
HRESULT ContentScriptManager::InitializeScriptHost(
IHTMLDocument2* document, IScriptHost* script_host) {
DCHECK(document != NULL);
DCHECK(script_host != NULL);
CComPtr<IExtensionPortMessagingProvider> messaging_provider;
HRESULT hr = host_->GetExtensionPortMessagingProvider(&messaging_provider);
if (FAILED(hr))
return hr;
hr = ContentScriptNativeApi::CreateInitialized(messaging_provider,
&native_api_);
if (FAILED(hr))
return hr;
std::wstring extension_id;
host_->GetExtensionId(&extension_id);
DCHECK(extension_id.size()) <<
"Need to revisit async loading of enabled extension list.";
// Execute the bootstrap scripts.
hr = BootstrapScriptHost(script_host, native_api_, extension_id.c_str());
if (FAILED(hr))
return hr;
// Register the window object and initialize the global namespace of the
// script host.
CComPtr<IHTMLWindow2> window;
hr = document->get_parentWindow(&window);
if (FAILED(hr))
return hr;
hr = script_host->RegisterScriptObject(L"unsafeWindow", window, false);
if (FAILED(hr))
return hr;
hr = InvokeNamedFunction(script_host, L"ceee.initGlobals_", NULL, 0);
return hr;
}
HRESULT ContentScriptManager::BootstrapScriptHost(IScriptHost* script_host,
IDispatch* native_api,
const wchar_t* extension_id) {
bool loaded = EnsureBoostrapScriptsLoaded();
if (!loaded) {
NOTREACHED() << "Unable to load bootstrap scripts";
return E_UNEXPECTED;
}
// Note args go in reverse order.
CComVariant args[] = {
extension_id,
native_api
};
// Run the bootstrap scripts.
for (int i = 0; i < arraysize(bootstrap_scripts); ++i) {
const wchar_t* url = bootstrap_scripts[i].url.c_str();
HRESULT hr = script_host->RunScript(url,
bootstrap_scripts[i].content.c_str());
if (FAILED(hr)) {
NOTREACHED() << "Bootstrap script \"" << url << "\" failed to load";
return hr;
}
// Execute the script's named function if it exists.
const wchar_t* function_name = bootstrap_scripts[i].function_name;
if (function_name) {
hr = InvokeNamedFunction(script_host, function_name, args,
arraysize(args));
if (FAILED(hr)) {
NOTREACHED() << "Named function \"" << function_name << "\" not called";
return hr;
}
}
}
return S_OK;
}
HRESULT ContentScriptManager::LoadCss(const GURL& match_url,
IHTMLDocument2* document) {
// Get the CSS content for all matching user scripts and inject it.
std::string css_content;
HRESULT hr = host_->GetMatchingUserScriptsCssContent(match_url,
require_all_frames_,
&css_content);
if (FAILED(hr)) {
LOG(ERROR) << "Failed to get script content " << com::LogHr(hr);
return hr;
}
if (!css_content.empty())
return InsertCss(CA2W(css_content.c_str()), document);
return S_OK;
}
HRESULT ContentScriptManager::LoadStartScripts(const GURL& match_url,
IHTMLDocument2* document) {
// Run the document start scripts.
return LoadScriptsImpl(match_url, document, UserScript::DOCUMENT_START);
}
HRESULT ContentScriptManager::LoadEndScripts(const GURL& match_url,
IHTMLDocument2* document) {
// Run the document end scripts.
return LoadScriptsImpl(match_url, document, UserScript::DOCUMENT_END);
}
HRESULT ContentScriptManager::LoadScriptsImpl(const GURL& match_url,
IHTMLDocument2* document,
UserScript::RunLocation when) {
// Run the document start scripts.
UserScriptsLibrarian::JsFileList js_file_list;
HRESULT hr = host_->GetMatchingUserScriptsJsContent(match_url,
when,
require_all_frames_,
&js_file_list);
if (FAILED(hr)) {
LOG(ERROR) << "Failed to get script content " << com::LogHr(hr);
return hr;
}
// Early out to avoid initializing scripting if we don't need it.
if (js_file_list.size() == 0)
return S_OK;
for (size_t i = 0; i < js_file_list.size(); ++i) {
hr = ExecuteScript(CA2W(js_file_list[i].content.c_str()),
js_file_list[i].file_path.c_str(),
document);
if (FAILED(hr)) {
LOG(ERROR) << "Failed to inject JS content into page " << com::LogHr(hr);
return hr;
}
}
return S_OK;
}
HRESULT ContentScriptManager::ExecuteScript(const wchar_t* code,
const wchar_t* file_path,
IHTMLDocument2* document) {
CComPtr<IScriptHost> script_host;
HRESULT hr = GetOrCreateScriptHost(document, &script_host);
if (FAILED(hr)) {
LOG(ERROR) << "Failed to retrieve script host " << com::LogHr(hr);
return hr;
}
hr = script_host->RunScript(file_path, code);
if (FAILED(hr)) {
if (hr == OLESCRIPT_E_SYNTAX) {
// This function is used to execute scripts from extensions. We log
// syntax and runtime errors but we don't return a failing HR as we are
// executing third party code. A syntax or runtime error already causes
// the script host to prompt the user to debug.
LOG(ERROR) << "A syntax or runtime error occured while executing " <<
"script " << com::LogHr(hr);
} else {
LOG(ERROR) << "Failed to execute script " << com::LogHr(hr);
return hr;
}
}
return S_OK;
}
HRESULT ContentScriptManager::InsertCss(const wchar_t* code,
IHTMLDocument2* document) {
CComPtr<IHTMLDOMNode> head_node;
HRESULT hr = GetHeadNode(document, &head_node);
if (FAILED(hr)) {
LOG(ERROR) << "Failed to retrieve document head node " << com::LogHr(hr);
return hr;
}
hr = InjectStyleTag(document, head_node, code);
if (FAILED(hr)) {
LOG(ERROR) << "Failed to inject CSS content into page "
<< com::LogHr(hr);
return hr;
}
return S_OK;
}
HRESULT ContentScriptManager::GetHeadNode(IHTMLDocument* document,
IHTMLDOMNode** dom_head) {
return DomUtils::GetHeadNode(document, dom_head);
}
HRESULT ContentScriptManager::InjectStyleTag(IHTMLDocument2* document,
IHTMLDOMNode* head_node,
const wchar_t* code) {
return DomUtils::InjectStyleTag(document, head_node, code);
}
HRESULT ContentScriptManager::Initialize(IFrameEventHandlerHost* host,
bool require_all_frames) {
DCHECK(host != NULL);
DCHECK(host_ == NULL);
host_ = host;
require_all_frames_ = require_all_frames;
return S_OK;
}
HRESULT ContentScriptManager::TearDown() {
if (native_api_ != NULL) {
CComPtr<ICeeeContentScriptNativeApi> native_api;
native_api_.QueryInterface(&native_api);
if (native_api != NULL) {
ContentScriptNativeApi* implementation =
static_cast<ContentScriptNativeApi*>(native_api.p);
// Teardown will release references from ContentScriptNativeApi to
// objects blocking release of BHO. Somehow ContentScriptNativeApi is
// alive after IScriptHost::Close().
implementation->TearDown();
}
native_api_.Release();
}
HRESULT hr = S_OK;
if (script_host_ != NULL) {
hr = script_host_->Close();
LOG_IF(ERROR, FAILED(hr)) << "ScriptHost::Close failed " << com::LogHr(hr);
CComQIPtr<IObjectWithSite> script_host_with_site(script_host_);
DCHECK(script_host_with_site != NULL);
hr = script_host_with_site->SetSite(NULL);
DCHECK(SUCCEEDED(hr));
}
// TODO(siggi@chromium.org): Kill off open extension ports.
script_host_.Release();
return hr;
}
<commit_msg>IE CEEE: Release native_api_ in ContentScriptManager when script host initialization fails. BUG=none TEST=none<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// @file
// Content script manager implementation.
#include "ceee/ie/plugin/scripting/content_script_manager.h"
#include "ceee/ie/common/ceee_module_util.h"
#include "ceee/ie/plugin/bho/dom_utils.h"
#include "ceee/ie/plugin/bho/frame_event_handler.h"
#include "ceee/ie/plugin/scripting/content_script_native_api.h"
#include "base/logging.h"
#include "base/resource_util.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "ceee/common/com_utils.h"
#include "toolband.h" // NOLINT
namespace {
// The list of bootstrap scripts we need to parse in a new scripting engine.
// We store our content scripts by name, in RT_HTML resources. This allows
// referring them by res: URLs, which makes debugging easier.
struct BootstrapScript {
const wchar_t* name;
// A named function to be called after the script is executed.
const wchar_t* function_name;
std::wstring url;
std::wstring content;
};
BootstrapScript bootstrap_scripts[] = {
{ L"base.js", NULL },
{ L"json.js", NULL },
{ L"ceee_bootstrap.js", L"ceee.startInit_" },
{ L"event_bindings.js", NULL },
{ L"renderer_extension_bindings.js", L"ceee.endInit_" }
};
bool bootstrap_scripts_loaded = false;
// Load the bootstrap javascript resources to our cache.
bool EnsureBoostrapScriptsLoaded() {
if (bootstrap_scripts_loaded)
return true;
ceee_module_util::AutoLock lock;
if (bootstrap_scripts_loaded)
return true;
HMODULE module = _AtlBaseModule.GetResourceInstance();
// And construct the base URL.
std::wstring base_url(L"ceee-content://bootstrap/");
// Retrieve the resources one by one and convert them to Unicode.
for (int i = 0; i < arraysize(bootstrap_scripts); ++i) {
const wchar_t* name = bootstrap_scripts[i].name;
HRSRC hres_info = ::FindResource(module, name, MAKEINTRESOURCE(RT_HTML));
if (hres_info == NULL)
return false;
DWORD data_size = ::SizeofResource(module, hres_info);
HGLOBAL hres = ::LoadResource(module, hres_info);
if (!hres)
return false;
void* resource = ::LockResource(hres);
if (!resource)
return false;
bool converted = UTF8ToWide(reinterpret_cast<const char*>(resource),
data_size,
&bootstrap_scripts[i].content);
if (!converted)
return false;
bootstrap_scripts[i].url = StringPrintf(L"%ls%ls", base_url.c_str(), name);
}
bootstrap_scripts_loaded = true;
return true;
}
HRESULT InvokeNamedFunction(IScriptHost* script_host,
const wchar_t* function_name,
VARIANT* args,
size_t num_args) {
// Get the named function.
CComVariant function_var;
HRESULT hr = script_host->RunExpression(function_name, &function_var);
if (FAILED(hr))
return hr;
// And invoke it with the the params.
if (V_VT(&function_var) != VT_DISPATCH)
return E_UNEXPECTED;
// Take over the IDispatch pointer.
CComDispatchDriver function_disp;
function_disp.Attach(V_DISPATCH(&function_var));
V_VT(&function_var) = VT_EMPTY;
V_DISPATCH(&function_var) = NULL;
return function_disp.InvokeN(static_cast<DISPID>(DISPID_VALUE),
args,
num_args);
}
} // namespace
ContentScriptManager::ContentScriptManager() : require_all_frames_(false) {
}
ContentScriptManager::~ContentScriptManager() {
// TODO(siggi@chromium.org): This mandates teardown prior to
// deletion, is that necessary?
DCHECK(script_host_ == NULL);
}
HRESULT ContentScriptManager::GetOrCreateScriptHost(
IHTMLDocument2* document, IScriptHost** host) {
if (script_host_ == NULL) {
HRESULT hr = CreateScriptHost(&script_host_);
if (FAILED(hr)) {
LOG(ERROR) << "Failed to create script host " << com::LogHr(hr);
return hr;
}
hr = InitializeScriptHost(document, script_host_);
if (FAILED(hr)) {
LOG(ERROR) << "Failed to initialize script host " << com::LogHr(hr);
script_host_.Release();
native_api_.Release();
return hr;
}
CComQIPtr<IObjectWithSite> script_host_with_site(script_host_);
// Our implementation of script host must always implement IObjectWithSite.
DCHECK(script_host_with_site != NULL);
hr = script_host_with_site->SetSite(document);
DCHECK(SUCCEEDED(hr));
}
DCHECK(script_host_ != NULL);
return script_host_.CopyTo(host);
}
HRESULT ContentScriptManager::CreateScriptHost(IScriptHost** script_host) {
return ScriptHost::CreateInitializedIID(IID_IScriptHost, script_host);
}
HRESULT ContentScriptManager::InitializeScriptHost(
IHTMLDocument2* document, IScriptHost* script_host) {
DCHECK(document != NULL);
DCHECK(script_host != NULL);
CComPtr<IExtensionPortMessagingProvider> messaging_provider;
HRESULT hr = host_->GetExtensionPortMessagingProvider(&messaging_provider);
if (FAILED(hr))
return hr;
hr = ContentScriptNativeApi::CreateInitialized(messaging_provider,
&native_api_);
if (FAILED(hr))
return hr;
std::wstring extension_id;
host_->GetExtensionId(&extension_id);
DCHECK(extension_id.size()) <<
"Need to revisit async loading of enabled extension list.";
// Execute the bootstrap scripts.
hr = BootstrapScriptHost(script_host, native_api_, extension_id.c_str());
if (FAILED(hr))
return hr;
// Register the window object and initialize the global namespace of the
// script host.
CComPtr<IHTMLWindow2> window;
hr = document->get_parentWindow(&window);
if (FAILED(hr))
return hr;
hr = script_host->RegisterScriptObject(L"unsafeWindow", window, false);
if (FAILED(hr))
return hr;
hr = InvokeNamedFunction(script_host, L"ceee.initGlobals_", NULL, 0);
return hr;
}
HRESULT ContentScriptManager::BootstrapScriptHost(IScriptHost* script_host,
IDispatch* native_api,
const wchar_t* extension_id) {
bool loaded = EnsureBoostrapScriptsLoaded();
if (!loaded) {
NOTREACHED() << "Unable to load bootstrap scripts";
return E_UNEXPECTED;
}
// Note args go in reverse order.
CComVariant args[] = {
extension_id,
native_api
};
// Run the bootstrap scripts.
for (int i = 0; i < arraysize(bootstrap_scripts); ++i) {
const wchar_t* url = bootstrap_scripts[i].url.c_str();
HRESULT hr = script_host->RunScript(url,
bootstrap_scripts[i].content.c_str());
if (FAILED(hr)) {
NOTREACHED() << "Bootstrap script \"" << url << "\" failed to load";
return hr;
}
// Execute the script's named function if it exists.
const wchar_t* function_name = bootstrap_scripts[i].function_name;
if (function_name) {
hr = InvokeNamedFunction(script_host, function_name, args,
arraysize(args));
if (FAILED(hr)) {
NOTREACHED() << "Named function \"" << function_name << "\" not called";
return hr;
}
}
}
return S_OK;
}
HRESULT ContentScriptManager::LoadCss(const GURL& match_url,
IHTMLDocument2* document) {
// Get the CSS content for all matching user scripts and inject it.
std::string css_content;
HRESULT hr = host_->GetMatchingUserScriptsCssContent(match_url,
require_all_frames_,
&css_content);
if (FAILED(hr)) {
LOG(ERROR) << "Failed to get script content " << com::LogHr(hr);
return hr;
}
if (!css_content.empty())
return InsertCss(CA2W(css_content.c_str()), document);
return S_OK;
}
HRESULT ContentScriptManager::LoadStartScripts(const GURL& match_url,
IHTMLDocument2* document) {
// Run the document start scripts.
return LoadScriptsImpl(match_url, document, UserScript::DOCUMENT_START);
}
HRESULT ContentScriptManager::LoadEndScripts(const GURL& match_url,
IHTMLDocument2* document) {
// Run the document end scripts.
return LoadScriptsImpl(match_url, document, UserScript::DOCUMENT_END);
}
HRESULT ContentScriptManager::LoadScriptsImpl(const GURL& match_url,
IHTMLDocument2* document,
UserScript::RunLocation when) {
// Run the document start scripts.
UserScriptsLibrarian::JsFileList js_file_list;
HRESULT hr = host_->GetMatchingUserScriptsJsContent(match_url,
when,
require_all_frames_,
&js_file_list);
if (FAILED(hr)) {
LOG(ERROR) << "Failed to get script content " << com::LogHr(hr);
return hr;
}
// Early out to avoid initializing scripting if we don't need it.
if (js_file_list.size() == 0)
return S_OK;
for (size_t i = 0; i < js_file_list.size(); ++i) {
hr = ExecuteScript(CA2W(js_file_list[i].content.c_str()),
js_file_list[i].file_path.c_str(),
document);
if (FAILED(hr)) {
LOG(ERROR) << "Failed to inject JS content into page " << com::LogHr(hr);
return hr;
}
}
return S_OK;
}
HRESULT ContentScriptManager::ExecuteScript(const wchar_t* code,
const wchar_t* file_path,
IHTMLDocument2* document) {
CComPtr<IScriptHost> script_host;
HRESULT hr = GetOrCreateScriptHost(document, &script_host);
if (FAILED(hr)) {
LOG(ERROR) << "Failed to retrieve script host " << com::LogHr(hr);
return hr;
}
hr = script_host->RunScript(file_path, code);
if (FAILED(hr)) {
if (hr == OLESCRIPT_E_SYNTAX) {
// This function is used to execute scripts from extensions. We log
// syntax and runtime errors but we don't return a failing HR as we are
// executing third party code. A syntax or runtime error already causes
// the script host to prompt the user to debug.
LOG(ERROR) << "A syntax or runtime error occured while executing " <<
"script " << com::LogHr(hr);
} else {
LOG(ERROR) << "Failed to execute script " << com::LogHr(hr);
return hr;
}
}
return S_OK;
}
HRESULT ContentScriptManager::InsertCss(const wchar_t* code,
IHTMLDocument2* document) {
CComPtr<IHTMLDOMNode> head_node;
HRESULT hr = GetHeadNode(document, &head_node);
if (FAILED(hr)) {
LOG(ERROR) << "Failed to retrieve document head node " << com::LogHr(hr);
return hr;
}
hr = InjectStyleTag(document, head_node, code);
if (FAILED(hr)) {
LOG(ERROR) << "Failed to inject CSS content into page "
<< com::LogHr(hr);
return hr;
}
return S_OK;
}
HRESULT ContentScriptManager::GetHeadNode(IHTMLDocument* document,
IHTMLDOMNode** dom_head) {
return DomUtils::GetHeadNode(document, dom_head);
}
HRESULT ContentScriptManager::InjectStyleTag(IHTMLDocument2* document,
IHTMLDOMNode* head_node,
const wchar_t* code) {
return DomUtils::InjectStyleTag(document, head_node, code);
}
HRESULT ContentScriptManager::Initialize(IFrameEventHandlerHost* host,
bool require_all_frames) {
DCHECK(host != NULL);
DCHECK(host_ == NULL);
host_ = host;
require_all_frames_ = require_all_frames;
return S_OK;
}
HRESULT ContentScriptManager::TearDown() {
if (native_api_ != NULL) {
CComPtr<ICeeeContentScriptNativeApi> native_api;
native_api_.QueryInterface(&native_api);
if (native_api != NULL) {
ContentScriptNativeApi* implementation =
static_cast<ContentScriptNativeApi*>(native_api.p);
// Teardown will release references from ContentScriptNativeApi to
// objects blocking release of BHO. Somehow ContentScriptNativeApi is
// alive after IScriptHost::Close().
implementation->TearDown();
}
native_api_.Release();
}
HRESULT hr = S_OK;
if (script_host_ != NULL) {
hr = script_host_->Close();
LOG_IF(ERROR, FAILED(hr)) << "ScriptHost::Close failed " << com::LogHr(hr);
CComQIPtr<IObjectWithSite> script_host_with_site(script_host_);
DCHECK(script_host_with_site != NULL);
hr = script_host_with_site->SetSite(NULL);
DCHECK(SUCCEEDED(hr));
}
// TODO(siggi@chromium.org): Kill off open extension ports.
script_host_.Release();
return hr;
}
<|endoftext|>
|
<commit_before>#include "ManagedHeap.hpp"
#ifdef ___INANITY_TRACE_HEAP
#include "CriticalCode.hpp"
#endif
#include <map>
#include <iostream>
#include <algorithm>
BEGIN_INANITY
#ifdef ___INANITY_TRACE_PTR
/// Выключить трассировку указателей?
/** Она очень замедляет работу в debug. */
static const bool disableTracePtr = true;
#endif
ManagedHeap managedHeap;
#ifdef ___INANITY_TRACE_HEAP
ManagedHeap::AllocationInfo::AllocationInfo(size_t number, size_t size) : number(number), size(size)
{
}
#endif
ManagedHeap::ManagedHeap()
#ifdef ___INANITY_TRACE_HEAP
: totalAllocationsCount(0), totalAllocationsSize(0)
#endif
{
#ifdef ___INANITY_WINDOWS
// создать кучу (растущую, с нулевым начальным размером)
heap = HeapCreate(0, 0, 0);
if(!heap)
exit(1);
// сделать кучу low-fragmentation
ULONG heapFragValue = 2;
// обработка ошибок не производится, чтобы работало на не-XP и не-Vista
HeapSetInformation(heap, HeapCompatibilityInformation, &heapFragValue, sizeof(heapFragValue));
#endif // ___INANITY_WINDOWS
}
ManagedHeap::~ManagedHeap()
{
#ifdef ___INANITY_WINDOWS
//удалить кучу
HeapDestroy(heap);
#endif
#ifdef ___INANITY_TRACE_HEAP
//выдать отчет по памяти
std::cout << "======= INANITY MANAGED HEAP REPORT =======\n";
std::cout << "Allocations count: " << totalAllocationsCount << "\nAllocations size: " << totalAllocationsSize << "\n";
if(allocations.size())
{
#ifdef ___INANITY_WINDOWS
Beep(750, 300);
#endif
std::cout << "ATTENTION! SOME LEAKS DETECTED!\n";
PrintAllocations(std::cout);
}
else
std::cout << "NO LEAKS DETECTED\n";
#ifdef ___INANITY_TRACE_PTR
std::cout << "======= PTR REPORT =======\n";
if(disableTracePtr)
std::cout << "TRACE PTR DISABLED\n";
else
PrintPtrs(std::cout);
#endif
std::cout << "======= END REPORT =======\n";
#endif
}
void* ManagedHeap::Allocate(size_t size)
{
#ifdef ___INANITY_WINDOWS
void* data = HeapAlloc(heap, 0, size);
if(!data)
ExitProcess(1);
#else
void* data = malloc(size);
#endif
#ifdef ___INANITY_TRACE_HEAP
{
CriticalCode code(criticalSection);
allocations.insert(std::make_pair(data, AllocationInfo(totalAllocationsCount++, size)));
totalAllocationsSize += size;
}
#endif
return data;
}
void ManagedHeap::Free(void *data)
{
// освободить память
#ifdef ___INANITY_WINDOWS
if(!HeapFree(heap, 0, data))
ExitProcess(1);
#else
free(data);
#endif
// отметить, что память удалена
#ifdef ___INANITY_TRACE_HEAP
{
CriticalCode code(criticalSection);
Allocations::iterator i = allocations.find(data);
if(i == allocations.end())
DebugBreak();
allocations.erase(i);
}
#endif
}
#ifdef ___INANITY_TRACE_HEAP
void ManagedHeap::PrintAllocations(std::ostream& stream)
{
CriticalCode code(criticalSection);
for(Allocations::const_iterator i = allocations.begin(); i != allocations.end(); ++i)
{
stream << i->first << " : #" << i->second.number << ", " << i->second.size << " bytes\n";
if(i->second.info)
stream << " " << i->second.info << "\n";
}
}
void ManagedHeap::SetAllocationInfo(void* data, const char* info)
{
CriticalCode code(criticalSection);
Allocations::iterator i = allocations.find(data);
if(i != allocations.end())
i->second.info = info;
}
void ManagedHeapSetAllocationInfo(void* data, const char* info)
{
managedHeap.SetAllocationInfo(data, info);
}
#ifdef ___INANITY_TRACE_PTR
class ManagedHeap::PtrTracer
{
struct Object
{
void* data;
size_t size;
const char* info;
Object(void* data, size_t size, const char* info) : data(data), size(size), info(info) {}
};
struct Sorter
{
bool operator()(const Object& a, const Object& b) const
{
return a.data < b.data;
}
bool operator()(void* a, const Object& b) const
{
return a < b.data;
}
bool operator()(const Object& a, void* b) const
{
return a.data < b;
}
} sorter;
typedef std::vector<Object> Objects;
Objects objects;
typedef std::multimap<Objects::const_iterator, Objects::const_iterator> Links;
Links links;
public:
PtrTracer(const ManagedHeap& heap)
{
// сформировать список объектов
objects.reserve(heap.allocations.size());
for(Allocations::const_iterator i = heap.allocations.begin(); i != heap.allocations.end(); ++i)
objects.push_back(Object(i->first, i->second.size, i->second.info));
std::sort(objects.begin(), objects.end(), sorter);
// сформировать карту ссылок
for(Ptrs::const_iterator i = heap.ptrs.begin(); i != heap.ptrs.end(); ++i)
{
// найти объект, в котором содержится указатель
Objects::const_iterator j = std::upper_bound(objects.begin(), objects.end(), i->first, sorter);
if(j > objects.begin())
{
--j;
if((size_t)((char*)i->first - (char*)j->data) < j->size)
// да, указатель содержится в этом объекте
// получить объект, на который указывает указатель, и добавить ссылку
links.insert(std::make_pair(j, std::lower_bound(objects.begin(), objects.end(), i->second, sorter)));
}
}
}
void Print(std::ostream& stream, Objects::const_iterator object, bool last = false)
{
static std::vector<bool> levels;
for(size_t i = 0; i < levels.size(); ++i)
if(i == levels.size() - 1)
stream << "|_";
else if(levels[i])
stream << "| ";
else
stream << " ";
stream << object->data << ", " << object->info << "\n";
if(last)
levels[levels.size() - 1] = false;
Links::const_iterator link = links.lower_bound(object);
Links::const_iterator endLink = links.upper_bound(object);
if(link != endLink)
{
levels.push_back(true);
Links::const_iterator nextLink;
for(; link != links.end() && link->first == object; link = nextLink)
{
nextLink = link;
++nextLink;
Print(stream, link->second, nextLink == links.end() || nextLink->first != object);
}
levels.pop_back();
}
}
void Print(std::ostream& stream)
{
std::vector<Objects::const_iterator> referencedObjects;
referencedObjects.reserve(links.size());
for(Links::const_iterator i = links.begin(); i != links.end(); ++i)
referencedObjects.push_back(i->second);
std::sort(referencedObjects.begin(), referencedObjects.end());
referencedObjects.resize(std::unique(referencedObjects.begin(), referencedObjects.end()) - referencedObjects.begin());
// пока просто вывести
for(Objects::const_iterator object = objects.begin(); object != objects.end(); ++object)
{
if(std::binary_search(referencedObjects.begin(), referencedObjects.end(), object))
continue;
Print(stream, object);
}
}
};
void ManagedHeap::PrintPtrs(std::ostream& stream)
{
CriticalCode code(criticalSection);
PtrTracer tracer(*this);
tracer.Print(stream);
}
void ManagedHeap::TracePtr(void* ptr, void* object)
{
if(disableTracePtr)
return;
CriticalCode code(criticalSection);
if(object)
ptrs[ptr] = object;
else
ptrs.erase(ptr);
}
void ManagedHeapTracePtr(void* ptr, void* object)
{
managedHeap.TracePtr(ptr, object);
}
#endif
#endif
END_INANITY
<commit_msg>proper detection of cyclic references while printing pointers in ManagedHeap<commit_after>#include "ManagedHeap.hpp"
#ifdef ___INANITY_TRACE_HEAP
#include "CriticalCode.hpp"
#endif
#include <map>
#include <iostream>
#include <algorithm>
BEGIN_INANITY
#ifdef ___INANITY_TRACE_PTR
/// Выключить трассировку указателей?
/** Она очень замедляет работу в debug. */
static const bool disableTracePtr = true;
#endif
ManagedHeap managedHeap;
#ifdef ___INANITY_TRACE_HEAP
ManagedHeap::AllocationInfo::AllocationInfo(size_t number, size_t size) : number(number), size(size)
{
}
#endif
ManagedHeap::ManagedHeap()
#ifdef ___INANITY_TRACE_HEAP
: totalAllocationsCount(0), totalAllocationsSize(0)
#endif
{
#ifdef ___INANITY_WINDOWS
// создать кучу (растущую, с нулевым начальным размером)
heap = HeapCreate(0, 0, 0);
if(!heap)
exit(1);
// сделать кучу low-fragmentation
ULONG heapFragValue = 2;
// обработка ошибок не производится, чтобы работало на не-XP и не-Vista
HeapSetInformation(heap, HeapCompatibilityInformation, &heapFragValue, sizeof(heapFragValue));
#endif // ___INANITY_WINDOWS
}
ManagedHeap::~ManagedHeap()
{
#ifdef ___INANITY_WINDOWS
//удалить кучу
HeapDestroy(heap);
#endif
#ifdef ___INANITY_TRACE_HEAP
//выдать отчет по памяти
std::cout << "======= INANITY MANAGED HEAP REPORT =======\n";
std::cout << "Allocations count: " << totalAllocationsCount << "\nAllocations size: " << totalAllocationsSize << "\n";
if(allocations.size())
{
#ifdef ___INANITY_WINDOWS
Beep(750, 300);
#endif
std::cout << "ATTENTION! SOME LEAKS DETECTED!\n";
PrintAllocations(std::cout);
}
else
std::cout << "NO LEAKS DETECTED\n";
#ifdef ___INANITY_TRACE_PTR
std::cout << "======= PTR REPORT =======\n";
if(disableTracePtr)
std::cout << "TRACE PTR DISABLED\n";
else
PrintPtrs(std::cout);
#endif
std::cout << "======= END REPORT =======\n";
#endif
}
void* ManagedHeap::Allocate(size_t size)
{
#ifdef ___INANITY_WINDOWS
void* data = HeapAlloc(heap, 0, size);
if(!data)
ExitProcess(1);
#else
void* data = malloc(size);
#endif
#ifdef ___INANITY_TRACE_HEAP
{
CriticalCode code(criticalSection);
allocations.insert(std::make_pair(data, AllocationInfo(totalAllocationsCount++, size)));
totalAllocationsSize += size;
}
#endif
return data;
}
void ManagedHeap::Free(void *data)
{
// освободить память
#ifdef ___INANITY_WINDOWS
if(!HeapFree(heap, 0, data))
ExitProcess(1);
#else
free(data);
#endif
// отметить, что память удалена
#ifdef ___INANITY_TRACE_HEAP
{
CriticalCode code(criticalSection);
Allocations::iterator i = allocations.find(data);
if(i == allocations.end())
DebugBreak();
allocations.erase(i);
}
#endif
}
#ifdef ___INANITY_TRACE_HEAP
void ManagedHeap::PrintAllocations(std::ostream& stream)
{
CriticalCode code(criticalSection);
for(Allocations::const_iterator i = allocations.begin(); i != allocations.end(); ++i)
{
stream << i->first << " : #" << i->second.number << ", " << i->second.size << " bytes\n";
if(i->second.info)
stream << " " << i->second.info << "\n";
}
}
void ManagedHeap::SetAllocationInfo(void* data, const char* info)
{
CriticalCode code(criticalSection);
Allocations::iterator i = allocations.find(data);
if(i != allocations.end())
i->second.info = info;
}
void ManagedHeapSetAllocationInfo(void* data, const char* info)
{
managedHeap.SetAllocationInfo(data, info);
}
#ifdef ___INANITY_TRACE_PTR
class ManagedHeap::PtrTracer
{
struct Object
{
void* data;
size_t size;
const char* info;
Object(void* data, size_t size, const char* info) : data(data), size(size), info(info) {}
};
struct Sorter
{
bool operator()(const Object& a, const Object& b) const
{
return a.data < b.data;
}
bool operator()(void* a, const Object& b) const
{
return a < b.data;
}
bool operator()(const Object& a, void* b) const
{
return a.data < b;
}
} sorter;
typedef std::vector<Object> Objects;
Objects objects;
typedef std::multimap<Objects::const_iterator, Objects::const_iterator> Links;
Links links;
std::vector<bool> levels;
std::vector<Objects::const_iterator> levelObjects;
public:
PtrTracer(const ManagedHeap& heap)
{
// сформировать список объектов
objects.reserve(heap.allocations.size());
for(Allocations::const_iterator i = heap.allocations.begin(); i != heap.allocations.end(); ++i)
objects.push_back(Object(i->first, i->second.size, i->second.info));
std::sort(objects.begin(), objects.end(), sorter);
// сформировать карту ссылок
for(Ptrs::const_iterator i = heap.ptrs.begin(); i != heap.ptrs.end(); ++i)
{
// найти объект, в котором содержится указатель
Objects::const_iterator j = std::upper_bound(objects.begin(), objects.end(), i->first, sorter);
if(j > objects.begin())
{
--j;
if((size_t)((char*)i->first - (char*)j->data) < j->size)
// да, указатель содержится в этом объекте
// получить объект, на который указывает указатель, и добавить ссылку
links.insert(std::make_pair(j, std::lower_bound(objects.begin(), objects.end(), i->second, sorter)));
}
}
}
void Print(std::ostream& stream, Objects::const_iterator object, bool last = false)
{
for(size_t i = 0; i < levels.size(); ++i)
if(i == levels.size() - 1)
stream << "|_";
else if(levels[i])
stream << "| ";
else
stream << " ";
bool cyclicReference = std::find(levelObjects.begin(), levelObjects.end(), object) != levelObjects.end();
if(cyclicReference)
stream << "CYCLIC ";
stream << object->data << ", " << object->info << "\n";
if(cyclicReference)
return;
if(last)
levels[levels.size() - 1] = false;
levelObjects.push_back(object);
Links::const_iterator link = links.lower_bound(object);
Links::const_iterator endLink = links.upper_bound(object);
if(link != endLink)
{
levels.push_back(true);
Links::const_iterator nextLink;
for(; link != links.end() && link->first == object; link = nextLink)
{
nextLink = link;
++nextLink;
Print(stream, link->second, nextLink == links.end() || nextLink->first != object);
}
levels.pop_back();
}
levelObjects.pop_back();
}
void Print(std::ostream& stream)
{
std::vector<Objects::const_iterator> referencedObjects;
referencedObjects.reserve(links.size());
for(Links::const_iterator i = links.begin(); i != links.end(); ++i)
referencedObjects.push_back(i->second);
std::sort(referencedObjects.begin(), referencedObjects.end());
referencedObjects.resize(std::unique(referencedObjects.begin(), referencedObjects.end()) - referencedObjects.begin());
// пока просто вывести
for(Objects::const_iterator object = objects.begin(); object != objects.end(); ++object)
{
if(std::binary_search(referencedObjects.begin(), referencedObjects.end(), object))
continue;
Print(stream, object);
}
}
};
void ManagedHeap::PrintPtrs(std::ostream& stream)
{
CriticalCode code(criticalSection);
PtrTracer tracer(*this);
tracer.Print(stream);
}
void ManagedHeap::TracePtr(void* ptr, void* object)
{
if(disableTracePtr)
return;
CriticalCode code(criticalSection);
if(object)
ptrs[ptr] = object;
else
ptrs.erase(ptr);
}
void ManagedHeapTracePtr(void* ptr, void* object)
{
managedHeap.TracePtr(ptr, object);
}
#endif
#endif
END_INANITY
<|endoftext|>
|
<commit_before>// Copyright 2015 Open Source Robotics Foundation, Inc.
//
// 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 <execinfo.h>
#include <malloc.h>
#include <sys/mman.h>
#include <sys/resource.h>
#include <unistd.h>
#include <rclcpp/rclcpp.hpp>
#include <rclcpp/strategies/message_pool_memory_strategy.hpp>
#include <rclcpp/strategies/allocator_memory_strategy.hpp>
#include <rttest/rttest.h>
#include <tlsf_cpp/tlsf.hpp>
#include <pendulum_msgs/msg/joint_command.hpp>
#include <pendulum_msgs/msg/joint_state.hpp>
#include <pendulum_msgs/msg/rttest_results.hpp>
#include <memory>
#include "pendulum_control/pendulum_controller.hpp"
#include "pendulum_control/pendulum_motor.hpp"
#include "pendulum_control/rtt_executor.hpp"
static bool running = false;
// Initialize a malloc hook so we can show that no mallocs are made during real-time execution
/// Declare a function pointer into which we will store the default malloc.
static void * (* prev_malloc_hook)(size_t, const void *);
// Use pragma to ignore a warning for using __malloc_hook, which is deprecated (but still awesome).
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
/// Implement a custom malloc.
/**
* Our custom malloc backtraces to find the address of the function that called malloc and formats
* the line as a string (if the code was compiled with debug symbols.
* \param[in] size Requested malloc size.
* \param[in] caller pointer to the caller of this function (unused).
* \return Pointer to the allocated memory
*/
static void * testing_malloc(size_t size, const void * caller)
{
(void)caller;
// Set the malloc implementation to the default malloc hook so that we can call it implicitly
// to initialize a string, otherwise this function will loop infinitely.
__malloc_hook = prev_malloc_hook;
if (running) {
fprintf(stderr, "Called malloc during realtime execution phase!\n");
rclcpp::shutdown();
exit(-1);
}
// Execute the requested malloc.
void * mem = malloc(size);
// Set the malloc hook back to this function, so that we can intercept future mallocs.
__malloc_hook = testing_malloc;
return mem;
}
/// Function to be called when the malloc hook is initialized.
void init_malloc_hook()
{
// Store the default malloc.
prev_malloc_hook = __malloc_hook;
// Set our custom malloc to the malloc hook.
__malloc_hook = testing_malloc;
}
#pragma GCC diagnostic pop
/// Set the hook for malloc initialize so that init_malloc_hook gets called.
void (*volatile __malloc_initialize_hook)(void) = init_malloc_hook;
using rclcpp::strategies::message_pool_memory_strategy::MessagePoolMemoryStrategy;
using rclcpp::memory_strategies::allocator_memory_strategy::AllocatorMemoryStrategy;
template<typename T = void>
using TLSFAllocator = tlsf_heap_allocator<T>;
int main(int argc, char * argv[])
{
// Initialization phase.
// In the initialization phase of a realtime program, non-realtime-safe operations such as
// allocation memory are permitted.
// Create a structure with the default physical propreties of the pendulum (length and mass).
pendulum_control::PendulumProperties properties;
// Instantiate a PendulumMotor class which simulates the physics of the inverted pendulum
// and provide a sensor message for the current position.
// Run the callback for the motor slightly faster than the executor update loop.
auto pendulum_motor = std::make_shared<pendulum_control::PendulumMotor>(
std::chrono::nanoseconds(970000), properties);
// Create the properties of the PID controller.
pendulum_control::PIDProperties pid;
// Instantiate a PendulumController class which will calculate the next motor command.
// Run the callback for the controller slightly faster than the executor update loop.
auto pendulum_controller = std::make_shared<pendulum_control::PendulumController>(
std::chrono::nanoseconds(960000), pid);
// Pass the input arguments to rttest.
// rttest will store relevant parameters and allocate buffers for data collection
rttest_read_args(argc, argv);
// Pass the input arguments to rclcpp and initialize the signal handler.
rclcpp::init(argc, argv);
// The MessagePoolMemoryStrategy preallocates a pool of messages to be used by the subscription.
// Typically, one MessagePoolMemoryStrategy is used per subscription type, and the size of the
// message pool is determined by the number of threads (the maximum number of concurrent accesses
// to the subscription).
// Since this example is single-threaded, we choose a message pool size of 1 for each strategy.
auto state_msg_strategy =
std::make_shared<MessagePoolMemoryStrategy<pendulum_msgs::msg::JointState, 1>>();
auto command_msg_strategy =
std::make_shared<MessagePoolMemoryStrategy<pendulum_msgs::msg::JointCommand, 1>>();
auto setpoint_msg_strategy =
std::make_shared<MessagePoolMemoryStrategy<pendulum_msgs::msg::JointCommand, 1>>();
// The controller node represents user code. This example implements a simple PID controller.
auto controller_node = rclcpp::Node::make_shared("pendulum_controller");
// The "motor" node simulates motors and sensors.
// It provides sensor data and changes the physical model based on the command.
auto motor_node = rclcpp::Node::make_shared("pendulum_motor");
// The quality of service profile is tuned for real-time performance.
// More QoS settings may be exposed by the rmw interface in the future to fulfill real-time
// requirements.
rmw_qos_profile_t qos_profile = rmw_qos_profile_default;
// From http://www.opendds.org/qosusages.html: "A RELIABLE setting can potentially block while
// trying to send." Therefore set the policy to best effort to avoid blocking during execution.
qos_profile.reliability = RMW_QOS_POLICY_RELIABILITY_BEST_EFFORT;
// The "KEEP_LAST" history setting tells DDS to store a fixed-size buffer of values before they
// are sent, to aid with recovery in the event of dropped messages.
// "depth" specifies the size of this buffer.
// In this example, we are optimizing for performance and limited resource usage (preventing page
// faults), instead of reliability. Thus, we set the size of the history buffer to 1.
qos_profile.history = RMW_QOS_POLICY_HISTORY_KEEP_LAST;
qos_profile.depth = 1;
// Initialize the publisher for the sensor message (the current position of the pendulum).
auto sensor_pub = motor_node->create_publisher<pendulum_msgs::msg::JointState>("pendulum_sensor",
qos_profile);
// Create a lambda function to invoke the motor callback when a command is received.
auto motor_subscribe_callback =
[&pendulum_motor](pendulum_msgs::msg::JointCommand::ConstSharedPtr msg) -> void
{
pendulum_motor->on_command_message(msg);
};
// Initialize the subscription to the command message.
// Notice that we pass the MessagePoolMemoryStrategy<JointCommand> initialized above.
auto command_sub = motor_node->create_subscription<pendulum_msgs::msg::JointCommand>(
"pendulum_command", motor_subscribe_callback, qos_profile,
nullptr, false, command_msg_strategy);
// Create a lambda function to invoke the controller callback when a command is received.
auto controller_subscribe_callback =
[&pendulum_controller](pendulum_msgs::msg::JointState::ConstSharedPtr msg) -> void
{
pendulum_controller->on_sensor_message(msg);
};
// Initialize the publisher for the command message.
auto command_pub = controller_node->create_publisher<pendulum_msgs::msg::JointCommand>(
"pendulum_command", qos_profile);
// Initialize the subscriber for the sensor message.
// Notice that we pass the MessageMemoryPoolStrategy<JointState> initialized above.
auto sensor_sub = controller_node->create_subscription<pendulum_msgs::msg::JointState>(
"pendulum_sensor", controller_subscribe_callback, qos_profile,
nullptr, false, state_msg_strategy);
// Create a lambda function to accept user input to command the pendulum
auto controller_command_callback =
[&pendulum_controller](pendulum_msgs::msg::JointCommand::ConstSharedPtr msg) -> void
{
pendulum_controller->on_pendulum_setpoint(msg);
};
// Receive the most recently published message from the teleop node publisher.
auto qos_profile_setpoint_sub(qos_profile);
qos_profile_setpoint_sub.durability = RMW_QOS_POLICY_DURABILITY_TRANSIENT_LOCAL;
auto setpoint_sub = controller_node->create_subscription<pendulum_msgs::msg::JointCommand>(
"pendulum_setpoint", controller_command_callback, qos_profile_setpoint_sub, nullptr, false,
setpoint_msg_strategy);
// Initialize the logger publisher.
auto logger_pub = controller_node->create_publisher<pendulum_msgs::msg::RttestResults>(
"pendulum_statistics", qos_profile);
std::chrono::nanoseconds logger_publisher_period(1000000);
// Initialize the executor.
rclcpp::executor::ExecutorArgs args;
// One of the arguments passed to the Executor is the memory strategy, which delegates the
// runtime-execution allocations to the TLSF allocator.
rclcpp::memory_strategy::MemoryStrategy::SharedPtr memory_strategy =
std::make_shared<AllocatorMemoryStrategy<TLSFAllocator<void>>>();
args.memory_strategy = memory_strategy;
// RttExecutor is a special single-threaded executor instrumented to calculate and record
// real-time performance statistics.
auto executor = std::make_shared<pendulum_control::RttExecutor>(args);
// Add the motor and controller nodes to the executor.
executor->add_node(motor_node);
executor->add_node(controller_node);
// Create a lambda function that will fire regularly to publish the next sensor message.
auto motor_publish_callback =
[&sensor_pub, &pendulum_motor]()
{
if (pendulum_motor->next_message_ready()) {
auto msg = pendulum_motor->get_next_sensor_message();
sensor_pub->publish(msg);
}
};
// Create a lambda function that will fire regularly to publish the next command message.
auto controller_publish_callback =
[&command_pub, &pendulum_controller]()
{
if (pendulum_controller->next_message_ready()) {
auto msg = pendulum_controller->get_next_command_message();
command_pub->publish(msg);
}
};
// Create a lambda function that will fire regularly to publish the next results message.
auto results_msg = std::make_shared<pendulum_msgs::msg::RttestResults>();
auto logger_publish_callback =
[&logger_pub, &results_msg, &executor, &pendulum_motor, &pendulum_controller]() {
results_msg->command = *pendulum_controller->get_next_command_message().get();
results_msg->state = *pendulum_motor->get_next_sensor_message().get();
executor->set_rtt_results_message(results_msg);
logger_pub->publish(results_msg);
};
// Add a timer to enable regular publication of sensor messages.
auto motor_publisher_timer = motor_node->create_wall_timer(
pendulum_motor->get_publish_period(), motor_publish_callback);
// Add a timer to enable regular publication of command messages.
auto controller_publisher_timer = controller_node->create_wall_timer(
pendulum_controller->get_publish_period(), controller_publish_callback);
// Add a timer to enable regular publication of results messages.
auto logger_publisher_timer = controller_node->create_wall_timer(
logger_publisher_period, logger_publish_callback);
// Set the priority of this thread to the maximum safe value, and set its scheduling policy to a
// deterministic (real-time safe) algorithm, round robin.
if (rttest_set_sched_priority(98, SCHED_RR)) {
perror("Couldn't set scheduling priority and policy");
}
// Lock the currently cached virtual memory into RAM, as well as any future memory allocations,
// and do our best to prefault the locked memory to prevent future pagefaults.
// Will return with a non-zero error code if something went wrong (insufficient resources or
// permissions).
// Always do this as the last step of the initialization phase.
// See README.md for instructions on setting permissions.
// See rttest/rttest.cpp for more details.
if (rttest_lock_and_prefault_dynamic() != 0) {
fprintf(stderr, "Couldn't lock all cached virtual memory.\n");
fprintf(stderr, "Pagefaults from reading pages not yet mapped into RAM will be recorded.\n");
}
// End initialization phase
// Execution phase
running = true;
// Unlike the default SingleThreadedExecutor::spin function, RttExecutor::spin runs in
// bounded time (for as many iterations as specified in the rttest parameters).
executor->spin();
// Once the executor has exited, notify the physics simulation to stop running.
pendulum_motor->set_done(true);
// End execution phase
// Teardown phase
// deallocation is handled automatically by objects going out of scope
running = false;
printf("PendulumMotor received %lu messages\n", pendulum_motor->messages_received);
printf("PendulumController received %lu messages\n", pendulum_controller->messages_received);
rclcpp::shutdown();
return 0;
}
<commit_msg>fix spacing to comply with uncrusity 0.67 (#267)<commit_after>// Copyright 2015 Open Source Robotics Foundation, Inc.
//
// 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 <execinfo.h>
#include <malloc.h>
#include <sys/mman.h>
#include <sys/resource.h>
#include <unistd.h>
#include <rclcpp/rclcpp.hpp>
#include <rclcpp/strategies/message_pool_memory_strategy.hpp>
#include <rclcpp/strategies/allocator_memory_strategy.hpp>
#include <rttest/rttest.h>
#include <tlsf_cpp/tlsf.hpp>
#include <pendulum_msgs/msg/joint_command.hpp>
#include <pendulum_msgs/msg/joint_state.hpp>
#include <pendulum_msgs/msg/rttest_results.hpp>
#include <memory>
#include "pendulum_control/pendulum_controller.hpp"
#include "pendulum_control/pendulum_motor.hpp"
#include "pendulum_control/rtt_executor.hpp"
static bool running = false;
// Initialize a malloc hook so we can show that no mallocs are made during real-time execution
/// Declare a function pointer into which we will store the default malloc.
static void * (* prev_malloc_hook)(size_t, const void *);
// Use pragma to ignore a warning for using __malloc_hook, which is deprecated (but still awesome).
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
/// Implement a custom malloc.
/**
* Our custom malloc backtraces to find the address of the function that called malloc and formats
* the line as a string (if the code was compiled with debug symbols.
* \param[in] size Requested malloc size.
* \param[in] caller pointer to the caller of this function (unused).
* \return Pointer to the allocated memory
*/
static void * testing_malloc(size_t size, const void * caller)
{
(void)caller;
// Set the malloc implementation to the default malloc hook so that we can call it implicitly
// to initialize a string, otherwise this function will loop infinitely.
__malloc_hook = prev_malloc_hook;
if (running) {
fprintf(stderr, "Called malloc during realtime execution phase!\n");
rclcpp::shutdown();
exit(-1);
}
// Execute the requested malloc.
void * mem = malloc(size);
// Set the malloc hook back to this function, so that we can intercept future mallocs.
__malloc_hook = testing_malloc;
return mem;
}
/// Function to be called when the malloc hook is initialized.
void init_malloc_hook()
{
// Store the default malloc.
prev_malloc_hook = __malloc_hook;
// Set our custom malloc to the malloc hook.
__malloc_hook = testing_malloc;
}
#pragma GCC diagnostic pop
/// Set the hook for malloc initialize so that init_malloc_hook gets called.
void(*volatile __malloc_initialize_hook)(void) = init_malloc_hook;
using rclcpp::strategies::message_pool_memory_strategy::MessagePoolMemoryStrategy;
using rclcpp::memory_strategies::allocator_memory_strategy::AllocatorMemoryStrategy;
template<typename T = void>
using TLSFAllocator = tlsf_heap_allocator<T>;
int main(int argc, char * argv[])
{
// Initialization phase.
// In the initialization phase of a realtime program, non-realtime-safe operations such as
// allocation memory are permitted.
// Create a structure with the default physical propreties of the pendulum (length and mass).
pendulum_control::PendulumProperties properties;
// Instantiate a PendulumMotor class which simulates the physics of the inverted pendulum
// and provide a sensor message for the current position.
// Run the callback for the motor slightly faster than the executor update loop.
auto pendulum_motor = std::make_shared<pendulum_control::PendulumMotor>(
std::chrono::nanoseconds(970000), properties);
// Create the properties of the PID controller.
pendulum_control::PIDProperties pid;
// Instantiate a PendulumController class which will calculate the next motor command.
// Run the callback for the controller slightly faster than the executor update loop.
auto pendulum_controller = std::make_shared<pendulum_control::PendulumController>(
std::chrono::nanoseconds(960000), pid);
// Pass the input arguments to rttest.
// rttest will store relevant parameters and allocate buffers for data collection
rttest_read_args(argc, argv);
// Pass the input arguments to rclcpp and initialize the signal handler.
rclcpp::init(argc, argv);
// The MessagePoolMemoryStrategy preallocates a pool of messages to be used by the subscription.
// Typically, one MessagePoolMemoryStrategy is used per subscription type, and the size of the
// message pool is determined by the number of threads (the maximum number of concurrent accesses
// to the subscription).
// Since this example is single-threaded, we choose a message pool size of 1 for each strategy.
auto state_msg_strategy =
std::make_shared<MessagePoolMemoryStrategy<pendulum_msgs::msg::JointState, 1>>();
auto command_msg_strategy =
std::make_shared<MessagePoolMemoryStrategy<pendulum_msgs::msg::JointCommand, 1>>();
auto setpoint_msg_strategy =
std::make_shared<MessagePoolMemoryStrategy<pendulum_msgs::msg::JointCommand, 1>>();
// The controller node represents user code. This example implements a simple PID controller.
auto controller_node = rclcpp::Node::make_shared("pendulum_controller");
// The "motor" node simulates motors and sensors.
// It provides sensor data and changes the physical model based on the command.
auto motor_node = rclcpp::Node::make_shared("pendulum_motor");
// The quality of service profile is tuned for real-time performance.
// More QoS settings may be exposed by the rmw interface in the future to fulfill real-time
// requirements.
rmw_qos_profile_t qos_profile = rmw_qos_profile_default;
// From http://www.opendds.org/qosusages.html: "A RELIABLE setting can potentially block while
// trying to send." Therefore set the policy to best effort to avoid blocking during execution.
qos_profile.reliability = RMW_QOS_POLICY_RELIABILITY_BEST_EFFORT;
// The "KEEP_LAST" history setting tells DDS to store a fixed-size buffer of values before they
// are sent, to aid with recovery in the event of dropped messages.
// "depth" specifies the size of this buffer.
// In this example, we are optimizing for performance and limited resource usage (preventing page
// faults), instead of reliability. Thus, we set the size of the history buffer to 1.
qos_profile.history = RMW_QOS_POLICY_HISTORY_KEEP_LAST;
qos_profile.depth = 1;
// Initialize the publisher for the sensor message (the current position of the pendulum).
auto sensor_pub = motor_node->create_publisher<pendulum_msgs::msg::JointState>("pendulum_sensor",
qos_profile);
// Create a lambda function to invoke the motor callback when a command is received.
auto motor_subscribe_callback =
[&pendulum_motor](pendulum_msgs::msg::JointCommand::ConstSharedPtr msg) -> void
{
pendulum_motor->on_command_message(msg);
};
// Initialize the subscription to the command message.
// Notice that we pass the MessagePoolMemoryStrategy<JointCommand> initialized above.
auto command_sub = motor_node->create_subscription<pendulum_msgs::msg::JointCommand>(
"pendulum_command", motor_subscribe_callback, qos_profile,
nullptr, false, command_msg_strategy);
// Create a lambda function to invoke the controller callback when a command is received.
auto controller_subscribe_callback =
[&pendulum_controller](pendulum_msgs::msg::JointState::ConstSharedPtr msg) -> void
{
pendulum_controller->on_sensor_message(msg);
};
// Initialize the publisher for the command message.
auto command_pub = controller_node->create_publisher<pendulum_msgs::msg::JointCommand>(
"pendulum_command", qos_profile);
// Initialize the subscriber for the sensor message.
// Notice that we pass the MessageMemoryPoolStrategy<JointState> initialized above.
auto sensor_sub = controller_node->create_subscription<pendulum_msgs::msg::JointState>(
"pendulum_sensor", controller_subscribe_callback, qos_profile,
nullptr, false, state_msg_strategy);
// Create a lambda function to accept user input to command the pendulum
auto controller_command_callback =
[&pendulum_controller](pendulum_msgs::msg::JointCommand::ConstSharedPtr msg) -> void
{
pendulum_controller->on_pendulum_setpoint(msg);
};
// Receive the most recently published message from the teleop node publisher.
auto qos_profile_setpoint_sub(qos_profile);
qos_profile_setpoint_sub.durability = RMW_QOS_POLICY_DURABILITY_TRANSIENT_LOCAL;
auto setpoint_sub = controller_node->create_subscription<pendulum_msgs::msg::JointCommand>(
"pendulum_setpoint", controller_command_callback, qos_profile_setpoint_sub, nullptr, false,
setpoint_msg_strategy);
// Initialize the logger publisher.
auto logger_pub = controller_node->create_publisher<pendulum_msgs::msg::RttestResults>(
"pendulum_statistics", qos_profile);
std::chrono::nanoseconds logger_publisher_period(1000000);
// Initialize the executor.
rclcpp::executor::ExecutorArgs args;
// One of the arguments passed to the Executor is the memory strategy, which delegates the
// runtime-execution allocations to the TLSF allocator.
rclcpp::memory_strategy::MemoryStrategy::SharedPtr memory_strategy =
std::make_shared<AllocatorMemoryStrategy<TLSFAllocator<void>>>();
args.memory_strategy = memory_strategy;
// RttExecutor is a special single-threaded executor instrumented to calculate and record
// real-time performance statistics.
auto executor = std::make_shared<pendulum_control::RttExecutor>(args);
// Add the motor and controller nodes to the executor.
executor->add_node(motor_node);
executor->add_node(controller_node);
// Create a lambda function that will fire regularly to publish the next sensor message.
auto motor_publish_callback =
[&sensor_pub, &pendulum_motor]()
{
if (pendulum_motor->next_message_ready()) {
auto msg = pendulum_motor->get_next_sensor_message();
sensor_pub->publish(msg);
}
};
// Create a lambda function that will fire regularly to publish the next command message.
auto controller_publish_callback =
[&command_pub, &pendulum_controller]()
{
if (pendulum_controller->next_message_ready()) {
auto msg = pendulum_controller->get_next_command_message();
command_pub->publish(msg);
}
};
// Create a lambda function that will fire regularly to publish the next results message.
auto results_msg = std::make_shared<pendulum_msgs::msg::RttestResults>();
auto logger_publish_callback =
[&logger_pub, &results_msg, &executor, &pendulum_motor, &pendulum_controller]() {
results_msg->command = *pendulum_controller->get_next_command_message().get();
results_msg->state = *pendulum_motor->get_next_sensor_message().get();
executor->set_rtt_results_message(results_msg);
logger_pub->publish(results_msg);
};
// Add a timer to enable regular publication of sensor messages.
auto motor_publisher_timer = motor_node->create_wall_timer(
pendulum_motor->get_publish_period(), motor_publish_callback);
// Add a timer to enable regular publication of command messages.
auto controller_publisher_timer = controller_node->create_wall_timer(
pendulum_controller->get_publish_period(), controller_publish_callback);
// Add a timer to enable regular publication of results messages.
auto logger_publisher_timer = controller_node->create_wall_timer(
logger_publisher_period, logger_publish_callback);
// Set the priority of this thread to the maximum safe value, and set its scheduling policy to a
// deterministic (real-time safe) algorithm, round robin.
if (rttest_set_sched_priority(98, SCHED_RR)) {
perror("Couldn't set scheduling priority and policy");
}
// Lock the currently cached virtual memory into RAM, as well as any future memory allocations,
// and do our best to prefault the locked memory to prevent future pagefaults.
// Will return with a non-zero error code if something went wrong (insufficient resources or
// permissions).
// Always do this as the last step of the initialization phase.
// See README.md for instructions on setting permissions.
// See rttest/rttest.cpp for more details.
if (rttest_lock_and_prefault_dynamic() != 0) {
fprintf(stderr, "Couldn't lock all cached virtual memory.\n");
fprintf(stderr, "Pagefaults from reading pages not yet mapped into RAM will be recorded.\n");
}
// End initialization phase
// Execution phase
running = true;
// Unlike the default SingleThreadedExecutor::spin function, RttExecutor::spin runs in
// bounded time (for as many iterations as specified in the rttest parameters).
executor->spin();
// Once the executor has exited, notify the physics simulation to stop running.
pendulum_motor->set_done(true);
// End execution phase
// Teardown phase
// deallocation is handled automatically by objects going out of scope
running = false;
printf("PendulumMotor received %lu messages\n", pendulum_motor->messages_received);
printf("PendulumController received %lu messages\n", pendulum_controller->messages_received);
rclcpp::shutdown();
return 0;
}
<|endoftext|>
|
<commit_before>/*
Copyright 2011, Jernej Kovacic
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 NumericUtil.cpp
Implementation of the class NumericUtil, a collection of some useful
numerical utilities. This is a templated class and must not be compiled.
Instead it must be included after the class declaration in the .h file
@author Jernej Kovacic
*/
// Delibarately there is no #include "NumericUtil.h"
#include "Rational.h"
#include "NumericUtil.h"
// Note that the optimal EPS depends on application requirements
/*
* Definition of EPS for type float
*/
template<>
float math::NumericUtil<float>::EPS = 1e-9f;
/*
* Double is a more accurate type...
*/
template<>
double math::NumericUtil<double>::EPS = 1e-16;
/*
* In int and other types, EPS doesn't make sense, so set it to 0
*/
template<class T>
T math::NumericUtil<T>::EPS = static_cast<T>(0);
/*
* The implementation for integers et al. where the == operator
* does make sense and no comparison to EPS is necessary.
*/
template<class T>
bool math::NumericUtil<T>::isZero(const T& value)
{
bool retVal = ( static_cast<T>(0)==value ? true : false );
return retVal;
}
/*
* Float and double require specialized implementations of isZero().
* In case of these two types, the equality operator (==) is useless.
* In numerical mathematics, two numbers are considered "equal", when
* absolute value of their difference does not exceed a reasonably set EPS.
* Both specializations are very similar and only differ in types of an input value.
* For easier maintainability, the specialization will be implemented
* only once using a parameterized #define
*/
#define _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(FD) \
template<> \
bool math::NumericUtil<FD>::isZero(const FD& value) \
{ \
bool retVal = false; \
retVal = ( value>-EPS && value<EPS ? true : false ); \
return retVal; \
}
// end od #define
// derive specialization for float:
_MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(float)
// ... and for double:
_MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(double)
// #definition of _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO not needed anymore, #undef it:
#undef _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO
/*
* Implementation for Rational
*/
template<>
bool math::NumericUtil<math::Rational>::isZero(const math::Rational& value)
{
// Rational already contains its own isZero()...
return value.isZero();
}
<commit_msg>minor change<commit_after>/*
Copyright 2011, Jernej Kovacic
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 NumericUtil.cpp
Implementation of the class NumericUtil, a collection of some useful
numerical utilities. This is a templated class and must not be compiled.
Instead it must be included after the class declaration in the .h file
@author Jernej Kovacic
*/
// Delibarately there is no #include "NumericUtil.h"
#include "Rational.h"
// Note that the optimal EPS depends on application requirements
/*
* Definition of EPS for type float
*/
template<>
float math::NumericUtil<float>::EPS = 1e-9f;
/*
* Double is a more accurate type...
*/
template<>
double math::NumericUtil<double>::EPS = 1e-16;
/*
* In int and other types, EPS doesn't make sense, so set it to 0
*/
template<class T>
T math::NumericUtil<T>::EPS = static_cast<T>(0);
/*
* The implementation for integers et al. where the == operator
* does make sense and no comparison to EPS is necessary.
*/
template<class T>
bool math::NumericUtil<T>::isZero(const T& value)
{
bool retVal = ( static_cast<T>(0)==value ? true : false );
return retVal;
}
/*
* Float and double require specialized implementations of isZero().
* In case of these two types, the equality operator (==) is useless.
* In numerical mathematics, two numbers are considered "equal", when
* absolute value of their difference does not exceed a reasonably set EPS.
* Both specializations are very similar and only differ in types of an input value.
* For easier maintainability, the specialization will be implemented
* only once using a parameterized #define
*/
#define _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(FD) \
template<> \
bool math::NumericUtil<FD>::isZero(const FD& value) \
{ \
bool retVal = false; \
retVal = ( value>-EPS && value<EPS ? true : false ); \
return retVal; \
}
// end od #define
// derive specialization for float:
_MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(float)
// ... and for double:
_MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(double)
// #definition of _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO not needed anymore, #undef it:
#undef _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO
/*
* Implementation for Rational
*/
template<>
bool math::NumericUtil<math::Rational>::isZero(const math::Rational& value)
{
// Rational already contains its own isZero()...
return value.isZero();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/views/domui_menu_widget.h"
#include "base/stringprintf.h"
#include "base/singleton.h"
#include "base/task.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/chromeos/views/menu_locator.h"
#include "chrome/browser/chromeos/views/native_menu_domui.h"
#include "chrome/browser/chromeos/wm_ipc.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/renderer_host/render_widget_host_view.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/views/dom_view.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/url_constants.h"
#include "cros/chromeos_wm_ipc_enums.h"
#include "gfx/canvas_skia.h"
#include "googleurl/src/gurl.h"
#include "third_party/skia/include/effects/SkGradientShader.h"
#include "views/border.h"
#include "views/layout_manager.h"
#include "views/widget/root_view.h"
namespace {
// Colors for menu's graident background.
const SkColor kMenuStartColor = SK_ColorWHITE;
const SkColor kMenuEndColor = 0xFFEEEEEE;
// Rounded border for menu. This draws three types of rounded border,
// for context menu, dropdown menu and submenu. Please see
// menu_locator.cc for details.
class RoundedBorder : public views::Border {
public:
explicit RoundedBorder(chromeos::MenuLocator* locator)
: menu_locator_(locator) {
}
private:
// views::Border implementatios.
virtual void Paint(const views::View& view, gfx::Canvas* canvas) const {
const SkScalar* corners = menu_locator_->GetCorners();
// The menu is in off screen so no need to draw corners.
if (!corners)
return;
int w = view.width();
int h = view.height();
SkRect rect = {0, 0, w, h};
SkPath path;
path.addRoundRect(rect, corners);
SkPaint paint;
paint.setStyle(SkPaint::kFill_Style);
paint.setFlags(SkPaint::kAntiAlias_Flag);
SkPoint p[2] = { {0, 0}, {0, h} };
SkColor colors[2] = {kMenuStartColor, kMenuEndColor};
SkShader* s = SkGradientShader::CreateLinear(
p, colors, NULL, 2, SkShader::kClamp_TileMode, NULL);
paint.setShader(s);
// Need to unref shader, otherwise never deleted.
s->unref();
canvas->AsCanvasSkia()->drawPath(path, paint);
}
virtual void GetInsets(gfx::Insets* insets) const {
DCHECK(insets);
menu_locator_->GetInsets(insets);
}
chromeos::MenuLocator* menu_locator_; // not owned
DISALLOW_COPY_AND_ASSIGN(RoundedBorder);
};
class InsetsLayout : public views::LayoutManager {
public:
InsetsLayout() : views::LayoutManager() {}
private:
// views::LayoutManager implementatios.
virtual void Layout(views::View* host) {
if (host->GetChildViewCount() == 0)
return;
gfx::Insets insets = host->GetInsets();
views::View* view = host->GetChildViewAt(0);
view->SetBounds(insets.left(), insets.top(),
host->width() - insets.width(),
host->height() - insets.height());
}
virtual gfx::Size GetPreferredSize(views::View* host) {
DCHECK(host->GetChildViewCount() == 1);
gfx::Insets insets = host->GetInsets();
gfx::Size size = host->GetChildViewAt(0)->GetPreferredSize();
return gfx::Size(size.width() + insets.width(),
size.height() + insets.height());
}
DISALLOW_COPY_AND_ASSIGN(InsetsLayout);
};
const int kDOMViewWarmUpDelayMs = 1000 * 5;
// A delayed task to initialize a cache. This is
// create when a profile is switched.
// (incognito, oobe/login has different profile).
class WarmUpTask : public Task {
public:
WarmUpTask() {}
virtual ~WarmUpTask() {}
virtual void Run();
private:
DISALLOW_COPY_AND_ASSIGN(WarmUpTask);
};
// DOMViewCache holds single cache instance of DOMView.
class DOMViewCache : NotificationObserver {
public:
DOMViewCache()
: current_profile_(NULL),
cache_(NULL) {
registrar_.Add(this, NotificationType::APP_TERMINATING,
NotificationService::AllSources());
}
virtual ~DOMViewCache() {}
// Returns a DOMView for given profile. If there is
// matching cache,
DOMView* Get(Profile* profile) {
if (cache_ &&
cache_->tab_contents()->profile() == profile) {
DOMView* c = cache_;
cache_ = NULL;
CheckClassInvariant();
return c;
}
DOMView* dom_view = new DOMView();
dom_view->Init(profile, NULL);
CheckClassInvariant();
return dom_view;
}
// Release a dom_view. A dom view is reused if its profile matches
// the current profile, or gets deleted otherwise.
void Release(DOMView* dom_view) {
if (cache_ == NULL &&
current_profile_ == dom_view->tab_contents()->profile()) {
cache_ = dom_view;
} else {
delete dom_view;
}
CheckClassInvariant();
}
// (Re)Initiailzes the cache with profile.
// If the current profile does not match the new profile,
// it delets the existing cache (if any) and creates new one.
void Init(Profile* profile) {
if (current_profile_ != profile) {
delete cache_;
cache_ = NULL;
current_profile_ = profile;
BrowserThread::PostDelayedTask(BrowserThread::UI,
FROM_HERE,
new WarmUpTask(),
kDOMViewWarmUpDelayMs);
}
CheckClassInvariant();
}
// Create a cache if one does not exist yet.
void WarmUp() {
if (cache_) {// domui is created in delay.
CheckClassInvariant();
return;
}
cache_ = new DOMView();
cache_->Init(current_profile_, NULL);
cache_->LoadURL(
GURL(StringPrintf("chrome://%s", chrome::kChromeUIMenu)));
CheckClassInvariant();
}
// Deletes cached DOMView instance if any.
void Shutdown() {
delete cache_;
cache_ = NULL;
// Reset current_profile_ as well so that a domview that
// is currently in use will be deleted in Release as well.
current_profile_ = NULL;
}
private:
// NotificationObserver impelmentation:
void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK_EQ(NotificationType::APP_TERMINATING, type.value);
Shutdown();
}
// Tests the class invariant condition.
void CheckClassInvariant() {
DCHECK(!cache_ ||
cache_->tab_contents()->profile() == current_profile_);
}
Profile* current_profile_;
DOMView* cache_;
NotificationRegistrar registrar_;
};
void WarmUpTask::Run() {
Singleton<DOMViewCache>::get()->WarmUp();
}
// A gtk widget key used to test if a given WidgetGtk instance is
// DOMUIMenuWidgetKey.
const char* kDOMUIMenuWidgetKey = "__DOMUI_MENU_WIDGET__";
} // namespace
namespace chromeos {
// static
DOMUIMenuWidget* DOMUIMenuWidget::FindDOMUIMenuWidget(gfx::NativeView native) {
DCHECK(native);
native = gtk_widget_get_toplevel(native);
if (!native)
return NULL;
return static_cast<chromeos::DOMUIMenuWidget*>(
g_object_get_data(G_OBJECT(native), kDOMUIMenuWidgetKey));
}
///////////////////////////////////////////////////////////////////////////////
// DOMUIMenuWidget public:
DOMUIMenuWidget::DOMUIMenuWidget(chromeos::NativeMenuDOMUI* domui_menu,
bool root)
: views::WidgetGtk(views::WidgetGtk::TYPE_POPUP),
domui_menu_(domui_menu),
dom_view_(NULL),
did_pointer_grab_(false),
is_root_(root) {
DCHECK(domui_menu_);
// TODO(oshima): Disabling transparent until we migrate bookmark
// menus to DOMUI. See crosbug.com/7718.
// MakeTransparent();
Singleton<DOMViewCache>::get()->Init(domui_menu->GetProfile());
}
DOMUIMenuWidget::~DOMUIMenuWidget() {
}
void DOMUIMenuWidget::Init(gfx::NativeView parent, const gfx::Rect& bounds) {
WidgetGtk::Init(parent, bounds);
gtk_window_set_destroy_with_parent(GTK_WINDOW(GetNativeView()), TRUE);
gtk_window_set_type_hint(GTK_WINDOW(GetNativeView()),
GDK_WINDOW_TYPE_HINT_MENU);
g_object_set_data(G_OBJECT(GetNativeView()), kDOMUIMenuWidgetKey, this);
}
void DOMUIMenuWidget::Hide() {
ReleaseGrab();
WidgetGtk::Hide();
// Clears the content.
ExecuteJavascript(L"updateModel({'items':[]})");
}
void DOMUIMenuWidget::Close() {
if (dom_view_ != NULL) {
dom_view_->GetParent()->RemoveChildView(dom_view_);
Singleton<DOMViewCache>::get()->Release(dom_view_);
dom_view_ = NULL;
}
// Detach the domui_menu_ which is being deleted.
domui_menu_ = NULL;
views::WidgetGtk::Close();
}
void DOMUIMenuWidget::ReleaseGrab() {
WidgetGtk::ReleaseGrab();
if (did_pointer_grab_) {
did_pointer_grab_ = false;
gdk_pointer_ungrab(GDK_CURRENT_TIME);
ClearGrabWidget();
}
}
gboolean DOMUIMenuWidget::OnGrabBrokeEvent(GtkWidget* widget,
GdkEvent* event) {
did_pointer_grab_ = false;
Hide();
return WidgetGtk::OnGrabBrokeEvent(widget, event);
}
void DOMUIMenuWidget::OnSizeAllocate(GtkWidget* widget,
GtkAllocation* allocation) {
views::WidgetGtk::OnSizeAllocate(widget, allocation);
// Adjust location when menu gets resized.
gfx::Rect bounds;
GetBounds(&bounds, false);
// Don't move until the menu gets contents.
if (bounds.height() > 1) {
menu_locator_->Move(this);
domui_menu_->InputIsReady();
}
}
gboolean MapToFocus(GtkWidget* widget, GdkEvent* event, gpointer data) {
DOMUIMenuWidget* menu_widget = DOMUIMenuWidget::FindDOMUIMenuWidget(widget);
if (menu_widget) {
// See EnableInput for the meaning of data.
bool select_item = data != NULL;
menu_widget->EnableInput(select_item);
}
return true;
}
void DOMUIMenuWidget::EnableScroll(bool enable) {
ExecuteJavascript(StringPrintf(
L"enableScroll(%ls)", enable ? L"true" : L"false" ));
}
void DOMUIMenuWidget::EnableInput(bool select_item) {
if (!dom_view_)
return;
DCHECK(dom_view_->tab_contents()->render_view_host());
DCHECK(dom_view_->tab_contents()->render_view_host()->view());
GtkWidget* target =
dom_view_->tab_contents()->render_view_host()->view()->GetNativeView();
DCHECK(target);
// Skip if the widget already own the input.
if (gtk_grab_get_current() == target)
return;
ClearGrabWidget();
if (!GTK_WIDGET_REALIZED(target)) {
// Wait grabbing widget if the widget is not yet realized.
// Using data as a flag. |select_item| is false if data is NULL,
// or true otherwise.
g_signal_connect(G_OBJECT(target), "map-event",
G_CALLBACK(&MapToFocus),
select_item ? this : NULL);
return;
}
gtk_grab_add(target);
dom_view_->tab_contents()->Focus();
if (select_item) {
ExecuteJavascript(L"selectItem()");
}
}
void DOMUIMenuWidget::ExecuteJavascript(const std::wstring& script) {
// Don't exeute there is no DOMView associated. This is fine because
// 1) selectItem make sense only when DOMView is associated.
// 2) updateModel will be called again when a DOMView is created/assigned.
if (!dom_view_)
return;
DCHECK(dom_view_->tab_contents()->render_view_host());
dom_view_->tab_contents()->render_view_host()->
ExecuteJavascriptInWebFrame(std::wstring(), script);
}
void DOMUIMenuWidget::ShowAt(chromeos::MenuLocator* locator) {
DCHECK(domui_menu_);
menu_locator_.reset(locator);
if (!dom_view_) {
dom_view_ = Singleton<DOMViewCache>::get()->Get(domui_menu_->GetProfile());
dom_view_->Init(domui_menu_->GetProfile(), NULL);
// TODO(oshima): remove extra view to draw rounded corner.
views::View* container = new views::View();
container->AddChildView(dom_view_);
container->set_border(new RoundedBorder(locator));
container->SetLayoutManager(new InsetsLayout());
SetContentsView(container);
dom_view_->LoadURL(domui_menu_->menu_url());
} else {
domui_menu_->UpdateStates();
dom_view_->GetParent()->set_border(new RoundedBorder(locator));
menu_locator_->Move(this);
}
Show();
// The pointer grab is captured only on the top level menu,
// all mouse event events are delivered to submenu using gtk_add_grab.
if (is_root_) {
CaptureGrab();
}
}
void DOMUIMenuWidget::SetSize(const gfx::Size& new_size) {
DCHECK(domui_menu_);
// Ignore the empty new_size request which is called when
// menu.html is loaded.
if (new_size.IsEmpty())
return;
int width, height;
gtk_widget_get_size_request(GetNativeView(), &width, &height);
gfx::Size real_size(std::max(new_size.width(), width),
new_size.height());
// Ignore the size request with the same size.
gfx::Rect bounds;
GetBounds(&bounds, false);
if (bounds.size() == real_size)
return;
menu_locator_->SetBounds(this, real_size);
}
///////////////////////////////////////////////////////////////////////////////
// DOMUIMenuWidget private:
void DOMUIMenuWidget::CaptureGrab() {
// Release the current grab.
ClearGrabWidget();
// NOTE: we do this to ensure we get mouse events from other apps, a grab
// done with gtk_grab_add doesn't get events from other apps.
GdkGrabStatus grab_status =
gdk_pointer_grab(window_contents()->window, FALSE,
static_cast<GdkEventMask>(
GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK |
GDK_POINTER_MOTION_MASK),
NULL, NULL, GDK_CURRENT_TIME);
did_pointer_grab_ = (grab_status == GDK_GRAB_SUCCESS);
DCHECK(did_pointer_grab_);
EnableInput(false /* no selection */);
}
void DOMUIMenuWidget::ClearGrabWidget() {
GtkWidget* grab_widget;
while ((grab_widget = gtk_grab_get_current()))
gtk_grab_remove(grab_widget);
}
} // namespace chromeos
<commit_msg>Skip creating hot-standby DOMView instance if chromeos is shutting down.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/views/domui_menu_widget.h"
#include "base/stringprintf.h"
#include "base/singleton.h"
#include "base/task.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/chromeos/views/menu_locator.h"
#include "chrome/browser/chromeos/views/native_menu_domui.h"
#include "chrome/browser/chromeos/wm_ipc.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/renderer_host/render_widget_host_view.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/views/dom_view.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/url_constants.h"
#include "cros/chromeos_wm_ipc_enums.h"
#include "gfx/canvas_skia.h"
#include "googleurl/src/gurl.h"
#include "third_party/skia/include/effects/SkGradientShader.h"
#include "views/border.h"
#include "views/layout_manager.h"
#include "views/widget/root_view.h"
namespace {
// Colors for menu's graident background.
const SkColor kMenuStartColor = SK_ColorWHITE;
const SkColor kMenuEndColor = 0xFFEEEEEE;
// Rounded border for menu. This draws three types of rounded border,
// for context menu, dropdown menu and submenu. Please see
// menu_locator.cc for details.
class RoundedBorder : public views::Border {
public:
explicit RoundedBorder(chromeos::MenuLocator* locator)
: menu_locator_(locator) {
}
private:
// views::Border implementatios.
virtual void Paint(const views::View& view, gfx::Canvas* canvas) const {
const SkScalar* corners = menu_locator_->GetCorners();
// The menu is in off screen so no need to draw corners.
if (!corners)
return;
int w = view.width();
int h = view.height();
SkRect rect = {0, 0, w, h};
SkPath path;
path.addRoundRect(rect, corners);
SkPaint paint;
paint.setStyle(SkPaint::kFill_Style);
paint.setFlags(SkPaint::kAntiAlias_Flag);
SkPoint p[2] = { {0, 0}, {0, h} };
SkColor colors[2] = {kMenuStartColor, kMenuEndColor};
SkShader* s = SkGradientShader::CreateLinear(
p, colors, NULL, 2, SkShader::kClamp_TileMode, NULL);
paint.setShader(s);
// Need to unref shader, otherwise never deleted.
s->unref();
canvas->AsCanvasSkia()->drawPath(path, paint);
}
virtual void GetInsets(gfx::Insets* insets) const {
DCHECK(insets);
menu_locator_->GetInsets(insets);
}
chromeos::MenuLocator* menu_locator_; // not owned
DISALLOW_COPY_AND_ASSIGN(RoundedBorder);
};
class InsetsLayout : public views::LayoutManager {
public:
InsetsLayout() : views::LayoutManager() {}
private:
// views::LayoutManager implementatios.
virtual void Layout(views::View* host) {
if (host->GetChildViewCount() == 0)
return;
gfx::Insets insets = host->GetInsets();
views::View* view = host->GetChildViewAt(0);
view->SetBounds(insets.left(), insets.top(),
host->width() - insets.width(),
host->height() - insets.height());
}
virtual gfx::Size GetPreferredSize(views::View* host) {
DCHECK(host->GetChildViewCount() == 1);
gfx::Insets insets = host->GetInsets();
gfx::Size size = host->GetChildViewAt(0)->GetPreferredSize();
return gfx::Size(size.width() + insets.width(),
size.height() + insets.height());
}
DISALLOW_COPY_AND_ASSIGN(InsetsLayout);
};
const int kDOMViewWarmUpDelayMs = 1000 * 5;
// A delayed task to initialize a cache. This is
// create when a profile is switched.
// (incognito, oobe/login has different profile).
class WarmUpTask : public Task {
public:
WarmUpTask() {}
virtual ~WarmUpTask() {}
virtual void Run();
private:
DISALLOW_COPY_AND_ASSIGN(WarmUpTask);
};
// DOMViewCache holds single cache instance of DOMView.
class DOMViewCache : NotificationObserver {
public:
DOMViewCache()
: current_profile_(NULL),
cache_(NULL) {
registrar_.Add(this, NotificationType::APP_TERMINATING,
NotificationService::AllSources());
}
virtual ~DOMViewCache() {}
// Returns a DOMView for given profile. If there is
// matching cache,
DOMView* Get(Profile* profile) {
if (cache_ &&
cache_->tab_contents()->profile() == profile) {
DOMView* c = cache_;
cache_ = NULL;
CheckClassInvariant();
return c;
}
DOMView* dom_view = new DOMView();
dom_view->Init(profile, NULL);
CheckClassInvariant();
return dom_view;
}
// Release a dom_view. A dom view is reused if its profile matches
// the current profile, or gets deleted otherwise.
void Release(DOMView* dom_view) {
if (cache_ == NULL &&
current_profile_ == dom_view->tab_contents()->profile()) {
cache_ = dom_view;
} else {
delete dom_view;
}
CheckClassInvariant();
}
// (Re)Initiailzes the cache with profile.
// If the current profile does not match the new profile,
// it delets the existing cache (if any) and creates new one.
void Init(Profile* profile) {
if (current_profile_ != profile) {
delete cache_;
cache_ = NULL;
current_profile_ = profile;
BrowserThread::PostDelayedTask(BrowserThread::UI,
FROM_HERE,
new WarmUpTask(),
kDOMViewWarmUpDelayMs);
}
CheckClassInvariant();
}
// Create a cache if one does not exist yet.
void WarmUp() {
// skip if domui is created in delay, or
// chromeos is shutting down.
if (cache_ || !current_profile_) {
CheckClassInvariant();
return;
}
cache_ = new DOMView();
cache_->Init(current_profile_, NULL);
cache_->LoadURL(
GURL(StringPrintf("chrome://%s", chrome::kChromeUIMenu)));
CheckClassInvariant();
}
// Deletes cached DOMView instance if any.
void Shutdown() {
delete cache_;
cache_ = NULL;
// Reset current_profile_ as well so that a domview that
// is currently in use will be deleted in Release as well.
current_profile_ = NULL;
}
private:
// NotificationObserver impelmentation:
void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK_EQ(NotificationType::APP_TERMINATING, type.value);
Shutdown();
}
// Tests the class invariant condition.
void CheckClassInvariant() {
DCHECK(!cache_ ||
cache_->tab_contents()->profile() == current_profile_);
}
Profile* current_profile_;
DOMView* cache_;
NotificationRegistrar registrar_;
};
void WarmUpTask::Run() {
Singleton<DOMViewCache>::get()->WarmUp();
}
// A gtk widget key used to test if a given WidgetGtk instance is
// DOMUIMenuWidgetKey.
const char* kDOMUIMenuWidgetKey = "__DOMUI_MENU_WIDGET__";
} // namespace
namespace chromeos {
// static
DOMUIMenuWidget* DOMUIMenuWidget::FindDOMUIMenuWidget(gfx::NativeView native) {
DCHECK(native);
native = gtk_widget_get_toplevel(native);
if (!native)
return NULL;
return static_cast<chromeos::DOMUIMenuWidget*>(
g_object_get_data(G_OBJECT(native), kDOMUIMenuWidgetKey));
}
///////////////////////////////////////////////////////////////////////////////
// DOMUIMenuWidget public:
DOMUIMenuWidget::DOMUIMenuWidget(chromeos::NativeMenuDOMUI* domui_menu,
bool root)
: views::WidgetGtk(views::WidgetGtk::TYPE_POPUP),
domui_menu_(domui_menu),
dom_view_(NULL),
did_pointer_grab_(false),
is_root_(root) {
DCHECK(domui_menu_);
// TODO(oshima): Disabling transparent until we migrate bookmark
// menus to DOMUI. See crosbug.com/7718.
// MakeTransparent();
Singleton<DOMViewCache>::get()->Init(domui_menu->GetProfile());
}
DOMUIMenuWidget::~DOMUIMenuWidget() {
}
void DOMUIMenuWidget::Init(gfx::NativeView parent, const gfx::Rect& bounds) {
WidgetGtk::Init(parent, bounds);
gtk_window_set_destroy_with_parent(GTK_WINDOW(GetNativeView()), TRUE);
gtk_window_set_type_hint(GTK_WINDOW(GetNativeView()),
GDK_WINDOW_TYPE_HINT_MENU);
g_object_set_data(G_OBJECT(GetNativeView()), kDOMUIMenuWidgetKey, this);
}
void DOMUIMenuWidget::Hide() {
ReleaseGrab();
WidgetGtk::Hide();
// Clears the content.
ExecuteJavascript(L"updateModel({'items':[]})");
}
void DOMUIMenuWidget::Close() {
if (dom_view_ != NULL) {
dom_view_->GetParent()->RemoveChildView(dom_view_);
Singleton<DOMViewCache>::get()->Release(dom_view_);
dom_view_ = NULL;
}
// Detach the domui_menu_ which is being deleted.
domui_menu_ = NULL;
views::WidgetGtk::Close();
}
void DOMUIMenuWidget::ReleaseGrab() {
WidgetGtk::ReleaseGrab();
if (did_pointer_grab_) {
did_pointer_grab_ = false;
gdk_pointer_ungrab(GDK_CURRENT_TIME);
ClearGrabWidget();
}
}
gboolean DOMUIMenuWidget::OnGrabBrokeEvent(GtkWidget* widget,
GdkEvent* event) {
did_pointer_grab_ = false;
Hide();
return WidgetGtk::OnGrabBrokeEvent(widget, event);
}
void DOMUIMenuWidget::OnSizeAllocate(GtkWidget* widget,
GtkAllocation* allocation) {
views::WidgetGtk::OnSizeAllocate(widget, allocation);
// Adjust location when menu gets resized.
gfx::Rect bounds;
GetBounds(&bounds, false);
// Don't move until the menu gets contents.
if (bounds.height() > 1) {
menu_locator_->Move(this);
domui_menu_->InputIsReady();
}
}
gboolean MapToFocus(GtkWidget* widget, GdkEvent* event, gpointer data) {
DOMUIMenuWidget* menu_widget = DOMUIMenuWidget::FindDOMUIMenuWidget(widget);
if (menu_widget) {
// See EnableInput for the meaning of data.
bool select_item = data != NULL;
menu_widget->EnableInput(select_item);
}
return true;
}
void DOMUIMenuWidget::EnableScroll(bool enable) {
ExecuteJavascript(StringPrintf(
L"enableScroll(%ls)", enable ? L"true" : L"false" ));
}
void DOMUIMenuWidget::EnableInput(bool select_item) {
if (!dom_view_)
return;
DCHECK(dom_view_->tab_contents()->render_view_host());
DCHECK(dom_view_->tab_contents()->render_view_host()->view());
GtkWidget* target =
dom_view_->tab_contents()->render_view_host()->view()->GetNativeView();
DCHECK(target);
// Skip if the widget already own the input.
if (gtk_grab_get_current() == target)
return;
ClearGrabWidget();
if (!GTK_WIDGET_REALIZED(target)) {
// Wait grabbing widget if the widget is not yet realized.
// Using data as a flag. |select_item| is false if data is NULL,
// or true otherwise.
g_signal_connect(G_OBJECT(target), "map-event",
G_CALLBACK(&MapToFocus),
select_item ? this : NULL);
return;
}
gtk_grab_add(target);
dom_view_->tab_contents()->Focus();
if (select_item) {
ExecuteJavascript(L"selectItem()");
}
}
void DOMUIMenuWidget::ExecuteJavascript(const std::wstring& script) {
// Don't exeute there is no DOMView associated. This is fine because
// 1) selectItem make sense only when DOMView is associated.
// 2) updateModel will be called again when a DOMView is created/assigned.
if (!dom_view_)
return;
DCHECK(dom_view_->tab_contents()->render_view_host());
dom_view_->tab_contents()->render_view_host()->
ExecuteJavascriptInWebFrame(std::wstring(), script);
}
void DOMUIMenuWidget::ShowAt(chromeos::MenuLocator* locator) {
DCHECK(domui_menu_);
menu_locator_.reset(locator);
if (!dom_view_) {
dom_view_ = Singleton<DOMViewCache>::get()->Get(domui_menu_->GetProfile());
dom_view_->Init(domui_menu_->GetProfile(), NULL);
// TODO(oshima): remove extra view to draw rounded corner.
views::View* container = new views::View();
container->AddChildView(dom_view_);
container->set_border(new RoundedBorder(locator));
container->SetLayoutManager(new InsetsLayout());
SetContentsView(container);
dom_view_->LoadURL(domui_menu_->menu_url());
} else {
domui_menu_->UpdateStates();
dom_view_->GetParent()->set_border(new RoundedBorder(locator));
menu_locator_->Move(this);
}
Show();
// The pointer grab is captured only on the top level menu,
// all mouse event events are delivered to submenu using gtk_add_grab.
if (is_root_) {
CaptureGrab();
}
}
void DOMUIMenuWidget::SetSize(const gfx::Size& new_size) {
DCHECK(domui_menu_);
// Ignore the empty new_size request which is called when
// menu.html is loaded.
if (new_size.IsEmpty())
return;
int width, height;
gtk_widget_get_size_request(GetNativeView(), &width, &height);
gfx::Size real_size(std::max(new_size.width(), width),
new_size.height());
// Ignore the size request with the same size.
gfx::Rect bounds;
GetBounds(&bounds, false);
if (bounds.size() == real_size)
return;
menu_locator_->SetBounds(this, real_size);
}
///////////////////////////////////////////////////////////////////////////////
// DOMUIMenuWidget private:
void DOMUIMenuWidget::CaptureGrab() {
// Release the current grab.
ClearGrabWidget();
// NOTE: we do this to ensure we get mouse events from other apps, a grab
// done with gtk_grab_add doesn't get events from other apps.
GdkGrabStatus grab_status =
gdk_pointer_grab(window_contents()->window, FALSE,
static_cast<GdkEventMask>(
GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK |
GDK_POINTER_MOTION_MASK),
NULL, NULL, GDK_CURRENT_TIME);
did_pointer_grab_ = (grab_status == GDK_GRAB_SUCCESS);
DCHECK(did_pointer_grab_);
EnableInput(false /* no selection */);
}
void DOMUIMenuWidget::ClearGrabWidget() {
GtkWidget* grab_widget;
while ((grab_widget = gtk_grab_get_current()))
gtk_grab_remove(grab_widget);
}
} // namespace chromeos
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/notifications/balloon_collection_impl.h"
#include "base/logging.h"
#include "base/stl_util-inl.h"
#include "chrome/browser/notifications/balloon.h"
#include "chrome/browser/notifications/notification.h"
#include "chrome/browser/window_sizer.h"
#include "gfx/rect.h"
#include "gfx/size.h"
namespace {
// Portion of the screen allotted for notifications. When notification balloons
// extend over this, no new notifications are shown until some are closed.
const double kPercentBalloonFillFactor = 0.7;
// Allow at least this number of balloons on the screen.
const int kMinAllowedBalloonCount = 2;
} // namespace
// static
// Note that on MacOS, since the coordinate system is inverted vertically from
// the others, this actually produces notifications coming from the TOP right,
// which is what is desired.
BalloonCollectionImpl::Layout::Placement
BalloonCollectionImpl::Layout::placement_ =
Layout::VERTICALLY_FROM_BOTTOM_RIGHT;
BalloonCollectionImpl::BalloonCollectionImpl() {
}
BalloonCollectionImpl::~BalloonCollectionImpl() {
STLDeleteElements(&balloons_);
}
void BalloonCollectionImpl::Add(const Notification& notification,
Profile* profile) {
Balloon* new_balloon = MakeBalloon(notification, profile);
balloons_.push_back(new_balloon);
PositionBalloons(false);
new_balloon->Show();
// There may be no listener in a unit test.
if (space_change_listener_)
space_change_listener_->OnBalloonSpaceChanged();
}
bool BalloonCollectionImpl::Remove(const Notification& notification) {
Balloons::iterator iter;
for (iter = balloons_.begin(); iter != balloons_.end(); ++iter) {
if (notification.IsSame((*iter)->notification())) {
// Balloon.CloseByScript() will cause OnBalloonClosed() to be called on
// this object, which will remove it from the collection and free it.
(*iter)->CloseByScript();
return true;
}
}
return false;
}
bool BalloonCollectionImpl::HasSpace() const {
if (count() < kMinAllowedBalloonCount)
return true;
int max_balloon_size = 0;
int total_size = 0;
layout_.GetMaxLinearSize(&max_balloon_size, &total_size);
int current_max_size = max_balloon_size * count();
int max_allowed_size = static_cast<int>(total_size *
kPercentBalloonFillFactor);
return current_max_size < max_allowed_size - max_balloon_size;
}
void BalloonCollectionImpl::ResizeBalloon(Balloon* balloon,
const gfx::Size& size) {
// restrict to the min & max sizes
gfx::Size real_size(
std::max(Layout::min_balloon_width(),
std::min(Layout::max_balloon_width(), size.width())),
std::max(Layout::min_balloon_height(),
std::min(Layout::max_balloon_height(), size.height())));
balloon->set_content_size(real_size);
PositionBalloons(true);
}
void BalloonCollectionImpl::DisplayChanged() {
layout_.RefreshSystemMetrics();
PositionBalloons(true);
}
void BalloonCollectionImpl::OnBalloonClosed(Balloon* source) {
// We want to free the balloon when finished.
scoped_ptr<Balloon> closed(source);
for (Balloons::iterator it = balloons_.begin(); it != balloons_.end(); ++it) {
if (*it == source) {
balloons_.erase(it);
break;
}
}
PositionBalloons(true);
// There may be no listener in a unit test.
if (space_change_listener_)
space_change_listener_->OnBalloonSpaceChanged();
}
void BalloonCollectionImpl::PositionBalloons(bool reposition) {
gfx::Point origin = layout_.GetLayoutOrigin();
for (Balloons::iterator it = balloons_.begin(); it != balloons_.end(); ++it) {
gfx::Point upper_left = layout_.NextPosition((*it)->GetViewSize(), &origin);
(*it)->SetPosition(upper_left, reposition);
}
}
BalloonCollectionImpl::Layout::Layout() {
RefreshSystemMetrics();
}
void BalloonCollectionImpl::Layout::GetMaxLinearSize(int* max_balloon_size,
int* total_size) const {
DCHECK(max_balloon_size && total_size);
switch (placement_) {
case HORIZONTALLY_FROM_BOTTOM_LEFT:
case HORIZONTALLY_FROM_BOTTOM_RIGHT:
*total_size = work_area_.width();
*max_balloon_size = max_balloon_width();
break;
case VERTICALLY_FROM_TOP_RIGHT:
case VERTICALLY_FROM_BOTTOM_RIGHT:
*total_size = work_area_.height();
*max_balloon_size = max_balloon_height();
break;
default:
NOTREACHED();
break;
}
}
gfx::Point BalloonCollectionImpl::Layout::GetLayoutOrigin() const {
int x = 0;
int y = 0;
switch (placement_) {
case HORIZONTALLY_FROM_BOTTOM_LEFT:
x = work_area_.x() + HorizontalEdgeMargin();
y = work_area_.bottom() - VerticalEdgeMargin();
break;
case HORIZONTALLY_FROM_BOTTOM_RIGHT:
x = work_area_.right() - HorizontalEdgeMargin();
y = work_area_.bottom() - VerticalEdgeMargin();
break;
case VERTICALLY_FROM_TOP_RIGHT:
x = work_area_.right() - HorizontalEdgeMargin();
y = work_area_.y() + VerticalEdgeMargin();
break;
case VERTICALLY_FROM_BOTTOM_RIGHT:
x = work_area_.right() - HorizontalEdgeMargin();
y = work_area_.bottom() - VerticalEdgeMargin();
break;
default:
NOTREACHED();
break;
}
return gfx::Point(x, y);
}
gfx::Point BalloonCollectionImpl::Layout::NextPosition(
const gfx::Size& balloon_size,
gfx::Point* position_iterator) const {
DCHECK(position_iterator);
int x = 0;
int y = 0;
switch (placement_) {
case HORIZONTALLY_FROM_BOTTOM_LEFT:
x = position_iterator->x();
y = position_iterator->y() - balloon_size.height();
position_iterator->set_x(position_iterator->x() + balloon_size.width() +
InterBalloonMargin());
break;
case HORIZONTALLY_FROM_BOTTOM_RIGHT:
position_iterator->set_x(position_iterator->x() - balloon_size.width() -
InterBalloonMargin());
x = position_iterator->x();
y = position_iterator->y() - balloon_size.height();
break;
case VERTICALLY_FROM_TOP_RIGHT:
x = position_iterator->x() - balloon_size.width();
y = position_iterator->y();
position_iterator->set_y(position_iterator->y() + balloon_size.height() +
InterBalloonMargin());
break;
case VERTICALLY_FROM_BOTTOM_RIGHT:
position_iterator->set_y(position_iterator->y() - balloon_size.height() -
InterBalloonMargin());
x = position_iterator->x() - balloon_size.width();
y = position_iterator->y();
break;
default:
NOTREACHED();
break;
}
return gfx::Point(x, y);
}
bool BalloonCollectionImpl::Layout::RefreshSystemMetrics() {
bool changed = false;
scoped_ptr<WindowSizer::MonitorInfoProvider> info_provider(
WindowSizer::CreateDefaultMonitorInfoProvider());
gfx::Rect new_work_area = info_provider->GetPrimaryMonitorWorkArea();
if (!work_area_.Equals(new_work_area)) {
work_area_.SetRect(new_work_area.x(), new_work_area.y(),
new_work_area.width(), new_work_area.height());
changed = true;
}
return changed;
}
<commit_msg>Only allow notifications to grow in size (as the content size is determined). Mac OS sometimes rapidly reports two alternating sizes, causing the animations to seize up and flicker.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/notifications/balloon_collection_impl.h"
#include "base/logging.h"
#include "base/stl_util-inl.h"
#include "chrome/browser/notifications/balloon.h"
#include "chrome/browser/notifications/notification.h"
#include "chrome/browser/window_sizer.h"
#include "gfx/rect.h"
#include "gfx/size.h"
namespace {
// Portion of the screen allotted for notifications. When notification balloons
// extend over this, no new notifications are shown until some are closed.
const double kPercentBalloonFillFactor = 0.7;
// Allow at least this number of balloons on the screen.
const int kMinAllowedBalloonCount = 2;
} // namespace
// static
// Note that on MacOS, since the coordinate system is inverted vertically from
// the others, this actually produces notifications coming from the TOP right,
// which is what is desired.
BalloonCollectionImpl::Layout::Placement
BalloonCollectionImpl::Layout::placement_ =
Layout::VERTICALLY_FROM_BOTTOM_RIGHT;
BalloonCollectionImpl::BalloonCollectionImpl() {
}
BalloonCollectionImpl::~BalloonCollectionImpl() {
STLDeleteElements(&balloons_);
}
void BalloonCollectionImpl::Add(const Notification& notification,
Profile* profile) {
Balloon* new_balloon = MakeBalloon(notification, profile);
balloons_.push_back(new_balloon);
PositionBalloons(false);
new_balloon->Show();
// There may be no listener in a unit test.
if (space_change_listener_)
space_change_listener_->OnBalloonSpaceChanged();
}
bool BalloonCollectionImpl::Remove(const Notification& notification) {
Balloons::iterator iter;
for (iter = balloons_.begin(); iter != balloons_.end(); ++iter) {
if (notification.IsSame((*iter)->notification())) {
// Balloon.CloseByScript() will cause OnBalloonClosed() to be called on
// this object, which will remove it from the collection and free it.
(*iter)->CloseByScript();
return true;
}
}
return false;
}
bool BalloonCollectionImpl::HasSpace() const {
if (count() < kMinAllowedBalloonCount)
return true;
int max_balloon_size = 0;
int total_size = 0;
layout_.GetMaxLinearSize(&max_balloon_size, &total_size);
int current_max_size = max_balloon_size * count();
int max_allowed_size = static_cast<int>(total_size *
kPercentBalloonFillFactor);
return current_max_size < max_allowed_size - max_balloon_size;
}
void BalloonCollectionImpl::ResizeBalloon(Balloon* balloon,
const gfx::Size& size) {
// restrict to the min & max sizes
gfx::Size real_size(
std::max(Layout::min_balloon_width(),
std::min(Layout::max_balloon_width(), size.width())),
std::max(Layout::min_balloon_height(),
std::min(Layout::max_balloon_height(), size.height())));
// Only allow the balloons to grow in size. This avoids flickering
// on Mac OS which sometimes rapidly reports alternating sizes.
gfx::Size old_size = balloon->content_size();
if (real_size.width() > old_size.width() ||
real_size.height() > old_size.height()) {
balloon->set_content_size(real_size);
PositionBalloons(true);
}
}
void BalloonCollectionImpl::DisplayChanged() {
layout_.RefreshSystemMetrics();
PositionBalloons(true);
}
void BalloonCollectionImpl::OnBalloonClosed(Balloon* source) {
// We want to free the balloon when finished.
scoped_ptr<Balloon> closed(source);
for (Balloons::iterator it = balloons_.begin(); it != balloons_.end(); ++it) {
if (*it == source) {
balloons_.erase(it);
break;
}
}
PositionBalloons(true);
// There may be no listener in a unit test.
if (space_change_listener_)
space_change_listener_->OnBalloonSpaceChanged();
}
void BalloonCollectionImpl::PositionBalloons(bool reposition) {
gfx::Point origin = layout_.GetLayoutOrigin();
for (Balloons::iterator it = balloons_.begin(); it != balloons_.end(); ++it) {
gfx::Point upper_left = layout_.NextPosition((*it)->GetViewSize(), &origin);
(*it)->SetPosition(upper_left, reposition);
}
}
BalloonCollectionImpl::Layout::Layout() {
RefreshSystemMetrics();
}
void BalloonCollectionImpl::Layout::GetMaxLinearSize(int* max_balloon_size,
int* total_size) const {
DCHECK(max_balloon_size && total_size);
switch (placement_) {
case HORIZONTALLY_FROM_BOTTOM_LEFT:
case HORIZONTALLY_FROM_BOTTOM_RIGHT:
*total_size = work_area_.width();
*max_balloon_size = max_balloon_width();
break;
case VERTICALLY_FROM_TOP_RIGHT:
case VERTICALLY_FROM_BOTTOM_RIGHT:
*total_size = work_area_.height();
*max_balloon_size = max_balloon_height();
break;
default:
NOTREACHED();
break;
}
}
gfx::Point BalloonCollectionImpl::Layout::GetLayoutOrigin() const {
int x = 0;
int y = 0;
switch (placement_) {
case HORIZONTALLY_FROM_BOTTOM_LEFT:
x = work_area_.x() + HorizontalEdgeMargin();
y = work_area_.bottom() - VerticalEdgeMargin();
break;
case HORIZONTALLY_FROM_BOTTOM_RIGHT:
x = work_area_.right() - HorizontalEdgeMargin();
y = work_area_.bottom() - VerticalEdgeMargin();
break;
case VERTICALLY_FROM_TOP_RIGHT:
x = work_area_.right() - HorizontalEdgeMargin();
y = work_area_.y() + VerticalEdgeMargin();
break;
case VERTICALLY_FROM_BOTTOM_RIGHT:
x = work_area_.right() - HorizontalEdgeMargin();
y = work_area_.bottom() - VerticalEdgeMargin();
break;
default:
NOTREACHED();
break;
}
return gfx::Point(x, y);
}
gfx::Point BalloonCollectionImpl::Layout::NextPosition(
const gfx::Size& balloon_size,
gfx::Point* position_iterator) const {
DCHECK(position_iterator);
int x = 0;
int y = 0;
switch (placement_) {
case HORIZONTALLY_FROM_BOTTOM_LEFT:
x = position_iterator->x();
y = position_iterator->y() - balloon_size.height();
position_iterator->set_x(position_iterator->x() + balloon_size.width() +
InterBalloonMargin());
break;
case HORIZONTALLY_FROM_BOTTOM_RIGHT:
position_iterator->set_x(position_iterator->x() - balloon_size.width() -
InterBalloonMargin());
x = position_iterator->x();
y = position_iterator->y() - balloon_size.height();
break;
case VERTICALLY_FROM_TOP_RIGHT:
x = position_iterator->x() - balloon_size.width();
y = position_iterator->y();
position_iterator->set_y(position_iterator->y() + balloon_size.height() +
InterBalloonMargin());
break;
case VERTICALLY_FROM_BOTTOM_RIGHT:
position_iterator->set_y(position_iterator->y() - balloon_size.height() -
InterBalloonMargin());
x = position_iterator->x() - balloon_size.width();
y = position_iterator->y();
break;
default:
NOTREACHED();
break;
}
return gfx::Point(x, y);
}
bool BalloonCollectionImpl::Layout::RefreshSystemMetrics() {
bool changed = false;
scoped_ptr<WindowSizer::MonitorInfoProvider> info_provider(
WindowSizer::CreateDefaultMonitorInfoProvider());
gfx::Rect new_work_area = info_provider->GetPrimaryMonitorWorkArea();
if (!work_area_.Equals(new_work_area)) {
work_area_.SetRect(new_work_area.x(), new_work_area.y(),
new_work_area.width(), new_work_area.height());
changed = true;
}
return changed;
}
<|endoftext|>
|
<commit_before>//===--- AvoidConstParamsInDecls.cpp - clang-tidy--------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "AvoidConstParamsInDecls.h"
#include "llvm/ADT/Optional.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/Lex/Lexer.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace readability {
namespace {
SourceRange getTypeRange(const ParmVarDecl &Param) {
if (Param.getIdentifier() != nullptr)
return SourceRange(Param.getLocStart(),
Param.getLocEnd().getLocWithOffset(-1));
return Param.getSourceRange();
}
} // namespace
void AvoidConstParamsInDecls::registerMatchers(MatchFinder *Finder) {
const auto ConstParamDecl =
parmVarDecl(hasType(qualType(isConstQualified()))).bind("param");
Finder->addMatcher(functionDecl(unless(isDefinition()),
has(typeLoc(forEach(ConstParamDecl))))
.bind("func"),
this);
}
// Re-lex the tokens to get precise location of last 'const'
static llvm::Optional<Token> ConstTok(CharSourceRange Range,
const MatchFinder::MatchResult &Result) {
const SourceManager &Sources = *Result.SourceManager;
std::pair<FileID, unsigned> LocInfo =
Sources.getDecomposedLoc(Range.getBegin());
StringRef File = Sources.getBufferData(LocInfo.first);
const char *TokenBegin = File.data() + LocInfo.second;
Lexer RawLexer(Sources.getLocForStartOfFile(LocInfo.first),
Result.Context->getLangOpts(), File.begin(), TokenBegin,
File.end());
Token Tok;
llvm::Optional<Token> ConstTok;
while (!RawLexer.LexFromRawLexer(Tok)) {
if (Sources.isBeforeInTranslationUnit(Range.getEnd(), Tok.getLocation()))
break;
if (Tok.is(tok::raw_identifier)) {
IdentifierInfo &Info = Result.Context->Idents.get(StringRef(
Sources.getCharacterData(Tok.getLocation()), Tok.getLength()));
Tok.setIdentifierInfo(&Info);
Tok.setKind(Info.getTokenID());
}
if (Tok.is(tok::kw_const))
ConstTok = Tok;
}
return ConstTok;
}
void AvoidConstParamsInDecls::check(const MatchFinder::MatchResult &Result) {
const auto *Func = Result.Nodes.getNodeAs<FunctionDecl>("func");
const auto *Param = Result.Nodes.getNodeAs<ParmVarDecl>("param");
if (!Param->getType().isLocalConstQualified())
return;
auto Diag = diag(Param->getLocStart(),
"parameter %0 is const-qualified in the function "
"declaration; const-qualification of parameters only has an "
"effect in function definitions");
if (Param->getName().empty()) {
for (unsigned int i = 0; i < Func->getNumParams(); ++i) {
if (Param == Func->getParamDecl(i)) {
Diag << (i + 1);
break;
}
}
} else {
Diag << Param;
}
CharSourceRange FileRange = Lexer::makeFileCharRange(
CharSourceRange::getTokenRange(getTypeRange(*Param)),
*Result.SourceManager, Result.Context->getLangOpts());
if (!FileRange.isValid())
return;
auto Tok = ConstTok(FileRange, Result);
if (!Tok)
return;
Diag << FixItHint::CreateRemoval(
CharSourceRange::getTokenRange(Tok->getLocation(), Tok->getLocation()));
}
} // namespace readability
} // namespace tidy
} // namespace clang
<commit_msg>[clang-tidy] Do not try to suggest a fix if the parameter is partially in a macro.<commit_after>//===--- AvoidConstParamsInDecls.cpp - clang-tidy--------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "AvoidConstParamsInDecls.h"
#include "llvm/ADT/Optional.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/Lex/Lexer.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace readability {
namespace {
SourceRange getTypeRange(const ParmVarDecl &Param) {
if (Param.getIdentifier() != nullptr)
return SourceRange(Param.getLocStart(),
Param.getLocEnd().getLocWithOffset(-1));
return Param.getSourceRange();
}
} // namespace
void AvoidConstParamsInDecls::registerMatchers(MatchFinder *Finder) {
const auto ConstParamDecl =
parmVarDecl(hasType(qualType(isConstQualified()))).bind("param");
Finder->addMatcher(functionDecl(unless(isDefinition()),
has(typeLoc(forEach(ConstParamDecl))))
.bind("func"),
this);
}
// Re-lex the tokens to get precise location of last 'const'
static llvm::Optional<Token> ConstTok(CharSourceRange Range,
const MatchFinder::MatchResult &Result) {
const SourceManager &Sources = *Result.SourceManager;
std::pair<FileID, unsigned> LocInfo =
Sources.getDecomposedLoc(Range.getBegin());
StringRef File = Sources.getBufferData(LocInfo.first);
const char *TokenBegin = File.data() + LocInfo.second;
Lexer RawLexer(Sources.getLocForStartOfFile(LocInfo.first),
Result.Context->getLangOpts(), File.begin(), TokenBegin,
File.end());
Token Tok;
llvm::Optional<Token> ConstTok;
while (!RawLexer.LexFromRawLexer(Tok)) {
if (Sources.isBeforeInTranslationUnit(Range.getEnd(), Tok.getLocation()))
break;
if (Tok.is(tok::raw_identifier)) {
IdentifierInfo &Info = Result.Context->Idents.get(StringRef(
Sources.getCharacterData(Tok.getLocation()), Tok.getLength()));
Tok.setIdentifierInfo(&Info);
Tok.setKind(Info.getTokenID());
}
if (Tok.is(tok::kw_const))
ConstTok = Tok;
}
return ConstTok;
}
void AvoidConstParamsInDecls::check(const MatchFinder::MatchResult &Result) {
const auto *Func = Result.Nodes.getNodeAs<FunctionDecl>("func");
const auto *Param = Result.Nodes.getNodeAs<ParmVarDecl>("param");
if (!Param->getType().isLocalConstQualified())
return;
auto Diag = diag(Param->getLocStart(),
"parameter %0 is const-qualified in the function "
"declaration; const-qualification of parameters only has an "
"effect in function definitions");
if (Param->getName().empty()) {
for (unsigned int i = 0; i < Func->getNumParams(); ++i) {
if (Param == Func->getParamDecl(i)) {
Diag << (i + 1);
break;
}
}
} else {
Diag << Param;
}
if (Param->getLocStart().isMacroID() != Param->getLocEnd().isMacroID()) {
// Do not offer a suggestion if the part of the variable declaration comes
// from a macro.
return;
}
CharSourceRange FileRange = Lexer::makeFileCharRange(
CharSourceRange::getTokenRange(getTypeRange(*Param)),
*Result.SourceManager, Result.Context->getLangOpts());
if (!FileRange.isValid())
return;
auto Tok = ConstTok(FileRange, Result);
if (!Tok)
return;
Diag << FixItHint::CreateRemoval(
CharSourceRange::getTokenRange(Tok->getLocation(), Tok->getLocation()));
}
} // namespace readability
} // namespace tidy
} // namespace clang
<|endoftext|>
|
<commit_before>/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/*************************************************************************
*
* 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: corbamaker.cxx,v $
* $Revision: 1.6 $
*
* 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_codemaker.hxx"
#include <stdio.h>
#include "sal/main.h"
#include <codemaker/typemanager.hxx>
#include <codemaker/dependency.hxx>
#include "corbaoptions.hxx"
#include "corbatype.hxx"
using namespace rtl;
sal_Bool produceAllTypes(const OString& typeName,
TypeManager& typeMgr,
TypeDependency& typeDependencies,
CorbaOptions* pOptions,
sal_Bool bFullScope,
FileStream& o,
TypeSet* pAllreadyDumped,
TypeSet* generatedConversion)
throw( CannotDumpException )
{
if (!produceType(typeName, typeMgr, typeDependencies, pOptions, o, pAllreadyDumped, generatedConversion))
{
fprintf(stderr, "%s ERROR: %s\n",
pOptions->getProgramName().getStr(),
OString("cannot dump Type '" + typeName + "'").getStr());
exit(99);
}
RegistryKey typeKey = typeMgr.getTypeKey(typeName);
RegistryKeyNames subKeys;
if (typeKey.getKeyNames(OUString(), subKeys))
return sal_False;
OString tmpName;
for (sal_uInt32 i=0; i < subKeys.getLength(); i++)
{
tmpName = OUStringToOString(subKeys.getElement(i), RTL_TEXTENCODING_UTF8);
if (pOptions->isValid("-B"))
tmpName = tmpName.copy(tmpName.indexOf('/', 1) + 1);
else
tmpName = tmpName.copy(1);
if (bFullScope)
{
if (!produceAllTypes(tmpName, typeMgr, typeDependencies, pOptions, sal_True, o, pAllreadyDumped, generatedConversion))
return sal_False;
} else
{
if (!produceType(tmpName, typeMgr, typeDependencies, pOptions, o, pAllreadyDumped, generatedConversion))
return sal_False;
}
}
return sal_True;
}
SAL_IMPLEMENT_MAIN_WITH_ARGS(argc, argv)
{
CorbaOptions options;
try
{
if (!options.initOptions(argc, argv))
{
exit(1);
}
}
catch( IllegalArgument& e)
{
fprintf(stderr, "Illegal option: %s\n", e.m_message.getStr());
exit(99);
}
RegistryTypeManager typeMgr;
TypeDependency typeDependencies;
if (!typeMgr.init(!options.isValid("-T"), options.getInputFiles()))
{
fprintf(stderr, "%s : init registries failed, check your registry files.\n", options.getProgramName().getStr());
exit(99);
}
if (options.isValid("-B"))
{
typeMgr.setBase(options.getOption("-B"));
}
try
{
TypeSet generatedConversion;
FileStream cppFile;
OString outPath;
if (options.isValid("-O"))
outPath = options.getOption("-O");
cppFile.open(outPath);
if(!cppFile.isValid())
{
OString message("cannot open ");
message += outPath + " for writing";
throw CannotDumpException(message);
}
if (options.isValid("-H"))
{
OString corbaHeader = options.getOption("-H");
cppFile << "#include <"
<< corbaHeader
<< ">\n\n";
CorbaType::dumpDefaultHxxIncludes(cppFile);
cppFile << "\n";
}
if (options.isValid("-T"))
{
OString tOption(options.getOption("-T"));
OString typeName, tmpName;
sal_Bool ret = sal_False;
sal_Int32 nIndex = 0;
do
{
typeName = tOption.getToken(0, ';', nIndex);
sal_Int32 nPos = typeName.lastIndexOf( '.' );
tmpName = typeName.copy( nPos != -1 ? nPos+1 : 0 );
if (tmpName == "*")
{
// produce this type and his scope, but the scope is not recursively generated.
if (typeName.equals("*"))
{
tmpName = "/";
} else
{
tmpName = typeName.copy(0, typeName.lastIndexOf('.')).replace('.', '/');
if (tmpName.getLength() == 0)
tmpName = "/";
else
tmpName.replace('.', '/');
}
ret = produceAllTypes(tmpName, typeMgr, typeDependencies, &options, sal_False, cppFile, NULL, &generatedConversion);
} else
{
// produce only this type
ret = produceType(typeName.replace('.', '/'), typeMgr, typeDependencies, &options, cppFile, NULL, &generatedConversion);
}
if (!ret)
{
fprintf(stderr, "%s ERROR: %s\n",
options.getProgramName().getStr(),
OString("cannot dump Type '" + typeName + "'").getStr());
exit(99);
}
} while( nIndex != -1 );
} else
{
// produce all types
if (!produceAllTypes("/", typeMgr, typeDependencies, &options, sal_True, cppFile, NULL, &generatedConversion))
{
fprintf(stderr, "%s ERROR: %s\n",
options.getProgramName().getStr(),
"an error occurs while dumping all types.");
exit(99);
}
}
cppFile << "namespace bonobobridge {\n"
<< "const ConversionInfo* get_conversion_functions() {\n"
<< " static ConversionInfo allFunctions[" << generatedConversion.size()+1<< "] = {\n";
for (TypeSet::iterator iter = generatedConversion.begin(); iter != generatedConversion.end(); iter++)
{
cppFile << " {\"" << (*iter).getStr() << "\""
<< ", &TC_" << (*iter).replace('/','_').getStr() << "_struct"
<< ", sizeof(" << (*iter).replace('/','_').getStr() << ")"
<< ", convert_b2u_" << (*iter).replace('/','_').getStr()
<< ", convert_u2b_" << (*iter).replace('/','_').getStr()
<< " },\n";
}
cppFile << " {NULL, NULL, 0 , NULL, NULL} };\n"
<< " return allFunctions;\n"
<< "}\n"
<< "}; // namespace bonobobridge\n";
cppFile.close();
}
catch( CannotDumpException& e)
{
fprintf(stderr, "%s ERROR: %s\n",
options.getProgramName().getStr(),
e.m_message.getStr());
exit(99);
}
return 0;
}
<commit_msg>INTEGRATION: CWS jsc21 (1.5.34); FILE MERGED 2008/04/23 09:48:52 jsc 1.5.34.2: RESYNC: (1.5-1.6); FILE MERGED 2008/02/13 08:54:56 jsc 1.5.34.1: #i72964# remove external header guards<commit_after>/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/*************************************************************************
*
* 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: corbamaker.cxx,v $
* $Revision: 1.7 $
*
* 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_codemaker.hxx"
#include <stdio.h>
#include "sal/main.h"
#include <codemaker/typemanager.hxx>
#include <codemaker/dependency.hxx>
#include "corbaoptions.hxx"
#include "corbatype.hxx"
using namespace rtl;
sal_Bool produceAllTypes(const OString& typeName,
TypeManager& typeMgr,
TypeDependency& typeDependencies,
CorbaOptions* pOptions,
sal_Bool bFullScope,
FileStream& o,
TypeSet* pAllreadyDumped,
TypeSet* generatedConversion)
throw( CannotDumpException )
{
if (!produceType(typeName, typeMgr, typeDependencies, pOptions, o, pAllreadyDumped, generatedConversion))
{
fprintf(stderr, "%s ERROR: %s\n",
pOptions->getProgramName().getStr(),
OString("cannot dump Type '" + typeName + "'").getStr());
exit(99);
}
RegistryKey typeKey = typeMgr.getTypeKey(typeName);
RegistryKeyNames subKeys;
if (typeKey.getKeyNames(OUString(), subKeys))
return sal_False;
OString tmpName;
for (sal_uInt32 i=0; i < subKeys.getLength(); i++)
{
tmpName = OUStringToOString(subKeys.getElement(i), RTL_TEXTENCODING_UTF8);
if (pOptions->isValid("-B"))
tmpName = tmpName.copy(tmpName.indexOf('/', 1) + 1);
else
tmpName = tmpName.copy(1);
if (bFullScope)
{
if (!produceAllTypes(tmpName, typeMgr, typeDependencies, pOptions, sal_True, o, pAllreadyDumped, generatedConversion))
return sal_False;
} else
{
if (!produceType(tmpName, typeMgr, typeDependencies, pOptions, o, pAllreadyDumped, generatedConversion))
return sal_False;
}
}
return sal_True;
}
SAL_IMPLEMENT_MAIN_WITH_ARGS(argc, argv)
{
CorbaOptions options;
try
{
if (!options.initOptions(argc, argv))
{
exit(1);
}
}
catch( IllegalArgument& e)
{
fprintf(stderr, "Illegal option: %s\n", e.m_message.getStr());
exit(99);
}
RegistryTypeManager typeMgr;
TypeDependency typeDependencies;
if (!typeMgr.init(!options.isValid("-T"), options.getInputFiles()))
{
fprintf(stderr, "%s : init registries failed, check your registry files.\n", options.getProgramName().getStr());
exit(99);
}
if (options.isValid("-B"))
{
typeMgr.setBase(options.getOption("-B"));
}
try
{
TypeSet generatedConversion;
FileStream cppFile;
OString outPath;
if (options.isValid("-O"))
outPath = options.getOption("-O");
cppFile.open(outPath);
if(!cppFile.isValid())
{
OString message("cannot open ");
message += outPath + " for writing";
throw CannotDumpException(message);
}
if (options.isValid("-H"))
{
OString corbaHeader = options.getOption("-H");
cppFile << "#include <"
<< corbaHeader
<< ">\n\n";
CorbaType::dumpDefaultHxxIncludes(cppFile);
cppFile << "\n";
}
if (options.isValid("-T"))
{
OString tOption(options.getOption("-T"));
OString typeName, tmpName;
sal_Bool ret = sal_False;
sal_Int32 nIndex = 0;
do
{
typeName = tOption.getToken(0, ';', nIndex);
sal_Int32 nPos = typeName.lastIndexOf( '.' );
tmpName = typeName.copy( nPos != -1 ? nPos+1 : 0 );
if (tmpName == "*")
{
// produce this type and his scope, but the scope is not recursively generated.
if (typeName.equals("*"))
{
tmpName = "/";
} else
{
tmpName = typeName.copy(0, typeName.lastIndexOf('.')).replace('.', '/');
if (tmpName.getLength() == 0)
tmpName = "/";
else
tmpName.replace('.', '/');
}
ret = produceAllTypes(tmpName, typeMgr, typeDependencies, &options, sal_False, cppFile, NULL, &generatedConversion);
} else
{
// produce only this type
ret = produceType(typeName.replace('.', '/'), typeMgr, typeDependencies, &options, cppFile, NULL, &generatedConversion);
}
if (!ret)
{
fprintf(stderr, "%s ERROR: %s\n",
options.getProgramName().getStr(),
OString("cannot dump Type '" + typeName + "'").getStr());
exit(99);
}
} while( nIndex != -1 );
} else
{
// produce all types
if (!produceAllTypes("/", typeMgr, typeDependencies, &options, sal_True, cppFile, NULL, &generatedConversion))
{
fprintf(stderr, "%s ERROR: %s\n",
options.getProgramName().getStr(),
"an error occurs while dumping all types.");
exit(99);
}
}
cppFile << "namespace bonobobridge {\n"
<< "const ConversionInfo* get_conversion_functions() {\n"
<< " static ConversionInfo allFunctions[" << generatedConversion.size()+1<< "] = {\n";
for (TypeSet::iterator iter = generatedConversion.begin(); iter != generatedConversion.end(); iter++)
{
cppFile << " {\"" << (*iter).getStr() << "\""
<< ", &TC_" << (*iter).replace('/','_').getStr() << "_struct"
<< ", sizeof(" << (*iter).replace('/','_').getStr() << ")"
<< ", convert_b2u_" << (*iter).replace('/','_').getStr()
<< ", convert_u2b_" << (*iter).replace('/','_').getStr()
<< " },\n";
}
cppFile << " {NULL, NULL, 0 , NULL, NULL} };\n"
<< " return allFunctions;\n"
<< "}\n"
<< "}; // namespace bonobobridge\n";
cppFile.close();
}
catch( CannotDumpException& e)
{
fprintf(stderr, "%s ERROR: %s\n",
options.getProgramName().getStr(),
e.m_message.getStr());
exit(99);
}
return 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: accessibletexthelper.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: vg $ $Date: 2003-04-24 17:26:09 $
*
* 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 COMPHELPER_ACCESSIBLE_TEXT_HELPER_HXX
#define COMPHELPER_ACCESSIBLE_TEXT_HELPER_HXX
#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLETEXT_HPP_
#include <com/sun/star/accessibility/XAccessibleText.hpp>
#endif
#ifndef _COM_SUN_STAR_I18N_XBREAKITERATOR_HPP_
#include <com/sun/star/i18n/XBreakIterator.hpp>
#endif
#ifndef _COM_SUN_STAR_I18N_XCHARACTERCLASSIFICATION_HPP_
#include <com/sun/star/i18n/XCharacterClassification.hpp>
#endif
#ifndef COMPHELPER_ACCESSIBLE_COMPONENT_HELPER_HXX
#include <comphelper/accessiblecomponenthelper.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
//..............................................................................
namespace comphelper
{
//..............................................................................
//==============================================================================
// OCommonAccessibleText
//==============================================================================
/** base class encapsulating common functionality for the helper classes implementing
the XAccessibleText
*/
class OCommonAccessibleText
{
private:
::com::sun::star::uno::Reference < ::com::sun::star::i18n::XBreakIterator > m_xBreakIter;
::com::sun::star::uno::Reference < ::com::sun::star::i18n::XCharacterClassification > m_xCharClass;
protected:
OCommonAccessibleText();
~OCommonAccessibleText();
::com::sun::star::uno::Reference < ::com::sun::star::i18n::XBreakIterator > implGetBreakIterator();
::com::sun::star::uno::Reference < ::com::sun::star::i18n::XCharacterClassification > implGetCharacterClassification();
sal_Bool implIsValidBoundary( ::com::sun::star::i18n::Boundary& rBoundary, sal_Int32 nLength );
virtual sal_Bool implIsValidIndex( sal_Int32 nIndex, sal_Int32 nLength );
virtual sal_Bool implIsValidRange( sal_Int32 nStartIndex, sal_Int32 nEndIndex, sal_Int32 nLength );
virtual ::rtl::OUString implGetText() = 0;
virtual ::com::sun::star::lang::Locale implGetLocale() = 0;
virtual void implGetSelection( sal_Int32& nStartIndex, sal_Int32& nEndIndex ) = 0;
virtual void implGetGlyphBoundary( ::com::sun::star::i18n::Boundary& rBoundary, sal_Int32 nIndex );
virtual sal_Bool implGetWordBoundary( ::com::sun::star::i18n::Boundary& rBoundary, sal_Int32 nIndex );
virtual void implGetSentenceBoundary( ::com::sun::star::i18n::Boundary& rBoundary, sal_Int32 nIndex );
virtual void implGetParagraphBoundary( ::com::sun::star::i18n::Boundary& rBoundary, sal_Int32 nIndex );
virtual void implGetLineBoundary( ::com::sun::star::i18n::Boundary& rBoundary, sal_Int32 nIndex );
/** non-virtual versions of the methods
*/
sal_Unicode SAL_CALL getCharacter( sal_Int32 nIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
sal_Int32 SAL_CALL getCharacterCount() throw (::com::sun::star::uno::RuntimeException);
::rtl::OUString SAL_CALL getSelectedText() throw (::com::sun::star::uno::RuntimeException);
sal_Int32 SAL_CALL getSelectionStart() throw (::com::sun::star::uno::RuntimeException);
sal_Int32 SAL_CALL getSelectionEnd() throw (::com::sun::star::uno::RuntimeException);
::rtl::OUString SAL_CALL getText() throw (::com::sun::star::uno::RuntimeException);
::rtl::OUString SAL_CALL getTextRange( sal_Int32 nStartIndex, sal_Int32 nEndIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
::rtl::OUString SAL_CALL getTextAtIndex( sal_Int32 nIndex, sal_Int16 aTextType ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
::rtl::OUString SAL_CALL getTextBeforeIndex( sal_Int32 nIndex, sal_Int16 aTextType ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
::rtl::OUString SAL_CALL getTextBehindIndex( sal_Int32 nIndex, sal_Int16 aTextType ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
public:
/** Helper method, that detects the difference between
two strings and returns the deleted selection and
the inserted selection if available.
@returns true if there are differences between the
two strings and false if both are equal
@see ::com::sun::star::accessibility::AccessibleEventId
::com::sun::star::awt::Selection
*/
static bool implInitTextChangedEvent(
const rtl::OUString& rOldString,
const rtl::OUString& rNewString,
/*out*/ ::com::sun::star::uno::Any& rDeleteSelection,
/*out*/ ::com::sun::star::uno::Any& rInsertSelection); // throw()
};
//==============================================================================
// OAccessibleTextHelper
//==============================================================================
typedef ::cppu::ImplHelper1 < ::com::sun::star::accessibility::XAccessibleText
> OAccessibleTextHelper_Base;
/** a helper class for implementing an AccessibleExtendedComponent which at the same time
supports an XAccessibleText interface
*/
class OAccessibleTextHelper : public OAccessibleExtendedComponentHelper,
public OCommonAccessibleText,
public OAccessibleTextHelper_Base
{
protected:
OAccessibleTextHelper();
// see the respective base class ctor for an extensive comment on this, please
OAccessibleTextHelper( IMutex* _pExternalLock );
public:
// XInterface
DECLARE_XINTERFACE( )
// XTypeProvider
DECLARE_XTYPEPROVIDER( )
// XAccessibleText
virtual sal_Unicode SAL_CALL getCharacter( sal_Int32 nIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getCharacterCount() throw (::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getSelectedText() throw (::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getSelectionStart() throw (::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getSelectionEnd() throw (::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getText() throw (::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getTextRange( sal_Int32 nStartIndex, sal_Int32 nEndIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getTextAtIndex( sal_Int32 nIndex, sal_Int16 aTextType ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getTextBeforeIndex( sal_Int32 nIndex, sal_Int16 aTextType ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getTextBehindIndex( sal_Int32 nIndex, sal_Int16 aTextType ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
};
//..............................................................................
} // namespace comphelper
//..............................................................................
#endif // COMPHELPER_ACCESSIBLE_TEXT_HELPER_HXX
// -----------------------------------------------------------------------------
//
// OAccessibleTextHelper is a helper class for implementing the
// XAccessibleText interface.
//
// The following methods have a default implementation:
//
// getCharacter
// getCharacterCount
// getSelectedText
// getSelectionStart
// getSelectionEnd
// getText
// getTextRange
// getTextAtIndex
// getTextBeforeIndex
// getTextBehindIndex
//
// The following methods must be overriden by derived classes:
//
// implGetText
// implGetLocale
// implGetSelection
// getCaretPosition
// setCaretPosition
// getCharacterAttributes
// getCharacterBounds
// getIndexAtPoint
// setSelection
// copyText
//
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS uaa03 (1.4.8); FILE MERGED 2003/05/21 15:41:34 mt 1.4.8.1: #i14623# UAA finalization<commit_after>/*************************************************************************
*
* $RCSfile: accessibletexthelper.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: vg $ $Date: 2003-05-22 13:33:28 $
*
* 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 COMPHELPER_ACCESSIBLE_TEXT_HELPER_HXX
#define COMPHELPER_ACCESSIBLE_TEXT_HELPER_HXX
#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLETEXT_HPP_
#include <com/sun/star/accessibility/XAccessibleText.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_TEXTSEGMENT_HPP_
#include <com/sun/star/accessibility/TextSegment.hpp>
#endif
#ifndef _COM_SUN_STAR_I18N_XBREAKITERATOR_HPP_
#include <com/sun/star/i18n/XBreakIterator.hpp>
#endif
#ifndef _COM_SUN_STAR_I18N_XCHARACTERCLASSIFICATION_HPP_
#include <com/sun/star/i18n/XCharacterClassification.hpp>
#endif
#ifndef COMPHELPER_ACCESSIBLE_COMPONENT_HELPER_HXX
#include <comphelper/accessiblecomponenthelper.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
//..............................................................................
namespace comphelper
{
//..............................................................................
//==============================================================================
// OCommonAccessibleText
//==============================================================================
/** base class encapsulating common functionality for the helper classes implementing
the XAccessibleText
*/
class OCommonAccessibleText
{
private:
::com::sun::star::uno::Reference < ::com::sun::star::i18n::XBreakIterator > m_xBreakIter;
::com::sun::star::uno::Reference < ::com::sun::star::i18n::XCharacterClassification > m_xCharClass;
protected:
OCommonAccessibleText();
~OCommonAccessibleText();
::com::sun::star::uno::Reference < ::com::sun::star::i18n::XBreakIterator > implGetBreakIterator();
::com::sun::star::uno::Reference < ::com::sun::star::i18n::XCharacterClassification > implGetCharacterClassification();
sal_Bool implIsValidBoundary( ::com::sun::star::i18n::Boundary& rBoundary, sal_Int32 nLength );
virtual sal_Bool implIsValidIndex( sal_Int32 nIndex, sal_Int32 nLength );
virtual sal_Bool implIsValidRange( sal_Int32 nStartIndex, sal_Int32 nEndIndex, sal_Int32 nLength );
virtual ::rtl::OUString implGetText() = 0;
virtual ::com::sun::star::lang::Locale implGetLocale() = 0;
virtual void implGetSelection( sal_Int32& nStartIndex, sal_Int32& nEndIndex ) = 0;
virtual void implGetGlyphBoundary( ::com::sun::star::i18n::Boundary& rBoundary, sal_Int32 nIndex );
virtual sal_Bool implGetWordBoundary( ::com::sun::star::i18n::Boundary& rBoundary, sal_Int32 nIndex );
virtual void implGetSentenceBoundary( ::com::sun::star::i18n::Boundary& rBoundary, sal_Int32 nIndex );
virtual void implGetParagraphBoundary( ::com::sun::star::i18n::Boundary& rBoundary, sal_Int32 nIndex );
virtual void implGetLineBoundary( ::com::sun::star::i18n::Boundary& rBoundary, sal_Int32 nIndex );
/** non-virtual versions of the methods
*/
sal_Unicode SAL_CALL getCharacter( sal_Int32 nIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
sal_Int32 SAL_CALL getCharacterCount() throw (::com::sun::star::uno::RuntimeException);
::rtl::OUString SAL_CALL getSelectedText() throw (::com::sun::star::uno::RuntimeException);
sal_Int32 SAL_CALL getSelectionStart() throw (::com::sun::star::uno::RuntimeException);
sal_Int32 SAL_CALL getSelectionEnd() throw (::com::sun::star::uno::RuntimeException);
::rtl::OUString SAL_CALL getText() throw (::com::sun::star::uno::RuntimeException);
::rtl::OUString SAL_CALL getTextRange( sal_Int32 nStartIndex, sal_Int32 nEndIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
::com::sun::star::accessibility::TextSegment SAL_CALL getTextAtIndex( sal_Int32 nIndex, sal_Int16 aTextType ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
::com::sun::star::accessibility::TextSegment SAL_CALL getTextBeforeIndex( sal_Int32 nIndex, sal_Int16 aTextType ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
::com::sun::star::accessibility::TextSegment SAL_CALL getTextBehindIndex( sal_Int32 nIndex, sal_Int16 aTextType ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
public:
/** Helper method, that detects the difference between
two strings and returns the deleted selection and
the inserted selection if available.
@returns true if there are differences between the
two strings and false if both are equal
@see ::com::sun::star::accessibility::AccessibleEventId
::com::sun::star::accessibility::TextSegment
*/
static bool implInitTextChangedEvent(
const rtl::OUString& rOldString,
const rtl::OUString& rNewString,
/*out*/ ::com::sun::star::uno::Any& rDeleted,
/*out*/ ::com::sun::star::uno::Any& rInserted); // throw()
};
//==============================================================================
// OAccessibleTextHelper
//==============================================================================
typedef ::cppu::ImplHelper1 < ::com::sun::star::accessibility::XAccessibleText
> OAccessibleTextHelper_Base;
/** a helper class for implementing an AccessibleExtendedComponent which at the same time
supports an XAccessibleText interface
*/
class OAccessibleTextHelper : public OAccessibleExtendedComponentHelper,
public OCommonAccessibleText,
public OAccessibleTextHelper_Base
{
protected:
OAccessibleTextHelper();
// see the respective base class ctor for an extensive comment on this, please
OAccessibleTextHelper( IMutex* _pExternalLock );
public:
// XInterface
DECLARE_XINTERFACE( )
// XTypeProvider
DECLARE_XTYPEPROVIDER( )
// XAccessibleText
virtual sal_Unicode SAL_CALL getCharacter( sal_Int32 nIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getCharacterCount() throw (::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getSelectedText() throw (::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getSelectionStart() throw (::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getSelectionEnd() throw (::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getText() throw (::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getTextRange( sal_Int32 nStartIndex, sal_Int32 nEndIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::accessibility::TextSegment SAL_CALL getTextAtIndex( sal_Int32 nIndex, sal_Int16 aTextType ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::accessibility::TextSegment SAL_CALL getTextBeforeIndex( sal_Int32 nIndex, sal_Int16 aTextType ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::accessibility::TextSegment SAL_CALL getTextBehindIndex( sal_Int32 nIndex, sal_Int16 aTextType ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
};
//..............................................................................
} // namespace comphelper
//..............................................................................
#endif // COMPHELPER_ACCESSIBLE_TEXT_HELPER_HXX
// -----------------------------------------------------------------------------
//
// OAccessibleTextHelper is a helper class for implementing the
// XAccessibleText interface.
//
// The following methods have a default implementation:
//
// getCharacter
// getCharacterCount
// getSelectedText
// getSelectionStart
// getSelectionEnd
// getText
// getTextRange
// getTextAtIndex
// getTextBeforeIndex
// getTextBehindIndex
//
// The following methods must be overriden by derived classes:
//
// implGetText
// implGetLocale
// implGetSelection
// getCaretPosition
// setCaretPosition
// getCharacterAttributes
// getCharacterBounds
// getIndexAtPoint
// setSelection
// copyText
//
// -----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief RX700 グループ Δ-Σモジュレータインタフェース定義
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2019 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/device.hpp"
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief DSMIF 定義
@param[in] base ベース・アドレス
@param[in] per ペリフェラル型
@param[in] ocdi 過電流検出割り込み
@param[in] sumei 合計電流エラー割り込み
@param[in] scdi 短絡検出割り込み
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <uint32_t base, peripheral per,
ICU::VECTOR_BL2 ocdi, ICU::VECTOR_BL2 sumei, ICU::VECTOR_BL2 scdi>
struct dsmif_t {
static const auto PERIPHERAL = per; ///< ペリフェラル型
static const auto OCD_VEC = ocdi; ///< 過電流検出割り込み
static const auto SUME_VEC = sumei; ///< 合計電流エラー割り込み
static const auto SCD_VEC = scdi; ///< 短絡検出割り込み
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief DSMIF 制御レジスタ (DSCR)
@param[in] ofs オフセット
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <uint32_t ofs>
struct dscr_t : public rw32_t<ofs> {
typedef rw32_t<ofs> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bit_rw_t <io_, bitpos::B0> FEN;
bit_rw_t <io_, bitpos::B1> CKDIR;
bits_rw_t<io_, bitpos::B4, 4> CKDIV;
bits_rw_t<io_, bitpos::B8, 2> CMSINC;
bits_rw_t<io_, bitpos::B12, 3> CMDEC;
bits_rw_t<io_, bitpos::B16, 4> CMSH;
bits_rw_t<io_, bitpos::B20, 2> OCSINC;
bits_rw_t<io_, bitpos::B24, 3> OCDEC;
bits_rw_t<io_, bitpos::B28, 4> OCSH;
};
static dscr_t<base + 0x00> DSCR;
};
typedef dsmif_t<0x000A0700, peripheral::PMGI0,
ICU::VECTOR_BL2::OCDI0, ICU::VECTOR_BL2::SUMEI0, ICU::VECTOR_BL2::SCDI0> DSMIF0;
typedef dsmif_t<0x000A0780, peripheral::PMGI1,
ICU::VECTOR_BL2::OCDI1, ICU::VECTOR_BL2::SUMEI1, ICU::VECTOR_BL2::SCDI1> DSMIF1;
}
<commit_msg>Update: The reality of the template when it is not optimized<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief RX700 グループ Δ-Σモジュレータインタフェース定義
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2019, 2020 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/device.hpp"
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief DSMIF 定義
@param[in] base ベース・アドレス
@param[in] per ペリフェラル型
@param[in] ocdi 過電流検出割り込み
@param[in] sumei 合計電流エラー割り込み
@param[in] scdi 短絡検出割り込み
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <uint32_t base, peripheral per,
ICU::VECTOR_BL2 ocdi, ICU::VECTOR_BL2 sumei, ICU::VECTOR_BL2 scdi>
struct dsmif_t {
static const auto PERIPHERAL = per; ///< ペリフェラル型
static const auto OCD_VEC = ocdi; ///< 過電流検出割り込み
static const auto SUME_VEC = sumei; ///< 合計電流エラー割り込み
static const auto SCD_VEC = scdi; ///< 短絡検出割り込み
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief DSMIF 制御レジスタ (DSCR)
@param[in] ofs オフセット
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <uint32_t ofs>
struct dscr_t : public rw32_t<ofs> {
typedef rw32_t<ofs> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bit_rw_t <io_, bitpos::B0> FEN;
bit_rw_t <io_, bitpos::B1> CKDIR;
bits_rw_t<io_, bitpos::B4, 4> CKDIV;
bits_rw_t<io_, bitpos::B8, 2> CMSINC;
bits_rw_t<io_, bitpos::B12, 3> CMDEC;
bits_rw_t<io_, bitpos::B16, 4> CMSH;
bits_rw_t<io_, bitpos::B20, 2> OCSINC;
bits_rw_t<io_, bitpos::B24, 3> OCDEC;
bits_rw_t<io_, bitpos::B28, 4> OCSH;
};
typedef dscr_t<base + 0x00> DSCR_;
static DSCR_ DSCR;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief DSMIF ステータスレジスタ (DSSR)
@param[in] ofs オフセット
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <uint32_t ofs>
struct dssr_t : public rw32_t<ofs> {
typedef rw32_t<ofs> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bit_rw_t <io_, bitpos::B0> OCF0;
bit_rw_t <io_, bitpos::B1> OCF1;
bit_rw_t <io_, bitpos::B2> OCF2;
bit_rw_t <io_, bitpos::B4> SCF0;
bit_rw_t <io_, bitpos::B5> SCF1;
bit_rw_t <io_, bitpos::B6> SCF2;
bit_rw_t <io_, bitpos::B8> SUMERR;
};
typedef dssr_t<base + 0x04> DSSR_;
static DSSR_ DSSR;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 過電流検出下基準値レジスタ (OCLTR)
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
typedef rw32_t<base + 0x08> OCLTR_;
static OCLTR_ OCLTR;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 過電流検出上基準値レジスタ (OCHTR)
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
typedef rw32_t<base + 0x0C> OCHTR_;
static OCHTR_ OCHTR;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 短絡検出下基準値レジスタ (SCLTR)
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
typedef rw32_t<base + 0x10> SCLTR_;
static SCLTR_ SCLTR;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 短絡検出上基準値レジスタ (SCHTR)
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
typedef rw32_t<base + 0x14> SCHTR_;
static SCHTR_ SCHTR;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 合計電流エラー検出下基準値レジスタ (SUMLTR)
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
typedef rw32_t<base + 0x18> SUMLTR_;
static SUMLTR_ SUMLTR;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 合計電流エラー検出上基準値レジスタ (SUMHTR)
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
typedef rw32_t<base + 0x18> SUMHTR_;
static SUMHTR_ SUMHTR;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief チャネル x 電流データレジスタ (CDRx) (x = 0 ~ 2)
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
typedef rw32_t<base + 0x20> CDR0_;
static CDR0_ CDR0;
typedef rw32_t<base + 0x30> CDR1_;
static CDR1_ CDR1;
typedef rw32_t<base + 0x40> CDR2_;
static CDR2_ CDR2;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief チャネル x 山電流データレジスタ (CCDRx) (x = 0 ~ 2)
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
typedef rw32_t<base + 0x24> CCDR0_;
static CCDR0_ CCDR0;
typedef rw32_t<base + 0x34> CCDR1_;
static CCDR1_ CCDR1;
typedef rw32_t<base + 0x44> CCDR2_;
static CCDR2_ CCDR2;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief チャネル x 谷電流データレジスタ (TCDRx) (x = 0 ~ 2)
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
typedef rw32_t<base + 0x28> TCDR0_;
static TCDR0_ TCDR0;
typedef rw32_t<base + 0x38> TCDR1_;
static TCDR1_ TCDR1;
typedef rw32_t<base + 0x48> TCDR2_;
static TCDR2_ TCDR2;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief チャネル x 過電流検出用データレジスタ (OCDRx) (x = 0 ~ 2)
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
typedef rw32_t<base + 0x2C> OCDR0_;
static OCDR0_ OCDR0;
typedef rw32_t<base + 0x3C> OCDR1_;
static OCDR1_ OCDR1;
typedef rw32_t<base + 0x4C> OCDR2_;
static OCDR2_ OCDR2;
};
typedef dsmif_t<0x000A0700, peripheral::DSMIF0,
ICU::VECTOR_BL2::OCDI0, ICU::VECTOR_BL2::SUMEI0, ICU::VECTOR_BL2::SCDI0> DSMIF0;
typedef dsmif_t<0x000A0780, peripheral::DSMIF1,
ICU::VECTOR_BL2::OCDI1, ICU::VECTOR_BL2::SUMEI1, ICU::VECTOR_BL2::SCDI1> DSMIF1;
template <uint32_t base, peripheral per, ICU::VECTOR_BL2 ocdi, ICU::VECTOR_BL2 sumei, ICU::VECTOR_BL2 scdi> typename dsmif_t<base, per, ocdi, sumei, scdi>::DSCR_ dsmif_t<base, per, ocdi, sumei, scdi>::DSCR;
template <uint32_t base, peripheral per, ICU::VECTOR_BL2 ocdi, ICU::VECTOR_BL2 sumei, ICU::VECTOR_BL2 scdi> typename dsmif_t<base, per, ocdi, sumei, scdi>::DSSR_ dsmif_t<base, per, ocdi, sumei, scdi>::DSSR;
template <uint32_t base, peripheral per, ICU::VECTOR_BL2 ocdi, ICU::VECTOR_BL2 sumei, ICU::VECTOR_BL2 scdi> typename dsmif_t<base, per, ocdi, sumei, scdi>::OCLTR_ dsmif_t<base, per, ocdi, sumei, scdi>::OCLTR;
template <uint32_t base, peripheral per, ICU::VECTOR_BL2 ocdi, ICU::VECTOR_BL2 sumei, ICU::VECTOR_BL2 scdi> typename dsmif_t<base, per, ocdi, sumei, scdi>::OCHTR_ dsmif_t<base, per, ocdi, sumei, scdi>::OCHTR;
template <uint32_t base, peripheral per, ICU::VECTOR_BL2 ocdi, ICU::VECTOR_BL2 sumei, ICU::VECTOR_BL2 scdi> typename dsmif_t<base, per, ocdi, sumei, scdi>::SCLTR_ dsmif_t<base, per, ocdi, sumei, scdi>::SCLTR;
template <uint32_t base, peripheral per, ICU::VECTOR_BL2 ocdi, ICU::VECTOR_BL2 sumei, ICU::VECTOR_BL2 scdi> typename dsmif_t<base, per, ocdi, sumei, scdi>::SCHTR_ dsmif_t<base, per, ocdi, sumei, scdi>::SCHTR;
template <uint32_t base, peripheral per, ICU::VECTOR_BL2 ocdi, ICU::VECTOR_BL2 sumei, ICU::VECTOR_BL2 scdi> typename dsmif_t<base, per, ocdi, sumei, scdi>::SUMLTR_ dsmif_t<base, per, ocdi, sumei, scdi>::SUMLTR;
template <uint32_t base, peripheral per, ICU::VECTOR_BL2 ocdi, ICU::VECTOR_BL2 sumei, ICU::VECTOR_BL2 scdi> typename dsmif_t<base, per, ocdi, sumei, scdi>::SUMHTR_ dsmif_t<base, per, ocdi, sumei, scdi>::SUMHTR;
template <uint32_t base, peripheral per, ICU::VECTOR_BL2 ocdi, ICU::VECTOR_BL2 sumei, ICU::VECTOR_BL2 scdi> typename dsmif_t<base, per, ocdi, sumei, scdi>::CDR0_ dsmif_t<base, per, ocdi, sumei, scdi>::CDR0;
template <uint32_t base, peripheral per, ICU::VECTOR_BL2 ocdi, ICU::VECTOR_BL2 sumei, ICU::VECTOR_BL2 scdi> typename dsmif_t<base, per, ocdi, sumei, scdi>::CDR1_ dsmif_t<base, per, ocdi, sumei, scdi>::CDR1;
template <uint32_t base, peripheral per, ICU::VECTOR_BL2 ocdi, ICU::VECTOR_BL2 sumei, ICU::VECTOR_BL2 scdi> typename dsmif_t<base, per, ocdi, sumei, scdi>::CDR2_ dsmif_t<base, per, ocdi, sumei, scdi>::CDR2;
template <uint32_t base, peripheral per, ICU::VECTOR_BL2 ocdi, ICU::VECTOR_BL2 sumei, ICU::VECTOR_BL2 scdi> typename dsmif_t<base, per, ocdi, sumei, scdi>::CCDR0_ dsmif_t<base, per, ocdi, sumei, scdi>::CCDR0;
template <uint32_t base, peripheral per, ICU::VECTOR_BL2 ocdi, ICU::VECTOR_BL2 sumei, ICU::VECTOR_BL2 scdi> typename dsmif_t<base, per, ocdi, sumei, scdi>::CCDR1_ dsmif_t<base, per, ocdi, sumei, scdi>::CCDR1;
template <uint32_t base, peripheral per, ICU::VECTOR_BL2 ocdi, ICU::VECTOR_BL2 sumei, ICU::VECTOR_BL2 scdi> typename dsmif_t<base, per, ocdi, sumei, scdi>::CCDR2_ dsmif_t<base, per, ocdi, sumei, scdi>::CCDR2;
template <uint32_t base, peripheral per, ICU::VECTOR_BL2 ocdi, ICU::VECTOR_BL2 sumei, ICU::VECTOR_BL2 scdi> typename dsmif_t<base, per, ocdi, sumei, scdi>::TCDR0_ dsmif_t<base, per, ocdi, sumei, scdi>::TCDR0;
template <uint32_t base, peripheral per, ICU::VECTOR_BL2 ocdi, ICU::VECTOR_BL2 sumei, ICU::VECTOR_BL2 scdi> typename dsmif_t<base, per, ocdi, sumei, scdi>::TCDR1_ dsmif_t<base, per, ocdi, sumei, scdi>::TCDR1;
template <uint32_t base, peripheral per, ICU::VECTOR_BL2 ocdi, ICU::VECTOR_BL2 sumei, ICU::VECTOR_BL2 scdi> typename dsmif_t<base, per, ocdi, sumei, scdi>::TCDR2_ dsmif_t<base, per, ocdi, sumei, scdi>::TCDR2;
template <uint32_t base, peripheral per, ICU::VECTOR_BL2 ocdi, ICU::VECTOR_BL2 sumei, ICU::VECTOR_BL2 scdi> typename dsmif_t<base, per, ocdi, sumei, scdi>::OCDR0_ dsmif_t<base, per, ocdi, sumei, scdi>::OCDR0;
template <uint32_t base, peripheral per, ICU::VECTOR_BL2 ocdi, ICU::VECTOR_BL2 sumei, ICU::VECTOR_BL2 scdi> typename dsmif_t<base, per, ocdi, sumei, scdi>::OCDR1_ dsmif_t<base, per, ocdi, sumei, scdi>::OCDR1;
template <uint32_t base, peripheral per, ICU::VECTOR_BL2 ocdi, ICU::VECTOR_BL2 sumei, ICU::VECTOR_BL2 scdi> typename dsmif_t<base, per, ocdi, sumei, scdi>::OCDR2_ dsmif_t<base, per, ocdi, sumei, scdi>::OCDR2;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief DSMIF 定義
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class _>
struct dsmif_ {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief DSMIF クロック制御レジスタ (DSCCR)
@param[in] ofs オフセット
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <uint32_t ofs>
struct dsccr_t : public rw32_t<ofs> {
typedef rw32_t<ofs> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bit_rw_t<io_, bitpos::B0> EDGE0;
bit_rw_t<io_, bitpos::B1> EDGE1;
bit_rw_t<io_, bitpos::B2> EDGE2;
bit_rw_t<io_, bitpos::B3> EDGE3;
bit_rw_t<io_, bitpos::B4> EDGE4;
bit_rw_t<io_, bitpos::B5> EDGE5;
};
typedef dsccr_t<0x000A07E0> DSCCR_;
static DSCCR_ DSCCR;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief DSMIF チャネル制御レジスタ (DSCHR)
@param[in] ofs オフセット
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <uint32_t ofs>
struct dschr_t : public rw32_t<ofs> {
typedef rw32_t<ofs> io_;
using io_::operator =;
using io_::operator ();
using io_::operator |=;
using io_::operator &=;
bit_rw_t<io_, bitpos::B0> EDGE0;
bit_rw_t<io_, bitpos::B1> EDGE1;
bit_rw_t<io_, bitpos::B2> EDGE2;
bit_rw_t<io_, bitpos::B3> EDGE3;
bit_rw_t<io_, bitpos::B4> EDGE4;
bit_rw_t<io_, bitpos::B5> EDGE5;
};
typedef dschr_t<0x000A07E4> DSCHR_;
static DSCHR_ DSCHR;
};
typedef dsmif_<void> DSMIF;
template <class _> typename dsmif_<_>::DSCCR_ dsmif_<_>::DSCCR;
template <class _> typename dsmif_<_>::DSCHR_ dsmif_<_>::DSCHR;
}
<|endoftext|>
|
<commit_before>#include <cmath>
#include <iostream>
#include <cstdlib>
#include "Block.h"
#include "Font.hpp"
int main()
{
//okno
sf::RenderWindow okno(sf::VideoMode(400, 400), "2048", sf::Style::Titlebar && sf::Style::Default);
//pojedynczy klocek Texture -- > tylko to rysowania obrazow
sf::Texture textura;
if (!textura.loadFromFile("klocek.png"))
return EXIT_FAILURE;
textura.loadFromFile("klocek.png");
//stworzenie obiektu one klasy Block
// w ktrej wektor obiektw klasy Block
Block* one = new Block;
one->singleBlock.setTexture(textura);
std::cout << "Rozmiar tablicy: " << one->allBlocks.size() << std::endl;
one->search();
while (okno.isOpen())
{
sf::Event event;
while (okno.pollEvent(event))
{
if (event.type == sf::Event::Closed)
okno.close();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
for(auto i: one->allBlocks){
if (i->posX != 300.0) {
okno.clear(sf::Color::Black);
i->singleBlock.move(1, 1);
i->singleBlock.move(-0.25, 0);
i->posX = 300;
i->singleBlock.setPosition(i->posX, i->posY);
okno.display();
}
}
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
for (auto i : one->allBlocks) {
if (i->posX != 0.0) {
okno.clear(sf::Color::Black);
i->singleBlock.move(-0.25, 0);
i->posX = 0;
i->singleBlock.setPosition(i->posX, i->posY);
okno.display();
}
}
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
for (auto i : one->allBlocks) {
if (i->posY != 0.0) {
okno.clear(sf::Color::Black);
i->singleBlock.move(0, -0.25);
i->posY = 0;
i->singleBlock.setPosition(i->posX, i->posY);
okno.display();
}
}
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
for (auto i : one->allBlocks) {
if (i->posY != 300.0) {
okno.clear(sf::Color::Black);
i->singleBlock.move(0, 0.25);
i->posY = 300;
i->singleBlock.setPosition(i->posX, i->posY);
okno.display();
}
}
}
sf::Font font;
if (!font.loadFromFile("arial.ttf"))
return EXIT_FAILURE;
okno.clear(sf::Color::Black);
sf::Text text;
text.setFont(font);
text.setString("Holololololololo");
text.setCharacterSize(100);
text.setColor(sf::Color::Red);
for (auto i = one->allBlocks.begin();
i < one->allBlocks.end(); i++) {
one->singleBlock.setPosition((*i)->posX, (*i)->posY);
okno.draw(one->singleBlock);
(*i)->text = text;
(*i)->text.setPosition((*i)->posX+10, (*i)->posY-10);
okno.draw((*i)->text);
}
okno.display();
}
return 0;
}<commit_msg>Checking<commit_after>#include <cmath>
#include <iostream>
#include <cstdlib>
#include "Block.h"
#include "Font.hpp"
int main()
{
//okno
sf::RenderWindow okno(sf::VideoMode(400, 400), "2048", sf::Style::Titlebar && sf::Style::Default);
//pojedynczy klocek Texture -- > tylko to rysowania obrazow
sf::Texture textura;
if (!textura.loadFromFile("klocek.png"))
return EXIT_FAILURE;
textura.loadFromFile("klocek.png");
//stworzenie obiektu one klasy Block
// w ktrej wektor obiektw klasy Block
Block* one = new Block;
one->singleBlock.setTexture(textura);
std::cout << "Rozmiar tablicy: " << one->allBlocks.size() << std::endl;
one->search();
while (okno.isOpen())
{
sf::Event event;
while (okno.pollEvent(event))
{
if (event.type == sf::Event::Closed)
okno.close();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
for(auto i: one->allBlocks){
if (i->posX != 300.0) {
okno.clear(sf::Color::Black);
i->singleBlock.move(1, 1);
i->singleBlock.move(-0.25, 0);
i->posX = 300;
i->singleBlock.setPosition(i->posX, i->posY);
okno.display();
}
}
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
for (auto i : one->allBlocks) {
if (i->posX != 0.0) {
okno.clear(sf::Color::Black);
i->singleBlock.move(-0.25, 0);
i->posX = 0;
i->singleBlock.setPosition(i->posX, i->posY);
okno.display();
}
}
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
for (auto i : one->allBlocks) {
if (i->posY != 0.0) {
okno.clear(sf::Color::Black);
i->singleBlock.move(0, -0.25);
i->posY = 0;
i->singleBlock.setPosition(i->posX, i->posY);
okno.display();
}
}
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
for (auto i : one->allBlocks) {
if (i->posY != 300.0) {
okno.clear(sf::Color::Black);
i->singleBlock.move(0, 0.25);
i->posY = 300;
i->singleBlock.setPosition(i->posX, i->posY);
okno.display();
}
}
}
sf::Font font;
if (!font.loadFromFile("arial.ttf"))
return EXIT_FAILURE;
okno.clear(sf::Color::Black);
sf::Text text;
text.setFont(font);
text.setString("H");
text.setCharacterSize(100);
text.setColor(sf::Color::Red);
for (auto i = one->allBlocks.begin();
i < one->allBlocks.end(); i++) {
one->singleBlock.setPosition((*i)->posX, (*i)->posY);
okno.draw(one->singleBlock);
(*i)->text = text;
(*i)->text.setPosition((*i)->posX+10, (*i)->posY-10);
okno.draw((*i)->text);
}
okno.display();
}
return 0;
}<|endoftext|>
|
<commit_before>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "filament_user.h"
#include <fclaw2d_forestclaw.h>
#include <fclaw2d_clawpatch.h>
void filament_link_solvers(fclaw2d_domain_t *domain)
{
const user_options_t* user = filament_user_get_options(domain);
const amr_options_t* gparms = fclaw2d_forestclaw_get_options(domain);
// fclaw2d_init_vtable();
if (user->claw_version == 4)
{
fc2d_clawpack46_vt()->setprob = &SETPROB;
fc2d_clawpack46_vt()->qinit = &CLAWPACK46_QINIT;
if (gparms->manifold)
{
fclaw2d_patch_vt()->patch_setup = &filament_patch_setup_manifold;
fc2d_clawpack46_vt()->rpn2 = &CLAWPACK46_RPN2ADV_MANIFOLD;
fc2d_clawpack46_vt()->rpt2 = &CLAWPACK46_RPT2ADV_MANIFOLD;
if (user->example == 2)
{
/* Avoid tagging block corners in 5 patch example*/
fclaw2d_clawpatch_vt()->fort_tag4refinement = &CLAWPACK46_TAG4REFINEMENT;
fclaw2d_clawpatch_vt()->fort_tag4coarsening = &CLAWPACK46_TAG4COARSENING;
}
}
else
{
fc2d_clawpack46_vt()->setaux = &CLAWPACK46_SETAUX; /* Used in non-manifold case */
fc2d_clawpack46_vt()->rpn2 = &CLAWPACK46_RPN2ADV;
fc2d_clawpack46_vt()->rpt2 = &CLAWPACK46_RPT2ADV;
}
}
else if (user->claw_version == 5)
{
fc2d_clawpack5_vt()->setprob = &SETPROB;
fc2d_clawpack5_vt()->qinit = &CLAWPACK5_QINIT;
if (gparms->manifold)
{
fclaw2d_patch_vt()->patch_setup = &filament_patch_setup_manifold;
fc2d_clawpack5_vt()->rpn2 = &CLAWPACK5_RPN2ADV_MANIFOLD;
fc2d_clawpack5_vt()->rpt2 = &CLAWPACK5_RPT2ADV_MANIFOLD;
if (user->example == 2)
{
/* Avoid tagging block corners in 5 patch example*/
fclaw2d_clawpatch_vt()->fort_tag4refinement = &CLAWPACK5_TAG4REFINEMENT;
fclaw2d_clawpatch_vt()->fort_tag4coarsening = &CLAWPACK5_TAG4COARSENING;
}
}
else
{
fc2d_clawpack5_vt()->setaux = &CLAWPACK5_SETAUX; /* Used in non-manifold case */
fc2d_clawpack5_vt()->rpn2 = &CLAWPACK5_RPN2ADV;
fc2d_clawpack5_vt()->rpt2 = &CLAWPACK5_RPT2ADV;
}
}
}
void filament_patch_setup_manifold(fclaw2d_domain_t *domain,
fclaw2d_patch_t *this_patch,
int this_block_idx,
int this_patch_idx)
{
const user_options_t* user = filament_user_get_options(domain);
int mx,my,mbc,maux;
double xlower,ylower,dx,dy;
double *aux,*xd,*yd,*zd,*area;
double *xp,*yp,*zp;
fclaw2d_clawpatch_grid_data(domain,this_patch,&mx,&my,&mbc,
&xlower,&ylower,&dx,&dy);
fclaw2d_clawpatch_metric_data(domain,this_patch,&xp,&yp,&zp,
&xd,&yd,&zd,&area);
if (user->claw_version == 4)
{
fc2d_clawpack46_define_auxarray(domain,this_patch);
fc2d_clawpack46_aux_data(domain,this_patch,&aux,&maux);
USER46_SETAUX_MANIFOLD(&mbc,&mx,&my,&xlower,&ylower,
&dx,&dy,&maux,aux,&this_block_idx,
xd,yd,zd,area);
}
else if (user->claw_version == 5)
{
fc2d_clawpack5_define_auxarray(domain,this_patch);
fc2d_clawpack5_aux_data(domain,this_patch,&aux,&maux);
USER5_SETAUX_MANIFOLD(&mbc,&mx,&my,&xlower,&ylower,
&dx,&dy,&maux,aux,&this_block_idx,
xd,yd,zd,area);
}
}
<commit_msg>(filament) Update to reflect latest vtables<commit_after>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "filament_user.h"
#include <fclaw2d_forestclaw.h>
#include <fclaw2d_clawpatch.h>
void filament_link_solvers(fclaw2d_domain_t *domain)
{
const user_options_t* user = filament_user_get_options(domain);
const amr_options_t* gparms = fclaw2d_forestclaw_get_options(domain);
// fclaw2d_init_vtable();
if (user->claw_version == 4)
{
fc2d_clawpack46_vt()->setprob = &SETPROB;
fc2d_clawpack46_vt()->qinit = &CLAWPACK46_QINIT;
if (gparms->manifold)
{
fclaw2d_patch_vt()->setup = &filament_patch_setup_manifold;
fc2d_clawpack46_vt()->rpn2 = &CLAWPACK46_RPN2ADV_MANIFOLD;
fc2d_clawpack46_vt()->rpt2 = &CLAWPACK46_RPT2ADV_MANIFOLD;
if (user->example == 2)
{
/* Avoid tagging block corners in 5 patch example*/
fclaw2d_clawpatch_vt()->fort_tag4refinement = &CLAWPACK46_TAG4REFINEMENT;
fclaw2d_clawpatch_vt()->fort_tag4coarsening = &CLAWPACK46_TAG4COARSENING;
}
}
else
{
fc2d_clawpack46_vt()->setaux = &CLAWPACK46_SETAUX; /* Used in non-manifold case */
fc2d_clawpack46_vt()->rpn2 = &CLAWPACK46_RPN2ADV;
fc2d_clawpack46_vt()->rpt2 = &CLAWPACK46_RPT2ADV;
}
}
else if (user->claw_version == 5)
{
fc2d_clawpack5_vt()->setprob = &SETPROB;
fc2d_clawpack5_vt()->qinit = &CLAWPACK5_QINIT;
if (gparms->manifold)
{
fclaw2d_patch_vt()->setup = &filament_patch_setup_manifold;
fc2d_clawpack5_vt()->rpn2 = &CLAWPACK5_RPN2ADV_MANIFOLD;
fc2d_clawpack5_vt()->rpt2 = &CLAWPACK5_RPT2ADV_MANIFOLD;
if (user->example == 2)
{
/* Avoid tagging block corners in 5 patch example*/
fclaw2d_clawpatch_vt()->fort_tag4refinement = &CLAWPACK5_TAG4REFINEMENT;
fclaw2d_clawpatch_vt()->fort_tag4coarsening = &CLAWPACK5_TAG4COARSENING;
}
}
else
{
fc2d_clawpack5_vt()->setaux = &CLAWPACK5_SETAUX; /* Used in non-manifold case */
fc2d_clawpack5_vt()->rpn2 = &CLAWPACK5_RPN2ADV;
fc2d_clawpack5_vt()->rpt2 = &CLAWPACK5_RPT2ADV;
}
}
}
void filament_patch_setup_manifold(fclaw2d_domain_t *domain,
fclaw2d_patch_t *this_patch,
int this_block_idx,
int this_patch_idx)
{
const user_options_t* user = filament_user_get_options(domain);
int mx,my,mbc,maux;
double xlower,ylower,dx,dy;
double *aux,*xd,*yd,*zd,*area;
double *xp,*yp,*zp;
fclaw2d_clawpatch_grid_data(domain,this_patch,&mx,&my,&mbc,
&xlower,&ylower,&dx,&dy);
fclaw2d_clawpatch_metric_data(domain,this_patch,&xp,&yp,&zp,
&xd,&yd,&zd,&area);
if (user->claw_version == 4)
{
fc2d_clawpack46_define_auxarray(domain,this_patch);
fc2d_clawpack46_aux_data(domain,this_patch,&aux,&maux);
USER46_SETAUX_MANIFOLD(&mbc,&mx,&my,&xlower,&ylower,
&dx,&dy,&maux,aux,&this_block_idx,
xd,yd,zd,area);
}
else if (user->claw_version == 5)
{
fc2d_clawpack5_define_auxarray(domain,this_patch);
fc2d_clawpack5_aux_data(domain,this_patch,&aux,&maux);
USER5_SETAUX_MANIFOLD(&mbc,&mx,&my,&xlower,&ylower,
&dx,&dy,&maux,aux,&this_block_idx,
xd,yd,zd,area);
}
}
<|endoftext|>
|
<commit_before>/*
* main.cpp
*
* Created on: 6 Sep 2015
* Author: jeremy
*/
#include "MainWindow/MainWindow.h"
#include <gtkmm/application.h>
#include <gtkmm/builder.h>
#include <gtkmm/button.h>
#include <string>
#include <memory>
#include <iostream>
#include "Controllers/MainController.h"
int main(int argc, char* argv[])
{
const std::string mainLocation = std::string(argv[0]);
std::size_t pos = mainLocation.find_last_of("/");
const std::string mainFolder = mainLocation.substr(0, pos);
const std::string uiFileLocation = mainFolder + "/../Source/Ui.glade";
// Create application and builder
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv);
Glib::RefPtr<Gtk::Builder> builder = Gtk::Builder::create_from_file(uiFileLocation);
// Get main window
Gui::MainWindow* mainWindow = nullptr;
builder->get_widget_derived("MainWindow", mainWindow);
// Create controller
std::shared_ptr<Gui::MainController> controller = std::shared_ptr<Gui::MainController>(new Gui::MainController(builder, mainFolder));
// Give controller to main window
mainWindow->SetController(controller);
// Handle quit button signal
Gtk::Button* quitButton = nullptr;
builder->get_widget("QuitButton", quitButton);
quitButton->signal_clicked().connect(sigc::mem_fun(mainWindow, &Gui::MainWindow::hide));
// Run application
int ret = app->run(*mainWindow);
// Delete pointers (dialogs and windows)
delete mainWindow;
return ret;
}
<commit_msg>Minor change<commit_after>/*
* main.cpp
*
* Created on: 6 Sep 2015
* Author: jeremy
*/
#include "Controllers/MainController.h"
#include "MainWindow/MainWindow.h"
#include <gtkmm/application.h>
#include <gtkmm/builder.h>
#include <gtkmm/button.h>
#include <string>
#include <memory>
#include <iostream>
int main(int argc, char* argv[])
{
const std::string mainLocation = std::string(argv[0]);
std::size_t pos = mainLocation.find_last_of("/");
const std::string mainFolder = mainLocation.substr(0, pos);
const std::string uiFileLocation = mainFolder + "/../Source/Ui.glade";
// Create application and builder
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv);
Glib::RefPtr<Gtk::Builder> builder = Gtk::Builder::create_from_file(uiFileLocation);
// Get main window
Gui::MainWindow* mainWindow = nullptr;
builder->get_widget_derived("MainWindow", mainWindow);
// Create controller
std::shared_ptr<Gui::MainController> controller = std::shared_ptr<Gui::MainController>(new Gui::MainController(builder, mainFolder));
// Give controller to main window
mainWindow->SetController(controller);
// Handle quit button signal
Gtk::Button* quitButton = nullptr;
builder->get_widget("QuitButton", quitButton);
quitButton->signal_clicked().connect(sigc::mem_fun(mainWindow, &Gui::MainWindow::hide));
// Run application
int ret = app->run(*mainWindow);
// Delete pointers (dialogs and windows)
delete mainWindow;
return ret;
}
<|endoftext|>
|
<commit_before>#include<iostream>
using namespace std;
int main(){
}
string[] splitString(string *s,char *split){
for(int i=0;i<s.lenth();i++){
<commit_msg>Simple string split implemented<commit_after>#include<iostream>
#include<string>
using namespace std;
struct list{
string s;
list *next;
};
list *splitString(string,char);
int main(){
string input;
getline(cin,input);
list *result = splitString(input,' ');
while(result!=NULL){
cout<<result->s<<"\n";
result=result->next;
}
}
list *splitString(string s,char split){
list *head=NULL;
int begin=-1;
int end=-1;
int count=-1;
for(int i=0;i<s.length();i++){
if(begin==-1 && s[i]!=split){
begin=i;
}
if(s[i]==split){
end=i;
}
if(begin>-1 && i==(s.length()-1)){
end=s.length();
}
if(begin>-1 && end>-1){
list *temp=new list;
temp->s=s.substr(begin,end-begin);
if(head==NULL){
head=temp;
}else{
temp->next=head;
head=temp;
}
begin=-1;
end=-1;
}
}
return head;
}
<|endoftext|>
|
<commit_before>/*
TPC DA for online calibration
Contact: Haavard.Helstrup@cern.ch
Link:
Run Type: PHYSICS STANDALONE DAQ
DA Type: MON
Number of events needed: 500
Input Files:
Output Files: tpcCE.root, to be exported to the DAQ FXS
fileId: CE
Trigger types used: PHYSICS_EVENT
*/
/*
TPCCEda.cxx - calibration algorithm for TPC Central Electrode events
10/06/2007 sylvain.chapeland@cern.ch : first version - clean skeleton based on DAQ DA case1
06/12/2007 haavard.helstrup@cern.ch : created CE DA based on pulser code
19/09/2008 J.Wiechula@gsi.de: Added support for configuration files.
contact: marian.ivanov@cern.ch
This process reads RAW data from the files provided as command line arguments
and save results in a file (named from RESULT_FILE define - see below).
*/
#define RESULT_FILE "tpcCE.root"
#define FILE_ID "CE"
#define MAPPING_FILE "tpcMapping.root"
#define CONFIG_FILE "TPCCEda.conf"
#include <daqDA.h>
#include "event.h"
#include "monitor.h"
#include <stdio.h>
#include <stdlib.h>
#include <vector>
//
//Root includes
//
#include <TFile.h>
#include "TROOT.h"
#include "TPluginManager.h"
#include "TSystem.h"
#include "TString.h"
#include "TObjString.h"
#include "TDatime.h"
#include "TStopwatch.h"
#include "TMap.h"
#include "TGraph.h"
#include "TMath.h"
//
//AliRoot includes
//
#include "AliRawReader.h"
#include "AliRawReaderDate.h"
#include "AliTPCmapper.h"
#include "AliTPCRawStream.h"
#include "AliTPCROC.h"
#include "AliTPCCalROC.h"
#include "AliTPCCalPad.h"
#include "AliMathBase.h"
#include "TTreeStream.h"
#include "AliLog.h"
#include "AliTPCConfigDA.h"
//
//AMORE
//
#include <AmoreDA.h>
//
// TPC calibration algorithm includes
//
#include "AliTPCCalibCE.h"
//functios, implementation below
void SendToAmoreDB(AliTPCCalibCE &calibCE, unsigned long32 runNb);
//for threaded processing
/* Main routine
Arguments: list of DATE raw data files
*/
int main(int argc, char **argv) {
/* log start of process */
printf("TPCCEda: DA started - %s\n",__FILE__);
if (argc<2) {
printf("TPCCEda: Wrong number of arguments\n");
return -1;
}
AliLog::SetClassDebugLevel("AliTPCRawStream",-5);
AliLog::SetClassDebugLevel("AliRawReaderDate",-5);
AliLog::SetClassDebugLevel("AliTPCAltroMapping",-5);
AliLog::SetModuleDebugLevel("RAW",-5);
gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
"*",
"TStreamerInfo",
"RIO",
"TStreamerInfo()");
/* declare monitoring program */
int i,status;
status=monitorDeclareMp( __FILE__ );
if (status!=0) {
printf("TPCCEda: monitorDeclareMp() failed : %s\n",monitorDecodeError(status));
return -1;
}
monitorSetNowait();
monitorSetNoWaitNetworkTimeout(1000);
//variables
AliTPCmapper *mapping = 0; // The TPC mapping
char localfile[255];
unsigned long32 runNb=0; //run number
//
// DA configuration from configuration file
//
//retrieve configuration file
sprintf(localfile,"./%s",CONFIG_FILE);
status = daqDA_DB_getFile(CONFIG_FILE,localfile);
if (status) {
printf("TPCCEda: Failed to get configuration file (%s) from DAQdetDB, status=%d\n", CONFIG_FILE, status);
return -1;
}
AliTPCConfigDA config(CONFIG_FILE);
// check configuration options
TString laserTriggerName("C0LSR-ABCE-NOPF-CENT");
TString monitoringType("YES");
Int_t forceTriggerId=-1;
if ( config.GetConfigurationMap()->GetValue("LaserTriggerName") ) {
laserTriggerName=config.GetConfigurationMap()->GetValue("LaserTriggerName")->GetName();
printf("TPCCEda: Laser trigger class name set to: %s.\n",laserTriggerName.Data());
}
if ( config.GetConfigurationMap()->GetValue("MonitoringType") ) {
monitoringType=config.GetConfigurationMap()->GetValue("MonitoringType")->GetName();
printf("TPCCEda: Monitoring type set to: %s.\n",monitoringType.Data());
}
if ( config.GetConfigurationMap()->GetValue("ForceLaserTriggerId") ) {
forceTriggerId=TMath::Nint(config.GetValue("ForceLaserTriggerId"));
printf("TPCCEda: Only processing triggers with Id: %d.\n",forceTriggerId);
}
//subsribe to laser triggers only in physics partition
//if the trigger class is not available the return value is -1
//in this case we are most probably running as a standalone
// laser run and should request all events
unsigned char classIdptr=0;
int retClassId=daqDA_getClassIdFromName(laserTriggerName.Data(),&classIdptr);
if (retClassId==0){
//interleaved laser in physics runs
//select proper trigger class id
char c[5];
snprintf(c,sizeof(c),"%u",(unsigned int)classIdptr);
char *table[5] = {"PHY",const_cast<char*>(monitoringType.Data()),"*",c,NULL};
monitorDeclareTableExtended(table);
printf("TPCCEda: Using monitoring table: (PHY, %s, *, %s)\n",monitoringType.Data(),c);
} else if (retClassId==-1){
//global partition without laser triggered events
//the DA should exit properly without processing
printf("TPCCEda: Laser trigger class '%s' was not found among trigger class names. Will stop processing.\n",laserTriggerName.Data());
return 0;
} else if (retClassId==-2){
//standalone case, accept all physics events
char *table[5] = {"PHY","Y","*","*",NULL};
monitorDeclareTableExtended(table);
printf("TPCCEda: Using all trigger class Ids\n");
} else {
printf("TPCCEda: Unknown return value of 'daqDA_getClassIdFromName': %d\n",retClassId);
return -2;
}
//see if we should force the trigger id
if (forceTriggerId>-1){
char c[5];
sprintf(c,"%d",forceTriggerId);
char *table[5] = {"PHY","Y","*",c,NULL};
monitorDeclareTableExtended(table);
}
// if test setup get parameters from $DAQDA_TEST_DIR
if (!mapping){
/* copy locally the mapping file from daq detector config db */
sprintf(localfile,"./%s",MAPPING_FILE);
status = daqDA_DB_getFile(MAPPING_FILE,localfile);
if (status) {
printf("TPCCEda: Failed to get mapping file (%s) from DAQdetDB, status=%d\n", MAPPING_FILE, status);
return -1;
}
/* open the mapping file and retrieve mapping object */
TFile *fileMapping = new TFile(MAPPING_FILE, "read");
mapping = (AliTPCmapper*) fileMapping->Get("tpcMapping");
delete fileMapping;
}
if (mapping == 0) {
printf("TPCCEda: Failed to get mapping object from %s. ...\n", MAPPING_FILE);
return -1;
} else {
printf("TPCCEda: Got mapping object from %s\n", MAPPING_FILE);
}
//create calibration object
AliTPCCalibCE calibCE(config.GetConfigurationMap()); // central electrode calibration
calibCE.SetAltroMapping(mapping->GetAltroMapping()); // Use altro mapping we got from daqDetDb
//amore update interval
Double_t updateInterval=300; //seconds
Double_t valConf=config.GetValue("AmoreUpdateInterval");
if ( valConf>0 ) updateInterval=valConf;
//timer
TStopwatch stopWatch;
//===========================//
// loop over RAW data files //
//==========================//
int nevents=0;
int neventsOld=0;
size_t counter=0;
for ( i=1; i<argc; i++) {
/* define data source : this is argument i */
printf("TPCCEda: Processing file %s\n", argv[i]);
status=monitorSetDataSource( argv[i] );
if (status!=0) {
printf("TPCCEda: monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* read until EOF */
while (true) {
struct eventHeaderStruct *event;
/* check shutdown condition */
if (daqDA_checkShutdown()) {break;}
/* get next event (blocking call until timeout) */
status=monitorGetEventDynamic((void **)&event);
if (status==MON_ERR_EOF) {
printf ("TPCCEda: End of File %d detected\n",i);
break; /* end of monitoring file has been reached */
}
if (status!=0) {
printf("TPCCEda: monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
break;
}
/* retry if got no event */
if (event==NULL){
//use time in between bursts to
// send the data to AMOREdb
if (stopWatch.RealTime()>updateInterval){
calibCE.Analyse();
SendToAmoreDB(calibCE,runNb);
stopWatch.Start();
} else {
stopWatch.Continue();
}
//debug output
if (nevents>neventsOld){
printf ("TPCCEda: %d events processed, %d used\n",nevents,calibCE.GetNeventsProcessed());
neventsOld=nevents;
}
continue;
}
/* skip start/end of run events */
if ( (event->eventType != physicsEvent) && (event->eventType != calibrationEvent) ){
free(event);
continue;
}
// get the run number
runNb = event->eventRunNb;
// CE calibration
calibCE.ProcessEvent(event);
/* free resources */
free(event);
++nevents;
}
}
//
// Analyse CE data and write them to rootfile
//
calibCE.Analyse();
printf ("TPCCEda: %d events processed, %d used\n",nevents,calibCE.GetNeventsProcessed());
TFile * fileTPC = new TFile (RESULT_FILE,"recreate");
calibCE.Write("tpcCalibCE");
delete fileTPC;
printf("TPCCEda: Wrote %s\n",RESULT_FILE);
/* store the result file on FES */
status=daqDA_FES_storeFile(RESULT_FILE,FILE_ID);
if (status) {
status = -2;
}
SendToAmoreDB(calibCE,runNb);
return status;
}
void SendToAmoreDB(AliTPCCalibCE &calibCE, unsigned long32 runNb)
{
//AMORE
// printf ("AMORE part\n");
const char *amoreDANameorig=gSystem->Getenv("AMORE_DA_NAME");
//cheet a little -- temporary solution (hopefully)
//
//currently amoreDA uses the environment variable AMORE_DA_NAME to create the mysql
//table in which the calib objects are stored. This table is dropped each time AmoreDA
//is initialised. This of course makes a problem if we would like to store different
//calibration entries in the AMORE DB. Therefore in each DA which writes to the AMORE DB
//the AMORE_DA_NAME env variable is overwritten.
gSystem->Setenv("AMORE_DA_NAME",Form("TPC-%s",FILE_ID));
//
// end cheet
TGraph *grA=calibCE.MakeGraphTimeCE(-1,0,2);
TGraph *grC=calibCE.MakeGraphTimeCE(-2,0,2);
TDatime time;
TObjString info(Form("Run: %u; Date: %s",runNb,time.AsSQLString()));
amore::da::AmoreDA amoreDA(amore::da::AmoreDA::kSender);
Int_t statusDA=0;
statusDA+=amoreDA.Send("CET0",calibCE.GetCalPadT0());
statusDA+=amoreDA.Send("CEQ",calibCE.GetCalPadQ());
statusDA+=amoreDA.Send("CERMS",calibCE.GetCalPadRMS());
statusDA+=amoreDA.Send("DriftA",grA);
statusDA+=amoreDA.Send("DriftC",grC);
statusDA+=amoreDA.Send("Info",&info);
if ( statusDA!=0 )
printf("TPCCEda: Waring: Failed to write one of the calib objects to the AMORE database\n");
// reset env var
if (amoreDANameorig) gSystem->Setenv("AMORE_DA_NAME",amoreDANameorig);
if (grA) delete grA;
if (grC) delete grC;
}
<commit_msg>Update TPCCEda to write output file in parts (to avoid too big files produced in lead runs)<commit_after>/*
TPC DA for online calibration
Contact: Haavard.Helstrup@cern.ch
Link:
Run Type: PHYSICS STANDALONE DAQ
DA Type: MON
Number of events needed: 500
Input Files:
Output Files: tpcCE.root, to be exported to the DAQ FXS
fileId: CE
Trigger types used: PHYSICS_EVENT
*/
/*
TPCCEda.cxx - calibration algorithm for TPC Central Electrode events
10/06/2007 sylvain.chapeland@cern.ch : first version - clean skeleton based on DAQ DA case1
06/12/2007 haavard.helstrup@cern.ch : created CE DA based on pulser code
19/09/2008 J.Wiechula@gsi.de: Added support for configuration files.
contact: marian.ivanov@cern.ch
This process reads RAW data from the files provided as command line arguments
and save results in a file (named from RESULT_FILE define - see below).
*/
#define RESULT_FILE "tpcCE.root"
#define FILE_ID "CE"
#define MAPPING_FILE "tpcMapping.root"
#define CONFIG_FILE "TPCCEda.conf"
#include <daqDA.h>
#include "event.h"
#include "monitor.h"
#include <stdio.h>
#include <stdlib.h>
#include <vector>
//
//Root includes
//
#include <TFile.h>
#include "TROOT.h"
#include "TPluginManager.h"
#include "TSystem.h"
#include "TString.h"
#include "TObjString.h"
#include "TDatime.h"
#include "TStopwatch.h"
#include "TMap.h"
#include "TGraph.h"
#include "TMath.h"
//
//AliRoot includes
//
#include "AliRawReader.h"
#include "AliRawReaderDate.h"
#include "AliTPCmapper.h"
#include "AliTPCRawStream.h"
#include "AliTPCROC.h"
#include "AliTPCCalROC.h"
#include "AliTPCCalPad.h"
#include "AliMathBase.h"
#include "TTreeStream.h"
#include "AliLog.h"
#include "AliTPCConfigDA.h"
//
//AMORE
//
#include <AmoreDA.h>
//
// TPC calibration algorithm includes
//
#include "AliTPCCalibCE.h"
//functios, implementation below
void SendToAmoreDB(AliTPCCalibCE *calibCE, unsigned long32 runNb);
//for threaded processing
/* Main routine
Arguments: list of DATE raw data files
*/
int main(int argc, char **argv) {
/* log start of process */
printf("TPCCEda: DA started - %s\n",__FILE__);
if (argc<2) {
printf("TPCCEda: Wrong number of arguments\n");
return -1;
}
AliLog::SetClassDebugLevel("AliTPCRawStream",-5);
AliLog::SetClassDebugLevel("AliRawReaderDate",-5);
AliLog::SetClassDebugLevel("AliTPCAltroMapping",-5);
AliLog::SetModuleDebugLevel("RAW",-5);
gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
"*",
"TStreamerInfo",
"RIO",
"TStreamerInfo()");
/* declare monitoring program */
int i,status;
status=monitorDeclareMp( __FILE__ );
if (status!=0) {
printf("TPCCEda: monitorDeclareMp() failed : %s\n",monitorDecodeError(status));
return -1;
}
monitorSetNowait();
monitorSetNoWaitNetworkTimeout(1000);
//variables
AliTPCmapper *mapping = 0; // The TPC mapping
char localfile[255];
unsigned long32 runNb=0; //run number
//
// DA configuration from configuration file
//
//retrieve configuration file
sprintf(localfile,"./%s",CONFIG_FILE);
status = daqDA_DB_getFile(CONFIG_FILE,localfile);
if (status) {
printf("TPCCEda: Failed to get configuration file (%s) from DAQdetDB, status=%d\n", CONFIG_FILE, status);
return -1;
}
AliTPCConfigDA config(CONFIG_FILE);
// check configuration options
TString laserTriggerName("C0LSR-ABCE-NOPF-CENT");
TString monitoringType("YES");
Int_t forceTriggerId=-1;
Int_t saveOption=2; // how to store the object. See AliTPCCalibCE::DumpToFile
if ( config.GetConfigurationMap()->GetValue("LaserTriggerName") ) {
laserTriggerName=config.GetConfigurationMap()->GetValue("LaserTriggerName")->GetName();
printf("TPCCEda: Laser trigger class name set to: %s.\n",laserTriggerName.Data());
}
if ( config.GetConfigurationMap()->GetValue("MonitoringType") ) {
monitoringType=config.GetConfigurationMap()->GetValue("MonitoringType")->GetName();
printf("TPCCEda: Monitoring type set to: %s.\n",monitoringType.Data());
}
if ( config.GetConfigurationMap()->GetValue("ForceLaserTriggerId") ) {
forceTriggerId=TMath::Nint(config.GetValue("ForceLaserTriggerId"));
printf("TPCCEda: Only processing triggers with Id: %d.\n",forceTriggerId);
}
if ( config.GetConfigurationMap()->GetValue("SaveOption") ) {
saveOption=TMath::Nint(config.GetValue("SaveOption"));
printf("TPCCEda: Saving option set to: %d.\n",saveOption);
}
//subsribe to laser triggers only in physics partition
//if the trigger class is not available the return value is -1
//in this case we are most probably running as a standalone
// laser run and should request all events
unsigned char classIdptr=0;
int retClassId=daqDA_getClassIdFromName(laserTriggerName.Data(),&classIdptr);
if (retClassId==0){
//interleaved laser in physics runs
//select proper trigger class id
char c[5];
snprintf(c,sizeof(c),"%u",(unsigned int)classIdptr);
char *table[5] = {"PHY",const_cast<char*>(monitoringType.Data()),"*",c,NULL};
monitorDeclareTableExtended(table);
printf("TPCCEda: Using monitoring table: (PHY, %s, *, %s)\n",monitoringType.Data(),c);
} else if (retClassId==-1){
//global partition without laser triggered events
//the DA should exit properly without processing
printf("TPCCEda: Laser trigger class '%s' was not found among trigger class names. Will stop processing.\n",laserTriggerName.Data());
return 0;
} else if (retClassId==-2){
//standalone case, accept all physics events
char *table[5] = {"PHY","Y","*","*",NULL};
monitorDeclareTableExtended(table);
printf("TPCCEda: Using all trigger class Ids\n");
} else {
printf("TPCCEda: Unknown return value of 'daqDA_getClassIdFromName': %d\n",retClassId);
return -2;
}
//see if we should force the trigger id
if (forceTriggerId>-1){
char c[5];
sprintf(c,"%d",forceTriggerId);
char *table[5] = {"PHY","Y","*",c,NULL};
monitorDeclareTableExtended(table);
}
// if test setup get parameters from $DAQDA_TEST_DIR
if (!mapping){
/* copy locally the mapping file from daq detector config db */
sprintf(localfile,"./%s",MAPPING_FILE);
status = daqDA_DB_getFile(MAPPING_FILE,localfile);
if (status) {
printf("TPCCEda: Failed to get mapping file (%s) from DAQdetDB, status=%d\n", MAPPING_FILE, status);
return -1;
}
/* open the mapping file and retrieve mapping object */
TFile *fileMapping = new TFile(MAPPING_FILE, "read");
mapping = (AliTPCmapper*) fileMapping->Get("tpcMapping");
delete fileMapping;
}
if (mapping == 0) {
printf("TPCCEda: Failed to get mapping object from %s. ...\n", MAPPING_FILE);
return -1;
} else {
printf("TPCCEda: Got mapping object from %s\n", MAPPING_FILE);
}
//create calibration object
AliTPCCalibCE *calibCE=new AliTPCCalibCE(config.GetConfigurationMap()); // central electrode calibration
calibCE->SetAltroMapping(mapping->GetAltroMapping()); // Use altro mapping we got from daqDetDb
//amore update interval
Double_t updateInterval=300; //seconds
Double_t valConf=config.GetValue("AmoreUpdateInterval");
if ( valConf>0 ) updateInterval=valConf;
//timer
TStopwatch stopWatch;
//===========================//
// loop over RAW data files //
//==========================//
int nevents=0;
int neventsOld=0;
size_t counter=0;
for ( i=1; i<argc; i++) {
/* define data source : this is argument i */
printf("TPCCEda: Processing file %s\n", argv[i]);
status=monitorSetDataSource( argv[i] );
if (status!=0) {
printf("TPCCEda: monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* read until EOF */
while (true) {
struct eventHeaderStruct *event;
/* check shutdown condition */
if (daqDA_checkShutdown()) {break;}
/* get next event (blocking call until timeout) */
status=monitorGetEventDynamic((void **)&event);
if (status==MON_ERR_EOF) {
printf ("TPCCEda: End of File %d detected\n",i);
break; /* end of monitoring file has been reached */
}
if (status!=0) {
printf("TPCCEda: monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
break;
}
/* retry if got no event */
if (event==NULL){
//use time in between bursts to
// send the data to AMOREdb
if (stopWatch.RealTime()>updateInterval){
calibCE->Analyse();
SendToAmoreDB(calibCE,runNb);
stopWatch.Start();
} else {
stopWatch.Continue();
}
//debug output
if (nevents>neventsOld){
printf ("TPCCEda: %d events processed, %d used\n",nevents,calibCE->GetNeventsProcessed());
neventsOld=nevents;
}
continue;
}
/* skip start/end of run events */
if ( (event->eventType != physicsEvent) && (event->eventType != calibrationEvent) ){
free(event);
continue;
}
// get the run number
runNb = event->eventRunNb;
// CE calibration
calibCE->ProcessEvent(event);
/* free resources */
free(event);
++nevents;
}
}
//
// Analyse CE data and write them to rootfile
//
// calibCE->Analyse();
printf ("TPCCEda: %d events processed, %d used\n",nevents,calibCE->GetNeventsProcessed());
// TFile * fileTPC = new TFile (RESULT_FILE,"recreate");
// calibCE->Write("tpcCalibCE");
// delete fileTPC;
calibCE->DumpToFile(RESULT_FILE,Form("name=tpcCalibCE,type=%d",saveOption));
printf("TPCCEda: Wrote %s\n",RESULT_FILE);
/* store the result file on FES */
status=daqDA_FES_storeFile(RESULT_FILE,FILE_ID);
if (status) {
status = -2;
}
SendToAmoreDB(calibCE,runNb);
delete calibCE;
return status;
}
void SendToAmoreDB(AliTPCCalibCE *calibCE, unsigned long32 runNb)
{
//AMORE
// printf ("AMORE part\n");
const char *amoreDANameorig=gSystem->Getenv("AMORE_DA_NAME");
//cheet a little -- temporary solution (hopefully)
//
//currently amoreDA uses the environment variable AMORE_DA_NAME to create the mysql
//table in which the calib objects are stored. This table is dropped each time AmoreDA
//is initialised. This of course makes a problem if we would like to store different
//calibration entries in the AMORE DB. Therefore in each DA which writes to the AMORE DB
//the AMORE_DA_NAME env variable is overwritten.
gSystem->Setenv("AMORE_DA_NAME",Form("TPC-%s",FILE_ID));
//
// end cheet
TGraph *grA=calibCE->MakeGraphTimeCE(-1,0,2);
TGraph *grC=calibCE->MakeGraphTimeCE(-2,0,2);
TDatime time;
TObjString info(Form("Run: %u; Date: %s",runNb,time.AsSQLString()));
amore::da::AmoreDA amoreDA(amore::da::AmoreDA::kSender);
Int_t statusDA=0;
statusDA+=amoreDA.Send("CET0",calibCE->GetCalPadT0());
statusDA+=amoreDA.Send("CEQ",calibCE->GetCalPadQ());
statusDA+=amoreDA.Send("CERMS",calibCE->GetCalPadRMS());
statusDA+=amoreDA.Send("DriftA",grA);
statusDA+=amoreDA.Send("DriftC",grC);
statusDA+=amoreDA.Send("Info",&info);
if ( statusDA!=0 )
printf("TPCCEda: Waring: Failed to write one of the calib objects to the AMORE database\n");
// reset env var
if (amoreDANameorig) gSystem->Setenv("AMORE_DA_NAME",amoreDANameorig);
if (grA) delete grA;
if (grC) delete grC;
}
<|endoftext|>
|
<commit_before>#include <thread>
#include <vector>
#include <time.h>
#include <chrono>
using namespace std;
std::atomic<bool> ready (false);
std::atomic<int> counter(0);
//int counter(0);
//int counter = 0;
//increment local
constexpr int max_value = 100000000;
void increment_l (int id) {
unsigned int lcounter = 0;
//std::cout << "In Thread Id #" << id << std::endl;
while (!ready) {
std::this_thread::yield();
}// wait for the ready signal
// Increment the atomic variable and go to a nano sleep
for(volatile int i=0; i<max_value; ++i){
++lcounter;
}
counter += lcounter;
}
//increment atomic
void increment_a (int id) {
//std::cout << "In Thread Id #" << id << std::endl;
while (!ready) {
std::this_thread::yield();
}// wait for the ready signal
// Increment the atomic variable and go to a nano sleep
for(volatile int i=0; i<max_value; ++i){
++counter;
}
}
//increment thread local
void increment_tl (int id) {
static thread_local unsigned int tlcounter;
//std::cout << "In Thread Id #" << id << std::endl;
while (!ready) {
std::this_thread::yield();
}// wait for the ready signal
// Increment the atomic variable and go to a nano sleep
for(volatile int i=0; i<max_value; ++i){
++tlcounter;
//nanosleep(&timeOut, &remains);
}
counter += tlcounter;
}
int func (void fptr(int))
{
ready = false;
counter = 0;
std::vector<std::thread> threads;
//std::cout << "spawning 10 threads...\n";
auto start = std::chrono::high_resolution_clock::now();
for (int i=1; i<=10; ++i) threads.push_back(std::thread((*fptr),i));
ready = true;
for (auto& th : threads) th.join();
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> elapsed = end-start;
std::cout << "Waited " << elapsed.count() << " ms\n";
std::cout << "The value of counter is " << counter << std::endl;
return 0;
}
int main ()
{
std::cout << "Local =========== " ;
func(increment_l);
std::cout << "Thread Local =========== " ;
func(increment_tl);
std::cout << "Atomic =========== " ;
func(increment_a);
return 0;
}
<commit_msg>Update atomic.cpp<commit_after>#include <iostream>
#include <functional>
#include <atomic>
#include <thread>
#include <vector>
#include <time.h>
#include <chrono>
using namespace std;
std::atomic<bool> ready (false);
std::atomic<int> counter(0);
//int counter(0);
//int counter = 0;
//increment local
constexpr int max_value = 100000000;
void increment_l (int id) {
unsigned int lcounter = 0;
//std::cout << "In Thread Id #" << id << std::endl;
while (!ready) {
std::this_thread::yield();
}// wait for the ready signal
// Increment the atomic variable and go to a nano sleep
for(volatile int i=0; i<max_value; ++i){
++lcounter;
}
counter += lcounter;
}
//increment atomic
void increment_a (int id) {
//std::cout << "In Thread Id #" << id << std::endl;
while (!ready) {
std::this_thread::yield();
}// wait for the ready signal
// Increment the atomic variable and go to a nano sleep
for(volatile int i=0; i<max_value; ++i){
++counter;
}
}
//increment thread local
void increment_tl (int id) {
static thread_local unsigned int tlcounter;
//std::cout << "In Thread Id #" << id << std::endl;
while (!ready) {
std::this_thread::yield();
}// wait for the ready signal
// Increment the atomic variable and go to a nano sleep
for(volatile int i=0; i<max_value; ++i){
++tlcounter;
//nanosleep(&timeOut, &remains);
}
counter += tlcounter;
}
int func (std::function<void(int)> func )
{
ready = false;
counter = 0;
std::vector<std::thread> threads;
//std::cout << "spawning 10 threads...\n";
auto start = std::chrono::high_resolution_clock::now();
for (int i=1; i<=10; ++i) threads.push_back(std::thread(func, i));
ready = true;
for (auto& th : threads) th.join();
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> elapsed = end-start;
std::cout << "Waited " << elapsed.count() << " ms\n";
std::cout << "The value of counter is " << counter << std::endl;
return 0;
}
int main ()
{
std::function<void(int)> f_func = increment_l;
std::cout << "Local =========== " ;
func(f_func);
std::cout << "Thread Local =========== " ;
func(increment_tl);
std::cout << "Atomic =========== " ;
func(increment_a);
return 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: canvascustomspritehelper.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2007-07-17 14:18:28 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef INCLUDED_CANVAS_CANVASCUSTOMSPRITEHELPER_HXX
#define INCLUDED_CANVAS_CANVASCUSTOMSPRITEHELPER_HXX
#ifndef _COM_SUN_STAR_RENDERING_XCUSTOMSPRITE_HPP_
#include <com/sun/star/rendering/XCustomSprite.hpp>
#endif
#ifndef _COM_SUN_STAR_RENDERING_XPOLYPOLYGON2D_HPP_
#include <com/sun/star/rendering/XPolyPolygon2D.hpp>
#endif
#ifndef _BGFX_POINT_B2DPOINT_HXX
#include <basegfx/point/b2dpoint.hxx>
#endif
#ifndef _BGFX_VECTOR_B2DVECTOR_HXX
#include <basegfx/vector/b2dvector.hxx>
#endif
#ifndef _BGFX_RANGE_B2DRANGE_HXX
#include <basegfx/range/b2drange.hxx>
#endif
#ifndef _BGFX_MATRIX_B2DHOMMATRIX_HXX
#include <basegfx/matrix/b2dhommatrix.hxx>
#endif
#ifndef INCLUDED_CANVAS_SPRITESURFACE_HXX
#include <canvas/base/spritesurface.hxx>
#endif
namespace canvas
{
/* Definition of CanvasCustomSpriteHelper class */
/** Base class for an XSprite helper implementation - to be used
in concert with CanvasCustomSpriteBase
*/
class CanvasCustomSpriteHelper
{
public:
CanvasCustomSpriteHelper();
virtual ~CanvasCustomSpriteHelper() {}
/** Init helper
@param rSpriteSize
Requested size of the sprite, as passed to the
XSpriteCanvas::createCustomSprite() method
@param rOwningSpriteCanvas
The XSpriteCanvas this sprite is displayed on
*/
void init( const ::com::sun::star::geometry::RealSize2D& rSpriteSize,
const SpriteSurface::Reference& rOwningSpriteCanvas );
/** Object is being disposed, release all internal references
@derive when overriding this method in derived classes,
<em>always</em> call the base class' method!
*/
void disposing();
// XCanvas
/// need to call this method for XCanvas::clear(), for opacity tracking
void clearingContent( const Sprite::Reference& rSprite );
/// need to call this method for XCanvas::drawBitmap(), for opacity tracking
void checkDrawBitmap( const Sprite::Reference& rSprite,
const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XBitmap >& xBitmap,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
// XSprite
void setAlpha( const Sprite::Reference& rSprite,
double alpha );
void move( const Sprite::Reference& rSprite,
const ::com::sun::star::geometry::RealPoint2D& aNewPos,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
void transform( const Sprite::Reference& rSprite,
const ::com::sun::star::geometry::AffineMatrix2D& aTransformation );
void clip( const Sprite::Reference& rSprite,
const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XPolyPolygon2D >& aClip );
void setPriority( const Sprite::Reference& rSprite,
double nPriority );
void show( const Sprite::Reference& rSprite );
void hide( const Sprite::Reference& rSprite );
// Sprite
bool isAreaUpdateOpaque( const ::basegfx::B2DRange& rUpdateArea ) const;
::basegfx::B2DPoint getPosPixel() const;
::basegfx::B2DVector getSizePixel() const;
::basegfx::B2DRange getUpdateArea() const;
double getPriority() const;
// redraw must be implemented by derived - non sensible default implementation
// void redraw( const Sprite::Reference& rSprite,
// const ::basegfx::B2DPoint& rPos ) const;
// Helper methods for derived classes
// ----------------------------------
/// Calc sprite update area from given raw sprite bounds
::basegfx::B2DRange getUpdateArea( const ::basegfx::B2DRange& rUntransformedSpriteBounds ) const;
/// Calc update area for unclipped sprite content
::basegfx::B2DRange getFullSpriteRect() const;
/** Returns true, if sprite content bitmap is fully opaque.
This does not take clipping or transformation into
account, but only denotes that the sprite bitmap's alpha
channel is all 1.0
*/
bool isContentFullyOpaque() const { return mbIsContentFullyOpaque; }
/// Returns true, if transformation has changed since last transformUpdated() call
bool hasAlphaChanged() const { return mbAlphaDirty; }
/// Returns true, if transformation has changed since last transformUpdated() call
bool hasPositionChanged() const { return mbPositionDirty; }
/// Returns true, if transformation has changed since last transformUpdated() call
bool hasTransformChanged() const { return mbTransformDirty; }
/// Returns true, if transformation has changed since last transformUpdated() call
bool hasClipChanged() const { return mbClipDirty; }
/// Returns true, if transformation has changed since last transformUpdated() call
bool hasPrioChanged() const { return mbPrioDirty; }
/// Returns true, if transformation has changed since last transformUpdated() call
bool hasVisibilityChanged() const { return mbVisibilityDirty; }
/// Retrieve current alpha value
double getAlpha() const { return mfAlpha; }
/// Retrieve current clip
const ::com::sun::star::uno::Reference<
::com::sun::star::rendering::XPolyPolygon2D >& getClip() const { return mxClipPoly; }
const ::basegfx::B2DHomMatrix& getTransformation() const { return maTransform; }
/// Retrieve current activation state
bool isActive() const { return mbActive; }
protected:
/** Notifies that caller is again in sync with current alph
const, but modifies state visible to derived
classes. beware of passing this information to the
outside!
*/
void alphaUpdated() const { mbAlphaDirty=false; }
/** Notifies that caller is again in sync with current position
const, but modifies state visible to derived
classes. beware of passing this information to the
outside!
*/
void positionUpdated() const { mbPositionDirty=false; }
/** Notifies that caller is again in sync with current transformation
const, but modifies state visible to derived
classes. beware of passing this information to the
outside!
*/
void transformUpdated() const { mbTransformDirty=false; }
/** Notifies that caller is again in sync with current clip
const, but modifies state visible to derived
classes. beware of passing this information to the
outside!
*/
void clipUpdated() const { mbClipDirty=false; }
/** Notifies that caller is again in sync with current priority
const, but modifies state visible to derived
classes. beware of passing this information to the
outside!
*/
void prioUpdated() const { mbPrioDirty=false; }
/** Notifies that caller is again in sync with current visibility
const, but modifies state visible to derived
classes. beware of passing this information to the
outside!
*/
void visibilityUpdated() const { mbVisibilityDirty=false; }
private:
CanvasCustomSpriteHelper( const CanvasCustomSpriteHelper& );
CanvasCustomSpriteHelper& operator=( const CanvasCustomSpriteHelper& );
/** Called to convert an API polygon to a basegfx polygon
@derive Needs to be provided by backend-specific code
*/
virtual ::basegfx::B2DPolyPolygon polyPolygonFromXPolyPolygon2D(
::com::sun::star::uno::Reference< ::com::sun::star::rendering::XPolyPolygon2D >& xPoly ) const = 0;
/** Update clip information from current state
This method recomputes the maCurrClipBounds and
mbIsCurrClipRectangle members from the current clip and
transformation. IFF the clip changed from rectangular to
rectangular again, this method issues a sequence of
optimized SpriteSurface::updateSprite() calls.
@return true, if SpriteSurface::updateSprite() was already
called within this method.
*/
bool updateClipState( const Sprite::Reference& rSprite );
// --------------------------------------------------------------------
/// Owning sprite canvas
SpriteSurface::Reference mpSpriteCanvas;
/** Currently active clip area.
This member is either empty, denoting that the current
clip shows the full sprite content, or contains a
rectangular subarea of the sprite, outside of which
the sprite content is fully clipped.
@see mbIsCurrClipRectangle
*/
::basegfx::B2DRange maCurrClipBounds;
// sprite state
::basegfx::B2DPoint maPosition;
::basegfx::B2DVector maSize;
::basegfx::B2DHomMatrix maTransform;
::com::sun::star::uno::Reference<
::com::sun::star::rendering::XPolyPolygon2D > mxClipPoly;
double mfPriority;
double mfAlpha;
bool mbActive; // true, if not hidden
/** If true, denotes that the current sprite clip is a true
rectangle, i.e. maCurrClipBounds <em>exactly</em>
describes the visible area of the sprite.
@see maCurrClipBounds
*/
bool mbIsCurrClipRectangle;
/** Redraw speedup.
When true, this flag denotes that the current sprite
content is fully opaque, thus, that blits to the screen do
neither have to take alpha into account, nor prepare any
background for the sprite area.
*/
mutable bool mbIsContentFullyOpaque;
/// True, iff mfAlpha has changed
mutable bool mbAlphaDirty;
/// True, iff maPosition has changed
mutable bool mbPositionDirty;
/// True, iff maTransform has changed
mutable bool mbTransformDirty;
/// True, iff mxClipPoly has changed
mutable bool mbClipDirty;
/// True, iff mnPriority has changed
mutable bool mbPrioDirty;
/// True, iff mbActive has changed
mutable bool mbVisibilityDirty;
};
}
#endif /* INCLUDED_CANVAS_CANVASCUSTOMSPRITEHELPER_HXX */
<commit_msg>INTEGRATION: CWS changefileheader (1.3.50); FILE MERGED 2008/04/01 15:03:03 thb 1.3.50.3: #i85898# Stripping all external header guards 2008/04/01 10:49:25 thb 1.3.50.2: #i85898# Stripping all external header guards 2008/03/28 16:34:53 rt 1.3.50.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: canvascustomspritehelper.hxx,v $
* $Revision: 1.4 $
*
* 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.
*
************************************************************************/
#ifndef INCLUDED_CANVAS_CANVASCUSTOMSPRITEHELPER_HXX
#define INCLUDED_CANVAS_CANVASCUSTOMSPRITEHELPER_HXX
#include <com/sun/star/rendering/XCustomSprite.hpp>
#include <com/sun/star/rendering/XPolyPolygon2D.hpp>
#include <basegfx/point/b2dpoint.hxx>
#include <basegfx/vector/b2dvector.hxx>
#include <basegfx/range/b2drange.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <canvas/base/spritesurface.hxx>
namespace canvas
{
/* Definition of CanvasCustomSpriteHelper class */
/** Base class for an XSprite helper implementation - to be used
in concert with CanvasCustomSpriteBase
*/
class CanvasCustomSpriteHelper
{
public:
CanvasCustomSpriteHelper();
virtual ~CanvasCustomSpriteHelper() {}
/** Init helper
@param rSpriteSize
Requested size of the sprite, as passed to the
XSpriteCanvas::createCustomSprite() method
@param rOwningSpriteCanvas
The XSpriteCanvas this sprite is displayed on
*/
void init( const ::com::sun::star::geometry::RealSize2D& rSpriteSize,
const SpriteSurface::Reference& rOwningSpriteCanvas );
/** Object is being disposed, release all internal references
@derive when overriding this method in derived classes,
<em>always</em> call the base class' method!
*/
void disposing();
// XCanvas
/// need to call this method for XCanvas::clear(), for opacity tracking
void clearingContent( const Sprite::Reference& rSprite );
/// need to call this method for XCanvas::drawBitmap(), for opacity tracking
void checkDrawBitmap( const Sprite::Reference& rSprite,
const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XBitmap >& xBitmap,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
// XSprite
void setAlpha( const Sprite::Reference& rSprite,
double alpha );
void move( const Sprite::Reference& rSprite,
const ::com::sun::star::geometry::RealPoint2D& aNewPos,
const ::com::sun::star::rendering::ViewState& viewState,
const ::com::sun::star::rendering::RenderState& renderState );
void transform( const Sprite::Reference& rSprite,
const ::com::sun::star::geometry::AffineMatrix2D& aTransformation );
void clip( const Sprite::Reference& rSprite,
const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XPolyPolygon2D >& aClip );
void setPriority( const Sprite::Reference& rSprite,
double nPriority );
void show( const Sprite::Reference& rSprite );
void hide( const Sprite::Reference& rSprite );
// Sprite
bool isAreaUpdateOpaque( const ::basegfx::B2DRange& rUpdateArea ) const;
::basegfx::B2DPoint getPosPixel() const;
::basegfx::B2DVector getSizePixel() const;
::basegfx::B2DRange getUpdateArea() const;
double getPriority() const;
// redraw must be implemented by derived - non sensible default implementation
// void redraw( const Sprite::Reference& rSprite,
// const ::basegfx::B2DPoint& rPos ) const;
// Helper methods for derived classes
// ----------------------------------
/// Calc sprite update area from given raw sprite bounds
::basegfx::B2DRange getUpdateArea( const ::basegfx::B2DRange& rUntransformedSpriteBounds ) const;
/// Calc update area for unclipped sprite content
::basegfx::B2DRange getFullSpriteRect() const;
/** Returns true, if sprite content bitmap is fully opaque.
This does not take clipping or transformation into
account, but only denotes that the sprite bitmap's alpha
channel is all 1.0
*/
bool isContentFullyOpaque() const { return mbIsContentFullyOpaque; }
/// Returns true, if transformation has changed since last transformUpdated() call
bool hasAlphaChanged() const { return mbAlphaDirty; }
/// Returns true, if transformation has changed since last transformUpdated() call
bool hasPositionChanged() const { return mbPositionDirty; }
/// Returns true, if transformation has changed since last transformUpdated() call
bool hasTransformChanged() const { return mbTransformDirty; }
/// Returns true, if transformation has changed since last transformUpdated() call
bool hasClipChanged() const { return mbClipDirty; }
/// Returns true, if transformation has changed since last transformUpdated() call
bool hasPrioChanged() const { return mbPrioDirty; }
/// Returns true, if transformation has changed since last transformUpdated() call
bool hasVisibilityChanged() const { return mbVisibilityDirty; }
/// Retrieve current alpha value
double getAlpha() const { return mfAlpha; }
/// Retrieve current clip
const ::com::sun::star::uno::Reference<
::com::sun::star::rendering::XPolyPolygon2D >& getClip() const { return mxClipPoly; }
const ::basegfx::B2DHomMatrix& getTransformation() const { return maTransform; }
/// Retrieve current activation state
bool isActive() const { return mbActive; }
protected:
/** Notifies that caller is again in sync with current alph
const, but modifies state visible to derived
classes. beware of passing this information to the
outside!
*/
void alphaUpdated() const { mbAlphaDirty=false; }
/** Notifies that caller is again in sync with current position
const, but modifies state visible to derived
classes. beware of passing this information to the
outside!
*/
void positionUpdated() const { mbPositionDirty=false; }
/** Notifies that caller is again in sync with current transformation
const, but modifies state visible to derived
classes. beware of passing this information to the
outside!
*/
void transformUpdated() const { mbTransformDirty=false; }
/** Notifies that caller is again in sync with current clip
const, but modifies state visible to derived
classes. beware of passing this information to the
outside!
*/
void clipUpdated() const { mbClipDirty=false; }
/** Notifies that caller is again in sync with current priority
const, but modifies state visible to derived
classes. beware of passing this information to the
outside!
*/
void prioUpdated() const { mbPrioDirty=false; }
/** Notifies that caller is again in sync with current visibility
const, but modifies state visible to derived
classes. beware of passing this information to the
outside!
*/
void visibilityUpdated() const { mbVisibilityDirty=false; }
private:
CanvasCustomSpriteHelper( const CanvasCustomSpriteHelper& );
CanvasCustomSpriteHelper& operator=( const CanvasCustomSpriteHelper& );
/** Called to convert an API polygon to a basegfx polygon
@derive Needs to be provided by backend-specific code
*/
virtual ::basegfx::B2DPolyPolygon polyPolygonFromXPolyPolygon2D(
::com::sun::star::uno::Reference< ::com::sun::star::rendering::XPolyPolygon2D >& xPoly ) const = 0;
/** Update clip information from current state
This method recomputes the maCurrClipBounds and
mbIsCurrClipRectangle members from the current clip and
transformation. IFF the clip changed from rectangular to
rectangular again, this method issues a sequence of
optimized SpriteSurface::updateSprite() calls.
@return true, if SpriteSurface::updateSprite() was already
called within this method.
*/
bool updateClipState( const Sprite::Reference& rSprite );
// --------------------------------------------------------------------
/// Owning sprite canvas
SpriteSurface::Reference mpSpriteCanvas;
/** Currently active clip area.
This member is either empty, denoting that the current
clip shows the full sprite content, or contains a
rectangular subarea of the sprite, outside of which
the sprite content is fully clipped.
@see mbIsCurrClipRectangle
*/
::basegfx::B2DRange maCurrClipBounds;
// sprite state
::basegfx::B2DPoint maPosition;
::basegfx::B2DVector maSize;
::basegfx::B2DHomMatrix maTransform;
::com::sun::star::uno::Reference<
::com::sun::star::rendering::XPolyPolygon2D > mxClipPoly;
double mfPriority;
double mfAlpha;
bool mbActive; // true, if not hidden
/** If true, denotes that the current sprite clip is a true
rectangle, i.e. maCurrClipBounds <em>exactly</em>
describes the visible area of the sprite.
@see maCurrClipBounds
*/
bool mbIsCurrClipRectangle;
/** Redraw speedup.
When true, this flag denotes that the current sprite
content is fully opaque, thus, that blits to the screen do
neither have to take alpha into account, nor prepare any
background for the sprite area.
*/
mutable bool mbIsContentFullyOpaque;
/// True, iff mfAlpha has changed
mutable bool mbAlphaDirty;
/// True, iff maPosition has changed
mutable bool mbPositionDirty;
/// True, iff maTransform has changed
mutable bool mbTransformDirty;
/// True, iff mxClipPoly has changed
mutable bool mbClipDirty;
/// True, iff mnPriority has changed
mutable bool mbPrioDirty;
/// True, iff mbActive has changed
mutable bool mbVisibilityDirty;
};
}
#endif /* INCLUDED_CANVAS_CANVASCUSTOMSPRITEHELPER_HXX */
<|endoftext|>
|
<commit_before>#pragma once
#include <utki/config.hpp>
#if M_OS != M_OS_WINDOWS
# error "compiling in non-Windows environment"
#endif
#include <cstring>
#include <thread>
#include <initguid.h> // The header file initguid.h is required to avoid the error message "undefined reference to `IID_IDirectSoundBuffer8'".
#include <dsound.h>
#include <opros/wait_set.hpp>
#include "../Player.hpp"
#include "../Exc.hpp"
namespace audout{
class WinEvent : public opros::waitable{
HANDLE eventForWaitable;
utki::flags<opros::ready> waiting_flags;
virtual void set_waiting_flags(utki::flags<opros::ready> wait_for)override{
// Only possible flag values are 'read' or 0 (not ready)
if(!(wait_for & (~utki::make_flags({opros::ready::read}))).is_clear()){
ASSERT_INFO(false, "wait_for = " << wait_for)
throw audout::Exc("WinEvent::set_waiting_flags(): only 'read' or no flags are allowed");
}
this->waiting_flags = wait_for;
}
bool check_signaled()override{
switch(WaitForSingleObject(this->eventForWaitable, 0)){
case WAIT_OBJECT_0: // event is signaled
this->readiness_flags.set(opros::ready::read);
if(ResetEvent(this->eventForWaitable) == 0){
ASSERT(false)
throw std::system_error(GetLastError(), std::generic_category(), "ResetEvent() failed");
}
break;
case WAIT_ABANDONED:
case WAIT_TIMEOUT: // event is not signalled
this->readiness_flags.clear(opros::ready::read);
break;
default:
case WAIT_FAILED:
throw std::system_error(GetLastError(), std::generic_category(), "WaitForSingleObject() failed");
}
return !(this->waiting_flags & this->flags()).is_clear();
}
public:
HANDLE get_handle()override{
return this->eventForWaitable;
}
WinEvent(){
this->eventForWaitable = CreateEvent(
nullptr, // security attributes
TRUE, // manual-reset
FALSE, // not signaled initially
nullptr // no name
);
if(this->eventForWaitable == 0){
throw std::system_error(GetLastError(), std::generic_category(), "CreateEvent() failed");
}
}
virtual ~WinEvent()noexcept{
CloseHandle(this->eventForWaitable);
}
};
class DirectSoundBackend{
Listener* listener;
std::thread thread;
nitki::queue queue;
bool quitFlag = false;
struct direct_sound{
LPDIRECTSOUND8 ds; // LP prefix means long pointer
direct_sound(){
if(DirectSoundCreate8(nullptr, &this->ds, nullptr) != DS_OK){
throw std::runtime_error("DirectSoundCreate8() failed");
}
utki::scope_exit ds_scope_exit([this](){
this->ds->Release();
});
HWND hwnd = GetDesktopWindow();
if(!hwnd){
throw std::runtime_error("no foreground window found");
}
if(this->ds->SetCooperativeLevel(hwnd, DSSCL_PRIORITY) != DS_OK){
throw std::runtime_error("SetCooperativeLevel() failed");
}
ds_scope_exit.reset();
}
~direct_sound()noexcept{
this->ds->Release();
}
} ds;
struct direct_sound_buffer{
LPDIRECTSOUNDBUFFER8 dsb; // LP stands for long pointer
unsigned halfSize;
direct_sound_buffer(direct_sound& ds, unsigned bufferSizeFrames, AudioFormat format) :
halfSize(format.bytesPerFrame() * bufferSizeFrames)
{
WAVEFORMATEX wf;
memset(&wf, 0, sizeof(WAVEFORMATEX));
wf.nChannels = format.numChannels();
wf.nSamplesPerSec = format.frequency();
wf.wFormatTag = WAVE_FORMAT_PCM;
wf.wBitsPerSample = 16;
wf.nBlockAlign = wf.nChannels * (wf.wBitsPerSample / 8);
wf.nAvgBytesPerSec = wf.nSamplesPerSec * wf.nBlockAlign;
DSBUFFERDESC dsbdesc;
memset(&dsbdesc, 0, sizeof(DSBUFFERDESC));
dsbdesc.dwSize = sizeof(DSBUFFERDESC);
dsbdesc.dwFlags = DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_CTRLPOSITIONNOTIFY | DSBCAPS_GLOBALFOCUS;
dsbdesc.dwBufferBytes = 2 * this->halfSize;
dsbdesc.lpwfxFormat = &wf;
if(dsbdesc.dwBufferBytes < DSBSIZE_MIN || DSBSIZE_MAX < dsbdesc.dwBufferBytes){
throw std::invalid_argument("DirectSound: requested buffer size is out of supported size range [DSBSIZE_MIN, DSBSIZE_MAX]");
}
{
LPDIRECTSOUNDBUFFER dsb1;
if(ds.ds->CreateSoundBuffer(&dsbdesc, &dsb1, nullptr) != DS_OK){
throw std::runtime_error("DirectSound: CreateSoundBuffer() failed");
}
utki::scope_exit dsb1_scope_exit([&dsb1](){dsb1->Release();});
if(dsb1->QueryInterface(IID_IDirectSoundBuffer8, (LPVOID*)&this->dsb) != DS_OK){
throw std::runtime_error("DirectSound: QueryInterface() failed");
}
}
utki::scope_exit dsb_scope_exit([this](){this->dsb->Release();});
// init buffer with silence, i.e. fill it with 0'es
{
LPVOID addr;
DWORD size;
// lock the entire buffer
if(this->dsb->Lock(
0,
0, // ignored because of the DSBLOCK_ENTIREBUFFER flag
&addr,
&size,
nullptr, // wraparound not needed
0, // size of wraparound not needed
DSBLOCK_ENTIREBUFFER
) != DS_OK)
{
throw std::runtime_error("DirectSound: buffer Lock() failed");
}
ASSERT(addr != 0)
ASSERT(size == 2 * this->halfSize)
// set buffer to 0'es
memset(addr, 0, size);
// unlock the buffer
if(this->dsb->Unlock(addr, size, nullptr, 0) != DS_OK){
throw std::runtime_error("DirectSound: buffer Unlock() failed");
}
}
this->dsb->SetCurrentPosition(0);
dsb_scope_exit.reset();
}
~direct_sound_buffer()noexcept{
this->dsb->Release();
}
} dsb;
WinEvent event1, event2;
void fillDSBuffer(unsigned partNum){
ASSERT(partNum == 0 || partNum == 1)
LPVOID addr;
DWORD size;
// lock the second part of buffer
if(this->dsb.dsb->Lock(
this->dsb.halfSize * partNum, // offset
this->dsb.halfSize, // size
&addr,
&size,
nullptr, // wraparound not needed
0, // size of wraparound not needed
0 // no flags
) != DS_OK)
{
TRACE(<< "DirectSound thread: locking buffer failed" << std::endl)
return;
}
ASSERT(addr != 0)
ASSERT(size == this->dsb.halfSize)
this->listener->fillPlayBuf(utki::make_span(static_cast<std::int16_t*>(addr), size / 2));
// unlock the buffer
if(this->dsb.dsb->Unlock(addr, size, nullptr, 0) != DS_OK){
TRACE(<< "DirectSound thread: unlocking buffer failed" << std::endl)
ASSERT(false)
}
}
void run(){
opros::wait_set ws(3);
ws.add(this->queue, {opros::ready::read});
ws.add(this->event1, {opros::ready::read});
ws.add(this->event2, {opros::ready::read});
while(!this->quitFlag){
// TRACE(<< "Backend loop" << std::endl)
ws.wait();
if(this->queue.flags().get(opros::ready::read)){
while(auto m = this->queue.pop_front()){
m();
}
}
// if first buffer playing has started, then fill the second one
if(this->event1.flags().get(opros::ready::read)){
this->fillDSBuffer(1);
}
// if second buffer playing has started, then fill the first one
if(this->event2.flags().get(opros::ready::read)){
this->fillDSBuffer(0);
}
}
ws.remove(this->event2);
ws.remove(this->event1);
ws.remove(this->queue);
}
public:
void setPaused(bool pause){
if(pause){
this->dsb.dsb->Stop();
}else{
this->dsb.dsb->Play(
0, // reserved, must be 0
0,
DSBPLAY_LOOPING
);
}
}
public:
DirectSoundBackend(AudioFormat format, unsigned bufferSizeFrames, Listener* listener) :
listener(listener),
dsb(this->ds, bufferSizeFrames, format)
{
// set notification points
{
LPDIRECTSOUNDNOTIFY notify;
// get IID_IDirectSoundNotify interface
if(this->dsb.dsb->QueryInterface(
IID_IDirectSoundNotify8,
(LPVOID*)¬ify
) != DS_OK)
{
throw std::runtime_error("DirectSound: QueryInterface(IID_IDirectSoundNotify8) failed");
}
utki::scope_exit notify_scope_exit([¬ify](){notify->Release();});
std::array<DSBPOSITIONNOTIFY, 2> pos;
pos[0].dwOffset = 0;
pos[0].hEventNotify = this->event1.get_handle();
pos[1].dwOffset = this->dsb.halfSize;
pos[1].hEventNotify = this->event2.get_handle();
if(notify->SetNotificationPositions(DWORD(pos.size()), pos.data()) != DS_OK){
throw std::runtime_error("DirectSound: SetNotificationPositions() failed");
}
}
// start playing thread
this->thread = std::thread([this](){this->run();});
// launch buffer playing
this->setPaused(false);
}
~DirectSoundBackend()noexcept{
// stop buffer playing
if(this->dsb.dsb->Stop() != DS_OK){
ASSERT(false)
}
// stop playing thread
ASSERT(this->thread.joinable())
this->queue.push_back([this](){this->quitFlag = true;});
this->thread.join();
}
};
}
<commit_msg>windows build fix<commit_after>#pragma once
#include <utki/config.hpp>
#include <opros/wait_set.hpp>
#include <nitki/queue.hpp>
#if M_OS != M_OS_WINDOWS
# error "compiling in non-Windows environment"
#endif
#include <cstring>
#include <thread>
#include <initguid.h> // The header file initguid.h is required to avoid the error message "undefined reference to `IID_IDirectSoundBuffer8'".
#include <dsound.h>
#include "../Player.hpp"
#include "../Exc.hpp"
namespace audout{
class WinEvent : public opros::waitable{
HANDLE eventForWaitable;
utki::flags<opros::ready> waiting_flags;
virtual void set_waiting_flags(utki::flags<opros::ready> wait_for)override{
// Only possible flag values are 'read' or 0 (not ready)
if(!(wait_for & (~utki::make_flags({opros::ready::read}))).is_clear()){
ASSERT_INFO(false, "wait_for = " << wait_for)
throw audout::Exc("WinEvent::set_waiting_flags(): only 'read' or no flags are allowed");
}
this->waiting_flags = wait_for;
}
bool check_signaled()override{
switch(WaitForSingleObject(this->eventForWaitable, 0)){
case WAIT_OBJECT_0: // event is signaled
this->readiness_flags.set(opros::ready::read);
if(ResetEvent(this->eventForWaitable) == 0){
ASSERT(false)
throw std::system_error(GetLastError(), std::generic_category(), "ResetEvent() failed");
}
break;
case WAIT_ABANDONED:
case WAIT_TIMEOUT: // event is not signalled
this->readiness_flags.clear(opros::ready::read);
break;
default:
case WAIT_FAILED:
throw std::system_error(GetLastError(), std::generic_category(), "WaitForSingleObject() failed");
}
return !(this->waiting_flags & this->flags()).is_clear();
}
public:
HANDLE get_handle()override{
return this->eventForWaitable;
}
WinEvent(){
this->eventForWaitable = CreateEvent(
nullptr, // security attributes
TRUE, // manual-reset
FALSE, // not signaled initially
nullptr // no name
);
if(this->eventForWaitable == 0){
throw std::system_error(GetLastError(), std::generic_category(), "CreateEvent() failed");
}
}
virtual ~WinEvent()noexcept{
CloseHandle(this->eventForWaitable);
}
};
class DirectSoundBackend{
Listener* listener;
std::thread thread;
nitki::queue queue;
bool quitFlag = false;
struct direct_sound{
LPDIRECTSOUND8 ds; // LP prefix means long pointer
direct_sound(){
if(DirectSoundCreate8(nullptr, &this->ds, nullptr) != DS_OK){
throw std::runtime_error("DirectSoundCreate8() failed");
}
utki::scope_exit ds_scope_exit([this](){
this->ds->Release();
});
HWND hwnd = GetDesktopWindow();
if(!hwnd){
throw std::runtime_error("no foreground window found");
}
if(this->ds->SetCooperativeLevel(hwnd, DSSCL_PRIORITY) != DS_OK){
throw std::runtime_error("SetCooperativeLevel() failed");
}
ds_scope_exit.reset();
}
~direct_sound()noexcept{
this->ds->Release();
}
} ds;
struct direct_sound_buffer{
LPDIRECTSOUNDBUFFER8 dsb; // LP stands for long pointer
unsigned halfSize;
direct_sound_buffer(direct_sound& ds, unsigned bufferSizeFrames, AudioFormat format) :
halfSize(format.bytesPerFrame() * bufferSizeFrames)
{
WAVEFORMATEX wf;
memset(&wf, 0, sizeof(WAVEFORMATEX));
wf.nChannels = format.numChannels();
wf.nSamplesPerSec = format.frequency();
wf.wFormatTag = WAVE_FORMAT_PCM;
wf.wBitsPerSample = 16;
wf.nBlockAlign = wf.nChannels * (wf.wBitsPerSample / 8);
wf.nAvgBytesPerSec = wf.nSamplesPerSec * wf.nBlockAlign;
DSBUFFERDESC dsbdesc;
memset(&dsbdesc, 0, sizeof(DSBUFFERDESC));
dsbdesc.dwSize = sizeof(DSBUFFERDESC);
dsbdesc.dwFlags = DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_CTRLPOSITIONNOTIFY | DSBCAPS_GLOBALFOCUS;
dsbdesc.dwBufferBytes = 2 * this->halfSize;
dsbdesc.lpwfxFormat = &wf;
if(dsbdesc.dwBufferBytes < DSBSIZE_MIN || DSBSIZE_MAX < dsbdesc.dwBufferBytes){
throw std::invalid_argument("DirectSound: requested buffer size is out of supported size range [DSBSIZE_MIN, DSBSIZE_MAX]");
}
{
LPDIRECTSOUNDBUFFER dsb1;
if(ds.ds->CreateSoundBuffer(&dsbdesc, &dsb1, nullptr) != DS_OK){
throw std::runtime_error("DirectSound: CreateSoundBuffer() failed");
}
utki::scope_exit dsb1_scope_exit([&dsb1](){dsb1->Release();});
if(dsb1->QueryInterface(IID_IDirectSoundBuffer8, (LPVOID*)&this->dsb) != DS_OK){
throw std::runtime_error("DirectSound: QueryInterface() failed");
}
}
utki::scope_exit dsb_scope_exit([this](){this->dsb->Release();});
// init buffer with silence, i.e. fill it with 0'es
{
LPVOID addr;
DWORD size;
// lock the entire buffer
if(this->dsb->Lock(
0,
0, // ignored because of the DSBLOCK_ENTIREBUFFER flag
&addr,
&size,
nullptr, // wraparound not needed
0, // size of wraparound not needed
DSBLOCK_ENTIREBUFFER
) != DS_OK)
{
throw std::runtime_error("DirectSound: buffer Lock() failed");
}
ASSERT(addr != 0)
ASSERT(size == 2 * this->halfSize)
// set buffer to 0'es
memset(addr, 0, size);
// unlock the buffer
if(this->dsb->Unlock(addr, size, nullptr, 0) != DS_OK){
throw std::runtime_error("DirectSound: buffer Unlock() failed");
}
}
this->dsb->SetCurrentPosition(0);
dsb_scope_exit.reset();
}
~direct_sound_buffer()noexcept{
this->dsb->Release();
}
} dsb;
WinEvent event1, event2;
void fillDSBuffer(unsigned partNum){
ASSERT(partNum == 0 || partNum == 1)
LPVOID addr;
DWORD size;
// lock the second part of buffer
if(this->dsb.dsb->Lock(
this->dsb.halfSize * partNum, // offset
this->dsb.halfSize, // size
&addr,
&size,
nullptr, // wraparound not needed
0, // size of wraparound not needed
0 // no flags
) != DS_OK)
{
TRACE(<< "DirectSound thread: locking buffer failed" << std::endl)
return;
}
ASSERT(addr != 0)
ASSERT(size == this->dsb.halfSize)
this->listener->fillPlayBuf(utki::make_span(static_cast<std::int16_t*>(addr), size / 2));
// unlock the buffer
if(this->dsb.dsb->Unlock(addr, size, nullptr, 0) != DS_OK){
TRACE(<< "DirectSound thread: unlocking buffer failed" << std::endl)
ASSERT(false)
}
}
void run(){
opros::wait_set ws(3);
ws.add(this->queue, {opros::ready::read});
ws.add(this->event1, {opros::ready::read});
ws.add(this->event2, {opros::ready::read});
while(!this->quitFlag){
// TRACE(<< "Backend loop" << std::endl)
ws.wait();
if(this->queue.flags().get(opros::ready::read)){
while(auto m = this->queue.pop_front()){
m();
}
}
// if first buffer playing has started, then fill the second one
if(this->event1.flags().get(opros::ready::read)){
this->fillDSBuffer(1);
}
// if second buffer playing has started, then fill the first one
if(this->event2.flags().get(opros::ready::read)){
this->fillDSBuffer(0);
}
}
ws.remove(this->event2);
ws.remove(this->event1);
ws.remove(this->queue);
}
public:
void setPaused(bool pause){
if(pause){
this->dsb.dsb->Stop();
}else{
this->dsb.dsb->Play(
0, // reserved, must be 0
0,
DSBPLAY_LOOPING
);
}
}
public:
DirectSoundBackend(AudioFormat format, unsigned bufferSizeFrames, Listener* listener) :
listener(listener),
dsb(this->ds, bufferSizeFrames, format)
{
// set notification points
{
LPDIRECTSOUNDNOTIFY notify;
// get IID_IDirectSoundNotify interface
if(this->dsb.dsb->QueryInterface(
IID_IDirectSoundNotify8,
(LPVOID*)¬ify
) != DS_OK)
{
throw std::runtime_error("DirectSound: QueryInterface(IID_IDirectSoundNotify8) failed");
}
utki::scope_exit notify_scope_exit([¬ify](){notify->Release();});
std::array<DSBPOSITIONNOTIFY, 2> pos;
pos[0].dwOffset = 0;
pos[0].hEventNotify = this->event1.get_handle();
pos[1].dwOffset = this->dsb.halfSize;
pos[1].hEventNotify = this->event2.get_handle();
if(notify->SetNotificationPositions(DWORD(pos.size()), pos.data()) != DS_OK){
throw std::runtime_error("DirectSound: SetNotificationPositions() failed");
}
}
// start playing thread
this->thread = std::thread([this](){this->run();});
// launch buffer playing
this->setPaused(false);
}
~DirectSoundBackend()noexcept{
// stop buffer playing
if(this->dsb.dsb->Stop() != DS_OK){
ASSERT(false)
}
// stop playing thread
ASSERT(this->thread.joinable())
this->queue.push_back([this](){this->quitFlag = true;});
this->thread.join();
}
};
}
<|endoftext|>
|
<commit_before>// This file is part of the dune-stuff project:
// http://users.dune-project.org/projects/dune-stuff/
// Copyright Holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifdef HAVE_CMAKE_CONFIG
# include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
# include "config.h"
#endif
#include "constant.hh"
namespace Dune {
namespace Stuff {
namespace Function {
// ====================
// ===== Constant =====
// ====================
template< class E, class D, int d, class R, int r >
std::string Constant< E, D, d, R, r >::static_id()
{
return BaseType::static_id() + ".constant";
}
template< class E, class D, int d, class R, int r >
Dune::ParameterTree Constant< E, D, d, R, r >::defaultSettings(const std::string subName)
{
Dune::ParameterTree description;
description["value"] = "1.0";
if (subName.empty())
return description;
else {
Dune::Stuff::Common::ExtendedParameterTree extendedDescription;
extendedDescription.add(description, subName);
return extendedDescription;
}
} // ... defaultSettings(...)
template< class E, class D, int d, class R, int r >
typename Constant< E, D, d, R, r >::ThisType* Constant< E, D, d, R, r >::create(const DSC::ExtendedParameterTree settings)
{
typedef typename Constant< E, D, d, R, r >::ThisType ThisType;
typedef typename Constant< E, D, d, R, r >::RangeFieldType RangeFieldType;
return new ThisType(settings.get< RangeFieldType >("value", RangeFieldType(0)));
} // ... create(...)
template< class E, class D, int d, class R, int r >
Constant< E, D, d, R, r >::Constant(const RangeFieldType& val, const std::string nm)
: value_(std::make_shared< RangeType >(val))
, name_(nm)
{}
template< class E, class D, int d, class R, int r >
Constant< E, D, d, R, r >::Constant(const RangeType& val, const std::string nm)
: value_(std::make_shared< RangeType >(val))
, name_(nm)
{}
template< class E, class D, int d, class R, int r >
Constant< E, D, d, R, r >::Constant(const ThisType& other)
: value_(other.value_)
, name_(other.name_)
{}
template< class E, class D, int d, class R, int r >
typename Constant< E, D, d, R, r >::ThisType& Constant< E, D, d, R, r >::operator=(const ThisType& other)
{
if (this != &other) {
value_ = other.value_;
name_ = other.name_;
}
return *this;
}
template< class E, class D, int d, class R, int r >
typename Constant< E, D, d, R, r >::ThisType* Constant< E, D, d, R, r >::copy() const
{
return new ThisType(*this);
}
template< class E, class D, int d, class R, int r >
std::string Constant< E, D, d, R, r >::name() const
{
return name_;
}
template< class E, class D, int d, class R, int r >
std::unique_ptr< typename Constant< E, D, d, R, r >::LocalfunctionType >
Constant< E, D, d, R, r >::local_function(const EntityType& entity) const
{
return std::unique_ptr< Localfunction >(new Localfunction(entity, value_));
}
} // namespace Function
} // namespace Stuff
} // namespace Dune
#include <dune/stuff/grid/fakeentity.hh>
typedef Dune::Stuff::Grid::FakeEntity< 1 > DuneStuffFake1dEntityType;
typedef Dune::Stuff::Grid::FakeEntity< 2 > DuneStuffFake2dEntityType;
typedef Dune::Stuff::Grid::FakeEntity< 3 > DuneStuffFake3dEntityType;
template class Dune::Stuff::Function::Constant< DuneStuffFake1dEntityType, double, 1, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneStuffFake1dEntityType, double, 1, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneStuffFake1dEntityType, double, 1, double, 3 >;
//template class Dune::Stuff::Function::Constant< DuneStuffFake2dEntityType, double, 2, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneStuffFake2dEntityType, double, 2, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneStuffFake2dEntityType, double, 2, double, 3 >;
//template class Dune::Stuff::Function::Constant< DuneStuffFake3dEntityType, double, 3, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneStuffFake3dEntityType, double, 3, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneStuffFake3dEntityType, double, 3, double, 3 >;
//#ifdef HAVE_DUNE_GRID
//# include <dune/grid/sgrid.hh>
//typedef typename Dune::SGrid< 1, 1 >::template Codim< 0 >::Entity DuneSGrid1dEntityType;
//typedef typename Dune::SGrid< 2, 2 >::template Codim< 0 >::Entity DuneSGrid2dEntityType;
//typedef typename Dune::SGrid< 3, 3 >::template Codim< 0 >::Entity DuneSGrid3dEntityType;
//template class Dune::Stuff::Function::Constant< DuneSGrid1dEntityType, double, 1, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneSGrid1dEntityType, double, 1, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneSGrid1dEntityType, double, 1, double, 3 >;
//template class Dune::Stuff::Function::Constant< DuneSGrid2dEntityType, double, 2, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneSGrid2dEntityType, double, 2, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneSGrid2dEntityType, double, 2, double, 3 >;
//template class Dune::Stuff::Function::Constant< DuneSGrid3dEntityType, double, 3, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneSGrid3dEntityType, double, 3, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneSGrid3dEntityType, double, 3, double, 3 >;
//# include <dune/grid/yaspgrid.hh>
//typedef typename Dune::YaspGrid< 1 >::template Codim< 0 >::Entity DuneYaspGrid1dEntityType;
//typedef typename Dune::YaspGrid< 2 >::template Codim< 0 >::Entity DuneYaspGrid2dEntityType;
//typedef typename Dune::YaspGrid< 3 >::template Codim< 0 >::Entity DuneYaspGrid3dEntityType;
//template class Dune::Stuff::Function::Constant< DuneYaspGrid1dEntityType, double, 1, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneYaspGrid1dEntityType, double, 1, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneYaspGrid1dEntityType, double, 1, double, 3 >;
//template class Dune::Stuff::Function::Constant< DuneYaspGrid2dEntityType, double, 2, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneYaspGrid2dEntityType, double, 2, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneYaspGrid2dEntityType, double, 2, double, 3 >;
//template class Dune::Stuff::Function::Constant< DuneYaspGrid3dEntityType, double, 3, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneYaspGrid3dEntityType, double, 3, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneYaspGrid3dEntityType, double, 3, double, 3 >;
//# if HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
//# define ALUGRID_CONFORM 1
//# define ENABLE_ALUGRID 1
//# include <dune/grid/alugrid.hh>
//typedef typename Dune::ALUSimplexGrid< 2, 2 >::template Codim< 0 >::Entity DuneAluSimplexGrid2dEntityType;
//typedef typename Dune::ALUSimplexGrid< 3, 3 >::template Codim< 0 >::Entity DuneAluSimplexGrid3dEntityType;
//typedef typename Dune::ALUCubeGrid< 3, 3 >::template Codim< 0 >::Entity DuneAluCubeGrid3dEntityType;
//template class Dune::Stuff::Function::Constant< DuneAluSimplexGrid2dEntityType, double, 2, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneAluSimplexGrid2dEntityType, double, 2, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneAluSimplexGrid2dEntityType, double, 2, double, 3 >;
//template class Dune::Stuff::Function::Constant< DuneAluSimplexGrid3dEntityType, double, 3, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneAluSimplexGrid3dEntityType, double, 3, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneAluSimplexGrid3dEntityType, double, 3, double, 3 >;
//template class Dune::Stuff::Function::Constant< DuneAluCubeGrid3dEntityType, double, 3, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneAluCubeGrid3dEntityType, double, 3, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneAluCubeGrid3dEntityType, double, 3, double, 3 >;
//# endif // HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
//#endif // HAVE_DUNE_GRID
<commit_msg>[functions.constant] use generator macros for lib<commit_after>// This file is part of the dune-stuff project:
// http://users.dune-project.org/projects/dune-stuff/
// Copyright Holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifdef HAVE_CMAKE_CONFIG
# include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
# include "config.h"
#endif
#include "constant.hh"
namespace Dune {
namespace Stuff {
namespace Function {
// ====================
// ===== Constant =====
// ====================
template< class E, class D, int d, class R, int r, int rC >
std::string Constant< E, D, d, R, r, rC >::static_id()
{
return BaseType::static_id() + ".constant";
}
template< class E, class D, int d, class R, int r, int rC >
Dune::ParameterTree Constant< E, D, d, R, r, rC >::defaultSettings(const std::string subName)
{
Dune::ParameterTree description;
description["value"] = "1.0";
if (subName.empty())
return description;
else {
Dune::Stuff::Common::ExtendedParameterTree extendedDescription;
extendedDescription.add(description, subName);
return extendedDescription;
}
} // ... defaultSettings(...)
template< class E, class D, int d, class R, int r, int rC >
typename Constant< E, D, d, R, r, rC >::ThisType* Constant< E, D, d, R, r, rC >::create(const DSC::ExtendedParameterTree settings)
{
typedef typename Constant< E, D, d, R, r, rC >::ThisType ThisType;
typedef typename Constant< E, D, d, R, r, rC >::RangeFieldType RangeFieldType;
return new ThisType(settings.get< RangeFieldType >("value", RangeFieldType(0)));
} // ... create(...)
template< class E, class D, int d, class R, int r, int rC >
Constant< E, D, d, R, r, rC >::Constant(const RangeFieldType& val, const std::string nm)
: value_(std::make_shared< RangeType >(val))
, name_(nm)
{}
template< class E, class D, int d, class R, int r, int rC >
Constant< E, D, d, R, r, rC >::Constant(const RangeType& val, const std::string nm)
: value_(std::make_shared< RangeType >(val))
, name_(nm)
{}
template< class E, class D, int d, class R, int r, int rC >
Constant< E, D, d, R, r, rC >::Constant(const ThisType& other)
: value_(other.value_)
, name_(other.name_)
{}
template< class E, class D, int d, class R, int r, int rC >
typename Constant< E, D, d, R, r, rC >::ThisType& Constant< E, D, d, R, r, rC >::operator=(const ThisType& other)
{
if (this != &other) {
value_ = other.value_;
name_ = other.name_;
}
return *this;
}
template< class E, class D, int d, class R, int r, int rC >
typename Constant< E, D, d, R, r, rC >::ThisType* Constant< E, D, d, R, r, rC >::copy() const
{
return new ThisType(*this);
}
template< class E, class D, int d, class R, int r, int rC >
std::string Constant< E, D, d, R, r, rC >::name() const
{
return name_;
}
template< class E, class D, int d, class R, int r, int rC >
std::unique_ptr< typename Constant< E, D, d, R, r, rC >::LocalfunctionType >
Constant< E, D, d, R, r, rC >::local_function(const EntityType& entity) const
{
return std::unique_ptr< Localfunction >(new Localfunction(entity, value_));
}
} // namespace Function
} // namespace Stuff
} // namespace Dune
#define DSF_LIST_DIMDOMAIN(etype) \
DSF_LIST_DIMRANGE(etype, 1) \
DSF_LIST_DIMRANGE(etype, 2) \
DSF_LIST_DIMRANGE(etype, 3)
#define DSF_LIST_DIMRANGE(etype, ddim) \
DSF_LIST_DIMRANGECOLS(Dune::Stuff::Function::Constant, etype, ddim, 1) \
DSF_LIST_DIMRANGECOLS(Dune::Stuff::Function::Constant, etype, ddim, 2) \
DSF_LIST_DIMRANGECOLS(Dune::Stuff::Function::Constant, etype, ddim, 3)
#define DSF_LIST_DIMRANGECOLS(cname, etype, ddim, rdim) \
DSF_LIST_DOMAINFIELDTYPES(cname, etype, ddim, rdim, 1) \
DSF_LIST_DOMAINFIELDTYPES(cname, etype, ddim, rdim, 2) \
DSF_LIST_DOMAINFIELDTYPES(cname, etype, ddim, rdim, 3)
#define DSF_LIST_DOMAINFIELDTYPES(cname, etype, ddim, rdim, rcdim) \
DSF_LIST_RANGEFIELDTYPES(cname, etype, double, ddim, rdim, rcdim)
#define DSF_LIST_RANGEFIELDTYPES(cname, etype, dftype, ddim, rdim, rcdim) \
DSF_LAST_EXPANSION(cname, etype, dftype, ddim, double, rdim, rcdim) \
DSF_LAST_EXPANSION(cname, etype, dftype, ddim, long double, rdim, rcdim)
#define DSF_LAST_EXPANSION(cname, etype, dftype, ddim, rftype, rdim, rcdim) \
template class cname< etype, dftype, ddim, rftype, rdim, rcdim >;
#include <dune/stuff/grid/fakeentity.hh>
typedef Dune::Stuff::Grid::FakeEntity< 1 > DuneStuffFake1dEntityType;
typedef Dune::Stuff::Grid::FakeEntity< 2 > DuneStuffFake2dEntityType;
typedef Dune::Stuff::Grid::FakeEntity< 3 > DuneStuffFake3dEntityType;
DSF_LIST_DIMDOMAIN(DuneStuffFake1dEntityType)
DSF_LIST_DIMDOMAIN(DuneStuffFake2dEntityType)
DSF_LIST_DIMDOMAIN(DuneStuffFake3dEntityType)
#ifdef HAVE_DUNE_GRID
# include <dune/grid/sgrid.hh>
typedef typename Dune::SGrid< 1, 1 >::template Codim< 0 >::Entity DuneSGrid1dEntityType;
typedef typename Dune::SGrid< 2, 2 >::template Codim< 0 >::Entity DuneSGrid2dEntityType;
typedef typename Dune::SGrid< 3, 3 >::template Codim< 0 >::Entity DuneSGrid3dEntityType;
DSF_LIST_DIMDOMAIN(DuneSGrid1dEntityType)
DSF_LIST_DIMDOMAIN(DuneSGrid2dEntityType)
DSF_LIST_DIMDOMAIN(DuneSGrid3dEntityType)
# include <dune/grid/yaspgrid.hh>
typedef typename Dune::YaspGrid< 1 >::template Codim< 0 >::Entity DuneYaspGrid1dEntityType;
typedef typename Dune::YaspGrid< 2 >::template Codim< 0 >::Entity DuneYaspGrid2dEntityType;
typedef typename Dune::YaspGrid< 3 >::template Codim< 0 >::Entity DuneYaspGrid3dEntityType;
DSF_LIST_DIMDOMAIN(DuneYaspGrid1dEntityType)
DSF_LIST_DIMDOMAIN(DuneYaspGrid2dEntityType)
DSF_LIST_DIMDOMAIN(DuneYaspGrid3dEntityType)
# if HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
# define ALUGRID_CONFORM 1
# define ENABLE_ALUGRID 1
# include <dune/grid/alugrid.hh>
typedef typename Dune::ALUSimplexGrid< 2, 2 >::template Codim< 0 >::Entity DuneAluSimplexGrid2dEntityType;
typedef typename Dune::ALUSimplexGrid< 3, 3 >::template Codim< 0 >::Entity DuneAluSimplexGrid3dEntityType;
typedef typename Dune::ALUCubeGrid< 3, 3 >::template Codim< 0 >::Entity DuneAluCubeGrid3dEntityType;
DSF_LIST_DIMRANGE(DuneAluSimplexGrid2dEntityType, 2)
DSF_LIST_DIMRANGE(DuneAluSimplexGrid3dEntityType, 3)
DSF_LIST_DIMRANGE(DuneAluCubeGrid3dEntityType, 3)
# endif // HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
#endif // HAVE_DUNE_GRID
<|endoftext|>
|
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH *
* *
* 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 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 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Framework *
* *
* Authors: The SOFA Team (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include <sofa/helper/system/PluginManager.h>
#include <sofa/helper/system/FileRepository.h>
#include <sofa/helper/system/SetDirectory.h>
#include <fstream>
namespace sofa
{
namespace helper
{
namespace system
{
namespace
{
#ifdef NDEBUG
const std::string pluginsIniFile = "config/sofaplugins_release.ini";
#else
const std::string pluginsIniFile = "config/sofaplugins_debug.ini";
#endif
template <class LibraryEntry>
bool getPluginEntry(LibraryEntry& entry, DynamicLibrary* plugin, std::ostream* errlog)
{
typedef typename LibraryEntry::FuncPtr FuncPtr;
entry.func = (FuncPtr)plugin->getSymbol(entry.symbol,errlog);
if( entry.func == 0 )
{
return false;
}
else
{
return true;
}
}
} // namespace
const char* Plugin::GetModuleComponentList::symbol = "getModuleComponentList";
const char* Plugin::InitExternalModule::symbol = "initExternalModule";
const char* Plugin::GetModuleDescription::symbol = "getModuleDescription";
const char* Plugin::GetModuleLicense::symbol = "getModuleLicense";
const char* Plugin::GetModuleName::symbol = "getModuleName";
const char* Plugin::GetModuleVersion::symbol = "getModuleVersion";
PluginManager & PluginManager::getInstance()
{
static PluginManager instance;
return instance;
}
PluginManager::~PluginManager()
{
// BUGFIX: writeToIniFile should not be called here as it will erase the file in case it was not loaded
// Instead we write the file each time a change have been made in the GUI and should be saved
//writeToIniFile();
}
void PluginManager::readFromIniFile()
{
std::string path= pluginsIniFile;
if ( !DataRepository.findFile(path) )
{
path = DataRepository.getFirstPath() + "/" + pluginsIniFile;
std::ofstream ofile(path.c_str());
ofile << "";
ofile.close();
}
else path = DataRepository.getFile( pluginsIniFile );
std::ifstream instream(path.c_str());
std::string pluginPath;
while(std::getline(instream,pluginPath))
{
if(loadPlugin(pluginPath))
m_pluginMap[pluginPath].initExternalModule();
}
instream.close();
}
void PluginManager::writeToIniFile()
{
std::string path= pluginsIniFile;
if ( !DataRepository.findFile(path) )
{
path = DataRepository.getFirstPath() + "/" + pluginsIniFile;
std::ofstream ofile(path.c_str(),std::ios::out);
ofile << "";
ofile.close();
}
else path = DataRepository.getFile( pluginsIniFile );
std::ofstream outstream(path.c_str());
PluginIterator iter;
for( iter = m_pluginMap.begin(); iter!=m_pluginMap.end(); ++iter)
{
const std::string& pluginPath = (iter->first);
outstream << pluginPath << "\n";
}
outstream.close();
}
bool PluginManager::loadPlugin(std::string& pluginPath, std::ostream* errlog)
{
if (sofa::helper::system::SetDirectory::GetParentDir(pluginPath.c_str()).empty() &&
sofa::helper::system::SetDirectory::GetExtension(pluginPath.c_str()).empty())
{
// no path and extension -> automatically add suffix and OS-specific extension
#ifdef SOFA_LIBSUFFIX
pluginPath += sofa_tostring(SOFA_LIBSUFFIX)
#endif
#if defined (WIN32)
pluginPath = pluginPath + std::string(".dll");
#elif defined (__APPLE__)
pluginPath = std::string("lib") + pluginPath + std::string(".dylib");
#else
pluginPath = std::string("lib") + pluginPath + std::string(".so");
#endif
}
if( !PluginRepository.findFile(pluginPath,"",errlog) )
{
return false;
}
if(m_pluginMap.find(pluginPath) != m_pluginMap.end() )
{
(*errlog) << "Plugin " << pluginPath << " already in PluginManager" << std::endl;
return false;
}
DynamicLibrary* d = DynamicLibrary::load(pluginPath, errlog);
Plugin p;
if( d == NULL )
{
return false;
}
else
{
if(! getPluginEntry(p.initExternalModule,d,errlog) ) return false;
getPluginEntry(p.getModuleName,d,errlog);
getPluginEntry(p.getModuleDescription,d,errlog);
getPluginEntry(p.getModuleLicense,d,errlog);
getPluginEntry(p.getModuleComponentList,d,errlog);
getPluginEntry(p.getModuleVersion,d,errlog);
}
p.dynamicLibrary = boost::shared_ptr<DynamicLibrary>(d);
m_pluginMap[pluginPath] = p;
return true;
}
bool PluginManager::unloadPlugin(std::string &pluginPath, std::ostream *errlog)
{
PluginMap::iterator iter;
iter = m_pluginMap.find(pluginPath);
if( iter == m_pluginMap.end() )
{
if (sofa::helper::system::SetDirectory::GetParentDir(pluginPath.c_str()).empty() &&
sofa::helper::system::SetDirectory::GetExtension(pluginPath.c_str()).empty())
{
// no path and extension -> automatically add suffix and OS-specific extension
#ifdef SOFA_LIBSUFFIX
pluginPath += sofa_tostring(SOFA_LIBSUFFIX)
#endif
#if defined (WIN32)
pluginPath = pluginPath + std::string(".dll");
#elif defined (__APPLE__)
pluginPath = std::string("lib") + pluginPath + std::string(".dylib");
#else
pluginPath = std::string("lib") + pluginPath + std::string(".so");
#endif
}
PluginRepository.findFile(pluginPath,"",errlog);
iter = m_pluginMap.find(pluginPath);
}
if( iter == m_pluginMap.end() )
{
(*errlog) << "Plugin " << pluginPath << "not in PluginManager" << std::endl;
return false;
}
else
{
m_pluginMap.erase(iter);
return true;
}
}
void PluginManager::initRecentlyOpened()
{
readFromIniFile();
}
std::istream& PluginManager::readFromStream(std::istream & in)
{
while(!in.eof())
{
std::string pluginPath;
in >> pluginPath;
loadPlugin(pluginPath);
}
return in;
}
std::ostream& PluginManager::writeToStream(std::ostream & os) const
{
PluginMap::const_iterator iter;
for(iter= m_pluginMap.begin(); iter!=m_pluginMap.end(); ++iter)
{
os << iter->first;
}
return os;
}
void PluginManager::init()
{
PluginMap::iterator iter;
for( iter = m_pluginMap.begin(); iter!= m_pluginMap.end(); ++iter)
{
Plugin& plugin = iter->second;
plugin.initExternalModule();
}
}
}
}
}
<commit_msg>r12416/sofa-dev : FIX: compilation<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH *
* *
* 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 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 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Framework *
* *
* Authors: The SOFA Team (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include <sofa/helper/system/PluginManager.h>
#include <sofa/helper/system/FileRepository.h>
#include <sofa/helper/system/SetDirectory.h>
#include <fstream>
namespace sofa
{
namespace helper
{
namespace system
{
namespace
{
#ifdef NDEBUG
const std::string pluginsIniFile = "config/sofaplugins_release.ini";
#else
const std::string pluginsIniFile = "config/sofaplugins_debug.ini";
#endif
template <class LibraryEntry>
bool getPluginEntry(LibraryEntry& entry, DynamicLibrary* plugin, std::ostream* errlog)
{
typedef typename LibraryEntry::FuncPtr FuncPtr;
entry.func = (FuncPtr)plugin->getSymbol(entry.symbol,errlog);
if( entry.func == 0 )
{
return false;
}
else
{
return true;
}
}
} // namespace
const char* Plugin::GetModuleComponentList::symbol = "getModuleComponentList";
const char* Plugin::InitExternalModule::symbol = "initExternalModule";
const char* Plugin::GetModuleDescription::symbol = "getModuleDescription";
const char* Plugin::GetModuleLicense::symbol = "getModuleLicense";
const char* Plugin::GetModuleName::symbol = "getModuleName";
const char* Plugin::GetModuleVersion::symbol = "getModuleVersion";
PluginManager & PluginManager::getInstance()
{
static PluginManager instance;
return instance;
}
PluginManager::~PluginManager()
{
// BUGFIX: writeToIniFile should not be called here as it will erase the file in case it was not loaded
// Instead we write the file each time a change have been made in the GUI and should be saved
//writeToIniFile();
}
void PluginManager::readFromIniFile()
{
std::string path= pluginsIniFile;
if ( !DataRepository.findFile(path) )
{
path = DataRepository.getFirstPath() + "/" + pluginsIniFile;
std::ofstream ofile(path.c_str());
ofile << "";
ofile.close();
}
else path = DataRepository.getFile( pluginsIniFile );
std::ifstream instream(path.c_str());
std::string pluginPath;
while(std::getline(instream,pluginPath))
{
if(loadPlugin(pluginPath))
m_pluginMap[pluginPath].initExternalModule();
}
instream.close();
}
void PluginManager::writeToIniFile()
{
std::string path= pluginsIniFile;
if ( !DataRepository.findFile(path) )
{
path = DataRepository.getFirstPath() + "/" + pluginsIniFile;
std::ofstream ofile(path.c_str(),std::ios::out);
ofile << "";
ofile.close();
}
else path = DataRepository.getFile( pluginsIniFile );
std::ofstream outstream(path.c_str());
PluginIterator iter;
for( iter = m_pluginMap.begin(); iter!=m_pluginMap.end(); ++iter)
{
const std::string& pluginPath = (iter->first);
outstream << pluginPath << "\n";
}
outstream.close();
}
bool PluginManager::loadPlugin(std::string& pluginPath, std::ostream* errlog)
{
if (sofa::helper::system::SetDirectory::GetParentDir(pluginPath.c_str()).empty() &&
sofa::helper::system::SetDirectory::GetExtension(pluginPath.c_str()).empty())
{
// no path and extension -> automatically add suffix and OS-specific extension
#ifdef SOFA_LIBSUFFIX
pluginPath += sofa_tostring(SOFA_LIBSUFFIX);
#endif
#if defined (WIN32)
pluginPath = pluginPath + std::string(".dll");
#elif defined (__APPLE__)
pluginPath = std::string("lib") + pluginPath + std::string(".dylib");
#else
pluginPath = std::string("lib") + pluginPath + std::string(".so");
#endif
}
if( !PluginRepository.findFile(pluginPath,"",errlog) )
{
return false;
}
if(m_pluginMap.find(pluginPath) != m_pluginMap.end() )
{
(*errlog) << "Plugin " << pluginPath << " already in PluginManager" << std::endl;
return false;
}
DynamicLibrary* d = DynamicLibrary::load(pluginPath, errlog);
Plugin p;
if( d == NULL )
{
return false;
}
else
{
if(! getPluginEntry(p.initExternalModule,d,errlog) ) return false;
getPluginEntry(p.getModuleName,d,errlog);
getPluginEntry(p.getModuleDescription,d,errlog);
getPluginEntry(p.getModuleLicense,d,errlog);
getPluginEntry(p.getModuleComponentList,d,errlog);
getPluginEntry(p.getModuleVersion,d,errlog);
}
p.dynamicLibrary = boost::shared_ptr<DynamicLibrary>(d);
m_pluginMap[pluginPath] = p;
return true;
}
bool PluginManager::unloadPlugin(std::string &pluginPath, std::ostream *errlog)
{
PluginMap::iterator iter;
iter = m_pluginMap.find(pluginPath);
if( iter == m_pluginMap.end() )
{
if (sofa::helper::system::SetDirectory::GetParentDir(pluginPath.c_str()).empty() &&
sofa::helper::system::SetDirectory::GetExtension(pluginPath.c_str()).empty())
{
// no path and extension -> automatically add suffix and OS-specific extension
#ifdef SOFA_LIBSUFFIX
pluginPath += sofa_tostring(SOFA_LIBSUFFIX);
#endif
#if defined (WIN32)
pluginPath = pluginPath + std::string(".dll");
#elif defined (__APPLE__)
pluginPath = std::string("lib") + pluginPath + std::string(".dylib");
#else
pluginPath = std::string("lib") + pluginPath + std::string(".so");
#endif
}
PluginRepository.findFile(pluginPath,"",errlog);
iter = m_pluginMap.find(pluginPath);
}
if( iter == m_pluginMap.end() )
{
(*errlog) << "Plugin " << pluginPath << "not in PluginManager" << std::endl;
return false;
}
else
{
m_pluginMap.erase(iter);
return true;
}
}
void PluginManager::initRecentlyOpened()
{
readFromIniFile();
}
std::istream& PluginManager::readFromStream(std::istream & in)
{
while(!in.eof())
{
std::string pluginPath;
in >> pluginPath;
loadPlugin(pluginPath);
}
return in;
}
std::ostream& PluginManager::writeToStream(std::ostream & os) const
{
PluginMap::const_iterator iter;
for(iter= m_pluginMap.begin(); iter!=m_pluginMap.end(); ++iter)
{
os << iter->first;
}
return os;
}
void PluginManager::init()
{
PluginMap::iterator iter;
for( iter = m_pluginMap.begin(); iter!= m_pluginMap.end(); ++iter)
{
Plugin& plugin = iter->second;
plugin.initExternalModule();
}
}
}
}
}
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////////
// Licensed to Qualys, Inc. (QUALYS) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// QUALYS 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.
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
/// @file
/// @brief IronBee --- Action Test Functions
///
/// @author Craig Forbes <cforbes@qualys.com>
//////////////////////////////////////////////////////////////////////////////
#include <ironbee/action.h>
#include <ironbee/server.h>
#include <ironbee/engine.h>
#include <ironbee/mpool.h>
#include "gtest/gtest.h"
#include "base_fixture.h"
class ActionTest : public BaseFixture {
};
TEST_F(ActionTest, RegisterTest) {
ib_status_t status;
status = ib_action_register(ib_engine,
"test_action",
IB_ACT_FLAG_NONE,
NULL, NULL,
NULL, NULL,
NULL, NULL);
EXPECT_EQ(IB_OK, status);
}
TEST_F(ActionTest, RegisterDup) {
ib_status_t status;
status = ib_action_register(ib_engine,
"test_action",
IB_ACT_FLAG_NONE,
NULL, NULL,
NULL, NULL,
NULL, NULL);
ASSERT_EQ(IB_OK, status);
status = ib_action_register(ib_engine,
"test_action",
IB_ACT_FLAG_NONE,
NULL, NULL,
NULL, NULL,
NULL, NULL);
EXPECT_EQ(IB_EINVAL, status);
}
TEST_F(ActionTest, CallAction) {
ib_status_t status;
ib_action_inst_t *act;
status = ib_action_register(ib_engine,
"test_action",
IB_ACT_FLAG_NONE,
NULL, NULL,
NULL, NULL,
NULL, NULL);
ASSERT_EQ(IB_OK, status);
status = ib_action_inst_create(ib_engine,
"test_action", "parameters",
IB_ACTINST_FLAG_NONE,
&act);
ASSERT_EQ(IB_OK, status);
status = ib_action_execute(NULL, act);
ASSERT_EQ(IB_OK, status);
}
static bool action_executed = false;
static ib_flags_t action_flags = IB_ACTINST_FLAG_NONE;
static const char *action_str = NULL;
static ib_status_t create_fn(ib_engine_t *ib,
const char *params,
ib_action_inst_t *inst,
void *cbdata)
{
if (strcmp(params, "INVALID") == 0) {
return IB_EINVAL;
}
inst->data = ib_mpool_strdup(ib_engine_pool_main_get(ib), params);
return IB_OK;
}
static ib_status_t execute_fn(const ib_rule_exec_t *rule_exec,
void *data,
ib_flags_t flags,
void *cbdata)
{
action_executed = true;
action_str = (const char *)data;
action_flags = flags;
return IB_OK;
}
TEST_F(ActionTest, ExecuteAction) {
ib_status_t status;
ib_action_inst_t *act;
ib_flags_t flags = (1 << 10);
const char *params = "parameters";
status = ib_action_register(ib_engine,
"test_action",
IB_ACT_FLAG_NONE,
create_fn, NULL,
NULL, NULL,
execute_fn, NULL);
ASSERT_EQ(IB_OK, status);
status = ib_action_inst_create(ib_engine,
"test_action",
"INVALID",
flags,
&act);
ASSERT_EQ(IB_EINVAL, status);
status = ib_action_inst_create(ib_engine,
"test_action",
params,
flags,
&act);
ASSERT_EQ(IB_OK, status);
action_executed = false;
status = ib_action_execute(NULL, act);
ASSERT_EQ(IB_OK, status);
ASSERT_TRUE(action_executed);
EXPECT_STREQ(action_str, params);
EXPECT_EQ(action_flags, flags);
}
<commit_msg>test_action.cpp: Making unit test more C++ie.<commit_after>//////////////////////////////////////////////////////////////////////////////
// Licensed to Qualys, Inc. (QUALYS) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// QUALYS 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.
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
/// @file
/// @brief IronBee --- Action Test Functions
///
/// @author Craig Forbes <cforbes@qualys.com>
//////////////////////////////////////////////////////////////////////////////
#include <ironbee/action.h>
#include <ironbee/server.h>
#include <ironbee/engine.h>
#include <ironbee/mpool.h>
#include "gtest/gtest.h"
#include "base_fixture.h"
class ActionTest : public BaseFixture {
};
TEST_F(ActionTest, RegisterTest) {
ib_status_t status;
status = ib_action_register(ib_engine,
"test_action",
IB_ACT_FLAG_NONE,
NULL, NULL,
NULL, NULL,
NULL, NULL);
EXPECT_EQ(IB_OK, status);
}
TEST_F(ActionTest, RegisterDup) {
ib_status_t status;
status = ib_action_register(ib_engine,
"test_action",
IB_ACT_FLAG_NONE,
NULL, NULL,
NULL, NULL,
NULL, NULL);
ASSERT_EQ(IB_OK, status);
status = ib_action_register(ib_engine,
"test_action",
IB_ACT_FLAG_NONE,
NULL, NULL,
NULL, NULL,
NULL, NULL);
EXPECT_EQ(IB_EINVAL, status);
}
TEST_F(ActionTest, CallAction) {
ib_status_t status;
ib_action_inst_t *act;
status = ib_action_register(ib_engine,
"test_action",
IB_ACT_FLAG_NONE,
NULL, NULL,
NULL, NULL,
NULL, NULL);
ASSERT_EQ(IB_OK, status);
status = ib_action_inst_create(ib_engine,
"test_action", "parameters",
IB_ACTINST_FLAG_NONE,
&act);
ASSERT_EQ(IB_OK, status);
status = ib_action_execute(NULL, act);
ASSERT_EQ(IB_OK, status);
}
namespace {
extern "C" {
static bool action_executed = false;
static ib_flags_t action_flags = IB_ACTINST_FLAG_NONE;
static const char *action_str = NULL;
ib_status_t create_fn(ib_engine_t *ib,
const char *params,
ib_action_inst_t *inst,
void *cbdata)
{
if (strcmp(params, "INVALID") == 0) {
return IB_EINVAL;
}
inst->data = ib_mpool_strdup(ib_engine_pool_main_get(ib), params);
return IB_OK;
}
ib_status_t execute_fn(const ib_rule_exec_t *rule_exec,
void *data,
ib_flags_t flags,
void *cbdata)
{
action_executed = true;
action_str = (const char *)data;
action_flags = flags;
return IB_OK;
}
}
}
TEST_F(ActionTest, ExecuteAction) {
ib_status_t status;
ib_action_inst_t *act;
ib_flags_t flags = (1 << 10);
const char *params = "parameters";
status = ib_action_register(ib_engine,
"test_action",
IB_ACT_FLAG_NONE,
create_fn, NULL,
NULL, NULL,
execute_fn, NULL);
ASSERT_EQ(IB_OK, status);
status = ib_action_inst_create(ib_engine,
"test_action",
"INVALID",
flags,
&act);
ASSERT_EQ(IB_EINVAL, status);
status = ib_action_inst_create(ib_engine,
"test_action",
params,
flags,
&act);
ASSERT_EQ(IB_OK, status);
action_executed = false;
status = ib_action_execute(NULL, act);
ASSERT_EQ(IB_OK, status);
ASSERT_TRUE(action_executed);
EXPECT_STREQ(action_str, params);
EXPECT_EQ(action_flags, flags);
}
<|endoftext|>
|
<commit_before><commit_msg>Cast pointer before dereferencing. (firebird-sdbc)<commit_after><|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p10/procedures/hwp/perv/p10_pre_poweroff.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2020 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p10_pre_poweroff.C
///
/// @brief Raises the fences
//------------------------------------------------------------------------------
// *HWP HW Maintainer : Anusha Reddy (anusrang@in.ibm.com)
// *HWP FW Maintainer : Raja Das (rajadas2@in.ibm.com)
// *HWP Consumed by : FSP
//------------------------------------------------------------------------------
#include "p10_pre_poweroff.H"
#include "p10_scom_perv.H"
enum P10_PRE_POWEROFF_Private_Constants
{
HW_NS_DELAY = 200, // unit is nano seconds
SIM_CYCLE_DELAY = 100000 // unit is sim cycles
};
fapi2::ReturnCode p10_pre_poweroff(const
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip)
{
using namespace scomt::perv;
fapi2::buffer<uint32_t> l_read_reg_rc0, l_read_reg_pc0, l_read_reg_rc1, l_read_reg_rc7;
FAPI_INF("p10_pre_poweroff : Entering ...");
FAPI_DBG("Assert all PERST# outputs");
l_read_reg_rc1.flush<0>().setBit<FSXCOMP_FSXLOG_ROOT_CTRL1_TPFSI_TP_GLB_PERST_OVR_DC>();
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, FSXCOMP_FSXLOG_ROOT_CTRL1_CLEAR_FSI,
l_read_reg_rc1));
// wait 1ms
fapi2::delay(HW_NS_DELAY, SIM_CYCLE_DELAY);
FAPI_DBG("Raise pervasive chiplet fence and endpoint reset");
l_read_reg_pc0.flush<0>()
.setBit<FSXCOMP_FSXLOG_PERV_CTRL0_TP_FENCE_EN_DC>()
.setBit<FSXCOMP_FSXLOG_PERV_CTRL0_TP_TCPERV_PCB_EP_RESET_DC>();
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, FSXCOMP_FSXLOG_PERV_CTRL0_SET_FSI,
l_read_reg_pc0));
// RC0 bit0: cfam protection 0, bit8: cfam protection 1, bit9: cfam protection 2
FAPI_DBG("Raise Cfam protection");
l_read_reg_rc0.flush<0>()
.setBit<FSXCOMP_FSXLOG_ROOT_CTRL0_CFAM_PROTECTION_0_DC>()
.setBit<FSXCOMP_FSXLOG_ROOT_CTRL0_CFAM_PROTECTION_1_DC>()
.setBit<FSXCOMP_FSXLOG_ROOT_CTRL0_CFAM_PROTECTION_2_DC>()
.setBit<FSXCOMP_FSXLOG_ROOT_CTRL0_CFAM_PIB_SLV_RESET_DC>()
.setBit<FSXCOMP_FSXLOG_ROOT_CTRL0_ROOT_CTRL0_11_SPARE>()
.setBit<FSXCOMP_FSXLOG_ROOT_CTRL0_ROOT_CTRL0_12_SPARE>()
.setBit<FSXCOMP_FSXLOG_ROOT_CTRL0_ROOT_CTRL0_13_SPARE>()
.setBit<FSXCOMP_FSXLOG_ROOT_CTRL0_SPARE_FENCE_CONTROL>();
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, FSXCOMP_FSXLOG_ROOT_CTRL0_SET_FSI,
l_read_reg_rc0));
FAPI_DBG("Set global endpoint reset");
l_read_reg_rc0.flush<0>().setBit<FSXCOMP_FSXLOG_ROOT_CTRL0_GLOBAL_EP_RESET_DC>();
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, FSXCOMP_FSXLOG_ROOT_CTRL0_SET_FSI,
l_read_reg_rc0));
FAPI_DBG("Turn off all outgoing refclocks");
l_read_reg_rc7.flush<0>().setBit<0, 28>();
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, FSXCOMP_FSXLOG_ROOT_CTRL7_CLEAR_FSI,
l_read_reg_rc7));
FAPI_DBG("Disable TP drivers and receivers");
l_read_reg_rc1.flush<0>()
.setBit<FSXCOMP_FSXLOG_ROOT_CTRL1_TP_RI_DC_B>()
.setBit<FSXCOMP_FSXLOG_ROOT_CTRL1_TP_DI1_DC_B>()
.setBit<FSXCOMP_FSXLOG_ROOT_CTRL1_TP_DI2_DC_B>()
.setBit<FSXCOMP_FSXLOG_ROOT_CTRL1_TP_TPM_DI1_DC_B>();
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, FSXCOMP_FSXLOG_ROOT_CTRL1_CLEAR_FSI,
l_read_reg_rc1));
FAPI_DBG("Clear FSI I2C fence to allow access from FSP side");
l_read_reg_rc0.flush<0>().setBit<FSXCOMP_FSXLOG_ROOT_CTRL0_TPFSI_TPI2C_BUS_FENCE_DC>();
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, FSXCOMP_FSXLOG_ROOT_CTRL0_CLEAR_FSI,
l_read_reg_rc0));
FAPI_INF("p10_pre_poweroff : Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
<commit_msg>p10_pre_poweroff: Assert OCMB reset<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p10/procedures/hwp/perv/p10_pre_poweroff.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2020 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p10_pre_poweroff.C
///
/// @brief Raises the fences
//------------------------------------------------------------------------------
// *HWP HW Maintainer : Anusha Reddy (anusrang@in.ibm.com)
// *HWP FW Maintainer : Raja Das (rajadas2@in.ibm.com)
// *HWP Consumed by : FSP
//------------------------------------------------------------------------------
#include "p10_pre_poweroff.H"
#include "p10_scom_perv.H"
enum P10_PRE_POWEROFF_Private_Constants
{
HW_NS_DELAY = 200, // unit is nano seconds
SIM_CYCLE_DELAY = 100000 // unit is sim cycles
};
fapi2::ReturnCode p10_pre_poweroff(const
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip)
{
using namespace scomt::perv;
fapi2::buffer<uint32_t> l_read_reg_rc0, l_read_reg_pc0, l_read_reg_rc1, l_read_reg_rc7;
FAPI_INF("p10_pre_poweroff : Entering ...");
FAPI_DBG("Assert all PERST# outputs");
l_read_reg_rc1.flush<0>().setBit<FSXCOMP_FSXLOG_ROOT_CTRL1_TPFSI_TP_GLB_PERST_OVR_DC>();
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, FSXCOMP_FSXLOG_ROOT_CTRL1_CLEAR_FSI,
l_read_reg_rc1));
FAPI_DBG("Assert OCMB reset");
l_read_reg_rc0.flush<0>().setBit<FSXCOMP_FSXLOG_ROOT_CTRL0_TPFSI_IO_OCMB_RESET_EN>();
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, FSXCOMP_FSXLOG_ROOT_CTRL0_SET_FSI,
l_read_reg_rc0));
// wait 1ms
fapi2::delay(HW_NS_DELAY, SIM_CYCLE_DELAY);
FAPI_DBG("Raise pervasive chiplet fence and endpoint reset");
l_read_reg_pc0.flush<0>()
.setBit<FSXCOMP_FSXLOG_PERV_CTRL0_TP_FENCE_EN_DC>()
.setBit<FSXCOMP_FSXLOG_PERV_CTRL0_TP_TCPERV_PCB_EP_RESET_DC>();
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, FSXCOMP_FSXLOG_PERV_CTRL0_SET_FSI,
l_read_reg_pc0));
// RC0 bit0: cfam protection 0, bit8: cfam protection 1, bit9: cfam protection 2
FAPI_DBG("Raise Cfam protection");
l_read_reg_rc0.flush<0>()
.setBit<FSXCOMP_FSXLOG_ROOT_CTRL0_CFAM_PROTECTION_0_DC>()
.setBit<FSXCOMP_FSXLOG_ROOT_CTRL0_CFAM_PROTECTION_1_DC>()
.setBit<FSXCOMP_FSXLOG_ROOT_CTRL0_CFAM_PROTECTION_2_DC>()
.setBit<FSXCOMP_FSXLOG_ROOT_CTRL0_CFAM_PIB_SLV_RESET_DC>()
.setBit<FSXCOMP_FSXLOG_ROOT_CTRL0_ROOT_CTRL0_11_SPARE>()
.setBit<FSXCOMP_FSXLOG_ROOT_CTRL0_ROOT_CTRL0_12_SPARE>()
.setBit<FSXCOMP_FSXLOG_ROOT_CTRL0_ROOT_CTRL0_13_SPARE>()
.setBit<FSXCOMP_FSXLOG_ROOT_CTRL0_SPARE_FENCE_CONTROL>();
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, FSXCOMP_FSXLOG_ROOT_CTRL0_SET_FSI,
l_read_reg_rc0));
FAPI_DBG("Set global endpoint reset");
l_read_reg_rc0.flush<0>().setBit<FSXCOMP_FSXLOG_ROOT_CTRL0_GLOBAL_EP_RESET_DC>();
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, FSXCOMP_FSXLOG_ROOT_CTRL0_SET_FSI,
l_read_reg_rc0));
FAPI_DBG("Turn off all outgoing refclocks");
l_read_reg_rc7.flush<0>().setBit<0, 28>();
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, FSXCOMP_FSXLOG_ROOT_CTRL7_CLEAR_FSI,
l_read_reg_rc7));
FAPI_DBG("Disable TP drivers and receivers");
l_read_reg_rc1.flush<0>()
.setBit<FSXCOMP_FSXLOG_ROOT_CTRL1_TP_RI_DC_B>()
.setBit<FSXCOMP_FSXLOG_ROOT_CTRL1_TP_DI1_DC_B>()
.setBit<FSXCOMP_FSXLOG_ROOT_CTRL1_TP_DI2_DC_B>()
.setBit<FSXCOMP_FSXLOG_ROOT_CTRL1_TP_TPM_DI1_DC_B>();
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, FSXCOMP_FSXLOG_ROOT_CTRL1_CLEAR_FSI,
l_read_reg_rc1));
FAPI_DBG("Clear FSI I2C fence to allow access from FSP side");
l_read_reg_rc0.flush<0>().setBit<FSXCOMP_FSXLOG_ROOT_CTRL0_TPFSI_TPI2C_BUS_FENCE_DC>();
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, FSXCOMP_FSXLOG_ROOT_CTRL0_CLEAR_FSI,
l_read_reg_rc0));
FAPI_INF("p10_pre_poweroff : Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_obus_scominit.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_io_obus_scominit.C
/// @brief Invoke OBUS initfile
///
//----------------------------------------------------------------------------
// *HWP HWP Owner : Chris Steffen <cwsteffen@us.ibm.com>
// *HWP HWP Backup Owner: Gary Peterson <garyp@us.ibm.com>
// *HWP FW Owner : Sumit Kumar <sumit_kumar@in.ibm.com>
// *HWP Team : IO
// *HWP Level : 2
// *HWP Consumed by : FSP:HB
//----------------------------------------------------------------------------
//
// @verbatim
// High-level procedure flow:
//
// Invoke OBUS scominit file.
//
// Procedure Prereq:
// - System clocks are running.
// @endverbatim
//----------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <p9_io_scom.H>
#include <p9_io_regs.H>
#include <p9_obus_scom.H>
#include <p9_io_obus_scominit.H>
#include <p9_obus_scom_addresses.H>
//------------------------------------------------------------------------------
// Constant definitions
//------------------------------------------------------------------------------
const uint64_t FIR_ACTION0 = 0x0000000000000000ULL;
const uint64_t FIR_ACTION1 = 0x2000000000000000ULL;
const uint64_t FIR_MASK = 0xDFFFFFFFFFFFC000ULL;
//------------------------------------------------------------------------------
// Function definitions
//------------------------------------------------------------------------------
// HWP entry point, comments in header
fapi2::ReturnCode p9_io_obus_scominit( const fapi2::Target<fapi2::TARGET_TYPE_OBUS>& i_target )
{
// mark HWP entry
FAPI_INF("p9_io_obus_scominit: Entering...");
const uint8_t GROUP_00 = 0;
const uint8_t LANE_00 = 0;
const uint8_t SET_RESET = 1;
const uint8_t CLEAR_RESET = 0;
fapi2::ReturnCode rc = fapi2::FAPI2_RC_SUCCESS;
// get system target
const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> l_system_target;
// get a proc target
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_proc_target = i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>();
// assert IO reset to power-up bus endpoint logic
FAPI_TRY( io::rmw( OPT_IORESET_HARD_BUS0, i_target, GROUP_00, LANE_00, SET_RESET ) );
// Bus Reset is relatively fast, only needing < a hundred cycles to allow the signal to propogate.
FAPI_TRY( fapi2::delay( 10, 1000 ) );
FAPI_TRY( io::rmw( OPT_IORESET_HARD_BUS0, i_target, GROUP_00, LANE_00, CLEAR_RESET ) );
FAPI_INF("Invoke FAPI procedure core: input_target");
FAPI_EXEC_HWP(rc, p9_obus_scom, i_target, l_system_target, l_proc_target);
// configure FIR, use OBUS unit number to form fully qualified SCOM address
{
uint8_t l_unit_pos;
uint64_t l_addr_offset;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS,
i_target,
l_unit_pos),
"Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)");
l_addr_offset = l_unit_pos;
l_addr_offset = l_addr_offset << 24;
FAPI_TRY(fapi2::putScom(l_proc_target,
OBUS_FIR_ACTION0_REG,
FIR_ACTION0),
"Error from putScom (OBUS_FIR_ACTION0_REG)");
FAPI_TRY(fapi2::putScom(l_proc_target,
OBUS_FIR_ACTION1_REG,
FIR_ACTION1),
"Error from putScom (OBUS_FIR_ACTION1_REG)");
FAPI_TRY(fapi2::putScom(l_proc_target,
OBUS_FIR_MASK_REG,
FIR_MASK),
"Error from putScom (OBUS_FIR_MASK_REG)");
}
// mark HWP exit
FAPI_INF("p9_io_obus_scominit: ...Exiting");
fapi_try_exit:
return fapi2::current_err;
}
<commit_msg>p9_io_obus_scominit -- use unit target to apply FIR settings<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_obus_scominit.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_io_obus_scominit.C
/// @brief Invoke OBUS initfile
///
//----------------------------------------------------------------------------
// *HWP HWP Owner : Chris Steffen <cwsteffen@us.ibm.com>
// *HWP HWP Backup Owner: Gary Peterson <garyp@us.ibm.com>
// *HWP FW Owner : Sumit Kumar <sumit_kumar@in.ibm.com>
// *HWP Team : IO
// *HWP Level : 2
// *HWP Consumed by : FSP:HB
//----------------------------------------------------------------------------
//
// @verbatim
// High-level procedure flow:
//
// Invoke OBUS scominit file.
//
// Procedure Prereq:
// - System clocks are running.
// @endverbatim
//----------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <p9_io_scom.H>
#include <p9_io_regs.H>
#include <p9_obus_scom.H>
#include <p9_io_obus_scominit.H>
#include <p9_obus_scom_addresses.H>
//------------------------------------------------------------------------------
// Constant definitions
//------------------------------------------------------------------------------
const uint64_t FIR_ACTION0 = 0x0000000000000000ULL;
const uint64_t FIR_ACTION1 = 0x2000000000000000ULL;
const uint64_t FIR_MASK = 0xDFFFFFFFFFFFC000ULL;
//------------------------------------------------------------------------------
// Function definitions
//------------------------------------------------------------------------------
// HWP entry point, comments in header
fapi2::ReturnCode p9_io_obus_scominit( const fapi2::Target<fapi2::TARGET_TYPE_OBUS>& i_target )
{
// mark HWP entry
FAPI_INF("p9_io_obus_scominit: Entering...");
const uint8_t GROUP_00 = 0;
const uint8_t LANE_00 = 0;
const uint8_t SET_RESET = 1;
const uint8_t CLEAR_RESET = 0;
fapi2::ReturnCode rc = fapi2::FAPI2_RC_SUCCESS;
// get system target
const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> l_system_target;
// get a proc target
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_proc_target = i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>();
// assert IO reset to power-up bus endpoint logic
FAPI_TRY( io::rmw( OPT_IORESET_HARD_BUS0, i_target, GROUP_00, LANE_00, SET_RESET ) );
// Bus Reset is relatively fast, only needing < a hundred cycles to allow the signal to propogate.
FAPI_TRY( fapi2::delay( 10, 1000 ) );
FAPI_TRY( io::rmw( OPT_IORESET_HARD_BUS0, i_target, GROUP_00, LANE_00, CLEAR_RESET ) );
FAPI_INF("Invoke FAPI procedure core: input_target");
FAPI_EXEC_HWP(rc, p9_obus_scom, i_target, l_system_target, l_proc_target);
// configure FIR
{
FAPI_TRY(fapi2::putScom(i_target,
OBUS_FIR_ACTION0_REG,
FIR_ACTION0),
"Error from putScom (OBUS_FIR_ACTION0_REG)");
FAPI_TRY(fapi2::putScom(i_target,
OBUS_FIR_ACTION1_REG,
FIR_ACTION1),
"Error from putScom (OBUS_FIR_ACTION1_REG)");
FAPI_TRY(fapi2::putScom(i_target,
OBUS_FIR_MASK_REG,
FIR_MASK),
"Error from putScom (OBUS_FIR_MASK_REG)");
}
// mark HWP exit
FAPI_INF("p9_io_obus_scominit: ...Exiting");
fapi_try_exit:
return fapi2::current_err;
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_scominit.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_scominit.C
/// @brief SCOM inits for PHY, MC
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <p9_mss_scominit.H>
#include <p9n_mca_scom.H>
#include <p9n_mcbist_scom.H>
#include <p9n_ddrphy_scom.H>
#include <lib/utils/count_dimm.H>
#include <generic/memory/lib/utils/find.H>
#include <lib/phy/ddr_phy.H>
#include <lib/mc/mc.H>
#include <lib/fir/unmask.H>
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::FAPI2_RC_SUCCESS;
///
/// @brief SCOM inits for PHY, MC
/// @param[in] i_target, the MCBIST
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_scominit( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )
{
FAPI_INF("Start MSS SCOM init");
// We need to make sure we scominit the magic port.
const auto l_mca_targets = mss::find_targets_with_magic<TARGET_TYPE_MCA>(i_target);
fapi2::ReturnCode l_rc;
fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;
if (mss::count_dimm(i_target) == 0)
{
FAPI_INF("... skipping mss_scominit %s - no DIMM ...", mss::c_str(i_target));
return fapi2::FAPI2_RC_SUCCESS;
}
for (const auto& l_mca_target : l_mca_targets )
{
FAPI_INF("scominit for %s", mss::c_str(l_mca_target));
// Can't MCA init ports with no DIMM, they don't have attributes like timing.
if (mss::count_dimm(l_mca_target) != 0)
{
FAPI_INF("mca scominit for %s", mss::c_str(l_mca_target));
FAPI_EXEC_HWP(l_rc, p9n_mca_scom, l_mca_target, i_target, l_mca_target.getParent<fapi2::TARGET_TYPE_MCS>(),
FAPI_SYSTEM, i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>());
if (l_rc)
{
FAPI_ERR("Error from p9.mca.scom.initfile");
fapi2::current_err = l_rc;
goto fapi_try_exit;
}
FAPI_INF("mca thermal throttle scominit for %s", mss::c_str(l_mca_target));
FAPI_TRY(mss::mc::thermal_throttle_scominit(l_mca_target));
}
// ... but we do scominit PHY's with no DIMM. There are no attributes needed and we need
// to make sure we init the magic port.
FAPI_INF("phy scominit for %s", mss::c_str(l_mca_target));
FAPI_EXEC_HWP(l_rc, p9n_ddrphy_scom, l_mca_target, i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>());
if (l_rc)
{
FAPI_ERR("Error from p9.ddrphy.scom.initfile");
fapi2::current_err = l_rc;
goto fapi_try_exit;
}
}
FAPI_EXEC_HWP(l_rc, p9n_mcbist_scom, i_target );
if (l_rc)
{
FAPI_ERR("Error from p9.mcbist.scom.initfile");
fapi2::current_err = l_rc;
goto fapi_try_exit;
}
// Initialize via scoms for non-static PHY items.
FAPI_TRY( mss::phy_scominit(i_target) );
// Do FIRry things
FAPI_TRY( mss::unmask::after_scominit(i_target) );
fapi_try_exit:
FAPI_INF("End MSS SCOM init");
return fapi2::current_err;
}
<commit_msg>Updated MSS HWP's level and owner change<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_scominit.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_scominit.C
/// @brief SCOM inits for PHY, MC
///
// *HWP HWP Owner: Louis Stermole <stermole@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <p9_mss_scominit.H>
#include <p9n_mca_scom.H>
#include <p9n_mcbist_scom.H>
#include <p9n_ddrphy_scom.H>
#include <lib/utils/count_dimm.H>
#include <generic/memory/lib/utils/find.H>
#include <lib/phy/ddr_phy.H>
#include <lib/mc/mc.H>
#include <lib/fir/unmask.H>
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::FAPI2_RC_SUCCESS;
///
/// @brief SCOM inits for PHY, MC
/// @param[in] i_target, the MCBIST
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_scominit( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )
{
FAPI_INF("Start MSS SCOM init");
// We need to make sure we scominit the magic port.
const auto l_mca_targets = mss::find_targets_with_magic<TARGET_TYPE_MCA>(i_target);
fapi2::ReturnCode l_rc;
fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;
if (mss::count_dimm(i_target) == 0)
{
FAPI_INF("... skipping mss_scominit %s - no DIMM ...", mss::c_str(i_target));
return fapi2::FAPI2_RC_SUCCESS;
}
for (const auto& l_mca_target : l_mca_targets )
{
FAPI_INF("scominit for %s", mss::c_str(l_mca_target));
// Can't MCA init ports with no DIMM, they don't have attributes like timing.
if (mss::count_dimm(l_mca_target) != 0)
{
FAPI_INF("mca scominit for %s", mss::c_str(l_mca_target));
FAPI_EXEC_HWP(l_rc, p9n_mca_scom, l_mca_target, i_target, l_mca_target.getParent<fapi2::TARGET_TYPE_MCS>(),
FAPI_SYSTEM, i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>());
if (l_rc)
{
FAPI_ERR("Error from p9.mca.scom.initfile");
fapi2::current_err = l_rc;
goto fapi_try_exit;
}
FAPI_INF("mca thermal throttle scominit for %s", mss::c_str(l_mca_target));
FAPI_TRY(mss::mc::thermal_throttle_scominit(l_mca_target));
}
// ... but we do scominit PHY's with no DIMM. There are no attributes needed and we need
// to make sure we init the magic port.
FAPI_INF("phy scominit for %s", mss::c_str(l_mca_target));
FAPI_EXEC_HWP(l_rc, p9n_ddrphy_scom, l_mca_target, i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>());
if (l_rc)
{
FAPI_ERR("Error from p9.ddrphy.scom.initfile");
fapi2::current_err = l_rc;
goto fapi_try_exit;
}
}
FAPI_EXEC_HWP(l_rc, p9n_mcbist_scom, i_target );
if (l_rc)
{
FAPI_ERR("Error from p9.mcbist.scom.initfile");
fapi2::current_err = l_rc;
goto fapi_try_exit;
}
// Initialize via scoms for non-static PHY items.
FAPI_TRY( mss::phy_scominit(i_target) );
// Do FIRry things
FAPI_TRY( mss::unmask::after_scominit(i_target) );
fapi_try_exit:
FAPI_INF("End MSS SCOM init");
return fapi2::current_err;
}
<|endoftext|>
|
<commit_before><commit_msg>Disable tests failing due webkit (Roll WebKit DEPS 45843:45873). Introduced in r20680. See http://crbug.com/16767. TBR=dimich Review URL: http://codereview.chromium.org/155545<commit_after><|endoftext|>
|
<commit_before><commit_msg>Enable devtools test (fixed upstream)<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2011 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 "chrome/browser/extensions/extension_input_ui_api.h"
#include <string>
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/browser/extensions/extension_event_router.h"
#include "chrome/browser/profiles/profile.h"
#include "third_party/cros/chromeos_cros_api.h"
#include "third_party/cros/chromeos_input_method_ui.h"
namespace events {
const char kOnUpdateAuxiliaryText[] =
"experimental.inputUI.onUpdateAuxiliaryText";
const char kOnUpdateLookupTable[] = "experimental.inputUI.onUpdateLookupTable";
const char kOnSetCursorLocation[] = "experimental.inputUI.onSetCursorLocation";
} // namespace events
class InputUiController {
public:
explicit InputUiController(ExtensionInputUiEventRouter* router);
~InputUiController();
void CandidateClicked(int index, int button, int flags);
void CursorUp();
void CursorDown();
void PageUp();
void PageDown();
private:
// The function is called when |HideAuxiliaryText| signal is received in
// libcros. |ui_controller| is a void pointer to this object.
static void OnHideAuxiliaryText(void* ui_controller);
// The function is called when |HideLookupTable| signal is received in
// libcros. |ui_controller| is a void pointer to this object.
static void OnHideLookupTable(void* ui_controller);
// The function is called when |SetCursorLocation| signal is received
// in libcros. |ui_controller| is a void pointer to this object.
static void OnSetCursorLocation(void* ui_controller,
int x,
int y,
int width,
int height);
// The function is called when |UpdateAuxiliaryText| signal is received
// in libcros. |ui_controller| is a void pointer to this object.
static void OnUpdateAuxiliaryText(void* ui_controller,
const std::string& utf8_text,
bool visible);
// The function is called when |UpdateLookupTable| signal is received
// in libcros. |ui_controller| is a void pointer to this object.
static void OnUpdateLookupTable(void* ui_controller,
const chromeos::InputMethodLookupTable& lookup_table);
// This function is called by libcros when ibus connects or disconnects.
// |ui_controller| is a void pointer to this object.
static void OnConnectionChange(void* ui_controller, bool connected);
ExtensionInputUiEventRouter* router_;
chromeos::InputMethodUiStatusConnection* ui_status_connection_;
DISALLOW_COPY_AND_ASSIGN(InputUiController);
};
InputUiController::InputUiController(
ExtensionInputUiEventRouter* router) :
router_(router),
ui_status_connection_(NULL) {
std::string error;
chromeos::LoadLibcros(NULL, error);
chromeos::InputMethodUiStatusMonitorFunctions functions;
functions.hide_auxiliary_text =
&InputUiController::OnHideAuxiliaryText;
functions.hide_lookup_table =
&InputUiController::OnHideLookupTable;
functions.set_cursor_location =
&InputUiController::OnSetCursorLocation;
functions.update_auxiliary_text =
&InputUiController::OnUpdateAuxiliaryText;
functions.update_lookup_table =
&InputUiController::OnUpdateLookupTable;
ui_status_connection_ = chromeos::MonitorInputMethodUiStatus(functions, this);
if (!ui_status_connection_)
LOG(ERROR) << "chromeos::MonitorInputMethodUiStatus() failed!";
}
InputUiController::~InputUiController() {
chromeos::DisconnectInputMethodUiStatus(ui_status_connection_);
}
void InputUiController::CandidateClicked(
int index, int button, int flags) {
chromeos::NotifyCandidateClicked(ui_status_connection_, index, button, flags);
}
void InputUiController::CursorUp() {
chromeos::NotifyCursorUp(ui_status_connection_);
}
void InputUiController::CursorDown() {
chromeos::NotifyCursorDown(ui_status_connection_);
}
void InputUiController::PageUp() {
chromeos::NotifyPageUp(ui_status_connection_);
}
void InputUiController::PageDown() {
chromeos::NotifyPageDown(ui_status_connection_);
}
void InputUiController::OnHideAuxiliaryText(
void* ui_controller) {
InputUiController *self = static_cast<InputUiController*>(ui_controller);
self->router_->OnHideAuxiliaryText();
}
void InputUiController::OnHideLookupTable(
void* ui_controller) {
InputUiController *self = static_cast<InputUiController*>(ui_controller);
self->router_->OnHideLookupTable();
}
void InputUiController::OnSetCursorLocation(
void* ui_controller,
int x, int y, int width, int height) {
InputUiController *self = static_cast<InputUiController*>(ui_controller);
self->router_->OnSetCursorLocation(x, y, width, height);
}
void InputUiController::OnUpdateAuxiliaryText(
void* ui_controller,
const std::string& utf8_text,
bool visible) {
InputUiController *self = static_cast<InputUiController*>(ui_controller);
if (!visible) {
self->router_->OnHideAuxiliaryText();
} else {
self->router_->OnUpdateAuxiliaryText(utf8_text);
}
}
void InputUiController::OnUpdateLookupTable(
void* ui_controller,
const chromeos::InputMethodLookupTable& lookup_table) {
InputUiController *self = static_cast<InputUiController*>(ui_controller);
self->router_->OnUpdateLookupTable(lookup_table);
}
ExtensionInputUiEventRouter*
ExtensionInputUiEventRouter::GetInstance() {
return Singleton<ExtensionInputUiEventRouter>::get();
}
ExtensionInputUiEventRouter::ExtensionInputUiEventRouter()
: profile_(NULL),
ui_controller_(NULL) {
}
ExtensionInputUiEventRouter::~ExtensionInputUiEventRouter() {
}
void ExtensionInputUiEventRouter::Init() {
if (ui_controller_.get() == NULL) {
ui_controller_.reset(new InputUiController(this));
}
}
void ExtensionInputUiEventRouter::Register(
Profile* profile, const std::string& extension_id) {
profile_ = profile;
extension_id_ = extension_id;
}
void ExtensionInputUiEventRouter::CandidateClicked(Profile* profile,
const std::string& extension_id, int index, int button) {
if (profile_ != profile || extension_id_ != extension_id) {
DLOG(WARNING) << "called from unregistered extension";
}
ui_controller_->CandidateClicked(index, button, 0);
}
void ExtensionInputUiEventRouter::CursorUp(Profile* profile,
const std::string& extension_id) {
if (profile_ != profile || extension_id_ != extension_id) {
DLOG(WARNING) << "called from unregistered extension";
}
ui_controller_->CursorUp();
}
void ExtensionInputUiEventRouter::CursorDown(Profile* profile,
const std::string& extension_id) {
if (profile_ != profile || extension_id_ != extension_id) {
DLOG(WARNING) << "called from unregistered extension";
}
ui_controller_->CursorDown();
}
void ExtensionInputUiEventRouter::PageUp(Profile* profile,
const std::string& extension_id) {
if (profile_ != profile || extension_id_ != extension_id) {
DLOG(WARNING) << "called from unregistered extension";
}
ui_controller_->PageUp();
}
void ExtensionInputUiEventRouter::PageDown(Profile* profile,
const std::string& extension_id) {
if (profile_ != profile || extension_id_ != extension_id) {
DLOG(WARNING) << "called from unregistered extension";
}
ui_controller_->PageDown();
}
void ExtensionInputUiEventRouter::OnHideAuxiliaryText() {
OnUpdateAuxiliaryText("");
}
void ExtensionInputUiEventRouter::OnHideLookupTable() {
if (profile_ == NULL || extension_id_.empty())
return;
DictionaryValue* dict = new DictionaryValue();
dict->SetBoolean("visible", false);
ListValue *candidates = new ListValue();
dict->Set("candidates", candidates);
ListValue args;
args.Append(dict);
std::string json_args;
base::JSONWriter::Write(&args, false, &json_args);
profile_->GetExtensionEventRouter()->DispatchEventToExtension(
extension_id_, events::kOnUpdateLookupTable, json_args, profile_, GURL());
}
void ExtensionInputUiEventRouter::OnSetCursorLocation(
int x, int y, int width, int height) {
if (profile_ == NULL || extension_id_.empty())
return;
ListValue args;
args.Append(Value::CreateIntegerValue(x));
args.Append(Value::CreateIntegerValue(y));
args.Append(Value::CreateIntegerValue(width));
args.Append(Value::CreateIntegerValue(height));
std::string json_args;
base::JSONWriter::Write(&args, false, &json_args);
profile_->GetExtensionEventRouter()->DispatchEventToExtension(
extension_id_, events::kOnSetCursorLocation, json_args, profile_, GURL());
}
void ExtensionInputUiEventRouter::OnUpdateAuxiliaryText(
const std::string& utf8_text) {
if (profile_ == NULL || extension_id_.empty())
return;
ListValue args;
args.Append(Value::CreateStringValue(utf8_text));
std::string json_args;
base::JSONWriter::Write(&args, false, &json_args);
profile_->GetExtensionEventRouter()->DispatchEventToExtension(
extension_id_, events::kOnUpdateAuxiliaryText, json_args, profile_, GURL());
}
void ExtensionInputUiEventRouter::OnUpdateLookupTable(
const chromeos::InputMethodLookupTable& lookup_table) {
if (profile_ == NULL || extension_id_.empty())
return;
DictionaryValue* dict = new DictionaryValue();
dict->SetBoolean("visible", lookup_table.visible);
if (lookup_table.visible) {
}
ListValue *candidates = new ListValue();
for (size_t i = 0; i < lookup_table.candidates.size(); i++) {
candidates->Append(Value::CreateStringValue(lookup_table.candidates[i]));
}
dict->Set("candidates", candidates);
ListValue args;
args.Append(dict);
std::string json_args;
base::JSONWriter::Write(&args, false, &json_args);
profile_->GetExtensionEventRouter()->DispatchEventToExtension(
extension_id_, events::kOnUpdateLookupTable, json_args, profile_, GURL());
}
bool RegisterInputUiFunction::RunImpl() {
ExtensionInputUiEventRouter::GetInstance()->Register(
profile(), extension_id());
return true;
}
bool CandidateClickedInputUiFunction::RunImpl() {
int index = 0;
int button = 0;
EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &index));
EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(1, &button));
ExtensionInputUiEventRouter::GetInstance()->CandidateClicked(
profile(), extension_id(), index, button);
return true;
}
bool CursorUpInputUiFunction::RunImpl() {
ExtensionInputUiEventRouter::GetInstance()->CursorUp(
profile(), extension_id());
return true;
}
bool CursorDownInputUiFunction::RunImpl() {
ExtensionInputUiEventRouter::GetInstance()->CursorDown(
profile(), extension_id());
return true;
}
bool PageUpInputUiFunction::RunImpl() {
ExtensionInputUiEventRouter::GetInstance()->PageUp(
profile(), extension_id());
return true;
}
bool PageDownInputUiFunction::RunImpl() {
ExtensionInputUiEventRouter::GetInstance()->PageDown(
profile(), extension_id());
return true;
}
<commit_msg>Use chromeos::CrosLibrary::Get()->EnsureLoaded() to replace chromeos::LoadLibcros()<commit_after>// Copyright (c) 2011 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 "chrome/browser/extensions/extension_input_ui_api.h"
#include <string>
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/extensions/extension_event_router.h"
#include "chrome/browser/profiles/profile.h"
#include "third_party/cros/chromeos_cros_api.h"
#include "third_party/cros/chromeos_input_method_ui.h"
namespace events {
const char kOnUpdateAuxiliaryText[] =
"experimental.inputUI.onUpdateAuxiliaryText";
const char kOnUpdateLookupTable[] = "experimental.inputUI.onUpdateLookupTable";
const char kOnSetCursorLocation[] = "experimental.inputUI.onSetCursorLocation";
} // namespace events
class InputUiController {
public:
explicit InputUiController(ExtensionInputUiEventRouter* router);
~InputUiController();
void CandidateClicked(int index, int button, int flags);
void CursorUp();
void CursorDown();
void PageUp();
void PageDown();
private:
// The function is called when |HideAuxiliaryText| signal is received in
// libcros. |ui_controller| is a void pointer to this object.
static void OnHideAuxiliaryText(void* ui_controller);
// The function is called when |HideLookupTable| signal is received in
// libcros. |ui_controller| is a void pointer to this object.
static void OnHideLookupTable(void* ui_controller);
// The function is called when |SetCursorLocation| signal is received
// in libcros. |ui_controller| is a void pointer to this object.
static void OnSetCursorLocation(void* ui_controller,
int x,
int y,
int width,
int height);
// The function is called when |UpdateAuxiliaryText| signal is received
// in libcros. |ui_controller| is a void pointer to this object.
static void OnUpdateAuxiliaryText(void* ui_controller,
const std::string& utf8_text,
bool visible);
// The function is called when |UpdateLookupTable| signal is received
// in libcros. |ui_controller| is a void pointer to this object.
static void OnUpdateLookupTable(void* ui_controller,
const chromeos::InputMethodLookupTable& lookup_table);
// This function is called by libcros when ibus connects or disconnects.
// |ui_controller| is a void pointer to this object.
static void OnConnectionChange(void* ui_controller, bool connected);
ExtensionInputUiEventRouter* router_;
chromeos::InputMethodUiStatusConnection* ui_status_connection_;
DISALLOW_COPY_AND_ASSIGN(InputUiController);
};
InputUiController::InputUiController(
ExtensionInputUiEventRouter* router) :
router_(router),
ui_status_connection_(NULL) {
if (!chromeos::CrosLibrary::Get()->EnsureLoaded())
return;
chromeos::InputMethodUiStatusMonitorFunctions functions;
functions.hide_auxiliary_text =
&InputUiController::OnHideAuxiliaryText;
functions.hide_lookup_table =
&InputUiController::OnHideLookupTable;
functions.set_cursor_location =
&InputUiController::OnSetCursorLocation;
functions.update_auxiliary_text =
&InputUiController::OnUpdateAuxiliaryText;
functions.update_lookup_table =
&InputUiController::OnUpdateLookupTable;
ui_status_connection_ = chromeos::MonitorInputMethodUiStatus(functions, this);
if (!ui_status_connection_)
LOG(ERROR) << "chromeos::MonitorInputMethodUiStatus() failed!";
}
InputUiController::~InputUiController() {
if (ui_status_connection_)
chromeos::DisconnectInputMethodUiStatus(ui_status_connection_);
}
void InputUiController::CandidateClicked(
int index, int button, int flags) {
chromeos::NotifyCandidateClicked(ui_status_connection_, index, button, flags);
}
void InputUiController::CursorUp() {
chromeos::NotifyCursorUp(ui_status_connection_);
}
void InputUiController::CursorDown() {
chromeos::NotifyCursorDown(ui_status_connection_);
}
void InputUiController::PageUp() {
chromeos::NotifyPageUp(ui_status_connection_);
}
void InputUiController::PageDown() {
chromeos::NotifyPageDown(ui_status_connection_);
}
void InputUiController::OnHideAuxiliaryText(
void* ui_controller) {
InputUiController *self = static_cast<InputUiController*>(ui_controller);
self->router_->OnHideAuxiliaryText();
}
void InputUiController::OnHideLookupTable(
void* ui_controller) {
InputUiController *self = static_cast<InputUiController*>(ui_controller);
self->router_->OnHideLookupTable();
}
void InputUiController::OnSetCursorLocation(
void* ui_controller,
int x, int y, int width, int height) {
InputUiController *self = static_cast<InputUiController*>(ui_controller);
self->router_->OnSetCursorLocation(x, y, width, height);
}
void InputUiController::OnUpdateAuxiliaryText(
void* ui_controller,
const std::string& utf8_text,
bool visible) {
InputUiController *self = static_cast<InputUiController*>(ui_controller);
if (!visible) {
self->router_->OnHideAuxiliaryText();
} else {
self->router_->OnUpdateAuxiliaryText(utf8_text);
}
}
void InputUiController::OnUpdateLookupTable(
void* ui_controller,
const chromeos::InputMethodLookupTable& lookup_table) {
InputUiController *self = static_cast<InputUiController*>(ui_controller);
self->router_->OnUpdateLookupTable(lookup_table);
}
ExtensionInputUiEventRouter*
ExtensionInputUiEventRouter::GetInstance() {
return Singleton<ExtensionInputUiEventRouter>::get();
}
ExtensionInputUiEventRouter::ExtensionInputUiEventRouter()
: profile_(NULL),
ui_controller_(NULL) {
}
ExtensionInputUiEventRouter::~ExtensionInputUiEventRouter() {
}
void ExtensionInputUiEventRouter::Init() {
if (ui_controller_.get() == NULL) {
ui_controller_.reset(new InputUiController(this));
}
}
void ExtensionInputUiEventRouter::Register(
Profile* profile, const std::string& extension_id) {
profile_ = profile;
extension_id_ = extension_id;
}
void ExtensionInputUiEventRouter::CandidateClicked(Profile* profile,
const std::string& extension_id, int index, int button) {
if (profile_ != profile || extension_id_ != extension_id) {
DLOG(WARNING) << "called from unregistered extension";
}
ui_controller_->CandidateClicked(index, button, 0);
}
void ExtensionInputUiEventRouter::CursorUp(Profile* profile,
const std::string& extension_id) {
if (profile_ != profile || extension_id_ != extension_id) {
DLOG(WARNING) << "called from unregistered extension";
}
ui_controller_->CursorUp();
}
void ExtensionInputUiEventRouter::CursorDown(Profile* profile,
const std::string& extension_id) {
if (profile_ != profile || extension_id_ != extension_id) {
DLOG(WARNING) << "called from unregistered extension";
}
ui_controller_->CursorDown();
}
void ExtensionInputUiEventRouter::PageUp(Profile* profile,
const std::string& extension_id) {
if (profile_ != profile || extension_id_ != extension_id) {
DLOG(WARNING) << "called from unregistered extension";
}
ui_controller_->PageUp();
}
void ExtensionInputUiEventRouter::PageDown(Profile* profile,
const std::string& extension_id) {
if (profile_ != profile || extension_id_ != extension_id) {
DLOG(WARNING) << "called from unregistered extension";
}
ui_controller_->PageDown();
}
void ExtensionInputUiEventRouter::OnHideAuxiliaryText() {
OnUpdateAuxiliaryText("");
}
void ExtensionInputUiEventRouter::OnHideLookupTable() {
if (profile_ == NULL || extension_id_.empty())
return;
DictionaryValue* dict = new DictionaryValue();
dict->SetBoolean("visible", false);
ListValue *candidates = new ListValue();
dict->Set("candidates", candidates);
ListValue args;
args.Append(dict);
std::string json_args;
base::JSONWriter::Write(&args, false, &json_args);
profile_->GetExtensionEventRouter()->DispatchEventToExtension(
extension_id_, events::kOnUpdateLookupTable, json_args, profile_, GURL());
}
void ExtensionInputUiEventRouter::OnSetCursorLocation(
int x, int y, int width, int height) {
if (profile_ == NULL || extension_id_.empty())
return;
ListValue args;
args.Append(Value::CreateIntegerValue(x));
args.Append(Value::CreateIntegerValue(y));
args.Append(Value::CreateIntegerValue(width));
args.Append(Value::CreateIntegerValue(height));
std::string json_args;
base::JSONWriter::Write(&args, false, &json_args);
profile_->GetExtensionEventRouter()->DispatchEventToExtension(
extension_id_, events::kOnSetCursorLocation, json_args, profile_, GURL());
}
void ExtensionInputUiEventRouter::OnUpdateAuxiliaryText(
const std::string& utf8_text) {
if (profile_ == NULL || extension_id_.empty())
return;
ListValue args;
args.Append(Value::CreateStringValue(utf8_text));
std::string json_args;
base::JSONWriter::Write(&args, false, &json_args);
profile_->GetExtensionEventRouter()->DispatchEventToExtension(
extension_id_, events::kOnUpdateAuxiliaryText, json_args, profile_, GURL());
}
void ExtensionInputUiEventRouter::OnUpdateLookupTable(
const chromeos::InputMethodLookupTable& lookup_table) {
if (profile_ == NULL || extension_id_.empty())
return;
DictionaryValue* dict = new DictionaryValue();
dict->SetBoolean("visible", lookup_table.visible);
if (lookup_table.visible) {
}
ListValue *candidates = new ListValue();
for (size_t i = 0; i < lookup_table.candidates.size(); i++) {
candidates->Append(Value::CreateStringValue(lookup_table.candidates[i]));
}
dict->Set("candidates", candidates);
ListValue args;
args.Append(dict);
std::string json_args;
base::JSONWriter::Write(&args, false, &json_args);
profile_->GetExtensionEventRouter()->DispatchEventToExtension(
extension_id_, events::kOnUpdateLookupTable, json_args, profile_, GURL());
}
bool RegisterInputUiFunction::RunImpl() {
ExtensionInputUiEventRouter::GetInstance()->Register(
profile(), extension_id());
return true;
}
bool CandidateClickedInputUiFunction::RunImpl() {
int index = 0;
int button = 0;
EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &index));
EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(1, &button));
ExtensionInputUiEventRouter::GetInstance()->CandidateClicked(
profile(), extension_id(), index, button);
return true;
}
bool CursorUpInputUiFunction::RunImpl() {
ExtensionInputUiEventRouter::GetInstance()->CursorUp(
profile(), extension_id());
return true;
}
bool CursorDownInputUiFunction::RunImpl() {
ExtensionInputUiEventRouter::GetInstance()->CursorDown(
profile(), extension_id());
return true;
}
bool PageUpInputUiFunction::RunImpl() {
ExtensionInputUiEventRouter::GetInstance()->PageUp(
profile(), extension_id());
return true;
}
bool PageDownInputUiFunction::RunImpl() {
ExtensionInputUiEventRouter::GetInstance()->PageDown(
profile(), extension_id());
return true;
}
<|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 "chrome/browser/password_manager/password_manager.h"
#include <vector>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/stl_util-inl.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/password_manager/password_form_manager.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_names.h"
#include "grit/generated_resources.h"
using webkit_glue::PasswordForm;
using webkit_glue::PasswordFormMap;
// static
void PasswordManager::RegisterUserPrefs(PrefService* prefs) {
prefs->RegisterBooleanPref(prefs::kPasswordManagerEnabled, true);
}
PasswordManager::PasswordManager(Delegate* delegate)
: login_managers_deleter_(&pending_login_managers_),
delegate_(delegate),
observer_(NULL) {
DCHECK(delegate_);
password_manager_enabled_.Init(prefs::kPasswordManagerEnabled,
delegate_->GetProfileForPasswordManager()->GetPrefs(), NULL);
}
PasswordManager::~PasswordManager() {
}
void PasswordManager::ProvisionallySavePassword(PasswordForm form) {
if (!delegate_->GetProfileForPasswordManager() ||
delegate_->GetProfileForPasswordManager()->IsOffTheRecord() ||
!*password_manager_enabled_)
return;
// No password to save? Then don't.
if (form.password_value.empty())
return;
LoginManagers::iterator iter;
PasswordFormManager* manager = NULL;
for (iter = pending_login_managers_.begin();
iter != pending_login_managers_.end(); iter++) {
if ((*iter)->DoesManage(form)) {
manager = *iter;
break;
}
}
// If we didn't find a manager, this means a form was submitted without
// first loading the page containing the form. Don't offer to save
// passwords in this case.
if (!manager)
return;
// If we found a manager but it didn't finish matching yet, the user has
// tried to submit credentials before we had time to even find matching
// results for the given form and autofill. If this is the case, we just
// give up.
if (!manager->HasCompletedMatching())
return;
// Also get out of here if the user told us to 'never remember' passwords for
// this form.
if (manager->IsBlacklisted())
return;
form.ssl_valid = form.origin.SchemeIsSecure() &&
!delegate_->DidLastPageLoadEncounterSSLErrors();
form.preferred = true;
manager->ProvisionallySave(form);
provisional_save_manager_.reset(manager);
pending_login_managers_.erase(iter);
// We don't care about the rest of the forms on the page now that one
// was selected.
STLDeleteElements(&pending_login_managers_);
}
void PasswordManager::DidNavigate() {
// As long as this navigation isn't due to a currently pending
// password form submit, we're ready to reset and move on.
if (!provisional_save_manager_.get() && !pending_login_managers_.empty())
STLDeleteElements(&pending_login_managers_);
}
void PasswordManager::ClearProvisionalSave() {
provisional_save_manager_.reset();
}
void PasswordManager::DidStopLoading() {
if (!provisional_save_manager_.get())
return;
DCHECK(!delegate_->GetProfileForPasswordManager()->IsOffTheRecord());
DCHECK(!provisional_save_manager_->IsBlacklisted());
if (!delegate_->GetProfileForPasswordManager())
return;
if (provisional_save_manager_->IsNewLogin()) {
delegate_->AddSavePasswordInfoBar(provisional_save_manager_.release());
} else {
// If the save is not a new username entry, then we just want to save this
// data (since the user already has related data saved), so don't prompt.
provisional_save_manager_->Save();
provisional_save_manager_.reset();
}
}
void PasswordManager::PasswordFormsFound(
const std::vector<PasswordForm>& forms) {
if (!delegate_->GetProfileForPasswordManager())
return;
if (!*password_manager_enabled_)
return;
// Ask the SSLManager for current security.
bool had_ssl_error = delegate_->DidLastPageLoadEncounterSSLErrors();
std::vector<PasswordForm>::const_iterator iter;
for (iter = forms.begin(); iter != forms.end(); iter++) {
bool ssl_valid = iter->origin.SchemeIsSecure() && !had_ssl_error;
PasswordFormManager* manager =
new PasswordFormManager(delegate_->GetProfileForPasswordManager(),
this, *iter, ssl_valid);
pending_login_managers_.push_back(manager);
manager->FetchMatchingLoginsFromWebDatabase();
}
}
void PasswordManager::PasswordFormsVisible(
const std::vector<PasswordForm>& visible_forms) {
if (!provisional_save_manager_.get())
return;
std::vector<PasswordForm>::const_iterator iter;
for (iter = visible_forms.begin(); iter != visible_forms.end(); iter++) {
if (provisional_save_manager_->DoesManage(*iter)) {
// The form trying to be saved has immediately re-appeared. Assume login
// failure and abort this save, by clearing provisional_save_manager_.
// Don't delete the login managers since the user may try again
// and we want to be able to save in that case.
provisional_save_manager_.release();
break;
}
}
}
void PasswordManager::Autofill(
const PasswordForm& form_for_autofill,
const PasswordFormMap& best_matches,
const PasswordForm* const preferred_match) const {
DCHECK(preferred_match);
switch (form_for_autofill.scheme) {
case PasswordForm::SCHEME_HTML: {
// Note the check above is required because the observer_ for a non-HTML
// schemed password form may have been freed, so we need to distinguish.
bool action_mismatch = form_for_autofill.action.GetWithEmptyPath() !=
preferred_match->action.GetWithEmptyPath();
webkit_glue::PasswordFormDomManager::FillData fill_data;
webkit_glue::PasswordFormDomManager::InitFillData(form_for_autofill,
best_matches,
preferred_match,
action_mismatch,
&fill_data);
delegate_->FillPasswordForm(fill_data);
return;
}
default:
if (observer_) {
observer_->OnAutofillDataAvailable(
UTF16ToWideHack(preferred_match->username_value),
UTF16ToWideHack(preferred_match->password_value));
}
}
}
<commit_msg>Fix memory leak introduced in r45841. BUG=none TEST=PasswordManagerTest::FormSubmitFailedLogin + valgrind<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 "chrome/browser/password_manager/password_manager.h"
#include <vector>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/stl_util-inl.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/password_manager/password_form_manager.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_names.h"
#include "grit/generated_resources.h"
using webkit_glue::PasswordForm;
using webkit_glue::PasswordFormMap;
// static
void PasswordManager::RegisterUserPrefs(PrefService* prefs) {
prefs->RegisterBooleanPref(prefs::kPasswordManagerEnabled, true);
}
PasswordManager::PasswordManager(Delegate* delegate)
: login_managers_deleter_(&pending_login_managers_),
delegate_(delegate),
observer_(NULL) {
DCHECK(delegate_);
password_manager_enabled_.Init(prefs::kPasswordManagerEnabled,
delegate_->GetProfileForPasswordManager()->GetPrefs(), NULL);
}
PasswordManager::~PasswordManager() {
}
void PasswordManager::ProvisionallySavePassword(PasswordForm form) {
if (!delegate_->GetProfileForPasswordManager() ||
delegate_->GetProfileForPasswordManager()->IsOffTheRecord() ||
!*password_manager_enabled_)
return;
// No password to save? Then don't.
if (form.password_value.empty())
return;
LoginManagers::iterator iter;
PasswordFormManager* manager = NULL;
for (iter = pending_login_managers_.begin();
iter != pending_login_managers_.end(); iter++) {
if ((*iter)->DoesManage(form)) {
manager = *iter;
break;
}
}
// If we didn't find a manager, this means a form was submitted without
// first loading the page containing the form. Don't offer to save
// passwords in this case.
if (!manager)
return;
// If we found a manager but it didn't finish matching yet, the user has
// tried to submit credentials before we had time to even find matching
// results for the given form and autofill. If this is the case, we just
// give up.
if (!manager->HasCompletedMatching())
return;
// Also get out of here if the user told us to 'never remember' passwords for
// this form.
if (manager->IsBlacklisted())
return;
form.ssl_valid = form.origin.SchemeIsSecure() &&
!delegate_->DidLastPageLoadEncounterSSLErrors();
form.preferred = true;
manager->ProvisionallySave(form);
provisional_save_manager_.reset(manager);
pending_login_managers_.erase(iter);
// We don't care about the rest of the forms on the page now that one
// was selected.
STLDeleteElements(&pending_login_managers_);
}
void PasswordManager::DidNavigate() {
// As long as this navigation isn't due to a currently pending
// password form submit, we're ready to reset and move on.
if (!provisional_save_manager_.get() && !pending_login_managers_.empty())
STLDeleteElements(&pending_login_managers_);
}
void PasswordManager::ClearProvisionalSave() {
provisional_save_manager_.reset();
}
void PasswordManager::DidStopLoading() {
if (!provisional_save_manager_.get())
return;
DCHECK(!delegate_->GetProfileForPasswordManager()->IsOffTheRecord());
DCHECK(!provisional_save_manager_->IsBlacklisted());
if (!delegate_->GetProfileForPasswordManager())
return;
if (provisional_save_manager_->IsNewLogin()) {
delegate_->AddSavePasswordInfoBar(provisional_save_manager_.release());
} else {
// If the save is not a new username entry, then we just want to save this
// data (since the user already has related data saved), so don't prompt.
provisional_save_manager_->Save();
provisional_save_manager_.reset();
}
}
void PasswordManager::PasswordFormsFound(
const std::vector<PasswordForm>& forms) {
if (!delegate_->GetProfileForPasswordManager())
return;
if (!*password_manager_enabled_)
return;
// Ask the SSLManager for current security.
bool had_ssl_error = delegate_->DidLastPageLoadEncounterSSLErrors();
std::vector<PasswordForm>::const_iterator iter;
for (iter = forms.begin(); iter != forms.end(); iter++) {
bool ssl_valid = iter->origin.SchemeIsSecure() && !had_ssl_error;
PasswordFormManager* manager =
new PasswordFormManager(delegate_->GetProfileForPasswordManager(),
this, *iter, ssl_valid);
pending_login_managers_.push_back(manager);
manager->FetchMatchingLoginsFromWebDatabase();
}
}
void PasswordManager::PasswordFormsVisible(
const std::vector<PasswordForm>& visible_forms) {
if (!provisional_save_manager_.get())
return;
std::vector<PasswordForm>::const_iterator iter;
for (iter = visible_forms.begin(); iter != visible_forms.end(); iter++) {
if (provisional_save_manager_->DoesManage(*iter)) {
// The form trying to be saved has immediately re-appeared. Assume login
// failure and abort this save, by clearing provisional_save_manager_.
// Don't delete the login managers since the user may try again
// and we want to be able to save in that case.
ClearProvisionalSave();
break;
}
}
}
void PasswordManager::Autofill(
const PasswordForm& form_for_autofill,
const PasswordFormMap& best_matches,
const PasswordForm* const preferred_match) const {
DCHECK(preferred_match);
switch (form_for_autofill.scheme) {
case PasswordForm::SCHEME_HTML: {
// Note the check above is required because the observer_ for a non-HTML
// schemed password form may have been freed, so we need to distinguish.
bool action_mismatch = form_for_autofill.action.GetWithEmptyPath() !=
preferred_match->action.GetWithEmptyPath();
webkit_glue::PasswordFormDomManager::FillData fill_data;
webkit_glue::PasswordFormDomManager::InitFillData(form_for_autofill,
best_matches,
preferred_match,
action_mismatch,
&fill_data);
delegate_->FillPasswordForm(fill_data);
return;
}
default:
if (observer_) {
observer_->OnAutofillDataAvailable(
UTF16ToWideHack(preferred_match->username_value),
UTF16ToWideHack(preferred_match->password_value));
}
}
}
<|endoftext|>
|
<commit_before><commit_msg>Chance the toast experiment from TS to TT - The TS data is not meaningful, we don't want to mix it - The base group moved from TS00 to TS80, since omaha does not show 00 - A better random number generator is used<commit_after><|endoftext|>
|
<commit_before>/* This file is part of the Vc library.
Copyright (C) 2010 Matthias Kretz <kretz@kde.org>
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/>.
*/
namespace Vc
{
namespace LRBni
{
template<typename Parent, typename T> template<typename T2> inline void StoreMixin<Parent, T>::store(T2 *mem) const
{
VectorHelper<T>::store(mem, static_cast<const Parent *>(this)->vdata(), Aligned);
}
template<typename Parent, typename T> template<typename T2> inline void StoreMixin<Parent, T>::store(T2 *mem, Mask mask) const
{
VectorHelper<T>::store(mem, static_cast<const Parent *>(this)->vdata(), mask.data(), Aligned);
}
template<typename Parent, typename T> template<typename T2, typename A> inline void StoreMixin<Parent, T>::store(T2 *mem, A align) const
{
VectorHelper<T>::store(mem, static_cast<const Parent *>(this)->vdata(), align);
}
template<typename Parent, typename T> template<typename T2, typename A> inline void StoreMixin<Parent, T>::store(T2 *mem, Mask mask, A align) const
{
VectorHelper<T>::store(mem, static_cast<const Parent *>(this)->vdata(), mask.data(), align);
}
} // namespace LRBni
} // namespace Vc
<commit_msg>implement operator-() for LRBni<commit_after>/* This file is part of the Vc library.
Copyright (C) 2010 Matthias Kretz <kretz@kde.org>
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/>.
*/
namespace Vc
{
namespace LRBni
{
template<typename Parent, typename T> template<typename T2> inline void StoreMixin<Parent, T>::store(T2 *mem) const
{
VectorHelper<T>::store(mem, static_cast<const Parent *>(this)->vdata(), Aligned);
}
template<typename Parent, typename T> template<typename T2> inline void StoreMixin<Parent, T>::store(T2 *mem, Mask mask) const
{
VectorHelper<T>::store(mem, static_cast<const Parent *>(this)->vdata(), mask.data(), Aligned);
}
template<typename Parent, typename T> template<typename T2, typename A> inline void StoreMixin<Parent, T>::store(T2 *mem, A align) const
{
VectorHelper<T>::store(mem, static_cast<const Parent *>(this)->vdata(), align);
}
template<typename Parent, typename T> template<typename T2, typename A> inline void StoreMixin<Parent, T>::store(T2 *mem, Mask mask, A align) const
{
VectorHelper<T>::store(mem, static_cast<const Parent *>(this)->vdata(), mask.data(), align);
}
template<> inline Vector<double> INTRINSIC Vector<double>::operator-() const
{
return lrb_cast<__m512d>(_mm512_xor_pi(lrb_cast<__m512i>(data.v()), _mm512_set_1to8_pq(0x8000000000000000ull)));
}
template<> inline Vector<float> INTRINSIC Vector<float>::operator-() const
{
return lrb_cast<__m512>(_mm512_xor_pi(lrb_cast<__m512i>(data.v()), _mm512_set_1to16_pi(0x80000000u)));
}
template<> inline Vector<int> INTRINSIC Vector<int>::operator-() const
{
return (~(*this)) + 1;
}
template<> inline Vector<int> INTRINSIC Vector<unsigned int>::operator-() const
{
return Vector<int>(~(*this)) + 1;
}
} // namespace LRBni
} // namespace Vc
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/file_path_watcher/file_path_watcher.h"
#include <CoreServices/CoreServices.h>
#include <set>
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/mac/scoped_cftyperef.h"
#include "base/singleton.h"
#include "base/time.h"
namespace {
// The latency parameter passed to FSEventsStreamCreate().
const CFAbsoluteTime kEventLatencySeconds = 0.3;
// Mac-specific file watcher implementation based on the FSEvents API.
class FilePathWatcherImpl : public FilePathWatcher::PlatformDelegate {
public:
FilePathWatcherImpl();
virtual ~FilePathWatcherImpl() {}
// Called from the FSEvents callback whenever there is a change to the paths
void OnFilePathChanged();
// (Re-)Initialize the event stream to start reporting events from
// |start_event|.
void UpdateEventStream(FSEventStreamEventId start_event);
// FilePathWatcher::PlatformDelegate overrides.
virtual bool Watch(const FilePath& path, FilePathWatcher::Delegate* delegate);
virtual void Cancel();
private:
// Destroy the event stream.
void DestroyEventStream();
// Delegate to notify upon changes.
scoped_refptr<FilePathWatcher::Delegate> delegate_;
// Target path to watch (passed to delegate).
FilePath target_;
// Keep track of the last modified time of the file. We use nulltime
// to represent the file not existing.
base::Time last_modified_;
// The time at which we processed the first notification with the
// |last_modified_| time stamp.
base::Time first_notification_;
// Backend stream we receive event callbacks from (strong reference).
FSEventStreamRef fsevent_stream_;
// Used to detect early cancellation.
bool canceled_;
DISALLOW_COPY_AND_ASSIGN(FilePathWatcherImpl);
};
// The callback passed to FSEventStreamCreate().
void FSEventsCallback(ConstFSEventStreamRef stream,
void* event_watcher, size_t num_events,
void* event_paths, const FSEventStreamEventFlags flags[],
const FSEventStreamEventId event_ids[]) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
FilePathWatcherImpl* watcher =
reinterpret_cast<FilePathWatcherImpl*>(event_watcher);
bool root_changed = false;
FSEventStreamEventId root_change_at = FSEventStreamGetLatestEventId(stream);
for (size_t i = 0; i < num_events; i++) {
if (flags[i] & kFSEventStreamEventFlagRootChanged)
root_changed = true;
if (event_ids[i])
root_change_at = std::min(root_change_at, event_ids[i]);
}
// Reinitialize the event stream if we find changes to the root. This is
// necessary since FSEvents doesn't report any events for the subtree after
// the directory to be watched gets created.
if (root_changed) {
// Resetting the event stream from within the callback fails (FSEvents spews
// bad file descriptor errors), so post a task to do the reset.
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
NewRunnableMethod(watcher, &FilePathWatcherImpl::UpdateEventStream,
root_change_at));
}
BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
NewRunnableMethod(watcher, &FilePathWatcherImpl::OnFilePathChanged));
}
// FilePathWatcherImpl implementation:
FilePathWatcherImpl::FilePathWatcherImpl()
: fsevent_stream_(NULL),
canceled_(false) {
}
void FilePathWatcherImpl::OnFilePathChanged() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
DCHECK(!target_.empty());
base::PlatformFileInfo file_info;
bool file_exists = file_util::GetFileInfo(target_, &file_info);
if (file_exists && (last_modified_.is_null() ||
last_modified_ != file_info.last_modified)) {
last_modified_ = file_info.last_modified;
first_notification_ = base::Time::Now();
delegate_->OnFilePathChanged(target_);
} else if (file_exists && !first_notification_.is_null()) {
// The target's last modification time is equal to what's on record. This
// means that either an unrelated event occurred, or the target changed
// again (file modification times only have a resolution of 1s). Comparing
// file modification times against the wall clock is not reliable to find
// out whether the change is recent, since this code might just run too
// late. Moreover, there's no guarantee that file modification time and wall
// clock times come from the same source.
//
// Instead, the time at which the first notification carrying the current
// |last_notified_| time stamp is recorded. Later notifications that find
// the same file modification time only need to be forwarded until wall
// clock has advanced one second from the initial notification. After that
// interval, client code is guaranteed to having seen the current revision
// of the file.
if (base::Time::Now() - first_notification_ >
base::TimeDelta::FromSeconds(1)) {
// Stop further notifications for this |last_modification_| time stamp.
first_notification_ = base::Time();
}
delegate_->OnFilePathChanged(target_);
} else if (!file_exists && !last_modified_.is_null()) {
last_modified_ = base::Time();
delegate_->OnFilePathChanged(target_);
}
}
bool FilePathWatcherImpl::Watch(const FilePath& path,
FilePathWatcher::Delegate* delegate) {
DCHECK(target_.value().empty());
target_ = path;
delegate_ = delegate;
FSEventStreamEventId start_event = FSEventsGetCurrentEventId();
base::PlatformFileInfo file_info;
if (file_util::GetFileInfo(target_, &file_info)) {
last_modified_ = file_info.last_modified;
first_notification_ = base::Time::Now();
}
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
NewRunnableMethod(this, &FilePathWatcherImpl::UpdateEventStream,
start_event));
return true;
}
void FilePathWatcherImpl::Cancel() {
// Switch to the UI thread if necessary, so we can tear down the event stream.
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
NewRunnableMethod(this, &FilePathWatcherImpl::Cancel));
return;
}
canceled_ = true;
if (fsevent_stream_)
DestroyEventStream();
}
void FilePathWatcherImpl::UpdateEventStream(FSEventStreamEventId start_event) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// It can happen that the watcher gets canceled while tasks that call this
// function are still in flight, so abort if this situation is detected.
if (canceled_)
return;
if (fsevent_stream_)
DestroyEventStream();
base::mac::ScopedCFTypeRef<CFStringRef> cf_path(CFStringCreateWithCString(
NULL, target_.value().c_str(), kCFStringEncodingMacHFS));
base::mac::ScopedCFTypeRef<CFStringRef> cf_dir_path(CFStringCreateWithCString(
NULL, target_.DirName().value().c_str(), kCFStringEncodingMacHFS));
CFStringRef paths_array[] = { cf_path.get(), cf_dir_path.get() };
base::mac::ScopedCFTypeRef<CFArrayRef> watched_paths(CFArrayCreate(
NULL, reinterpret_cast<const void**>(paths_array), arraysize(paths_array),
&kCFTypeArrayCallBacks));
FSEventStreamContext context;
context.version = 0;
context.info = this;
context.retain = NULL;
context.release = NULL;
context.copyDescription = NULL;
fsevent_stream_ = FSEventStreamCreate(NULL, &FSEventsCallback, &context,
watched_paths,
start_event,
kEventLatencySeconds,
kFSEventStreamCreateFlagWatchRoot);
FSEventStreamScheduleWithRunLoop(fsevent_stream_, CFRunLoopGetCurrent(),
kCFRunLoopDefaultMode);
if (!FSEventStreamStart(fsevent_stream_)) {
BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
NewRunnableMethod(delegate_.get(),
&FilePathWatcher::Delegate::OnError));
}
}
void FilePathWatcherImpl::DestroyEventStream() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
FSEventStreamStop(fsevent_stream_);
FSEventStreamInvalidate(fsevent_stream_);
FSEventStreamRelease(fsevent_stream_);
fsevent_stream_ = NULL;
}
} // namespace
FilePathWatcher::FilePathWatcher() {
impl_ = new FilePathWatcherImpl();
}
<commit_msg>[Mac] Work around FSEventStreamInvalidate() bug.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/file_path_watcher/file_path_watcher.h"
#include <CoreServices/CoreServices.h>
#include <set>
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/mac/scoped_cftyperef.h"
#include "base/singleton.h"
#include "base/time.h"
namespace {
// The latency parameter passed to FSEventsStreamCreate().
const CFAbsoluteTime kEventLatencySeconds = 0.3;
// Mac-specific file watcher implementation based on the FSEvents API.
class FilePathWatcherImpl : public FilePathWatcher::PlatformDelegate {
public:
FilePathWatcherImpl();
virtual ~FilePathWatcherImpl() {}
// Called from the FSEvents callback whenever there is a change to the paths
void OnFilePathChanged();
// (Re-)Initialize the event stream to start reporting events from
// |start_event|.
void UpdateEventStream(FSEventStreamEventId start_event);
// FilePathWatcher::PlatformDelegate overrides.
virtual bool Watch(const FilePath& path, FilePathWatcher::Delegate* delegate);
virtual void Cancel();
private:
// Destroy the event stream.
void DestroyEventStream();
// Delegate to notify upon changes.
scoped_refptr<FilePathWatcher::Delegate> delegate_;
// Target path to watch (passed to delegate).
FilePath target_;
// Keep track of the last modified time of the file. We use nulltime
// to represent the file not existing.
base::Time last_modified_;
// The time at which we processed the first notification with the
// |last_modified_| time stamp.
base::Time first_notification_;
// Backend stream we receive event callbacks from (strong reference).
FSEventStreamRef fsevent_stream_;
// Used to detect early cancellation.
bool canceled_;
DISALLOW_COPY_AND_ASSIGN(FilePathWatcherImpl);
};
// The callback passed to FSEventStreamCreate().
void FSEventsCallback(ConstFSEventStreamRef stream,
void* event_watcher, size_t num_events,
void* event_paths, const FSEventStreamEventFlags flags[],
const FSEventStreamEventId event_ids[]) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
FilePathWatcherImpl* watcher =
reinterpret_cast<FilePathWatcherImpl*>(event_watcher);
bool root_changed = false;
FSEventStreamEventId root_change_at = FSEventStreamGetLatestEventId(stream);
for (size_t i = 0; i < num_events; i++) {
if (flags[i] & kFSEventStreamEventFlagRootChanged)
root_changed = true;
if (event_ids[i])
root_change_at = std::min(root_change_at, event_ids[i]);
}
// Reinitialize the event stream if we find changes to the root. This is
// necessary since FSEvents doesn't report any events for the subtree after
// the directory to be watched gets created.
if (root_changed) {
// Resetting the event stream from within the callback fails (FSEvents spews
// bad file descriptor errors), so post a task to do the reset.
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
NewRunnableMethod(watcher, &FilePathWatcherImpl::UpdateEventStream,
root_change_at));
}
BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
NewRunnableMethod(watcher, &FilePathWatcherImpl::OnFilePathChanged));
}
// FilePathWatcherImpl implementation:
FilePathWatcherImpl::FilePathWatcherImpl()
: fsevent_stream_(NULL),
canceled_(false) {
}
void FilePathWatcherImpl::OnFilePathChanged() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
DCHECK(!target_.empty());
base::PlatformFileInfo file_info;
bool file_exists = file_util::GetFileInfo(target_, &file_info);
if (file_exists && (last_modified_.is_null() ||
last_modified_ != file_info.last_modified)) {
last_modified_ = file_info.last_modified;
first_notification_ = base::Time::Now();
delegate_->OnFilePathChanged(target_);
} else if (file_exists && !first_notification_.is_null()) {
// The target's last modification time is equal to what's on record. This
// means that either an unrelated event occurred, or the target changed
// again (file modification times only have a resolution of 1s). Comparing
// file modification times against the wall clock is not reliable to find
// out whether the change is recent, since this code might just run too
// late. Moreover, there's no guarantee that file modification time and wall
// clock times come from the same source.
//
// Instead, the time at which the first notification carrying the current
// |last_notified_| time stamp is recorded. Later notifications that find
// the same file modification time only need to be forwarded until wall
// clock has advanced one second from the initial notification. After that
// interval, client code is guaranteed to having seen the current revision
// of the file.
if (base::Time::Now() - first_notification_ >
base::TimeDelta::FromSeconds(1)) {
// Stop further notifications for this |last_modification_| time stamp.
first_notification_ = base::Time();
}
delegate_->OnFilePathChanged(target_);
} else if (!file_exists && !last_modified_.is_null()) {
last_modified_ = base::Time();
delegate_->OnFilePathChanged(target_);
}
}
bool FilePathWatcherImpl::Watch(const FilePath& path,
FilePathWatcher::Delegate* delegate) {
DCHECK(target_.value().empty());
target_ = path;
delegate_ = delegate;
FSEventStreamEventId start_event = FSEventsGetCurrentEventId();
base::PlatformFileInfo file_info;
if (file_util::GetFileInfo(target_, &file_info)) {
last_modified_ = file_info.last_modified;
first_notification_ = base::Time::Now();
}
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
NewRunnableMethod(this, &FilePathWatcherImpl::UpdateEventStream,
start_event));
return true;
}
void FilePathWatcherImpl::Cancel() {
// Switch to the UI thread if necessary, so we can tear down the event stream.
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
NewRunnableMethod(this, &FilePathWatcherImpl::Cancel));
return;
}
canceled_ = true;
if (fsevent_stream_)
DestroyEventStream();
}
void FilePathWatcherImpl::UpdateEventStream(FSEventStreamEventId start_event) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// It can happen that the watcher gets canceled while tasks that call this
// function are still in flight, so abort if this situation is detected.
if (canceled_)
return;
if (fsevent_stream_)
DestroyEventStream();
base::mac::ScopedCFTypeRef<CFStringRef> cf_path(CFStringCreateWithCString(
NULL, target_.value().c_str(), kCFStringEncodingMacHFS));
base::mac::ScopedCFTypeRef<CFStringRef> cf_dir_path(CFStringCreateWithCString(
NULL, target_.DirName().value().c_str(), kCFStringEncodingMacHFS));
CFStringRef paths_array[] = { cf_path.get(), cf_dir_path.get() };
base::mac::ScopedCFTypeRef<CFArrayRef> watched_paths(CFArrayCreate(
NULL, reinterpret_cast<const void**>(paths_array), arraysize(paths_array),
&kCFTypeArrayCallBacks));
FSEventStreamContext context;
context.version = 0;
context.info = this;
context.retain = NULL;
context.release = NULL;
context.copyDescription = NULL;
fsevent_stream_ = FSEventStreamCreate(NULL, &FSEventsCallback, &context,
watched_paths,
start_event,
kEventLatencySeconds,
kFSEventStreamCreateFlagWatchRoot);
FSEventStreamScheduleWithRunLoop(fsevent_stream_, CFRunLoopGetCurrent(),
kCFRunLoopDefaultMode);
if (!FSEventStreamStart(fsevent_stream_)) {
BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
NewRunnableMethod(delegate_.get(),
&FilePathWatcher::Delegate::OnError));
}
}
void FilePathWatcherImpl::DestroyEventStream() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
FSEventStreamStop(fsevent_stream_);
FSEventStreamUnscheduleFromRunLoop(fsevent_stream_, CFRunLoopGetCurrent(),
kCFRunLoopDefaultMode);
FSEventStreamRelease(fsevent_stream_);
fsevent_stream_ = NULL;
}
} // namespace
FilePathWatcher::FilePathWatcher() {
impl_ = new FilePathWatcherImpl();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/password_manager/password_store_change.h"
#include "chrome/browser/password_manager/password_store_default.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/webdata/web_data_service.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_names.h"
#include "base/logging.h"
#include "base/task.h"
using webkit_glue::PasswordForm;
PasswordStoreDefault::PasswordStoreDefault(LoginDatabase* login_db,
Profile* profile,
WebDataService* web_data_service)
: web_data_service_(web_data_service),
login_db_(login_db), profile_(profile) {
DCHECK(login_db);
DCHECK(profile);
DCHECK(web_data_service);
MigrateIfNecessary();
}
PasswordStoreDefault::~PasswordStoreDefault() {
}
void PasswordStoreDefault::AddLoginImpl(const PasswordForm& form) {
if (login_db_->AddLogin(form)) {
PasswordStoreChangeList changes;
changes.push_back(PasswordStoreChange(PasswordStoreChange::ADD, form));
NotificationService::current()->Notify(
NotificationType::LOGINS_CHANGED,
NotificationService::AllSources(),
Details<PasswordStoreChangeList>(&changes));
}
}
void PasswordStoreDefault::UpdateLoginImpl(const PasswordForm& form) {
if (login_db_->UpdateLogin(form, NULL)) {
PasswordStoreChangeList changes;
changes.push_back(PasswordStoreChange(PasswordStoreChange::UPDATE, form));
NotificationService::current()->Notify(
NotificationType::LOGINS_CHANGED,
NotificationService::AllSources(),
Details<PasswordStoreChangeList>(&changes));
}
}
void PasswordStoreDefault::RemoveLoginImpl(const PasswordForm& form) {
if (login_db_->RemoveLogin(form)) {
PasswordStoreChangeList changes;
changes.push_back(PasswordStoreChange(PasswordStoreChange::REMOVE, form));
NotificationService::current()->Notify(
NotificationType::LOGINS_CHANGED,
NotificationService::AllSources(),
Details<PasswordStoreChangeList>(&changes));
}
}
void PasswordStoreDefault::RemoveLoginsCreatedBetweenImpl(
const base::Time& delete_begin, const base::Time& delete_end) {
std::vector<PasswordForm*> forms;
if (login_db_->GetLoginsCreatedBetween(delete_begin, delete_end, &forms)) {
if (login_db_->RemoveLoginsCreatedBetween(delete_begin, delete_end)) {
PasswordStoreChangeList changes;
for (std::vector<PasswordForm*>::const_iterator it = forms.begin();
it != forms.end(); ++it) {
changes.push_back(PasswordStoreChange(PasswordStoreChange::REMOVE,
**it));
}
NotificationService::current()->Notify(
NotificationType::LOGINS_CHANGED,
NotificationService::AllSources(),
Details<PasswordStoreChangeList>(&changes));
}
}
}
void PasswordStoreDefault::GetLoginsImpl(
GetLoginsRequest* request, const webkit_glue::PasswordForm& form) {
std::vector<PasswordForm*> forms;
login_db_->GetLogins(form, &forms);
NotifyConsumer(request, forms);
}
void PasswordStoreDefault::GetAutofillableLoginsImpl(
GetLoginsRequest* request) {
std::vector<PasswordForm*> forms;
login_db_->GetAutofillableLogins(&forms);
NotifyConsumer(request, forms);
}
void PasswordStoreDefault::GetBlacklistLoginsImpl(
GetLoginsRequest* request) {
std::vector<PasswordForm*> forms;
login_db_->GetBlacklistLogins(&forms);
NotifyConsumer(request, forms);
}
void PasswordStoreDefault::MigrateIfNecessary() {
PrefService* prefs = profile_->GetPrefs();
if (prefs->FindPreference(prefs::kLoginDatabaseMigrated))
return;
handles_.insert(web_data_service_->GetAutofillableLogins(this));
handles_.insert(web_data_service_->GetBlacklistLogins(this));
}
typedef std::vector<const PasswordForm*> PasswordForms;
void PasswordStoreDefault::OnWebDataServiceRequestDone(
WebDataService::Handle handle,
const WDTypedResult* result) {
DCHECK(handles_.end() != handles_.find(handle));
DCHECK(result);
if (PASSWORD_RESULT != result->GetType()) {
NOTREACHED();
return;
}
handles_.erase(handle);
if (!result)
return;
const PasswordForms& forms =
static_cast<const WDResult<PasswordForms>*>(result)->GetValue();
for (PasswordForms::const_iterator it = forms.begin();
it != forms.end(); ++it) {
AddLoginImpl(**it);
web_data_service_->RemoveLogin(**it);
delete *it;
}
if (handles_.empty()) {
profile_->GetPrefs()->RegisterBooleanPref(prefs::kLoginDatabaseMigrated,
true);
}
}
<commit_msg>Fix a possible crash introduced by r46412 by not accessing the result variable before the NULL check<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/password_manager/password_store_change.h"
#include "chrome/browser/password_manager/password_store_default.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/webdata/web_data_service.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_names.h"
#include "base/logging.h"
#include "base/task.h"
using webkit_glue::PasswordForm;
PasswordStoreDefault::PasswordStoreDefault(LoginDatabase* login_db,
Profile* profile,
WebDataService* web_data_service)
: web_data_service_(web_data_service),
login_db_(login_db), profile_(profile) {
DCHECK(login_db);
DCHECK(profile);
DCHECK(web_data_service);
MigrateIfNecessary();
}
PasswordStoreDefault::~PasswordStoreDefault() {
}
void PasswordStoreDefault::AddLoginImpl(const PasswordForm& form) {
if (login_db_->AddLogin(form)) {
PasswordStoreChangeList changes;
changes.push_back(PasswordStoreChange(PasswordStoreChange::ADD, form));
NotificationService::current()->Notify(
NotificationType::LOGINS_CHANGED,
NotificationService::AllSources(),
Details<PasswordStoreChangeList>(&changes));
}
}
void PasswordStoreDefault::UpdateLoginImpl(const PasswordForm& form) {
if (login_db_->UpdateLogin(form, NULL)) {
PasswordStoreChangeList changes;
changes.push_back(PasswordStoreChange(PasswordStoreChange::UPDATE, form));
NotificationService::current()->Notify(
NotificationType::LOGINS_CHANGED,
NotificationService::AllSources(),
Details<PasswordStoreChangeList>(&changes));
}
}
void PasswordStoreDefault::RemoveLoginImpl(const PasswordForm& form) {
if (login_db_->RemoveLogin(form)) {
PasswordStoreChangeList changes;
changes.push_back(PasswordStoreChange(PasswordStoreChange::REMOVE, form));
NotificationService::current()->Notify(
NotificationType::LOGINS_CHANGED,
NotificationService::AllSources(),
Details<PasswordStoreChangeList>(&changes));
}
}
void PasswordStoreDefault::RemoveLoginsCreatedBetweenImpl(
const base::Time& delete_begin, const base::Time& delete_end) {
std::vector<PasswordForm*> forms;
if (login_db_->GetLoginsCreatedBetween(delete_begin, delete_end, &forms)) {
if (login_db_->RemoveLoginsCreatedBetween(delete_begin, delete_end)) {
PasswordStoreChangeList changes;
for (std::vector<PasswordForm*>::const_iterator it = forms.begin();
it != forms.end(); ++it) {
changes.push_back(PasswordStoreChange(PasswordStoreChange::REMOVE,
**it));
}
NotificationService::current()->Notify(
NotificationType::LOGINS_CHANGED,
NotificationService::AllSources(),
Details<PasswordStoreChangeList>(&changes));
}
}
}
void PasswordStoreDefault::GetLoginsImpl(
GetLoginsRequest* request, const webkit_glue::PasswordForm& form) {
std::vector<PasswordForm*> forms;
login_db_->GetLogins(form, &forms);
NotifyConsumer(request, forms);
}
void PasswordStoreDefault::GetAutofillableLoginsImpl(
GetLoginsRequest* request) {
std::vector<PasswordForm*> forms;
login_db_->GetAutofillableLogins(&forms);
NotifyConsumer(request, forms);
}
void PasswordStoreDefault::GetBlacklistLoginsImpl(
GetLoginsRequest* request) {
std::vector<PasswordForm*> forms;
login_db_->GetBlacklistLogins(&forms);
NotifyConsumer(request, forms);
}
void PasswordStoreDefault::MigrateIfNecessary() {
PrefService* prefs = profile_->GetPrefs();
if (prefs->FindPreference(prefs::kLoginDatabaseMigrated))
return;
handles_.insert(web_data_service_->GetAutofillableLogins(this));
handles_.insert(web_data_service_->GetBlacklistLogins(this));
}
typedef std::vector<const PasswordForm*> PasswordForms;
void PasswordStoreDefault::OnWebDataServiceRequestDone(
WebDataService::Handle handle,
const WDTypedResult* result) {
DCHECK(handles_.end() != handles_.find(handle));
handles_.erase(handle);
if (!result)
return;
if (PASSWORD_RESULT != result->GetType()) {
NOTREACHED();
return;
}
const PasswordForms& forms =
static_cast<const WDResult<PasswordForms>*>(result)->GetValue();
for (PasswordForms::const_iterator it = forms.begin();
it != forms.end(); ++it) {
AddLoginImpl(**it);
web_data_service_->RemoveLogin(**it);
delete *it;
}
if (handles_.empty()) {
profile_->GetPrefs()->RegisterBooleanPref(prefs::kLoginDatabaseMigrated,
true);
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <numeric>
#include <vector>
using MyInt = size_t;
int main() {
MyInt T;
std::cin >> T;
for (auto testCase{1u}; testCase <= T; ++testCase) {
MyInt N;
MyInt K;
MyInt x1;
MyInt y1;
MyInt C;
MyInt D;
MyInt E1;
MyInt E2;
MyInt F;
std::cin >> N >> K >> x1 >> y1 >> C >> D >> E1 >> E2 >> F;
x1 %= F;
y1 %= F;
C %= F;
D %= F;
E1 %= F;
E2 %= F;
std::vector<MyInt> A;
A.reserve(N);
{
auto modF = [&F](const auto val) { return val % F; };
A.push_back(modF(x1 + y1));
MyInt prevX{x1};
MyInt prevY{y1};
for (auto i{1u}; i < N; ++i) {
const auto currentX = modF(C * prevX + D * prevY + E1);
const auto currentY = modF(D * prevX + C * prevY + E2);
A.push_back(modF(currentX + currentY));
prevX = currentX;
prevY = currentY;
}
}
std::vector<MyInt> currentPowers;
currentPowers.resize(N);
std::iota(currentPowers.begin(), currentPowers.end(), 1u);
auto modPower = [](const auto val) {
const auto powerModulo{1000000007u};
return val % powerModulo;
};
const auto getPOWER = [&N, &A, ¤tPowers, &modPower]() {
MyInt NDependentFactor{N + 1};
MyInt itemIndexDependentFactor{0u};
MyInt POWER{0u};
for (auto itemIndex{0u}; itemIndex < N; ++itemIndex) {
--NDependentFactor;
itemIndexDependentFactor = modPower(itemIndexDependentFactor + currentPowers[itemIndex]);
POWER = POWER + modPower(modPower(NDependentFactor * itemIndexDependentFactor) * A[itemIndex]);
}
return POWER;
};
auto totalPOWER{0u};
for (auto i{1u}; i <= K; ++i) {
const auto ithPOWER{getPOWER()};
totalPOWER = modPower(totalPOWER + ithPOWER);
for (auto j{1u}; j <= N; ++j) {
currentPowers[j - 1] = modPower(currentPowers[j - 1] * j);
}
}
std::cout << "Case #" << testCase << ": " << totalPOWER << '\n';
}
}
<commit_msg>Add working solution based on analysis<commit_after>#include <iostream>
#include <numeric>
#include <vector>
using MyInt = uint64_t;
int main() {
MyInt T;
std::cin >> T;
for (auto testCase{1u}; testCase <= T; ++testCase) {
MyInt N;
MyInt K;
MyInt x1;
MyInt y1;
MyInt C;
MyInt D;
MyInt E1;
MyInt E2;
MyInt F;
std::cin >> N >> K >> x1 >> y1 >> C >> D >> E1 >> E2 >> F;
x1 %= F;
y1 %= F;
C %= F;
D %= F;
E1 %= F;
E2 %= F;
std::vector<MyInt> A;
A.reserve(N);
{
auto modF = [&F](const auto val) { return val % F; };
A.push_back(modF(x1 + y1));
MyInt prevX{x1};
MyInt prevY{y1};
for (auto i{1u}; i < N; ++i) {
const auto currentX = modF(C * prevX + D * prevY + E1);
const auto currentY = modF(D * prevX + C * prevY + E2);
A.push_back(modF(currentX + currentY));
prevX = currentX;
prevY = currentY;
}
}
const auto powerModulo{1000000007u};
auto modPower = [&powerModulo](const auto val) { return val % powerModulo; };
auto quickPowerWithModulo = [&modPower](auto base, auto exp) {
auto t{1u};
while (exp != 0) {
if (exp % 2 == 1)
t = modPower(t * base);
base = modPower(base * base);
exp /= 2;
}
return t;
};
auto moduloInverse = [&powerModulo, &quickPowerWithModulo](const auto val) {
return quickPowerWithModulo(val, powerModulo - 2u);
};
MyInt POWER{0u};
MyInt totalSumOfGeometricProgressions{K};
// POWER_K(A) = power_1(A) + power_2(A) + ... + power_K(A) =
// = (N + 1 - 1)(1^1)A_1 + (N + 1 - 2)(1^1 + 2^1)A_2 + ... (N + 1 - N)(1^1 + 2^1 + ... + N^1)A_N +
// + (N + 1 - 1)(1^2)A_1 + (N + 1 - 2)(1^2 + 2^2)A_2 + ... (N + 1 - N)(1^2 + 2^2 + ... + N^2)A_N +
// + ... +
// + (N + 1 - 1)(1^K)A_1 + (N + 1 - 2)(1^K + 2^K)A_2 + ... (N + 1 - N)(1^K + 2^K + ... + N^K)A_N =
// = (N + 1 - 1)(1^1 + 1^2 + ... + 1^K)A_1 +
// + (N + 1 - 2)(1^1 + 1^2 + ... + 1^K + 2^1 + 2^2 + ... + 2^K)A_2 +
// + ... +
// + (N + 1 - N)(1^1 + 1^2 + ... + 1^K + 2^1 + 2^2 + ... + 2^K + ... + N^1 + N^2 + ... + N^K)A_N
for (MyInt x{1u}; x <= N; ++x) {
if (x != 1u) {
// Sum of geometric progression
// x^1 + x^2 + ... + x^K =
// = x(1 - x^K)/(1 - x) =
// = (x - x^(K + 1))/(1 - x) =
// = (x^(K+1) - x)/(x - 1) =
// = (x^(K+1) - x)(x - 1)^(-1)
// | t1 || t2 |
const auto t1 = powerModulo + quickPowerWithModulo(x, K + 1u) - x;
// Calculate modular inverse using Euler-theorem
// (x - 1)^(-1) mod M = (x - 1)^(M - 2) mod M
const auto t2 = moduloInverse(MyInt{x - 1u});
const auto sumOfSingleGeometricProgression = modPower(t1 * t2);
totalSumOfGeometricProgressions = modPower(totalSumOfGeometricProgressions + sumOfSingleGeometricProgression);
}
POWER = modPower(POWER + modPower(modPower(totalSumOfGeometricProgressions * A[x - 1u]) * (N + 1u - x)));
}
std::cout << "Case #" << testCase << ": " << POWER << '\n';
}
}
<|endoftext|>
|
<commit_before>//
// Copyright 2015 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// DebugAnnotator11.cpp: D3D11 helpers for adding trace annotations.
//
#include "libANGLE/renderer/d3d/d3d11/DebugAnnotator11.h"
#include "common/debug.h"
#include "libANGLE/renderer/d3d/d3d11/renderer11_utils.h"
namespace rx
{
DebugAnnotator11::DebugAnnotator11()
: mInitialized(false),
mD3d11Module(nullptr),
mUserDefinedAnnotation(nullptr)
{
// D3D11 devices can't be created during DllMain.
// We defer device creation until the object is actually used.
}
DebugAnnotator11::~DebugAnnotator11()
{
if (mInitialized)
{
SafeRelease(mUserDefinedAnnotation);
#if !defined(ANGLE_ENABLE_WINDOWS_STORE)
FreeLibrary(mD3d11Module);
#endif // !ANGLE_ENABLE_WINDOWS_STORE
}
}
void DebugAnnotator11::beginEvent(const std::wstring &eventName)
{
initializeDevice();
mUserDefinedAnnotation->BeginEvent(eventName.c_str());
}
void DebugAnnotator11::endEvent()
{
initializeDevice();
mUserDefinedAnnotation->EndEvent();
}
void DebugAnnotator11::setMarker(const std::wstring &markerName)
{
initializeDevice();
mUserDefinedAnnotation->SetMarker(markerName.c_str());
}
bool DebugAnnotator11::getStatus()
{
// ID3DUserDefinedAnnotation::GetStatus doesn't work with the Graphics Diagnostics tools in Visual Studio 2013.
#if defined(_DEBUG) && defined(ANGLE_ENABLE_WINDOWS_STORE)
// In the Windows Store, we can use IDXGraphicsAnalysis. The call to GetDebugInterface1 only succeeds if the app is under capture.
// This should only be called in DEBUG mode.
// If an app links against DXGIGetDebugInterface1 in release mode then it will fail Windows Store ingestion checks.
IDXGraphicsAnalysis *graphicsAnalysis;
DXGIGetDebugInterface1(0, IID_PPV_ARGS(&graphicsAnalysis));
bool underCapture = (graphicsAnalysis != nullptr);
SafeRelease(graphicsAnalysis);
return underCapture;
#endif // _DEBUG && !ANGLE_ENABLE_WINDOWS_STORE
// Otherwise, we have to return true here.
// TODO: We set this to false here to allow angle_end2end_tests to run at a reasonable speed.
// We should figure out a better way of using the D3D11 debug annotations in classic desktop builds
return false;
}
void DebugAnnotator11::initializeDevice()
{
if (!mInitialized)
{
#if !defined(ANGLE_ENABLE_WINDOWS_STORE)
mD3d11Module = LoadLibrary(TEXT("d3d11.dll"));
ASSERT(mD3d11Module);
PFN_D3D11_CREATE_DEVICE D3D11CreateDevice = (PFN_D3D11_CREATE_DEVICE)GetProcAddress(mD3d11Module, "D3D11CreateDevice");
ASSERT(D3D11CreateDevice != nullptr);
#endif // !ANGLE_ENABLE_WINDOWS_STORE
ID3D11Device *device = nullptr;
ID3D11DeviceContext *context = nullptr;
HRESULT hr = E_FAIL;
// Create a D3D_DRIVER_TYPE_NULL device, which is much cheaper than other types of device.
hr = D3D11CreateDevice(NULL, D3D_DRIVER_TYPE_NULL, nullptr, 0, nullptr, 0, D3D11_SDK_VERSION, &device, nullptr, &context);
ASSERT(SUCCEEDED(hr));
if (SUCCEEDED(hr))
{
mUserDefinedAnnotation = d3d11::DynamicCastComObject<ID3DUserDefinedAnnotation>(context);
ASSERT(mUserDefinedAnnotation != nullptr);
}
SafeRelease(device);
SafeRelease(context);
mInitialized = true;
}
}
}
<commit_msg>Revert "Fix debug markers in ms-master"<commit_after>//
// Copyright 2015 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// DebugAnnotator11.cpp: D3D11 helpers for adding trace annotations.
//
#include "libANGLE/renderer/d3d/d3d11/DebugAnnotator11.h"
#include "common/debug.h"
#include "libANGLE/renderer/d3d/d3d11/renderer11_utils.h"
namespace rx
{
DebugAnnotator11::DebugAnnotator11()
: mInitialized(false),
mD3d11Module(nullptr),
mUserDefinedAnnotation(nullptr)
{
// D3D11 devices can't be created during DllMain.
// We defer device creation until the object is actually used.
}
DebugAnnotator11::~DebugAnnotator11()
{
if (mInitialized)
{
SafeRelease(mUserDefinedAnnotation);
#if !defined(ANGLE_ENABLE_WINDOWS_STORE)
FreeLibrary(mD3d11Module);
#endif // !ANGLE_ENABLE_WINDOWS_STORE
}
}
void DebugAnnotator11::beginEvent(const std::wstring &eventName)
{
initializeDevice();
mUserDefinedAnnotation->BeginEvent(eventName.c_str());
}
void DebugAnnotator11::endEvent()
{
initializeDevice();
mUserDefinedAnnotation->EndEvent();
}
void DebugAnnotator11::setMarker(const std::wstring &markerName)
{
initializeDevice();
mUserDefinedAnnotation->SetMarker(markerName.c_str());
}
bool DebugAnnotator11::getStatus()
{
// ID3DUserDefinedAnnotation::GetStatus doesn't work with the Graphics Diagnostics tools in Visual Studio 2013.
#if defined(_DEBUG) && defined(ANGLE_ENABLE_WINDOWS_STORE)
// In the Windows Store, we can use IDXGraphicsAnalysis. The call to GetDebugInterface1 only succeeds if the app is under capture.
// This should only be called in DEBUG mode.
// If an app links against DXGIGetDebugInterface1 in release mode then it will fail Windows Store ingestion checks.
IDXGraphicsAnalysis *graphicsAnalysis;
DXGIGetDebugInterface1(0, IID_PPV_ARGS(&graphicsAnalysis));
bool underCapture = (graphicsAnalysis != nullptr);
SafeRelease(graphicsAnalysis);
return underCapture;
#endif // _DEBUG && !ANGLE_ENABLE_WINDOWS_STORE
// Otherwise, we have to return true here.
return true;
}
void DebugAnnotator11::initializeDevice()
{
if (!mInitialized)
{
#if !defined(ANGLE_ENABLE_WINDOWS_STORE)
mD3d11Module = LoadLibrary(TEXT("d3d11.dll"));
ASSERT(mD3d11Module);
PFN_D3D11_CREATE_DEVICE D3D11CreateDevice = (PFN_D3D11_CREATE_DEVICE)GetProcAddress(mD3d11Module, "D3D11CreateDevice");
ASSERT(D3D11CreateDevice != nullptr);
#endif // !ANGLE_ENABLE_WINDOWS_STORE
ID3D11Device *device = nullptr;
ID3D11DeviceContext *context = nullptr;
HRESULT hr = E_FAIL;
// Create a D3D_DRIVER_TYPE_NULL device, which is much cheaper than other types of device.
hr = D3D11CreateDevice(NULL, D3D_DRIVER_TYPE_NULL, nullptr, 0, nullptr, 0, D3D11_SDK_VERSION, &device, nullptr, &context);
ASSERT(SUCCEEDED(hr));
if (SUCCEEDED(hr))
{
mUserDefinedAnnotation = d3d11::DynamicCastComObject<ID3DUserDefinedAnnotation>(context);
ASSERT(mUserDefinedAnnotation != nullptr);
}
SafeRelease(device);
SafeRelease(context);
mInitialized = true;
}
}
}
<|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.
*/
#include "MockTransportFactory.h"
#include <activemq/connector/stomp/StompResponseBuilder.h>
#include <activemq/transport/MockTransport.h>
#include <activemq/transport/MockTransportFactory.h>
#include <activemq/transport/TransportFactoryMapRegistrar.h>
using namespace activemq;
using namespace activemq::transport;
using namespace activemq::util;
////////////////////////////////////////////////////////////////////////////////
Transport* MockTransportFactory::createTransport(
const activemq::util::Properties& properties,
Transport* next,
bool own ) throw ( exceptions::ActiveMQException )
{
// We don't use the next here, so clean it up now.
if( own == true ) {
delete next;
}
std::string wireFormat =
properties.getProperty( "wireFormat", "stomp" );
MockTransport::ResponseBuilder* builder = NULL;
if( wireFormat == "stomp" )
{
builder = new connector::stomp::StompResponseBuilder(
properties.getProperty(
"transport.sessionId", "testSessionId" ) );
}
return new MockTransport( builder, true, true );
}
////////////////////////////////////////////////////////////////////////////////
TransportFactory& MockTransportFactory::getInstance() {
// Create the one and only instance of the registrar
static TransportFactoryMapRegistrar registrar(
"mock", new MockTransportFactory() );
return registrar.getFactory();
}
<commit_msg>http://issues.apache.org/activemq/browse/AMQCPP-130<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.
*/
#include "MockTransportFactory.h"
#include <activemq/connector/stomp/StompResponseBuilder.h>
#include <activemq/connector/openwire/OpenWireResponseBuilder.h>
#include <activemq/transport/MockTransport.h>
#include <activemq/transport/MockTransportFactory.h>
#include <activemq/transport/TransportFactoryMapRegistrar.h>
using namespace activemq;
using namespace activemq::transport;
using namespace activemq::util;
////////////////////////////////////////////////////////////////////////////////
Transport* MockTransportFactory::createTransport(
const activemq::util::Properties& properties,
Transport* next,
bool own ) throw ( exceptions::ActiveMQException )
{
// We don't use the next here, so clean it up now.
if( own == true ) {
delete next;
}
std::string wireFormat =
properties.getProperty( "wireFormat", "stomp" );
MockTransport::ResponseBuilder* builder = NULL;
if( wireFormat == "stomp" ) {
builder = new connector::stomp::StompResponseBuilder(
properties.getProperty(
"transport.sessionId", "testSessionId" ) );
} else if( wireFormat == "openwire" ) {
builder = new connector::openwire::OpenWireResponseBuilder(
properties.getProperty(
"transport.sessionId", "testSessionId" ) );
}
return new MockTransport( builder, true, true );
}
////////////////////////////////////////////////////////////////////////////////
TransportFactory& MockTransportFactory::getInstance() {
// Create the one and only instance of the registrar
static TransportFactoryMapRegistrar registrar(
"mock", new MockTransportFactory() );
return registrar.getFactory();
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2011 DataStax
*
* 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.
*/
#ifndef _PHP_PDO_CASSANDRA_PRIVATE_H_
# define _PHP_PDO_CASSANDRA_PRIVATE_H_
extern "C" {
/* Need to undefine these so that thrift config doesn't complain */
#ifdef HAVE_CONFIG_H
# include "config.h"
# undef PACKAGE_NAME
# undef PACKAGE_STRING
# undef PACKAGE_TARNAME
# undef PACKAGE_VERSION
#endif
#include "ext/standard/info.h"
#include "Zend/zend_exceptions.h"
#include "Zend/zend_interfaces.h"
#include "main/php_ini.h"
#include "pdo/php_pdo.h"
#include "pdo/php_pdo_driver.h"
#include "ext/standard/url.h"
#include "ext/standard/php_string.h"
#include "ext/pcre/php_pcre.h"
}
#define HAVE_ZLIB_CP HAVE_ZLIB
#undef HAVE_ZLIB
#include "gen-cpp/Cassandra.h"
#include <protocol/TBinaryProtocol.h>
#include <transport/TSocketPool.h>
#include <transport/TTransportUtils.h>
#undef HAVE_ZLIB
#define HAVE_ZLIB HAVE_ZLIB_CP
#include <boost/bimap.hpp>
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
using namespace org::apache::cassandra;
enum pdo_cassandra_type {
PDO_CASSANDRA_TYPE_BYTES,
PDO_CASSANDRA_TYPE_ASCII,
PDO_CASSANDRA_TYPE_UTF8,
PDO_CASSANDRA_TYPE_INTEGER,
PDO_CASSANDRA_TYPE_LONG,
PDO_CASSANDRA_TYPE_UUID,
PDO_CASSANDRA_TYPE_LEXICAL,
PDO_CASSANDRA_TYPE_TIMEUUID,
PDO_CASSANDRA_TYPE_UNKNOWN
};
/** {{{
*/
typedef struct {
const char *file;
char *errmsg;
int line;
unsigned int errcode;
} pdo_cassandra_einfo;
/* }}} */
/* {{{ typedef struct php_cassandra_db_handle
*/
typedef struct {
zend_object zo;
zend_bool compression;
boost::shared_ptr<TSocketPool> socket;
boost::shared_ptr<TFramedTransport> transport;
boost::shared_ptr<TProtocol> protocol;
boost::shared_ptr<CassandraClient> client;
pdo_cassandra_einfo einfo;
std::string active_keyspace;
KsDef description;
zend_bool has_description;
zend_bool preserve_values;
} pdo_cassandra_db_handle;
/* }}} */
typedef boost::bimap<std::string, int> ColumnMap;
typedef boost::bimap<std::string, pdo_param_type> ColumnTypeMap;
/* {{{ typedef struct pdo_cassandra_stmt
*/
typedef struct {
pdo_cassandra_db_handle *H;
zend_bool has_iterator;
boost::shared_ptr<CqlResult> result;
std::vector<CqlRow>::iterator it;
ColumnMap original_column_names;
ColumnMap column_name_labels;
std::string active_columnfamily;
} pdo_cassandra_stmt;
/* }}} */
/* {{{ enum pdo_cassandra_constant
*/
enum pdo_cassandra_constant {
PDO_CASSANDRA_ATTR_MIN = PDO_ATTR_DRIVER_SPECIFIC,
PDO_CASSANDRA_ATTR_NUM_RETRIES,
PDO_CASSANDRA_ATTR_RETRY_INTERVAL,
PDO_CASSANDRA_ATTR_MAX_CONSECUTIVE_FAILURES,
PDO_CASSANDRA_ATTR_RANDOMIZE,
PDO_CASSANDRA_ATTR_ALWAYS_TRY_LAST,
PDO_CASSANDRA_ATTR_LINGER,
PDO_CASSANDRA_ATTR_NO_DELAY,
PDO_CASSANDRA_ATTR_CONN_TIMEOUT,
PDO_CASSANDRA_ATTR_RECV_TIMEOUT,
PDO_CASSANDRA_ATTR_SEND_TIMEOUT,
PDO_CASSANDRA_ATTR_COMPRESSION,
PDO_CASSANDRA_ATTR_THRIFT_DEBUG,
PDO_CASSANDRA_ATTR_PRESERVE_VALUES,
PDO_CASSANDRA_ATTR_MAX
};
/* }}} */
enum pdo_cassandra_error {
PDO_CASSANDRA_GENERAL_ERROR,
PDO_CASSANDRA_NOT_FOUND,
PDO_CASSANDRA_INVALID_REQUEST,
PDO_CASSANDRA_UNAVAILABLE,
PDO_CASSANDRA_TIMED_OUT,
PDO_CASSANDRA_AUTHENTICATION_ERROR,
PDO_CASSANDRA_AUTHORIZATION_ERROR,
PDO_CASSANDRA_SCHEMA_DISAGREEMENT,
PDO_CASSANDRA_TRANSPORT_ERROR,
PDO_CASSANDRA_INVALID_CONNECTION_STRING
};
void pdo_cassandra_error_ex(pdo_dbh_t *dbh TSRMLS_DC, pdo_cassandra_error code, const char *file, int line, zend_bool force_exception, const char *message, ...);
#define pdo_cassandra_error(dbh, code, message, ...) pdo_cassandra_error_ex(dbh TSRMLS_CC, code, __FILE__, __LINE__, 0, message, __VA_ARGS__)
#define pdo_cassandra_error_exception(dbh, code, message, ...) pdo_cassandra_error_ex(dbh TSRMLS_CC, code, __FILE__, __LINE__, 1, message, __VA_ARGS__)
void pdo_cassandra_set_active_keyspace(pdo_cassandra_db_handle *H, const std::string &sql);
#endif /* _PHP_PDO_CASSANDRA_PRIVATE_H_ */
<commit_msg>Remove unnecessary typedef<commit_after>/*
* Copyright 2011 DataStax
*
* 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.
*/
#ifndef _PHP_PDO_CASSANDRA_PRIVATE_H_
# define _PHP_PDO_CASSANDRA_PRIVATE_H_
extern "C" {
/* Need to undefine these so that thrift config doesn't complain */
#ifdef HAVE_CONFIG_H
# include "config.h"
# undef PACKAGE_NAME
# undef PACKAGE_STRING
# undef PACKAGE_TARNAME
# undef PACKAGE_VERSION
#endif
#include "ext/standard/info.h"
#include "Zend/zend_exceptions.h"
#include "Zend/zend_interfaces.h"
#include "main/php_ini.h"
#include "pdo/php_pdo.h"
#include "pdo/php_pdo_driver.h"
#include "ext/standard/url.h"
#include "ext/standard/php_string.h"
#include "ext/pcre/php_pcre.h"
}
#define HAVE_ZLIB_CP HAVE_ZLIB
#undef HAVE_ZLIB
#include "gen-cpp/Cassandra.h"
#include <protocol/TBinaryProtocol.h>
#include <transport/TSocketPool.h>
#include <transport/TTransportUtils.h>
#undef HAVE_ZLIB
#define HAVE_ZLIB HAVE_ZLIB_CP
#include <boost/bimap.hpp>
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
using namespace org::apache::cassandra;
enum pdo_cassandra_type {
PDO_CASSANDRA_TYPE_BYTES,
PDO_CASSANDRA_TYPE_ASCII,
PDO_CASSANDRA_TYPE_UTF8,
PDO_CASSANDRA_TYPE_INTEGER,
PDO_CASSANDRA_TYPE_LONG,
PDO_CASSANDRA_TYPE_UUID,
PDO_CASSANDRA_TYPE_LEXICAL,
PDO_CASSANDRA_TYPE_TIMEUUID,
PDO_CASSANDRA_TYPE_UNKNOWN
};
/** {{{
*/
typedef struct {
const char *file;
char *errmsg;
int line;
unsigned int errcode;
} pdo_cassandra_einfo;
/* }}} */
/* {{{ typedef struct php_cassandra_db_handle
*/
typedef struct {
zend_object zo;
zend_bool compression;
boost::shared_ptr<TSocketPool> socket;
boost::shared_ptr<TFramedTransport> transport;
boost::shared_ptr<TProtocol> protocol;
boost::shared_ptr<CassandraClient> client;
pdo_cassandra_einfo einfo;
std::string active_keyspace;
KsDef description;
zend_bool has_description;
zend_bool preserve_values;
} pdo_cassandra_db_handle;
/* }}} */
typedef boost::bimap<std::string, int> ColumnMap;
/* {{{ typedef struct pdo_cassandra_stmt
*/
typedef struct {
pdo_cassandra_db_handle *H;
zend_bool has_iterator;
boost::shared_ptr<CqlResult> result;
std::vector<CqlRow>::iterator it;
ColumnMap original_column_names;
ColumnMap column_name_labels;
std::string active_columnfamily;
} pdo_cassandra_stmt;
/* }}} */
/* {{{ enum pdo_cassandra_constant
*/
enum pdo_cassandra_constant {
PDO_CASSANDRA_ATTR_MIN = PDO_ATTR_DRIVER_SPECIFIC,
PDO_CASSANDRA_ATTR_NUM_RETRIES,
PDO_CASSANDRA_ATTR_RETRY_INTERVAL,
PDO_CASSANDRA_ATTR_MAX_CONSECUTIVE_FAILURES,
PDO_CASSANDRA_ATTR_RANDOMIZE,
PDO_CASSANDRA_ATTR_ALWAYS_TRY_LAST,
PDO_CASSANDRA_ATTR_LINGER,
PDO_CASSANDRA_ATTR_NO_DELAY,
PDO_CASSANDRA_ATTR_CONN_TIMEOUT,
PDO_CASSANDRA_ATTR_RECV_TIMEOUT,
PDO_CASSANDRA_ATTR_SEND_TIMEOUT,
PDO_CASSANDRA_ATTR_COMPRESSION,
PDO_CASSANDRA_ATTR_THRIFT_DEBUG,
PDO_CASSANDRA_ATTR_PRESERVE_VALUES,
PDO_CASSANDRA_ATTR_MAX
};
/* }}} */
enum pdo_cassandra_error {
PDO_CASSANDRA_GENERAL_ERROR,
PDO_CASSANDRA_NOT_FOUND,
PDO_CASSANDRA_INVALID_REQUEST,
PDO_CASSANDRA_UNAVAILABLE,
PDO_CASSANDRA_TIMED_OUT,
PDO_CASSANDRA_AUTHENTICATION_ERROR,
PDO_CASSANDRA_AUTHORIZATION_ERROR,
PDO_CASSANDRA_SCHEMA_DISAGREEMENT,
PDO_CASSANDRA_TRANSPORT_ERROR,
PDO_CASSANDRA_INVALID_CONNECTION_STRING
};
void pdo_cassandra_error_ex(pdo_dbh_t *dbh TSRMLS_DC, pdo_cassandra_error code, const char *file, int line, zend_bool force_exception, const char *message, ...);
#define pdo_cassandra_error(dbh, code, message, ...) pdo_cassandra_error_ex(dbh TSRMLS_CC, code, __FILE__, __LINE__, 0, message, __VA_ARGS__)
#define pdo_cassandra_error_exception(dbh, code, message, ...) pdo_cassandra_error_ex(dbh TSRMLS_CC, code, __FILE__, __LINE__, 1, message, __VA_ARGS__)
void pdo_cassandra_set_active_keyspace(pdo_cassandra_db_handle *H, const std::string &sql);
#endif /* _PHP_PDO_CASSANDRA_PRIVATE_H_ */
<|endoftext|>
|
<commit_before>// Copyright 2020 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "distance_function.h"
#include "hnsw_index.h"
#include "random_level_generator.h"
#include <vespa/eval/tensor/dense/typed_cells.h>
#include <vespa/vespalib/datastore/array_store.hpp>
#include <vespa/vespalib/util/rcuvector.hpp>
namespace search::tensor {
namespace {
// TODO: Move this to MemoryAllocator, with name PAGE_SIZE.
constexpr size_t small_page_size = 4 * 1024;
constexpr size_t min_num_arrays_for_new_buffer = 8 * 1024;
constexpr float alloc_grow_factor = 0.2;
// TODO: Adjust these numbers to what we accept as max in config.
constexpr size_t max_level_array_size = 16;
constexpr size_t max_link_array_size = 64;
}
search::datastore::ArrayStoreConfig
HnswIndex::make_default_node_store_config()
{
return NodeStore::optimizedConfigForHugePage(max_level_array_size, vespalib::alloc::MemoryAllocator::HUGEPAGE_SIZE,
small_page_size, min_num_arrays_for_new_buffer, alloc_grow_factor).enable_free_lists(true);
}
search::datastore::ArrayStoreConfig
HnswIndex::make_default_link_store_config()
{
return LinkStore::optimizedConfigForHugePage(max_link_array_size, vespalib::alloc::MemoryAllocator::HUGEPAGE_SIZE,
small_page_size, min_num_arrays_for_new_buffer, alloc_grow_factor).enable_free_lists(true);
}
uint32_t
HnswIndex::max_links_for_level(uint32_t level) const
{
return (level == 0) ? _cfg.max_links_at_level_0() : _cfg.max_links_at_hierarchic_levels();
}
uint32_t
HnswIndex::make_node_for_document(uint32_t docid)
{
uint32_t max_level = _level_generator.max_level();
// TODO: Add capping on num_levels
uint32_t num_levels = max_level + 1;
// Note: The level array instance lives as long as the document is present in the index.
LevelArray levels(num_levels, AtomicEntryRef());
auto node_ref = _nodes.add(levels);
_node_refs[docid].store_release(node_ref);
return max_level;
}
HnswIndex::LevelArrayRef
HnswIndex::get_level_array(uint32_t docid) const
{
auto node_ref = _node_refs[docid].load_acquire();
return _nodes.get(node_ref);
}
HnswIndex::LinkArrayRef
HnswIndex::get_link_array(uint32_t docid, uint32_t level) const
{
auto levels = get_level_array(docid);
assert(level < levels.size());
return _links.get(levels[level].load_acquire());
}
void
HnswIndex::set_link_array(uint32_t docid, uint32_t level, const LinkArrayRef& links)
{
auto links_ref = _links.add(links);
auto node_ref = _node_refs[docid].load_acquire();
auto levels = _nodes.get_writable(node_ref);
levels[level].store_release(links_ref);
}
bool
HnswIndex::have_closer_distance(HnswCandidate candidate, const LinkArray& result) const
{
for (uint32_t result_docid : result) {
double dist = calc_distance(candidate.docid, result_docid);
if (dist < candidate.distance) {
return true;
}
}
return false;
}
HnswIndex::LinkArray
HnswIndex::select_neighbors_simple(const HnswCandidateVector& neighbors, uint32_t max_links) const
{
HnswCandidateVector sorted(neighbors);
std::sort(sorted.begin(), sorted.end(), LesserDistance());
LinkArray result;
for (size_t i = 0, m = std::min(static_cast<size_t>(max_links), sorted.size()); i < m; ++i) {
result.push_back(sorted[i].docid);
}
return result;
}
HnswIndex::LinkArray
HnswIndex::select_neighbors_heuristic(const HnswCandidateVector& neighbors, uint32_t max_links) const
{
LinkArray result;
bool need_filtering = neighbors.size() > max_links;
NearestPriQ nearest;
for (const auto& entry : neighbors) {
nearest.push(entry);
}
while (!nearest.empty()) {
auto candidate = nearest.top();
nearest.pop();
if (need_filtering && have_closer_distance(candidate, result)) {
continue;
}
result.push_back(candidate.docid);
if (result.size() == max_links) {
return result;
}
}
return result;
}
HnswIndex::LinkArray
HnswIndex::select_neighbors(const HnswCandidateVector& neighbors, uint32_t max_links) const
{
if (_cfg.heuristic_select_neighbors()) {
return select_neighbors_heuristic(neighbors, max_links);
} else {
return select_neighbors_simple(neighbors, max_links);
}
}
void
HnswIndex::connect_new_node(uint32_t docid, const LinkArray& neighbors, uint32_t level)
{
set_link_array(docid, level, neighbors);
for (uint32_t neighbor_docid : neighbors) {
auto old_links = get_link_array(neighbor_docid, level);
LinkArray new_links(old_links.begin(), old_links.end());
new_links.push_back(docid);
set_link_array(neighbor_docid, level, new_links);
}
}
void
HnswIndex::remove_link_to(uint32_t remove_from, uint32_t remove_id, uint32_t level)
{
LinkArray new_links;
auto old_links = get_link_array(remove_from, level);
for (uint32_t id : old_links) {
if (id != remove_id) new_links.push_back(id);
}
set_link_array(remove_from, level, new_links);
}
double
HnswIndex::calc_distance(uint32_t lhs_docid, uint32_t rhs_docid) const
{
auto lhs = get_vector(lhs_docid);
return calc_distance(lhs, rhs_docid);
}
double
HnswIndex::calc_distance(const TypedCells& lhs, uint32_t rhs_docid) const
{
auto rhs = get_vector(rhs_docid);
return _distance_func.calc(lhs, rhs);
}
HnswCandidate
HnswIndex::find_nearest_in_layer(const TypedCells& input, const HnswCandidate& entry_point, uint32_t level)
{
HnswCandidate nearest = entry_point;
bool keep_searching = true;
while (keep_searching) {
keep_searching = false;
for (uint32_t neighbor_docid : get_link_array(nearest.docid, level)) {
double dist = calc_distance(input, neighbor_docid);
if (dist < nearest.distance) {
nearest = HnswCandidate(neighbor_docid, dist);
keep_searching = true;
}
}
}
return nearest;
}
void
HnswIndex::search_layer(const TypedCells& input, uint32_t neighbors_to_find, FurthestPriQ& best_neighbors, uint32_t level)
{
NearestPriQ candidates;
// TODO: Add proper handling of visited set.
auto visited = BitVector::create(_node_refs.size());
for (const auto &entry : best_neighbors.peek()) {
candidates.push(entry);
visited->setBit(entry.docid);
}
double limit_dist = std::numeric_limits<double>::max();
while (!candidates.empty()) {
auto cand = candidates.top();
if (cand.distance > limit_dist) {
break;
}
candidates.pop();
for (uint32_t neighbor_docid : get_link_array(cand.docid, level)) {
if (visited->testBit(neighbor_docid)) {
continue;
}
visited->setBit(neighbor_docid);
double dist_to_input = calc_distance(input, neighbor_docid);
if (dist_to_input < limit_dist) {
candidates.emplace(neighbor_docid, dist_to_input);
best_neighbors.emplace(neighbor_docid, dist_to_input);
if (best_neighbors.size() > neighbors_to_find) {
best_neighbors.pop();
limit_dist = best_neighbors.top().distance;
}
}
}
}
}
HnswIndex::HnswIndex(const DocVectorAccess& vectors, const DistanceFunction& distance_func,
RandomLevelGenerator& level_generator, const Config& cfg)
: _vectors(vectors),
_distance_func(distance_func),
_level_generator(level_generator),
_cfg(cfg),
_node_refs(),
_nodes(make_default_node_store_config()),
_links(make_default_link_store_config()),
_entry_docid(0), // Note that docid 0 is reserved and never used
_entry_level(-1)
{
}
HnswIndex::~HnswIndex() = default;
void
HnswIndex::add_document(uint32_t docid)
{
auto input = get_vector(docid);
_node_refs.ensure_size(docid + 1, AtomicEntryRef());
// A document cannot be added twice.
assert(!_node_refs[docid].load_acquire().valid());
int level = make_node_for_document(docid);
if (_entry_docid == 0) {
_entry_docid = docid;
_entry_level = level;
return;
}
int search_level = _entry_level;
double entry_dist = calc_distance(input, _entry_docid);
HnswCandidate entry_point(_entry_docid, entry_dist);
while (search_level > level) {
entry_point = find_nearest_in_layer(input, entry_point, search_level);
--search_level;
}
FurthestPriQ best_neighbors;
best_neighbors.push(entry_point);
search_level = std::min(level, _entry_level);
// Insert the added document in each level it should exist in.
while (search_level >= 0) {
// TODO: Rename to search_level?
search_layer(input, _cfg.neighbors_to_explore_at_construction(), best_neighbors, search_level);
auto neighbors = select_neighbors(best_neighbors.peek(), max_links_for_level(search_level));
connect_new_node(docid, neighbors, search_level);
// TODO: Shrink neighbors if needed
--search_level;
}
if (level > _entry_level) {
_entry_docid = docid;
_entry_level = level;
}
}
void
HnswIndex::remove_document(uint32_t docid)
{
bool need_new_entrypoint = (docid == _entry_docid);
LinkArray empty;
LevelArrayRef node_levels = get_level_array(docid);
for (int level = node_levels.size(); level-- > 0; ) {
LinkArrayRef my_links = get_link_array(docid, level);
for (uint32_t neighbor_id : my_links) {
if (need_new_entrypoint) {
_entry_docid = neighbor_id;
_entry_level = level;
need_new_entrypoint = false;
}
remove_link_to(neighbor_id, docid, level);
}
set_link_array(docid, level, empty);
}
if (need_new_entrypoint) {
_entry_docid = 0;
_entry_level = -1;
}
search::datastore::EntryRef invalid;
_node_refs[docid].store_release(invalid);
}
std::vector<uint32_t>
HnswIndex::find_top_k(uint32_t k, TypedCells vector, uint32_t explore_k)
{
std::vector<uint32_t> result;
FurthestPriQ candidates = top_k_candidates(vector, explore_k);
while (candidates.size() > k) {
candidates.pop();
}
result.reserve(candidates.size());
for (const HnswCandidate & hit : candidates.peek()) {
result.emplace_back(hit.docid);
}
std::sort(result.begin(), result.end());
return result;
}
FurthestPriQ
HnswIndex::top_k_candidates(const TypedCells &vector, uint32_t k)
{
FurthestPriQ best_neighbors;
if (_entry_level < 0) {
return best_neighbors;
}
double entry_dist = calc_distance(vector, _entry_docid);
HnswCandidate entry_point(_entry_docid, entry_dist);
int search_level = _entry_level;
while (search_level > 0) {
entry_point = find_nearest_in_layer(vector, entry_point, search_level);
--search_level;
}
best_neighbors.push(entry_point);
search_layer(vector, k, best_neighbors, 0);
return best_neighbors;
}
HnswNode
HnswIndex::get_node(uint32_t docid) const
{
auto node_ref = _node_refs[docid].load_acquire();
if (!node_ref.valid()) {
return HnswNode();
}
auto levels = _nodes.get(node_ref);
HnswNode::LevelArray result;
for (const auto& links_ref : levels) {
auto links = _links.get(links_ref.load_acquire());
HnswNode::LinkArray result_links(links.begin(), links.end());
std::sort(result_links.begin(), result_links.end());
result.push_back(result_links);
}
return HnswNode(result);
}
}
<commit_msg>explore at least k always<commit_after>// Copyright 2020 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "distance_function.h"
#include "hnsw_index.h"
#include "random_level_generator.h"
#include <vespa/eval/tensor/dense/typed_cells.h>
#include <vespa/vespalib/datastore/array_store.hpp>
#include <vespa/vespalib/util/rcuvector.hpp>
namespace search::tensor {
namespace {
// TODO: Move this to MemoryAllocator, with name PAGE_SIZE.
constexpr size_t small_page_size = 4 * 1024;
constexpr size_t min_num_arrays_for_new_buffer = 8 * 1024;
constexpr float alloc_grow_factor = 0.2;
// TODO: Adjust these numbers to what we accept as max in config.
constexpr size_t max_level_array_size = 16;
constexpr size_t max_link_array_size = 64;
}
search::datastore::ArrayStoreConfig
HnswIndex::make_default_node_store_config()
{
return NodeStore::optimizedConfigForHugePage(max_level_array_size, vespalib::alloc::MemoryAllocator::HUGEPAGE_SIZE,
small_page_size, min_num_arrays_for_new_buffer, alloc_grow_factor).enable_free_lists(true);
}
search::datastore::ArrayStoreConfig
HnswIndex::make_default_link_store_config()
{
return LinkStore::optimizedConfigForHugePage(max_link_array_size, vespalib::alloc::MemoryAllocator::HUGEPAGE_SIZE,
small_page_size, min_num_arrays_for_new_buffer, alloc_grow_factor).enable_free_lists(true);
}
uint32_t
HnswIndex::max_links_for_level(uint32_t level) const
{
return (level == 0) ? _cfg.max_links_at_level_0() : _cfg.max_links_at_hierarchic_levels();
}
uint32_t
HnswIndex::make_node_for_document(uint32_t docid)
{
uint32_t max_level = _level_generator.max_level();
// TODO: Add capping on num_levels
uint32_t num_levels = max_level + 1;
// Note: The level array instance lives as long as the document is present in the index.
LevelArray levels(num_levels, AtomicEntryRef());
auto node_ref = _nodes.add(levels);
_node_refs[docid].store_release(node_ref);
return max_level;
}
HnswIndex::LevelArrayRef
HnswIndex::get_level_array(uint32_t docid) const
{
auto node_ref = _node_refs[docid].load_acquire();
return _nodes.get(node_ref);
}
HnswIndex::LinkArrayRef
HnswIndex::get_link_array(uint32_t docid, uint32_t level) const
{
auto levels = get_level_array(docid);
assert(level < levels.size());
return _links.get(levels[level].load_acquire());
}
void
HnswIndex::set_link_array(uint32_t docid, uint32_t level, const LinkArrayRef& links)
{
auto links_ref = _links.add(links);
auto node_ref = _node_refs[docid].load_acquire();
auto levels = _nodes.get_writable(node_ref);
levels[level].store_release(links_ref);
}
bool
HnswIndex::have_closer_distance(HnswCandidate candidate, const LinkArray& result) const
{
for (uint32_t result_docid : result) {
double dist = calc_distance(candidate.docid, result_docid);
if (dist < candidate.distance) {
return true;
}
}
return false;
}
HnswIndex::LinkArray
HnswIndex::select_neighbors_simple(const HnswCandidateVector& neighbors, uint32_t max_links) const
{
HnswCandidateVector sorted(neighbors);
std::sort(sorted.begin(), sorted.end(), LesserDistance());
LinkArray result;
for (size_t i = 0, m = std::min(static_cast<size_t>(max_links), sorted.size()); i < m; ++i) {
result.push_back(sorted[i].docid);
}
return result;
}
HnswIndex::LinkArray
HnswIndex::select_neighbors_heuristic(const HnswCandidateVector& neighbors, uint32_t max_links) const
{
LinkArray result;
bool need_filtering = neighbors.size() > max_links;
NearestPriQ nearest;
for (const auto& entry : neighbors) {
nearest.push(entry);
}
while (!nearest.empty()) {
auto candidate = nearest.top();
nearest.pop();
if (need_filtering && have_closer_distance(candidate, result)) {
continue;
}
result.push_back(candidate.docid);
if (result.size() == max_links) {
return result;
}
}
return result;
}
HnswIndex::LinkArray
HnswIndex::select_neighbors(const HnswCandidateVector& neighbors, uint32_t max_links) const
{
if (_cfg.heuristic_select_neighbors()) {
return select_neighbors_heuristic(neighbors, max_links);
} else {
return select_neighbors_simple(neighbors, max_links);
}
}
void
HnswIndex::connect_new_node(uint32_t docid, const LinkArray& neighbors, uint32_t level)
{
set_link_array(docid, level, neighbors);
for (uint32_t neighbor_docid : neighbors) {
auto old_links = get_link_array(neighbor_docid, level);
LinkArray new_links(old_links.begin(), old_links.end());
new_links.push_back(docid);
set_link_array(neighbor_docid, level, new_links);
}
}
void
HnswIndex::remove_link_to(uint32_t remove_from, uint32_t remove_id, uint32_t level)
{
LinkArray new_links;
auto old_links = get_link_array(remove_from, level);
for (uint32_t id : old_links) {
if (id != remove_id) new_links.push_back(id);
}
set_link_array(remove_from, level, new_links);
}
double
HnswIndex::calc_distance(uint32_t lhs_docid, uint32_t rhs_docid) const
{
auto lhs = get_vector(lhs_docid);
return calc_distance(lhs, rhs_docid);
}
double
HnswIndex::calc_distance(const TypedCells& lhs, uint32_t rhs_docid) const
{
auto rhs = get_vector(rhs_docid);
return _distance_func.calc(lhs, rhs);
}
HnswCandidate
HnswIndex::find_nearest_in_layer(const TypedCells& input, const HnswCandidate& entry_point, uint32_t level)
{
HnswCandidate nearest = entry_point;
bool keep_searching = true;
while (keep_searching) {
keep_searching = false;
for (uint32_t neighbor_docid : get_link_array(nearest.docid, level)) {
double dist = calc_distance(input, neighbor_docid);
if (dist < nearest.distance) {
nearest = HnswCandidate(neighbor_docid, dist);
keep_searching = true;
}
}
}
return nearest;
}
void
HnswIndex::search_layer(const TypedCells& input, uint32_t neighbors_to_find, FurthestPriQ& best_neighbors, uint32_t level)
{
NearestPriQ candidates;
// TODO: Add proper handling of visited set.
auto visited = BitVector::create(_node_refs.size());
for (const auto &entry : best_neighbors.peek()) {
candidates.push(entry);
visited->setBit(entry.docid);
}
double limit_dist = std::numeric_limits<double>::max();
while (!candidates.empty()) {
auto cand = candidates.top();
if (cand.distance > limit_dist) {
break;
}
candidates.pop();
for (uint32_t neighbor_docid : get_link_array(cand.docid, level)) {
if (visited->testBit(neighbor_docid)) {
continue;
}
visited->setBit(neighbor_docid);
double dist_to_input = calc_distance(input, neighbor_docid);
if (dist_to_input < limit_dist) {
candidates.emplace(neighbor_docid, dist_to_input);
best_neighbors.emplace(neighbor_docid, dist_to_input);
if (best_neighbors.size() > neighbors_to_find) {
best_neighbors.pop();
limit_dist = best_neighbors.top().distance;
}
}
}
}
}
HnswIndex::HnswIndex(const DocVectorAccess& vectors, const DistanceFunction& distance_func,
RandomLevelGenerator& level_generator, const Config& cfg)
: _vectors(vectors),
_distance_func(distance_func),
_level_generator(level_generator),
_cfg(cfg),
_node_refs(),
_nodes(make_default_node_store_config()),
_links(make_default_link_store_config()),
_entry_docid(0), // Note that docid 0 is reserved and never used
_entry_level(-1)
{
}
HnswIndex::~HnswIndex() = default;
void
HnswIndex::add_document(uint32_t docid)
{
auto input = get_vector(docid);
_node_refs.ensure_size(docid + 1, AtomicEntryRef());
// A document cannot be added twice.
assert(!_node_refs[docid].load_acquire().valid());
int level = make_node_for_document(docid);
if (_entry_docid == 0) {
_entry_docid = docid;
_entry_level = level;
return;
}
int search_level = _entry_level;
double entry_dist = calc_distance(input, _entry_docid);
HnswCandidate entry_point(_entry_docid, entry_dist);
while (search_level > level) {
entry_point = find_nearest_in_layer(input, entry_point, search_level);
--search_level;
}
FurthestPriQ best_neighbors;
best_neighbors.push(entry_point);
search_level = std::min(level, _entry_level);
// Insert the added document in each level it should exist in.
while (search_level >= 0) {
// TODO: Rename to search_level?
search_layer(input, _cfg.neighbors_to_explore_at_construction(), best_neighbors, search_level);
auto neighbors = select_neighbors(best_neighbors.peek(), max_links_for_level(search_level));
connect_new_node(docid, neighbors, search_level);
// TODO: Shrink neighbors if needed
--search_level;
}
if (level > _entry_level) {
_entry_docid = docid;
_entry_level = level;
}
}
void
HnswIndex::remove_document(uint32_t docid)
{
bool need_new_entrypoint = (docid == _entry_docid);
LinkArray empty;
LevelArrayRef node_levels = get_level_array(docid);
for (int level = node_levels.size(); level-- > 0; ) {
LinkArrayRef my_links = get_link_array(docid, level);
for (uint32_t neighbor_id : my_links) {
if (need_new_entrypoint) {
_entry_docid = neighbor_id;
_entry_level = level;
need_new_entrypoint = false;
}
remove_link_to(neighbor_id, docid, level);
}
set_link_array(docid, level, empty);
}
if (need_new_entrypoint) {
_entry_docid = 0;
_entry_level = -1;
}
search::datastore::EntryRef invalid;
_node_refs[docid].store_release(invalid);
}
std::vector<uint32_t>
HnswIndex::find_top_k(uint32_t k, TypedCells vector, uint32_t explore_k)
{
std::vector<uint32_t> result;
FurthestPriQ candidates = top_k_candidates(vector, std::max(k, explore_k));
while (candidates.size() > k) {
candidates.pop();
}
result.reserve(candidates.size());
for (const HnswCandidate & hit : candidates.peek()) {
result.emplace_back(hit.docid);
}
std::sort(result.begin(), result.end());
return result;
}
FurthestPriQ
HnswIndex::top_k_candidates(const TypedCells &vector, uint32_t k)
{
FurthestPriQ best_neighbors;
if (_entry_level < 0) {
return best_neighbors;
}
double entry_dist = calc_distance(vector, _entry_docid);
HnswCandidate entry_point(_entry_docid, entry_dist);
int search_level = _entry_level;
while (search_level > 0) {
entry_point = find_nearest_in_layer(vector, entry_point, search_level);
--search_level;
}
best_neighbors.push(entry_point);
search_layer(vector, k, best_neighbors, 0);
return best_neighbors;
}
HnswNode
HnswIndex::get_node(uint32_t docid) const
{
auto node_ref = _node_refs[docid].load_acquire();
if (!node_ref.valid()) {
return HnswNode();
}
auto levels = _nodes.get(node_ref);
HnswNode::LevelArray result;
for (const auto& links_ref : levels) {
auto links = _links.get(links_ref.load_acquire());
HnswNode::LinkArray result_links(links.begin(), links.end());
std::sort(result_links.begin(), result_links.end());
result.push_back(result_links);
}
return HnswNode(result);
}
}
<|endoftext|>
|
<commit_before>// -*- C++ -*-
//===-------------------- support/win32/locale_win32.cpp ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include <locale>
#include <cstdarg> // va_start, va_end
#include <memory>
#include <type_traits>
typedef _VSTD::remove_pointer<locale_t>::type __locale_struct;
typedef _VSTD::unique_ptr<__locale_struct, decltype(&uselocale)> __locale_raii;
// FIXME: base currently unused. Needs manual work to construct the new locale
locale_t newlocale( int mask, const char * locale, locale_t /*base*/ )
{
return _create_locale( mask, locale );
}
locale_t uselocale( locale_t newloc )
{
locale_t old_locale = _get_current_locale();
if ( newloc == NULL )
return old_locale;
// uselocale sets the thread's locale by definition, so unconditionally use thread-local locale
_configthreadlocale( _ENABLE_PER_THREAD_LOCALE );
// uselocale sets all categories
setlocale( LC_ALL, newloc->locinfo->lc_category[LC_ALL].locale );
// uselocale returns the old locale_t
return old_locale;
}
lconv *localeconv_l( locale_t loc )
{
__locale_raii __current( uselocale(loc), uselocale );
return localeconv();
}
size_t mbrlen_l( const char *__restrict s, size_t n,
mbstate_t *__restrict ps, locale_t loc )
{
__locale_raii __current( uselocale(loc), uselocale );
return mbrlen( s, n, ps );
}
size_t mbsrtowcs_l( wchar_t *__restrict dst, const char **__restrict src,
size_t len, mbstate_t *__restrict ps, locale_t loc )
{
__locale_raii __current( uselocale(loc), uselocale );
return mbsrtowcs( dst, src, len, ps );
}
size_t wcrtomb_l( char *__restrict s, wchar_t wc, mbstate_t *__restrict ps,
locale_t loc )
{
__locale_raii __current( uselocale(loc), uselocale );
return wcrtomb( s, wc, ps );
}
size_t mbrtowc_l( wchar_t *__restrict pwc, const char *__restrict s,
size_t n, mbstate_t *__restrict ps, locale_t loc )
{
__locale_raii __current( uselocale(loc), uselocale );
return mbrtowc( pwc, s, n, ps );
}
size_t mbsnrtowcs_l( wchar_t *__restrict dst, const char **__restrict src,
size_t nms, size_t len, mbstate_t *__restrict ps, locale_t loc )
{
__locale_raii __current( uselocale(loc), uselocale );
return mbsnrtowcs( dst, src, nms, len, ps );
}
size_t wcsnrtombs_l( char *__restrict dst, const wchar_t **__restrict src,
size_t nwc, size_t len, mbstate_t *__restrict ps, locale_t loc )
{
__locale_raii __current( uselocale(loc), uselocale );
return wcsnrtombs( dst, src, nwc, len, ps );
}
wint_t btowc_l( int c, locale_t loc )
{
__locale_raii __current( uselocale(loc), uselocale );
return btowc( c );
}
int wctob_l( wint_t c, locale_t loc )
{
__locale_raii __current( uselocale(loc), uselocale );
return wctob( c );
}
int snprintf_l(char *ret, size_t n, locale_t loc, const char *format, ...)
{
__locale_raii __current( uselocale(loc), uselocale );
va_list ap;
va_start( ap, format );
int result = vsnprintf( ret, n, format, ap );
va_end(ap);
return result;
}
int asprintf_l( char **ret, locale_t loc, const char *format, ... )
{
va_list ap;
va_start( ap, format );
int result = vasprintf_l( ret, loc, format, ap );
va_end(ap);
return result;
}
int vasprintf_l( char **ret, locale_t loc, const char *format, va_list ap )
{
__locale_raii __current( uselocale(loc), uselocale );
return vasprintf( ret, format, ap );
}
<commit_msg>win32: temporarily disable setting locale on 14+<commit_after>// -*- C++ -*-
//===-------------------- support/win32/locale_win32.cpp ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include <locale>
#include <cstdarg> // va_start, va_end
#include <memory>
#include <type_traits>
#include <crtversion.h>
typedef _VSTD::remove_pointer<locale_t>::type __locale_struct;
typedef _VSTD::unique_ptr<__locale_struct, decltype(&uselocale)> __locale_raii;
// FIXME: base currently unused. Needs manual work to construct the new locale
locale_t newlocale( int mask, const char * locale, locale_t /*base*/ )
{
return _create_locale( mask, locale );
}
locale_t uselocale( locale_t newloc )
{
locale_t old_locale = _get_current_locale();
if ( newloc == NULL )
return old_locale;
// uselocale sets the thread's locale by definition, so unconditionally use thread-local locale
_configthreadlocale( _ENABLE_PER_THREAD_LOCALE );
// uselocale sets all categories
#if _VC_CRT_MAJOR_VERSION < 14
setlocale( LC_ALL, newloc->locinfo->lc_category[LC_ALL].locale );
#endif
// uselocale returns the old locale_t
return old_locale;
}
lconv *localeconv_l( locale_t loc )
{
__locale_raii __current( uselocale(loc), uselocale );
return localeconv();
}
size_t mbrlen_l( const char *__restrict s, size_t n,
mbstate_t *__restrict ps, locale_t loc )
{
__locale_raii __current( uselocale(loc), uselocale );
return mbrlen( s, n, ps );
}
size_t mbsrtowcs_l( wchar_t *__restrict dst, const char **__restrict src,
size_t len, mbstate_t *__restrict ps, locale_t loc )
{
__locale_raii __current( uselocale(loc), uselocale );
return mbsrtowcs( dst, src, len, ps );
}
size_t wcrtomb_l( char *__restrict s, wchar_t wc, mbstate_t *__restrict ps,
locale_t loc )
{
__locale_raii __current( uselocale(loc), uselocale );
return wcrtomb( s, wc, ps );
}
size_t mbrtowc_l( wchar_t *__restrict pwc, const char *__restrict s,
size_t n, mbstate_t *__restrict ps, locale_t loc )
{
__locale_raii __current( uselocale(loc), uselocale );
return mbrtowc( pwc, s, n, ps );
}
size_t mbsnrtowcs_l( wchar_t *__restrict dst, const char **__restrict src,
size_t nms, size_t len, mbstate_t *__restrict ps, locale_t loc )
{
__locale_raii __current( uselocale(loc), uselocale );
return mbsnrtowcs( dst, src, nms, len, ps );
}
size_t wcsnrtombs_l( char *__restrict dst, const wchar_t **__restrict src,
size_t nwc, size_t len, mbstate_t *__restrict ps, locale_t loc )
{
__locale_raii __current( uselocale(loc), uselocale );
return wcsnrtombs( dst, src, nwc, len, ps );
}
wint_t btowc_l( int c, locale_t loc )
{
__locale_raii __current( uselocale(loc), uselocale );
return btowc( c );
}
int wctob_l( wint_t c, locale_t loc )
{
__locale_raii __current( uselocale(loc), uselocale );
return wctob( c );
}
int snprintf_l(char *ret, size_t n, locale_t loc, const char *format, ...)
{
__locale_raii __current( uselocale(loc), uselocale );
va_list ap;
va_start( ap, format );
int result = vsnprintf( ret, n, format, ap );
va_end(ap);
return result;
}
int asprintf_l( char **ret, locale_t loc, const char *format, ... )
{
va_list ap;
va_start( ap, format );
int result = vasprintf_l( ret, loc, format, ap );
va_end(ap);
return result;
}
int vasprintf_l( char **ret, locale_t loc, const char *format, va_list ap )
{
__locale_raii __current( uselocale(loc), uselocale );
return vasprintf( ret, format, ap );
}
<|endoftext|>
|
<commit_before>// STL
#include <cassert>
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <string>
// Boost (Extended STL)
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/tokenizer.hpp>
#include <boost/program_options.hpp>
// StdAir
#include <stdair/stdair_basic_types.hpp>
#include <stdair/basic/BasLogParams.hpp>
#include <stdair/basic/BasDBParams.hpp>
#include <stdair/service/Logger.hpp>
// DSIM
#include <dsim/DSIM_Service.hpp>
#include <dsim/config/dsim-paths.hpp>
// //////// Type definitions ///////
typedef std::vector<std::string> WordList_T;
// //////// Constants //////
/** Default name and location for the log file. */
const std::string K_DSIM_DEFAULT_LOG_FILENAME ("simulate.log");
/** Default name and location for the (CSV) demand input file. */
const std::string K_DSIM_DEFAULT_DEMAND_INPUT_FILENAME (STDAIR_SAMPLE_DIR "/demand01.csv");
/** Default name and location for the (CSV) schedule input file. */
const std::string K_DSIM_DEFAULT_SCHEDULE_INPUT_FILENAME (STDAIR_SAMPLE_DIR "/schedule01.csv");
/** Default name and location for the (CSV) O&D input file. */
const std::string K_DSIM_DEFAULT_OND_INPUT_FILENAME (STDAIR_SAMPLE_DIR "/ond01.csv");
/** Default name and location for the (CSV) fare input file. */
const std::string K_DSIM_DEFAULT_FARE_INPUT_FILENAME (STDAIR_SAMPLE_DIR "/fare01.csv");
/** Default query string. */
const std::string K_DSIM_DEFAULT_QUERY_STRING ("my good old query");
/** Default name and location for the Xapian database. */
const std::string K_DSIM_DEFAULT_DB_USER ("dsim");
const std::string K_DSIM_DEFAULT_DB_PASSWD ("dsim");
const std::string K_DSIM_DEFAULT_DB_DBNAME ("sim_dsim");
const std::string K_DSIM_DEFAULT_DB_HOST ("localhost");
const std::string K_DSIM_DEFAULT_DB_PORT ("3306");
// //////////////////////////////////////////////////////////////////////
void tokeniseStringIntoWordList (const std::string& iPhrase,
WordList_T& ioWordList) {
// Empty the word list
ioWordList.clear();
// Boost Tokeniser
typedef boost::tokenizer<boost::char_separator<char> > Tokeniser_T;
// Define the separators
const boost::char_separator<char> lSepatorList(" .,;:|+-*/_=!@#$%`~^&(){}[]?'<>\"");
// Initialise the phrase to be tokenised
Tokeniser_T lTokens (iPhrase, lSepatorList);
for (Tokeniser_T::const_iterator tok_iter = lTokens.begin();
tok_iter != lTokens.end(); ++tok_iter) {
const std::string& lTerm = *tok_iter;
ioWordList.push_back (lTerm);
}
}
// //////////////////////////////////////////////////////////////////////
std::string createStringFromWordList (const WordList_T& iWordList) {
std::ostringstream oStr;
unsigned short idx = iWordList.size();
for (WordList_T::const_iterator itWord = iWordList.begin();
itWord != iWordList.end(); ++itWord, --idx) {
const std::string& lWord = *itWord;
oStr << lWord;
if (idx > 1) {
oStr << " ";
}
}
return oStr.str();
}
// ///////// Parsing of Options & Configuration /////////
// A helper function to simplify the main part.
template<class T> std::ostream& operator<< (std::ostream& os,
const std::vector<T>& v) {
std::copy (v.begin(), v.end(), std::ostream_iterator<T> (std::cout, " "));
return os;
}
/** Early return status (so that it can be differentiated from an error). */
const int K_DSIM_EARLY_RETURN_STATUS = 99;
/** Read and parse the command line options. */
int readConfiguration (int argc, char* argv[],
std::string& ioQueryString,
stdair::Filename_T& ioDemandInputFilename,
stdair::Filename_T& ioScheduleInputFilename,
stdair::Filename_T& ioOnDInputFilename,
stdair::Filename_T& ioFareInputFilename,
std::string& ioLogFilename,
std::string& ioDBUser, std::string& ioDBPasswd,
std::string& ioDBHost, std::string& ioDBPort,
std::string& ioDBDBName) {
// Initialise the travel query string, if that one is empty
if (ioQueryString.empty() == true) {
ioQueryString = K_DSIM_DEFAULT_QUERY_STRING;
}
// Transform the query string into a list of words (STL strings)
WordList_T lWordList;
tokeniseStringIntoWordList (ioQueryString, lWordList);
// Declare a group of options that will be allowed only on command line
boost::program_options::options_description generic ("Generic options");
generic.add_options()
("prefix", "print installation prefix")
("version,v", "print version string")
("help,h", "produce help message");
// Declare a group of options that will be allowed both on command
// line and in config file
boost::program_options::options_description config ("Configuration");
config.add_options()
("demand,d",
boost::program_options::value< std::string >(&ioDemandInputFilename)->default_value(K_DSIM_DEFAULT_DEMAND_INPUT_FILENAME),
"(CVS) input file for the demand distributions")
("schedule,s",
boost::program_options::value< std::string >(&ioScheduleInputFilename)->default_value(K_DSIM_DEFAULT_SCHEDULE_INPUT_FILENAME),
"(CVS) input file for the schedules")
("ond,o",
boost::program_options::value< std::string >(&ioOnDInputFilename)->default_value(K_DSIM_DEFAULT_OND_INPUT_FILENAME),
"(CVS) input file for the O&D definitions")
("fare,f",
boost::program_options::value< std::string >(&ioFareInputFilename)->default_value(K_DSIM_DEFAULT_FARE_INPUT_FILENAME),
"(CVS) input file for the fares")
("log,l",
boost::program_options::value< std::string >(&ioLogFilename)->default_value(K_DSIM_DEFAULT_LOG_FILENAME),
"Filepath for the logs")
("user,u",
boost::program_options::value< std::string >(&ioDBUser)->default_value(K_DSIM_DEFAULT_DB_USER),
"SQL database hostname (e.g., dsim)")
("passwd,p",
boost::program_options::value< std::string >(&ioDBPasswd)->default_value(K_DSIM_DEFAULT_DB_PASSWD),
"SQL database hostname (e.g., dsim)")
("host,H",
boost::program_options::value< std::string >(&ioDBHost)->default_value(K_DSIM_DEFAULT_DB_HOST),
"SQL database hostname (e.g., localhost)")
("port,P",
boost::program_options::value< std::string >(&ioDBPort)->default_value(K_DSIM_DEFAULT_DB_PORT),
"SQL database port (e.g., 3306)")
("dbname,m",
boost::program_options::value< std::string >(&ioDBDBName)->default_value(K_DSIM_DEFAULT_DB_DBNAME),
"SQL database name (e.g., dsim)")
("query,q",
boost::program_options::value< WordList_T >(&lWordList)->multitoken(),
"Query word list")
;
// Hidden options, will be allowed both on command line and
// in config file, but will not be shown to the user.
boost::program_options::options_description hidden ("Hidden options");
hidden.add_options()
("copyright",
boost::program_options::value< std::vector<std::string> >(),
"Show the copyright (license)");
boost::program_options::options_description cmdline_options;
cmdline_options.add(generic).add(config).add(hidden);
boost::program_options::options_description config_file_options;
config_file_options.add(config).add(hidden);
boost::program_options::options_description visible ("Allowed options");
visible.add(generic).add(config);
boost::program_options::positional_options_description p;
p.add ("copyright", -1);
boost::program_options::variables_map vm;
boost::program_options::
store (boost::program_options::command_line_parser (argc, argv).
options (cmdline_options).positional(p).run(), vm);
std::ifstream ifs ("simulate.cfg");
boost::program_options::store (parse_config_file (ifs, config_file_options),
vm);
boost::program_options::notify (vm);
if (vm.count ("help")) {
std::cout << visible << std::endl;
return K_DSIM_EARLY_RETURN_STATUS;
}
if (vm.count ("version")) {
std::cout << PACKAGE_NAME << ", version " << PACKAGE_VERSION << std::endl;
return K_DSIM_EARLY_RETURN_STATUS;
}
if (vm.count ("prefix")) {
std::cout << "Installation prefix: " << PREFIXDIR << std::endl;
return K_DSIM_EARLY_RETURN_STATUS;
}
if (vm.count ("demand")) {
ioDemandInputFilename = vm["demand"].as< std::string >();
std::cout << "Demand input filename is: " << ioDemandInputFilename
<< std::endl;
}
if (vm.count ("ond")) {
ioOnDInputFilename = vm["ond"].as< std::string >();
std::cout << "O&D input filename is: " << ioOnDInputFilename << std::endl;
}
if (vm.count ("fare")) {
ioFareInputFilename = vm["fare"].as< std::string >();
std::cout << "Fare input filename is: " << ioFareInputFilename << std::endl;
}
if (vm.count ("schedule")) {
ioScheduleInputFilename = vm["schedule"].as< std::string >();
std::cout << "Schedule input filename is: " << ioScheduleInputFilename
<< std::endl;
}
if (vm.count ("log")) {
ioLogFilename = vm["log"].as< std::string >();
std::cout << "Log filename is: " << ioLogFilename << std::endl;
}
if (vm.count ("user")) {
ioDBUser = vm["user"].as< std::string >();
std::cout << "SQL database user name is: " << ioDBUser << std::endl;
}
if (vm.count ("passwd")) {
ioDBPasswd = vm["passwd"].as< std::string >();
//std::cout << "SQL database user password is: " << ioDBPasswd << std::endl;
}
if (vm.count ("host")) {
ioDBHost = vm["host"].as< std::string >();
std::cout << "SQL database host name is: " << ioDBHost << std::endl;
}
if (vm.count ("port")) {
ioDBPort = vm["port"].as< std::string >();
std::cout << "SQL database port number is: " << ioDBPort << std::endl;
}
if (vm.count ("dbname")) {
ioDBDBName = vm["dbname"].as< std::string >();
std::cout << "SQL database name is: " << ioDBDBName << std::endl;
}
ioQueryString = createStringFromWordList (lWordList);
std::cout << "The query string is: " << ioQueryString << std::endl;
return 0;
}
// ///////// M A I N ////////////
int main (int argc, char* argv[]) {
// Query
std::string lQuery;
// Demand input file name
stdair::Filename_T lDemandInputFilename;
// Schedule input file name
stdair::Filename_T lScheduleInputFilename;
// O&D input filename
std::string lOnDInputFilename;
// Fare input filename
std::string lFareInputFilename;
// Output log File
std::string lLogFilename;
// SQL database parameters
std::string lDBUser;
std::string lDBPasswd;
std::string lDBHost;
std::string lDBPort;
std::string lDBDBName;
// Call the command-line option parser
const int lOptionParserStatus =
readConfiguration (argc, argv, lQuery, lDemandInputFilename,
lScheduleInputFilename, lOnDInputFilename,
lFareInputFilename, lLogFilename,
lDBUser, lDBPasswd, lDBHost, lDBPort, lDBDBName);
if (lOptionParserStatus == K_DSIM_EARLY_RETURN_STATUS) {
return 0;
}
// Set the database parameters
stdair::BasDBParams lDBParams (lDBUser, lDBPasswd, lDBHost, lDBPort,
lDBDBName);
// Set the log parameters
std::ofstream logOutputFile;
// open and clean the log outputfile
logOutputFile.open (lLogFilename.c_str());
logOutputFile.clear();
// Initialise the simulation context
const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
DSIM::DSIM_Service dsimService (lLogParams, lDBParams,
lScheduleInputFilename, lOnDInputFilename,
lFareInputFilename, lDemandInputFilename);
// Perform a simulation
dsimService.simulate();
// DEBUG
// Display the airlines stored in the database
dsimService.displayAirlineListFromDB();
return 0;
}
<commit_msg>[dsim] Changed the default input files.<commit_after>// STL
#include <cassert>
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <string>
// Boost (Extended STL)
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/tokenizer.hpp>
#include <boost/program_options.hpp>
// StdAir
#include <stdair/stdair_basic_types.hpp>
#include <stdair/basic/BasLogParams.hpp>
#include <stdair/basic/BasDBParams.hpp>
#include <stdair/service/Logger.hpp>
// DSIM
#include <dsim/DSIM_Service.hpp>
#include <dsim/config/dsim-paths.hpp>
// //////// Type definitions ///////
typedef std::vector<std::string> WordList_T;
// //////// Constants //////
/** Default name and location for the log file. */
const std::string K_DSIM_DEFAULT_LOG_FILENAME ("simulate.log");
/** Default name and location for the (CSV) demand input file. */
const std::string K_DSIM_DEFAULT_DEMAND_INPUT_FILENAME (STDAIR_SAMPLE_DIR "/RDS01/demand.csv");
/** Default name and location for the (CSV) schedule input file. */
const std::string K_DSIM_DEFAULT_SCHEDULE_INPUT_FILENAME (STDAIR_SAMPLE_DIR "/RDS01/schedule.csv");
/** Default name and location for the (CSV) O&D input file. */
const std::string K_DSIM_DEFAULT_OND_INPUT_FILENAME (STDAIR_SAMPLE_DIR "/ond01.csv");
/** Default name and location for the (CSV) fare input file. */
const std::string K_DSIM_DEFAULT_FARE_INPUT_FILENAME (STDAIR_SAMPLE_DIR "/RDS01/fare.csv");
/** Default query string. */
const std::string K_DSIM_DEFAULT_QUERY_STRING ("my good old query");
/** Default name and location for the Xapian database. */
const std::string K_DSIM_DEFAULT_DB_USER ("dsim");
const std::string K_DSIM_DEFAULT_DB_PASSWD ("dsim");
const std::string K_DSIM_DEFAULT_DB_DBNAME ("sim_dsim");
const std::string K_DSIM_DEFAULT_DB_HOST ("localhost");
const std::string K_DSIM_DEFAULT_DB_PORT ("3306");
// //////////////////////////////////////////////////////////////////////
void tokeniseStringIntoWordList (const std::string& iPhrase,
WordList_T& ioWordList) {
// Empty the word list
ioWordList.clear();
// Boost Tokeniser
typedef boost::tokenizer<boost::char_separator<char> > Tokeniser_T;
// Define the separators
const boost::char_separator<char> lSepatorList(" .,;:|+-*/_=!@#$%`~^&(){}[]?'<>\"");
// Initialise the phrase to be tokenised
Tokeniser_T lTokens (iPhrase, lSepatorList);
for (Tokeniser_T::const_iterator tok_iter = lTokens.begin();
tok_iter != lTokens.end(); ++tok_iter) {
const std::string& lTerm = *tok_iter;
ioWordList.push_back (lTerm);
}
}
// //////////////////////////////////////////////////////////////////////
std::string createStringFromWordList (const WordList_T& iWordList) {
std::ostringstream oStr;
unsigned short idx = iWordList.size();
for (WordList_T::const_iterator itWord = iWordList.begin();
itWord != iWordList.end(); ++itWord, --idx) {
const std::string& lWord = *itWord;
oStr << lWord;
if (idx > 1) {
oStr << " ";
}
}
return oStr.str();
}
// ///////// Parsing of Options & Configuration /////////
// A helper function to simplify the main part.
template<class T> std::ostream& operator<< (std::ostream& os,
const std::vector<T>& v) {
std::copy (v.begin(), v.end(), std::ostream_iterator<T> (std::cout, " "));
return os;
}
/** Early return status (so that it can be differentiated from an error). */
const int K_DSIM_EARLY_RETURN_STATUS = 99;
/** Read and parse the command line options. */
int readConfiguration (int argc, char* argv[],
std::string& ioQueryString,
stdair::Filename_T& ioDemandInputFilename,
stdair::Filename_T& ioScheduleInputFilename,
stdair::Filename_T& ioOnDInputFilename,
stdair::Filename_T& ioFareInputFilename,
std::string& ioLogFilename,
std::string& ioDBUser, std::string& ioDBPasswd,
std::string& ioDBHost, std::string& ioDBPort,
std::string& ioDBDBName) {
// Initialise the travel query string, if that one is empty
if (ioQueryString.empty() == true) {
ioQueryString = K_DSIM_DEFAULT_QUERY_STRING;
}
// Transform the query string into a list of words (STL strings)
WordList_T lWordList;
tokeniseStringIntoWordList (ioQueryString, lWordList);
// Declare a group of options that will be allowed only on command line
boost::program_options::options_description generic ("Generic options");
generic.add_options()
("prefix", "print installation prefix")
("version,v", "print version string")
("help,h", "produce help message");
// Declare a group of options that will be allowed both on command
// line and in config file
boost::program_options::options_description config ("Configuration");
config.add_options()
("demand,d",
boost::program_options::value< std::string >(&ioDemandInputFilename)->default_value(K_DSIM_DEFAULT_DEMAND_INPUT_FILENAME),
"(CVS) input file for the demand distributions")
("schedule,s",
boost::program_options::value< std::string >(&ioScheduleInputFilename)->default_value(K_DSIM_DEFAULT_SCHEDULE_INPUT_FILENAME),
"(CVS) input file for the schedules")
("ond,o",
boost::program_options::value< std::string >(&ioOnDInputFilename)->default_value(K_DSIM_DEFAULT_OND_INPUT_FILENAME),
"(CVS) input file for the O&D definitions")
("fare,f",
boost::program_options::value< std::string >(&ioFareInputFilename)->default_value(K_DSIM_DEFAULT_FARE_INPUT_FILENAME),
"(CVS) input file for the fares")
("log,l",
boost::program_options::value< std::string >(&ioLogFilename)->default_value(K_DSIM_DEFAULT_LOG_FILENAME),
"Filepath for the logs")
("user,u",
boost::program_options::value< std::string >(&ioDBUser)->default_value(K_DSIM_DEFAULT_DB_USER),
"SQL database hostname (e.g., dsim)")
("passwd,p",
boost::program_options::value< std::string >(&ioDBPasswd)->default_value(K_DSIM_DEFAULT_DB_PASSWD),
"SQL database hostname (e.g., dsim)")
("host,H",
boost::program_options::value< std::string >(&ioDBHost)->default_value(K_DSIM_DEFAULT_DB_HOST),
"SQL database hostname (e.g., localhost)")
("port,P",
boost::program_options::value< std::string >(&ioDBPort)->default_value(K_DSIM_DEFAULT_DB_PORT),
"SQL database port (e.g., 3306)")
("dbname,m",
boost::program_options::value< std::string >(&ioDBDBName)->default_value(K_DSIM_DEFAULT_DB_DBNAME),
"SQL database name (e.g., dsim)")
("query,q",
boost::program_options::value< WordList_T >(&lWordList)->multitoken(),
"Query word list")
;
// Hidden options, will be allowed both on command line and
// in config file, but will not be shown to the user.
boost::program_options::options_description hidden ("Hidden options");
hidden.add_options()
("copyright",
boost::program_options::value< std::vector<std::string> >(),
"Show the copyright (license)");
boost::program_options::options_description cmdline_options;
cmdline_options.add(generic).add(config).add(hidden);
boost::program_options::options_description config_file_options;
config_file_options.add(config).add(hidden);
boost::program_options::options_description visible ("Allowed options");
visible.add(generic).add(config);
boost::program_options::positional_options_description p;
p.add ("copyright", -1);
boost::program_options::variables_map vm;
boost::program_options::
store (boost::program_options::command_line_parser (argc, argv).
options (cmdline_options).positional(p).run(), vm);
std::ifstream ifs ("simulate.cfg");
boost::program_options::store (parse_config_file (ifs, config_file_options),
vm);
boost::program_options::notify (vm);
if (vm.count ("help")) {
std::cout << visible << std::endl;
return K_DSIM_EARLY_RETURN_STATUS;
}
if (vm.count ("version")) {
std::cout << PACKAGE_NAME << ", version " << PACKAGE_VERSION << std::endl;
return K_DSIM_EARLY_RETURN_STATUS;
}
if (vm.count ("prefix")) {
std::cout << "Installation prefix: " << PREFIXDIR << std::endl;
return K_DSIM_EARLY_RETURN_STATUS;
}
if (vm.count ("demand")) {
ioDemandInputFilename = vm["demand"].as< std::string >();
std::cout << "Demand input filename is: " << ioDemandInputFilename
<< std::endl;
}
if (vm.count ("ond")) {
ioOnDInputFilename = vm["ond"].as< std::string >();
std::cout << "O&D input filename is: " << ioOnDInputFilename << std::endl;
}
if (vm.count ("fare")) {
ioFareInputFilename = vm["fare"].as< std::string >();
std::cout << "Fare input filename is: " << ioFareInputFilename << std::endl;
}
if (vm.count ("schedule")) {
ioScheduleInputFilename = vm["schedule"].as< std::string >();
std::cout << "Schedule input filename is: " << ioScheduleInputFilename
<< std::endl;
}
if (vm.count ("log")) {
ioLogFilename = vm["log"].as< std::string >();
std::cout << "Log filename is: " << ioLogFilename << std::endl;
}
if (vm.count ("user")) {
ioDBUser = vm["user"].as< std::string >();
std::cout << "SQL database user name is: " << ioDBUser << std::endl;
}
if (vm.count ("passwd")) {
ioDBPasswd = vm["passwd"].as< std::string >();
//std::cout << "SQL database user password is: " << ioDBPasswd << std::endl;
}
if (vm.count ("host")) {
ioDBHost = vm["host"].as< std::string >();
std::cout << "SQL database host name is: " << ioDBHost << std::endl;
}
if (vm.count ("port")) {
ioDBPort = vm["port"].as< std::string >();
std::cout << "SQL database port number is: " << ioDBPort << std::endl;
}
if (vm.count ("dbname")) {
ioDBDBName = vm["dbname"].as< std::string >();
std::cout << "SQL database name is: " << ioDBDBName << std::endl;
}
ioQueryString = createStringFromWordList (lWordList);
std::cout << "The query string is: " << ioQueryString << std::endl;
return 0;
}
// ///////// M A I N ////////////
int main (int argc, char* argv[]) {
// Query
std::string lQuery;
// Demand input file name
stdair::Filename_T lDemandInputFilename;
// Schedule input file name
stdair::Filename_T lScheduleInputFilename;
// O&D input filename
std::string lOnDInputFilename;
// Fare input filename
std::string lFareInputFilename;
// Output log File
std::string lLogFilename;
// SQL database parameters
std::string lDBUser;
std::string lDBPasswd;
std::string lDBHost;
std::string lDBPort;
std::string lDBDBName;
// Call the command-line option parser
const int lOptionParserStatus =
readConfiguration (argc, argv, lQuery, lDemandInputFilename,
lScheduleInputFilename, lOnDInputFilename,
lFareInputFilename, lLogFilename,
lDBUser, lDBPasswd, lDBHost, lDBPort, lDBDBName);
if (lOptionParserStatus == K_DSIM_EARLY_RETURN_STATUS) {
return 0;
}
// Set the database parameters
stdair::BasDBParams lDBParams (lDBUser, lDBPasswd, lDBHost, lDBPort,
lDBDBName);
// Set the log parameters
std::ofstream logOutputFile;
// open and clean the log outputfile
logOutputFile.open (lLogFilename.c_str());
logOutputFile.clear();
// Initialise the simulation context
const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
DSIM::DSIM_Service dsimService (lLogParams, lDBParams,
lScheduleInputFilename, lOnDInputFilename,
lFareInputFilename, lDemandInputFilename);
// Perform a simulation
dsimService.simulate();
// DEBUG
// Display the airlines stored in the database
dsimService.displayAirlineListFromDB();
return 0;
}
<|endoftext|>
|
<commit_before><commit_msg>Ajokki: do not use heightmap for Helsinki east downtown scene.<commit_after><|endoftext|>
|
<commit_before>#pragma once
#include "config.h"
#include <pybind11/pybind11.h>
#include <autocxxpy/autocxxpy.hpp>
#include "generated_functions.h"
#include "xtp_trader_api.h"
#include "xtp_quote_api.h"
class PyTraderSpi : public XTP::API::TraderSpi
{
public:
void OnDisconnected(uint64_t session_id,int reason) override
{
return autocxxpy::callback_wrapper<&XTP::API::TraderSpi::OnDisconnected>::call(
this,"OnDisconnected",session_id,reason
);
}
void OnError(XTPRI * error_info) override
{
return autocxxpy::callback_wrapper<&XTP::API::TraderSpi::OnError>::call(
this,"OnError",error_info
);
}
void OnOrderEvent(XTPOrderInfo * order_info,XTPRI * error_info,uint64_t session_id) override
{
return autocxxpy::callback_wrapper<&XTP::API::TraderSpi::OnOrderEvent>::call(
this,"OnOrderEvent",order_info,error_info,session_id
);
}
void OnTradeEvent(XTPTradeReport * trade_info,uint64_t session_id) override
{
return autocxxpy::callback_wrapper<&XTP::API::TraderSpi::OnTradeEvent>::call(
this,"OnTradeEvent",trade_info,session_id
);
}
void OnCancelOrderError(XTPOrderCancelInfo * cancel_info,XTPRI * error_info,uint64_t session_id) override
{
return autocxxpy::callback_wrapper<&XTP::API::TraderSpi::OnCancelOrderError>::call(
this,"OnCancelOrderError",cancel_info,error_info,session_id
);
}
void OnQueryOrder(XTPQueryOrderRsp * order_info,XTPRI * error_info,int request_id,bool is_last,uint64_t session_id) override
{
return autocxxpy::callback_wrapper<&XTP::API::TraderSpi::OnQueryOrder>::call(
this,"OnQueryOrder",order_info,error_info,request_id,is_last,session_id
);
}
void OnQueryTrade(XTPQueryTradeRsp * trade_info,XTPRI * error_info,int request_id,bool is_last,uint64_t session_id) override
{
return autocxxpy::callback_wrapper<&XTP::API::TraderSpi::OnQueryTrade>::call(
this,"OnQueryTrade",trade_info,error_info,request_id,is_last,session_id
);
}
void OnQueryPosition(XTPQueryStkPositionRsp * position,XTPRI * error_info,int request_id,bool is_last,uint64_t session_id) override
{
return autocxxpy::callback_wrapper<&XTP::API::TraderSpi::OnQueryPosition>::call(
this,"OnQueryPosition",position,error_info,request_id,is_last,session_id
);
}
void OnQueryAsset(XTPQueryAssetRsp * asset,XTPRI * error_info,int request_id,bool is_last,uint64_t session_id) override
{
return autocxxpy::callback_wrapper<&XTP::API::TraderSpi::OnQueryAsset>::call(
this,"OnQueryAsset",asset,error_info,request_id,is_last,session_id
);
}
void OnQueryStructuredFund(XTPStructuredFundInfo * fund_info,XTPRI * error_info,int request_id,bool is_last,uint64_t session_id) override
{
return autocxxpy::callback_wrapper<&XTP::API::TraderSpi::OnQueryStructuredFund>::call(
this,"OnQueryStructuredFund",fund_info,error_info,request_id,is_last,session_id
);
}
void OnQueryFundTransfer(XTPFundTransferNotice * fund_transfer_info,XTPRI * error_info,int request_id,bool is_last,uint64_t session_id) override
{
return autocxxpy::callback_wrapper<&XTP::API::TraderSpi::OnQueryFundTransfer>::call(
this,"OnQueryFundTransfer",fund_transfer_info,error_info,request_id,is_last,session_id
);
}
void OnFundTransfer(XTPFundTransferNotice * fund_transfer_info,XTPRI * error_info,uint64_t session_id) override
{
return autocxxpy::callback_wrapper<&XTP::API::TraderSpi::OnFundTransfer>::call(
this,"OnFundTransfer",fund_transfer_info,error_info,session_id
);
}
void OnQueryETF(XTPQueryETFBaseRsp * etf_info,XTPRI * error_info,int request_id,bool is_last,uint64_t session_id) override
{
return autocxxpy::callback_wrapper<&XTP::API::TraderSpi::OnQueryETF>::call(
this,"OnQueryETF",etf_info,error_info,request_id,is_last,session_id
);
}
void OnQueryETFBasket(XTPQueryETFComponentRsp * etf_component_info,XTPRI * error_info,int request_id,bool is_last,uint64_t session_id) override
{
return autocxxpy::callback_wrapper<&XTP::API::TraderSpi::OnQueryETFBasket>::call(
this,"OnQueryETFBasket",etf_component_info,error_info,request_id,is_last,session_id
);
}
void OnQueryIPOInfoList(XTPQueryIPOTickerRsp * ipo_info,XTPRI * error_info,int request_id,bool is_last,uint64_t session_id) override
{
return autocxxpy::callback_wrapper<&XTP::API::TraderSpi::OnQueryIPOInfoList>::call(
this,"OnQueryIPOInfoList",ipo_info,error_info,request_id,is_last,session_id
);
}
void OnQueryIPOQuotaInfo(XTPQueryIPOQuotaRsp * quota_info,XTPRI * error_info,int request_id,bool is_last,uint64_t session_id) override
{
return autocxxpy::callback_wrapper<&XTP::API::TraderSpi::OnQueryIPOQuotaInfo>::call(
this,"OnQueryIPOQuotaInfo",quota_info,error_info,request_id,is_last,session_id
);
}
void OnQueryOptionAuctionInfo(XTPQueryOptionAuctionInfoRsp * option_info,XTPRI * error_info,int request_id,bool is_last,uint64_t session_id) override
{
return autocxxpy::callback_wrapper<&XTP::API::TraderSpi::OnQueryOptionAuctionInfo>::call(
this,"OnQueryOptionAuctionInfo",option_info,error_info,request_id,is_last,session_id
);
}
void OnCreditCashRepay(XTPCrdCashRepayRsp * cash_repay_info,XTPRI * error_info,uint64_t session_id) override
{
return autocxxpy::callback_wrapper<&XTP::API::TraderSpi::OnCreditCashRepay>::call(
this,"OnCreditCashRepay",cash_repay_info,error_info,session_id
);
}
void OnQueryCreditCashRepayInfo(XTPCrdCashRepayInfo * cash_repay_info,XTPRI * error_info,int request_id,bool is_last,uint64_t session_id) override
{
return autocxxpy::callback_wrapper<&XTP::API::TraderSpi::OnQueryCreditCashRepayInfo>::call(
this,"OnQueryCreditCashRepayInfo",cash_repay_info,error_info,request_id,is_last,session_id
);
}
void OnQueryCreditFundInfo(XTPCrdFundInfo * fund_info,XTPRI * error_info,int request_id,uint64_t session_id) override
{
return autocxxpy::callback_wrapper<&XTP::API::TraderSpi::OnQueryCreditFundInfo>::call(
this,"OnQueryCreditFundInfo",fund_info,error_info,request_id,session_id
);
}
void OnQueryCreditDebtInfo(XTPCrdDebtInfo * debt_info,XTPRI * error_info,int request_id,bool is_last,uint64_t session_id) override
{
return autocxxpy::callback_wrapper<&XTP::API::TraderSpi::OnQueryCreditDebtInfo>::call(
this,"OnQueryCreditDebtInfo",debt_info,error_info,request_id,is_last,session_id
);
}
void OnQueryCreditTickerDebtInfo(XTPCrdDebtStockInfo * debt_info,XTPRI * error_info,int request_id,bool is_last,uint64_t session_id) override
{
return autocxxpy::callback_wrapper<&XTP::API::TraderSpi::OnQueryCreditTickerDebtInfo>::call(
this,"OnQueryCreditTickerDebtInfo",debt_info,error_info,request_id,is_last,session_id
);
}
void OnQueryCreditAssetDebtInfo(double remain_amount,XTPRI * error_info,int request_id,uint64_t session_id) override
{
return autocxxpy::callback_wrapper<&XTP::API::TraderSpi::OnQueryCreditAssetDebtInfo>::call(
this,"OnQueryCreditAssetDebtInfo",remain_amount,error_info,request_id,session_id
);
}
void OnQueryCreditTickerAssignInfo(XTPClientQueryCrdPositionStkInfo * assign_info,XTPRI * error_info,int request_id,bool is_last,uint64_t session_id) override
{
return autocxxpy::callback_wrapper<&XTP::API::TraderSpi::OnQueryCreditTickerAssignInfo>::call(
this,"OnQueryCreditTickerAssignInfo",assign_info,error_info,request_id,is_last,session_id
);
}
void OnQueryCreditExcessStock(XTPClientQueryCrdSurplusStkRspInfo * stock_info,XTPRI * error_info,int request_id,uint64_t session_id) override
{
return autocxxpy::callback_wrapper<&XTP::API::TraderSpi::OnQueryCreditExcessStock>::call(
this,"OnQueryCreditExcessStock",stock_info,error_info,request_id,session_id
);
}
};
class PyTraderApi : public XTP::API::TraderApi
{
public:
};
class PyQuoteSpi : public XTP::API::QuoteSpi
{
public:
void OnDisconnected(int reason) override
{
return autocxxpy::callback_wrapper<&XTP::API::QuoteSpi::OnDisconnected>::call(
this,"OnDisconnected",reason
);
}
void OnError(XTPRI * error_info) override
{
return autocxxpy::callback_wrapper<&XTP::API::QuoteSpi::OnError>::call(
this,"OnError",error_info
);
}
void OnSubMarketData(XTPST * ticker,XTPRI * error_info,bool is_last) override
{
return autocxxpy::callback_wrapper<&XTP::API::QuoteSpi::OnSubMarketData>::call(
this,"OnSubMarketData",ticker,error_info,is_last
);
}
void OnUnSubMarketData(XTPST * ticker,XTPRI * error_info,bool is_last) override
{
return autocxxpy::callback_wrapper<&XTP::API::QuoteSpi::OnUnSubMarketData>::call(
this,"OnUnSubMarketData",ticker,error_info,is_last
);
}
void OnDepthMarketData(XTPMD * market_data,int64_t bid1_qty[],int32_t bid1_count,int32_t max_bid1_count,int64_t ask1_qty[],int32_t ask1_count,int32_t max_ask1_count) override
{
return autocxxpy::callback_wrapper<&XTP::API::QuoteSpi::OnDepthMarketData>::call(
this,"OnDepthMarketData",market_data,bid1_qty,bid1_count,max_bid1_count,ask1_qty,ask1_count,max_ask1_count
);
}
void OnSubOrderBook(XTPST * ticker,XTPRI * error_info,bool is_last) override
{
return autocxxpy::callback_wrapper<&XTP::API::QuoteSpi::OnSubOrderBook>::call(
this,"OnSubOrderBook",ticker,error_info,is_last
);
}
void OnUnSubOrderBook(XTPST * ticker,XTPRI * error_info,bool is_last) override
{
return autocxxpy::callback_wrapper<&XTP::API::QuoteSpi::OnUnSubOrderBook>::call(
this,"OnUnSubOrderBook",ticker,error_info,is_last
);
}
void OnOrderBook(XTPOB * order_book) override
{
return autocxxpy::callback_wrapper<&XTP::API::QuoteSpi::OnOrderBook>::call(
this,"OnOrderBook",order_book
);
}
void OnSubTickByTick(XTPST * ticker,XTPRI * error_info,bool is_last) override
{
return autocxxpy::callback_wrapper<&XTP::API::QuoteSpi::OnSubTickByTick>::call(
this,"OnSubTickByTick",ticker,error_info,is_last
);
}
void OnUnSubTickByTick(XTPST * ticker,XTPRI * error_info,bool is_last) override
{
return autocxxpy::callback_wrapper<&XTP::API::QuoteSpi::OnUnSubTickByTick>::call(
this,"OnUnSubTickByTick",ticker,error_info,is_last
);
}
void OnTickByTick(XTPTBT * tbt_data) override
{
return autocxxpy::callback_wrapper<&XTP::API::QuoteSpi::OnTickByTick>::call(
this,"OnTickByTick",tbt_data
);
}
void OnSubscribeAllMarketData(XTP_EXCHANGE_TYPE exchange_id,XTPRI * error_info) override
{
return autocxxpy::callback_wrapper<&XTP::API::QuoteSpi::OnSubscribeAllMarketData>::call(
this,"OnSubscribeAllMarketData",exchange_id,error_info
);
}
void OnUnSubscribeAllMarketData(XTP_EXCHANGE_TYPE exchange_id,XTPRI * error_info) override
{
return autocxxpy::callback_wrapper<&XTP::API::QuoteSpi::OnUnSubscribeAllMarketData>::call(
this,"OnUnSubscribeAllMarketData",exchange_id,error_info
);
}
void OnSubscribeAllOrderBook(XTP_EXCHANGE_TYPE exchange_id,XTPRI * error_info) override
{
return autocxxpy::callback_wrapper<&XTP::API::QuoteSpi::OnSubscribeAllOrderBook>::call(
this,"OnSubscribeAllOrderBook",exchange_id,error_info
);
}
void OnUnSubscribeAllOrderBook(XTP_EXCHANGE_TYPE exchange_id,XTPRI * error_info) override
{
return autocxxpy::callback_wrapper<&XTP::API::QuoteSpi::OnUnSubscribeAllOrderBook>::call(
this,"OnUnSubscribeAllOrderBook",exchange_id,error_info
);
}
void OnSubscribeAllTickByTick(XTP_EXCHANGE_TYPE exchange_id,XTPRI * error_info) override
{
return autocxxpy::callback_wrapper<&XTP::API::QuoteSpi::OnSubscribeAllTickByTick>::call(
this,"OnSubscribeAllTickByTick",exchange_id,error_info
);
}
void OnUnSubscribeAllTickByTick(XTP_EXCHANGE_TYPE exchange_id,XTPRI * error_info) override
{
return autocxxpy::callback_wrapper<&XTP::API::QuoteSpi::OnUnSubscribeAllTickByTick>::call(
this,"OnUnSubscribeAllTickByTick",exchange_id,error_info
);
}
void OnQueryAllTickers(XTPQSI * ticker_info,XTPRI * error_info,bool is_last) override
{
return autocxxpy::callback_wrapper<&XTP::API::QuoteSpi::OnQueryAllTickers>::call(
this,"OnQueryAllTickers",ticker_info,error_info,is_last
);
}
void OnQueryTickersPriceInfo(XTPTPI * ticker_info,XTPRI * error_info,bool is_last) override
{
return autocxxpy::callback_wrapper<&XTP::API::QuoteSpi::OnQueryTickersPriceInfo>::call(
this,"OnQueryTickersPriceInfo",ticker_info,error_info,is_last
);
}
void OnSubscribeAllOptionMarketData(XTP_EXCHANGE_TYPE exchange_id,XTPRI * error_info) override
{
return autocxxpy::callback_wrapper<&XTP::API::QuoteSpi::OnSubscribeAllOptionMarketData>::call(
this,"OnSubscribeAllOptionMarketData",exchange_id,error_info
);
}
void OnUnSubscribeAllOptionMarketData(XTP_EXCHANGE_TYPE exchange_id,XTPRI * error_info) override
{
return autocxxpy::callback_wrapper<&XTP::API::QuoteSpi::OnUnSubscribeAllOptionMarketData>::call(
this,"OnUnSubscribeAllOptionMarketData",exchange_id,error_info
);
}
void OnSubscribeAllOptionOrderBook(XTP_EXCHANGE_TYPE exchange_id,XTPRI * error_info) override
{
return autocxxpy::callback_wrapper<&XTP::API::QuoteSpi::OnSubscribeAllOptionOrderBook>::call(
this,"OnSubscribeAllOptionOrderBook",exchange_id,error_info
);
}
void OnUnSubscribeAllOptionOrderBook(XTP_EXCHANGE_TYPE exchange_id,XTPRI * error_info) override
{
return autocxxpy::callback_wrapper<&XTP::API::QuoteSpi::OnUnSubscribeAllOptionOrderBook>::call(
this,"OnUnSubscribeAllOptionOrderBook",exchange_id,error_info
);
}
void OnSubscribeAllOptionTickByTick(XTP_EXCHANGE_TYPE exchange_id,XTPRI * error_info) override
{
return autocxxpy::callback_wrapper<&XTP::API::QuoteSpi::OnSubscribeAllOptionTickByTick>::call(
this,"OnSubscribeAllOptionTickByTick",exchange_id,error_info
);
}
void OnUnSubscribeAllOptionTickByTick(XTP_EXCHANGE_TYPE exchange_id,XTPRI * error_info) override
{
return autocxxpy::callback_wrapper<&XTP::API::QuoteSpi::OnUnSubscribeAllOptionTickByTick>::call(
this,"OnUnSubscribeAllOptionTickByTick",exchange_id,error_info
);
}
};
class PyQuoteApi : public XTP::API::QuoteApi
{
public:
};
<commit_msg>Delete wrappers.hpp<commit_after><|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
#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
<commit_msg>TaskKernelOmp5: Add check num_[teams,threads] in CI<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 || defined ALPAKA_CI
// 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 || defined ALPAKA_CI
// 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>// Copyright (c) 2008, Google 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// 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.
#include "config.h"
#include "ScriptCallContext.h"
#include "ScriptValue.h"
#include "PlatformString.h"
#include "KURL.h"
#include "v8.h"
#include "v8_binding.h"
#include "v8_proxy.h"
namespace WebCore {
ScriptCallContext::ScriptCallContext(const v8::Arguments& args)
: m_args(args)
{
// Line numbers in V8 are starting from zero.
m_lineNumber = V8Proxy::GetSourceLineNumber() + 1;
m_sourceURL = KURL(V8Proxy::GetSourceName());
}
ScriptValue ScriptCallContext::argumentAt(unsigned index)
{
if (index >= argumentCount())
return ScriptValue(v8::Handle<v8::Value>());
return ScriptValue(m_args[index]);
}
String ScriptCallContext::argumentStringAt(unsigned index,
bool checkForNullOrUndefined)
{
if (index >= argumentCount())
return String();
return ToWebCoreString(m_args[index]);
}
unsigned ScriptCallContext::argumentCount() const
{
return m_args.Length();
}
unsigned ScriptCallContext::lineNumber() const
{
return m_lineNumber;
}
KURL ScriptCallContext::sourceURL() const
{
return m_sourceURL;
}
} // namespace WebCore
<commit_msg>Remove unused ScriptCallContextV8.cpp<commit_after><|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2012 Artem Pavlenko
*
* 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 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
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_GEOMETRY_GRAMMAR_HPP
#define MAPNIK_GEOMETRY_GRAMMAR_HPP
// mapnik
#include <mapnik/geometry.hpp> // for geometry_type
#include <mapnik/vertex.hpp> // for CommandType
// spirit::qi
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
namespace mapnik { namespace json {
namespace qi = boost::spirit::qi;
namespace standard_wide = boost::spirit::standard_wide;
using standard_wide::space_type;
#ifdef BOOST_SPIRIT_USE_PHOENIX_V3
struct push_vertex
{
typedef void result_type;
template <typename T0,typename T1, typename T2, typename T3>
result_type operator() (T0 c, T1 path, T2 x, T3 y) const
{
BOOST_ASSERT( path!=0 );
path->push_vertex(x,y,c);
}
};
struct close_path
{
typedef void result_type;
template <typename T>
result_type operator() (T path) const
{
BOOST_ASSERT( path!=0 );
if (path->size() > 2u) // to form a polygon ring we need at least 3 vertices
{
path->close_path();
}
}
};
struct cleanup
{
typedef void result_type;
template <typename T0>
void operator() (T0 & path) const
{
if (path) delete path, path=0;
}
};
struct where_message
{
typedef std::string result_type;
template <typename Iterator>
std::string operator() (Iterator first, Iterator last, std::size_t size) const
{
std::string str(first, last);
if (str.length() > size)
return str.substr(0, size) + "..." ;
return str;
}
};
#else
struct push_vertex
{
template <typename T0,typename T1, typename T2, typename T3>
struct result
{
typedef void type;
};
template <typename T0,typename T1, typename T2, typename T3>
void operator() (T0 c, T1 path, T2 x, T3 y) const
{
BOOST_ASSERT( path!=0 );
path->push_vertex(x,y,c);
}
};
struct close_path
{
template <typename T>
struct result
{
typedef void type;
};
template <typename T>
void operator() (T path) const
{
BOOST_ASSERT( path!=0 );
path->close_path();
}
};
struct cleanup
{
template <typename T0>
struct result
{
typedef void type;
};
template <typename T0>
void operator() (T0 & path) const
{
if (path) delete path, path=0;
}
};
struct where_message
{
template <typename T0,typename T1,typename T2>
struct result
{
typedef std::string type;
};
template <typename Iterator>
std::string operator() (Iterator first, Iterator last, std::size_t size) const
{
std::string str(first, last);
if (str.length() > size)
return str.substr(0, size) + "..." ;
return str;
}
};
#endif
template <typename Iterator>
struct geometry_grammar :
qi::grammar<Iterator,qi::locals<int>, void(boost::ptr_vector<mapnik::geometry_type>& )
, space_type>
{
geometry_grammar();
qi::rule<Iterator, qi::locals<int>, void(boost::ptr_vector<mapnik::geometry_type>& ),space_type> geometry;
qi::symbols<char, int> geometry_dispatch;
qi::rule<Iterator,void(CommandType,geometry_type*),space_type> point;
qi::rule<Iterator,qi::locals<CommandType>,void(geometry_type*),space_type> points;
qi::rule<Iterator,void(boost::ptr_vector<mapnik::geometry_type>&,int),space_type> coordinates;
//
qi::rule<Iterator,qi::locals<geometry_type*>,
void(boost::ptr_vector<mapnik::geometry_type>& ),space_type> point_coordinates;
qi::rule<Iterator,qi::locals<geometry_type*>,
void(boost::ptr_vector<mapnik::geometry_type>& ),space_type> linestring_coordinates;
qi::rule<Iterator,qi::locals<geometry_type*>,
void(boost::ptr_vector<mapnik::geometry_type>& ),space_type> polygon_coordinates;
qi::rule<Iterator,void(boost::ptr_vector<mapnik::geometry_type>& ),space_type> multipoint_coordinates;
qi::rule<Iterator,void(boost::ptr_vector<mapnik::geometry_type>& ),space_type> multilinestring_coordinates;
qi::rule<Iterator,void(boost::ptr_vector<mapnik::geometry_type>& ),space_type> multipolygon_coordinates;
qi::rule<Iterator,void(boost::ptr_vector<mapnik::geometry_type>& ),space_type> geometry_collection;
// Nabialek trick //////////////////////////////////////
//typedef typename qi::rule<Iterator,void(FeatureType &), space_type> dispatch_rule;
//qi::rule<Iterator,qi::locals<dispatch_rule*>, void(FeatureType&),space_type> geometry;
//qi::symbols<char, dispatch_rule*> geometry_dispatch;
////////////////////////////////////////////////////////
boost::phoenix::function<push_vertex> push_vertex_;
boost::phoenix::function<close_path> close_path_;
boost::phoenix::function<cleanup> cleanup_;
boost::phoenix::function<where_message> where_message_;
};
}}
#endif // MAPNIK_GEOMETRY_GRAMMAR_HPP
<commit_msg>apply 5eb406c7df to non PHOENIX_V3 code<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2012 Artem Pavlenko
*
* 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 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
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_GEOMETRY_GRAMMAR_HPP
#define MAPNIK_GEOMETRY_GRAMMAR_HPP
// mapnik
#include <mapnik/geometry.hpp> // for geometry_type
#include <mapnik/vertex.hpp> // for CommandType
// spirit::qi
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
namespace mapnik { namespace json {
namespace qi = boost::spirit::qi;
namespace standard_wide = boost::spirit::standard_wide;
using standard_wide::space_type;
#ifdef BOOST_SPIRIT_USE_PHOENIX_V3
struct push_vertex
{
typedef void result_type;
template <typename T0,typename T1, typename T2, typename T3>
result_type operator() (T0 c, T1 path, T2 x, T3 y) const
{
BOOST_ASSERT( path!=0 );
path->push_vertex(x,y,c);
}
};
struct close_path
{
typedef void result_type;
template <typename T>
result_type operator() (T path) const
{
BOOST_ASSERT( path!=0 );
if (path->size() > 2u) // to form a polygon ring we need at least 3 vertices
{
path->close_path();
}
}
};
struct cleanup
{
typedef void result_type;
template <typename T0>
void operator() (T0 & path) const
{
if (path) delete path, path=0;
}
};
struct where_message
{
typedef std::string result_type;
template <typename Iterator>
std::string operator() (Iterator first, Iterator last, std::size_t size) const
{
std::string str(first, last);
if (str.length() > size)
return str.substr(0, size) + "..." ;
return str;
}
};
#else
struct push_vertex
{
template <typename T0,typename T1, typename T2, typename T3>
struct result
{
typedef void type;
};
template <typename T0,typename T1, typename T2, typename T3>
void operator() (T0 c, T1 path, T2 x, T3 y) const
{
BOOST_ASSERT( path!=0 );
path->push_vertex(x,y,c);
}
};
struct close_path
{
template <typename T>
struct result
{
typedef void type;
};
template <typename T>
void operator() (T path) const
{
BOOST_ASSERT( path!=0 );
if (path->size() > 2u) // to form a polygon ring we need at least 3 vertices
{
path->close_path();
}
}
};
struct cleanup
{
template <typename T0>
struct result
{
typedef void type;
};
template <typename T0>
void operator() (T0 & path) const
{
if (path) delete path, path=0;
}
};
struct where_message
{
template <typename T0,typename T1,typename T2>
struct result
{
typedef std::string type;
};
template <typename Iterator>
std::string operator() (Iterator first, Iterator last, std::size_t size) const
{
std::string str(first, last);
if (str.length() > size)
return str.substr(0, size) + "..." ;
return str;
}
};
#endif
template <typename Iterator>
struct geometry_grammar :
qi::grammar<Iterator,qi::locals<int>, void(boost::ptr_vector<mapnik::geometry_type>& )
, space_type>
{
geometry_grammar();
qi::rule<Iterator, qi::locals<int>, void(boost::ptr_vector<mapnik::geometry_type>& ),space_type> geometry;
qi::symbols<char, int> geometry_dispatch;
qi::rule<Iterator,void(CommandType,geometry_type*),space_type> point;
qi::rule<Iterator,qi::locals<CommandType>,void(geometry_type*),space_type> points;
qi::rule<Iterator,void(boost::ptr_vector<mapnik::geometry_type>&,int),space_type> coordinates;
//
qi::rule<Iterator,qi::locals<geometry_type*>,
void(boost::ptr_vector<mapnik::geometry_type>& ),space_type> point_coordinates;
qi::rule<Iterator,qi::locals<geometry_type*>,
void(boost::ptr_vector<mapnik::geometry_type>& ),space_type> linestring_coordinates;
qi::rule<Iterator,qi::locals<geometry_type*>,
void(boost::ptr_vector<mapnik::geometry_type>& ),space_type> polygon_coordinates;
qi::rule<Iterator,void(boost::ptr_vector<mapnik::geometry_type>& ),space_type> multipoint_coordinates;
qi::rule<Iterator,void(boost::ptr_vector<mapnik::geometry_type>& ),space_type> multilinestring_coordinates;
qi::rule<Iterator,void(boost::ptr_vector<mapnik::geometry_type>& ),space_type> multipolygon_coordinates;
qi::rule<Iterator,void(boost::ptr_vector<mapnik::geometry_type>& ),space_type> geometry_collection;
// Nabialek trick //////////////////////////////////////
//typedef typename qi::rule<Iterator,void(FeatureType &), space_type> dispatch_rule;
//qi::rule<Iterator,qi::locals<dispatch_rule*>, void(FeatureType&),space_type> geometry;
//qi::symbols<char, dispatch_rule*> geometry_dispatch;
////////////////////////////////////////////////////////
boost::phoenix::function<push_vertex> push_vertex_;
boost::phoenix::function<close_path> close_path_;
boost::phoenix::function<cleanup> cleanup_;
boost::phoenix::function<where_message> where_message_;
};
}}
#endif // MAPNIK_GEOMETRY_GRAMMAR_HPP
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2014 Eran Pe'er.
*
* This program is made available under the terms of the MIT License.
*
* Created on Mar 10, 2014
*/
#ifndef VIRTUALTABLE_H_
#define VIRTUALTABLE_H_
#include "mockutils/VTUtils.hpp"
namespace fakeit {
typedef unsigned long DWORD;
struct TypeDescriptor {
TypeDescriptor() :
ptrToVTable(0), spare(0) {
// ptrToVTable should contain the pointer to the virtual table of the type type_info!!!
int ** tiVFTPtr = (int**) (&typeid(void));
int * i = (int*) tiVFTPtr[0];
int type_info_vft_ptr = (int) i;
ptrToVTable = type_info_vft_ptr;
}
DWORD ptrToVTable;
DWORD spare;
char name[8];
};
struct PMD {
/************************************************************************/
/* member displacement.
/* For a simple inheritance structure the member displacement is always 0.
/* since since the first member is placed at 0.
/* In the case of multiple inheritance, this value may have a positive value.
/************************************************************************/
int mdisp;
int pdisp; // vtable displacement
int vdisp; //displacement inside vtable
PMD() :
mdisp(0), pdisp(-1), vdisp(0) {
}
};
struct RTTIBaseClassDescriptor {
RTTIBaseClassDescriptor() :
pTypeDescriptor(nullptr), numContainedBases(0), attributes(0) {
}
const std::type_info* pTypeDescriptor; //type descriptor of the class
DWORD numContainedBases; //number of nested classes following in the Base Class Array
struct PMD where; //pointer-to-member displacement info
DWORD attributes; //flags, usually 0
};
template <typename C, typename... baseclasses>
struct RTTIClassHierarchyDescriptor {
RTTIClassHierarchyDescriptor() :
signature(0), attributes(0), numBaseClasses(0),pBaseClassArray(nullptr){
pBaseClassArray = new RTTIBaseClassDescriptor*[1 + sizeof...(baseclasses)];
addBaseClass<C, baseclasses...>();
}
~RTTIClassHierarchyDescriptor(){
for (int i = 0; i < 1 + sizeof...(baseclasses); i++){
RTTIBaseClassDescriptor * desc = pBaseClassArray[i];
delete desc;
}
delete[] pBaseClassArray;
}
DWORD signature; //always zero?
DWORD attributes; //bit 0 set = multiple inheritance, bit 1 set = virtual inheritance
DWORD numBaseClasses; //number of classes in pBaseClassArray
RTTIBaseClassDescriptor** pBaseClassArray;
template<typename BaseType>
void addBaseClass(){
static_assert(std::is_base_of<BaseType, C>::value, "C must be a derived class of BaseType");
RTTIBaseClassDescriptor* desc = new RTTIBaseClassDescriptor();
desc->pTypeDescriptor = &typeid(BaseType);
pBaseClassArray[numBaseClasses] = desc;
for (unsigned int i = 0; i < numBaseClasses; i++) {
pBaseClassArray[i]->numContainedBases++;
}
numBaseClasses++;
}
template<typename head,typename B1, typename... tail>
void addBaseClass(){
static_assert(std::is_base_of<B1, head>::value, "invalid inheritance list");
addBaseClass<head>();
addBaseClass<B1, tail...>();
}
};
template<typename C, typename... baseclasses>
struct RTTICompleteObjectLocator {
RTTICompleteObjectLocator(const std::type_info& info) :
signature(0), offset(0), cdOffset(0), pTypeDescriptor(&info), pClassDescriptor(new RTTIClassHierarchyDescriptor<C,baseclasses...>()) {
}
~RTTICompleteObjectLocator(){
delete pClassDescriptor;
}
DWORD signature; //always zero ?
DWORD offset; //offset of this vtable in the complete class
DWORD cdOffset; //constructor displacement offset
const std::type_info* pTypeDescriptor; //TypeDescriptor of the complete class
struct RTTIClassHierarchyDescriptor<C, baseclasses...>* pClassDescriptor; //describes inheritance hierarchy
};
template<class C, class... baseclasses>
struct VirtualTable {
class Handle {
friend struct VirtualTable<C,baseclasses...>;
void** firstMethod;
Handle(void** firstMethod) :firstMethod(firstMethod){}
public:
VirtualTable<C, baseclasses...>& restore(){
VirtualTable<C, baseclasses...>* vt = (VirtualTable<C, baseclasses...>*)this;
return *vt;
}
};
static VirtualTable<C, baseclasses...>& nullVTable(){
static VirtualTable<C, baseclasses...> instance;
return instance;
}
static VirtualTable<C, baseclasses...>& getVTable(C& instance) {
fakeit::VirtualTable<C, baseclasses...>* vt = (fakeit::VirtualTable<C, baseclasses...>*)(&instance);
return *vt;
}
void copyFrom(VirtualTable<C, baseclasses...>& from) {
int size = VTUtils::getVTSize<C>();
firstMethod[-1] = from.firstMethod[-1]; // copy object locator
for (size_t i = 0; i < size; i++) {
firstMethod[i] = from.getMethod(i);
}
}
VirtualTable(): VirtualTable(buildVTArray()) {
}
void dispose() {
firstMethod--; // skip objectLocator
firstMethod--; // skip cookie
delete[] firstMethod;
}
void setMethod(unsigned int index, void *method) {
firstMethod[index] = method;
}
void * getMethod(unsigned int index) const {
return firstMethod[index];
}
unsigned int getSize() {
return VTUtils::getVTSize<C>();
}
void initAll(void* value){
auto size = getSize();
for (unsigned int i = 0; i < size; i++) {
setMethod(i, value);
}
}
void* getCookie(){
return firstMethod[-2];
}
void setCookie(void * value){
firstMethod[-2] = value;
}
Handle createHandle() {
Handle h(firstMethod);
return h;
}
private:
void** firstMethod;
class SimpleType {
};
static_assert(sizeof(unsigned int (SimpleType::*)()) == sizeof(unsigned int (C::*)()), "Can't mock a type with multiple inheritance");
static void ** buildVTArray(){
int size = VTUtils::getVTSize<C>();
auto array = new void*[size + 2] {};
RTTICompleteObjectLocator<C, baseclasses...> * objectLocator = new RTTICompleteObjectLocator<C, baseclasses...>(typeid(C));
array[1] = objectLocator; // initialize RTTICompleteObjectLocator pointer
array++; // skip cookie
array++; // skip object locator
return array;
}
VirtualTable(void** firstMethod) :firstMethod(firstMethod){
}
};
}
#endif /* VIRTUALTABLE_H_ */
<commit_msg>silence compilation warning.<commit_after>/*
* Copyright (c) 2014 Eran Pe'er.
*
* This program is made available under the terms of the MIT License.
*
* Created on Mar 10, 2014
*/
#ifndef VIRTUALTABLE_H_
#define VIRTUALTABLE_H_
#include "mockutils/VTUtils.hpp"
namespace fakeit {
typedef unsigned long DWORD;
struct TypeDescriptor {
TypeDescriptor() :
ptrToVTable(0), spare(0) {
// ptrToVTable should contain the pointer to the virtual table of the type type_info!!!
int ** tiVFTPtr = (int**) (&typeid(void));
int * i = (int*) tiVFTPtr[0];
int type_info_vft_ptr = (int) i;
ptrToVTable = type_info_vft_ptr;
}
DWORD ptrToVTable;
DWORD spare;
char name[8];
};
struct PMD {
/************************************************************************/
/* member displacement.
/* For a simple inheritance structure the member displacement is always 0.
/* since since the first member is placed at 0.
/* In the case of multiple inheritance, this value may have a positive value.
/************************************************************************/
int mdisp;
int pdisp; // vtable displacement
int vdisp; //displacement inside vtable
PMD() :
mdisp(0), pdisp(-1), vdisp(0) {
}
};
struct RTTIBaseClassDescriptor {
RTTIBaseClassDescriptor() :
pTypeDescriptor(nullptr), numContainedBases(0), attributes(0) {
}
const std::type_info* pTypeDescriptor; //type descriptor of the class
DWORD numContainedBases; //number of nested classes following in the Base Class Array
struct PMD where; //pointer-to-member displacement info
DWORD attributes; //flags, usually 0
};
template <typename C, typename... baseclasses>
struct RTTIClassHierarchyDescriptor {
RTTIClassHierarchyDescriptor() :
signature(0), attributes(0), numBaseClasses(0),pBaseClassArray(nullptr){
pBaseClassArray = new RTTIBaseClassDescriptor*[1 + sizeof...(baseclasses)];
addBaseClass<C, baseclasses...>();
}
~RTTIClassHierarchyDescriptor(){
for (int i = 0; i < 1 + sizeof...(baseclasses); i++){
RTTIBaseClassDescriptor * desc = pBaseClassArray[i];
delete desc;
}
delete[] pBaseClassArray;
}
DWORD signature; //always zero?
DWORD attributes; //bit 0 set = multiple inheritance, bit 1 set = virtual inheritance
DWORD numBaseClasses; //number of classes in pBaseClassArray
RTTIBaseClassDescriptor** pBaseClassArray;
template<typename BaseType>
void addBaseClass(){
static_assert(std::is_base_of<BaseType, C>::value, "C must be a derived class of BaseType");
RTTIBaseClassDescriptor* desc = new RTTIBaseClassDescriptor();
desc->pTypeDescriptor = &typeid(BaseType);
pBaseClassArray[numBaseClasses] = desc;
for (unsigned int i = 0; i < numBaseClasses; i++) {
pBaseClassArray[i]->numContainedBases++;
}
numBaseClasses++;
}
template<typename head,typename B1, typename... tail>
void addBaseClass(){
static_assert(std::is_base_of<B1, head>::value, "invalid inheritance list");
addBaseClass<head>();
addBaseClass<B1, tail...>();
}
};
template<typename C, typename... baseclasses>
struct RTTICompleteObjectLocator {
RTTICompleteObjectLocator(const std::type_info& info) :
signature(0), offset(0), cdOffset(0), pTypeDescriptor(&info), pClassDescriptor(new RTTIClassHierarchyDescriptor<C,baseclasses...>()) {
}
~RTTICompleteObjectLocator(){
delete pClassDescriptor;
}
DWORD signature; //always zero ?
DWORD offset; //offset of this vtable in the complete class
DWORD cdOffset; //constructor displacement offset
const std::type_info* pTypeDescriptor; //TypeDescriptor of the complete class
struct RTTIClassHierarchyDescriptor<C, baseclasses...>* pClassDescriptor; //describes inheritance hierarchy
};
template<class C, class... baseclasses>
struct VirtualTable {
class Handle {
friend struct VirtualTable<C,baseclasses...>;
void** firstMethod;
Handle(void** firstMethod) :firstMethod(firstMethod){}
public:
VirtualTable<C, baseclasses...>& restore(){
VirtualTable<C, baseclasses...>* vt = (VirtualTable<C, baseclasses...>*)this;
return *vt;
}
};
static VirtualTable<C, baseclasses...>& nullVTable(){
static VirtualTable<C, baseclasses...> instance;
return instance;
}
static VirtualTable<C, baseclasses...>& getVTable(C& instance) {
fakeit::VirtualTable<C, baseclasses...>* vt = (fakeit::VirtualTable<C, baseclasses...>*)(&instance);
return *vt;
}
void copyFrom(VirtualTable<C, baseclasses...>& from) {
unsigned int size = VTUtils::getVTSize<C>();
firstMethod[-1] = from.firstMethod[-1]; // copy object locator
for (unsigned int i = 0; i < size; i++) {
firstMethod[i] = from.getMethod(i);
}
}
VirtualTable(): VirtualTable(buildVTArray()) {
}
void dispose() {
firstMethod--; // skip objectLocator
firstMethod--; // skip cookie
delete[] firstMethod;
}
void setMethod(unsigned int index, void *method) {
firstMethod[index] = method;
}
void * getMethod(unsigned int index) const {
return firstMethod[index];
}
unsigned int getSize() {
return VTUtils::getVTSize<C>();
}
void initAll(void* value){
auto size = getSize();
for (unsigned int i = 0; i < size; i++) {
setMethod(i, value);
}
}
void* getCookie(){
return firstMethod[-2];
}
void setCookie(void * value){
firstMethod[-2] = value;
}
Handle createHandle() {
Handle h(firstMethod);
return h;
}
private:
void** firstMethod;
class SimpleType {
};
static_assert(sizeof(unsigned int (SimpleType::*)()) == sizeof(unsigned int (C::*)()), "Can't mock a type with multiple inheritance");
static void ** buildVTArray(){
int size = VTUtils::getVTSize<C>();
auto array = new void*[size + 2] {};
RTTICompleteObjectLocator<C, baseclasses...> * objectLocator = new RTTICompleteObjectLocator<C, baseclasses...>(typeid(C));
array[1] = objectLocator; // initialize RTTICompleteObjectLocator pointer
array++; // skip cookie
array++; // skip object locator
return array;
}
VirtualTable(void** firstMethod) :firstMethod(firstMethod){
}
};
}
#endif /* VIRTUALTABLE_H_ */
<|endoftext|>
|
<commit_before>/**
* @file llfloatermediasettings.cpp
* @brief Tabbed dialog for media settings - class implementation
*
* $LicenseInfo:firstyear=2002&license=viewergpl$
*
* Copyright (c) 2009, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llfloaterreg.h"
#include "llfloatermediasettings.h"
#include "llpanelmediasettingsgeneral.h"
#include "llpanelmediasettingssecurity.h"
#include "llpanelmediasettingspermissions.h"
#include "llviewercontrol.h"
#include "lluictrlfactory.h"
#include "llbutton.h"
#include "llselectmgr.h"
#include "llsdutil.h"
LLFloaterMediaSettings* LLFloaterMediaSettings::sInstance = NULL;
////////////////////////////////////////////////////////////////////////////////
//
LLFloaterMediaSettings::LLFloaterMediaSettings(const LLSD& key)
: LLFloater(key),
mTabContainer(NULL),
mPanelMediaSettingsGeneral(NULL),
mPanelMediaSettingsSecurity(NULL),
mPanelMediaSettingsPermissions(NULL),
mWaitingToClose( false ),
mIdenticalHasMediaInfo( true ),
mMultipleMedia(false),
mMultipleValidMedia(false)
{
}
////////////////////////////////////////////////////////////////////////////////
//
LLFloaterMediaSettings::~LLFloaterMediaSettings()
{
if ( mPanelMediaSettingsGeneral )
{
delete mPanelMediaSettingsGeneral;
mPanelMediaSettingsGeneral = NULL;
}
if ( mPanelMediaSettingsSecurity )
{
delete mPanelMediaSettingsSecurity;
mPanelMediaSettingsSecurity = NULL;
}
if ( mPanelMediaSettingsPermissions )
{
delete mPanelMediaSettingsPermissions;
mPanelMediaSettingsPermissions = NULL;
}
sInstance = NULL;
}
////////////////////////////////////////////////////////////////////////////////
//
BOOL LLFloaterMediaSettings::postBuild()
{
mApplyBtn = getChild<LLButton>("Apply");
mApplyBtn->setClickedCallback(onBtnApply, this);
mCancelBtn = getChild<LLButton>("Cancel");
mCancelBtn->setClickedCallback(onBtnCancel, this);
mOKBtn = getChild<LLButton>("OK");
mOKBtn->setClickedCallback(onBtnOK, this);
mTabContainer = getChild<LLTabContainer>( "tab_container" );
mPanelMediaSettingsGeneral = new LLPanelMediaSettingsGeneral();
mTabContainer->addTabPanel(
LLTabContainer::TabPanelParams().
panel(mPanelMediaSettingsGeneral));
mPanelMediaSettingsGeneral->setParent( this );
// note that "permissions" tab is really "Controls" tab - refs to 'perms' and
// 'permissions' not changed to 'controls' since we don't want to change
// shared files in server code and keeping everything the same seemed best.
mPanelMediaSettingsPermissions = new LLPanelMediaSettingsPermissions();
mTabContainer->addTabPanel(
LLTabContainer::TabPanelParams().
panel(mPanelMediaSettingsPermissions));
mPanelMediaSettingsSecurity = new LLPanelMediaSettingsSecurity();
mTabContainer->addTabPanel(
LLTabContainer::TabPanelParams().
panel(mPanelMediaSettingsSecurity));
mPanelMediaSettingsSecurity->setParent( this );
// restore the last tab viewed from persistance variable storage
if (!mTabContainer->selectTab(gSavedSettings.getS32("LastMediaSettingsTab")))
{
mTabContainer->selectFirstTab();
};
sInstance = this;
return TRUE;
}
//static
LLFloaterMediaSettings* LLFloaterMediaSettings::getInstance()
{
if ( !sInstance )
{
sInstance = (LLFloaterReg::getTypedInstance<LLFloaterMediaSettings>("media_settings"));
}
return sInstance;
}
//static
void LLFloaterMediaSettings::apply()
{
if (sInstance->haveValuesChanged())
{
LLSD settings;
sInstance->mPanelMediaSettingsGeneral->preApply();
sInstance->mPanelMediaSettingsGeneral->getValues( settings, false );
sInstance->mPanelMediaSettingsSecurity->preApply();
sInstance->mPanelMediaSettingsSecurity->getValues( settings, false );
sInstance->mPanelMediaSettingsPermissions->preApply();
sInstance->mPanelMediaSettingsPermissions->getValues( settings, false );
LLSelectMgr::getInstance()->selectionSetMedia( LLTextureEntry::MF_HAS_MEDIA, settings );
sInstance->mPanelMediaSettingsGeneral->postApply();
sInstance->mPanelMediaSettingsSecurity->postApply();
sInstance->mPanelMediaSettingsPermissions->postApply();
}
}
////////////////////////////////////////////////////////////////////////////////
void LLFloaterMediaSettings::onClose(bool app_quitting)
{
if(mPanelMediaSettingsGeneral)
{
mPanelMediaSettingsGeneral->onClose(app_quitting);
}
LLFloaterReg::hideInstance("whitelist_entry");
}
////////////////////////////////////////////////////////////////////////////////
//static
void LLFloaterMediaSettings::initValues( const LLSD& media_settings, bool editable )
{
if (sInstance->hasFocus()) return;
sInstance->clearValues(editable);
// update all panels with values from simulator
sInstance->mPanelMediaSettingsGeneral->
initValues( sInstance->mPanelMediaSettingsGeneral, media_settings, editable );
sInstance->mPanelMediaSettingsSecurity->
initValues( sInstance->mPanelMediaSettingsSecurity, media_settings, editable );
sInstance->mPanelMediaSettingsPermissions->
initValues( sInstance->mPanelMediaSettingsPermissions, media_settings, editable );
// Squirrel away initial values
sInstance->mInitialValues.clear();
sInstance->mPanelMediaSettingsGeneral->getValues( sInstance->mInitialValues );
sInstance->mPanelMediaSettingsSecurity->getValues( sInstance->mInitialValues );
sInstance->mPanelMediaSettingsPermissions->getValues( sInstance->mInitialValues );
sInstance->mApplyBtn->setEnabled(editable);
sInstance->mOKBtn->setEnabled(editable);
}
////////////////////////////////////////////////////////////////////////////////
//
void LLFloaterMediaSettings::commitFields()
{
if (hasFocus())
{
LLUICtrl* cur_focus = dynamic_cast<LLUICtrl*>(gFocusMgr.getKeyboardFocus());
if (cur_focus->acceptsTextInput())
{
cur_focus->onCommit();
};
};
}
////////////////////////////////////////////////////////////////////////////////
//static
void LLFloaterMediaSettings::clearValues( bool editable)
{
// clean up all panels before updating
sInstance->mPanelMediaSettingsGeneral ->clearValues(sInstance->mPanelMediaSettingsGeneral, editable);
sInstance->mPanelMediaSettingsSecurity ->clearValues(sInstance->mPanelMediaSettingsSecurity, editable);
sInstance->mPanelMediaSettingsPermissions->clearValues(sInstance->mPanelMediaSettingsPermissions, editable);
}
////////////////////////////////////////////////////////////////////////////////
// static
void LLFloaterMediaSettings::onBtnOK( void* userdata )
{
sInstance->commitFields();
sInstance->apply();
sInstance->closeFloater();
}
////////////////////////////////////////////////////////////////////////////////
// static
void LLFloaterMediaSettings::onBtnApply( void* userdata )
{
sInstance->commitFields();
sInstance->apply();
}
////////////////////////////////////////////////////////////////////////////////
// static
void LLFloaterMediaSettings::onBtnCancel( void* userdata )
{
sInstance->closeFloater();
}
////////////////////////////////////////////////////////////////////////////////
// static
void LLFloaterMediaSettings::onTabChanged(void* user_data, bool from_click)
{
LLTabContainer* self = (LLTabContainer*)user_data;
gSavedSettings.setS32("LastMediaSettingsTab", self->getCurrentPanelIndex());
}
////////////////////////////////////////////////////////////////////////////////
//
const std::string LLFloaterMediaSettings::getHomeUrl()
{
if ( mPanelMediaSettingsGeneral )
return mPanelMediaSettingsGeneral->getHomeUrl();
else
return std::string( "" );
}
////////////////////////////////////////////////////////////////////////////////
// virtual
void LLFloaterMediaSettings::draw()
{
if (NULL != mApplyBtn)
{
// Set the enabled state of the "Apply" button if values changed
mApplyBtn->setEnabled( haveValuesChanged() );
}
LLFloater::draw();
}
//private
bool LLFloaterMediaSettings::haveValuesChanged() const
{
bool values_changed = false;
// *NOTE: The code below is very inefficient. Better to do this
// only when data change.
// Every frame, check to see what the values are. If they are not
// the same as the initial media data, enable the OK/Apply buttons
LLSD settings;
sInstance->mPanelMediaSettingsGeneral->getValues( settings );
sInstance->mPanelMediaSettingsSecurity->getValues( settings );
sInstance->mPanelMediaSettingsPermissions->getValues( settings );
LLSD::map_const_iterator iter = settings.beginMap();
LLSD::map_const_iterator end = settings.endMap();
for ( ; iter != end; ++iter )
{
const std::string ¤t_key = iter->first;
const LLSD ¤t_value = iter->second;
if ( ! llsd_equals(current_value, mInitialValues[current_key]))
{
values_changed = true;
break;
}
}
return values_changed;
}
<commit_msg>CID-95<commit_after>/**
* @file llfloatermediasettings.cpp
* @brief Tabbed dialog for media settings - class implementation
*
* $LicenseInfo:firstyear=2002&license=viewergpl$
*
* Copyright (c) 2009, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llfloaterreg.h"
#include "llfloatermediasettings.h"
#include "llpanelmediasettingsgeneral.h"
#include "llpanelmediasettingssecurity.h"
#include "llpanelmediasettingspermissions.h"
#include "llviewercontrol.h"
#include "lluictrlfactory.h"
#include "llbutton.h"
#include "llselectmgr.h"
#include "llsdutil.h"
LLFloaterMediaSettings* LLFloaterMediaSettings::sInstance = NULL;
////////////////////////////////////////////////////////////////////////////////
//
LLFloaterMediaSettings::LLFloaterMediaSettings(const LLSD& key)
: LLFloater(key),
mTabContainer(NULL),
mPanelMediaSettingsGeneral(NULL),
mPanelMediaSettingsSecurity(NULL),
mPanelMediaSettingsPermissions(NULL),
mWaitingToClose( false ),
mIdenticalHasMediaInfo( true ),
mMultipleMedia(false),
mMultipleValidMedia(false)
{
}
////////////////////////////////////////////////////////////////////////////////
//
LLFloaterMediaSettings::~LLFloaterMediaSettings()
{
if ( mPanelMediaSettingsGeneral )
{
delete mPanelMediaSettingsGeneral;
mPanelMediaSettingsGeneral = NULL;
}
if ( mPanelMediaSettingsSecurity )
{
delete mPanelMediaSettingsSecurity;
mPanelMediaSettingsSecurity = NULL;
}
if ( mPanelMediaSettingsPermissions )
{
delete mPanelMediaSettingsPermissions;
mPanelMediaSettingsPermissions = NULL;
}
sInstance = NULL;
}
////////////////////////////////////////////////////////////////////////////////
//
BOOL LLFloaterMediaSettings::postBuild()
{
mApplyBtn = getChild<LLButton>("Apply");
mApplyBtn->setClickedCallback(onBtnApply, this);
mCancelBtn = getChild<LLButton>("Cancel");
mCancelBtn->setClickedCallback(onBtnCancel, this);
mOKBtn = getChild<LLButton>("OK");
mOKBtn->setClickedCallback(onBtnOK, this);
mTabContainer = getChild<LLTabContainer>( "tab_container" );
mPanelMediaSettingsGeneral = new LLPanelMediaSettingsGeneral();
mTabContainer->addTabPanel(
LLTabContainer::TabPanelParams().
panel(mPanelMediaSettingsGeneral));
mPanelMediaSettingsGeneral->setParent( this );
// note that "permissions" tab is really "Controls" tab - refs to 'perms' and
// 'permissions' not changed to 'controls' since we don't want to change
// shared files in server code and keeping everything the same seemed best.
mPanelMediaSettingsPermissions = new LLPanelMediaSettingsPermissions();
mTabContainer->addTabPanel(
LLTabContainer::TabPanelParams().
panel(mPanelMediaSettingsPermissions));
mPanelMediaSettingsSecurity = new LLPanelMediaSettingsSecurity();
mTabContainer->addTabPanel(
LLTabContainer::TabPanelParams().
panel(mPanelMediaSettingsSecurity));
mPanelMediaSettingsSecurity->setParent( this );
// restore the last tab viewed from persistance variable storage
if (!mTabContainer->selectTab(gSavedSettings.getS32("LastMediaSettingsTab")))
{
mTabContainer->selectFirstTab();
};
sInstance = this;
return TRUE;
}
//static
LLFloaterMediaSettings* LLFloaterMediaSettings::getInstance()
{
if ( !sInstance )
{
sInstance = (LLFloaterReg::getTypedInstance<LLFloaterMediaSettings>("media_settings"));
}
return sInstance;
}
//static
void LLFloaterMediaSettings::apply()
{
if (sInstance->haveValuesChanged())
{
LLSD settings;
sInstance->mPanelMediaSettingsGeneral->preApply();
sInstance->mPanelMediaSettingsGeneral->getValues( settings, false );
sInstance->mPanelMediaSettingsSecurity->preApply();
sInstance->mPanelMediaSettingsSecurity->getValues( settings, false );
sInstance->mPanelMediaSettingsPermissions->preApply();
sInstance->mPanelMediaSettingsPermissions->getValues( settings, false );
LLSelectMgr::getInstance()->selectionSetMedia( LLTextureEntry::MF_HAS_MEDIA, settings );
sInstance->mPanelMediaSettingsGeneral->postApply();
sInstance->mPanelMediaSettingsSecurity->postApply();
sInstance->mPanelMediaSettingsPermissions->postApply();
}
}
////////////////////////////////////////////////////////////////////////////////
void LLFloaterMediaSettings::onClose(bool app_quitting)
{
if(mPanelMediaSettingsGeneral)
{
mPanelMediaSettingsGeneral->onClose(app_quitting);
}
LLFloaterReg::hideInstance("whitelist_entry");
}
////////////////////////////////////////////////////////////////////////////////
//static
void LLFloaterMediaSettings::initValues( const LLSD& media_settings, bool editable )
{
if (sInstance->hasFocus()) return;
sInstance->clearValues(editable);
// update all panels with values from simulator
sInstance->mPanelMediaSettingsGeneral->
initValues( sInstance->mPanelMediaSettingsGeneral, media_settings, editable );
sInstance->mPanelMediaSettingsSecurity->
initValues( sInstance->mPanelMediaSettingsSecurity, media_settings, editable );
sInstance->mPanelMediaSettingsPermissions->
initValues( sInstance->mPanelMediaSettingsPermissions, media_settings, editable );
// Squirrel away initial values
sInstance->mInitialValues.clear();
sInstance->mPanelMediaSettingsGeneral->getValues( sInstance->mInitialValues );
sInstance->mPanelMediaSettingsSecurity->getValues( sInstance->mInitialValues );
sInstance->mPanelMediaSettingsPermissions->getValues( sInstance->mInitialValues );
sInstance->mApplyBtn->setEnabled(editable);
sInstance->mOKBtn->setEnabled(editable);
}
////////////////////////////////////////////////////////////////////////////////
//
void LLFloaterMediaSettings::commitFields()
{
if (hasFocus())
{
LLUICtrl* cur_focus = dynamic_cast<LLUICtrl*>(gFocusMgr.getKeyboardFocus());
if (cur_focus && cur_focus->acceptsTextInput())
{
cur_focus->onCommit();
};
};
}
////////////////////////////////////////////////////////////////////////////////
//static
void LLFloaterMediaSettings::clearValues( bool editable)
{
// clean up all panels before updating
sInstance->mPanelMediaSettingsGeneral ->clearValues(sInstance->mPanelMediaSettingsGeneral, editable);
sInstance->mPanelMediaSettingsSecurity ->clearValues(sInstance->mPanelMediaSettingsSecurity, editable);
sInstance->mPanelMediaSettingsPermissions->clearValues(sInstance->mPanelMediaSettingsPermissions, editable);
}
////////////////////////////////////////////////////////////////////////////////
// static
void LLFloaterMediaSettings::onBtnOK( void* userdata )
{
sInstance->commitFields();
sInstance->apply();
sInstance->closeFloater();
}
////////////////////////////////////////////////////////////////////////////////
// static
void LLFloaterMediaSettings::onBtnApply( void* userdata )
{
sInstance->commitFields();
sInstance->apply();
}
////////////////////////////////////////////////////////////////////////////////
// static
void LLFloaterMediaSettings::onBtnCancel( void* userdata )
{
sInstance->closeFloater();
}
////////////////////////////////////////////////////////////////////////////////
// static
void LLFloaterMediaSettings::onTabChanged(void* user_data, bool from_click)
{
LLTabContainer* self = (LLTabContainer*)user_data;
gSavedSettings.setS32("LastMediaSettingsTab", self->getCurrentPanelIndex());
}
////////////////////////////////////////////////////////////////////////////////
//
const std::string LLFloaterMediaSettings::getHomeUrl()
{
if ( mPanelMediaSettingsGeneral )
return mPanelMediaSettingsGeneral->getHomeUrl();
else
return std::string( "" );
}
////////////////////////////////////////////////////////////////////////////////
// virtual
void LLFloaterMediaSettings::draw()
{
if (NULL != mApplyBtn)
{
// Set the enabled state of the "Apply" button if values changed
mApplyBtn->setEnabled( haveValuesChanged() );
}
LLFloater::draw();
}
//private
bool LLFloaterMediaSettings::haveValuesChanged() const
{
bool values_changed = false;
// *NOTE: The code below is very inefficient. Better to do this
// only when data change.
// Every frame, check to see what the values are. If they are not
// the same as the initial media data, enable the OK/Apply buttons
LLSD settings;
sInstance->mPanelMediaSettingsGeneral->getValues( settings );
sInstance->mPanelMediaSettingsSecurity->getValues( settings );
sInstance->mPanelMediaSettingsPermissions->getValues( settings );
LLSD::map_const_iterator iter = settings.beginMap();
LLSD::map_const_iterator end = settings.endMap();
for ( ; iter != end; ++iter )
{
const std::string ¤t_key = iter->first;
const LLSD ¤t_value = iter->second;
if ( ! llsd_equals(current_value, mInitialValues[current_key]))
{
values_changed = true;
break;
}
}
return values_changed;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/electron_download_manager_delegate.h"
#include <string>
#include <utility>
#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/task/post_task.h"
#include "chrome/common/pref_names.h"
#include "components/download/public/common/download_danger_type.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/download_item_utils.h"
#include "content/public/browser/download_manager.h"
#include "net/base/filename_util.h"
#include "shell/browser/api/electron_api_download_item.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/native_window.h"
#include "shell/browser/ui/file_dialog.h"
#include "shell/browser/web_contents_preferences.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/options_switches.h"
namespace electron {
namespace {
// Generate default file path to save the download.
base::FilePath CreateDownloadPath(const GURL& url,
const std::string& content_disposition,
const std::string& suggested_filename,
const std::string& mime_type,
const base::FilePath& default_download_path) {
auto generated_name =
net::GenerateFileName(url, content_disposition, std::string(),
suggested_filename, mime_type, "download");
if (!base::PathExists(default_download_path))
base::CreateDirectory(default_download_path);
return default_download_path.Append(generated_name);
}
} // namespace
ElectronDownloadManagerDelegate::ElectronDownloadManagerDelegate(
content::DownloadManager* manager)
: download_manager_(manager), weak_ptr_factory_(this) {}
ElectronDownloadManagerDelegate::~ElectronDownloadManagerDelegate() {
if (download_manager_) {
DCHECK_EQ(static_cast<content::DownloadManagerDelegate*>(this),
download_manager_->GetDelegate());
download_manager_->SetDelegate(nullptr);
download_manager_ = nullptr;
}
}
void ElectronDownloadManagerDelegate::GetItemSavePath(
download::DownloadItem* item,
base::FilePath* path) {
api::DownloadItem* download = api::DownloadItem::FromDownloadItem(item);
if (download)
*path = download->GetSavePath();
}
void ElectronDownloadManagerDelegate::GetItemSaveDialogOptions(
download::DownloadItem* item,
file_dialog::DialogSettings* options) {
api::DownloadItem* download = api::DownloadItem::FromDownloadItem(item);
if (download)
*options = download->GetSaveDialogOptions();
}
void ElectronDownloadManagerDelegate::OnDownloadPathGenerated(
uint32_t download_id,
content::DownloadTargetCallback callback,
const base::FilePath& default_path) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
base::ThreadRestrictions::ScopedAllowIO allow_io;
auto* item = download_manager_->GetDownload(download_id);
if (!item)
return;
NativeWindow* window = nullptr;
content::WebContents* web_contents =
content::DownloadItemUtils::GetWebContents(item);
auto* relay =
web_contents ? NativeWindowRelay::FromWebContents(web_contents) : nullptr;
if (relay)
window = relay->GetNativeWindow();
// Show save dialog if save path was not set already on item
base::FilePath path;
GetItemSavePath(item, &path);
if (path.empty()) {
file_dialog::DialogSettings settings;
GetItemSaveDialogOptions(item, &settings);
if (!settings.parent_window)
settings.parent_window = window;
if (settings.title.size() == 0)
settings.title = item->GetURL().spec();
if (settings.default_path.empty())
settings.default_path = default_path;
auto* web_preferences = WebContentsPreferences::From(web_contents);
const bool offscreen =
!web_preferences || web_preferences->IsEnabled(options::kOffscreen);
settings.force_detached = offscreen;
v8::Isolate* isolate = v8::Isolate::GetCurrent();
gin_helper::Promise<gin_helper::Dictionary> dialog_promise(isolate);
auto dialog_callback = base::BindOnce(
&ElectronDownloadManagerDelegate::OnDownloadSaveDialogDone,
base::Unretained(this), download_id, std::move(callback));
ignore_result(dialog_promise.Then(std::move(dialog_callback)));
file_dialog::ShowSaveDialog(settings, std::move(dialog_promise));
} else {
std::move(callback).Run(path,
download::DownloadItem::TARGET_DISPOSITION_PROMPT,
download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
item->GetMixedContentStatus(), path,
download::DOWNLOAD_INTERRUPT_REASON_NONE);
}
}
void ElectronDownloadManagerDelegate::OnDownloadSaveDialogDone(
uint32_t download_id,
content::DownloadTargetCallback download_callback,
gin_helper::Dictionary result) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
auto* item = download_manager_->GetDownload(download_id);
if (!item)
return;
bool canceled = true;
result.Get("canceled", &canceled);
base::FilePath path;
if (!canceled) {
if (result.Get("filePath", &path)) {
// Remember the last selected download directory.
ElectronBrowserContext* browser_context =
static_cast<ElectronBrowserContext*>(
download_manager_->GetBrowserContext());
browser_context->prefs()->SetFilePath(prefs::kDownloadDefaultDirectory,
path.DirName());
api::DownloadItem* download = api::DownloadItem::FromDownloadItem(item);
if (download)
download->SetSavePath(path);
}
}
// Running the DownloadTargetCallback with an empty FilePath signals that the
// download should be cancelled. If user cancels the file save dialog, run
// the callback with empty FilePath.
const auto interrupt_reason =
path.empty() ? download::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED
: download::DOWNLOAD_INTERRUPT_REASON_NONE;
std::move(download_callback)
.Run(path, download::DownloadItem::TARGET_DISPOSITION_PROMPT,
download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
item->GetMixedContentStatus(), path, interrupt_reason);
}
void ElectronDownloadManagerDelegate::Shutdown() {
weak_ptr_factory_.InvalidateWeakPtrs();
download_manager_ = nullptr;
}
bool ElectronDownloadManagerDelegate::DetermineDownloadTarget(
download::DownloadItem* download,
content::DownloadTargetCallback* callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!download->GetForcedFilePath().empty()) {
std::move(*callback).Run(
download->GetForcedFilePath(),
download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
download::DownloadItem::MixedContentStatus::UNKNOWN,
download->GetForcedFilePath(),
download::DOWNLOAD_INTERRUPT_REASON_NONE);
return true;
}
// Try to get the save path from JS wrapper.
base::FilePath save_path;
GetItemSavePath(download, &save_path);
if (!save_path.empty()) {
std::move(*callback).Run(
save_path, download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
download::DownloadItem::MixedContentStatus::UNKNOWN, save_path,
download::DOWNLOAD_INTERRUPT_REASON_NONE);
return true;
}
ElectronBrowserContext* browser_context =
static_cast<ElectronBrowserContext*>(
download_manager_->GetBrowserContext());
base::FilePath default_download_path =
browser_context->prefs()->GetFilePath(prefs::kDownloadDefaultDirectory);
base::ThreadPool::PostTaskAndReplyWithResult(
FROM_HERE,
{base::MayBlock(), base::TaskPriority::BEST_EFFORT,
base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN},
base::BindOnce(&CreateDownloadPath, download->GetURL(),
download->GetContentDisposition(),
download->GetSuggestedFilename(), download->GetMimeType(),
default_download_path),
base::BindOnce(&ElectronDownloadManagerDelegate::OnDownloadPathGenerated,
weak_ptr_factory_.GetWeakPtr(), download->GetId(),
std::move(*callback)));
return true;
}
bool ElectronDownloadManagerDelegate::ShouldOpenDownload(
download::DownloadItem* download,
content::DownloadOpenDelayedCallback callback) {
return true;
}
void ElectronDownloadManagerDelegate::GetNextId(
content::DownloadIdCallback callback) {
static uint32_t next_id = download::DownloadItem::kInvalidId + 1;
std::move(callback).Run(next_id++);
}
} // namespace electron
<commit_msg>fix: missing HandleScope in OnDownloadPathGenerated (#23005)<commit_after>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/electron_download_manager_delegate.h"
#include <string>
#include <utility>
#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/task/post_task.h"
#include "chrome/common/pref_names.h"
#include "components/download/public/common/download_danger_type.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/download_item_utils.h"
#include "content/public/browser/download_manager.h"
#include "net/base/filename_util.h"
#include "shell/browser/api/electron_api_download_item.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/native_window.h"
#include "shell/browser/ui/file_dialog.h"
#include "shell/browser/web_contents_preferences.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/options_switches.h"
namespace electron {
namespace {
// Generate default file path to save the download.
base::FilePath CreateDownloadPath(const GURL& url,
const std::string& content_disposition,
const std::string& suggested_filename,
const std::string& mime_type,
const base::FilePath& default_download_path) {
auto generated_name =
net::GenerateFileName(url, content_disposition, std::string(),
suggested_filename, mime_type, "download");
if (!base::PathExists(default_download_path))
base::CreateDirectory(default_download_path);
return default_download_path.Append(generated_name);
}
} // namespace
ElectronDownloadManagerDelegate::ElectronDownloadManagerDelegate(
content::DownloadManager* manager)
: download_manager_(manager), weak_ptr_factory_(this) {}
ElectronDownloadManagerDelegate::~ElectronDownloadManagerDelegate() {
if (download_manager_) {
DCHECK_EQ(static_cast<content::DownloadManagerDelegate*>(this),
download_manager_->GetDelegate());
download_manager_->SetDelegate(nullptr);
download_manager_ = nullptr;
}
}
void ElectronDownloadManagerDelegate::GetItemSavePath(
download::DownloadItem* item,
base::FilePath* path) {
api::DownloadItem* download = api::DownloadItem::FromDownloadItem(item);
if (download)
*path = download->GetSavePath();
}
void ElectronDownloadManagerDelegate::GetItemSaveDialogOptions(
download::DownloadItem* item,
file_dialog::DialogSettings* options) {
api::DownloadItem* download = api::DownloadItem::FromDownloadItem(item);
if (download)
*options = download->GetSaveDialogOptions();
}
void ElectronDownloadManagerDelegate::OnDownloadPathGenerated(
uint32_t download_id,
content::DownloadTargetCallback callback,
const base::FilePath& default_path) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
base::ThreadRestrictions::ScopedAllowIO allow_io;
auto* item = download_manager_->GetDownload(download_id);
if (!item)
return;
NativeWindow* window = nullptr;
content::WebContents* web_contents =
content::DownloadItemUtils::GetWebContents(item);
auto* relay =
web_contents ? NativeWindowRelay::FromWebContents(web_contents) : nullptr;
if (relay)
window = relay->GetNativeWindow();
// Show save dialog if save path was not set already on item
base::FilePath path;
GetItemSavePath(item, &path);
if (path.empty()) {
file_dialog::DialogSettings settings;
GetItemSaveDialogOptions(item, &settings);
if (!settings.parent_window)
settings.parent_window = window;
if (settings.title.size() == 0)
settings.title = item->GetURL().spec();
if (settings.default_path.empty())
settings.default_path = default_path;
auto* web_preferences = WebContentsPreferences::From(web_contents);
const bool offscreen =
!web_preferences || web_preferences->IsEnabled(options::kOffscreen);
settings.force_detached = offscreen;
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
gin_helper::Promise<gin_helper::Dictionary> dialog_promise(isolate);
auto dialog_callback = base::BindOnce(
&ElectronDownloadManagerDelegate::OnDownloadSaveDialogDone,
base::Unretained(this), download_id, std::move(callback));
ignore_result(dialog_promise.Then(std::move(dialog_callback)));
file_dialog::ShowSaveDialog(settings, std::move(dialog_promise));
} else {
std::move(callback).Run(path,
download::DownloadItem::TARGET_DISPOSITION_PROMPT,
download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
item->GetMixedContentStatus(), path,
download::DOWNLOAD_INTERRUPT_REASON_NONE);
}
}
void ElectronDownloadManagerDelegate::OnDownloadSaveDialogDone(
uint32_t download_id,
content::DownloadTargetCallback download_callback,
gin_helper::Dictionary result) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
auto* item = download_manager_->GetDownload(download_id);
if (!item)
return;
bool canceled = true;
result.Get("canceled", &canceled);
base::FilePath path;
if (!canceled) {
if (result.Get("filePath", &path)) {
// Remember the last selected download directory.
ElectronBrowserContext* browser_context =
static_cast<ElectronBrowserContext*>(
download_manager_->GetBrowserContext());
browser_context->prefs()->SetFilePath(prefs::kDownloadDefaultDirectory,
path.DirName());
api::DownloadItem* download = api::DownloadItem::FromDownloadItem(item);
if (download)
download->SetSavePath(path);
}
}
// Running the DownloadTargetCallback with an empty FilePath signals that the
// download should be cancelled. If user cancels the file save dialog, run
// the callback with empty FilePath.
const auto interrupt_reason =
path.empty() ? download::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED
: download::DOWNLOAD_INTERRUPT_REASON_NONE;
std::move(download_callback)
.Run(path, download::DownloadItem::TARGET_DISPOSITION_PROMPT,
download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
item->GetMixedContentStatus(), path, interrupt_reason);
}
void ElectronDownloadManagerDelegate::Shutdown() {
weak_ptr_factory_.InvalidateWeakPtrs();
download_manager_ = nullptr;
}
bool ElectronDownloadManagerDelegate::DetermineDownloadTarget(
download::DownloadItem* download,
content::DownloadTargetCallback* callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!download->GetForcedFilePath().empty()) {
std::move(*callback).Run(
download->GetForcedFilePath(),
download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
download::DownloadItem::MixedContentStatus::UNKNOWN,
download->GetForcedFilePath(),
download::DOWNLOAD_INTERRUPT_REASON_NONE);
return true;
}
// Try to get the save path from JS wrapper.
base::FilePath save_path;
GetItemSavePath(download, &save_path);
if (!save_path.empty()) {
std::move(*callback).Run(
save_path, download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
download::DownloadItem::MixedContentStatus::UNKNOWN, save_path,
download::DOWNLOAD_INTERRUPT_REASON_NONE);
return true;
}
ElectronBrowserContext* browser_context =
static_cast<ElectronBrowserContext*>(
download_manager_->GetBrowserContext());
base::FilePath default_download_path =
browser_context->prefs()->GetFilePath(prefs::kDownloadDefaultDirectory);
base::ThreadPool::PostTaskAndReplyWithResult(
FROM_HERE,
{base::MayBlock(), base::TaskPriority::BEST_EFFORT,
base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN},
base::BindOnce(&CreateDownloadPath, download->GetURL(),
download->GetContentDisposition(),
download->GetSuggestedFilename(), download->GetMimeType(),
default_download_path),
base::BindOnce(&ElectronDownloadManagerDelegate::OnDownloadPathGenerated,
weak_ptr_factory_.GetWeakPtr(), download->GetId(),
std::move(*callback)));
return true;
}
bool ElectronDownloadManagerDelegate::ShouldOpenDownload(
download::DownloadItem* download,
content::DownloadOpenDelayedCallback callback) {
return true;
}
void ElectronDownloadManagerDelegate::GetNextId(
content::DownloadIdCallback callback) {
static uint32_t next_id = download::DownloadItem::kInvalidId + 1;
std::move(callback).Run(next_id++);
}
} // namespace electron
<|endoftext|>
|
<commit_before>#include "FilterUnion.hpp"
namespace org_pqrs_KeyRemap4MacBook {
namespace RemapFilter {
FilterUnion::FilterUnion(const unsigned int* vec, size_t length)
{
initialize(vec, length);
}
FilterUnion::~FilterUnion(void)
{
terminate();
}
void
FilterUnion::initialize(const unsigned int* vec, size_t length)
{
type_ = BRIDGE_FILTERTYPE_NONE;
// ------------------------------------------------------------
// check parameters.
//
if (! vec || length <= 0) {
IOLOG_ERROR("FilterUnion::FilterUnion invalid parameter.\n");
goto error;
}
// ------------------------------------------------------------
// initialize values.
//
type_ = vec[0];
switch (type_) {
case BRIDGE_FILTERTYPE_APPLICATION_NOT:
case BRIDGE_FILTERTYPE_APPLICATION_ONLY:
p_.applicationFilter = new ApplicationFilter(type_);
if (p_.applicationFilter) {
for (size_t i = 1; i < length; ++i) {
(p_.applicationFilter)->add(vec[i]);
}
}
break;
case BRIDGE_FILTERTYPE_CONFIG_NOT:
case BRIDGE_FILTERTYPE_CONFIG_ONLY:
p_.configFilter = new ConfigFilter(type_);
if (p_.configFilter) {
for (size_t i = 1; i < length; ++i) {
(p_.configFilter)->add(vec[i]);
}
}
break;
case BRIDGE_FILTERTYPE_DEVICE_NOT:
case BRIDGE_FILTERTYPE_DEVICE_ONLY:
p_.deviceFilter = new DeviceFilter(type_);
if (p_.deviceFilter) {
for (size_t i = 1; i < length - 1; i += 2) {
(p_.deviceFilter)->add(vec[i], vec[i + 1]);
}
}
break;
case BRIDGE_FILTERTYPE_INPUTMODE_NOT:
case BRIDGE_FILTERTYPE_INPUTMODE_ONLY:
case BRIDGE_FILTERTYPE_INPUTMODEDETAIL_NOT:
case BRIDGE_FILTERTYPE_INPUTMODEDETAIL_ONLY:
p_.inputModeFilter = new InputModeFilter(type_);
if (p_.inputModeFilter) {
for (size_t i = 1; i < length; ++i) {
(p_.inputModeFilter)->add(vec[i]);
}
}
break;
}
error:
terminate();
}
void
FilterUnion::terminate(void)
{
switch (type_) {
case BRIDGE_FILTERTYPE_APPLICATION_NOT:
case BRIDGE_FILTERTYPE_APPLICATION_ONLY:
if (p_.applicationFilter) {
delete p_.applicationFilter;
}
break;
case BRIDGE_FILTERTYPE_CONFIG_NOT:
case BRIDGE_FILTERTYPE_CONFIG_ONLY:
if (p_.configFilter) {
delete p_.configFilter;
}
break;
case BRIDGE_FILTERTYPE_DEVICE_NOT:
case BRIDGE_FILTERTYPE_DEVICE_ONLY:
if (p_.deviceFilter) {
delete p_.deviceFilter;
}
break;
case BRIDGE_FILTERTYPE_INPUTMODE_NOT:
case BRIDGE_FILTERTYPE_INPUTMODE_ONLY:
case BRIDGE_FILTERTYPE_INPUTMODEDETAIL_NOT:
case BRIDGE_FILTERTYPE_INPUTMODEDETAIL_ONLY:
if (p_.inputModeFilter) {
delete p_.inputModeFilter;
}
break;
}
}
bool
FilterUnion::isblocked(void)
{
return false;
}
}
}
<commit_msg>update kext/FilterUnion<commit_after>#include "FilterUnion.hpp"
namespace org_pqrs_KeyRemap4MacBook {
namespace RemapFilter {
FilterUnion::FilterUnion(const unsigned int* vec, size_t length)
{
initialize(vec, length);
}
FilterUnion::~FilterUnion(void)
{
terminate();
}
void
FilterUnion::initialize(const unsigned int* vec, size_t length)
{
type_ = BRIDGE_FILTERTYPE_NONE;
// ------------------------------------------------------------
// check parameters.
//
if (! vec || length <= 0) {
IOLOG_ERROR("FilterUnion::FilterUnion invalid parameter.\n");
goto error;
}
// ------------------------------------------------------------
// initialize values.
//
type_ = vec[0];
switch (type_) {
case BRIDGE_FILTERTYPE_APPLICATION_NOT:
case BRIDGE_FILTERTYPE_APPLICATION_ONLY:
p_.applicationFilter = new ApplicationFilter(type_);
if (p_.applicationFilter) {
for (size_t i = 1; i < length; ++i) {
(p_.applicationFilter)->add(vec[i]);
}
}
break;
case BRIDGE_FILTERTYPE_CONFIG_NOT:
case BRIDGE_FILTERTYPE_CONFIG_ONLY:
p_.configFilter = new ConfigFilter(type_);
if (p_.configFilter) {
for (size_t i = 1; i < length; ++i) {
(p_.configFilter)->add(vec[i]);
}
}
break;
case BRIDGE_FILTERTYPE_DEVICE_NOT:
case BRIDGE_FILTERTYPE_DEVICE_ONLY:
p_.deviceFilter = new DeviceFilter(type_);
if (p_.deviceFilter) {
for (size_t i = 1; i < length - 1; i += 2) {
(p_.deviceFilter)->add(vec[i], vec[i + 1]);
}
}
break;
case BRIDGE_FILTERTYPE_INPUTMODE_NOT:
case BRIDGE_FILTERTYPE_INPUTMODE_ONLY:
case BRIDGE_FILTERTYPE_INPUTMODEDETAIL_NOT:
case BRIDGE_FILTERTYPE_INPUTMODEDETAIL_ONLY:
p_.inputModeFilter = new InputModeFilter(type_);
if (p_.inputModeFilter) {
for (size_t i = 1; i < length; ++i) {
(p_.inputModeFilter)->add(vec[i]);
}
}
break;
}
error:
terminate();
}
void
FilterUnion::terminate(void)
{
switch (type_) {
case BRIDGE_FILTERTYPE_APPLICATION_NOT:
case BRIDGE_FILTERTYPE_APPLICATION_ONLY:
if (p_.applicationFilter) {
delete p_.applicationFilter;
}
break;
case BRIDGE_FILTERTYPE_CONFIG_NOT:
case BRIDGE_FILTERTYPE_CONFIG_ONLY:
if (p_.configFilter) {
delete p_.configFilter;
}
break;
case BRIDGE_FILTERTYPE_DEVICE_NOT:
case BRIDGE_FILTERTYPE_DEVICE_ONLY:
if (p_.deviceFilter) {
delete p_.deviceFilter;
}
break;
case BRIDGE_FILTERTYPE_INPUTMODE_NOT:
case BRIDGE_FILTERTYPE_INPUTMODE_ONLY:
case BRIDGE_FILTERTYPE_INPUTMODEDETAIL_NOT:
case BRIDGE_FILTERTYPE_INPUTMODEDETAIL_ONLY:
if (p_.inputModeFilter) {
delete p_.inputModeFilter;
}
break;
}
type_ = BRIDGE_FILTERTYPE_NONE;
}
bool
FilterUnion::isblocked(void)
{
switch (type_) {
case BRIDGE_FILTERTYPE_APPLICATION_NOT:
case BRIDGE_FILTERTYPE_APPLICATION_ONLY:
if (p_.applicationFilter) {
return (p_.applicationFilter)->isblocked();
}
break;
case BRIDGE_FILTERTYPE_CONFIG_NOT:
case BRIDGE_FILTERTYPE_CONFIG_ONLY:
if (p_.configFilter) {
return (p_.configFilter)->isblocked();
}
break;
case BRIDGE_FILTERTYPE_DEVICE_NOT:
case BRIDGE_FILTERTYPE_DEVICE_ONLY:
if (p_.deviceFilter) {
return (p_.deviceFilter)->isblocked();
}
break;
case BRIDGE_FILTERTYPE_INPUTMODE_NOT:
case BRIDGE_FILTERTYPE_INPUTMODE_ONLY:
case BRIDGE_FILTERTYPE_INPUTMODEDETAIL_NOT:
case BRIDGE_FILTERTYPE_INPUTMODEDETAIL_ONLY:
if (p_.inputModeFilter) {
return (p_.inputModeFilter)->isblocked();
}
break;
}
return false;
}
}
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the 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 qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qplatformdefs.h"
#include "qsharedmemory.h"
#include "qsharedmemory_p.h"
#include "qsystemsemaphore.h"
#include <qdir.h>
#include <qdebug.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "private/qcore_unix_p.h"
#ifndef QT_NO_SHAREDMEMORY
QT_BEGIN_NAMESPACE
QSharedMemoryPrivate::QSharedMemoryPrivate()
: QObjectPrivate(), memory(0), size(0), error(QSharedMemory::NoError),
#ifndef QT_NO_SYSTEMSEMAPHORE
systemSemaphore(QString()), lockedByMe(false),
#endif
unix_key(0)
{
}
void QSharedMemoryPrivate::setErrorString(const QString &function)
{
// EINVAL is handled in functions so they can give better error strings
switch (errno) {
case EACCES:
errorString = QSharedMemory::tr("%1: permission denied").arg(function);
error = QSharedMemory::PermissionDenied;
break;
case EEXIST:
errorString = QSharedMemory::tr("%1: already exists").arg(function);
error = QSharedMemory::AlreadyExists;
break;
case ENOENT:
errorString = QSharedMemory::tr("%1: doesn't exist").arg(function);
error = QSharedMemory::NotFound;
break;
case EMFILE:
case ENOMEM:
case ENOSPC:
errorString = QSharedMemory::tr("%1: out of resources").arg(function);
error = QSharedMemory::OutOfResources;
break;
default:
errorString = QSharedMemory::tr("%1: unknown error %2").arg(function).arg(errno);
error = QSharedMemory::UnknownError;
#if defined QSHAREDMEMORY_DEBUG
qDebug() << errorString << "key" << key << "errno" << errno << EINVAL;
#endif
}
}
/*!
\internal
If not already made create the handle used for accessing the shared memory.
*/
key_t QSharedMemoryPrivate::handle()
{
// already made
if (unix_key)
return unix_key;
// don't allow making handles on empty keys
if (key.isEmpty()) {
errorString = QSharedMemory::tr("%1: key is empty").arg(QLatin1String("QSharedMemory::handle:"));
error = QSharedMemory::KeyError;
return 0;
}
// ftok requires that an actual file exists somewhere
QString fileName = makePlatformSafeKey(key);
if (!QFile::exists(fileName)) {
errorString = QSharedMemory::tr("%1: UNIX key file doesn't exist").arg(QLatin1String("QSharedMemory::handle:"));
error = QSharedMemory::NotFound;
return 0;
}
unix_key = ftok(QFile::encodeName(fileName).constData(), 'Q');
if (-1 == unix_key) {
errorString = QSharedMemory::tr("%1: ftok failed").arg(QLatin1String("QSharedMemory::handle:"));
error = QSharedMemory::KeyError;
unix_key = 0;
}
return unix_key;
}
#endif // QT_NO_SHAREDMEMORY
#if !(defined(QT_NO_SHAREDMEMORY) && defined(QT_NO_SYSTEMSEMAPHORE))
/*!
\internal
Creates the unix file if needed.
returns true if the unix file was created.
-1 error
0 already existed
1 created
*/
int QSharedMemoryPrivate::createUnixKeyFile(const QString &fileName)
{
if (QFile::exists(fileName))
return 0;
int fd = qt_safe_open(QFile::encodeName(fileName).constData(),
O_EXCL | O_CREAT | O_RDWR, 0640);
if (-1 == fd) {
if (errno == EEXIST)
return 0;
return -1;
} else {
close(fd);
}
return 1;
}
#endif // QT_NO_SHAREDMEMORY && QT_NO_SYSTEMSEMAPHORE
#ifndef QT_NO_SHAREDMEMORY
bool QSharedMemoryPrivate::cleanHandle()
{
unix_key = 0;
return true;
}
bool QSharedMemoryPrivate::create(int size)
{
// build file if needed
bool createdFile = false;
int built = createUnixKeyFile(makePlatformSafeKey(key));
if (built == -1) {
errorString = QSharedMemory::tr("%1: unable to make key").arg(QLatin1String("QSharedMemory::handle:"));
error = QSharedMemory::KeyError;
return false;
}
if (built == 1) {
createdFile = true;
}
// get handle
if (!handle()) {
if (createdFile)
QFile::remove(makePlatformSafeKey(key));
return false;
}
// create
if (-1 == shmget(handle(), size, 0666 | IPC_CREAT | IPC_EXCL)) {
QString function = QLatin1String("QSharedMemory::create");
switch (errno) {
case EINVAL:
errorString = QSharedMemory::tr("%1: system-imposed size restrictions").arg(QLatin1String("QSharedMemory::handle"));
error = QSharedMemory::InvalidSize;
break;
default:
setErrorString(function);
}
if (createdFile && error != QSharedMemory::AlreadyExists)
QFile::remove(makePlatformSafeKey(key));
return false;
}
return true;
}
bool QSharedMemoryPrivate::attach(QSharedMemory::AccessMode mode)
{
// grab the shared memory segment id
if (!handle())
return false;
int id = shmget(handle(), 0, (mode == QSharedMemory::ReadOnly ? 0444 : 0660));
if (-1 == id) {
setErrorString(QLatin1String("QSharedMemory::attach (shmget)"));
return false;
}
// grab the memory
memory = shmat(id, 0, (mode == QSharedMemory::ReadOnly ? SHM_RDONLY : 0));
if ((void*) - 1 == memory) {
memory = 0;
setErrorString(QLatin1String("QSharedMemory::attach (shmat)"));
return false;
}
// grab the size
shmid_ds shmid_ds;
if (!shmctl(id, IPC_STAT, &shmid_ds)) {
size = (int)shmid_ds.shm_segsz;
} else {
setErrorString(QLatin1String("QSharedMemory::attach (shmctl)"));
return false;
}
return true;
}
bool QSharedMemoryPrivate::detach()
{
// detach from the memory segment
if (-1 == shmdt(memory)) {
QString function = QLatin1String("QSharedMemory::detach");
switch (errno) {
case EINVAL:
errorString = QSharedMemory::tr("%1: not attached").arg(function);
error = QSharedMemory::NotFound;
break;
default:
setErrorString(function);
}
return false;
}
memory = 0;
// Get the number of current attachments
if (!handle())
return false;
int id = shmget(handle(), 0, 0444);
unix_key = 0;
struct shmid_ds shmid_ds;
if (0 != shmctl(id, IPC_STAT, &shmid_ds)) {
switch (errno) {
case EINVAL:
return true;
default:
return false;
}
}
// If there are no attachments then remove it.
if (shmid_ds.shm_nattch == 0) {
// mark for removal
if (-1 == shmctl(id, IPC_RMID, &shmid_ds)) {
setErrorString(QLatin1String("QSharedMemory::remove"));
switch (errno) {
case EINVAL:
return true;
default:
return false;
}
}
// remove file
if (!QFile::remove(makePlatformSafeKey(key)))
return false;
}
return true;
}
QT_END_NAMESPACE
#endif // QT_NO_SHAREDMEMORY
<commit_msg>Fix QT_NO_SHAREDMEMORY while not breaking the QNX build<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the 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 qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qplatformdefs.h"
#include "qsharedmemory.h"
#include "qsharedmemory_p.h"
#include "qsystemsemaphore.h"
#include <qdir.h>
#include <qdebug.h>
#include <errno.h>
#ifndef QT_NO_SHAREDMEMORY
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#endif //QT_NO_SHAREDMEMORY
#include "private/qcore_unix_p.h"
#ifndef QT_NO_SHAREDMEMORY
QT_BEGIN_NAMESPACE
QSharedMemoryPrivate::QSharedMemoryPrivate()
: QObjectPrivate(), memory(0), size(0), error(QSharedMemory::NoError),
#ifndef QT_NO_SYSTEMSEMAPHORE
systemSemaphore(QString()), lockedByMe(false),
#endif
unix_key(0)
{
}
void QSharedMemoryPrivate::setErrorString(const QString &function)
{
// EINVAL is handled in functions so they can give better error strings
switch (errno) {
case EACCES:
errorString = QSharedMemory::tr("%1: permission denied").arg(function);
error = QSharedMemory::PermissionDenied;
break;
case EEXIST:
errorString = QSharedMemory::tr("%1: already exists").arg(function);
error = QSharedMemory::AlreadyExists;
break;
case ENOENT:
errorString = QSharedMemory::tr("%1: doesn't exist").arg(function);
error = QSharedMemory::NotFound;
break;
case EMFILE:
case ENOMEM:
case ENOSPC:
errorString = QSharedMemory::tr("%1: out of resources").arg(function);
error = QSharedMemory::OutOfResources;
break;
default:
errorString = QSharedMemory::tr("%1: unknown error %2").arg(function).arg(errno);
error = QSharedMemory::UnknownError;
#if defined QSHAREDMEMORY_DEBUG
qDebug() << errorString << "key" << key << "errno" << errno << EINVAL;
#endif
}
}
/*!
\internal
If not already made create the handle used for accessing the shared memory.
*/
key_t QSharedMemoryPrivate::handle()
{
// already made
if (unix_key)
return unix_key;
// don't allow making handles on empty keys
if (key.isEmpty()) {
errorString = QSharedMemory::tr("%1: key is empty").arg(QLatin1String("QSharedMemory::handle:"));
error = QSharedMemory::KeyError;
return 0;
}
// ftok requires that an actual file exists somewhere
QString fileName = makePlatformSafeKey(key);
if (!QFile::exists(fileName)) {
errorString = QSharedMemory::tr("%1: UNIX key file doesn't exist").arg(QLatin1String("QSharedMemory::handle:"));
error = QSharedMemory::NotFound;
return 0;
}
unix_key = ftok(QFile::encodeName(fileName).constData(), 'Q');
if (-1 == unix_key) {
errorString = QSharedMemory::tr("%1: ftok failed").arg(QLatin1String("QSharedMemory::handle:"));
error = QSharedMemory::KeyError;
unix_key = 0;
}
return unix_key;
}
#endif // QT_NO_SHAREDMEMORY
#if !(defined(QT_NO_SHAREDMEMORY) && defined(QT_NO_SYSTEMSEMAPHORE))
/*!
\internal
Creates the unix file if needed.
returns true if the unix file was created.
-1 error
0 already existed
1 created
*/
int QSharedMemoryPrivate::createUnixKeyFile(const QString &fileName)
{
if (QFile::exists(fileName))
return 0;
int fd = qt_safe_open(QFile::encodeName(fileName).constData(),
O_EXCL | O_CREAT | O_RDWR, 0640);
if (-1 == fd) {
if (errno == EEXIST)
return 0;
return -1;
} else {
close(fd);
}
return 1;
}
#endif // QT_NO_SHAREDMEMORY && QT_NO_SYSTEMSEMAPHORE
#ifndef QT_NO_SHAREDMEMORY
bool QSharedMemoryPrivate::cleanHandle()
{
unix_key = 0;
return true;
}
bool QSharedMemoryPrivate::create(int size)
{
// build file if needed
bool createdFile = false;
int built = createUnixKeyFile(makePlatformSafeKey(key));
if (built == -1) {
errorString = QSharedMemory::tr("%1: unable to make key").arg(QLatin1String("QSharedMemory::handle:"));
error = QSharedMemory::KeyError;
return false;
}
if (built == 1) {
createdFile = true;
}
// get handle
if (!handle()) {
if (createdFile)
QFile::remove(makePlatformSafeKey(key));
return false;
}
// create
if (-1 == shmget(handle(), size, 0666 | IPC_CREAT | IPC_EXCL)) {
QString function = QLatin1String("QSharedMemory::create");
switch (errno) {
case EINVAL:
errorString = QSharedMemory::tr("%1: system-imposed size restrictions").arg(QLatin1String("QSharedMemory::handle"));
error = QSharedMemory::InvalidSize;
break;
default:
setErrorString(function);
}
if (createdFile && error != QSharedMemory::AlreadyExists)
QFile::remove(makePlatformSafeKey(key));
return false;
}
return true;
}
bool QSharedMemoryPrivate::attach(QSharedMemory::AccessMode mode)
{
// grab the shared memory segment id
if (!handle())
return false;
int id = shmget(handle(), 0, (mode == QSharedMemory::ReadOnly ? 0444 : 0660));
if (-1 == id) {
setErrorString(QLatin1String("QSharedMemory::attach (shmget)"));
return false;
}
// grab the memory
memory = shmat(id, 0, (mode == QSharedMemory::ReadOnly ? SHM_RDONLY : 0));
if ((void*) - 1 == memory) {
memory = 0;
setErrorString(QLatin1String("QSharedMemory::attach (shmat)"));
return false;
}
// grab the size
shmid_ds shmid_ds;
if (!shmctl(id, IPC_STAT, &shmid_ds)) {
size = (int)shmid_ds.shm_segsz;
} else {
setErrorString(QLatin1String("QSharedMemory::attach (shmctl)"));
return false;
}
return true;
}
bool QSharedMemoryPrivate::detach()
{
// detach from the memory segment
if (-1 == shmdt(memory)) {
QString function = QLatin1String("QSharedMemory::detach");
switch (errno) {
case EINVAL:
errorString = QSharedMemory::tr("%1: not attached").arg(function);
error = QSharedMemory::NotFound;
break;
default:
setErrorString(function);
}
return false;
}
memory = 0;
// Get the number of current attachments
if (!handle())
return false;
int id = shmget(handle(), 0, 0444);
unix_key = 0;
struct shmid_ds shmid_ds;
if (0 != shmctl(id, IPC_STAT, &shmid_ds)) {
switch (errno) {
case EINVAL:
return true;
default:
return false;
}
}
// If there are no attachments then remove it.
if (shmid_ds.shm_nattch == 0) {
// mark for removal
if (-1 == shmctl(id, IPC_RMID, &shmid_ds)) {
setErrorString(QLatin1String("QSharedMemory::remove"));
switch (errno) {
case EINVAL:
return true;
default:
return false;
}
}
// remove file
if (!QFile::remove(makePlatformSafeKey(key)))
return false;
}
return true;
}
QT_END_NAMESPACE
#endif // QT_NO_SHAREDMEMORY
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: DIndexColumns.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: obo $ $Date: 2006-09-17 02:22:14 $
*
* 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_connectivity.hxx"
#ifndef _CONNECTIVITY_DBASE_INDEXCOLUMNS_HXX_
#include "dbase/DIndexColumns.hxx"
#endif
#ifndef _CONNECTIVITY_DBASE_TABLE_HXX_
#include "dbase/DTable.hxx"
#endif
#ifndef _CONNECTIVITY_SDBCX_INDEXCOLUMN_HXX_
#include "connectivity/sdbcx/VIndexColumn.hxx"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _COMPHELPER_PROPERTY_HXX_
#include <comphelper/property.hxx>
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include <connectivity/dbexception.hxx>
#endif
using namespace ::comphelper;
using namespace connectivity::dbase;
using namespace connectivity;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
sdbcx::ObjectType ODbaseIndexColumns::createObject(const ::rtl::OUString& _rName)
{
const ODbaseTable* pTable = m_pIndex->getTable();
::vos::ORef<OSQLColumns> aCols = pTable->getTableColumns();
OSQLColumns::const_iterator aIter = find(aCols->begin(),aCols->end(),_rName,::comphelper::UStringMixEqual(isCaseSensitive()));
Reference< XPropertySet > xCol;
if(aIter != aCols->end())
xCol = *aIter;
if(!xCol.is())
return sdbcx::ObjectType();
sdbcx::ObjectType xRet = new sdbcx::OIndexColumn(sal_True,_rName
,getString(xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPENAME)))
,::rtl::OUString()
,getINT32(xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISNULLABLE)))
,getINT32(xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PRECISION)))
,getINT32(xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCALE)))
,getINT32(xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE)))
,sal_False
,sal_False
,sal_False
,pTable->getConnection()->getMetaData()->storesMixedCaseQuotedIdentifiers());
return xRet;
}
// -------------------------------------------------------------------------
void ODbaseIndexColumns::impl_refresh() throw(RuntimeException)
{
m_pIndex->refreshColumns();
}
// -------------------------------------------------------------------------
Reference< XPropertySet > ODbaseIndexColumns::createDescriptor()
{
return new sdbcx::OIndexColumn(m_pIndex->getTable()->getConnection()->getMetaData()->storesMixedCaseQuotedIdentifiers());
}
// -------------------------------------------------------------------------
sdbcx::ObjectType ODbaseIndexColumns::appendObject( const ::rtl::OUString& /*_rForName*/, const Reference< XPropertySet >& descriptor )
{
return cloneDescriptor( descriptor );
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS changefileheader (1.14.216); FILE MERGED 2008/04/01 15:08:40 thb 1.14.216.3: #i85898# Stripping all external header guards 2008/04/01 10:52:52 thb 1.14.216.2: #i85898# Stripping all external header guards 2008/03/28 15:23:28 rt 1.14.216.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: DIndexColumns.cxx,v $
* $Revision: 1.15 $
*
* 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_connectivity.hxx"
#include "dbase/DIndexColumns.hxx"
#include "dbase/DTable.hxx"
#include "connectivity/sdbcx/VIndexColumn.hxx"
#include <comphelper/types.hxx>
#include <comphelper/property.hxx>
#include <connectivity/dbexception.hxx>
using namespace ::comphelper;
using namespace connectivity::dbase;
using namespace connectivity;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
sdbcx::ObjectType ODbaseIndexColumns::createObject(const ::rtl::OUString& _rName)
{
const ODbaseTable* pTable = m_pIndex->getTable();
::vos::ORef<OSQLColumns> aCols = pTable->getTableColumns();
OSQLColumns::const_iterator aIter = find(aCols->begin(),aCols->end(),_rName,::comphelper::UStringMixEqual(isCaseSensitive()));
Reference< XPropertySet > xCol;
if(aIter != aCols->end())
xCol = *aIter;
if(!xCol.is())
return sdbcx::ObjectType();
sdbcx::ObjectType xRet = new sdbcx::OIndexColumn(sal_True,_rName
,getString(xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPENAME)))
,::rtl::OUString()
,getINT32(xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISNULLABLE)))
,getINT32(xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PRECISION)))
,getINT32(xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCALE)))
,getINT32(xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE)))
,sal_False
,sal_False
,sal_False
,pTable->getConnection()->getMetaData()->storesMixedCaseQuotedIdentifiers());
return xRet;
}
// -------------------------------------------------------------------------
void ODbaseIndexColumns::impl_refresh() throw(RuntimeException)
{
m_pIndex->refreshColumns();
}
// -------------------------------------------------------------------------
Reference< XPropertySet > ODbaseIndexColumns::createDescriptor()
{
return new sdbcx::OIndexColumn(m_pIndex->getTable()->getConnection()->getMetaData()->storesMixedCaseQuotedIdentifiers());
}
// -------------------------------------------------------------------------
sdbcx::ObjectType ODbaseIndexColumns::appendObject( const ::rtl::OUString& /*_rForName*/, const Reference< XPropertySet >& descriptor )
{
return cloneDescriptor( descriptor );
}
// -----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: basenode.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2005-03-10 13:50:17 $
*
* 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 _SLIDESHOW_BASENODE_HXX
#define _SLIDESHOW_BASENODE_HXX
#include <animationnode.hxx>
#include <slideshowcontext.hxx>
#include <shapesubset.hxx>
#include <vector>
namespace presentation
{
namespace internal
{
typedef int StateTransitionTable[17];
/** Context for every node.
Besides the global AnimationNodeFactory::Context data,
this struct also contains the current DocTree subset
for this node. If start and end index of the
DocTreeNode are equal, the node should use the
complete shape.
*/
struct NodeContext
{
NodeContext( const SlideShowContext& rContext ) :
maContext( rContext ),
mpMasterShapeSubset(),
mnStartDelay(0.0),
mbIsIndependentSubset( true )
{
}
void dispose() { maContext.dispose(); }
/// Context as passed to createAnimationNode()
SlideShowContext maContext;
/// Shape to be used (provided by parent, e.g. for iterations)
ShapeSubsetSharedPtr mpMasterShapeSubset;
/// Additional delay to node begin (to offset iterate effects)
double mnStartDelay;
/// When true, subset must be created during slide initialization
bool mbIsIndependentSubset;
};
class BaseContainerNode;
/** This interface extends AnimationNode with some
file-private accessor methods.
*/
class BaseNode : public AnimationNode
{
public:
BaseNode( const ::com::sun::star::uno::Reference<
::com::sun::star::animations::XAnimationNode >& xNode,
const ::boost::shared_ptr< BaseContainerNode >& rParent,
const NodeContext& rContext );
// Disposable interface
// --------------------
virtual void dispose();
// Implemented subset of AnimationNode interface
// ---------------------------------------------
virtual ::com::sun::star::uno::Reference<
::com::sun::star::animations::XAnimationNode > getXAnimationNode() const;
virtual bool init();
virtual bool resolve();
virtual bool activate();
virtual void deactivate();
virtual void end();
virtual NodeState getState() const;
virtual bool registerDeactivatingListener( const AnimationNodeSharedPtr& rNotifee );
/** Provide the node with a shared_ptr to itself.
Since implementation has to create objects which need
a shared_ptr to this node, and a pointee cannot
retrieve a shared_ptr to itself internally, have to
set that from the outside.
*/
virtual void setSelf( const ::boost::shared_ptr< BaseNode >& rSelf );
/** Get the default fill mode.
If this node's default mode is AnimationFill::DEFAULT,
this method recursively calls the parent node.
*/
virtual sal_Int16 getFillDefaultMode() const;
/** Get the default restart mode
If this node's default mode is
AnimationRestart::DEFAULT, this method recursively
calls the parent node.
*/
virtual sal_Int16 getRestartDefaultMode() const;
/// Get the node's restart mode
virtual sal_Int16 getRestartMode();
/// Get the node's fill mode
virtual sal_Int16 getFillMode();
/** Notify a fired user event to this node
This method differs from a plain activate(), in that
it is able to also activate a yet unresolved node. If
a node cannot be simply activated, this method issues
a requestResolveOnChildren() on the parent node.
*/
virtual void notifyUserEvent();
#if defined(VERBOSE) && defined(DBG_UTIL)
virtual void showState() const;
virtual const char* getDescription() const;
void showTreeFromWithin() const;
#endif
const ::boost::shared_ptr< BaseContainerNode >& getParentNode() const { return mpParent; }
protected:
/** Schedule event that activates the node, once it is resolved
You can override this method in derived
classes. AnimateBaseNode does it to implement its
fixed delay
*/
virtual void scheduleActivationEvent();
/** Schedule event that deactivates the node, once it is active
You can override this method in derived
classes.
*/
virtual void scheduleDeactivationEvent() const;
// inline accessors
// ----------------
const SlideShowContext& getContext() const { return maContext; }
const ::boost::shared_ptr< BaseNode >& getSelf() const { return mpSelf; }
const ::com::sun::star::uno::Reference<
::com::sun::star::animations::XAnimationNode >& getXNode() const { return mxNode; }
private:
typedef ::std::vector< AnimationNodeSharedPtr > ListenerVector;
ListenerVector maDeactivatingListeners;
::com::sun::star::uno::Reference<
::com::sun::star::animations::XAnimationNode > mxNode;
::boost::shared_ptr< BaseContainerNode > mpParent;
::boost::shared_ptr< BaseNode > mpSelf;
const int* mpStateTransitionTable;
SlideShowContext maContext;
const double mnStartDelay;
AnimationNode::NodeState meCurrState;
const bool mbIsMainSequenceRootNode;
};
typedef ::boost::shared_ptr< BaseNode > BaseNodeSharedPtr;
}
}
#endif /* _SLIDESHOW_BASENODE_HXX */
<commit_msg>INTEGRATION: CWS presfixes02 (1.3.2); FILE MERGED 2005/03/21 17:37:15 dbo 1.3.2.1: #i41476# schedule deactivation of parent node if no children are available Issue number: Submitted by: Reviewed by:<commit_after>/*************************************************************************
*
* $RCSfile: basenode.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-03-30 08:06:41 $
*
* 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 _SLIDESHOW_BASENODE_HXX
#define _SLIDESHOW_BASENODE_HXX
#include <animationnode.hxx>
#include <slideshowcontext.hxx>
#include <shapesubset.hxx>
#include <vector>
namespace presentation
{
namespace internal
{
typedef int StateTransitionTable[17];
/** Context for every node.
Besides the global AnimationNodeFactory::Context data,
this struct also contains the current DocTree subset
for this node. If start and end index of the
DocTreeNode are equal, the node should use the
complete shape.
*/
struct NodeContext
{
NodeContext( const SlideShowContext& rContext ) :
maContext( rContext ),
mpMasterShapeSubset(),
mnStartDelay(0.0),
mbIsIndependentSubset( true )
{
}
void dispose() { maContext.dispose(); }
/// Context as passed to createAnimationNode()
SlideShowContext maContext;
/// Shape to be used (provided by parent, e.g. for iterations)
ShapeSubsetSharedPtr mpMasterShapeSubset;
/// Additional delay to node begin (to offset iterate effects)
double mnStartDelay;
/// When true, subset must be created during slide initialization
bool mbIsIndependentSubset;
};
class BaseContainerNode;
/** This interface extends AnimationNode with some
file-private accessor methods.
*/
class BaseNode : public AnimationNode
{
public:
BaseNode( const ::com::sun::star::uno::Reference<
::com::sun::star::animations::XAnimationNode >& xNode,
const ::boost::shared_ptr< BaseContainerNode >& rParent,
const NodeContext& rContext );
// Disposable interface
// --------------------
virtual void dispose();
// Implemented subset of AnimationNode interface
// ---------------------------------------------
virtual ::com::sun::star::uno::Reference<
::com::sun::star::animations::XAnimationNode > getXAnimationNode() const;
virtual bool init();
virtual bool resolve();
virtual bool activate();
virtual void deactivate();
virtual void end();
virtual NodeState getState() const;
virtual bool registerDeactivatingListener( const AnimationNodeSharedPtr& rNotifee );
/** Provide the node with a shared_ptr to itself.
Since implementation has to create objects which need
a shared_ptr to this node, and a pointee cannot
retrieve a shared_ptr to itself internally, have to
set that from the outside.
*/
virtual void setSelf( const ::boost::shared_ptr< BaseNode >& rSelf );
/** Get the default fill mode.
If this node's default mode is AnimationFill::DEFAULT,
this method recursively calls the parent node.
*/
virtual sal_Int16 getFillDefaultMode() const;
/** Get the default restart mode
If this node's default mode is
AnimationRestart::DEFAULT, this method recursively
calls the parent node.
*/
virtual sal_Int16 getRestartDefaultMode() const;
/// Get the node's restart mode
virtual sal_Int16 getRestartMode();
/// Get the node's fill mode
virtual sal_Int16 getFillMode();
/** Notify a fired user event to this node
This method differs from a plain activate(), in that
it is able to also activate a yet unresolved node. If
a node cannot be simply activated, this method issues
a requestResolveOnChildren() on the parent node.
*/
virtual void notifyUserEvent();
#if defined(VERBOSE) && defined(DBG_UTIL)
virtual void showState() const;
virtual const char* getDescription() const;
void showTreeFromWithin() const;
#endif
const ::boost::shared_ptr< BaseContainerNode >& getParentNode() const { return mpParent; }
protected:
/** Schedule event that activates the node, once it is resolved
You can override this method in derived
classes. AnimateBaseNode does it to implement its
fixed delay
*/
virtual void scheduleActivationEvent();
/** Schedule event that deactivates the node, once it is active
You can override this method in derived
classes.
*/
virtual void scheduleDeactivationEvent() const;
// inline accessors
// ----------------
const SlideShowContext& getContext() const { return maContext; }
const ::boost::shared_ptr< BaseNode >& getSelf() const { return mpSelf; }
const ::com::sun::star::uno::Reference<
::com::sun::star::animations::XAnimationNode >& getXNode() const { return mxNode; }
protected:
SlideShowContext maContext;
private:
typedef ::std::vector< AnimationNodeSharedPtr > ListenerVector;
ListenerVector maDeactivatingListeners;
::com::sun::star::uno::Reference<
::com::sun::star::animations::XAnimationNode > mxNode;
::boost::shared_ptr< BaseContainerNode > mpParent;
::boost::shared_ptr< BaseNode > mpSelf;
const int* mpStateTransitionTable;
const double mnStartDelay;
AnimationNode::NodeState meCurrState;
const bool mbIsMainSequenceRootNode;
};
typedef ::boost::shared_ptr< BaseNode > BaseNodeSharedPtr;
}
}
#endif /* _SLIDESHOW_BASENODE_HXX */
<|endoftext|>
|
<commit_before>/* @(#)dtkComposerNodeRemote.cpp ---
*
* Author: Nicolas Niclausse
* Copyright (C) 2012 - Nicolas Niclausse, Inria.
* Created: 2012/04/03 15:19:20
* Version: $Id$
* Last-Updated: Mon Oct 8 15:18:00 2012 (+0200)
* By: Thibaud Kloczko, Inria.
* Update #: 1024
*/
/* Commentary:
*
*/
/* Change log:
*
*/
#include "dtkComposerMetatype.h"
#include "dtkComposerNodeRemote.h"
#include "dtkComposerTransmitterEmitter.h"
#include "dtkComposerTransmitterReceiver.h"
#include "dtkComposerTransmitterVariant.h"
#include <dtkDistributed/dtkDistributedController.h>
#include <dtkDistributed/dtkDistributedCommunicator.h>
#include <dtkDistributed/dtkDistributedCommunicatorTcp.h>
#include <dtkDistributed/dtkDistributedSlave.h>
#include <dtkCore/dtkAbstractDataFactory.h>
#include <dtkCore/dtkGlobal.h>
#include <dtkJson>
#include <dtkMath/dtkMath.h>
#include <dtkLog/dtkLog.h>
// /////////////////////////////////////////////////////////////////
// dtkComposerNodeRemotePrivate interface
// /////////////////////////////////////////////////////////////////
class dtkComposerNodeRemotePrivate
{
public:
dtkComposerTransmitterReceiver<QString> jobid_receiver;
public:
QDomDocument composition;
QByteArray current_hash;
QByteArray last_sent_hash;
public:
dtkDistributedController *controller;
public:
dtkDistributedCommunicator *communicator;
dtkDistributedCommunicatorTcp *server;
public:
dtkDistributedSlave *slave;
public:
QString jobid;
QString last_jobid;
public:
QString title;
};
// /////////////////////////////////////////////////////////////////
// dtkComposerNodeRemote implementation
// /////////////////////////////////////////////////////////////////
dtkComposerNodeRemote::dtkComposerNodeRemote(void) : QObject(), dtkComposerNodeComposite(), d(new dtkComposerNodeRemotePrivate)
{
this->appendReceiver(&(d->jobid_receiver));
this->setInputLabelHint("jobid", 0);
d->controller = NULL;
d->slave = NULL;
d->server = NULL;
d->title = "Remote";
}
dtkComposerNodeRemote::~dtkComposerNodeRemote(void)
{
delete d->server;
delete d;
d = NULL;
}
QString dtkComposerNodeRemote::type(void)
{
return "remote";
}
QString dtkComposerNodeRemote::titleHint(void)
{
return d->title;
}
void dtkComposerNodeRemote::setComposition(QDomDocument document)
{
d->composition = document;
d->current_hash = QCryptographicHash::hash(d->composition.toByteArray(),QCryptographicHash::Md5);
}
void dtkComposerNodeRemote::setController(dtkDistributedController *controller)
{
if (d->jobid.isEmpty()) {
dtkWarn() << "No job id while setting controller !";
}
d->controller = controller;
}
void dtkComposerNodeRemote::setSlave(dtkDistributedSlave *slave)
{
d->slave = slave;
}
void dtkComposerNodeRemote::setCommunicator(dtkDistributedCommunicator *c)
{
d->communicator = c;
}
void dtkComposerNodeRemote::setJob(QString jobid)
{
d->jobid = jobid;
}
bool dtkComposerNodeRemote::isSlave(void)
{
if (d->slave)
return true;
return false;
}
void dtkComposerNodeRemote::onJobStarted(QString jobid)
{
if (jobid == d->jobid) {
QObject::disconnect( dtkDistributedController::instance(), SIGNAL(jobStarted(QString)), this, SLOT(onJobStarted(QString)));
} else {
dtkDebug() << "A job has started, but it's not ours, keep waiting " << d->jobid << jobid ;
}
}
void dtkComposerNodeRemote::begin(void)
{
if (!d->slave && !d->jobid_receiver.isEmpty()) {
// we are running on the controller but controller and job was
// not drag&dropped, get job from transmitter and main
// controller instance
d->jobid = *d->jobid_receiver.data();
d->controller = dtkDistributedController::instance();
if (!d->controller->is_running(d->jobid)) {
dtkDebug() << " Wait for job to start, jobid is " << d->jobid;
QEventLoop loop;
this->connect(d->controller, SIGNAL(jobStarted(QString)), this, SLOT(onJobStarted(QString)),Qt::DirectConnection);
loop.connect(d->controller, SIGNAL(jobStarted(QString)), &loop, SLOT(quit()));
loop.connect(qApp, SIGNAL(aboutToQuit()), &loop, SLOT(quit()));
loop.exec();
dtkTrace() << "waiting event loop ended, job has started" << d->jobid;
} else
dtkDebug() << " Job already running, go " << d->jobid;
}
if (d->controller) {
if (!d->server) {
d->server = new dtkDistributedCommunicatorTcp;
d->server->connectToHost(d->controller->socket(d->jobid)->peerAddress().toString(),d->controller->socket(d->jobid)->peerPort());
if (d->server->socket()->waitForConnected()) {
dtkDebug() << "Connected to server";
} else {
dtkError() << "Can't connect to server";
return;
}
}
dtkDistributedMessage *msg;
if (d->last_jobid != d->jobid) {
msg = new dtkDistributedMessage(dtkDistributedMessage::SETRANK,d->jobid,dtkDistributedMessage::CONTROLLER_RUN_RANK );
d->server->socket()->sendRequest(msg);
delete msg;
d->last_jobid=d->jobid;
// the job has changed, so we must send the composition even if it has not changed
d->last_sent_hash.clear();
}
if (d->current_hash != d->last_sent_hash){
// send sub-composition to rank 0 on remote node
QByteArray compo = d->composition.toByteArray();
dtkDebug() << "running node remote begin statement on controller, send composition of size " << compo.size();
msg = new dtkDistributedMessage(dtkDistributedMessage::DATA,d->jobid,0,compo.size(), "xml", compo );
d->last_sent_hash=d->current_hash;
} else {
dtkDebug() << "composition hash hasn't changed, send 'not-modified' to slave";
msg = new dtkDistributedMessage(dtkDistributedMessage::DATA,d->jobid,0,d->current_hash.size(), "not-modified", d->current_hash );
}
d->server->socket()->sendRequest(msg);
delete msg;
dtkDebug() << "composition sent";
// then send transmitters data
int max = dtkComposerNodeComposite::receivers().count();
for (int i = 1; i < max; i++) {
dtkComposerTransmitterVariant *t = dynamic_cast<dtkComposerTransmitterVariant *>(dtkComposerNodeComposite::receivers().at(i));
// FIXME: use our own transmitter variant list (see control nodes)
QByteArray array = t->dataToByteArray();
dtkDebug() << "sending transmitter" << i << "of size" << array.size();
msg = new dtkDistributedMessage(dtkDistributedMessage::DATA, d->jobid, 0, array.size(), "qvariant", array);
d->server->socket()->sendRequest(msg);
delete msg;
}
d->server->socket()->waitForBytesWritten();
} else {
// running on the slave, receive data and set transmitters
int max = dtkComposerNodeComposite::receivers().count();
int size = d->communicator->size();
for (int i = 1; i < max; i++) {
dtkComposerTransmitterVariant *t = dynamic_cast<dtkComposerTransmitterVariant *>(dtkComposerNodeComposite::receivers().at(i));
if (d->communicator->rank() == 0) {
if (d->slave->communicator()->socket()->bytesAvailable()) {
dtkDebug() << "data already available, parse" ;
} else {
if (!(d->slave->communicator()->socket()->waitForReadyRead(60000))) {
dtkError() << "No data received from server after 1mn, abort " ;
return;
} else
dtkDebug() << "Ok, data received, parse" ;
}
dtkDistributedMessage *msg = d->slave->communicator()->socket()->parseRequest();
t->setTwinned(false);
t->setDataFrom(msg->content());
t->setTwinned(true);
dtkDebug() << "send data to slaves";
for (int j=1; j< size; j++)
d->communicator->send(msg->content(),j,0);
} else {
QByteArray array;
dtkDebug() << "receive data from rank 0";
d->communicator->receive(array, 0, 0);
dtkDebug() << "data received, set";
t->setTwinned(false);
t->setDataFrom(array);
t->setTwinned(true);
}
}
}
}
void dtkComposerNodeRemote::end(void)
{
if (d->controller) {
dtkDebug() << "running node remote end statement on controller";
int max = this->emitters().count();
for (int i = 0; i < max; i++) {
dtkComposerTransmitterVariant *t = dynamic_cast<dtkComposerTransmitterVariant *>(this->emitters().at(i));
if (d->server->socket()->bytesAvailable()) {
dtkDebug() << "data already available, parse" ;
} else {
if (!(d->server->socket()->waitForReadyRead(60000))) {
dtkError() << "No data received from slave after 1mn, abort " ;
return;
} else
dtkDebug() << "Ok, data received, parse" ;
}
dtkDistributedMessage *msg = d->server->socket()->parseRequest();
t->setTwinned(false);
t->setDataFrom(msg->content());
t->setTwinned(true);
}
} else {
// running on the slave, send data and set transmitters
dtkDebug() << "running node remote end statement on slave" << d->communicator->rank() ;
int max = this->emitters().count();
int size = d->communicator->size();
Q_UNUSED(size);
for (int i = 0; i < max; i++) {
dtkComposerTransmitterVariant *t = dynamic_cast<dtkComposerTransmitterVariant *>(this->emitters().at(i));
// FIXME: use our own transmitter variant list (see control nodes)
if (d->communicator->rank() == 0) {
dtkDebug() << "end, send transmitter data (we are rank 0)";
QByteArray array = t->dataToByteArray();
if (!array.isEmpty()) {
dtkDistributedMessage *req = new dtkDistributedMessage(dtkDistributedMessage::DATA, d->jobid, dtkDistributedMessage::CONTROLLER_RUN_RANK, array.size(), "qvariant");
d->slave->communicator()->socket()->sendRequest(req);
d->slave->communicator()->socket()->write(array);
delete req;
} else {
dtkError() << "serialization failed in transmitter";
}
} else {
//TODO rank >0
}
}
if (d->communicator->rank() == 0)
d->slave->communicator()->socket()->waitForBytesWritten();
}
}
// /////////////////////////////////////////////////////////////////
// Submit
// /////////////////////////////////////////////////////////////////
class dtkComposerNodeRemoteSubmitPrivate
{
public:
dtkComposerTransmitterEmitter<QString> id;
dtkComposerTransmitterReceiver<QString> cluster;
dtkComposerTransmitterReceiver<qlonglong> nodes;
dtkComposerTransmitterReceiver<qlonglong> cores;
dtkComposerTransmitterReceiver<QString> walltime;
dtkComposerTransmitterReceiver<QString> queuename;
dtkComposerTransmitterReceiver<QString> application;
QMutex mutex;
public:
QString job_id;
};
dtkComposerNodeRemoteSubmit::dtkComposerNodeRemoteSubmit(void) : dtkComposerNodeLeaf(), d(new dtkComposerNodeRemoteSubmitPrivate)
{
this->appendReceiver(&(d->cluster));
this->appendReceiver(&(d->nodes));
this->appendReceiver(&(d->cores));
this->appendReceiver(&(d->walltime));
this->appendReceiver(&(d->queuename));
d->job_id = QString();
d->id.setData(&d->job_id);
this->appendEmitter(&(d->id));
d->mutex.lock();
}
dtkComposerNodeRemoteSubmit::~dtkComposerNodeRemoteSubmit(void)
{
delete d;
d = NULL;
}
void dtkComposerNodeRemoteSubmit::run(void)
{
QVariantMap resources;
if (d->cluster.isEmpty()) {
dtkError() << "Empty server in remote submit, can't submit job";
return;
}
QVariantMap job;
if (d->cores.isEmpty())
resources.insert("cores", 1);
else
resources.insert("cores", *d->cores.data());
if (d->nodes.isEmpty())
resources.insert("nodes", 1);
else
resources.insert("nodes", *d->nodes.data());
job.insert("resources", resources);
if (d->walltime.isEmpty())
job.insert("walltime", "00:15:00");
else
job.insert("walltime", *d->walltime.data());
if (!d->queuename.isEmpty())
job.insert("queue", *d->queuename.data());
job.insert("properties", QVariantMap());
job.insert("application", "dtkComposerEvaluatorSlave "+*d->cluster.data());
QByteArray job_data = dtkJson::serialize(job);
dtkTrace() << " submit job with parameters: "<< job_data;
dtkDistributedController *controller = dtkDistributedController::instance();
if (controller->submit(QUrl(*d->cluster.data()), job_data)) {
QEventLoop loop;
this->connect(controller, SIGNAL(jobQueued(QString)), this, SLOT(onJobQueued(QString)),Qt::DirectConnection);
loop.connect(controller, SIGNAL(jobQueued(QString)), &loop, SLOT(quit()));
loop.connect(qApp, SIGNAL(aboutToQuit()), &loop, SLOT(quit()));
loop.exec();
dtkTrace() << "event loop ended, job is queued";
} else
dtkWarn() << "failed to submit ";
}
void dtkComposerNodeRemoteSubmit::onJobQueued(const QString& job_id)
{
d->job_id = job_id;
QObject::disconnect( dtkDistributedController::instance(), SIGNAL(jobQueued(QString)), this, SLOT(onJobQueued(QString)));
}
<commit_msg>fix memory leak<commit_after>/* @(#)dtkComposerNodeRemote.cpp ---
*
* Author: Nicolas Niclausse
* Copyright (C) 2012 - Nicolas Niclausse, Inria.
* Created: 2012/04/03 15:19:20
* Version: $Id$
* Last-Updated: lun. oct. 8 18:27:11 2012 (+0200)
* By: Nicolas Niclausse
* Update #: 1042
*/
/* Commentary:
*
*/
/* Change log:
*
*/
#include "dtkComposerMetatype.h"
#include "dtkComposerNodeRemote.h"
#include "dtkComposerTransmitterEmitter.h"
#include "dtkComposerTransmitterReceiver.h"
#include "dtkComposerTransmitterVariant.h"
#include <dtkDistributed/dtkDistributedController.h>
#include <dtkDistributed/dtkDistributedCommunicator.h>
#include <dtkDistributed/dtkDistributedCommunicatorTcp.h>
#include <dtkDistributed/dtkDistributedSlave.h>
#include <dtkCore/dtkAbstractDataFactory.h>
#include <dtkCore/dtkGlobal.h>
#include <dtkJson>
#include <dtkMath/dtkMath.h>
#include <dtkLog/dtkLog.h>
// /////////////////////////////////////////////////////////////////
// dtkComposerNodeRemotePrivate interface
// /////////////////////////////////////////////////////////////////
class dtkComposerNodeRemotePrivate
{
public:
dtkComposerTransmitterReceiver<QString> jobid_receiver;
public:
QDomDocument composition;
QByteArray current_hash;
QByteArray last_sent_hash;
public:
dtkDistributedController *controller;
public:
dtkDistributedCommunicator *communicator;
dtkDistributedCommunicatorTcp *server;
public:
dtkDistributedSlave *slave;
public:
QString jobid;
QString last_jobid;
public:
QString title;
};
// /////////////////////////////////////////////////////////////////
// dtkComposerNodeRemote implementation
// /////////////////////////////////////////////////////////////////
dtkComposerNodeRemote::dtkComposerNodeRemote(void) : QObject(), dtkComposerNodeComposite(), d(new dtkComposerNodeRemotePrivate)
{
this->appendReceiver(&(d->jobid_receiver));
this->setInputLabelHint("jobid", 0);
d->controller = NULL;
d->slave = NULL;
d->server = NULL;
d->title = "Remote";
}
dtkComposerNodeRemote::~dtkComposerNodeRemote(void)
{
delete d->server;
delete d;
d = NULL;
}
QString dtkComposerNodeRemote::type(void)
{
return "remote";
}
QString dtkComposerNodeRemote::titleHint(void)
{
return d->title;
}
void dtkComposerNodeRemote::setComposition(QDomDocument document)
{
d->composition = document;
d->current_hash = QCryptographicHash::hash(d->composition.toByteArray(),QCryptographicHash::Md5);
}
void dtkComposerNodeRemote::setController(dtkDistributedController *controller)
{
if (d->jobid.isEmpty()) {
dtkWarn() << "No job id while setting controller !";
}
d->controller = controller;
}
void dtkComposerNodeRemote::setSlave(dtkDistributedSlave *slave)
{
d->slave = slave;
}
void dtkComposerNodeRemote::setCommunicator(dtkDistributedCommunicator *c)
{
d->communicator = c;
}
void dtkComposerNodeRemote::setJob(QString jobid)
{
d->jobid = jobid;
}
bool dtkComposerNodeRemote::isSlave(void)
{
if (d->slave)
return true;
return false;
}
void dtkComposerNodeRemote::onJobStarted(QString jobid)
{
if (jobid == d->jobid) {
QObject::disconnect( dtkDistributedController::instance(), SIGNAL(jobStarted(QString)), this, SLOT(onJobStarted(QString)));
} else {
dtkDebug() << "A job has started, but it's not ours, keep waiting " << d->jobid << jobid ;
}
}
void dtkComposerNodeRemote::begin(void)
{
if (!d->slave && !d->jobid_receiver.isEmpty()) {
// we are running on the controller but controller and job was
// not drag&dropped, get job from transmitter and main
// controller instance
d->jobid = *d->jobid_receiver.data();
d->controller = dtkDistributedController::instance();
if (!d->controller->is_running(d->jobid)) {
dtkDebug() << " Wait for job to start, jobid is " << d->jobid;
QEventLoop loop;
this->connect(d->controller, SIGNAL(jobStarted(QString)), this, SLOT(onJobStarted(QString)),Qt::DirectConnection);
loop.connect(d->controller, SIGNAL(jobStarted(QString)), &loop, SLOT(quit()));
loop.connect(qApp, SIGNAL(aboutToQuit()), &loop, SLOT(quit()));
loop.exec();
dtkTrace() << "waiting event loop ended, job has started" << d->jobid;
} else
dtkDebug() << " Job already running, go " << d->jobid;
}
if (d->controller) {
if (!d->server) {
d->server = new dtkDistributedCommunicatorTcp;
d->server->connectToHost(d->controller->socket(d->jobid)->peerAddress().toString(),d->controller->socket(d->jobid)->peerPort());
if (d->server->socket()->waitForConnected()) {
dtkDebug() << "Connected to server";
} else {
dtkError() << "Can't connect to server";
return;
}
}
dtkDistributedMessage *msg;
if (d->last_jobid != d->jobid) {
msg = new dtkDistributedMessage(dtkDistributedMessage::SETRANK,d->jobid,dtkDistributedMessage::CONTROLLER_RUN_RANK );
d->server->socket()->sendRequest(msg);
delete msg;
d->last_jobid=d->jobid;
// the job has changed, so we must send the composition even if it has not changed
d->last_sent_hash.clear();
}
if (d->current_hash != d->last_sent_hash){
// send sub-composition to rank 0 on remote node
QByteArray compo = d->composition.toByteArray();
dtkDebug() << "running node remote begin statement on controller, send composition of size " << compo.size();
msg = new dtkDistributedMessage(dtkDistributedMessage::DATA,d->jobid,0,compo.size(), "xml", compo );
d->last_sent_hash=d->current_hash;
} else {
dtkDebug() << "composition hash hasn't changed, send 'not-modified' to slave";
msg = new dtkDistributedMessage(dtkDistributedMessage::DATA,d->jobid,0,d->current_hash.size(), "not-modified", d->current_hash );
}
d->server->socket()->sendRequest(msg);
delete msg;
dtkDebug() << "composition sent";
// then send transmitters data
int max = dtkComposerNodeComposite::receivers().count();
for (int i = 1; i < max; i++) {
dtkComposerTransmitterVariant *t = dynamic_cast<dtkComposerTransmitterVariant *>(dtkComposerNodeComposite::receivers().at(i));
// FIXME: use our own transmitter variant list (see control nodes)
QByteArray array = t->dataToByteArray();
dtkDebug() << "sending transmitter" << i << "of size" << array.size();
msg = new dtkDistributedMessage(dtkDistributedMessage::DATA, d->jobid, 0, array.size(), "qvariant", array);
d->server->socket()->sendRequest(msg);
delete msg;
}
d->server->socket()->waitForBytesWritten();
} else {
// running on the slave, receive data and set transmitters
int max = dtkComposerNodeComposite::receivers().count();
int size = d->communicator->size();
for (int i = 1; i < max; i++) {
dtkComposerTransmitterVariant *t = dynamic_cast<dtkComposerTransmitterVariant *>(dtkComposerNodeComposite::receivers().at(i));
if (d->communicator->rank() == 0) {
if (d->slave->communicator()->socket()->bytesAvailable()) {
dtkDebug() << "data already available, parse" ;
} else {
if (!(d->slave->communicator()->socket()->waitForReadyRead(60000))) {
dtkError() << "No data received from server after 1mn, abort " ;
return;
} else
dtkDebug() << "Ok, data received, parse" ;
}
dtkDistributedMessage *msg = d->slave->communicator()->socket()->parseRequest();
t->setTwinned(false);
t->setDataFrom(msg->content());
t->setTwinned(true);
dtkDebug() << "send data to slaves";
for (int j=1; j< size; j++)
d->communicator->send(msg->content(),j,0);
delete msg;
} else {
QByteArray array;
dtkDebug() << "receive data from rank 0";
d->communicator->receive(array, 0, 0);
dtkDebug() << "data received, set";
t->setTwinned(false);
t->setDataFrom(array);
t->setTwinned(true);
}
}
}
}
void dtkComposerNodeRemote::end(void)
{
if (d->controller) {
dtkDebug() << "running node remote end statement on controller";
int max = this->emitters().count();
for (int i = 0; i < max; i++) {
dtkComposerTransmitterVariant *t = dynamic_cast<dtkComposerTransmitterVariant *>(this->emitters().at(i));
if (d->server->socket()->bytesAvailable()) {
dtkDebug() << "data already available, parse" ;
} else {
if (!(d->server->socket()->waitForReadyRead(60000))) {
dtkError() << "No data received from slave after 1mn, abort " ;
return;
} else
dtkDebug() << "Ok, data received, parse" ;
}
dtkDistributedMessage *msg = d->server->socket()->parseRequest();
t->setTwinned(false);
t->setDataFrom(msg->content());
t->setTwinned(true);
delete msg;
}
} else {
// running on the slave, send data and set transmitters
dtkDebug() << "running node remote end statement on slave" << d->communicator->rank() ;
int max = this->emitters().count();
int size = d->communicator->size();
Q_UNUSED(size);
for (int i = 0; i < max; i++) {
dtkComposerTransmitterVariant *t = dynamic_cast<dtkComposerTransmitterVariant *>(this->emitters().at(i));
// FIXME: use our own transmitter variant list (see control nodes)
if (d->communicator->rank() == 0) {
dtkDebug() << "end, send transmitter data (we are rank 0)";
QByteArray array = t->dataToByteArray();
if (!array.isEmpty()) {
dtkDistributedMessage *req = new dtkDistributedMessage(dtkDistributedMessage::DATA, d->jobid, dtkDistributedMessage::CONTROLLER_RUN_RANK, array.size(), "qvariant", array);
d->slave->communicator()->socket()->sendRequest(req);
delete req;
} else {
dtkError() << "serialization failed in transmitter";
}
} else {
//TODO rank >0
}
}
if (d->communicator->rank() == 0)
d->slave->communicator()->socket()->waitForBytesWritten();
}
}
// /////////////////////////////////////////////////////////////////
// Submit
// /////////////////////////////////////////////////////////////////
class dtkComposerNodeRemoteSubmitPrivate
{
public:
dtkComposerTransmitterEmitter<QString> id;
dtkComposerTransmitterReceiver<QString> cluster;
dtkComposerTransmitterReceiver<qlonglong> nodes;
dtkComposerTransmitterReceiver<qlonglong> cores;
dtkComposerTransmitterReceiver<QString> walltime;
dtkComposerTransmitterReceiver<QString> queuename;
dtkComposerTransmitterReceiver<QString> application;
QMutex mutex;
public:
QString job_id;
};
dtkComposerNodeRemoteSubmit::dtkComposerNodeRemoteSubmit(void) : dtkComposerNodeLeaf(), d(new dtkComposerNodeRemoteSubmitPrivate)
{
this->appendReceiver(&(d->cluster));
this->appendReceiver(&(d->nodes));
this->appendReceiver(&(d->cores));
this->appendReceiver(&(d->walltime));
this->appendReceiver(&(d->queuename));
d->job_id = QString();
d->id.setData(&d->job_id);
this->appendEmitter(&(d->id));
d->mutex.lock();
}
dtkComposerNodeRemoteSubmit::~dtkComposerNodeRemoteSubmit(void)
{
delete d;
d = NULL;
}
void dtkComposerNodeRemoteSubmit::run(void)
{
QVariantMap resources;
if (d->cluster.isEmpty()) {
dtkError() << "Empty server in remote submit, can't submit job";
return;
}
QVariantMap job;
if (d->cores.isEmpty())
resources.insert("cores", 1);
else
resources.insert("cores", *d->cores.data());
if (d->nodes.isEmpty())
resources.insert("nodes", 1);
else
resources.insert("nodes", *d->nodes.data());
job.insert("resources", resources);
if (d->walltime.isEmpty())
job.insert("walltime", "00:15:00");
else
job.insert("walltime", *d->walltime.data());
if (!d->queuename.isEmpty())
job.insert("queue", *d->queuename.data());
job.insert("properties", QVariantMap());
job.insert("application", "dtkComposerEvaluatorSlave "+*d->cluster.data());
QByteArray job_data = dtkJson::serialize(job);
dtkTrace() << " submit job with parameters: "<< job_data;
dtkDistributedController *controller = dtkDistributedController::instance();
if (controller->submit(QUrl(*d->cluster.data()), job_data)) {
QEventLoop loop;
this->connect(controller, SIGNAL(jobQueued(QString)), this, SLOT(onJobQueued(QString)),Qt::DirectConnection);
loop.connect(controller, SIGNAL(jobQueued(QString)), &loop, SLOT(quit()));
loop.connect(qApp, SIGNAL(aboutToQuit()), &loop, SLOT(quit()));
loop.exec();
dtkTrace() << "event loop ended, job is queued";
} else
dtkWarn() << "failed to submit ";
}
void dtkComposerNodeRemoteSubmit::onJobQueued(const QString& job_id)
{
d->job_id = job_id;
QObject::disconnect( dtkDistributedController::instance(), SIGNAL(jobQueued(QString)), this, SLOT(onJobQueued(QString)));
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrTextureDomainEffect.h"
#include "GrTBackendEffectFactory.h"
#include "gl/GrGLEffect.h"
#include "gl/GrGLEffectMatrix.h"
#include "SkFloatingPoint.h"
class GrGLTextureDomainEffect : public GrGLEffect {
public:
GrGLTextureDomainEffect(const GrBackendEffectFactory&, const GrEffect&);
virtual void emitCode(GrGLShaderBuilder*,
const GrEffectStage&,
EffectKey,
const char* vertexCoords,
const char* outputColor,
const char* inputColor,
const TextureSamplerArray&) SK_OVERRIDE;
virtual void setData(const GrGLUniformManager&, const GrEffectStage&) SK_OVERRIDE;
static inline EffectKey GenKey(const GrEffectStage&, const GrGLCaps&);
private:
GrGLUniformManager::UniformHandle fNameUni;
GrGLEffectMatrix fEffectMatrix;
GrGLfloat fPrevDomain[4];
typedef GrGLEffect INHERITED;
};
GrGLTextureDomainEffect::GrGLTextureDomainEffect(const GrBackendEffectFactory& factory,
const GrEffect&)
: INHERITED(factory)
, fNameUni(GrGLUniformManager::kInvalidUniformHandle) {
fPrevDomain[0] = SK_FloatNaN;
}
void GrGLTextureDomainEffect::emitCode(GrGLShaderBuilder* builder,
const GrEffectStage& stage,
EffectKey key,
const char* vertexCoords,
const char* outputColor,
const char* inputColor,
const TextureSamplerArray& samplers) {
const GrTextureDomainEffect& effect =
static_cast<const GrTextureDomainEffect&>(*stage.getEffect());
const char* coords;
fEffectMatrix.emitCodeMakeFSCoords2D(builder, key, vertexCoords, &coords);
const char* domain;
fNameUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,
kVec4f_GrSLType, "TexDom", &domain);
if (GrTextureDomainEffect::kClamp_WrapMode == effect.wrapMode()) {
builder->fFSCode.appendf("\tvec2 clampCoord = clamp(%s, %s.xy, %s.zw);\n",
coords, domain, domain);
builder->fFSCode.appendf("\t%s = ", outputColor);
builder->appendTextureLookupAndModulate(&builder->fFSCode,
inputColor,
samplers[0],
"clampCoord");
builder->fFSCode.append(";\n");
} else {
GrAssert(GrTextureDomainEffect::kDecal_WrapMode == effect.wrapMode());
builder->fFSCode.append("\tbvec4 outside;\n");
builder->fFSCode.appendf("\toutside.xy = lessThan(%s, %s.xy);\n", coords, domain);
builder->fFSCode.appendf("\toutside.zw = greaterThan(%s, %s.zw);\n", coords, domain);
builder->fFSCode.appendf("\t%s = any(outside) ? vec4(0.0, 0.0, 0.0, 0.0) : ", outputColor);
builder->appendTextureLookupAndModulate(&builder->fFSCode, inputColor, samplers[0], coords);
builder->fFSCode.append(";\n");
}
}
void GrGLTextureDomainEffect::setData(const GrGLUniformManager& uman, const GrEffectStage& stage) {
const GrTextureDomainEffect& effect =
static_cast<const GrTextureDomainEffect&>(*stage.getEffect());
const GrRect& domain = effect.domain();
float values[4] = {
SkScalarToFloat(domain.left()),
SkScalarToFloat(domain.top()),
SkScalarToFloat(domain.right()),
SkScalarToFloat(domain.bottom())
};
// vertical flip if necessary
if (GrSurface::kBottomLeft_Origin == effect.texture(0)->origin()) {
values[1] = 1.0f - values[1];
values[3] = 1.0f - values[3];
// The top and bottom were just flipped, so correct the ordering
// of elements so that values = (l, t, r, b).
SkTSwap(values[1], values[3]);
}
if (0 != memcmp(values, fPrevDomain, 4 * sizeof(GrGLfloat))) {
uman.set4fv(fNameUni, 0, 1, values);
}
fEffectMatrix.setData(uman,
effect.getMatrix(),
stage.getCoordChangeMatrix(),
effect.texture(0));
}
GrGLEffect::EffectKey GrGLTextureDomainEffect::GenKey(const GrEffectStage& stage, const GrGLCaps&) {
const GrTextureDomainEffect& effect =
static_cast<const GrTextureDomainEffect&>(*stage.getEffect());
EffectKey key = effect.wrapMode();
key <<= GrGLEffectMatrix::kKeyBits;
EffectKey matrixKey = GrGLEffectMatrix::GenKey(effect.getMatrix(),
stage.getCoordChangeMatrix(),
effect.texture(0));
return key | matrixKey;
}
///////////////////////////////////////////////////////////////////////////////
GrEffect* GrTextureDomainEffect::Create(GrTexture* texture,
const SkMatrix& matrix,
const GrRect& domain,
WrapMode wrapMode,
bool bilerp) {
static const SkRect kFullRect = {0, 0, SK_Scalar1, SK_Scalar1};
if (kClamp_WrapMode == wrapMode && domain.contains(kFullRect)) {
return SkNEW_ARGS(GrSingleTextureEffect, (texture, matrix, bilerp));
} else {
SkRect clippedDomain;
// We don't currently handle domains that are empty or don't intersect the texture.
SkAssertResult(clippedDomain.intersect(kFullRect, domain));
return SkNEW_ARGS(GrTextureDomainEffect,
(texture, matrix, clippedDomain, wrapMode, bilerp));
}
}
GrTextureDomainEffect::GrTextureDomainEffect(GrTexture* texture,
const SkMatrix& matrix,
const GrRect& domain,
WrapMode wrapMode,
bool bilerp)
: GrSingleTextureEffect(texture, matrix, bilerp)
, fWrapMode(wrapMode)
, fTextureDomain(domain) {
}
GrTextureDomainEffect::~GrTextureDomainEffect() {
}
const GrBackendEffectFactory& GrTextureDomainEffect::getFactory() const {
return GrTBackendEffectFactory<GrTextureDomainEffect>::getInstance();
}
bool GrTextureDomainEffect::isEqual(const GrEffect& sBase) const {
const GrTextureDomainEffect& s = static_cast<const GrTextureDomainEffect&>(sBase);
return (INHERITED::isEqual(sBase) && this->fTextureDomain == s.fTextureDomain);
}
///////////////////////////////////////////////////////////////////////////////
GR_DEFINE_EFFECT_TEST(GrTextureDomainEffect);
GrEffect* GrTextureDomainEffect::TestCreate(SkRandom* random,
GrContext* context,
GrTexture* textures[]) {
int texIdx = random->nextBool() ? GrEffectUnitTest::kSkiaPMTextureIdx :
GrEffectUnitTest::kAlphaTextureIdx;
GrRect domain;
domain.fLeft = random->nextUScalar1();
domain.fRight = random->nextRangeScalar(domain.fLeft, SK_Scalar1);
domain.fTop = random->nextUScalar1();
domain.fBottom = random->nextRangeScalar(domain.fTop, SK_Scalar1);
WrapMode wrapMode = random->nextBool() ? kClamp_WrapMode : kDecal_WrapMode;
const SkMatrix& matrix = GrEffectUnitTest::TestMatrix(random);
return GrTextureDomainEffect::Create(textures[texIdx], matrix, domain, wrapMode);
}
<commit_msg>Fix texture domain clipping assertion. It is OK to have a degenerate domain. Review URL: https://codereview.appspot.com/6812101<commit_after>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrTextureDomainEffect.h"
#include "GrTBackendEffectFactory.h"
#include "gl/GrGLEffect.h"
#include "gl/GrGLEffectMatrix.h"
#include "SkFloatingPoint.h"
class GrGLTextureDomainEffect : public GrGLEffect {
public:
GrGLTextureDomainEffect(const GrBackendEffectFactory&, const GrEffect&);
virtual void emitCode(GrGLShaderBuilder*,
const GrEffectStage&,
EffectKey,
const char* vertexCoords,
const char* outputColor,
const char* inputColor,
const TextureSamplerArray&) SK_OVERRIDE;
virtual void setData(const GrGLUniformManager&, const GrEffectStage&) SK_OVERRIDE;
static inline EffectKey GenKey(const GrEffectStage&, const GrGLCaps&);
private:
GrGLUniformManager::UniformHandle fNameUni;
GrGLEffectMatrix fEffectMatrix;
GrGLfloat fPrevDomain[4];
typedef GrGLEffect INHERITED;
};
GrGLTextureDomainEffect::GrGLTextureDomainEffect(const GrBackendEffectFactory& factory,
const GrEffect&)
: INHERITED(factory)
, fNameUni(GrGLUniformManager::kInvalidUniformHandle) {
fPrevDomain[0] = SK_FloatNaN;
}
void GrGLTextureDomainEffect::emitCode(GrGLShaderBuilder* builder,
const GrEffectStage& stage,
EffectKey key,
const char* vertexCoords,
const char* outputColor,
const char* inputColor,
const TextureSamplerArray& samplers) {
const GrTextureDomainEffect& effect =
static_cast<const GrTextureDomainEffect&>(*stage.getEffect());
const char* coords;
fEffectMatrix.emitCodeMakeFSCoords2D(builder, key, vertexCoords, &coords);
const char* domain;
fNameUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,
kVec4f_GrSLType, "TexDom", &domain);
if (GrTextureDomainEffect::kClamp_WrapMode == effect.wrapMode()) {
builder->fFSCode.appendf("\tvec2 clampCoord = clamp(%s, %s.xy, %s.zw);\n",
coords, domain, domain);
builder->fFSCode.appendf("\t%s = ", outputColor);
builder->appendTextureLookupAndModulate(&builder->fFSCode,
inputColor,
samplers[0],
"clampCoord");
builder->fFSCode.append(";\n");
} else {
GrAssert(GrTextureDomainEffect::kDecal_WrapMode == effect.wrapMode());
builder->fFSCode.append("\tbvec4 outside;\n");
builder->fFSCode.appendf("\toutside.xy = lessThan(%s, %s.xy);\n", coords, domain);
builder->fFSCode.appendf("\toutside.zw = greaterThan(%s, %s.zw);\n", coords, domain);
builder->fFSCode.appendf("\t%s = any(outside) ? vec4(0.0, 0.0, 0.0, 0.0) : ", outputColor);
builder->appendTextureLookupAndModulate(&builder->fFSCode, inputColor, samplers[0], coords);
builder->fFSCode.append(";\n");
}
}
void GrGLTextureDomainEffect::setData(const GrGLUniformManager& uman, const GrEffectStage& stage) {
const GrTextureDomainEffect& effect =
static_cast<const GrTextureDomainEffect&>(*stage.getEffect());
const GrRect& domain = effect.domain();
float values[4] = {
SkScalarToFloat(domain.left()),
SkScalarToFloat(domain.top()),
SkScalarToFloat(domain.right()),
SkScalarToFloat(domain.bottom())
};
// vertical flip if necessary
if (GrSurface::kBottomLeft_Origin == effect.texture(0)->origin()) {
values[1] = 1.0f - values[1];
values[3] = 1.0f - values[3];
// The top and bottom were just flipped, so correct the ordering
// of elements so that values = (l, t, r, b).
SkTSwap(values[1], values[3]);
}
if (0 != memcmp(values, fPrevDomain, 4 * sizeof(GrGLfloat))) {
uman.set4fv(fNameUni, 0, 1, values);
}
fEffectMatrix.setData(uman,
effect.getMatrix(),
stage.getCoordChangeMatrix(),
effect.texture(0));
}
GrGLEffect::EffectKey GrGLTextureDomainEffect::GenKey(const GrEffectStage& stage, const GrGLCaps&) {
const GrTextureDomainEffect& effect =
static_cast<const GrTextureDomainEffect&>(*stage.getEffect());
EffectKey key = effect.wrapMode();
key <<= GrGLEffectMatrix::kKeyBits;
EffectKey matrixKey = GrGLEffectMatrix::GenKey(effect.getMatrix(),
stage.getCoordChangeMatrix(),
effect.texture(0));
return key | matrixKey;
}
///////////////////////////////////////////////////////////////////////////////
GrEffect* GrTextureDomainEffect::Create(GrTexture* texture,
const SkMatrix& matrix,
const GrRect& domain,
WrapMode wrapMode,
bool bilerp) {
static const SkRect kFullRect = {0, 0, SK_Scalar1, SK_Scalar1};
if (kClamp_WrapMode == wrapMode && domain.contains(kFullRect)) {
return SkNEW_ARGS(GrSingleTextureEffect, (texture, matrix, bilerp));
} else {
SkRect clippedDomain;
// We don't currently handle domains that are empty or don't intersect the texture.
// It is OK if the domain rect is a line or point, but it should not be inverted. We do not
// handle rects that do not intersect the [0..1]x[0..1] rect.
GrAssert(domain.fLeft <= domain.fRight);
GrAssert(domain.fTop <= domain.fBottom);
clippedDomain.fLeft = SkMaxScalar(domain.fLeft, kFullRect.fLeft);
clippedDomain.fRight = SkMinScalar(domain.fRight, kFullRect.fRight);
clippedDomain.fTop = SkMaxScalar(domain.fTop, kFullRect.fTop);
clippedDomain.fBottom = SkMinScalar(domain.fBottom, kFullRect.fBottom);
GrAssert(clippedDomain.fLeft <= clippedDomain.fRight);
GrAssert(clippedDomain.fTop <= clippedDomain.fBottom);
return SkNEW_ARGS(GrTextureDomainEffect,
(texture, matrix, clippedDomain, wrapMode, bilerp));
}
}
GrTextureDomainEffect::GrTextureDomainEffect(GrTexture* texture,
const SkMatrix& matrix,
const GrRect& domain,
WrapMode wrapMode,
bool bilerp)
: GrSingleTextureEffect(texture, matrix, bilerp)
, fWrapMode(wrapMode)
, fTextureDomain(domain) {
}
GrTextureDomainEffect::~GrTextureDomainEffect() {
}
const GrBackendEffectFactory& GrTextureDomainEffect::getFactory() const {
return GrTBackendEffectFactory<GrTextureDomainEffect>::getInstance();
}
bool GrTextureDomainEffect::isEqual(const GrEffect& sBase) const {
const GrTextureDomainEffect& s = static_cast<const GrTextureDomainEffect&>(sBase);
return (INHERITED::isEqual(sBase) && this->fTextureDomain == s.fTextureDomain);
}
///////////////////////////////////////////////////////////////////////////////
GR_DEFINE_EFFECT_TEST(GrTextureDomainEffect);
GrEffect* GrTextureDomainEffect::TestCreate(SkRandom* random,
GrContext* context,
GrTexture* textures[]) {
int texIdx = random->nextBool() ? GrEffectUnitTest::kSkiaPMTextureIdx :
GrEffectUnitTest::kAlphaTextureIdx;
GrRect domain;
domain.fLeft = random->nextUScalar1();
domain.fRight = random->nextRangeScalar(domain.fLeft, SK_Scalar1);
domain.fTop = random->nextUScalar1();
domain.fBottom = random->nextRangeScalar(domain.fTop, SK_Scalar1);
WrapMode wrapMode = random->nextBool() ? kClamp_WrapMode : kDecal_WrapMode;
const SkMatrix& matrix = GrEffectUnitTest::TestMatrix(random);
return GrTextureDomainEffect::Create(textures[texIdx], matrix, domain, wrapMode);
}
<|endoftext|>
|
<commit_before>/**
Copyright 2015 Emil Maskovsky
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
Cookies puzzle.
@author Emil Maskovsky
Determine the minimum time to reach the target with different types
of cookies generating credit.
Git repository: https://github.com/emaskovsky/puzzles-cookies
*/
#include <map>
#include <iostream>
using namespace std;
typedef map< double, double > ValuesT;
double minTime(
const ValuesT::const_iterator & start,
const ValuesT::const_iterator & end,
const double total,
const double cps = 0)
{
if (start == end)
{
return (cps > 0) ? (total / cps) : 0.0;
}
const double G = start->first;
const double P = start->second;
const double CPS = (cps > 0) ? cps : G;
ValuesT::const_iterator next = start;
++next;
// compute the minimum for the current status
// (the result must not be worse)
double timeMin = minTime(next, end, total, CPS);
// time to get N factories
double timeN = 0.0;
for (unsigned N = 1; /* empty */; ++N)
{
// time to get the N-th factory from (N-1)-th is P/((N -1) * G + CPS)
// and that is added to the total time to get N
timeN += P / ((N - 1) * G + CPS);
// time to get T with current N factories
// (next sources checked recursively)
const double timeMinNext = minTime(next, end, total, N * G + CPS);
// and add the time to get the N factories
const double timeTotal = timeN + timeMinNext;
if (timeTotal >= timeMin)
{
// found the optimum - the time to get T with current N is greater
// than or equat to the previous minimum
break;
}
// found a new minimum
timeMin = timeTotal;
}
return timeMin;
}
void testMinTime(const ValuesT & values, const double total)
{
const double time = minTime(values.begin(), values.end(), total);
cout << "Minimum time: " << time << " s" << endl;
}
void test_1source()
{
ValuesT values;
values[1] = 5;
testMinTime(values, 100);
}
void test_2sources()
{
ValuesT values;
values[1] = 5;
values[4] = 16;
testMinTime(values, 100);
}
void test_2sources2ndExpensive()
{
ValuesT values;
values[1] = 5;
values[4] = 21;
testMinTime(values, 100);
}
void test_3sources()
{
ValuesT values;
values[1] = 5;
values[4] = 16;
values[8] = 25;
testMinTime(values, 1000);
}
void test_3sourcesBigNumbers()
{
ValuesT values;
values[0.1] = 15;
values[0.5] = 100;
values[4.0] = 500;
testMinTime(values, 1e6);
}
int main()
{
test_1source();
test_2sources();
test_2sources2ndExpensive();
test_3sources();
test_3sourcesBigNumbers();
return EXIT_SUCCESS;
}
/* EOF */
<commit_msg>Improved reporting<commit_after>/**
Copyright 2015 Emil Maskovsky
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
Cookies puzzle.
@author Emil Maskovsky
Determine the minimum time to reach the target with different types
of cookies generating credit.
Git repository: https://github.com/emaskovsky/puzzles-cookies
*/
#include <ctime>
#include <map>
#include <vector>
#include <iostream>
using namespace std;
typedef map< double, double > ValuesT;
typedef vector< unsigned > CountsT;
double minTime(
const ValuesT::const_iterator & start,
const ValuesT::const_iterator & end,
const CountsT::iterator & counts,
const double total,
const double cps = 0)
{
if (start == end)
{
return (cps > 0) ? (total / cps) : 0.0;
}
const double G = start->first;
const double P = start->second;
const double CPS = (cps > 0) ? cps : G;
ValuesT::const_iterator valuesNext = start;
++valuesNext;
CountsT::iterator countsNext = counts;
++countsNext;
// compute the minimum for the current status
// (the result must not be worse)
double timeMin = minTime(valuesNext, end, countsNext, total, CPS);
// time to get N factories
double timeN = 0.0;
for (unsigned N = 1; /* empty */; ++N)
{
// time to get the N-th factory from (N-1)-th is P/((N -1) * G + CPS)
// and that is added to the total time to get N
timeN += P / ((N - 1) * G + CPS);
// time to get T with current N factories
// (next sources checked recursively)
const double timeMinNext = minTime(
valuesNext,
end,
countsNext,
total,
N * G + CPS);
// and add the time to get the N factories
const double timeTotal = timeN + timeMinNext;
if (timeTotal >= timeMin)
{
// found the optimum - the time to get T with current N is greater
// than or equat to the previous minimum
*counts = N - 1;
break;
}
// found a new minimum
timeMin = timeTotal;
}
return timeMin;
}
void testMinTime(const ValuesT & values, const double total)
{
CountsT counts(values.size(), 0);
clock_t start;
const clock_t tmp = clock();
do
{
start = clock();
}
while (tmp == start);
const double time = minTime(
values.begin(),
values.end(),
counts.begin(),
total);
const clock_t end = clock();
const double elapsed = static_cast< double >(end - start)
/ CLOCKS_PER_SEC;
// there is one cookie #1 already available at the beginning
if (counts.size() > 0)
{
++counts[0];
}
cout << "========================================" << endl;
cout << "Calculation for cookies list:" << endl;
cout << "========================================" << endl;
size_t i = 0;
ValuesT::const_iterator itV = values.begin();
CountsT::const_iterator itC = counts.begin();
while (itV != values.end())
{
cout << "\t#" << ++i
<< ": gen = " << itV->first
<< " c/s, price = " << itV->second
<< " c\t... " << *itC << endl;
++itV, ++itC;
}
cout << "----------------------------------------" << endl;
cout << "Result minimal time: " << time << " s" << endl;
cout << "----------------------------------------" << endl;
cout << "Calculation time: " << elapsed << " s" << endl << endl;
}
void test_1source()
{
ValuesT values;
values[1] = 5;
testMinTime(values, 100);
}
void test_2sources()
{
ValuesT values;
values[1] = 5;
values[4] = 16;
testMinTime(values, 100);
}
void test_2sources2ndExpensive()
{
ValuesT values;
values[1] = 5;
values[4] = 21;
testMinTime(values, 100);
}
void test_3sources()
{
ValuesT values;
values[1] = 5;
values[4] = 16;
values[20] = 75;
testMinTime(values, 1000);
}
void test_3sourcesBigNumbers()
{
ValuesT values;
values[0.1] = 15;
values[0.5] = 100;
values[4.0] = 500;
testMinTime(values, 1e6);
}
int main()
{
test_1source();
test_2sources();
test_2sources2ndExpensive();
test_3sources();
test_3sourcesBigNumbers();
return EXIT_SUCCESS;
}
/* EOF */
<|endoftext|>
|
<commit_before>#include <iostream>
#include <vector>
using namespace std;
vector<int> char_to_bin(string str) {
vector<int> temp (64,0);
int size = str.size();
for (int i = 0; i < size; ++i) {
int count = 7;
while(str[i]) {
temp[i*8+count] = str[i]&1;
str[i] >>= 1;
count--;
}
}
return temp;
}
vector<int> initial_permutation(vector<int> temp) {
vector<int> ip = { 57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5,
63, 55, 47, 39, 31, 23, 15, 7,
56, 48, 40, 32, 24, 16, 8, 0,
58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6};
vector<int> x (64);
int size = ip.size();
for (int i = 0; i < size; ++i)
{
x[i] = temp[ip[i]];
}
return x;
}
vector<int> inverse_initial_permutation(vector<int> temp) {
vector<int> ip_1 = {39, 7, 47, 15, 55, 23, 63, 31,
38, 6, 46, 14, 54, 22, 62, 30,
37, 5, 45, 13, 53, 21, 61, 29,
36, 4, 44, 12, 52, 20, 60, 28,
35, 3, 43, 11, 51, 19, 59, 27,
34, 2, 42, 10, 50, 18, 58, 26,
33, 1, 41, 9, 49, 17, 57, 25,
32, 0, 40, 8, 48, 16, 56, 24};
vector<int> x (64);
int size = ip_1.size();
for (int i = 0; i < size; ++i)
{
x[i] = temp[ip_1[i]];
}
return x;
}
int main() {
string plaintext = "abcdefgh";
cout << (int) plaintext[0] << " " << (int) plaintext[1] << endl;
int size = plaintext.size();
vector<int> temp(64);
vector<vector<int>> bits;
for (int i = 0; i < size; i+=8) {
temp = char_to_bin(plaintext.substr(i,8));
bits.push_back(temp);
}
// for (size_t i = 0; i < bits.size(); ++i)
// {
// for (size_t j = 0; j < bits[i].size(); ++j)
// {
// if(j%8 == 0) {
// cout << endl;
// }
// cout << bits[i][j];
// }
// cout << "--------" << endl;
// }
return 0;
}<commit_msg>Expansion Permutation<commit_after>#include <iostream>
#include <vector>
using namespace std;
vector<int> char_to_bin(string str) {
vector<int> temp (64,0);
int size = str.size();
for (int i = 0; i < size; ++i) {
int count = 7;
while(str[i]) {
temp[i*8+count] = str[i]&1;
str[i] >>= 1;
count--;
}
}
return temp;
}
vector<int> initial_permutation(vector<int> temp) {
vector<int> ip = { 57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5,
63, 55, 47, 39, 31, 23, 15, 7,
56, 48, 40, 32, 24, 16, 8, 0,
58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6};
vector<int> x (64);
int size = ip.size();
for (int i = 0; i < size; ++i)
{
x[i] = temp[ip[i]];
}
return x;
}
vector<int> inverse_initial_permutation(vector<int> temp) {
vector<int> ip_1 = {39, 7, 47, 15, 55, 23, 63, 31,
38, 6, 46, 14, 54, 22, 62, 30,
37, 5, 45, 13, 53, 21, 61, 29,
36, 4, 44, 12, 52, 20, 60, 28,
35, 3, 43, 11, 51, 19, 59, 27,
34, 2, 42, 10, 50, 18, 58, 26,
33, 1, 41, 9, 49, 17, 57, 25,
32, 0, 40, 8, 48, 16, 56, 24};
vector<int> x (64);
int size = ip_1.size();
for (int i = 0; i < size; ++i)
{
x[i] = temp[ip_1[i]];
}
return x;
}
vector<int> expansion_permutation(vector<int> temp) {
vector<int> ep = {31, 0, 1, 2, 3, 4,
3, 4, 5, 6, 7, 8,
7, 8, 9, 10, 11, 12,
11, 12, 13, 14, 15, 16,
15, 16, 17, 18, 19, 20,
19, 20, 21, 22, 23, 24,
23, 24, 25, 26, 27, 28,
27, 28, 29, 30, 31, 0};
vector<int> x (48);
int size = ep.size();
for (int i = 0; i < size; ++i)
{
x[i] = temp[ep[i]];
}
return x;
}
int main() {
string plaintext = "abcdefgh";
cout << (int) plaintext[0] << " " << (int) plaintext[1] << endl;
int size = plaintext.size();
vector<int> temp(64);
vector<vector<int>> bits;
for (int i = 0; i < size; i+=8) {
temp = char_to_bin(plaintext.substr(i,8));
bits.push_back(temp);
}
size = bits.size();
for (int i = 0; i < size; ++i)
{
bits[i] = initial_permutation(bits[i]);
vector<int> left(32), right(32);
int size2 = size/2;
for(int j = 0; j < size2; j++) {
left[j] = bits[i][j];
right[j] = bits[i][size2+j-1];
}
right = expansion_permutation(right);
cout << right.size();
}
// for (size_t i = 0; i < bits.size(); ++i)
// {
// for (size_t j = 0; j < bits[i].size(); ++j)
// {
// if(j%8 == 0) {
// cout << endl;
// }
// cout << bits[i][j];
// }
// cout << "--------" << endl;
// }
return 0;
}<|endoftext|>
|
<commit_before>/*
* MacFileMonitor.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/system/FileMonitor.hpp>
#include <CoreServices/CoreServices.h>
#include <list>
#include <boost/foreach.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <core/Log.hpp>
#include <core/Error.hpp>
#include <core/FileInfo.hpp>
#include <core/Thread.hpp>
#include <core/system/FileScanner.hpp>
#include <core/system/System.hpp>
namespace core {
namespace system {
namespace file_monitor {
namespace {
class FileEventContext : boost::noncopyable
{
public:
FileEventContext() : streamRef(NULL) {}
virtual ~FileEventContext() {}
FSEventStreamRef streamRef;
tree<FileInfo> fileTree;
Callbacks::FilesChanged onFilesChanged;
};
void addEvent(FileChangeEvent::Type type,
const FileInfo& fileInfo,
std::vector<FileChangeEvent>* pEvents)
{
pEvents->push_back(FileChangeEvent(type, fileInfo));
}
Error processAdded(tree<FileInfo>::iterator parentIt,
const FileChangeEvent& fileChange,
tree<FileInfo>* pTree,
std::vector<FileChangeEvent>* pFileChanges)
{
if (fileChange.fileInfo().isDirectory())
{
tree<FileInfo> subTree;
Error error = scanFiles(fileChange.fileInfo(),
true,
&subTree);
if (error)
return error;
// merge in the sub-tree
tree<FileInfo>::sibling_iterator addedIter =
pTree->append_child(parentIt, fileChange.fileInfo());
pTree->insert_subtree_after(addedIter, subTree.begin());
pTree->erase(addedIter);
// generate events
std::for_each(subTree.begin(),
subTree.end(),
boost::bind(addEvent,
FileChangeEvent::FileAdded,
_1,
pFileChanges));
}
else
{
pTree->append_child(parentIt, fileChange.fileInfo());
pFileChanges->push_back(fileChange);
}
// sort the container after insert
pTree->sort(pTree->begin(parentIt),
pTree->end(parentIt),
fileInfoPathLessThan,
false);
return Success();
}
void processModified(tree<FileInfo>::iterator parentIt,
const FileChangeEvent& fileChange,
tree<FileInfo>* pTree,
std::vector<FileChangeEvent>* pFileChanges)
{
tree<FileInfo>::sibling_iterator modIt =
std::find_if(
pTree->begin(parentIt),
pTree->end(parentIt),
boost::bind(fileInfoHasPath,
_1,
fileChange.fileInfo().absolutePath()));
if (modIt != pTree->end(parentIt))
pTree->replace(modIt, fileChange.fileInfo());
// add it to the fileChanges
pFileChanges->push_back(fileChange);
}
void processRemoved(tree<FileInfo>::iterator parentIt,
const FileChangeEvent& fileChange,
tree<FileInfo>* pTree,
std::vector<FileChangeEvent>* pFileChanges)
{
// find the item in the current tree
tree<FileInfo>::sibling_iterator remIt =
std::find(pTree->begin(parentIt),
pTree->end(parentIt),
fileChange.fileInfo());
if (remIt != pTree->end(parentIt))
{
// if this is folder then we need to generate recursive
// remove events, otherwise can just add single event
if (remIt->isDirectory())
{
tree<FileInfo> subTree(remIt);
std::for_each(subTree.begin(),
subTree.end(),
boost::bind(addEvent,
FileChangeEvent::FileRemoved,
_1,
pFileChanges));
}
else
{
pFileChanges->push_back(fileChange);
}
// remove it from the tree
pTree->erase(remIt);
}
}
Error processFileChanges(const FileInfo& fileInfo,
bool recursive,
tree<FileInfo>* pTree,
const Callbacks::FilesChanged& onFilesChanged)
{
// scan this directory into a new tree which we can compare to the old tree
tree<FileInfo> subdirTree;
Error error = scanFiles(fileInfo, recursive, &subdirTree);
if (error)
return error;
// find this path in our fileTree
tree<FileInfo>::iterator it = std::find(pTree->begin(),
pTree->end(),
fileInfo);
if (it != pTree->end())
{
// handle recursive vs. non-recursive scan differnetly
if (recursive)
{
// check for changes on full subtree
std::vector<FileChangeEvent> fileChanges;
tree<FileInfo> existingSubtree(it);
collectFileChangeEvents(existingSubtree.begin(),
existingSubtree.end(),
subdirTree.begin(),
subdirTree.end(),
&fileChanges);
// fire events
onFilesChanged(fileChanges);
// wholesale replace subtree
pTree->insert_subtree_after(it, subdirTree.begin());
pTree->erase(it);
}
else
{
// scan for changes on just the children
std::vector<FileChangeEvent> childrenFileChanges;
collectFileChangeEvents(pTree->begin(it),
pTree->end(it),
subdirTree.begin(subdirTree.begin()),
subdirTree.end(subdirTree.begin()),
&childrenFileChanges);
// build up actual file changes and mutate the tree as appropriate
std::vector<FileChangeEvent> fileChanges;
BOOST_FOREACH(const FileChangeEvent& fileChange, childrenFileChanges)
{
switch(fileChange.type())
{
case FileChangeEvent::FileAdded:
{
Error error = processAdded(it, fileChange, pTree, &fileChanges);
if (error)
LOG_ERROR(error);
break;
}
case FileChangeEvent::FileModified:
{
processModified(it, fileChange, pTree, &fileChanges);
break;
}
case FileChangeEvent::FileRemoved:
{
processRemoved(it, fileChange, pTree, &fileChanges);
break;
}
case FileChangeEvent::None:
default:
break;
}
}
// fire events
onFilesChanged(fileChanges);
}
}
else
{
LOG_WARNING_MESSAGE("Unable to find treeItem for " +
fileInfo.absolutePath());
}
return Success();
}
void fileEventCallback(ConstFSEventStreamRef streamRef,
void *pCallbackInfo,
size_t numEvents,
void *eventPaths,
const FSEventStreamEventFlags eventFlags[],
const FSEventStreamEventId eventIds[])
{
// get context
FileEventContext* pContext = (FileEventContext*)pCallbackInfo;
// bail if we don't have onFilesChanged (we wouldn't if a callback snuck
// through to us even after we failed to fully initialize the file monitor
// (e.g. if there was an error during file listing)
if (!pContext->onFilesChanged)
return;
char **paths = (char**)eventPaths;
for (std::size_t i=0; i<numEvents; i++)
{
// check for root changed (unregister)
if (eventFlags[i] & kFSEventStreamEventFlagRootChanged)
{
unregisterMonitor((Handle)pContext);
return;
}
// make a copy of the path and strip off trailing / if necessary
std::string path(paths[i]);
boost::algorithm::trim_right_if(path, boost::algorithm::is_any_of("/"));
// get FileInfo for this directory
FileInfo fileInfo(path, true);
// check for need to do recursive scan
bool recursive = eventFlags[i] & kFSEventStreamEventFlagMustScanSubDirs;
// process changes
Error error = processFileChanges(fileInfo,
recursive,
&(pContext->fileTree),
pContext->onFilesChanged);
if (error)
LOG_ERROR(error);
}
}
class CFRefScope : boost::noncopyable
{
public:
explicit CFRefScope(CFTypeRef ref)
: ref_(ref)
{
}
virtual ~CFRefScope()
{
try
{
::CFRelease(ref_);
}
catch(...)
{
}
}
private:
CFTypeRef ref_;
};
void invalidateAndReleaseEventStream(FSEventStreamRef streamRef)
{
::FSEventStreamInvalidate(streamRef);
::FSEventStreamRelease(streamRef);
}
void stopInvalidateAndReleaseEventStream(FSEventStreamRef streamRef)
{
::FSEventStreamStop(streamRef);
invalidateAndReleaseEventStream(streamRef);
}
// track active handles so we can implement unregisterAll
std::list<Handle> s_activeHandles;
} // anonymous namespace
namespace detail {
// register a new file monitor
void registerMonitor(const core::FilePath& filePath, const Callbacks& callbacks)
{
// allocate file path
std::string path = filePath.absolutePath();
CFStringRef filePathRef = ::CFStringCreateWithCString(
kCFAllocatorDefault,
filePath.absolutePath().c_str(),
kCFStringEncodingUTF8);
if (filePathRef == NULL)
{
callbacks.onRegistrationError(systemError(
boost::system::errc::not_enough_memory,
ERROR_LOCATION));
return;
}
CFRefScope filePathRefScope(filePathRef);
// allocate paths array
CFArrayRef pathsArrayRef = ::CFArrayCreate(kCFAllocatorDefault,
(const void **)&filePathRef,
1,
NULL);
if (pathsArrayRef == NULL)
{
callbacks.onRegistrationError(systemError(
boost::system::errc::not_enough_memory,
ERROR_LOCATION));
return;
}
CFRefScope pathsArrayRefScope(pathsArrayRef);
// create and allocate FileEventContext (create auto-ptr in case we
// return early, we'll call release later before returning)
FileEventContext* pContext = new FileEventContext();
std::auto_ptr<FileEventContext> autoPtrContext(pContext);
FSEventStreamContext context;
context.version = 0;
context.info = (void*) pContext;
context.retain = NULL;
context.release = NULL;
context.copyDescription = NULL;
// create the stream and save a reference to it
pContext->streamRef = ::FSEventStreamCreate(
kCFAllocatorDefault,
&fileEventCallback,
&context,
pathsArrayRef,
kFSEventStreamEventIdSinceNow,
1,
kFSEventStreamCreateFlagNoDefer |
kFSEventStreamCreateFlagWatchRoot);
if (pContext->streamRef == NULL)
{
callbacks.onRegistrationError(systemError(
boost::system::errc::no_stream_resources,
ERROR_LOCATION));
return;
}
// schedule with the run loop
::FSEventStreamScheduleWithRunLoop(pContext->streamRef,
::CFRunLoopGetCurrent(),
kCFRunLoopDefaultMode);
// start the event stream (check for errors and release if necessary
if (!::FSEventStreamStart(pContext->streamRef))
{
invalidateAndReleaseEventStream(pContext->streamRef);
callbacks.onRegistrationError(systemError(
boost::system::errc::no_stream_resources,
ERROR_LOCATION));
return;
}
// scan the files
Error error = scanFiles(FileInfo(filePath), true, &pContext->fileTree);
if (error)
{
// stop, invalidate, release
stopInvalidateAndReleaseEventStream(pContext->streamRef);
// return error
callbacks.onRegistrationError(error);
return;
}
// now that we have finished the file listing we know we have a valid
// file-monitor so set the onFilesChanged callback so that the
// client can receive events
pContext->onFilesChanged = callbacks.onFilesChanged;
// we are going to pass the context pointer to the client (as the Handle)
// so we release it here to relinquish ownership
autoPtrContext.release();
// track the handle
s_activeHandles.push_back((Handle*)pContext);
// notify the caller that we have successfully registered
callbacks.onRegistered((Handle)pContext, pContext->fileTree);
}
// unregister a file monitor
void unregisterMonitor(Handle handle)
{
// cast to context
FileEventContext* pContext = (FileEventContext*)handle;
// stop, invalidate, release
stopInvalidateAndReleaseEventStream(pContext->streamRef);
// untrack the handle
s_activeHandles.remove(handle);
// delete context
delete pContext;
}
void unregisterAll()
{
// make a copy of all active handles so we can unregister them
// (unregistering mutates the list so that's why we need a copy)
std::vector<Handle> activeHandles;
std::copy(s_activeHandles.begin(),
s_activeHandles.end(),
std::back_inserter(activeHandles));
// unregister all
std::for_each(activeHandles.begin(), activeHandles.end(), unregisterMonitor);
}
void run(const boost::function<void()>& checkForInput)
{
// ensure we have a run loop for this thread (not sure if this is
// strictly necessary but it is not harmful)
::CFRunLoopGetCurrent();
while (true)
{
// process the run loop for 1 second
SInt32 reason = ::CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, false);
// if we were stopped then break
if (reason == kCFRunLoopRunStopped)
{
unregisterAll();
break;
}
// check for input
checkForInput();
}
}
} // namespace detail
} // namespace file_monitor
} // namespace system
} // namespace core
<commit_msg>Revert "make change processing functions generic"<commit_after>/*
* MacFileMonitor.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/system/FileMonitor.hpp>
#include <CoreServices/CoreServices.h>
#include <list>
#include <algorithm>
#include <boost/foreach.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <core/Log.hpp>
#include <core/Error.hpp>
#include <core/FileInfo.hpp>
#include <core/Thread.hpp>
#include <core/system/FileScanner.hpp>
#include <core/system/System.hpp>
namespace core {
namespace system {
namespace file_monitor {
namespace {
class FileEventContext : boost::noncopyable
{
public:
FileEventContext() : streamRef(NULL) {}
virtual ~FileEventContext() {}
FSEventStreamRef streamRef;
tree<FileInfo> fileTree;
Callbacks::FilesChanged onFilesChanged;
};
void addEvent(FileChangeEvent::Type type,
const FileInfo& fileInfo,
std::vector<FileChangeEvent>* pEvents)
{
pEvents->push_back(FileChangeEvent(type, fileInfo));
}
Error processAdded(tree<FileInfo>::iterator parentIt,
const FileChangeEvent& fileChange,
FileEventContext* pContext,
std::vector<FileChangeEvent>* pFileChanges)
{
if (fileChange.fileInfo().isDirectory())
{
tree<FileInfo> subTree;
Error error = scanFiles(fileChange.fileInfo(),
true,
&subTree);
if (error)
return error;
// merge in the sub-tree
tree<FileInfo>::sibling_iterator addedIter =
pContext->fileTree.append_child(parentIt, fileChange.fileInfo());
pContext->fileTree.insert_subtree_after(addedIter,
subTree.begin());
pContext->fileTree.erase(addedIter);
// generate events
std::for_each(subTree.begin(),
subTree.end(),
boost::bind(addEvent,
FileChangeEvent::FileAdded,
_1,
pFileChanges));
}
else
{
pContext->fileTree.append_child(parentIt, fileChange.fileInfo());
pFileChanges->push_back(fileChange);
}
// sort the container after insert (so future calls to collectFileChangeEvents
// can rely on this order)
pContext->fileTree.sort(pContext->fileTree.begin(parentIt),
pContext->fileTree.end(parentIt),
fileInfoPathLessThan,
false);
return Success();
}
void processModified(tree<FileInfo>::iterator parentIt,
const FileChangeEvent& fileChange,
FileEventContext* pContext,
std::vector<FileChangeEvent>* pFileChanges)
{
tree<FileInfo>::sibling_iterator modIt =
std::find_if(
pContext->fileTree.begin(parentIt),
pContext->fileTree.end(parentIt),
boost::bind(fileInfoHasPath,
_1,
fileChange.fileInfo().absolutePath()));
if (modIt != pContext->fileTree.end(parentIt))
pContext->fileTree.replace(modIt, fileChange.fileInfo());
// add it to the fileChanges
pFileChanges->push_back(fileChange);
}
void processRemoved(tree<FileInfo>::iterator parentIt,
const FileChangeEvent& fileChange,
FileEventContext* pContext,
std::vector<FileChangeEvent>* pFileChanges)
{
// find the item in the current tree
tree<FileInfo>::sibling_iterator remIt =
std::find(pContext->fileTree.begin(parentIt),
pContext->fileTree.end(parentIt),
fileChange.fileInfo());
if (remIt != pContext->fileTree.end(parentIt))
{
// if this is folder then we need to generate recursive
// remove events, otherwise can just add single event
if (remIt->isDirectory())
{
tree<FileInfo> subTree(remIt);
std::for_each(subTree.begin(),
subTree.end(),
boost::bind(addEvent,
FileChangeEvent::FileRemoved,
_1,
pFileChanges));
}
else
{
pFileChanges->push_back(fileChange);
}
// remove it from the tree
pContext->fileTree.erase(remIt);
}
}
Error processFileChanges(const FileInfo& fileInfo,
bool recursive,
FileEventContext* pContext)
{
// scan this directory into a new tree which we can compare to the old tree
tree<FileInfo> subdirTree;
Error error = scanFiles(fileInfo, recursive, &subdirTree);
if (error)
return error;
// find this path in our fileTree
tree<FileInfo>::iterator it = std::find(pContext->fileTree.begin(),
pContext->fileTree.end(),
fileInfo);
if (it != pContext->fileTree.end())
{
// handle recursive vs. non-recursive scan differnetly
if (recursive)
{
// check for changes on full subtree
std::vector<FileChangeEvent> fileChanges;
tree<FileInfo> existingSubtree(it);
collectFileChangeEvents(existingSubtree.begin(),
existingSubtree.end(),
subdirTree.begin(),
subdirTree.end(),
&fileChanges);
// fire events
pContext->onFilesChanged(fileChanges);
// wholesale replace subtree
pContext->fileTree.insert_subtree_after(it, subdirTree.begin());
pContext->fileTree.erase(it);
}
else
{
// scan for changes on just the children
std::vector<FileChangeEvent> childrenFileChanges;
collectFileChangeEvents(pContext->fileTree.begin(it),
pContext->fileTree.end(it),
subdirTree.begin(subdirTree.begin()),
subdirTree.end(subdirTree.begin()),
&childrenFileChanges);
// build up actual file changes and mutate the tree as appropriate
std::vector<FileChangeEvent> fileChanges;
BOOST_FOREACH(const FileChangeEvent& fileChange, childrenFileChanges)
{
switch(fileChange.type())
{
case FileChangeEvent::FileAdded:
{
Error error = processAdded(it, fileChange, pContext, &fileChanges);
if (error)
LOG_ERROR(error);
break;
}
case FileChangeEvent::FileModified:
{
processModified(it, fileChange, pContext, &fileChanges);
break;
}
case FileChangeEvent::FileRemoved:
{
processRemoved(it, fileChange, pContext, &fileChanges);
break;
}
case FileChangeEvent::None:
default:
break;
}
}
// fire events
pContext->onFilesChanged(fileChanges);
}
}
else
{
LOG_WARNING_MESSAGE("Unable to find treeItem for " +
fileInfo.absolutePath());
}
return Success();
}
void fileEventCallback(ConstFSEventStreamRef streamRef,
void *pCallbackInfo,
size_t numEvents,
void *eventPaths,
const FSEventStreamEventFlags eventFlags[],
const FSEventStreamEventId eventIds[])
{
// get context
FileEventContext* pContext = (FileEventContext*)pCallbackInfo;
// bail if we don't have onFilesChanged (we wouldn't if a callback snuck
// through to us even after we failed to fully initialize the file monitor
// (e.g. if there was an error during file listing)
if (!pContext->onFilesChanged)
return;
char **paths = (char**)eventPaths;
for (std::size_t i=0; i<numEvents; i++)
{
// check for root changed (unregister)
if (eventFlags[i] & kFSEventStreamEventFlagRootChanged)
{
unregisterMonitor((Handle)pContext);
return;
}
// make a copy of the path and strip off trailing / if necessary
std::string path(paths[i]);
boost::algorithm::trim_right_if(path, boost::algorithm::is_any_of("/"));
// get FileInfo for this directory
FileInfo fileInfo(path, true);
// check for need to do recursive scan
bool recursive = eventFlags[i] & kFSEventStreamEventFlagMustScanSubDirs;
// process changes
Error error = processFileChanges(fileInfo, recursive, pContext);
if (error)
LOG_ERROR(error);
}
}
class CFRefScope : boost::noncopyable
{
public:
explicit CFRefScope(CFTypeRef ref)
: ref_(ref)
{
}
virtual ~CFRefScope()
{
try
{
::CFRelease(ref_);
}
catch(...)
{
}
}
private:
CFTypeRef ref_;
};
void invalidateAndReleaseEventStream(FSEventStreamRef streamRef)
{
::FSEventStreamInvalidate(streamRef);
::FSEventStreamRelease(streamRef);
}
void stopInvalidateAndReleaseEventStream(FSEventStreamRef streamRef)
{
::FSEventStreamStop(streamRef);
invalidateAndReleaseEventStream(streamRef);
}
// track active handles so we can implement unregisterAll
std::list<Handle> s_activeHandles;
} // anonymous namespace
namespace detail {
// register a new file monitor
void registerMonitor(const core::FilePath& filePath, const Callbacks& callbacks)
{
// allocate file path
std::string path = filePath.absolutePath();
CFStringRef filePathRef = ::CFStringCreateWithCString(
kCFAllocatorDefault,
filePath.absolutePath().c_str(),
kCFStringEncodingUTF8);
if (filePathRef == NULL)
{
callbacks.onRegistrationError(systemError(
boost::system::errc::not_enough_memory,
ERROR_LOCATION));
return;
}
CFRefScope filePathRefScope(filePathRef);
// allocate paths array
CFArrayRef pathsArrayRef = ::CFArrayCreate(kCFAllocatorDefault,
(const void **)&filePathRef,
1,
NULL);
if (pathsArrayRef == NULL)
{
callbacks.onRegistrationError(systemError(
boost::system::errc::not_enough_memory,
ERROR_LOCATION));
return;
}
CFRefScope pathsArrayRefScope(pathsArrayRef);
// create and allocate FileEventContext (create auto-ptr in case we
// return early, we'll call release later before returning)
FileEventContext* pContext = new FileEventContext();
std::auto_ptr<FileEventContext> autoPtrContext(pContext);
FSEventStreamContext context;
context.version = 0;
context.info = (void*) pContext;
context.retain = NULL;
context.release = NULL;
context.copyDescription = NULL;
// create the stream and save a reference to it
pContext->streamRef = ::FSEventStreamCreate(
kCFAllocatorDefault,
&fileEventCallback,
&context,
pathsArrayRef,
kFSEventStreamEventIdSinceNow,
1,
kFSEventStreamCreateFlagNoDefer |
kFSEventStreamCreateFlagWatchRoot);
if (pContext->streamRef == NULL)
{
callbacks.onRegistrationError(systemError(
boost::system::errc::no_stream_resources,
ERROR_LOCATION));
return;
}
// schedule with the run loop
::FSEventStreamScheduleWithRunLoop(pContext->streamRef,
::CFRunLoopGetCurrent(),
kCFRunLoopDefaultMode);
// start the event stream (check for errors and release if necessary
if (!::FSEventStreamStart(pContext->streamRef))
{
invalidateAndReleaseEventStream(pContext->streamRef);
callbacks.onRegistrationError(systemError(
boost::system::errc::no_stream_resources,
ERROR_LOCATION));
return;
}
// scan the files
Error error = scanFiles(FileInfo(filePath),
true,
&pContext->fileTree);
if (error)
{
// stop, invalidate, release
stopInvalidateAndReleaseEventStream(pContext->streamRef);
// return error
callbacks.onRegistrationError(error);
return;
}
// now that we have finished the file listing we know we have a valid
// file-monitor so set the onFilesChanged callback so that the
// client can receive events
pContext->onFilesChanged = callbacks.onFilesChanged;
// we are going to pass the context pointer to the client (as the Handle)
// so we release it here to relinquish ownership
autoPtrContext.release();
// track the handle
s_activeHandles.push_back((Handle*)pContext);
// notify the caller that we have successfully registered
callbacks.onRegistered((Handle)pContext, pContext->fileTree);
}
// unregister a file monitor
void unregisterMonitor(Handle handle)
{
// cast to context
FileEventContext* pContext = (FileEventContext*)handle;
// stop, invalidate, release
stopInvalidateAndReleaseEventStream(pContext->streamRef);
// untrack the handle
s_activeHandles.remove(handle);
// delete context
delete pContext;
}
void unregisterAll()
{
// make a copy of all active handles so we can unregister them
// (unregistering mutates the list so that's why we need a copy)
std::vector<Handle> activeHandles;
std::copy(s_activeHandles.begin(),
s_activeHandles.end(),
std::back_inserter(activeHandles));
// unregister all
std::for_each(activeHandles.begin(), activeHandles.end(), unregisterMonitor);
}
void run(const boost::function<void()>& checkForInput)
{
// ensure we have a run loop for this thread (not sure if this is
// strictly necessary but it is not harmful)
::CFRunLoopGetCurrent();
while (true)
{
// process the run loop for 1 second
SInt32 reason = ::CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, false);
// if we were stopped then break
if (reason == kCFRunLoopRunStopped)
{
unregisterAll();
break;
}
// check for input
checkForInput();
}
}
} // namespace detail
} // namespace file_monitor
} // namespace system
} // namespace core
<|endoftext|>
|
<commit_before>#include "gtest/gtest.h"
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/sync/interprocess_mutex.hpp>
#include <boost/interprocess/sync/interprocess_condition.hpp>
#include <cstdlib>
class SharedMemoryTest : public ::testing::Test
{
protected:
SharedMemoryTest()
{
}
virtual ~SharedMemoryTest()
{
// You can do clean-up work that doesn't throw exceptions here.
}
// If the constructor and destructor are not enough for setting up
// and cleaning up each test, you can define the following methods:
void SetUp() override
{
// Code here will be called immediately after the constructor (right
// before each test).
}
void TearDown() override
{
// Code here will be called immediately after each test (right
// before the destructor).
}
};
template <typename T>
using ShmAllocator = boost::interprocess::allocator<T, boost::interprocess::managed_shared_memory::segment_manager>;
struct ShmBlock
{
ShmBlock(bool can_process)
: can_process(can_process)
{
}
boost::interprocess::interprocess_mutex m;
boost::interprocess::interprocess_condition message_available;
boost::interprocess::interprocess_condition message_processed;
bool can_process;
};
struct Foo
{
Foo()
: value(0)
{
}
int value;
};
template <template <typename> class Allocator = std::allocator>
struct MessageT
{
MessageT(int v, const Allocator<uint8_t>& alloc = Allocator<uint8_t>())
: alloc_(alloc),
foo_alloc_(alloc),
int_values(alloc_), float_values(alloc_),
string_p(std::allocate_shared<std::string>(alloc, "init")),
raw_ptr(foo_alloc_.allocate(1))
{
int_values.push_back(v);
float_values.push_back(v*0.5);
raw_ptr->value = v * 20.0;
*string_p = std::string("foobarbaz") + std::to_string(v);
}
~MessageT()
{
foo_alloc_.deallocate(raw_ptr, 1);
}
Allocator<uint8_t> alloc_;
Allocator<Foo> foo_alloc_;
std::vector<int, Allocator<int>> int_values;
std::vector<float, Allocator<float>> float_values;
std::shared_ptr<std::string> string_p;
typename Allocator<Foo>::pointer raw_ptr;
};
//using Message = MessageT<ShmAllocator>;
using Message = MessageT<ShmAllocator>;
TEST_F(SharedMemoryTest, MessagesCanBeSentToSubprocess)
{
using namespace boost::interprocess;
//Remove shared memory on construction and destruction
struct shm_remove
{
shm_remove() { remove(); }
~shm_remove(){ remove(); }
void remove()
{
shared_memory_object::remove("csapex::test_node_0::shm");
}
} remover;
//Create a managed shared memory segment
managed_shared_memory segment(create_only, "csapex::test_node_0::shm", 65536);
ShmBlock* shm = segment.construct<ShmBlock>("shm")(false);
ASSERT_NE(nullptr, shm);
const ShmAllocator<int> alloc_inst (segment.get_segment_manager());
pid_t pid = fork();
if (pid == 0)
{
// CHILD
{
scoped_lock<interprocess_mutex> lock(shm->m);
// wait for a message
while(!shm->can_process) {
shm->message_available.wait(lock);
}
//Get buffer local address from handle
std::pair<Message*, managed_shared_memory::size_type> msg_data
= segment.find<Message> ("in/msg_0");
Message* msg = msg_data.first;
if(msg) {
if(msg->int_values.size() > 0 && msg->int_values.at(0) == 23) {
segment.construct<Message>
("out/msg_0")
(42, alloc_inst);
}
} else {
std::cout << "child: no message received" << std::endl;
}
shm->message_processed.notify_all();
}
std::quick_exit(0);
} else {
// PARENT
// notify child process
{
scoped_lock<interprocess_mutex> lock(shm->m);
// create shm marker block
// send message to child process
Message *msg = segment.construct<Message>
("in/msg_0")
(23, alloc_inst);
ASSERT_NE(nullptr, msg);
ASSERT_EQ("foobarbaz23", *msg->string_p);
ASSERT_NEAR(23*20, msg->raw_ptr->value, 0.001);
shm->can_process = true;
shm->message_available.notify_all();
shm->message_processed.wait(lock);
Message* res = segment.find<Message> ("out/msg_0").first;
ASSERT_NE(nullptr, res);
ASSERT_EQ(42, res->int_values.at(0));
ASSERT_NEAR(42*0.5, res->float_values.at(0), 0.001);
ASSERT_NEAR(42*20, res->raw_ptr->value, 0.001);
ASSERT_EQ("foobarbaz42", *res->string_p);
//Deallocate previously allocated memory
segment.destroy<Message>("in/msg_0");
segment.destroy<Message>("out/msg_0");
}
segment.destroy<ShmBlock>("shm");
// Check memory has been freed
ASSERT_EQ(nullptr, segment.find<Message>("in/msg_0").first);
}
}
<commit_msg>Adjusted the shared memory test case for older GCC versions<commit_after>#include "gtest/gtest.h"
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/sync/interprocess_mutex.hpp>
#include <boost/interprocess/sync/interprocess_condition.hpp>
#include <cstdlib>
#include <scoped_allocator>
#include <boost/interprocess/containers/string.hpp>
class SharedMemoryTest : public ::testing::Test
{
protected:
SharedMemoryTest()
{
}
virtual ~SharedMemoryTest()
{
// You can do clean-up work that doesn't throw exceptions here.
}
// If the constructor and destructor are not enough for setting up
// and cleaning up each test, you can define the following methods:
void SetUp() override
{
// Code here will be called immediately after the constructor (right
// before each test).
}
void TearDown() override
{
// Code here will be called immediately after each test (right
// before the destructor).
}
};
template <typename T>
using ShmAllocator = boost::interprocess::allocator<T, boost::interprocess::managed_shared_memory::segment_manager>;
struct ShmBlock
{
ShmBlock(bool can_process)
: can_process(can_process)
{
}
boost::interprocess::interprocess_mutex m;
boost::interprocess::interprocess_condition message_available;
boost::interprocess::interprocess_condition message_processed;
bool can_process;
};
struct Foo
{
Foo()
: value(0)
{
}
int value;
};
template <template <typename> class Allocator = std::allocator>
struct MessageT
{
template <typename T>
using ScopedAllocator = typename std::scoped_allocator_adaptor<Allocator<T>>;
MessageT(int v, const ScopedAllocator<uint8_t>& alloc = ScopedAllocator<uint8_t>())
: alloc_(alloc),
foo_alloc_(alloc),
string_alloc_(alloc),
int_values(alloc_), float_values(alloc_),
string_p(alloc),
raw_ptr(foo_alloc_.allocate(1))
{
int_values.push_back(v);
float_values.push_back(v*0.5);
raw_ptr->value = v * 20.0;
std::string string = std::string("foobarbaz") + std::to_string(v);
string_p.assign(string.begin(), string.end());
}
~MessageT()
{
foo_alloc_.deallocate(raw_ptr, 1);
}
using shared_string = typename boost::interprocess::basic_string<char, std::char_traits<char>, ScopedAllocator<char>>;
ScopedAllocator<uint8_t>alloc_;
ScopedAllocator<Foo> foo_alloc_;
ScopedAllocator<shared_string> string_alloc_;
std::vector<int, ScopedAllocator<int>> int_values;
std::vector<float, ScopedAllocator<float>> float_values;
shared_string string_p;
typename Allocator<Foo>::pointer raw_ptr;
};
//using Message = MessageT<ShmAllocator>;
using Message = MessageT<ShmAllocator>;
TEST_F(SharedMemoryTest, MessagesCanBeSentToSubprocess)
{
using namespace boost::interprocess;
//Remove shared memory on construction and destruction
struct shm_remove
{
shm_remove() { remove(); }
~shm_remove(){ remove(); }
void remove()
{
shared_memory_object::remove("csapex::test_node_0::shm");
}
} remover;
//Create a managed shared memory segment
managed_shared_memory segment(create_only, "csapex::test_node_0::shm", 65536);
ShmBlock* shm = segment.construct<ShmBlock>("shm")(false);
ASSERT_NE(nullptr, shm);
const ShmAllocator<int> alloc_inst (segment.get_segment_manager());
pid_t pid = fork();
if (pid == 0)
{
// CHILD
{
scoped_lock<interprocess_mutex> lock(shm->m);
// wait for a message
while(!shm->can_process) {
shm->message_available.wait(lock);
}
//Get buffer local address from handle
std::pair<Message*, managed_shared_memory::size_type> msg_data
= segment.find<Message> ("in/msg_0");
Message* msg = msg_data.first;
if(msg) {
if(msg->int_values.size() > 0 && msg->int_values.at(0) == 23) {
segment.construct<Message>
("out/msg_0")
(42, alloc_inst);
}
} else {
std::cout << "child: no message received" << std::endl;
}
shm->message_processed.notify_all();
}
std::quick_exit(0);
} else {
// PARENT
// notify child process
{
scoped_lock<interprocess_mutex> lock(shm->m);
// create shm marker block
// send message to child process
Message *msg = segment.construct<Message>
("in/msg_0")
(23, alloc_inst);
ASSERT_NE(nullptr, msg);
ASSERT_EQ("foobarbaz23", msg->string_p);
ASSERT_NEAR(23*20, msg->raw_ptr->value, 0.001);
shm->can_process = true;
shm->message_available.notify_all();
shm->message_processed.wait(lock);
Message* res = segment.find<Message> ("out/msg_0").first;
ASSERT_NE(nullptr, res);
ASSERT_EQ(42, res->int_values.at(0));
ASSERT_NEAR(42*0.5, res->float_values.at(0), 0.001);
ASSERT_NEAR(42*20, res->raw_ptr->value, 0.001);
ASSERT_EQ("foobarbaz42", res->string_p);
//Deallocate previously allocated memory
segment.destroy<Message>("in/msg_0");
segment.destroy<Message>("out/msg_0");
}
segment.destroy<ShmBlock>("shm");
// Check memory has been freed
ASSERT_EQ(nullptr, segment.find<Message>("in/msg_0").first);
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2007-2020 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* 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.
*
* 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
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "AcmeClient.hxx"
#include "AcmeChallenge.hxx"
#include "AcmeError.hxx"
#include "AcmeConfig.hxx"
#include "JWS.hxx"
#include "ssl/Base64.hxx"
#include "ssl/Certificate.hxx"
#include "ssl/Key.hxx"
#include "uri/Extract.hxx"
#include "util/Exception.hxx"
#include "util/RuntimeError.hxx"
#include <json/json.h>
#include <memory>
#include <sstream>
gcc_pure
static bool
IsJson(const GlueHttpResponse &response) noexcept
{
auto i = response.headers.find("content-type");
if (i == response.headers.end())
return false;
const char *content_type = i->second.c_str();
return strcmp(content_type, "application/json") == 0 ||
strcmp(content_type, "application/problem+json") == 0;
}
gcc_pure
static Json::Value
ParseJson(std::string &&s) noexcept
{
Json::Value root;
std::stringstream(std::move(s)) >> root;
return root;
}
gcc_pure
static Json::Value
ParseJson(GlueHttpResponse &&response)
{
if (!IsJson(response))
throw std::runtime_error("JSON expected");
return ParseJson(std::move(response.body));
}
/**
* Throw an exception if the given JSON document contains an "error"
* element.
*/
static void
CheckThrowError(const Json::Value &root, const char *msg)
{
const auto &error = root["error"];
if (error.isNull())
return;
std::rethrow_exception(NestException(std::make_exception_ptr(AcmeError(error)),
std::runtime_error(msg)));
}
/**
* Throw an exception, adding "detail" from the JSON document (if the
* response is JSON).
*/
gcc_noreturn
static void
ThrowError(GlueHttpResponse &&response, const char *msg)
{
if (IsJson(response)) {
const auto root = ParseJson(std::move(response.body));
std::rethrow_exception(NestException(std::make_exception_ptr(AcmeError(root)),
std::runtime_error(msg)));
}
throw std::runtime_error(msg);
}
/**
* Throw an exception due to unexpected status.
*/
gcc_noreturn
static void
ThrowStatusError(GlueHttpResponse &&response, const char *msg)
{
std::string what(msg);
what += " (";
what += http_status_to_string(response.status);
what += ")";
ThrowError(std::move(response), what.c_str());
}
/**
* Check the status, and if it's not the expected one, throw an
* exception.
*/
static void
CheckThrowStatusError(GlueHttpResponse &&response,
http_status_t expected_status,
const char *msg)
{
if (response.status != expected_status)
ThrowStatusError(std::move(response), msg);
}
AcmeClient::AcmeClient(const AcmeConfig &config) noexcept
:glue_http_client(event_loop),
server(config.staging
? "https://acme-staging.api.letsencrypt.org"
: "https://acme-v01.api.letsencrypt.org"),
agreement_url(config.agreement_url),
fake(config.fake)
{
if (config.debug)
glue_http_client.EnableVerbose();
}
AcmeClient::~AcmeClient() noexcept = default;
std::string
AcmeClient::RequestNonce()
{
if (fake)
return "foo";
unsigned remaining_tries = 3;
while (true) {
auto response = glue_http_client.Request(event_loop,
HTTP_METHOD_HEAD,
(server + "/directory").c_str(),
nullptr);
if (response.status != HTTP_STATUS_OK) {
if (http_status_is_server_error(response.status) &&
--remaining_tries > 0)
/* try again, just in case it's a temporary Let's
Encrypt hiccup */
continue;
throw FormatRuntimeError("Unexpected response status %d",
response.status);
}
auto nonce = response.headers.find("replay-nonce");
if (nonce == response.headers.end())
throw std::runtime_error("No Replay-Nonce response header");
return nonce->second.c_str();
}
}
std::string
AcmeClient::NextNonce()
{
if (next_nonce.empty())
next_nonce = RequestNonce();
std::string result;
std::swap(result, next_nonce);
return result;
}
static std::string
MakeHeader(EVP_PKEY &key) noexcept
{
auto jwk = MakeJwk(key);
std::string header("{\"alg\": \"RS256\", \"jwk\": ");
header += jwk;
header += "}";
return header;
}
static std::string
WithNonce(const std::string &_header, const std::string &nonce) noexcept
{
std::string header(_header);
assert(header.size() > 8);
size_t i = header.length() - 1;
std::string s(", \"nonce\": \"");
s += nonce;
s += "\"";
header.insert(i, s);
return header;
}
static AllocatedString<>
Sign(EVP_PKEY &key, ConstBuffer<void> data)
{
UniqueEVP_PKEY_CTX ctx(EVP_PKEY_CTX_new(&key, nullptr));
if (!ctx)
throw SslError("EVP_PKEY_CTX_new() failed");
if (EVP_PKEY_sign_init(ctx.get()) <= 0)
throw SslError("EVP_PKEY_sign_init() failed");
if (EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PADDING) <= 0)
throw SslError("EVP_PKEY_CTX_set_rsa_padding() failed");
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-qual"
if (EVP_PKEY_CTX_set_signature_md(ctx.get(), EVP_sha256()) <= 0)
throw SslError("EVP_PKEY_CTX_set_signature_md() failed");
#pragma GCC diagnostic pop
unsigned char md[SHA256_DIGEST_LENGTH];
SHA256((const unsigned char *)data.data, data.size, md);
size_t length;
if (EVP_PKEY_sign(ctx.get(), nullptr, &length, md, sizeof(md)) <= 0)
throw SslError("EVP_PKEY_sign() failed");
std::unique_ptr<unsigned char[]> buffer(new unsigned char[length]);
if (EVP_PKEY_sign(ctx.get(), buffer.get(), &length, md, sizeof(md)) <= 0)
throw SslError("EVP_PKEY_sign() failed");
return UrlSafeBase64(ConstBuffer<void>(buffer.get(), length));
}
static AllocatedString<>
Sign(EVP_PKEY &key, const char *protected_header_b64, const char *payload_b64)
{
std::string data(protected_header_b64);
data += '.';
data += payload_b64;
return Sign(key, ConstBuffer<void>(data.data(), data.length()));
}
GlueHttpResponse
AcmeClient::Request(http_method_t method, const char *uri,
ConstBuffer<void> body)
{
auto response = fake
? FakeRequest(method, uri, body)
: glue_http_client.Request(event_loop,
method, (server + uri).c_str(),
body);
auto new_nonce = response.headers.find("replay-nonce");
if (new_nonce != response.headers.end())
next_nonce = std::move(new_nonce->second);
return response;
}
GlueHttpResponse
AcmeClient::SignedRequest(EVP_PKEY &key,
http_method_t method, const char *uri,
ConstBuffer<void> payload)
{
const auto payload_b64 = UrlSafeBase64(payload);
const auto header = MakeHeader(key);
const auto nonce = NextNonce();
const auto protected_header = WithNonce(header, nonce);
const auto protected_header_b64 = UrlSafeBase64(protected_header);
const auto signature = Sign(key, protected_header_b64.c_str(),
payload_b64.c_str());
std::string body = "{\"signature\": \"";
body += signature.c_str();
body += "\", \"payload\": \"";
body += payload_b64.c_str();
body += "\", \"header\": ";
body += header;
body += ", \"protected\": \"";
body += protected_header_b64.c_str();
body += "\"}";
return Request(method, uri,
{body.data(), body.length()});
}
AcmeClient::Account
AcmeClient::NewReg(EVP_PKEY &key, const char *email)
{
std::string payload("{\"resource\": \"new-reg\", ");
if (email != nullptr) {
payload += "\"contact\": [ \"mailto:";
payload += email;
payload += "\" ], ";
}
payload += "\"agreement\": \"";
payload += agreement_url;
payload += "\"}";
auto response = SignedRequestRetry(key,
HTTP_METHOD_POST, "/acme/new-reg",
payload.c_str());
CheckThrowStatusError(std::move(response), HTTP_STATUS_CREATED,
"Failed to register account");
Account account;
auto location = response.headers.find("location");
if (location != response.headers.end())
account.location = std::move(location->second);
return account;
}
static const Json::Value &
FindInArray(const Json::Value &v, const char *key, const char *value)
{
for (const auto &i : v) {
const auto &l = i[key];
if (!l.isNull() && l.asString() == value)
return i;
}
return Json::Value::null;
}
AcmeChallenge
AcmeClient::NewAuthz(EVP_PKEY &key, const char *host,
const char *challenge_type)
{
std::string payload("{\"resource\": \"new-authz\", "
"\"identifier\": { "
"\"type\": \"dns\", "
"\"value\": \"");
payload += host;
payload += "\" } }";
auto response = SignedRequestRetry(key,
HTTP_METHOD_POST, "/acme/new-authz",
payload.c_str());
CheckThrowStatusError(std::move(response), HTTP_STATUS_CREATED,
"Failed to create authz");
const auto root = ParseJson(std::move(response));
CheckThrowError(root, "Failed to create authz");
const auto &challenge = FindInArray(root["challenges"],
"type", challenge_type);
if (challenge.isNull())
throw FormatRuntimeError("No %s challenge", challenge_type);
const auto &token = challenge["token"];
if (!token.isString())
throw FormatRuntimeError("No %s token", challenge_type);
const auto &uri = challenge["uri"];
if (!uri.isString())
throw FormatRuntimeError("No %s uri", challenge_type);
return {challenge_type, token.asString(), uri.asString()};
}
bool
AcmeClient::UpdateAuthz(EVP_PKEY &key, const AcmeChallenge &authz)
{
const char *uri = uri_path(authz.uri.c_str());
if (uri == nullptr)
throw std::runtime_error("Malformed URI in AcmeChallenge");
std::string payload("{ \"resource\": \"challenge\", "
"\"type\": \"");
payload += authz.type;
payload += "\", \"keyAuthorization\": \"";
payload += authz.token;
payload += '.';
payload += UrlSafeBase64SHA256(MakeJwk(key)).c_str();
payload += "\" }";
auto response = SignedRequestRetry(key,
HTTP_METHOD_POST, uri,
payload.c_str());
CheckThrowStatusError(std::move(response), HTTP_STATUS_ACCEPTED,
"Failed to update authz");
auto root = ParseJson(std::move(response));
CheckThrowError(root, "Failed to update authz");
return root["status"].asString() != "pending";
}
bool
AcmeClient::CheckAuthz(const AcmeChallenge &authz)
{
const char *uri = uri_path(authz.uri.c_str());
if (uri == nullptr)
throw std::runtime_error("Malformed URI in AcmeChallenge");
auto response = Request(HTTP_METHOD_GET, uri,
nullptr);
CheckThrowStatusError(std::move(response), HTTP_STATUS_ACCEPTED,
"Failed to check authz");
auto root = ParseJson(std::move(response));
CheckThrowError(root, "Failed to check authz");
return root["status"].asString() != "pending";
}
UniqueX509
AcmeClient::NewCert(EVP_PKEY &key, X509_REQ &req)
{
std::string payload("{\"resource\": \"new-cert\", "
"\"csr\": \"");
payload += UrlSafeBase64(req).c_str();
payload += "\" }";
auto response = SignedRequestRetry(key,
HTTP_METHOD_POST, "/acme/new-cert",
payload.c_str());
CheckThrowStatusError(std::move(response), HTTP_STATUS_CREATED,
"Failed to create certificate");
return DecodeDerCertificate({response.body.data(), response.body.length()});
}
<commit_msg>certdb/AcmeClient: recognize status 200 on new-reg<commit_after>/*
* Copyright 2007-2020 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* 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.
*
* 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
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "AcmeClient.hxx"
#include "AcmeChallenge.hxx"
#include "AcmeError.hxx"
#include "AcmeConfig.hxx"
#include "JWS.hxx"
#include "ssl/Base64.hxx"
#include "ssl/Certificate.hxx"
#include "ssl/Key.hxx"
#include "uri/Extract.hxx"
#include "util/Exception.hxx"
#include "util/RuntimeError.hxx"
#include <json/json.h>
#include <memory>
#include <sstream>
gcc_pure
static bool
IsJson(const GlueHttpResponse &response) noexcept
{
auto i = response.headers.find("content-type");
if (i == response.headers.end())
return false;
const char *content_type = i->second.c_str();
return strcmp(content_type, "application/json") == 0 ||
strcmp(content_type, "application/problem+json") == 0;
}
gcc_pure
static Json::Value
ParseJson(std::string &&s) noexcept
{
Json::Value root;
std::stringstream(std::move(s)) >> root;
return root;
}
gcc_pure
static Json::Value
ParseJson(GlueHttpResponse &&response)
{
if (!IsJson(response))
throw std::runtime_error("JSON expected");
return ParseJson(std::move(response.body));
}
/**
* Throw an exception if the given JSON document contains an "error"
* element.
*/
static void
CheckThrowError(const Json::Value &root, const char *msg)
{
const auto &error = root["error"];
if (error.isNull())
return;
std::rethrow_exception(NestException(std::make_exception_ptr(AcmeError(error)),
std::runtime_error(msg)));
}
/**
* Throw an exception, adding "detail" from the JSON document (if the
* response is JSON).
*/
gcc_noreturn
static void
ThrowError(GlueHttpResponse &&response, const char *msg)
{
if (IsJson(response)) {
const auto root = ParseJson(std::move(response.body));
std::rethrow_exception(NestException(std::make_exception_ptr(AcmeError(root)),
std::runtime_error(msg)));
}
throw std::runtime_error(msg);
}
/**
* Throw an exception due to unexpected status.
*/
gcc_noreturn
static void
ThrowStatusError(GlueHttpResponse &&response, const char *msg)
{
std::string what(msg);
what += " (";
what += http_status_to_string(response.status);
what += ")";
ThrowError(std::move(response), what.c_str());
}
/**
* Check the status, and if it's not the expected one, throw an
* exception.
*/
static void
CheckThrowStatusError(GlueHttpResponse &&response,
http_status_t expected_status,
const char *msg)
{
if (response.status != expected_status)
ThrowStatusError(std::move(response), msg);
}
AcmeClient::AcmeClient(const AcmeConfig &config) noexcept
:glue_http_client(event_loop),
server(config.staging
? "https://acme-staging.api.letsencrypt.org"
: "https://acme-v01.api.letsencrypt.org"),
agreement_url(config.agreement_url),
fake(config.fake)
{
if (config.debug)
glue_http_client.EnableVerbose();
}
AcmeClient::~AcmeClient() noexcept = default;
std::string
AcmeClient::RequestNonce()
{
if (fake)
return "foo";
unsigned remaining_tries = 3;
while (true) {
auto response = glue_http_client.Request(event_loop,
HTTP_METHOD_HEAD,
(server + "/directory").c_str(),
nullptr);
if (response.status != HTTP_STATUS_OK) {
if (http_status_is_server_error(response.status) &&
--remaining_tries > 0)
/* try again, just in case it's a temporary Let's
Encrypt hiccup */
continue;
throw FormatRuntimeError("Unexpected response status %d",
response.status);
}
auto nonce = response.headers.find("replay-nonce");
if (nonce == response.headers.end())
throw std::runtime_error("No Replay-Nonce response header");
return nonce->second.c_str();
}
}
std::string
AcmeClient::NextNonce()
{
if (next_nonce.empty())
next_nonce = RequestNonce();
std::string result;
std::swap(result, next_nonce);
return result;
}
static std::string
MakeHeader(EVP_PKEY &key) noexcept
{
auto jwk = MakeJwk(key);
std::string header("{\"alg\": \"RS256\", \"jwk\": ");
header += jwk;
header += "}";
return header;
}
static std::string
WithNonce(const std::string &_header, const std::string &nonce) noexcept
{
std::string header(_header);
assert(header.size() > 8);
size_t i = header.length() - 1;
std::string s(", \"nonce\": \"");
s += nonce;
s += "\"";
header.insert(i, s);
return header;
}
static AllocatedString<>
Sign(EVP_PKEY &key, ConstBuffer<void> data)
{
UniqueEVP_PKEY_CTX ctx(EVP_PKEY_CTX_new(&key, nullptr));
if (!ctx)
throw SslError("EVP_PKEY_CTX_new() failed");
if (EVP_PKEY_sign_init(ctx.get()) <= 0)
throw SslError("EVP_PKEY_sign_init() failed");
if (EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PADDING) <= 0)
throw SslError("EVP_PKEY_CTX_set_rsa_padding() failed");
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-qual"
if (EVP_PKEY_CTX_set_signature_md(ctx.get(), EVP_sha256()) <= 0)
throw SslError("EVP_PKEY_CTX_set_signature_md() failed");
#pragma GCC diagnostic pop
unsigned char md[SHA256_DIGEST_LENGTH];
SHA256((const unsigned char *)data.data, data.size, md);
size_t length;
if (EVP_PKEY_sign(ctx.get(), nullptr, &length, md, sizeof(md)) <= 0)
throw SslError("EVP_PKEY_sign() failed");
std::unique_ptr<unsigned char[]> buffer(new unsigned char[length]);
if (EVP_PKEY_sign(ctx.get(), buffer.get(), &length, md, sizeof(md)) <= 0)
throw SslError("EVP_PKEY_sign() failed");
return UrlSafeBase64(ConstBuffer<void>(buffer.get(), length));
}
static AllocatedString<>
Sign(EVP_PKEY &key, const char *protected_header_b64, const char *payload_b64)
{
std::string data(protected_header_b64);
data += '.';
data += payload_b64;
return Sign(key, ConstBuffer<void>(data.data(), data.length()));
}
GlueHttpResponse
AcmeClient::Request(http_method_t method, const char *uri,
ConstBuffer<void> body)
{
auto response = fake
? FakeRequest(method, uri, body)
: glue_http_client.Request(event_loop,
method, (server + uri).c_str(),
body);
auto new_nonce = response.headers.find("replay-nonce");
if (new_nonce != response.headers.end())
next_nonce = std::move(new_nonce->second);
return response;
}
GlueHttpResponse
AcmeClient::SignedRequest(EVP_PKEY &key,
http_method_t method, const char *uri,
ConstBuffer<void> payload)
{
const auto payload_b64 = UrlSafeBase64(payload);
const auto header = MakeHeader(key);
const auto nonce = NextNonce();
const auto protected_header = WithNonce(header, nonce);
const auto protected_header_b64 = UrlSafeBase64(protected_header);
const auto signature = Sign(key, protected_header_b64.c_str(),
payload_b64.c_str());
std::string body = "{\"signature\": \"";
body += signature.c_str();
body += "\", \"payload\": \"";
body += payload_b64.c_str();
body += "\", \"header\": ";
body += header;
body += ", \"protected\": \"";
body += protected_header_b64.c_str();
body += "\"}";
return Request(method, uri,
{body.data(), body.length()});
}
AcmeClient::Account
AcmeClient::NewReg(EVP_PKEY &key, const char *email)
{
std::string payload("{\"resource\": \"new-reg\", ");
if (email != nullptr) {
payload += "\"contact\": [ \"mailto:";
payload += email;
payload += "\" ], ";
}
payload += "\"agreement\": \"";
payload += agreement_url;
payload += "\"}";
auto response = SignedRequestRetry(key,
HTTP_METHOD_POST, "/acme/new-reg",
payload.c_str());
if (response.status == HTTP_STATUS_OK)
throw std::runtime_error("This key is already registered");
CheckThrowStatusError(std::move(response), HTTP_STATUS_CREATED,
"Failed to register account");
Account account;
auto location = response.headers.find("location");
if (location != response.headers.end())
account.location = std::move(location->second);
return account;
}
static const Json::Value &
FindInArray(const Json::Value &v, const char *key, const char *value)
{
for (const auto &i : v) {
const auto &l = i[key];
if (!l.isNull() && l.asString() == value)
return i;
}
return Json::Value::null;
}
AcmeChallenge
AcmeClient::NewAuthz(EVP_PKEY &key, const char *host,
const char *challenge_type)
{
std::string payload("{\"resource\": \"new-authz\", "
"\"identifier\": { "
"\"type\": \"dns\", "
"\"value\": \"");
payload += host;
payload += "\" } }";
auto response = SignedRequestRetry(key,
HTTP_METHOD_POST, "/acme/new-authz",
payload.c_str());
CheckThrowStatusError(std::move(response), HTTP_STATUS_CREATED,
"Failed to create authz");
const auto root = ParseJson(std::move(response));
CheckThrowError(root, "Failed to create authz");
const auto &challenge = FindInArray(root["challenges"],
"type", challenge_type);
if (challenge.isNull())
throw FormatRuntimeError("No %s challenge", challenge_type);
const auto &token = challenge["token"];
if (!token.isString())
throw FormatRuntimeError("No %s token", challenge_type);
const auto &uri = challenge["uri"];
if (!uri.isString())
throw FormatRuntimeError("No %s uri", challenge_type);
return {challenge_type, token.asString(), uri.asString()};
}
bool
AcmeClient::UpdateAuthz(EVP_PKEY &key, const AcmeChallenge &authz)
{
const char *uri = uri_path(authz.uri.c_str());
if (uri == nullptr)
throw std::runtime_error("Malformed URI in AcmeChallenge");
std::string payload("{ \"resource\": \"challenge\", "
"\"type\": \"");
payload += authz.type;
payload += "\", \"keyAuthorization\": \"";
payload += authz.token;
payload += '.';
payload += UrlSafeBase64SHA256(MakeJwk(key)).c_str();
payload += "\" }";
auto response = SignedRequestRetry(key,
HTTP_METHOD_POST, uri,
payload.c_str());
CheckThrowStatusError(std::move(response), HTTP_STATUS_ACCEPTED,
"Failed to update authz");
auto root = ParseJson(std::move(response));
CheckThrowError(root, "Failed to update authz");
return root["status"].asString() != "pending";
}
bool
AcmeClient::CheckAuthz(const AcmeChallenge &authz)
{
const char *uri = uri_path(authz.uri.c_str());
if (uri == nullptr)
throw std::runtime_error("Malformed URI in AcmeChallenge");
auto response = Request(HTTP_METHOD_GET, uri,
nullptr);
CheckThrowStatusError(std::move(response), HTTP_STATUS_ACCEPTED,
"Failed to check authz");
auto root = ParseJson(std::move(response));
CheckThrowError(root, "Failed to check authz");
return root["status"].asString() != "pending";
}
UniqueX509
AcmeClient::NewCert(EVP_PKEY &key, X509_REQ &req)
{
std::string payload("{\"resource\": \"new-cert\", "
"\"csr\": \"");
payload += UrlSafeBase64(req).c_str();
payload += "\" }";
auto response = SignedRequestRetry(key,
HTTP_METHOD_POST, "/acme/new-cert",
payload.c_str());
CheckThrowStatusError(std::move(response), HTTP_STATUS_CREATED,
"Failed to create certificate");
return DecodeDerCertificate({response.body.data(), response.body.length()});
}
<|endoftext|>
|
<commit_before>#include <map>
#include <iostream>
#include <stdlib.h>
using namespace std;
float* def_variables(int ecozone, int forestmodel_data, int ifl, int climate, int plant_data, int lossyr)
{
int model_years; // How many loss years are in the model
model_years = 15;
int tropical; // The ecozone code for the tropics
tropical = 1;
int temperate; // The ecozone code for the temperate zone
temperate = 3;
int boreal; // The ecozone code for the boreal zone
boreal = 2;
// returns Cf, CO2, CH4, N2O, peatburn, peat_drain_total
float Cf;
float CO2;
float CH4;
float N2O;
float peatburn;
float peat_drain_annual;
float peat_drain_total;
if ((forestmodel_data == 1) || (forestmodel_data == 2) || (forestmodel_data == 5)) // Commodities, shifting ag., or urbanization
{
if (ecozone == boreal) // Commodities/shifting ag/urbanization, boreal
{
Cf = 0.59;
CO2 = 1569;
CH4 = 4.7;
N2O = 0.26;
peatburn = 41;
peat_drain_total = (model_years - lossyr) * 36;
}
else if (ecozone == temperate)// Commodities/shifting ag/urbanization, temperate
{
Cf = 0.51;
CO2 = 1569;
CH4 = 4.7;
N2O = 0.26;
peatburn = 41;
peat_drain_total = (model_years - lossyr) * 31;
}
else if (ecozone == tropical) // Commodities/shifting ag/urbanization, tropics
{
CO2 = 1580;
CH4 = 6.8;
N2O = 0.2;
peatburn = 163;
if (plant_data == 1) // Commodities/shifting ag/urbanization, tropics, oil palm
{
peat_drain_annual = 47;
}
else if (plant_data == 2) // Commodities/shifting ag/urbanization, tropics, wood fiber
{
peat_drain_annual = 80;
}
else // Commodities/shifting ag/urbanization, tropics, other plantation or no plantation
{
peat_drain_annual = 62;
}
peat_drain_total = (model_years - lossyr) * peat_drain_annual;
if (ifl > 0) // Commodities/shifting ag/urbanization, tropics, in IFL
{
Cf = 0.36;
}
else // Commodities/shifting ag/urbanization, tropics, outside IFL
{
Cf = 0.55;
}
}
cout << "ecozone: " << ecozone << endl;
cout << "forestmodel_data: " << forestmodel_data << endl;
cout << "ifl: " << ifl << endl;
cout << "climate: " << climate << endl;
cout << "plant_data: " << plant_data << endl;
cout << "model_years: " << model_years << endl;
cout << "loss_yr: " << lossyr << endl;
cout << "peat_drain_annual: " << peat_drain_annual << endl;
cout << "peat_drain_total: " << peat_drain_total << endl;
}
else if (forestmodel_data == 3) // Forestry
{
if (ecozone == boreal) // Forestry, boreal
{
Cf = 0.33;
CO2 = 1569;
CH4 = 4.7;
N2O = 0.26;
peatburn = 41;
peat_drain_total = (model_years - lossyr) * 3;
}
else if (ecozone == temperate)// Forestry, temperate
{
Cf = 0.62;
CO2 = 1569;
CH4 = 4.7;
N2O = 0.26;
peatburn = 41;
peat_drain_total = (model_years - lossyr) * 12;
}
else if (ecozone == tropical) // Forestry, tropics
{
CO2 = 1580;
CH4 = 6.8;
N2O = 0.2;
peatburn = 163;
if (plant_data == 1) // Forestry, tropics, oil palm
{
peat_drain_annual = 45;
}
else if (plant_data == 2) // Forestry, tropics, wood fiber
{
peat_drain_annual = 79;
}
else // Forestry, tropics, other plantation or no plantation
{
peat_drain_annual = 60;
}
peat_drain_total = (model_years - lossyr) * peat_drain_annual;
if (ifl > 0)
{
Cf = 0.36; // Forestry, tropics, in IFL
}
else
{
Cf = 0.55; // Forestry, tropics, outside IFL
}
}
cout << "ecozone: " << ecozone << endl;
cout << "forestmodel_data: " << forestmodel_data << endl;
cout << "ifl: " << ifl << endl;
cout << "climate: " << climate << endl;
cout << "plant_data: " << plant_data << endl;
cout << "model_years: " << model_years << endl;
cout << "loss_yr: " << lossyr << endl;
cout << "peat_drain_annual: " << peat_drain_annual << endl;
cout << "peat_drain_total: " << peat_drain_total << endl;
}
else if (forestmodel_data == 4) // Wildfire
{
if (ecozone == boreal) // Wildfire, boreal
{
Cf = 0.59;
CO2 = 1569;
CH4 = 4.7;
N2O = 0.26;
peatburn = 41;
peat_drain_total = (model_years - lossyr) * 3;
}
else if (ecozone == temperate)// Wildfire, temperate
{
Cf = 0.51;
CO2 = 1569;
CH4 = 4.7;
N2O = 0.26;
peatburn = 41;
peat_drain_total = (model_years - lossyr) * 12;
}
else if (ecozone == tropical) // Wildfire, tropics
{
CO2 = 1580;
CH4 = 6.8;
N2O = 0.2;
peatburn = 371;
if (plant_data == 1) // Wildfire, tropics, oil palm
{
peat_drain_annual = 45;
}
else if (plant_data == 2) // Wildfire, tropics, wood fiber
{
peat_drain_annual = 79;
}
else // Wildfire, tropics, other plantation or no plantation
{
peat_drain_annual = 60;
}
peat_drain_total = (model_years - lossyr) * peat_drain_annual;
if (ifl > 0) // Wildfire, tropics, in IFL
{
Cf = 0.36;
}
else // Wildfire, tropics, outside IFL
{
Cf = 0.55;
}
}
cout << "ecozone: " << ecozone << endl;
cout << "forestmodel_data: " << forestmodel_data << endl;
cout << "ifl: " << ifl << endl;
cout << "climate: " << climate << endl;
cout << "plant_data: " << plant_data << endl;
cout << "model_years: " << model_years << endl;
cout << "loss_yr: " << lossyr << endl;
cout << "peat_drain_annual: " << peat_drain_annual << endl;
cout << "peat_drain_total: " << peat_drain_total << endl;
}
else // No driver-- same as forestry
{
if (ecozone == boreal) // No driver, boreal
{
Cf = 0.33;
CO2 = 1569;
CH4 = 4.7;
N2O = 0.26;
peatburn = 41;
peat_drain_total = (model_years - lossyr) * 3;
}
else if (ecozone == temperate)// No driver, temperate
{
Cf = 0.62;
CO2 = 1569;
CH4 = 4.7;
N2O = 0.26;
peatburn = 41;
peat_drain_total = (model_years - lossyr) * 12;
}
else if (ecozone == tropical) // No driver, tropics
{
CO2 = 1580;
CH4 = 6.8;
N2O = 0.2;
peatburn = 163;
if (plant_data == 1) // No driver, tropics, oil palm
{
peat_drain_annual = 45;
}
else if (plant_data == 2) // No driver, tropics, wood fiber
{
peat_drain_annual = 79;
}
else // No driver, tropics, other plantation or no plantation
{
peat_drain_annual = 60;
}
peat_drain_total = (model_years - lossyr) * peat_drain_annual;
if (ifl > 0)
{
Cf = 0.36; // No driver, tropics, in IFL
}
else
{
Cf = 0.55; // No driver, tropics, outside IFL
}
}
cout << "ecozone: " << ecozone << endl;
cout << "forestmodel_data: " << forestmodel_data << endl;
cout << "ifl: " << ifl << endl;
cout << "climate: " << climate << endl;
cout << "plant_data: " << plant_data << endl;
cout << "model_years: " << model_years << endl;
cout << "loss_yr: " << lossyr << endl;
cout << "peat_drain_annual: " << peat_drain_annual << endl;
cout << "peat_drain_total: " << peat_drain_total << endl;
}
cout << "ecozone end of fx: " << ecozone << endl;
cout << "forestmodel_data end of fx: " << forestmodel_data << endl;
cout << "ifl end of fx: " << ifl << endl;
cout << "climate end of fx: " << climate << endl;
cout << "plant_data end of fx: " << plant_data << endl;
cout << "model_years end of fx: " << model_years << endl;
cout << "loss_yr end of fx: " << lossyr << endl;
cout << "peat_drain_annual end of fx: " << peat_drain_annual << endl;
cout << "peat_drain_total end of fx: " << peat_drain_total << endl;
static float def_variables[6] = {Cf, CO2, CH4, N2O, peatburn, peat_drain_total};
return def_variables;
}<commit_msg>Peat drain values aren't being added to emissions. Trying to figure out why.<commit_after>#include <map>
#include <iostream>
#include <stdlib.h>
using namespace std;
float* def_variables(int ecozone, int forestmodel_data, int ifl, int climate, int plant_data, int lossyr)
{
int model_years; // How many loss years are in the model
model_years = 15;
int tropical; // The ecozone code for the tropics
tropical = 1;
int temperate; // The ecozone code for the temperate zone
temperate = 3;
int boreal; // The ecozone code for the boreal zone
boreal = 2;
// returns Cf, CO2, CH4, N2O, peatburn, peat_drain_total
float Cf;
float CO2;
float CH4;
float N2O;
float peatburn;
float peat_drain_annual;
float peat_drain_total;
if ((forestmodel_data == 1) || (forestmodel_data == 2) || (forestmodel_data == 5)) // Commodities, shifting ag., or urbanization
{
if (ecozone == boreal) // Commodities/shifting ag/urbanization, boreal
{
Cf = 0.59;
CO2 = 1569;
CH4 = 4.7;
N2O = 0.26;
peatburn = 41;
peat_drain_total = (model_years - lossyr) * 36;
}
else if (ecozone == temperate)// Commodities/shifting ag/urbanization, temperate
{
Cf = 0.51;
CO2 = 1569;
CH4 = 4.7;
N2O = 0.26;
peatburn = 41;
peat_drain_total = (model_years - lossyr) * 31;
}
else if (ecozone == tropical) // Commodities/shifting ag/urbanization, tropics
{
CO2 = 1580;
CH4 = 6.8;
N2O = 0.2;
peatburn = 163;
if (plant_data == 1) // Commodities/shifting ag/urbanization, tropics, oil palm
{
peat_drain_annual = 47;
}
else if (plant_data == 2) // Commodities/shifting ag/urbanization, tropics, wood fiber
{
peat_drain_annual = 80;
}
else // Commodities/shifting ag/urbanization, tropics, other plantation or no plantation
{
peat_drain_annual = 62;
}
peat_drain_total = (model_years - lossyr) * peat_drain_annual;
if (ifl > 0) // Commodities/shifting ag/urbanization, tropics, in IFL
{
Cf = 0.36;
}
else // Commodities/shifting ag/urbanization, tropics, outside IFL
{
Cf = 0.55;
}
}
cout << "ecozone: " << ecozone << endl;
cout << "forestmodel_data: " << forestmodel_data << endl;
cout << "ifl: " << ifl << endl;
cout << "climate: " << climate << endl;
cout << "plant_data: " << plant_data << endl;
cout << "model_years: " << model_years << endl;
cout << "loss_yr: " << lossyr << endl;
cout << "peat_drain_annual: " << peat_drain_annual << endl;
cout << "peat_drain_total: " << peat_drain_total << endl;
}
else if (forestmodel_data == 3) // Forestry
{
if (ecozone == boreal) // Forestry, boreal
{
Cf = 0.33;
CO2 = 1569;
CH4 = 4.7;
N2O = 0.26;
peatburn = 41;
peat_drain_total = (model_years - lossyr) * 3;
}
else if (ecozone == temperate)// Forestry, temperate
{
Cf = 0.62;
CO2 = 1569;
CH4 = 4.7;
N2O = 0.26;
peatburn = 41;
peat_drain_total = (model_years - lossyr) * 12;
}
else if (ecozone == tropical) // Forestry, tropics
{
CO2 = 1580;
CH4 = 6.8;
N2O = 0.2;
peatburn = 163;
if (plant_data == 1) // Forestry, tropics, oil palm
{
peat_drain_annual = 45;
}
else if (plant_data == 2) // Forestry, tropics, wood fiber
{
peat_drain_annual = 79;
}
else // Forestry, tropics, other plantation or no plantation
{
peat_drain_annual = 60;
}
peat_drain_total = (model_years - lossyr) * peat_drain_annual;
if (ifl > 0)
{
Cf = 0.36; // Forestry, tropics, in IFL
}
else
{
Cf = 0.55; // Forestry, tropics, outside IFL
}
}
cout << "ecozone: " << ecozone << endl;
cout << "forestmodel_data: " << forestmodel_data << endl;
cout << "ifl: " << ifl << endl;
cout << "climate: " << climate << endl;
cout << "plant_data: " << plant_data << endl;
cout << "model_years: " << model_years << endl;
cout << "loss_yr: " << lossyr << endl;
cout << "peat_drain_annual: " << peat_drain_annual << endl;
cout << "peat_drain_total: " << peat_drain_total << endl;
}
else if (forestmodel_data == 4) // Wildfire
{
if (ecozone == boreal) // Wildfire, boreal
{
Cf = 0.59;
CO2 = 1569;
CH4 = 4.7;
N2O = 0.26;
peatburn = 41;
peat_drain_total = (model_years - lossyr) * 3;
}
else if (ecozone == temperate)// Wildfire, temperate
{
Cf = 0.51;
CO2 = 1569;
CH4 = 4.7;
N2O = 0.26;
peatburn = 41;
peat_drain_total = (model_years - lossyr) * 12;
}
else if (ecozone == tropical) // Wildfire, tropics
{
CO2 = 1580;
CH4 = 6.8;
N2O = 0.2;
peatburn = 371;
if (plant_data == 1) // Wildfire, tropics, oil palm
{
peat_drain_annual = 45;
}
else if (plant_data == 2) // Wildfire, tropics, wood fiber
{
peat_drain_annual = 79;
}
else // Wildfire, tropics, other plantation or no plantation
{
peat_drain_annual = 60;
}
peat_drain_total = (model_years - lossyr) * peat_drain_annual;
if (ifl > 0) // Wildfire, tropics, in IFL
{
Cf = 0.36;
}
else // Wildfire, tropics, outside IFL
{
Cf = 0.55;
}
}
cout << "ecozone: " << ecozone << endl;
cout << "forestmodel_data: " << forestmodel_data << endl;
cout << "ifl: " << ifl << endl;
cout << "climate: " << climate << endl;
cout << "plant_data: " << plant_data << endl;
cout << "model_years: " << model_years << endl;
cout << "loss_yr: " << lossyr << endl;
cout << "peat_drain_annual: " << peat_drain_annual << endl;
cout << "peat_drain_total: " << peat_drain_total << endl;
}
else // No driver-- same as forestry
{
if (ecozone == boreal) // No driver, boreal
{
Cf = 0.33;
CO2 = 1569;
CH4 = 4.7;
N2O = 0.26;
peatburn = 41;
peat_drain_total = (model_years - lossyr) * 3;
}
else if (ecozone == temperate)// No driver, temperate
{
Cf = 0.62;
CO2 = 1569;
CH4 = 4.7;
N2O = 0.26;
peatburn = 41;
peat_drain_total = (model_years - lossyr) * 12;
}
else if (ecozone == tropical) // No driver, tropics
{
CO2 = 1580;
CH4 = 6.8;
N2O = 0.2;
peatburn = 163;
if (plant_data == 1) // No driver, tropics, oil palm
{
peat_drain_annual = 45;
}
else if (plant_data == 2) // No driver, tropics, wood fiber
{
peat_drain_annual = 79;
}
else // No driver, tropics, other plantation or no plantation
{
peat_drain_annual = 60;
}
peat_drain_total = (model_years - lossyr) * peat_drain_annual;
if (ifl > 0)
{
Cf = 0.36; // No driver, tropics, in IFL
}
else
{
Cf = 0.55; // No driver, tropics, outside IFL
}
}
cout << "ecozone: " << ecozone << endl;
cout << "forestmodel_data: " << forestmodel_data << endl;
cout << "ifl: " << ifl << endl;
cout << "climate: " << climate << endl;
cout << "plant_data: " << plant_data << endl;
cout << "model_years: " << model_years << endl;
cout << "loss_yr: " << lossyr << endl;
cout << "peat_drain_annual: " << peat_drain_annual << endl;
cout << "peat_drain_total: " << peat_drain_total << endl;
}
cout << "ecozone end of fx: " << ecozone << endl;
cout << "forestmodel_data end of fx: " << forestmodel_data << endl;
cout << "ifl end of fx: " << ifl << endl;
cout << "climate end of fx: " << climate << endl;
cout << "plant_data end of fx: " << plant_data << endl;
cout << "model_years end of fx: " << model_years << endl;
cout << "loss_yr end of fx: " << lossyr << endl;
cout << "peat_drain_annual end of fx: " << peat_drain_annual << endl;
cout << "peat_drain_total end of fx: " << peat_drain_total << endl;
cout << "cf end of fx: " << Cf << endl;
cout << "gef_co2 end of fx: " << Gef_CO2 << endl;
cout << "gef_Ch4 end of fx: " << Gef_CH4 << endl;
cout << "gef_n2o end of fx: " << Gef_N2O << endl;
cout << "peatburn end of fx: " << peatburn << endl;
cout << "peat_drain_total end of fx: " << peat_drain_total << endl;
static float def_variables[6] = {Cf, CO2, CH4, N2O, peatburn, peat_drain_total};
return def_variables;
}<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (C) 2005-2013 by the FIFE team *
* http://www.fifengine.net *
* This file is part of FIFE. *
* *
* FIFE 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 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 *
* 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., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************/
// Standard C++ library includes
// 3rd party library includes
// FIFE includes
// These includes are split up in two parts, separated by one empty line
// First block: files included from the FIFE root src directory
// Second block: files included from the same folder
#include "util/log/logger.h"
#include "model/metamodel/object.h"
#include "model/structures/location.h"
#include "route.h"
namespace FIFE {
static Logger _log(LM_STRUCTURES);
Route::Route(const Location& start, const Location& end):
m_status(ROUTE_CREATED),
m_startNode(start),
m_endNode(end),
m_walked(0),
m_sessionId(-1),
m_rotation(0),
m_replanned(false),
m_costId(""),
m_object(NULL) {
}
Route::~Route() {
}
void Route::setRouteStatus(RouteStatusInfo status) {
if (m_status != status) {
m_status = status;
}
}
RouteStatusInfo Route::getRouteStatus() {
return m_status;
}
void Route::setStartNode(const Location& node) {
m_startNode = node;
if (m_status != ROUTE_CREATED) {
m_status = ROUTE_CREATED;
if (!m_path.empty()) {
m_path.clear();
}
m_walked = 1;
}
}
const Location& Route::getStartNode() {
return m_startNode;
}
void Route::setEndNode(const Location& node) {
if (m_status != ROUTE_CREATED) {
m_status = ROUTE_CREATED;
if (!m_path.empty()) {
m_startNode = *m_current;
m_path.clear();
}
m_walked = 1;
}
m_endNode = node;
}
const Location& Route::getEndNode() {
return m_endNode;
}
const Location& Route::getCurrentNode() {
if (m_path.empty()) {
return m_startNode;
}
if (m_current == m_path.end()) {
return m_path.back();
}
return *m_current;
}
const Location& Route::getPreviousNode() {
if (m_path.empty()) {
return m_startNode;
}
if (m_current != m_path.begin()) {
--m_current;
const Location& loc = *m_current;
++m_current;
return loc;
}
return *m_current;
}
const Location& Route::getNextNode() {
if (m_path.empty()) {
return m_startNode;
}
if (m_current != m_path.end()) {
++m_current;
if (m_current != m_path.end()) {
const Location& loc = *m_current;
--m_current;
return loc;
}
--m_current;
}
return *m_current;
}
bool Route::walkToNextNode(int32_t step) {
if (m_path.empty() || step == 0) {
return false;
}
int32_t pos = static_cast<int32_t>(m_walked) + step;
if (pos > static_cast<int32_t>(m_path.size()) || pos < 0) {
return false;
}
if (step > 0) {
for (int32_t i = 0; i < step; ++i, ++m_current);
} else {
for (int32_t i = 0; i > step; --i, --m_current);
}
m_walked += step;
return true;
}
bool Route::reachedEnd() {
if (m_path.empty()) {
return true;
}
return m_current == m_path.end();
}
void Route::setPath(const Path& path) {
m_path = path;
if (!m_path.empty()) {
m_status = ROUTE_SOLVED;
m_current = m_path.begin();
m_startNode = path.front();
m_endNode = path.back();
}
if (!isMultiCell()) {
m_replanned = false;
}
m_walked = 1;
}
Path Route::getPath() {
return m_path;
}
void Route::cutPath(uint32_t length) {
if (length == 0) {
if (!m_path.empty()) {
m_startNode = *m_current;
m_endNode = *m_current;
m_path.clear();
m_current = m_path.end();
}
m_status = ROUTE_CREATED;
m_walked = 1;
m_replanned = true;
return;
} else if (length >= m_path.size()) {
return;
}
uint32_t newend = m_walked + length - 1;
if (newend > m_path.size()) {
return;
}
m_path.resize(newend);
m_endNode = m_path.back();
m_replanned = true;
}
void Route::setReplanned(bool replanned) {
m_replanned = replanned;
}
bool Route::isReplanned() {
return m_replanned;
}
uint32_t Route::getPathLength() {
return m_path.size();
}
uint32_t Route::getWalkedLength() {
return m_walked;
}
void Route::setSessionId(int32_t id) {
m_sessionId = id;
}
int32_t Route::getSessionId() {
return m_sessionId;
}
void Route::setRotation(int32_t rotation) {
m_rotation = rotation;
}
int32_t Route::getRotation() {
return m_rotation;
}
void Route::setCostId(const std::string& cost) {
m_costId = cost;
}
const std::string& Route::getCostId() {
return m_costId;
}
bool Route::isMultiCell() {
if (m_object) {
return m_object->isMultiObject();
}
return false;
}
void Route::setOccupiedArea(const std::vector<ModelCoordinate>& area) {
m_area = area;
}
const std::vector<ModelCoordinate>& Route::getOccupiedArea() {
return m_area;
}
std::vector<ModelCoordinate> Route::getOccupiedCells(int32_t rotation) {
if (m_object) {
return m_object->getMultiObjectCoordinates(rotation);
}
std::vector<ModelCoordinate> coords;
return coords;
}
int32_t Route::getZStepRange() {
if (!m_object) {
return -1;
}
return m_object->getZStepRange();
}
bool Route::isAreaLimited() {
if (m_object) {
if (!m_object->getWalkableAreas().empty()) {
return true;
}
}
return false;
}
const std::list<std::string> Route::getLimitedAreas() {
std::list<std::string> areas;
if (m_object) {
areas = m_object->getWalkableAreas();
}
return areas;
}
void Route::setObject(Object* obj) {
m_object = obj;
}
Object* Route::getObject() {
return m_object;
}
} // FIFE
<commit_msg> * Fixed hopefully the segmentation fault which is described here https://github.com/unknown-horizons/unknown-horizons/issues/1993<commit_after>/***************************************************************************
* Copyright (C) 2005-2013 by the FIFE team *
* http://www.fifengine.net *
* This file is part of FIFE. *
* *
* FIFE 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 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 *
* 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., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************/
// Standard C++ library includes
// 3rd party library includes
// FIFE includes
// These includes are split up in two parts, separated by one empty line
// First block: files included from the FIFE root src directory
// Second block: files included from the same folder
#include "util/log/logger.h"
#include "model/metamodel/object.h"
#include "model/structures/location.h"
#include "route.h"
namespace FIFE {
static Logger _log(LM_STRUCTURES);
Route::Route(const Location& start, const Location& end):
m_status(ROUTE_CREATED),
m_startNode(start),
m_endNode(end),
m_walked(0),
m_sessionId(-1),
m_rotation(0),
m_replanned(false),
m_costId(""),
m_object(NULL) {
}
Route::~Route() {
}
void Route::setRouteStatus(RouteStatusInfo status) {
if (m_status != status) {
m_status = status;
}
}
RouteStatusInfo Route::getRouteStatus() {
return m_status;
}
void Route::setStartNode(const Location& node) {
m_startNode = node;
if (m_status != ROUTE_CREATED) {
m_status = ROUTE_CREATED;
if (!m_path.empty()) {
m_path.clear();
}
m_walked = 1;
}
}
const Location& Route::getStartNode() {
return m_startNode;
}
void Route::setEndNode(const Location& node) {
if (m_status != ROUTE_CREATED) {
m_status = ROUTE_CREATED;
if (!m_path.empty()) {
m_startNode = *m_current;
m_path.clear();
}
m_walked = 1;
}
m_endNode = node;
}
const Location& Route::getEndNode() {
return m_endNode;
}
const Location& Route::getCurrentNode() {
if (m_path.empty()) {
return m_startNode;
}
if (m_current == m_path.end()) {
return m_path.back();
}
return *m_current;
}
const Location& Route::getPreviousNode() {
if (m_path.empty()) {
return m_startNode;
}
if (m_current != m_path.begin()) {
--m_current;
const Location& loc = *m_current;
++m_current;
return loc;
}
return *m_current;
}
const Location& Route::getNextNode() {
if (m_path.empty()) {
return m_startNode;
}
if (m_current != m_path.end()) {
++m_current;
if (m_current != m_path.end()) {
const Location& loc = *m_current;
--m_current;
return loc;
}
--m_current;
}
return *m_current;
}
bool Route::walkToNextNode(int32_t step) {
if (m_path.empty() || step == 0) {
return false;
}
int32_t pos = static_cast<int32_t>(m_walked) + step;
if (pos > static_cast<int32_t>(m_path.size()) || pos < 0) {
return false;
}
if (step > 0) {
for (int32_t i = 0; i < step; ++i, ++m_current);
} else {
for (int32_t i = 0; i > step; --i, --m_current);
}
m_walked += step;
return true;
}
bool Route::reachedEnd() {
if (m_path.empty()) {
return true;
}
return m_current == m_path.end();
}
void Route::setPath(const Path& path) {
m_path = path;
if (!m_path.empty()) {
m_status = ROUTE_SOLVED;
m_current = m_path.begin();
m_startNode = m_path.front();
m_endNode = m_path.back();
}
if (!isMultiCell()) {
m_replanned = false;
}
m_walked = 1;
}
Path Route::getPath() {
return m_path;
}
void Route::cutPath(uint32_t length) {
if (length == 0) {
if (!m_path.empty()) {
m_startNode = *m_current;
m_endNode = *m_current;
m_path.clear();
m_current = m_path.end();
}
m_status = ROUTE_CREATED;
m_walked = 1;
m_replanned = true;
return;
} else if (length >= m_path.size()) {
return;
}
uint32_t newend = m_walked + length - 1;
if (newend > m_path.size()) {
return;
}
m_path.resize(newend);
m_endNode = m_path.back();
m_replanned = true;
}
void Route::setReplanned(bool replanned) {
m_replanned = replanned;
}
bool Route::isReplanned() {
return m_replanned;
}
uint32_t Route::getPathLength() {
return m_path.size();
}
uint32_t Route::getWalkedLength() {
return m_walked;
}
void Route::setSessionId(int32_t id) {
m_sessionId = id;
}
int32_t Route::getSessionId() {
return m_sessionId;
}
void Route::setRotation(int32_t rotation) {
m_rotation = rotation;
}
int32_t Route::getRotation() {
return m_rotation;
}
void Route::setCostId(const std::string& cost) {
m_costId = cost;
}
const std::string& Route::getCostId() {
return m_costId;
}
bool Route::isMultiCell() {
if (m_object) {
return m_object->isMultiObject();
}
return false;
}
void Route::setOccupiedArea(const std::vector<ModelCoordinate>& area) {
m_area = area;
}
const std::vector<ModelCoordinate>& Route::getOccupiedArea() {
return m_area;
}
std::vector<ModelCoordinate> Route::getOccupiedCells(int32_t rotation) {
if (m_object) {
return m_object->getMultiObjectCoordinates(rotation);
}
std::vector<ModelCoordinate> coords;
return coords;
}
int32_t Route::getZStepRange() {
if (!m_object) {
return -1;
}
return m_object->getZStepRange();
}
bool Route::isAreaLimited() {
if (m_object) {
if (!m_object->getWalkableAreas().empty()) {
return true;
}
}
return false;
}
const std::list<std::string> Route::getLimitedAreas() {
std::list<std::string> areas;
if (m_object) {
areas = m_object->getWalkableAreas();
}
return areas;
}
void Route::setObject(Object* obj) {
m_object = obj;
}
Object* Route::getObject() {
return m_object;
}
} // FIFE
<|endoftext|>
|
<commit_before>//===--- ASTNode.cpp - Swift Language ASTs --------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the ASTNode, which is a union of Stmt, Expr, and Decl.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/ASTNode.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Stmt.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/TypeRepr.h"
#include "swift/Basic/SourceLoc.h"
using namespace swift;
SourceRange ASTNode::getSourceRange() const {
if (const auto *E = this->dyn_cast<Expr*>())
return E->getSourceRange();
if (const auto *S = this->dyn_cast<Stmt*>())
return S->getSourceRange();
if (const auto *D = this->dyn_cast<Decl*>())
return D->getSourceRange();
if (const auto *P = this->dyn_cast<Pattern*>())
return P->getSourceRange();
if (const auto *T = this->dyn_cast<TypeRepr *>())
return T->getSourceRange();
if (const auto *C = this->dyn_cast<StmtConditionElement *>())
return C->getSourceRange();
if (const auto *I = this->dyn_cast<CaseLabelItem *>()) {
return I->getSourceRange();
}
llvm_unreachable("unsupported AST node");
}
/// Return the location of the start of the statement.
SourceLoc ASTNode::getStartLoc() const {
return getSourceRange().Start;
}
/// Return the location of the end of the statement.
SourceLoc ASTNode::getEndLoc() const {
return getSourceRange().End;
}
DeclContext *ASTNode::getAsDeclContext() const {
if (auto *E = this->dyn_cast<Expr*>()) {
if (isa<AbstractClosureExpr>(E))
return static_cast<AbstractClosureExpr*>(E);
} else if (is<Stmt*>()) {
return nullptr;
} else if (auto *D = this->dyn_cast<Decl*>()) {
if (isa<DeclContext>(D))
return cast<DeclContext>(D);
} else if (getOpaqueValue())
llvm_unreachable("unsupported AST node");
return nullptr;
}
bool ASTNode::isImplicit() const {
if (const auto *E = this->dyn_cast<Expr*>())
return E->isImplicit();
if (const auto *S = this->dyn_cast<Stmt*>())
return S->isImplicit();
if (const auto *D = this->dyn_cast<Decl*>())
return D->isImplicit();
if (const auto *P = this->dyn_cast<Pattern*>())
return P->isImplicit();
if (const auto *T = this->dyn_cast<TypeRepr*>())
return false;
if (const auto *C = this->dyn_cast<StmtConditionElement *>())
return false;
if (const auto *I = this->dyn_cast<CaseLabelItem *>())
return false;
llvm_unreachable("unsupported AST node");
}
void ASTNode::walk(ASTWalker &Walker) {
if (auto *E = this->dyn_cast<Expr*>())
E->walk(Walker);
else if (auto *S = this->dyn_cast<Stmt*>())
S->walk(Walker);
else if (auto *D = this->dyn_cast<Decl*>())
D->walk(Walker);
else if (auto *P = this->dyn_cast<Pattern*>())
P->walk(Walker);
else if (auto *T = this->dyn_cast<TypeRepr*>())
T->walk(Walker);
else if (auto *C = this->dyn_cast<StmtConditionElement *>())
C->walk(Walker);
else if (auto *I = this->dyn_cast<CaseLabelItem *>()) {
if (auto *P = I->getPattern())
P->walk(Walker);
if (auto *G = I->getGuardExpr())
G->walk(Walker);
} else
llvm_unreachable("unsupported AST node");
}
void ASTNode::dump(raw_ostream &OS, unsigned Indent) const {
if (auto S = dyn_cast<Stmt*>())
S->dump(OS, /*context=*/nullptr, Indent);
else if (auto E = dyn_cast<Expr*>())
E->dump(OS, Indent);
else if (auto D = dyn_cast<Decl*>())
D->dump(OS, Indent);
else if (auto P = dyn_cast<Pattern*>())
P->dump(OS, Indent);
else if (auto T = dyn_cast<TypeRepr*>())
T->print(OS);
else if (auto *C = dyn_cast<StmtConditionElement *>())
OS.indent(Indent) << "(statement condition)";
else if (auto *I = dyn_cast<CaseLabelItem *>()) {
OS.indent(Indent) << "(case label item)";
} else
llvm_unreachable("unsupported AST node");
}
void ASTNode::dump() const {
dump(llvm::errs());
}
#define FUNC(T) \
bool ASTNode::is##T(T##Kind Kind) const { \
if (!is<T*>()) \
return false; \
return get<T*>()->getKind() == Kind; \
}
FUNC(Stmt)
FUNC(Expr)
FUNC(Decl)
FUNC(Pattern)
#undef FUNC
<commit_msg>[AST] Don’t crash when dumping null ASTNodes<commit_after>//===--- ASTNode.cpp - Swift Language ASTs --------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the ASTNode, which is a union of Stmt, Expr, and Decl.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/ASTNode.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Stmt.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/TypeRepr.h"
#include "swift/Basic/SourceLoc.h"
using namespace swift;
SourceRange ASTNode::getSourceRange() const {
if (const auto *E = this->dyn_cast<Expr*>())
return E->getSourceRange();
if (const auto *S = this->dyn_cast<Stmt*>())
return S->getSourceRange();
if (const auto *D = this->dyn_cast<Decl*>())
return D->getSourceRange();
if (const auto *P = this->dyn_cast<Pattern*>())
return P->getSourceRange();
if (const auto *T = this->dyn_cast<TypeRepr *>())
return T->getSourceRange();
if (const auto *C = this->dyn_cast<StmtConditionElement *>())
return C->getSourceRange();
if (const auto *I = this->dyn_cast<CaseLabelItem *>()) {
return I->getSourceRange();
}
llvm_unreachable("unsupported AST node");
}
/// Return the location of the start of the statement.
SourceLoc ASTNode::getStartLoc() const {
return getSourceRange().Start;
}
/// Return the location of the end of the statement.
SourceLoc ASTNode::getEndLoc() const {
return getSourceRange().End;
}
DeclContext *ASTNode::getAsDeclContext() const {
if (auto *E = this->dyn_cast<Expr*>()) {
if (isa<AbstractClosureExpr>(E))
return static_cast<AbstractClosureExpr*>(E);
} else if (is<Stmt*>()) {
return nullptr;
} else if (auto *D = this->dyn_cast<Decl*>()) {
if (isa<DeclContext>(D))
return cast<DeclContext>(D);
} else if (getOpaqueValue())
llvm_unreachable("unsupported AST node");
return nullptr;
}
bool ASTNode::isImplicit() const {
if (const auto *E = this->dyn_cast<Expr*>())
return E->isImplicit();
if (const auto *S = this->dyn_cast<Stmt*>())
return S->isImplicit();
if (const auto *D = this->dyn_cast<Decl*>())
return D->isImplicit();
if (const auto *P = this->dyn_cast<Pattern*>())
return P->isImplicit();
if (const auto *T = this->dyn_cast<TypeRepr*>())
return false;
if (const auto *C = this->dyn_cast<StmtConditionElement *>())
return false;
if (const auto *I = this->dyn_cast<CaseLabelItem *>())
return false;
llvm_unreachable("unsupported AST node");
}
void ASTNode::walk(ASTWalker &Walker) {
if (auto *E = this->dyn_cast<Expr*>())
E->walk(Walker);
else if (auto *S = this->dyn_cast<Stmt*>())
S->walk(Walker);
else if (auto *D = this->dyn_cast<Decl*>())
D->walk(Walker);
else if (auto *P = this->dyn_cast<Pattern*>())
P->walk(Walker);
else if (auto *T = this->dyn_cast<TypeRepr*>())
T->walk(Walker);
else if (auto *C = this->dyn_cast<StmtConditionElement *>())
C->walk(Walker);
else if (auto *I = this->dyn_cast<CaseLabelItem *>()) {
if (auto *P = I->getPattern())
P->walk(Walker);
if (auto *G = I->getGuardExpr())
G->walk(Walker);
} else
llvm_unreachable("unsupported AST node");
}
void ASTNode::dump(raw_ostream &OS, unsigned Indent) const {
if (isNull())
OS << "(null)";
else if (auto S = dyn_cast<Stmt*>())
S->dump(OS, /*context=*/nullptr, Indent);
else if (auto E = dyn_cast<Expr*>())
E->dump(OS, Indent);
else if (auto D = dyn_cast<Decl*>())
D->dump(OS, Indent);
else if (auto P = dyn_cast<Pattern*>())
P->dump(OS, Indent);
else if (auto T = dyn_cast<TypeRepr*>())
T->print(OS);
else if (auto *C = dyn_cast<StmtConditionElement *>())
OS.indent(Indent) << "(statement condition)";
else if (auto *I = dyn_cast<CaseLabelItem *>()) {
OS.indent(Indent) << "(case label item)";
} else
llvm_unreachable("unsupported AST node");
}
void ASTNode::dump() const {
dump(llvm::errs());
}
#define FUNC(T) \
bool ASTNode::is##T(T##Kind Kind) const { \
if (!is<T*>()) \
return false; \
return get<T*>()->getKind() == Kind; \
}
FUNC(Stmt)
FUNC(Expr)
FUNC(Decl)
FUNC(Pattern)
#undef FUNC
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.