text
stringlengths 54
60.6k
|
---|
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/prediction/predictor/sequence/sequence_predictor.h"
#include <cmath>
#include <limits>
#include <memory>
#include <utility>
#include "modules/common/adapters/proto/adapter_config.pb.h"
#include "modules/common/math/vec2d.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
#include "modules/prediction/common/road_graph.h"
#include "modules/prediction/container/adc_trajectory/adc_trajectory_container.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/pose/pose_container.h"
namespace apollo {
namespace prediction {
using ::apollo::common::PathPoint;
using ::apollo::common::TrajectoryPoint;
using ::apollo::common::adapter::AdapterConfig;
using ::apollo::common::math::Vec2d;
using ::apollo::hdmap::LaneInfo;
void SequencePredictor::Predict(Obstacle* obstacle) {
Clear();
CHECK_NOTNULL(obstacle);
CHECK_GT(obstacle->history_size(), 0);
}
void SequencePredictor::Clear() { Predictor::Clear(); }
std::string SequencePredictor::ToString(const LaneSequence& sequence) {
std::string str_lane_sequence = "";
if (sequence.lane_segment_size() > 0) {
str_lane_sequence += sequence.lane_segment(0).lane_id();
}
for (int i = 1; i < sequence.lane_segment_size(); ++i) {
str_lane_sequence += ("->" + sequence.lane_segment(i).lane_id());
}
return str_lane_sequence;
}
void SequencePredictor::FilterLaneSequences(
const LaneGraph& lane_graph, const std::string& lane_id,
std::vector<bool>* enable_lane_sequence) {
int num_lane_sequence = lane_graph.lane_sequence_size();
std::vector<LaneChangeType> lane_change_type(num_lane_sequence,
LaneChangeType::INVALID);
std::pair<int, double> change(-1, -1.0);
std::pair<int, double> all(-1, -1.0);
for (int i = 0; i < num_lane_sequence; ++i) {
const LaneSequence& sequence = lane_graph.lane_sequence(i);
lane_change_type[i] = GetLaneChangeType(lane_id, sequence);
if (lane_change_type[i] != LaneChangeType::LEFT &&
lane_change_type[i] != LaneChangeType::RIGHT &&
lane_change_type[i] != LaneChangeType::ONTO_LANE) {
ADEBUG "Ignore lane sequence [" << ToString(sequence) << "].";
continue;
}
// The obstacle has interference with ADC within a small distance
double distance = GetLaneChangeDistanceWithADC(sequence);
ADEBUG << "Distance to ADC " << std::fixed << std::setprecision(6)
<< distance;
if (distance < FLAGS_lane_change_dist) {
(*enable_lane_sequence)[i] = false;
ADEBUG << "Filter trajectory [" << ToString(sequence)
<< "] due to small distance " << distance << ".";
}
}
for (int i = 0; i < num_lane_sequence; ++i) {
const LaneSequence& sequence = lane_graph.lane_sequence(i);
if (!(*enable_lane_sequence)[i]) {
ADEBUG << "Disabled lane sequence [" << ToString(sequence) << "].";
continue;
}
double probability = sequence.probability();
if (LaneSequenceWithMaxProb(lane_change_type[i], probability, all.second)) {
all.first = i;
all.second = probability;
}
if (LaneChangeWithMaxProb(lane_change_type[i], probability,
change.second)) {
change.first = i;
change.second = probability;
}
}
for (int i = 0; i < num_lane_sequence; ++i) {
const LaneSequence& sequence = lane_graph.lane_sequence(i);
if (!(*enable_lane_sequence)[i]) {
ADEBUG << "Disabled lane sequence [" << ToString(sequence) << "].";
continue;
}
double probability = sequence.probability();
if (probability < FLAGS_lane_sequence_threshold && i != all.first) {
(*enable_lane_sequence)[i] = false;
} else if (change.first >= 0 && change.first < num_lane_sequence &&
(lane_change_type[i] == LaneChangeType::LEFT ||
lane_change_type[i] == LaneChangeType::RIGHT) &&
lane_change_type[i] != lane_change_type[change.first]) {
(*enable_lane_sequence)[i] = false;
}
}
}
SequencePredictor::LaneChangeType SequencePredictor::GetLaneChangeType(
const std::string& lane_id, const LaneSequence& lane_sequence) {
PredictionMap* map = PredictionMap::instance();
if (lane_id.empty()) {
return LaneChangeType::ONTO_LANE;
}
std::string lane_change_id = lane_sequence.lane_segment(0).lane_id();
if (lane_id == lane_change_id) {
return LaneChangeType::STRAIGHT;
} else {
if (map->IsLeftNeighborLane(map->LaneById(lane_change_id),
map->LaneById(lane_id))) {
return LaneChangeType::LEFT;
} else if (map->IsRightNeighborLane(map->LaneById(lane_change_id),
map->LaneById(lane_id))) {
return LaneChangeType::RIGHT;
}
}
return LaneChangeType::INVALID;
}
double SequencePredictor::GetLaneChangeDistanceWithADC(
const LaneSequence& lane_sequence) {
PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
ContainerManager::instance()->GetContainer(AdapterConfig::LOCALIZATION));
ADCTrajectoryContainer* adc_container = dynamic_cast<ADCTrajectoryContainer*>(
ContainerManager::instance()->GetContainer(
AdapterConfig::PLANNING_TRAJECTORY));
CHECK_NOTNULL(pose_container);
CHECK_NOTNULL(adc_container);
if (!adc_container->HasOverlap(lane_sequence)) {
return std::numeric_limits<double>::max();
}
Eigen::Vector2d adc_position;
if (pose_container->ToPerceptionObstacle() != nullptr) {
adc_position[0] = pose_container->ToPerceptionObstacle()->position().x();
adc_position[1] = pose_container->ToPerceptionObstacle()->position().y();
PredictionMap* map = PredictionMap::instance();
std::string obstacle_lane_id = lane_sequence.lane_segment(0).lane_id();
double obstacle_lane_s = lane_sequence.lane_segment(0).start_s();
double lane_s = 0.0;
double lane_l = 0.0;
ADEBUG << "Obstacle lane " << obstacle_lane_id << " and s "
<< obstacle_lane_s;
if (map->GetProjection(adc_position, map->LaneById(obstacle_lane_id),
&lane_s, &lane_l)) {
ADEBUG << "ADC on lane s " << lane_s;
return std::fabs(lane_s - obstacle_lane_s);
}
}
return std::numeric_limits<double>::max();
}
bool SequencePredictor::LaneSequenceWithMaxProb(const LaneChangeType& type,
const double& probability,
const double& max_prob) {
if (probability > max_prob) {
return true;
} else {
double prob_diff = std::fabs(probability - max_prob);
if (prob_diff <= std::numeric_limits<double>::epsilon() &&
type == LaneChangeType::STRAIGHT) {
return true;
}
}
return false;
}
bool SequencePredictor::LaneChangeWithMaxProb(const LaneChangeType& type,
const double& probability,
const double& max_prob) {
if (type == LaneChangeType::LEFT || type == LaneChangeType::RIGHT) {
if (probability > max_prob) {
return true;
}
}
return false;
}
} // namespace prediction
} // namespace apollo
<commit_msg>Prediction: added some debug info<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/prediction/predictor/sequence/sequence_predictor.h"
#include <cmath>
#include <limits>
#include <memory>
#include <utility>
#include "modules/common/adapters/proto/adapter_config.pb.h"
#include "modules/common/math/vec2d.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
#include "modules/prediction/common/road_graph.h"
#include "modules/prediction/container/adc_trajectory/adc_trajectory_container.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/pose/pose_container.h"
namespace apollo {
namespace prediction {
using ::apollo::common::PathPoint;
using ::apollo::common::TrajectoryPoint;
using ::apollo::common::adapter::AdapterConfig;
using ::apollo::common::math::Vec2d;
using ::apollo::hdmap::LaneInfo;
void SequencePredictor::Predict(Obstacle* obstacle) {
Clear();
CHECK_NOTNULL(obstacle);
CHECK_GT(obstacle->history_size(), 0);
}
void SequencePredictor::Clear() { Predictor::Clear(); }
std::string SequencePredictor::ToString(const LaneSequence& sequence) {
std::string str_lane_sequence = "";
if (sequence.lane_segment_size() > 0) {
str_lane_sequence += sequence.lane_segment(0).lane_id();
}
for (int i = 1; i < sequence.lane_segment_size(); ++i) {
str_lane_sequence += ("->" + sequence.lane_segment(i).lane_id());
}
return str_lane_sequence;
}
void SequencePredictor::FilterLaneSequences(
const LaneGraph& lane_graph, const std::string& lane_id,
std::vector<bool>* enable_lane_sequence) {
int num_lane_sequence = lane_graph.lane_sequence_size();
std::vector<LaneChangeType> lane_change_type(num_lane_sequence,
LaneChangeType::INVALID);
std::pair<int, double> change(-1, -1.0);
std::pair<int, double> all(-1, -1.0);
for (int i = 0; i < num_lane_sequence; ++i) {
const LaneSequence& sequence = lane_graph.lane_sequence(i);
lane_change_type[i] = GetLaneChangeType(lane_id, sequence);
if (lane_change_type[i] != LaneChangeType::LEFT &&
lane_change_type[i] != LaneChangeType::RIGHT &&
lane_change_type[i] != LaneChangeType::ONTO_LANE) {
ADEBUG "Ignore lane sequence [" << ToString(sequence) << "].";
continue;
}
// The obstacle has interference with ADC within a small distance
double distance = GetLaneChangeDistanceWithADC(sequence);
ADEBUG << "Distance to ADC " << std::fixed << std::setprecision(6)
<< distance;
if (distance < FLAGS_lane_change_dist) {
(*enable_lane_sequence)[i] = false;
ADEBUG << "Filter trajectory [" << ToString(sequence)
<< "] due to small distance " << distance << ".";
}
}
for (int i = 0; i < num_lane_sequence; ++i) {
const LaneSequence& sequence = lane_graph.lane_sequence(i);
if (!(*enable_lane_sequence)[i]) {
ADEBUG << "Disabled lane sequence [" << ToString(sequence) << "].";
continue;
}
double probability = sequence.probability();
if (LaneSequenceWithMaxProb(lane_change_type[i], probability, all.second)) {
all.first = i;
all.second = probability;
}
if (LaneChangeWithMaxProb(lane_change_type[i], probability,
change.second)) {
change.first = i;
change.second = probability;
}
}
for (int i = 0; i < num_lane_sequence; ++i) {
const LaneSequence& sequence = lane_graph.lane_sequence(i);
if (!(*enable_lane_sequence)[i]) {
ADEBUG << "Disabled lane sequence [" << ToString(sequence) << "].";
continue;
}
double probability = sequence.probability();
if (probability < FLAGS_lane_sequence_threshold && i != all.first) {
(*enable_lane_sequence)[i] = false;
} else if (change.first >= 0 && change.first < num_lane_sequence &&
(lane_change_type[i] == LaneChangeType::LEFT ||
lane_change_type[i] == LaneChangeType::RIGHT) &&
lane_change_type[i] != lane_change_type[change.first]) {
(*enable_lane_sequence)[i] = false;
}
}
}
SequencePredictor::LaneChangeType SequencePredictor::GetLaneChangeType(
const std::string& lane_id, const LaneSequence& lane_sequence) {
PredictionMap* map = PredictionMap::instance();
if (lane_id.empty()) {
return LaneChangeType::ONTO_LANE;
}
std::string lane_change_id = lane_sequence.lane_segment(0).lane_id();
if (lane_id == lane_change_id) {
return LaneChangeType::STRAIGHT;
} else {
if (map->IsLeftNeighborLane(map->LaneById(lane_change_id),
map->LaneById(lane_id))) {
return LaneChangeType::LEFT;
} else if (map->IsRightNeighborLane(map->LaneById(lane_change_id),
map->LaneById(lane_id))) {
return LaneChangeType::RIGHT;
}
}
return LaneChangeType::INVALID;
}
double SequencePredictor::GetLaneChangeDistanceWithADC(
const LaneSequence& lane_sequence) {
PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
ContainerManager::instance()->GetContainer(AdapterConfig::LOCALIZATION));
ADCTrajectoryContainer* adc_container = dynamic_cast<ADCTrajectoryContainer*>(
ContainerManager::instance()->GetContainer(
AdapterConfig::PLANNING_TRAJECTORY));
CHECK_NOTNULL(pose_container);
CHECK_NOTNULL(adc_container);
if (!adc_container->HasOverlap(lane_sequence)) {
ADEBUG << "The sequence [" << ToString(lane_sequence)
<< "] has no overlap with ADC.";
return std::numeric_limits<double>::max();
}
Eigen::Vector2d adc_position;
if (pose_container->ToPerceptionObstacle() != nullptr) {
adc_position[0] = pose_container->ToPerceptionObstacle()->position().x();
adc_position[1] = pose_container->ToPerceptionObstacle()->position().y();
PredictionMap* map = PredictionMap::instance();
std::string obstacle_lane_id = lane_sequence.lane_segment(0).lane_id();
double obstacle_lane_s = lane_sequence.lane_segment(0).start_s();
double lane_s = 0.0;
double lane_l = 0.0;
if (map->GetProjection(adc_position, map->LaneById(obstacle_lane_id),
&lane_s, &lane_l)) {
ADEBUG << "Distance with ADC is " << std::fabs(lane_s - obstacle_lane_s);
return std::fabs(lane_s - obstacle_lane_s);
}
}
ADEBUG << "Invalid ADC pose.";
return std::numeric_limits<double>::max();
}
bool SequencePredictor::LaneSequenceWithMaxProb(const LaneChangeType& type,
const double& probability,
const double& max_prob) {
if (probability > max_prob) {
return true;
} else {
double prob_diff = std::fabs(probability - max_prob);
if (prob_diff <= std::numeric_limits<double>::epsilon() &&
type == LaneChangeType::STRAIGHT) {
return true;
}
}
return false;
}
bool SequencePredictor::LaneChangeWithMaxProb(const LaneChangeType& type,
const double& probability,
const double& max_prob) {
if (type == LaneChangeType::LEFT || type == LaneChangeType::RIGHT) {
if (probability > max_prob) {
return true;
}
}
return false;
}
} // namespace prediction
} // namespace apollo
<|endoftext|> |
<commit_before>// SqlBak.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
// The following come from "SQL Server 2005 Virtual Backup Device Interface (VDI) Specification"
// http://www.microsoft.com/downloads/en/details.aspx?familyid=416f8a51-65a3-4e8e-a4c8-adfe15e850fc
#include "vdi/vdi.h" // interface declaration
#include "vdi/vdierror.h" // error constants
#include "vdi/vdiguid.h" // define the interface identifiers.
// Globals
TCHAR* _serverInstanceName;
bool _optionQuiet = false;
// printf to stdout (if -q quiet option isn't specified)
void log(const TCHAR* format, ...)
{
if (_optionQuiet)
return;
// Basically do a fprintf to stderr. The va_* stuff is just to handle variable args
va_list arglist;
va_start(arglist, format);
vfwprintf(stderr, format, arglist);
}
// printf to stdout (regardless of -q quiet option)
void err(const TCHAR* format, ...)
{
va_list arglist;
va_start(arglist, format);
vfwprintf(stderr, format, arglist);
}
// Get human-readable message given a HRESULT
_bstr_t errorMessage(DWORD messageId)
{
LPTSTR szMessage;
if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, messageId, 0, (LPTSTR)&szMessage, 0, NULL))
{
szMessage = (LPTSTR)LocalAlloc(LPTR, 50 * sizeof(TCHAR));
_snwprintf(szMessage, 50 * sizeof(TCHAR), L"Unknown error 0x%x.\n", messageId);
}
_bstr_t retval = szMessage;
LocalFree(szMessage);
return retval;
}
// Execute the given SQL against _serverInstanceName
DWORD executeSql(TCHAR* sql)
{
//log(L"\nexecuteSql '%s'\n", sql);
HRESULT hr;
// Use '_Connection_Deprecated' interface for maximum MDAC compatibility
// BTW: Windows 7 SP1 introduced _Connection_Deprecated: http://social.msdn.microsoft.com/Forums/en/windowsgeneraldevelopmentissues/thread/3a4ce946-effa-4f77-98a6-34f11c6b5a13
_Connection_DeprecatedPtr conn;
hr = conn.CreateInstance(__uuidof(Connection));
if (FAILED(hr))
{
err(L"ADODB.Connection CreateInstance failed: %s", (TCHAR*)errorMessage(hr));
return hr;
}
// "lpc:..." ensures shared memory...
_bstr_t serverName = "lpc:.";
if (_serverInstanceName != NULL)
serverName += "\\" + _bstr_t(_serverInstanceName);
try
{
conn->ConnectionString = "Provider=SQLOLEDB; Data Source=" + serverName + "; Initial Catalog=master; Integrated Security=SSPI;";
//log(L"> Connect: %s\n", (TCHAR*)conn->ConnectionString);
conn->ConnectionTimeout = 25;
conn->Open("", "", "", adConnectUnspecified);
}
catch(_com_error e)
{
err(L"\nFailed to open connection to '" + serverName + L"': ");
err(L"%s [%s]\n", (TCHAR*)e.Description(), (TCHAR*)e.Source());
return e.Error();
}
try
{
//log(L"> SQL: %s\n", sql);
variant_t recordsAffected;
conn->CommandTimeout = 0;
conn->Execute(sql, &recordsAffected, adExecuteNoRecords);
conn->Close();
}
catch(_com_error e)
{
err(L"\nQuery failed: '%s'\n\n%s [%s]\n", sql, (TCHAR*)e.Description(), (TCHAR*)e.Source());
//err(L" Errors:\n", conn->Errors->Count);
//for (int i = 0; i < conn->Errors->Count; i++)
// err(L" - %s\n\n", (TCHAR*)conn->Errors->Item[i]->Description);
conn->Close();
return e.Error();
}
return 0;
}
// Transfer data from virtualDevice to backupfile or vice-versa
HRESULT performTransfer(IClientVirtualDevice* virtualDevice, FILE* backupfile)
{
VDC_Command * cmd;
DWORD completionCode;
DWORD bytesTransferred;
HRESULT hr;
DWORD totalBytes = 0;
//DWORD increment = 0;
while (SUCCEEDED (hr = virtualDevice->GetCommand(3 * 60 * 1000, &cmd)))
{
//log(L">command %d, size %d\n", cmd->commandCode, cmd->size);
bytesTransferred = 0;
switch (cmd->commandCode)
{
case VDC_Read:
while(bytesTransferred < cmd->size)
bytesTransferred += fread(cmd->buffer + bytesTransferred, 1, cmd->size - bytesTransferred, backupfile);
totalBytes += bytesTransferred;
log(L"%d bytes read \r", totalBytes);
//if ((increment += bytesTransferred)> 1000000)
//{
// log(L".");
// increment = 0;
//}
cmd->size = bytesTransferred;
completionCode = ERROR_SUCCESS;
break;
case VDC_Write:
//log(L"VDC_Write - size: %d\r\n", cmd->size);
while(bytesTransferred < cmd->size)
bytesTransferred += fwrite(cmd->buffer + bytesTransferred, 1, cmd->size - bytesTransferred, backupfile);
totalBytes += bytesTransferred;
log(L"%d bytes written\r", totalBytes);
completionCode = ERROR_SUCCESS;
break;
case VDC_Flush:
//log(L"\nVDC_Flush %d\n", cmd->size);
completionCode = ERROR_SUCCESS;
break;
case VDC_ClearError:
log(L"\nVDC_ClearError\n");
//Debug::WriteLine("VDC_ClearError");
completionCode = ERROR_SUCCESS;
break;
default:
// If command is unknown...
completionCode = ERROR_NOT_SUPPORTED;
}
hr = virtualDevice->CompleteCommand(cmd, completionCode, bytesTransferred, 0);
if (FAILED(hr))
{
err(L"\nvirtualDevice->CompleteCommand failed: %s\n", (TCHAR*)errorMessage(hr));
return hr;
}
}
log(L"\n");
if (hr != VD_E_CLOSE)
{
err(L"virtualDevice->GetCommand failed: ");
if (hr == VD_E_TIMEOUT)
err(L" timeout awaiting data.\n");
else if (hr == VD_E_ABORT)
err(L" transfer was aborted.\n");
else
err(L"%s\n", (TCHAR*)errorMessage(hr));
return hr;
}
return NOERROR;
}
// Entry point
int _tmain(int argc, _TCHAR* argv[])
{
if (argc < 3)
{
err(L"\n\
Action and database required.\n\
\n\
Usage: sqlbak backup|restore <database> [options]\n\
Options:\n\
-q Quiet, don't print messages to STDERR\n\
-i instancename\n");
return 1;
}
TCHAR* command = argv[1];
TCHAR* databaseName = argv[2];
// Parse options
for (int i = 0; i < argc; i++)
{
TCHAR* arg = _wcslwr(_wcsdup(argv[i]));
if (wcscmp(arg, L"-q") == 0)
_optionQuiet = true;
if (wcscmp(arg, L"-i") == 0)
_serverInstanceName = argv[i+1];
free(arg);
}
HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
if (FAILED(hr))
{
// Switching from apartment to multi-threaded is OK
if(hr != RPC_E_CHANGED_MODE)
{
err(L"CoInitializeEx failed: ", hr);
return 1;
}
}
// Create Device Set
IClientVirtualDeviceSet2 * virtualDeviceSet;
hr = CoCreateInstance(
CLSID_MSSQL_ClientVirtualDeviceSet,
NULL,
CLSCTX_INPROC_SERVER,
IID_IClientVirtualDeviceSet2,
(void**)&virtualDeviceSet);
if (FAILED(hr))
{
err(L"Could not create VDI component. Check registration of SQLVDI.DLL. %s\n", (TCHAR*)errorMessage(hr));
return 2;
}
// Generate virtualDeviceName
TCHAR virtualDeviceName[39];
GUID guid; CoCreateGuid(&guid);
StringFromGUID2(guid, virtualDeviceName, sizeof(virtualDeviceName));
// Create Device
VDConfig vdConfig = {0};
vdConfig.deviceCount = 1;
hr = virtualDeviceSet->CreateEx(_serverInstanceName, virtualDeviceName, &vdConfig);
if (!SUCCEEDED (hr))
{
err(L"IClientVirtualDeviceSet2.CreateEx failed\r\n");
switch(hr)
{
case VD_E_INSTANCE_NAME:
err(L"Didn't recognize the SQL Server instance name '"+ _bstr_t(_serverInstanceName) + L"'.\r\n");
break;
case E_ACCESSDENIED:
err(L"Access Denied: You must be logged in as a Windows administrator to create virtual devices.\r\n");
break;
default:
err(L"%s\n", (TCHAR*)errorMessage(hr));
break;
}
return 3;
}
TCHAR* sql;
FILE* backupFile;
if (_wcsicmp(command, L"backup") == 0)
{
sql = "BACKUP DATABASE [" + _bstr_t(databaseName) + "] TO VIRTUAL_DEVICE = '" + virtualDeviceName + "'";
backupFile = stdout;
}
else if(_wcsicmp(command, L"restore") == 0)
{
hr = executeSql("CREATE DATABASE ["+ _bstr_t(databaseName) +"]");
if (FAILED(hr))
return hr;
sql = "RESTORE DATABASE [" + _bstr_t(databaseName) + "] FROM VIRTUAL_DEVICE = '" + virtualDeviceName + "' WITH REPLACE";
backupFile = stdin;
}
else
{
err(L"Unsupported command '%s': only BACKUP or RESTORE are supported.\n", command);
return 1;
}
// Invoke backup on separate thread because virtualDeviceSet->GetConfiguration will block until "BACKUP DATABASE..."
DWORD threadId;
HANDLE executeSqlThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&executeSql, (TCHAR*)sql, 0, &threadId);
//executeSqlAsync(sql);
// Ready...
hr = virtualDeviceSet->GetConfiguration(30000, &vdConfig);
if (FAILED(hr))
{
err(L"\n%s: virtualDeviceSet->GetConfiguration failed: ", command);
if (hr == VD_E_TIMEOUT)
err(L"Timed out waiting for backup to be initiated.\n");
else
err(L"%s\n", (TCHAR*)errorMessage(hr));
return 3;
}
// Steady...
IClientVirtualDevice *virtualDevice = NULL;
hr = virtualDeviceSet->OpenDevice(virtualDeviceName, &virtualDevice);
if (FAILED(hr))
{
err(L"virtualDeviceSet->OpenDevice failed: 0x%x - ");
if (hr == VD_E_TIMEOUT)
err(L" timeout.\n");
else
err(L" %s.\n", (TCHAR*)errorMessage(hr));
return 4;
}
// Go
_setmode(_fileno(backupFile), _O_BINARY);
hr = performTransfer(virtualDevice, backupFile);
WaitForSingleObject(executeSqlThread, 5000);
// Tidy up
CloseHandle(executeSqlThread);
virtualDeviceSet->Close();
virtualDevice->Release();
virtualDeviceSet->Release();
//log(L"%s: Finished.\n", command);
return hr;
}
<commit_msg>tidy up<commit_after>// SqlBak.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
// The following come from "SQL Server 2005 Virtual Backup Device Interface (VDI) Specification"
// http://www.microsoft.com/downloads/en/details.aspx?familyid=416f8a51-65a3-4e8e-a4c8-adfe15e850fc
#include "vdi/vdi.h" // interface declaration
#include "vdi/vdierror.h" // error constants
#include "vdi/vdiguid.h" // define the interface identifiers.
// Globals
TCHAR* _serverInstanceName;
bool _optionQuiet = false;
// printf to stdout (if -q quiet option isn't specified)
void log(const TCHAR* format, ...)
{
if (_optionQuiet)
return;
// Basically do a fprintf to stderr. The va_* stuff is just to handle variable args
va_list arglist;
va_start(arglist, format);
vfwprintf(stderr, format, arglist);
}
// printf to stdout (regardless of -q quiet option)
void err(const TCHAR* format, ...)
{
va_list arglist;
va_start(arglist, format);
vfwprintf(stderr, format, arglist);
}
// Get human-readable message given a HRESULT
_bstr_t errorMessage(DWORD messageId)
{
LPTSTR szMessage;
if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, messageId, 0, (LPTSTR)&szMessage, 0, NULL))
{
szMessage = (LPTSTR)LocalAlloc(LPTR, 50 * sizeof(TCHAR));
_snwprintf(szMessage, 50 * sizeof(TCHAR), L"Unknown error 0x%x.\n", messageId);
}
_bstr_t retval = szMessage;
LocalFree(szMessage);
return retval;
}
// Execute the given SQL against _serverInstanceName
DWORD executeSql(TCHAR* sql)
{
//log(L"\nexecuteSql '%s'\n", sql);
HRESULT hr;
// Use '_Connection_Deprecated' interface for maximum MDAC compatibility
// BTW: Windows 7 SP1 introduced _Connection_Deprecated: See:
// http://social.msdn.microsoft.com/Forums/en/windowsgeneraldevelopmentissues/thread/3a4ce946-effa-4f77-98a6-34f11c6b5a13
// and
// http://support.microsoft.com/kb/2517589
_Connection_DeprecatedPtr conn;
hr = conn.CreateInstance(__uuidof(Connection));
if (FAILED(hr))
{
err(L"ADODB.Connection CreateInstance failed: %s", (TCHAR*)errorMessage(hr));
return hr;
}
// "lpc:..." ensures shared memory...
_bstr_t serverName = "lpc:.";
if (_serverInstanceName != NULL)
serverName += "\\" + _bstr_t(_serverInstanceName);
try
{
conn->ConnectionString = "Provider=SQLOLEDB; Data Source=" + serverName + "; Initial Catalog=master; Integrated Security=SSPI;";
//log(L"> Connect: %s\n", (TCHAR*)conn->ConnectionString);
conn->ConnectionTimeout = 25;
conn->Open("", "", "", adConnectUnspecified);
}
catch(_com_error e)
{
err(L"\nFailed to open connection to '" + serverName + L"': ");
err(L"%s [%s]\n", (TCHAR*)e.Description(), (TCHAR*)e.Source());
return e.Error();
}
try
{
//log(L"> SQL: %s\n", sql);
variant_t recordsAffected;
conn->CommandTimeout = 0;
conn->Execute(sql, &recordsAffected, adExecuteNoRecords);
conn->Close();
}
catch(_com_error e)
{
err(L"\nQuery failed: '%s'\n\n%s [%s]\n", sql, (TCHAR*)e.Description(), (TCHAR*)e.Source());
//err(L" Errors:\n", conn->Errors->Count);
//for (int i = 0; i < conn->Errors->Count; i++)
// err(L" - %s\n\n", (TCHAR*)conn->Errors->Item[i]->Description);
conn->Close();
return e.Error();
}
return 0;
}
// Transfer data from virtualDevice to backupfile or vice-versa
HRESULT performTransfer(IClientVirtualDevice* virtualDevice, FILE* backupfile)
{
VDC_Command * cmd;
DWORD completionCode;
DWORD bytesTransferred;
HRESULT hr;
DWORD totalBytes = 0;
while (SUCCEEDED (hr = virtualDevice->GetCommand(3 * 60 * 1000, &cmd)))
{
//log(L">command %d, size %d\n", cmd->commandCode, cmd->size);
bytesTransferred = 0;
switch (cmd->commandCode)
{
case VDC_Read:
while(bytesTransferred < cmd->size)
bytesTransferred += fread(cmd->buffer + bytesTransferred, 1, cmd->size - bytesTransferred, backupfile);
totalBytes += bytesTransferred;
log(L"%d bytes read \r", totalBytes);
cmd->size = bytesTransferred;
completionCode = ERROR_SUCCESS;
break;
case VDC_Write:
//log(L"VDC_Write - size: %d\r\n", cmd->size);
while(bytesTransferred < cmd->size)
bytesTransferred += fwrite(cmd->buffer + bytesTransferred, 1, cmd->size - bytesTransferred, backupfile);
totalBytes += bytesTransferred;
log(L"%d bytes written\r", totalBytes);
completionCode = ERROR_SUCCESS;
break;
case VDC_Flush:
//log(L"\nVDC_Flush %d\n", cmd->size);
completionCode = ERROR_SUCCESS;
break;
case VDC_ClearError:
log(L"\nVDC_ClearError\n");
//Debug::WriteLine("VDC_ClearError");
completionCode = ERROR_SUCCESS;
break;
default:
// If command is unknown...
completionCode = ERROR_NOT_SUPPORTED;
}
hr = virtualDevice->CompleteCommand(cmd, completionCode, bytesTransferred, 0);
if (FAILED(hr))
{
err(L"\nvirtualDevice->CompleteCommand failed: %s\n", (TCHAR*)errorMessage(hr));
return hr;
}
}
log(L"\n");
if (hr != VD_E_CLOSE)
{
err(L"virtualDevice->GetCommand failed: ");
if (hr == VD_E_TIMEOUT)
err(L" timeout awaiting data.\n");
else if (hr == VD_E_ABORT)
err(L" transfer was aborted.\n");
else
err(L"%s\n", (TCHAR*)errorMessage(hr));
return hr;
}
return NOERROR;
}
// Entry point
int _tmain(int argc, _TCHAR* argv[])
{
if (argc < 3)
{
err(L"\n\
Action and database required.\n\
\n\
Usage: sqlbak backup|restore <database> [options]\n\
Options:\n\
-q Quiet, don't print messages to STDERR\n\
-i instancename\n");
return 1;
}
TCHAR* command = argv[1];
TCHAR* databaseName = argv[2];
// Parse options
for (int i = 0; i < argc; i++)
{
TCHAR* arg = _wcslwr(_wcsdup(argv[i]));
if (wcscmp(arg, L"-q") == 0)
_optionQuiet = true;
if (wcscmp(arg, L"-i") == 0)
_serverInstanceName = argv[i+1];
free(arg);
}
HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
if (FAILED(hr))
{
// Switching from apartment to multi-threaded is OK
if(hr != RPC_E_CHANGED_MODE)
{
err(L"CoInitializeEx failed: ", hr);
return 1;
}
}
// Create Device Set
IClientVirtualDeviceSet2 * virtualDeviceSet;
hr = CoCreateInstance(
CLSID_MSSQL_ClientVirtualDeviceSet,
NULL,
CLSCTX_INPROC_SERVER,
IID_IClientVirtualDeviceSet2,
(void**)&virtualDeviceSet);
if (FAILED(hr))
{
err(L"Could not create VDI component. Check registration of SQLVDI.DLL. %s\n", (TCHAR*)errorMessage(hr));
return 2;
}
// Generate virtualDeviceName
TCHAR virtualDeviceName[39];
GUID guid; CoCreateGuid(&guid);
StringFromGUID2(guid, virtualDeviceName, sizeof(virtualDeviceName));
// Create Device
VDConfig vdConfig = {0};
vdConfig.deviceCount = 1;
hr = virtualDeviceSet->CreateEx(_serverInstanceName, virtualDeviceName, &vdConfig);
if (!SUCCEEDED (hr))
{
err(L"IClientVirtualDeviceSet2.CreateEx failed\r\n");
switch(hr)
{
case VD_E_INSTANCE_NAME:
err(L"Didn't recognize the SQL Server instance name '"+ _bstr_t(_serverInstanceName) + L"'.\r\n");
break;
case E_ACCESSDENIED:
err(L"Access Denied: You must be logged in as a Windows administrator to create virtual devices.\r\n");
break;
default:
err(L"%s\n", (TCHAR*)errorMessage(hr));
break;
}
return 3;
}
TCHAR* sql;
FILE* backupFile;
if (_wcsicmp(command, L"backup") == 0)
{
sql = "BACKUP DATABASE [" + _bstr_t(databaseName) + "] TO VIRTUAL_DEVICE = '" + virtualDeviceName + "'";
backupFile = stdout;
}
else if(_wcsicmp(command, L"restore") == 0)
{
hr = executeSql("CREATE DATABASE ["+ _bstr_t(databaseName) +"]");
if (FAILED(hr))
return hr;
sql = "RESTORE DATABASE [" + _bstr_t(databaseName) + "] FROM VIRTUAL_DEVICE = '" + virtualDeviceName + "' WITH REPLACE";
backupFile = stdin;
}
else
{
err(L"Unsupported command '%s': only BACKUP or RESTORE are supported.\n", command);
return 1;
}
// Invoke backup on separate thread because virtualDeviceSet->GetConfiguration will block until "BACKUP DATABASE..."
DWORD threadId;
HANDLE executeSqlThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&executeSql, (TCHAR*)sql, 0, &threadId);
// Ready...
hr = virtualDeviceSet->GetConfiguration(30000, &vdConfig);
if (FAILED(hr))
{
err(L"\n%s: virtualDeviceSet->GetConfiguration failed: ", command);
if (hr == VD_E_TIMEOUT)
err(L"Timed out waiting for backup to be initiated.\n");
else
err(L"%s\n", (TCHAR*)errorMessage(hr));
return 3;
}
// Steady...
IClientVirtualDevice *virtualDevice = NULL;
hr = virtualDeviceSet->OpenDevice(virtualDeviceName, &virtualDevice);
if (FAILED(hr))
{
err(L"virtualDeviceSet->OpenDevice failed: 0x%x - ");
if (hr == VD_E_TIMEOUT)
err(L" timeout.\n");
else
err(L" %s.\n", (TCHAR*)errorMessage(hr));
return 4;
}
// Go
_setmode(_fileno(backupFile), _O_BINARY);
hr = performTransfer(virtualDevice, backupFile);
WaitForSingleObject(executeSqlThread, 5000);
// Tidy up
CloseHandle(executeSqlThread);
virtualDeviceSet->Close();
virtualDevice->Release();
virtualDeviceSet->Release();
//log(L"%s: Finished.\n", command);
return hr;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015 Flowgrammable.org
// All rights reserved
#ifndef LIBMATCH_HASH_HPP
#define LIBMATCH_HASH_HPP
// The hashing module...
//
// TODO: Actually document the hash table.
#include <vector>
namespace hash_table
{
constexpr long table_sizes[] = {
29, 53, 97, 193, 389, 769, 1543, 3079,
6151, 12289, 24593, 49157, 98317, 196613,
393241, 786433, 1572869, 3145739, 6191469,
12582917, 25165843, 50331653, 100663319,
201326611, 402653189, 805306457, 1610612741
}
namespace data_store
{
// A simple key-value pair
template<typename K, typename V>
struct entry
{
entry()
: key(K()),val(V())
{ }
entry(K const& k, V const& v)
: key(k),val(v)
{ }
K key;
V val;
};
// A linked key-value pair
template<typename K, typename V>
struct list_entry : entry<K, V>
{
list_entry()
: entry<K, V>(), next(nullptr)
{ }
list_entry(K const& k, V const& v)
: entry<K, V>(k, v), next(nullptr)
{ }
~list_entry()
{
if (nullptr != next)
delete next;
}
list_entry<K, V>* next;
};
// A tree node key-value pair
template<typename K, typename V>
struct tree_entry : entry<K, V>
{
tree_entry()
: entry<K, V>(), left(nullptr), right(nullptr)
{ }
tree_entry(K const& k, V const& v)
: entry<K, V>(k, v), left(nullptr), right(nullptr)
{ }
tree_entry<K, V>* left;
tree_entry<K, V>* right;
};
// A basic hash table bucket containing a single entry
template<typename K, typename V>
struct basic_bucket : public entry<K, V>
{
basic_bucket()
: entry<K, V>(), empty(true)
{ }
basic_bucket(K const& k, V const& v)
: entry<K, V>(k, v), empty(false)
{ }
bool
is_empty()
{
return empty;
}
void
add(K const& k, V const& v)
{
this->key = k;
this->val = v;
empty = false;
}
void
clear()
{
empty = true;
}
bool empty;
};
// A chained hash table bucket containing chained entries
template<typename K, typename V>
struct list_bucket
{
list_bucket()
: head(nullptr), size(0), empty(true)
{ }
~list_bucket()
{
if (nullptr != head)
delete head;
}
bool
is_empty()
{
return empty;
}
void
add(K const& k, V const& v)
{
list_entry<K, V>* nh = new list_entry<K, V>(k, v);
nh->next = head;
head = nh;
empty = false;
size++;
}
void
clear()
{
// TODO: implement this
empty = true;
size = 0;
}
list_entry<K, V>* head;
int size;
bool empty;
};
// An array based hash table bucket
template<typename K, typename V>
struct array_bucket
{
array_bucket()
: size(0), capacity(7), empty(true)
{
data = new entry<K, V>[capacity];
}
array_bucket(int n)
: size(0), capacity(n), empty(true)
{
data = new entry<K, V>[n];
}
~array_bucket()
{
delete[] data;
}
void
add(K const& k, V const& v)
{
if (size + 1 < capacity) {
data[size++] = entry<K, V>(k, v);
empty = false;
}
}
bool
is_empty()
{
return empty;
}
void
clear()
{
// TODO: implement this
empty = true;
size = 0;
}
entry<K, V>* data;
int size;
int capacity;
bool empty;
};
// A tree based hash table bucket
// TODO: implement this using an array, not pointers
template<typename K, typename V>
struct tree_bucket : tree_entry<K, V>
{
tree_bucket()
: tree_entry<K, V>(), empty(true)
{ }
tree_bucket(K const& k, V const& v)
: tree_entry<K, V>(k, v), empty(false)
{ }
~tree_bucket()
{
// TODO: may need to do this different
if (nullptr != this->left)
delete this->left;
if (nullptr != this->right)
delete this->right;
}
void
add(K const& k, V const& v)
{
// TODO: balance & sort the tree when adding to it
this->key = k;
this->val = v;
empty = false;
}
bool
is_empty()
{
return empty;
}
void
clear()
{
// TODO: implement this
empty = true;
}
bool empty;
};
} // end namespace data_store
// Encapsulates the open addressing hash table family
namespace open
{
// A hash table with open addressing and linear probing for
// resolving collisions.
template<typename K, typename V, typename H, typename C>
class linear
{
public:
using store_type = std::vector<data_store::basic_bucket<K, V>>;
using value_type = data_store::basic_bucket<K, V>;
using hasher = H;
using compare = C;
linear()
: linear(17)
{ }
linear(int n)
: linear(n, hasher(), compare())
{ }
linear(int n, hasher h, compare c)
: size_(0), buckets_(n), hash_(h), cmp_(c), data_(n)
{ }
// Observers
int size() const { return size_; }
int buckets() const { return buckets_; }
bool empty() const { return size_ == 0; }
// Lookup
value_type const* find(K const&) const;
// Mutators
value_type* insert(K const&, V const&);
void erase(K const&);
private:
int get_hash_index(K const&) const;
int get_entry_index(K const&) const;
// Resizes the hash table when the load reaches a particular value
void resize();
private:
int size_; // Current number of entries
int buckets_; // Number of buckets
hasher hash_; // Hash function
compare cmp_; // Equality comparison
store_type data_; // Data store
};
// Retrieves a key-value pair from the data store
template<typename K, typename V, typename H, typename C>
auto
linear<K, V, H, C>::find(K const& key) const -> value_type const*
{
int idx = get_entry_index(key);
if (idx < 0)
return nullptr;
return &data_[idx];
}
// Inserts a new key-value pair into an empty bucket.
template<typename K, typename V, typename H, typename C>
auto
linear<K, V, H, C>::insert(K const& key, V const& value) -> value_type*
{
int idx = get_hash_index(key);
while (!data_[idx].is_empty())
idx = (idx + 1 < buckets ? idx + 1 : 0);
data_[idx] = data_store::basic_bucket<K, V>(key, value);
++size;
return &data_[idx];
}
// Clears the bucket containing the same key, if found.
template<typename K, typename V, typename H, typename C>
void
linear<K, V, H, C>::erase(K const& key)
{
int idx = get_entry_index(key);
if (idx >= 0) {
data_[idx].clear();
--size;
}
}
// Returns the index in the table for the given key or -1 if not found.
// This is guaranteed to be the actual index in the table for the key.
template<typename K, typename V, typename H, typename C>
int
linear<K, V, H, C>::get_entry_index(K const& key) const
{
int idx = get_hash_index(key);
while (!comp_(data_[idx].key, key))
idx = (idx + 1 < buckets ? idx + 1 : 0);
return (comp_(data_[idx].key, key) ? idx : -1);
}
// Returns an index in the table for a given key. This is not guaranteed
// to be the actual index for the key.
template<typename K, typename V, typename H, typename C>
inline int
linear<K, V, H, C>::get_hash_index(K const& key) const
{
return hash(key) % buckets;
}
} //end namespace open
namespace closed
{
} // end namespace closed
} // end namespace hash_table
#endif<commit_msg>Started using boost::optional for buckets<commit_after>// Copyright (c) 2015 Flowgrammable.org
// All rights reserved
#ifndef LIBMATCH_HASH_HPP
#define LIBMATCH_HASH_HPP
// The hashing module...
//
// TODO: Actually document the hash table.
#include <vector>
#include <boost/optional.hpp>
namespace hash_table
{
constexpr long table_sizes[] = {
29, 53, 97, 193, 389, 769, 1543, 3079,
6151, 12289, 24593, 49157, 98317, 196613,
393241, 786433, 1572869, 3145739, 6191469,
12582917, 25165843, 50331653, 100663319,
201326611, 402653189, 805306457, 1610612741
};
namespace data_store
{
// A key-value pair
template<typename K, typename V>
struct key_value
{
key_value()
: key(K()), val(V())
{ }
key_value(K const& k, V const& v)
: key(k), val(v)
{ }
K key;
V val;
};
// A basic entry type
template<typename K, typename V>
struct entry
{
entry()
: key(), val()
{ }
entry(K const& k, V const& v)
: key(k), val(v)
{ }
K key;
V val;
};
// A linked key-value pair
template<typename K, typename V>
struct list_entry : entry<K, V>
{
list_entry()
: entry<K, V>(), next(nullptr)
{ }
list_entry(K const& k, V const& v)
: entry<K, V>(k, v), next(nullptr)
{ }
~list_entry()
{
if (nullptr != next)
delete next;
}
list_entry<K, V>* next;
};
// A tree node key-value pair
template<typename K, typename V>
struct tree_entry : entry<K, V>
{
tree_entry()
: entry<K, V>(), left(nullptr), right(nullptr)
{ }
tree_entry(K const& k, V const& v)
: entry<K, V>(k, v), left(nullptr), right(nullptr)
{ }
tree_entry<K, V>* left;
tree_entry<K, V>* right;
};
// A basic hash table bucket containing a single entry
template<typename T>
struct basic_bucket
{
basic_bucket()
{ }
basic_bucket(T const& v)
{
data_.emplace(v);
}
// Accessors
// Retrieves the current value from the bucket. This can be a
// usable value or the boost::none value to indicate it is not
// set.
boost::optional<T>
open()
{
return (full() ? *data_ : boost::none);
}
// Checks if the bucket contains a usable value
inline bool
full()
{
return data_ != boost::none;
}
// Mutators
// Adds an item to the bucket if it is not full
void
fill(T const& v)
{
if (!full())
data_.emplace(v);
}
// Clears the bucket of its current value(s)
void
dump()
{
data_ = boost::none;
}
// Data members
boost::optional<T> data_;
};
// A chained hash table bucket containing chained entries
template<typename K, typename V>
struct list_bucket
{
list_bucket()
: head(nullptr), size(0), empty(true)
{ }
~list_bucket()
{
if (nullptr != head)
delete head;
}
bool
is_empty()
{
return empty;
}
void
add(K const& k, V const& v)
{
list_entry<K, V>* nh = new list_entry<K, V>(k, v);
nh->next = head;
head = nh;
empty = false;
size++;
}
void
clear()
{
// TODO: implement this
empty = true;
size = 0;
}
list_entry<K, V>* head;
int size;
bool empty;
};
// An array based hash table bucket
template<typename K, typename V>
struct array_bucket
{
array_bucket()
: size(0), capacity(7), empty(true)
{
data = new entry<K, V>[capacity];
}
array_bucket(int n)
: size(0), capacity(n), empty(true)
{
data = new entry<K, V>[n];
}
~array_bucket()
{
delete[] data;
}
void
add(K const& k, V const& v)
{
if (size + 1 < capacity) {
data[size++] = entry<K, V>(k, v);
empty = false;
}
}
bool
is_empty()
{
return empty;
}
void
clear()
{
// TODO: implement this
empty = true;
size = 0;
}
entry<K, V>* data;
int size;
int capacity;
bool empty;
};
// A tree based hash table bucket
// TODO: implement this using an array, not pointers
template<typename K, typename V>
struct tree_bucket : tree_entry<K, V>
{
tree_bucket()
: tree_entry<K, V>(), empty(true)
{ }
tree_bucket(K const& k, V const& v)
: tree_entry<K, V>(k, v), empty(false)
{ }
~tree_bucket()
{
// TODO: may need to do this different
if (nullptr != this->left)
delete this->left;
if (nullptr != this->right)
delete this->right;
}
void
add(K const& k, V const& v)
{
// TODO: balance & sort the tree when adding to it
this->key = k;
this->val = v;
empty = false;
}
bool
is_empty()
{
return empty;
}
void
clear()
{
// TODO: implement this
empty = true;
}
bool empty;
};
} // end namespace data_store
// Encapsulates the open addressing hash table family
namespace open
{
// A hash table with open addressing and linear probing for
// resolving collisions.
template<typename K, typename V, typename H, typename C>
class linear
{
public:
using store_type = std::vector<data_store::basic_bucket<data_store::entry<K, V>>>;
using value_type = data_store::basic_bucket<data_store::entry<K, V>>;
using hasher = H;
using compare = C;
linear()
: linear(17)
{ }
linear(int n)
: linear(n, hasher(), compare())
{ }
linear(int n, hasher h, compare c)
: size_(0), buckets_(n), hash_(h), cmp_(c), data_(n)
{ }
// Observers
int size() const { return size_; }
int buckets() const { return buckets_; }
bool empty() const { return size_ == 0; }
// Lookup
value_type const* find(K const&) const;
// Mutators
value_type* insert(K const&, V const&);
void erase(K const&);
private:
int get_hash_index(K const&) const;
int get_entry_index(K const&) const;
// Resizes the hash table when the load reaches a particular value
void resize();
private:
int size_; // Current number of entries
int buckets_; // Number of buckets
hasher hash_; // Hash function
compare cmp_; // Equality comparison
store_type data_; // Data store
};
// Retrieves a key-value pair from the data store
template<typename K, typename V, typename H, typename C>
auto
linear<K, V, H, C>::find(K const& key) const -> value_type const*
{
int idx = get_entry_index(key);
if (idx < 0)
return nullptr;
return &data_[idx].open();
}
// Inserts a new key-value pair into an empty bucket.
template<typename K, typename V, typename H, typename C>
auto
linear<K, V, H, C>::insert(K const& key, V const& value) -> value_type*
{
int idx = get_hash_index(key);
while (!data_[idx].full())
idx = (idx + 1 < buckets ? idx + 1 : 0);
data_[idx].fill(data_store::entry<K, V>(key, value));
++size;
return &data_[idx].open();
}
// Clears the bucket containing the same key, if found.
template<typename K, typename V, typename H, typename C>
void
linear<K, V, H, C>::erase(K const& key)
{
int idx = get_entry_index(key);
if (idx >= 0) {
data_[idx].dump();
--size;
}
}
// Returns the index in the table for the given key or -1 if not found.
// This is guaranteed to be the actual index in the table for the key.
template<typename K, typename V, typename H, typename C>
int
linear<K, V, H, C>::get_entry_index(K const& key) const
{
int idx = get_hash_index(key);
while (!comp_(data_[idx], key))
idx = (idx + 1 < buckets ? idx + 1 : 0);
return (comp_(data_[idx], key) ? idx : -1);
}
// Returns an index in the table for a given key. This is not guaranteed
// to be the actual index for the key.
template<typename K, typename V, typename H, typename C>
inline int
linear<K, V, H, C>::get_hash_index(K const& key) const
{
return hash(key) % buckets;
}
} //end namespace open
namespace closed
{
} // end namespace closed
} // end namespace hash_table
#endif<|endoftext|> |
<commit_before>/*
c2ffi
Copyright (C) 2013 Ryan Pavlik
This file is part of c2ffi.
c2ffi is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
c2ffi is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with c2ffi. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <map>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/Host.h>
#include <llvm/ADT/IntrusiveRefCntPtr.h>
#include <clang/Basic/DiagnosticOptions.h>
#include <clang/Frontend/TextDiagnosticPrinter.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Basic/TargetOptions.h>
#include <clang/Basic/TargetInfo.h>
#include <clang/Basic/FileManager.h>
#include <clang/Basic/SourceManager.h>
#include <clang/Lex/HeaderSearch.h>
#include <clang/Lex/Preprocessor.h>
#include <clang/Basic/Diagnostic.h>
#include <clang/AST/ASTContext.h>
#include <clang/AST/ASTConsumer.h>
#include <clang/Parse/Parser.h>
#include <clang/Parse/ParseAST.h>
#include "c2ffi.h"
#include "c2ffi/ast.h"
using namespace c2ffi;
static std::string value_to_string(clang::APValue *v) {
std::string s;
llvm::raw_string_ostream ss(s);
if(v->isInt() && v->getInt().isSigned())
v->getInt().print(ss, true);
else if(v->isInt())
v->getInt().print(ss, false);
else if(v->isFloat())
ss << v->getFloat().convertToDouble();
ss.flush();
return s;
}
void C2FFIASTConsumer::HandleTopLevelDeclInObjCContainer(clang::DeclGroupRef d) {
_od->write_comment("HandleTopLevelDeclInObjCContainer");
}
bool C2FFIASTConsumer::HandleTopLevelDecl(clang::DeclGroupRef d) {
clang::DeclGroupRef::iterator it;
for(it = d.begin(); it != d.end(); it++) {
Decl *decl = NULL;
if((*it)->isInvalidDecl()) {
std::cerr << "Skipping invalid Decl:" << std::endl;
(*it)->dump();
continue;
}
if_cast(x, clang::VarDecl, *it) { decl = make_decl(x); }
else if_cast(x, clang::FunctionDecl, *it) { decl = make_decl(x); }
else if_cast(x, clang::RecordDecl, *it) { decl = make_decl(x); }
else if_cast(x, clang::EnumDecl, *it) { decl = make_decl(x); }
else if_cast(x, clang::TypedefDecl, *it) { decl = make_decl(x); }
/* ObjC */
else if_cast(x, clang::ObjCInterfaceDecl, *it) { decl = make_decl(x); }
else if_cast(x, clang::ObjCCategoryDecl, *it) { decl = make_decl(x); }
else if_cast(x, clang::ObjCProtocolDecl, *it) { decl = make_decl(x); }
else if_cast(x, clang::ObjCImplementationDecl, *it) continue;
else if_cast(x, clang::ObjCMethodDecl, *it) continue;
/* Always should be last */
else if_cast(x, clang::NamedDecl, *it) { decl = make_decl(x); }
else decl = make_decl(*it);
if(decl) {
decl->set_location(_ci, (*it));
if(_mid) _od->write_between();
else _mid = true;
_od->write(*decl);
delete decl;
}
}
return true;
}
bool C2FFIASTConsumer::is_cur_decl(const clang::Decl *d) const {
return _cur_decls.count(d);
}
Decl* C2FFIASTConsumer::make_decl(const clang::Decl *d, bool is_toplevel) {
return new UnhandledDecl("", d->getDeclKindName());
}
Decl* C2FFIASTConsumer::make_decl(const clang::NamedDecl *d, bool is_toplevel) {
return new UnhandledDecl(d->getDeclName().getAsString(),
d->getDeclKindName());
}
Decl* C2FFIASTConsumer::make_decl(const clang::FunctionDecl *d, bool is_toplevel) {
_cur_decls.insert(d);
const clang::Type *return_type = d->getResultType().getTypePtr();
FunctionDecl *fd = new FunctionDecl(d->getDeclName().getAsString(),
Type::make_type(this, return_type),
d->isVariadic());
for(clang::FunctionDecl::param_const_iterator i = d->param_begin();
i != d->param_end(); i++) {
fd->add_field(this, *i);
}
return fd;
}
Decl* C2FFIASTConsumer::make_decl(const clang::VarDecl *d, bool is_toplevel) {
clang::ASTContext &ctx = _ci.getASTContext();
clang::APValue *v = NULL;
std::string name = d->getDeclName().getAsString(),
value = "";
bool is_string = false;
if(name.substr(0, 8) == "__c2ffi_")
name = name.substr(8, std::string::npos);
if(d->hasInit() && ((v = d->evaluateValue()) ||
(v = d->getEvaluatedValue()))) {
if(v->isLValue()) {
clang::APValue::LValueBase base = v->getLValueBase();
const clang::Expr *e = base.get<const clang::Expr*>();
if_const_cast(s, clang::StringLiteral, e) {
value = s->getString();
is_string = true;
}
} else {
value = value_to_string(v);
}
}
Type *t = Type::make_type(this, d->getTypeSourceInfo()->getType().getTypePtr());
return new VarDecl(name, t, value, d->hasExternalStorage(), is_string);
}
Decl* C2FFIASTConsumer::make_decl(const clang::RecordDecl *d, bool is_toplevel) {
std::string name = d->getDeclName().getAsString();
clang::ASTContext &ctx = _ci.getASTContext();
const clang::Type *t = d->getTypeForDecl();
if(is_toplevel && name == "") return NULL;
_cur_decls.insert(d);
RecordDecl *rd = new RecordDecl(name, d->isUnion());
if(!t->isIncompleteType()) {
rd->set_bit_size(ctx.getTypeSize(t));
rd->set_bit_alignment(ctx.getTypeAlign(t));
} else {
rd->set_bit_size(0);
rd->set_bit_alignment(0);
}
if(name == "") {
_anon_decls[d] = _anon_id;
rd->set_id(_anon_id);
_anon_id++;
}
for(clang::RecordDecl::field_iterator i = d->field_begin();
i != d->field_end(); i++)
rd->add_field(this, *i);
return rd;
}
Decl* C2FFIASTConsumer::make_decl(const clang::TypedefDecl *d, bool is_toplevel) {
return new TypedefDecl(d->getDeclName().getAsString(),
Type::make_type(this, d->getTypeSourceInfo()->getType().getTypePtr()));
}
Decl* C2FFIASTConsumer::make_decl(const clang::EnumDecl *d, bool is_toplevel) {
std::string name = d->getDeclName().getAsString();
_cur_decls.insert(d);
EnumDecl *decl = new EnumDecl(name);
if(name == "") {
_anon_decls[d] = _anon_id;
decl->set_id(_anon_id);
_anon_id++;
}
for(clang::EnumDecl::enumerator_iterator i = d->enumerator_begin();
i != d->enumerator_end(); i++) {
const clang::EnumConstantDecl *ecd = (*i);
decl->add_field(ecd->getDeclName().getAsString(),
ecd->getInitVal().getLimitedValue());
}
return decl;
}
Decl* C2FFIASTConsumer::make_decl(const clang::ObjCInterfaceDecl *d, bool is_toplevel) {
const clang::ObjCInterfaceDecl *super = d->getSuperClass();
_cur_decls.insert(d);
ObjCInterfaceDecl *r = new ObjCInterfaceDecl(d->getDeclName().getAsString(),
super ? super->getDeclName().getAsString() : "",
!d->hasDefinition());
for(clang::ObjCInterfaceDecl::protocol_iterator i = d->protocol_begin();
i != d->protocol_end(); i++)
r->add_protocol((*i)->getDeclName().getAsString());
for(clang::ObjCInterfaceDecl::ivar_iterator i = d->ivar_begin();
i != d->ivar_end(); i++) {
r->add_field(this, *i);
}
r->add_functions(this, d);
return r;
}
Decl* C2FFIASTConsumer::make_decl(const clang::ObjCCategoryDecl *d, bool is_toplevel) {
ObjCCategoryDecl *r = new ObjCCategoryDecl(d->getClassInterface()->getDeclName().getAsString(),
d->getDeclName().getAsString());
_cur_decls.insert(d);
r->add_functions(this, d);
return r;
}
Decl* C2FFIASTConsumer::make_decl(const clang::ObjCProtocolDecl *d, bool is_toplevel) {
ObjCProtocolDecl *r = new ObjCProtocolDecl(d->getDeclName().getAsString());
_cur_decls.insert(d);
r->add_functions(this, d);
return r;
}
unsigned int C2FFIASTConsumer::decl_id(const clang::Decl *d) const {
ClangDeclIDMap::const_iterator it = _anon_decls.find(d);
if(it != _anon_decls.end())
return it->second;
else
return 0;
}
<commit_msg>Fix for typedefs with __attribute__ ((__mode__ ...))<commit_after>/*
c2ffi
Copyright (C) 2013 Ryan Pavlik
This file is part of c2ffi.
c2ffi is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
c2ffi is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with c2ffi. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <map>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/Host.h>
#include <llvm/ADT/IntrusiveRefCntPtr.h>
#include <clang/Basic/DiagnosticOptions.h>
#include <clang/Frontend/TextDiagnosticPrinter.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Basic/TargetOptions.h>
#include <clang/Basic/TargetInfo.h>
#include <clang/Basic/FileManager.h>
#include <clang/Basic/SourceManager.h>
#include <clang/Lex/HeaderSearch.h>
#include <clang/Lex/Preprocessor.h>
#include <clang/Basic/Diagnostic.h>
#include <clang/AST/ASTContext.h>
#include <clang/AST/ASTConsumer.h>
#include <clang/Parse/Parser.h>
#include <clang/Parse/ParseAST.h>
#include "c2ffi.h"
#include "c2ffi/ast.h"
using namespace c2ffi;
static std::string value_to_string(clang::APValue *v) {
std::string s;
llvm::raw_string_ostream ss(s);
if(v->isInt() && v->getInt().isSigned())
v->getInt().print(ss, true);
else if(v->isInt())
v->getInt().print(ss, false);
else if(v->isFloat())
ss << v->getFloat().convertToDouble();
ss.flush();
return s;
}
void C2FFIASTConsumer::HandleTopLevelDeclInObjCContainer(clang::DeclGroupRef d) {
_od->write_comment("HandleTopLevelDeclInObjCContainer");
}
bool C2FFIASTConsumer::HandleTopLevelDecl(clang::DeclGroupRef d) {
clang::DeclGroupRef::iterator it;
for(it = d.begin(); it != d.end(); it++) {
Decl *decl = NULL;
if((*it)->isInvalidDecl()) {
std::cerr << "Skipping invalid Decl:" << std::endl;
(*it)->dump();
continue;
}
if_cast(x, clang::VarDecl, *it) { decl = make_decl(x); }
else if_cast(x, clang::FunctionDecl, *it) { decl = make_decl(x); }
else if_cast(x, clang::RecordDecl, *it) { decl = make_decl(x); }
else if_cast(x, clang::EnumDecl, *it) { decl = make_decl(x); }
else if_cast(x, clang::TypedefDecl, *it) { decl = make_decl(x); }
/* ObjC */
else if_cast(x, clang::ObjCInterfaceDecl, *it) { decl = make_decl(x); }
else if_cast(x, clang::ObjCCategoryDecl, *it) { decl = make_decl(x); }
else if_cast(x, clang::ObjCProtocolDecl, *it) { decl = make_decl(x); }
else if_cast(x, clang::ObjCImplementationDecl, *it) continue;
else if_cast(x, clang::ObjCMethodDecl, *it) continue;
/* Always should be last */
else if_cast(x, clang::NamedDecl, *it) { decl = make_decl(x); }
else decl = make_decl(*it);
if(decl) {
decl->set_location(_ci, (*it));
if(_mid) _od->write_between();
else _mid = true;
_od->write(*decl);
delete decl;
}
}
return true;
}
bool C2FFIASTConsumer::is_cur_decl(const clang::Decl *d) const {
return _cur_decls.count(d);
}
Decl* C2FFIASTConsumer::make_decl(const clang::Decl *d, bool is_toplevel) {
return new UnhandledDecl("", d->getDeclKindName());
}
Decl* C2FFIASTConsumer::make_decl(const clang::NamedDecl *d, bool is_toplevel) {
return new UnhandledDecl(d->getDeclName().getAsString(),
d->getDeclKindName());
}
Decl* C2FFIASTConsumer::make_decl(const clang::FunctionDecl *d, bool is_toplevel) {
_cur_decls.insert(d);
const clang::Type *return_type = d->getResultType().getTypePtr();
FunctionDecl *fd = new FunctionDecl(d->getDeclName().getAsString(),
Type::make_type(this, return_type),
d->isVariadic());
for(clang::FunctionDecl::param_const_iterator i = d->param_begin();
i != d->param_end(); i++) {
fd->add_field(this, *i);
}
return fd;
}
Decl* C2FFIASTConsumer::make_decl(const clang::VarDecl *d, bool is_toplevel) {
clang::ASTContext &ctx = _ci.getASTContext();
clang::APValue *v = NULL;
std::string name = d->getDeclName().getAsString(),
value = "";
bool is_string = false;
if(name.substr(0, 8) == "__c2ffi_")
name = name.substr(8, std::string::npos);
if(d->hasInit() && ((v = d->evaluateValue()) ||
(v = d->getEvaluatedValue()))) {
if(v->isLValue()) {
clang::APValue::LValueBase base = v->getLValueBase();
const clang::Expr *e = base.get<const clang::Expr*>();
if_const_cast(s, clang::StringLiteral, e) {
value = s->getString();
is_string = true;
}
} else {
value = value_to_string(v);
}
}
Type *t = Type::make_type(this, d->getTypeSourceInfo()->getType().getTypePtr());
return new VarDecl(name, t, value, d->hasExternalStorage(), is_string);
}
Decl* C2FFIASTConsumer::make_decl(const clang::RecordDecl *d, bool is_toplevel) {
std::string name = d->getDeclName().getAsString();
clang::ASTContext &ctx = _ci.getASTContext();
const clang::Type *t = d->getTypeForDecl();
if(is_toplevel && name == "") return NULL;
_cur_decls.insert(d);
RecordDecl *rd = new RecordDecl(name, d->isUnion());
if(!t->isIncompleteType()) {
rd->set_bit_size(ctx.getTypeSize(t));
rd->set_bit_alignment(ctx.getTypeAlign(t));
} else {
rd->set_bit_size(0);
rd->set_bit_alignment(0);
}
if(name == "") {
_anon_decls[d] = _anon_id;
rd->set_id(_anon_id);
_anon_id++;
}
for(clang::RecordDecl::field_iterator i = d->field_begin();
i != d->field_end(); i++)
rd->add_field(this, *i);
return rd;
}
Decl* C2FFIASTConsumer::make_decl(const clang::TypedefDecl *d, bool is_toplevel) {
return new TypedefDecl(d->getDeclName().getAsString(),
Type::make_type(this, d->getUnderlyingType().getTypePtr()));
}
Decl* C2FFIASTConsumer::make_decl(const clang::EnumDecl *d, bool is_toplevel) {
std::string name = d->getDeclName().getAsString();
_cur_decls.insert(d);
EnumDecl *decl = new EnumDecl(name);
if(name == "") {
_anon_decls[d] = _anon_id;
decl->set_id(_anon_id);
_anon_id++;
}
for(clang::EnumDecl::enumerator_iterator i = d->enumerator_begin();
i != d->enumerator_end(); i++) {
const clang::EnumConstantDecl *ecd = (*i);
decl->add_field(ecd->getDeclName().getAsString(),
ecd->getInitVal().getLimitedValue());
}
return decl;
}
Decl* C2FFIASTConsumer::make_decl(const clang::ObjCInterfaceDecl *d, bool is_toplevel) {
const clang::ObjCInterfaceDecl *super = d->getSuperClass();
_cur_decls.insert(d);
ObjCInterfaceDecl *r = new ObjCInterfaceDecl(d->getDeclName().getAsString(),
super ? super->getDeclName().getAsString() : "",
!d->hasDefinition());
for(clang::ObjCInterfaceDecl::protocol_iterator i = d->protocol_begin();
i != d->protocol_end(); i++)
r->add_protocol((*i)->getDeclName().getAsString());
for(clang::ObjCInterfaceDecl::ivar_iterator i = d->ivar_begin();
i != d->ivar_end(); i++) {
r->add_field(this, *i);
}
r->add_functions(this, d);
return r;
}
Decl* C2FFIASTConsumer::make_decl(const clang::ObjCCategoryDecl *d, bool is_toplevel) {
ObjCCategoryDecl *r = new ObjCCategoryDecl(d->getClassInterface()->getDeclName().getAsString(),
d->getDeclName().getAsString());
_cur_decls.insert(d);
r->add_functions(this, d);
return r;
}
Decl* C2FFIASTConsumer::make_decl(const clang::ObjCProtocolDecl *d, bool is_toplevel) {
ObjCProtocolDecl *r = new ObjCProtocolDecl(d->getDeclName().getAsString());
_cur_decls.insert(d);
r->add_functions(this, d);
return r;
}
unsigned int C2FFIASTConsumer::decl_id(const clang::Decl *d) const {
ClangDeclIDMap::const_iterator it = _anon_decls.find(d);
if(it != _anon_decls.end())
return it->second;
else
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <cstdlib>
#include <cstring>
#include <string>
#include "boost/program_options.hpp"
#include "Model.h"
#include "Logician.h"
#include "BookKeeper.h"
#include "Timer.h"
#include "InputXML.h"
#include "CycException.h"
#include "Env.h"
#include "Logger.h"
using namespace std;
namespace po = boost::program_options;
//-----------------------------------------------------------------------------
// Main entry point for the test application...
//-----------------------------------------------------------------------------
int main(int argc, char* argv[]) {
map<string, string> mymap;
cout << "myval: " << mymap.count("empty") << endl;
// parse command line options
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "produce help message")
("verbosity,v", po::value<string>(), "set output log verbosity level")
("input-file", po::value<string>(), "input file")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
po::positional_options_description p;
p.add("input-file", 1);
//po::variables_map vm;
po::store(po::command_line_parser(argc, argv).
options(desc).positional(p).run(), vm);
po::notify(vm);
// tell ENV the path between the cwd and the cyclus executable
string path = ENV->pathBase(argv[0]);
ENV->setCyclusPath(path);
// announce yourself
cout << "|--------------------------------------------|" << endl;
cout << "| Cyclus |" << endl;
cout << "| a nuclear fuel cycle simulator |" << endl;
cout << "| from the University of Wisconsin-Madison |" << endl;
cout << "|--------------------------------------------|" << endl;
// respond to command line args
if (vm.count("help")) {
string err_msg = "Cyclus usage requires an input file.\n";
err_msg += "Usage: cyclus [path/to/input/filename]\n";
cout << err_msg << endl;
cout << desc << "\n";
return 0;
}
if (! vm.count("input-file")) {
string err_msg = "Cyclus usage requires an input file.\n";
err_msg += "Usage: cyclus [path/to/input/filename]\n";
cout << err_msg << endl;
cout << desc << "\n";
return 0;
}
if (vm.count("verbosity")) {
Log::ReportLevel() = Log::ToLogLevel(vm["verbosity"].as<string>());
}
////// logging example //////
// use the LOG macro where its arg is the log level or type
// LEV_DEBUG is the type used for this logging statement
// the macro statment returns a string stream that can be used like cout
const int count = 3;
LOG(LEV_DEBUG) << "A loop with " << count << " iterations";
for (int i = 0; i != count; ++i) {
LOG(LEV_DEBUG1) << "the counter i = " << i;
}
////// end logging example //////
// initialize simulation
try {
// read input file and setup simulation
XMLinput->load_file(vm["input-file"].as<string>());
cout << "Here is a list of " << LI->getNumModels(CONVERTER) << " converters:" << endl;
LI->printModelList(CONVERTER);
cout << "Here is a list of " << LI->getNumModels(MARKET) << " markets:" << endl;
LI->printModelList(MARKET);
cout << "Here is a list of " << LI->getNumModels(FACILITY) << " facilities:" << endl;
LI->printModelList(FACILITY);
cout << "Here is a list of " << LI->getNumModels(REGION) << " regions:" << endl;
LI->printModelList(REGION);
cout << "Here is a list of " << LI->getNumRecipes() << " recipes:" << endl;
LI->printRecipes();
// Run the simulation
TI->runSim();
// Create the output file
BI->createDB();
BI->writeModelList(INST);
BI->writeModelList(REGION);
BI->writeModelList(FACILITY);
BI->writeModelList(MARKET);
BI->writeTransList();
BI->writeMatHist();
BI->closeDB();
} catch (CycException ge) {
cout << ge.what() << endl;
};
return 0;
}
<commit_msg>removed experimental lines I left in App.cpp from the last commit. I'm getting sloppy.<commit_after>#include <iostream>
#include <cstdlib>
#include <cstring>
#include <string>
#include "boost/program_options.hpp"
#include "Model.h"
#include "Logician.h"
#include "BookKeeper.h"
#include "Timer.h"
#include "InputXML.h"
#include "CycException.h"
#include "Env.h"
#include "Logger.h"
using namespace std;
namespace po = boost::program_options;
//-----------------------------------------------------------------------------
// Main entry point for the test application...
//-----------------------------------------------------------------------------
int main(int argc, char* argv[]) {
// parse command line options
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "produce help message")
("verbosity,v", po::value<string>(), "set output log verbosity level")
("input-file", po::value<string>(), "input file")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
po::positional_options_description p;
p.add("input-file", 1);
//po::variables_map vm;
po::store(po::command_line_parser(argc, argv).
options(desc).positional(p).run(), vm);
po::notify(vm);
// tell ENV the path between the cwd and the cyclus executable
string path = ENV->pathBase(argv[0]);
ENV->setCyclusPath(path);
// announce yourself
cout << "|--------------------------------------------|" << endl;
cout << "| Cyclus |" << endl;
cout << "| a nuclear fuel cycle simulator |" << endl;
cout << "| from the University of Wisconsin-Madison |" << endl;
cout << "|--------------------------------------------|" << endl;
// respond to command line args
if (vm.count("help")) {
string err_msg = "Cyclus usage requires an input file.\n";
err_msg += "Usage: cyclus [path/to/input/filename]\n";
cout << err_msg << endl;
cout << desc << "\n";
return 0;
}
if (! vm.count("input-file")) {
string err_msg = "Cyclus usage requires an input file.\n";
err_msg += "Usage: cyclus [path/to/input/filename]\n";
cout << err_msg << endl;
cout << desc << "\n";
return 0;
}
if (vm.count("verbosity")) {
Log::ReportLevel() = Log::ToLogLevel(vm["verbosity"].as<string>());
}
////// logging example //////
// use the LOG macro where its arg is the log level or type
// LEV_DEBUG is the type used for this logging statement
// the macro statment returns a string stream that can be used like cout
const int count = 3;
LOG(LEV_DEBUG) << "A loop with " << count << " iterations";
for (int i = 0; i != count; ++i) {
LOG(LEV_DEBUG1) << "the counter i = " << i;
}
////// end logging example //////
// initialize simulation
try {
// read input file and setup simulation
XMLinput->load_file(vm["input-file"].as<string>());
cout << "Here is a list of " << LI->getNumModels(CONVERTER) << " converters:" << endl;
LI->printModelList(CONVERTER);
cout << "Here is a list of " << LI->getNumModels(MARKET) << " markets:" << endl;
LI->printModelList(MARKET);
cout << "Here is a list of " << LI->getNumModels(FACILITY) << " facilities:" << endl;
LI->printModelList(FACILITY);
cout << "Here is a list of " << LI->getNumModels(REGION) << " regions:" << endl;
LI->printModelList(REGION);
cout << "Here is a list of " << LI->getNumRecipes() << " recipes:" << endl;
LI->printRecipes();
// Run the simulation
TI->runSim();
// Create the output file
BI->createDB();
BI->writeModelList(INST);
BI->writeModelList(REGION);
BI->writeModelList(FACILITY);
BI->writeModelList(MARKET);
BI->writeTransList();
BI->writeMatHist();
BI->closeDB();
} catch (CycException ge) {
cout << ge.what() << endl;
};
return 0;
}
<|endoftext|> |
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2016, CITEC, Bielefeld University
* 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 Willow Garage 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.
*********************************************************************/
/* Author: Robert Haschke */
#include "collision_linear_model.h"
#include "collision_matrix_model.h"
#include <QItemSelection>
#include <QPainter>
using namespace moveit_setup_assistant;
CollisionLinearModel::CollisionLinearModel(CollisionMatrixModel* src, QObject* parent) : QAbstractProxyModel(parent)
{
setSourceModel(src);
}
CollisionLinearModel::~CollisionLinearModel()
{
delete sourceModel();
}
QModelIndex CollisionLinearModel::mapFromSource(const QModelIndex& sourceIndex) const
{
// map (row,column) index to linear index k
// http://stackoverflow.com/questions/27086195/linear-index-upper-triangular-matrix
int r = sourceIndex.row(), c = sourceIndex.column();
int n = this->sourceModel()->columnCount();
if (r == c)
return QModelIndex(); // main diagonal elements are invalid
if (r > c) // only consider upper triagonal matrix
std::swap(r, c); // swap r,c if below diagonal
int k = (n * (n - 1) / 2) - (n - r) * ((n - r) - 1) / 2 + c - r - 1;
return index(k, 2);
}
QModelIndex CollisionLinearModel::mapToSource(const QModelIndex& proxyIndex) const
{
// map linear index k to (row, column)
// http://stackoverflow.com/questions/27086195/linear-index-upper-triangular-matrix
int n = sourceModel()->columnCount();
int k = proxyIndex.row(); // linear (row) index
int r = n - 2 - (int)(sqrt(-8 * k + 4 * n * (n - 1) - 7) / 2.0 - 0.5);
int c = k + r + 1 - n * (n - 1) / 2 + (n - r) * ((n - r) - 1) / 2;
return sourceModel()->index(r, c);
}
int CollisionLinearModel::rowCount(const QModelIndex& parent) const
{
int n = this->sourceModel()->rowCount();
return (n * (n - 1) / 2);
}
int CollisionLinearModel::columnCount(const QModelIndex& parent) const
{
return 4;
}
QModelIndex CollisionLinearModel::index(int row, int column, const QModelIndex& parent) const
{
return createIndex(row, column);
}
QModelIndex CollisionLinearModel::parent(const QModelIndex& child) const
{
return QModelIndex();
}
QVariant CollisionLinearModel::data(const QModelIndex& index, int role) const
{
QModelIndex srcIndex = this->mapToSource(index);
switch (index.column())
{
case 0: // link name 1
if (role != Qt::DisplayRole)
return QVariant();
else
return this->sourceModel()->headerData(srcIndex.row(), Qt::Horizontal, Qt::DisplayRole);
case 1: // link name 2
if (role != Qt::DisplayRole)
return QVariant();
return this->sourceModel()->headerData(srcIndex.column(), Qt::Vertical, Qt::DisplayRole);
case 2: // checkbox
if (role != Qt::CheckStateRole)
return QVariant();
else
return this->sourceModel()->data(srcIndex, Qt::CheckStateRole);
case 3: // reason
if (role != Qt::DisplayRole)
return QVariant();
else
return this->sourceModel()->data(srcIndex, Qt::ToolTipRole);
}
return QVariant();
}
DisabledReason CollisionLinearModel::reason(int row) const
{
QModelIndex srcIndex = this->mapToSource(index(row, 0));
return qobject_cast<CollisionMatrixModel*>(sourceModel())->reason(srcIndex);
}
bool CollisionLinearModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
QModelIndex srcIndex = this->mapToSource(index);
if (role == Qt::CheckStateRole)
{
sourceModel()->setData(srcIndex, value, role);
int r = index.row();
Q_EMIT dataChanged(this->index(r, 2), this->index(r, 3)); // reason changed too
return true;
}
return false; // reject all other changes
}
void CollisionLinearModel::setEnabled(const QItemSelection& selection, bool value)
{
for (const auto idx : selection.indexes())
{
if (idx.column() != 2) // only consider checkbox indexes
continue;
setData(idx, value ? Qt::Checked : Qt::Unchecked, Qt::CheckStateRole);
}
}
Qt::ItemFlags CollisionLinearModel::flags(const QModelIndex& index) const
{
if (index.column() == 2)
return Qt::ItemIsUserCheckable | QAbstractItemModel::flags(index);
else
return QAbstractItemModel::flags(index);
}
QVariant CollisionLinearModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role != Qt::DisplayRole)
return QVariant();
if (orientation == Qt::Horizontal)
{
switch (section)
{
case 0:
return "Link A";
case 1:
return "Link B";
case 2:
return "Disabled";
case 3:
return "Reason to Disable";
}
}
else if (orientation == Qt::Vertical)
{
return section + 1;
}
return QVariant();
}
SortFilterProxyModel::SortFilterProxyModel(QObject* parent) : QSortFilterProxyModel(parent), show_all_(false)
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
connect(this, SIGNAL(sourceModelChanged()), this, SLOT(initSorting()));
#endif
// by default: sort by link A (col 0), then link B (col 1)
sort_columns_ << 0 << 1;
sort_orders_ << Qt::AscendingOrder << Qt::AscendingOrder;
}
QVariant SortFilterProxyModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role == Qt::DisplayRole && orientation == Qt::Vertical)
return section + 1; // simply enumerate rows
else
return QSortFilterProxyModel::headerData(section, orientation, role);
}
void SortFilterProxyModel::setEnabled(const QItemSelection& selection, bool value)
{
static_cast<CollisionLinearModel*>(sourceModel())->setEnabled(mapSelectionToSource(selection), value);
}
void SortFilterProxyModel::initSorting()
{
int cols = sourceModel()->columnCount();
int prev_size = sort_columns_.size();
sort_columns_.resize(cols);
sort_orders_.resize(cols);
// initialize new entries to -1
for (int i = prev_size, end = sort_columns_.size(); i < end; ++i)
sort_columns_[i] = -1;
}
void SortFilterProxyModel::setShowAll(bool show_all)
{
if (show_all_ == show_all)
return;
show_all_ = show_all;
invalidateFilter();
}
bool SortFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const
{
CollisionLinearModel* m = qobject_cast<CollisionLinearModel*>(sourceModel());
if (!(show_all_ || m->reason(source_row) <= moveit_setup_assistant::ALWAYS ||
m->data(m->index(source_row, 2), Qt::CheckStateRole) == Qt::Checked))
return false; // not accepted due to check state
const QRegExp regexp = this->filterRegExp();
if (regexp.isEmpty())
return true;
return m->data(m->index(source_row, 0, source_parent), Qt::DisplayRole).toString().contains(regexp) ||
m->data(m->index(source_row, 1, source_parent), Qt::DisplayRole).toString().contains(regexp);
}
// define a fallback comparison operator for QVariants
#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
namespace
{
bool operator<(const QVariant& left, const QVariant& right)
{
if (left.userType() == QVariant::Type::Int)
return left.toInt() < right.toInt();
else
return left.toString() < right.toString();
}
}
#endif
bool SortFilterProxyModel::lessThan(const QModelIndex& src_left, const QModelIndex& src_right) const
{
int row_left = src_left.row();
int row_right = src_right.row();
QAbstractItemModel* m = sourceModel();
for (int i = 0, end = sort_columns_.size(); i < end && sort_columns_[i] >= 0; ++i)
{
int sc = sort_columns_[i];
int role = sc == 2 ? Qt::CheckStateRole : Qt::DisplayRole;
QVariant value_left = m->data(m->index(row_left, sc), role);
QVariant value_right = m->data(m->index(row_right, sc), role);
if (value_left == value_right)
continue;
bool smaller = (value_left < value_right);
if (sort_orders_[i] == Qt::DescendingOrder)
smaller = !smaller;
return smaller;
}
return false;
}
void SortFilterProxyModel::sort(int column, Qt::SortOrder order)
{
beginResetModel();
if (column < 0)
initSorting();
else
{
// remember sorting history
int prev_idx = sort_columns_.indexOf(column);
if (prev_idx < 0)
prev_idx = sort_columns_.size() - 1;
// remove old entries
sort_columns_.takeAt(prev_idx);
sort_orders_.remove(prev_idx);
// add new entries at front
sort_columns_.insert(0, column);
sort_orders_.insert(0, order);
}
QSortFilterProxyModel::sort(column, Qt::AscendingOrder);
endResetModel();
}
<commit_msg>remove call to takeAt for Qt4 compatibility<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2016, CITEC, Bielefeld University
* 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 Willow Garage 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.
*********************************************************************/
/* Author: Robert Haschke */
#include "collision_linear_model.h"
#include "collision_matrix_model.h"
#include <QItemSelection>
#include <QPainter>
using namespace moveit_setup_assistant;
CollisionLinearModel::CollisionLinearModel(CollisionMatrixModel* src, QObject* parent) : QAbstractProxyModel(parent)
{
setSourceModel(src);
}
CollisionLinearModel::~CollisionLinearModel()
{
delete sourceModel();
}
QModelIndex CollisionLinearModel::mapFromSource(const QModelIndex& sourceIndex) const
{
// map (row,column) index to linear index k
// http://stackoverflow.com/questions/27086195/linear-index-upper-triangular-matrix
int r = sourceIndex.row(), c = sourceIndex.column();
int n = this->sourceModel()->columnCount();
if (r == c)
return QModelIndex(); // main diagonal elements are invalid
if (r > c) // only consider upper triagonal matrix
std::swap(r, c); // swap r,c if below diagonal
int k = (n * (n - 1) / 2) - (n - r) * ((n - r) - 1) / 2 + c - r - 1;
return index(k, 2);
}
QModelIndex CollisionLinearModel::mapToSource(const QModelIndex& proxyIndex) const
{
// map linear index k to (row, column)
// http://stackoverflow.com/questions/27086195/linear-index-upper-triangular-matrix
int n = sourceModel()->columnCount();
int k = proxyIndex.row(); // linear (row) index
int r = n - 2 - (int)(sqrt(-8 * k + 4 * n * (n - 1) - 7) / 2.0 - 0.5);
int c = k + r + 1 - n * (n - 1) / 2 + (n - r) * ((n - r) - 1) / 2;
return sourceModel()->index(r, c);
}
int CollisionLinearModel::rowCount(const QModelIndex& parent) const
{
int n = this->sourceModel()->rowCount();
return (n * (n - 1) / 2);
}
int CollisionLinearModel::columnCount(const QModelIndex& parent) const
{
return 4;
}
QModelIndex CollisionLinearModel::index(int row, int column, const QModelIndex& parent) const
{
return createIndex(row, column);
}
QModelIndex CollisionLinearModel::parent(const QModelIndex& child) const
{
return QModelIndex();
}
QVariant CollisionLinearModel::data(const QModelIndex& index, int role) const
{
QModelIndex srcIndex = this->mapToSource(index);
switch (index.column())
{
case 0: // link name 1
if (role != Qt::DisplayRole)
return QVariant();
else
return this->sourceModel()->headerData(srcIndex.row(), Qt::Horizontal, Qt::DisplayRole);
case 1: // link name 2
if (role != Qt::DisplayRole)
return QVariant();
return this->sourceModel()->headerData(srcIndex.column(), Qt::Vertical, Qt::DisplayRole);
case 2: // checkbox
if (role != Qt::CheckStateRole)
return QVariant();
else
return this->sourceModel()->data(srcIndex, Qt::CheckStateRole);
case 3: // reason
if (role != Qt::DisplayRole)
return QVariant();
else
return this->sourceModel()->data(srcIndex, Qt::ToolTipRole);
}
return QVariant();
}
DisabledReason CollisionLinearModel::reason(int row) const
{
QModelIndex srcIndex = this->mapToSource(index(row, 0));
return qobject_cast<CollisionMatrixModel*>(sourceModel())->reason(srcIndex);
}
bool CollisionLinearModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
QModelIndex srcIndex = this->mapToSource(index);
if (role == Qt::CheckStateRole)
{
sourceModel()->setData(srcIndex, value, role);
int r = index.row();
Q_EMIT dataChanged(this->index(r, 2), this->index(r, 3)); // reason changed too
return true;
}
return false; // reject all other changes
}
void CollisionLinearModel::setEnabled(const QItemSelection& selection, bool value)
{
for (const auto idx : selection.indexes())
{
if (idx.column() != 2) // only consider checkbox indexes
continue;
setData(idx, value ? Qt::Checked : Qt::Unchecked, Qt::CheckStateRole);
}
}
Qt::ItemFlags CollisionLinearModel::flags(const QModelIndex& index) const
{
if (index.column() == 2)
return Qt::ItemIsUserCheckable | QAbstractItemModel::flags(index);
else
return QAbstractItemModel::flags(index);
}
QVariant CollisionLinearModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role != Qt::DisplayRole)
return QVariant();
if (orientation == Qt::Horizontal)
{
switch (section)
{
case 0:
return "Link A";
case 1:
return "Link B";
case 2:
return "Disabled";
case 3:
return "Reason to Disable";
}
}
else if (orientation == Qt::Vertical)
{
return section + 1;
}
return QVariant();
}
SortFilterProxyModel::SortFilterProxyModel(QObject* parent) : QSortFilterProxyModel(parent), show_all_(false)
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
connect(this, SIGNAL(sourceModelChanged()), this, SLOT(initSorting()));
#endif
// by default: sort by link A (col 0), then link B (col 1)
sort_columns_ << 0 << 1;
sort_orders_ << Qt::AscendingOrder << Qt::AscendingOrder;
}
QVariant SortFilterProxyModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role == Qt::DisplayRole && orientation == Qt::Vertical)
return section + 1; // simply enumerate rows
else
return QSortFilterProxyModel::headerData(section, orientation, role);
}
void SortFilterProxyModel::setEnabled(const QItemSelection& selection, bool value)
{
static_cast<CollisionLinearModel*>(sourceModel())->setEnabled(mapSelectionToSource(selection), value);
}
void SortFilterProxyModel::initSorting()
{
int cols = sourceModel()->columnCount();
int prev_size = sort_columns_.size();
sort_columns_.resize(cols);
sort_orders_.resize(cols);
// initialize new entries to -1
for (int i = prev_size, end = sort_columns_.size(); i < end; ++i)
sort_columns_[i] = -1;
}
void SortFilterProxyModel::setShowAll(bool show_all)
{
if (show_all_ == show_all)
return;
show_all_ = show_all;
invalidateFilter();
}
bool SortFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const
{
CollisionLinearModel* m = qobject_cast<CollisionLinearModel*>(sourceModel());
if (!(show_all_ || m->reason(source_row) <= moveit_setup_assistant::ALWAYS ||
m->data(m->index(source_row, 2), Qt::CheckStateRole) == Qt::Checked))
return false; // not accepted due to check state
const QRegExp regexp = this->filterRegExp();
if (regexp.isEmpty())
return true;
return m->data(m->index(source_row, 0, source_parent), Qt::DisplayRole).toString().contains(regexp) ||
m->data(m->index(source_row, 1, source_parent), Qt::DisplayRole).toString().contains(regexp);
}
// define a fallback comparison operator for QVariants
#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
namespace
{
bool operator<(const QVariant& left, const QVariant& right)
{
if (left.userType() == QVariant::Type::Int)
return left.toInt() < right.toInt();
else
return left.toString() < right.toString();
}
}
#endif
bool SortFilterProxyModel::lessThan(const QModelIndex& src_left, const QModelIndex& src_right) const
{
int row_left = src_left.row();
int row_right = src_right.row();
QAbstractItemModel* m = sourceModel();
for (int i = 0, end = sort_columns_.size(); i < end && sort_columns_[i] >= 0; ++i)
{
int sc = sort_columns_[i];
int role = sc == 2 ? Qt::CheckStateRole : Qt::DisplayRole;
QVariant value_left = m->data(m->index(row_left, sc), role);
QVariant value_right = m->data(m->index(row_right, sc), role);
if (value_left == value_right)
continue;
bool smaller = (value_left < value_right);
if (sort_orders_[i] == Qt::DescendingOrder)
smaller = !smaller;
return smaller;
}
return false;
}
void SortFilterProxyModel::sort(int column, Qt::SortOrder order)
{
beginResetModel();
if (column < 0)
initSorting();
else
{
// remember sorting history
int prev_idx = sort_columns_.indexOf(column);
if (prev_idx < 0)
prev_idx = sort_columns_.size() - 1;
// remove old entries
sort_columns_.remove(prev_idx);
sort_orders_.remove(prev_idx);
// add new entries at front
sort_columns_.insert(0, column);
sort_orders_.insert(0, order);
}
QSortFilterProxyModel::sort(column, Qt::AscendingOrder);
endResetModel();
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////
// Coop Door Controller
////////////////////////////////////////////////////////////
#include <Arduino.h>
#include <PMS.h>
#include <GPSParser.h>
#include <SaveController.h>
#include "ICommInterface.h"
#include "TelemetryTags.h"
#include "Telemetry.h"
#include "Pins.h"
#include "SunCalc.h"
#include "DoorController.h"
#include "LightController.h"
#include "BeepController.h"
#include "GaryCooper.h"
////////////////////////////////////////////////////////////
// Use GPS to decide when to open and close the coop door
////////////////////////////////////////////////////////////
CDoorController::CDoorController()
{
m_correctState = doorController_doorStateUnknown;
m_commandedState = doorController_doorStateUnknown;
m_sunriseOffset = 0.;
m_sunsetOffset = 0.;
m_stuckDoorMS = 0;
}
CDoorController::~CDoorController()
{
}
void CDoorController::setup()
{
if(getDoorMotor())
getDoorMotor()->setup();
}
void CDoorController::saveSettings(CSaveController &_saveController, bool _defaults)
{
// Should I setup for default settings?
if(_defaults)
{
setSunriseOffset(0.);
setSunsetOffset(0.);
}
// Save settings
_saveController.writeInt(getSunriseOffset());
_saveController.writeInt(getSunsetOffset());
}
void CDoorController::loadSettings(CSaveController &_saveController)
{
// Load settings
int sunriseOffset = _saveController.readInt();
setSunriseOffset(sunriseOffset);
int sunsetOffset = _saveController.readInt();
setSunsetOffset(sunsetOffset);
#ifdef DEBUG_DOOR_CONTROLLER
DEBUG_SERIAL.print(PMS("CDoorController - sunrise offset is: "));
DEBUG_SERIAL.println(getSunriseOffset());
DEBUG_SERIAL.print(PMS("CDoorController - sunset offset is :"));
DEBUG_SERIAL.println(getSunsetOffset());
DEBUG_SERIAL.println();
#endif
}
void CDoorController::tick()
{
// Let the door motor do its thing
if(!getDoorMotor())
return;
getDoorMotor()->tick();
// See of the door has been commanded to a specific state.
// If not then there is nothing to do
if(m_commandedState == doorController_doorStateUnknown)
return;
// We have commanded the door to move, so it should soon be
// in the correct state
if((m_stuckDoorMS > 0) && getDoorMotor()->getDoorState() == m_commandedState)
{
m_stuckDoorMS = 0;
#ifdef DEBUG_DOOR_CONTROLLER
DEBUG_SERIAL.println(PMS("CDoorController - door motor has reached commanded state... Monitoring ends."));
#endif
reportError(telemetry_error_door_not_responding, false);
return;
}
// The door has not reached the correct state. Has the
// timer timed out?
if(m_stuckDoorMS && millis() > m_stuckDoorMS)
{
#ifdef DEBUG_DOOR_CONTROLLER
DEBUG_SERIAL.println(PMS("CDoorController - door motor has NOT reached commanded state... Monitoring continues."));
#endif
m_stuckDoorMS = millis() + CDoorController_Stuck_door_delayMS;
reportError(telemetry_error_door_not_responding, true);
}
}
double CDoorController::getSunriseTime()
{
double sunrise = g_sunCalc.getSunriseTime() + (getSunriseOffset() / 60.);
normalizeTime(sunrise);
return sunrise;
}
double CDoorController::getSunsetTime()
{
double sunset = g_sunCalc.getSunsetTime() + (getSunsetOffset() / 60.);
normalizeTime(sunset);
return sunset;
}
void CDoorController::checkTime()
{
// First of all, if the door motor does not know the door state
// then there is nothing to do.
if(!getDoorMotor())
{
#ifdef DEBUG_DOOR_CONTROLLER
DEBUG_SERIAL.println(PMS("CDoorController - no door motor found."));
DEBUG_SERIAL.println();
#endif
reportError(telemetry_error_no_door_motor, true);
return;
}
else
{
reportError(telemetry_error_no_door_motor, false);
}
// If the door state is unknown and we are not waiting for it to
// move then we have a problem
if(m_stuckDoorMS == 0)
{
if(getDoorMotor()->getDoorState() == doorController_doorStateUnknown)
{
#ifdef DEBUG_DOOR_CONTROLLER
DEBUG_SERIAL.println(PMS("CDoorController - door motor in unknown state."));
#endif
reportError(telemetry_error_door_motor_unknown_state, true);
return;
}
else
{
#ifdef DEBUG_DOOR_CONTROLLER
DEBUG_SERIAL.println(PMS("CDoorController - door motor state OK."));
#endif
reportError(telemetry_error_door_motor_unknown_state, false);
}
}
// Get the times and keep going
double current = g_sunCalc.getCurrentTime();
double sunrise = getSunriseTime();
double sunset = getSunsetTime();
#ifdef DEBUG_DOOR_CONTROLLER
DEBUG_SERIAL.print(PMS("CDoorController - door open from: "));
debugPrintDoubleTime(getSunriseTime(), false);
DEBUG_SERIAL.print(PMS(" - "));
debugPrintDoubleTime(getSunsetTime(), false);
DEBUG_SERIAL.println(PMS(" (UTC)"));
#endif
// Validate the values and report telemetry
if(!g_sunCalc.isValidTime(sunrise))
{
reportError(telemetry_error_suncalc_invalid_time, true);
return;
}
if(!g_sunCalc.isValidTime(sunset))
{
reportError(telemetry_error_suncalc_invalid_time, true);
return;
}
reportError(telemetry_error_suncalc_invalid_time, false);
// Check to see if the door state should change.
// NOTE: we do it this way because a blind setting of the state
// each time would make it impossible to remotely command the door
// because the DoorController would keep resetting it to the "correct"
// state each minute. So, we check for changes in the correct state and
// then tell the door motor where we want it. That way, if you close the door
// early, perhaps the birds have already cooped up, then it won't keep forcing
// the door back to open until sunset.
doorController_doorStateE newCorrectState =
timeIsBetween(current, sunrise, sunset) ? doorController_doorOpen : doorController_doorClosed;
if(m_correctState != newCorrectState)
{
#ifdef COOPDOOR_CHANGE_BEEPER
if(newCorrectState)
g_beepController.beep(BEEP_FREQ_INFO, 900, 100, 2);
else
g_beepController.beep(BEEP_FREQ_INFO, 500, 500, 2);
#endif
m_correctState = newCorrectState;
setDoorState(m_correctState);
#ifdef DEBUG_DOOR_CONTROLLER
if(m_correctState)
DEBUG_SERIAL.println(PMS("CDoorController - opening coop door."));
else
DEBUG_SERIAL.println(PMS("CDoorController - closing coop door."));
#endif
}
#ifdef DEBUG_DOOR_CONTROLLER
if(m_correctState)
DEBUG_SERIAL.println(PMS("CDoorController - coop door should be OPEN."));
else
DEBUG_SERIAL.println(PMS("CDoorController - coop door should be CLOSED."));
doorController_doorStateE doorState = getDoorMotor()->getDoorState();
DEBUG_SERIAL.print(PMS("CDoorController - door motor reports: "));
DEBUG_SERIAL.println((doorState == doorController_doorOpen) ? PMS("open.") :
(doorState == doorController_doorClosed) ? PMS("closed.") :
(doorState == doorController_doorStateUnknown) ? PMS("UNKNOWN.") :
PMS("*** INVALID ***"));
DEBUG_SERIAL.println();
#endif
}
void CDoorController::sendTelemetry()
{
double sunrise = getSunriseTime();
double sunset = getSunsetTime();
// Update telemetry starting with config info
g_telemetry.transmissionStart();
g_telemetry.sendTerm(telemetry_tag_door_config);
g_telemetry.sendTerm((int)getSunriseOffset());
g_telemetry.sendTerm((int)getSunsetOffset());
g_telemetry.transmissionEnd();
// Now, current times and door state
g_telemetry.transmissionStart();
g_telemetry.sendTerm(telemetry_tag_door_info);
g_telemetry.sendTerm(sunrise);
g_telemetry.sendTerm(sunset);
// How we send the door motor state depends on if the door is
// expected to be moving. We do this to mask the "door state unknown"
// error message to the user.
doorController_doorStateE doorMotorState = getDoorMotor()->getDoorState();
if(m_stuckDoorMS == 0)
{
g_telemetry.sendTerm((int)doorMotorState);
}
else
{
if(doorMotorState == doorController_doorStateUnknown)
g_telemetry.sendTerm((int)m_commandedState);
else
g_telemetry.sendTerm((int)doorMotorState);
}
g_telemetry.transmissionEnd();
}
void CDoorController::setDoorState(doorController_doorStateE _state)
{
// Remember the commanded state, no matter who commanded it
m_commandedState = _state;
if(getDoorMotor()->getDoorState() != m_commandedState)
{
getDoorMotor()->setDesiredDoorState(m_commandedState);
#ifdef DEBUG_DOOR_CONTROLLER
DEBUG_SERIAL.println(PMS("CDoorController - starting door response monitor."));
#endif
m_stuckDoorMS = millis() + CDoorController_Stuck_door_delayMS;
}
}
<commit_msg>Delete DoorController.cpp<commit_after><|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(XALANSOURCETREEPARSERLIAISON_HEADER_GUARD_1357924680)
#define XALANSOURCETREEPARSERLIAISON_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include <XalanSourceTree/XalanSourceTreeDefinitions.hpp>
// Standard Library header files.
#include <map>
#include <XercesParserLiaison/XercesDOMSupport.hpp>
#include <XercesParserLiaison/XercesParserLiaison.hpp>
class ContentHandler;
class DTDHandler;
class LexicalHandler;
class XalanSourceTreeDOMSupport;
class XalanSourceTreeDocument;
class XALAN_XALANSOURCETREE_EXPORT XalanSourceTreeParserLiaison : public XMLParserLiaison
{
public:
/**
* Construct a XalanSourceTreeParserLiaison instance.
*
* @param theSupport instance of DOMSupport object
* @param theStartingNumber the starting number for documents
*
* @deprecated This constructor is deprecated. Use the next constructor instead.
*/
XalanSourceTreeParserLiaison(
XalanSourceTreeDOMSupport& theSupport,
DocumentNumberType theStartingNumber = 0);
/**
* Construct a XalanSourceTreeParserLiaison instance.
*
* @param theStartingNumber the starting number for documents
*/
XalanSourceTreeParserLiaison(DocumentNumberType theStartingNumber = 0);
virtual
~XalanSourceTreeParserLiaison();
/**
* Get the value of the flag which determines if the data of all
* text nodes are pooled, or just whitespace text nodes.
*
* @return true if the data of all text nodes are pooled, false otherwise.
*/
bool
getPoolAllText() const
{
return m_poolAllText;
}
/**
* Set the value of the flag which determines if the data of all
* text nodes are pooled, or just whitespace text nodes.
*
* @param fValue The new value for the flag.
*/
void
setPoolAllText(bool fValue)
{
m_poolAllText = fValue;
}
// These interfaces are inherited from XMLParserLiaison...
virtual void
reset();
virtual ExecutionContext*
getExecutionContext() const;
virtual void
setExecutionContext(ExecutionContext& theContext);
virtual XalanDocument*
parseXMLStream(
const InputSource& reader,
const XalanDOMString& identifier = XalanDOMString());
virtual void
parseXMLStream(
const InputSource& inputSource,
DocumentHandler& handler,
const XalanDOMString& identifier = XalanDOMString());
virtual XalanDocument*
createDocument();
virtual XalanDocument*
createDOMFactory();
virtual void
destroyDocument(XalanDocument* theDocument);
virtual DocumentNumberType
getNextDocumentNumber();
virtual int
getIndent() const;
virtual void
setIndent(int i);
virtual bool
getUseValidation() const;
virtual void
setUseValidation(bool b);
virtual const XalanDOMString
getParserDescription() const;
virtual EntityResolver*
getEntityResolver() const;
virtual void
setEntityResolver(EntityResolver* resolver);
// These interfaces are new to XalanSourceTreeParserLiaison...
/**
* Parse using a SAX2 ContentHandler, DTDHandler, and LexicalHandler.
*
* @param theInputSource The input source for the parser
* @param theContentHandler The ContentHandler to use
* @param theDTDHandler The DTDHandler to use. May be null.
* @param theLexicalHandler The LexicalHandler to use. May be null.
* @param identifier Used for error reporting only.
*/
virtual void
parseXMLStream(
const InputSource& theInputSource,
ContentHandler& theContentHandler,
DTDHandler* theDTDHandler = 0,
LexicalHandler* theLexicalHandler = 0,
const XalanDOMString& theIdentifier = XalanDOMString());
/** Get the 'include ignorable whitespace' flag.
*
* This method returns the state of the parser's include ignorable
* whitespace flag.
*
* @return 'true' if the include ignorable whitespace flag is set on
* the parser, 'false' otherwise.
*
* @see #setIncludeIgnorableWhitespace
*/
virtual bool
getIncludeIgnorableWhitespace() const;
/** Set the 'include ignorable whitespace' flag
*
* This method allows the user to specify whether a validating parser
* should include ignorable whitespaces as text nodes. It has no effect
* on non-validating parsers which always include non-markup text.
* <p>When set to true (also the default), ignorable whitespaces will be
* added to the DOM tree as text nodes. The method
* DOM_Text::isIgnorableWhitespace() will return true for those text
* nodes only.
* <p>When set to false, all ignorable whitespace will be discarded and
* no text node is added to the DOM tree. Note: applications intended
* to process the "xml:space" attribute should not set this flag to false.
*
* @param include The new state of the include ignorable whitespace
* flag.
*
* @see #getIncludeIgnorableWhitespace
*/
virtual void
setIncludeIgnorableWhitespace(bool include);
/**
* This method returns the installed error handler.
*
* @return A pointer to the installed error handler object.
*/
virtual ErrorHandler*
getErrorHandler() const;
/**
* This method installs the user specified error handler on
* the parser.
*
* @param handler A pointer to the error handler to be called
* when the parser comes across 'error' events
* as per the SAX specification.
*
* @see Parser#setErrorHandler
*/
virtual void
setErrorHandler(ErrorHandler* handler);
/**
* This method returns the state of the parser's namespace
* handling capability.
*
* @return true, if the parser is currently configured to
* understand namespaces, false otherwise.
*
* @see #setDoNamespaces
*/
virtual bool
getDoNamespaces() const;
/**
* This method allows users to enable or disable the parser's
* namespace processing. When set to true, parser starts enforcing
* all the constraints / rules specified by the NameSpace
* specification.
*
* <p>The parser's default state is: false.</p>
*
* <p>This flag is ignored by the underlying scanner if the installed
* validator indicates that namespace constraints should be
* enforced.</p>
*
* @param newState The value specifying whether NameSpace rules should
* be enforced or not.
*
* @see #getDoNamespaces
*/
virtual void
setDoNamespaces(bool newState);
/**
* This method returns the state of the parser's
* exit-on-First-Fatal-Error flag.
*
* @return true, if the parser is currently configured to
* exit on the first fatal error, false otherwise.
*
* @see #setExitOnFirstFatalError
*/
virtual bool
getExitOnFirstFatalError() const;
/**
* This method allows users to set the parser's behaviour when it
* encounters the first fatal error. If set to true, the parser
* will exit at the first fatal error. If false, then it will
* report the error and continue processing.
*
* <p>The default value is 'true' and the parser exits on the
* first fatal error.</p>
*
* @param newState The value specifying whether the parser should
* continue or exit when it encounters the first
* fatal error.
*
* @see #getExitOnFirstFatalError
*/
virtual void
setExitOnFirstFatalError(bool newState);
/**
* Map a pointer to a XalanDocument instance to its implementation
* class pointer. Normally, you should have no reason for doing
* this. The liaison will return a null pointer if it did not
* create the instance passed.
*
* @param theDocument A pointer to a XalanDocument instance.
* @return A pointer to the XalanSourceTreeDocument instance.
*/
XalanSourceTreeDocument*
mapDocument(const XalanDocument* theDocument) const;
/**
* Create a XalanSourceTreeDocument instance.
*
* @return A pointer to the XalanSourceTreeDocument instance.
*/
XalanSourceTreeDocument*
createXalanSourceTreeDocument();
bool
setPersistent(XalanSourceTreeDocument* theDocument);
bool
unsetPersistent(XalanSourceTreeDocument* theDocument);
#if defined(XALAN_NO_NAMESPACES)
typedef map<const XalanDocument*,
XalanSourceTreeDocument*,
less<const XalanDocument*> > DocumentMapType;
#else
typedef std::map<const XalanDocument*,
XalanSourceTreeDocument*> DocumentMapType;
#endif
DocumentNumberType
getDocumentNumber() const
{
return m_documentNumber;
}
private:
// Data members...
DocumentNumberType m_documentNumber;
XercesParserLiaison m_xercesParserLiaison;
DocumentMapType m_documentMap;
DocumentMapType m_persistentDocumentMap;
bool m_poolAllText;
static const XalanDOMChar validationString[];
};
#endif // XALANSOURCETREEPARSERLIAISON_HEADER_GUARD_1357924680
<commit_msg>Made copy constructor and operator=() private and unimplemented.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(XALANSOURCETREEPARSERLIAISON_HEADER_GUARD_1357924680)
#define XALANSOURCETREEPARSERLIAISON_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include <XalanSourceTree/XalanSourceTreeDefinitions.hpp>
// Standard Library header files.
#include <map>
#include <XercesParserLiaison/XercesDOMSupport.hpp>
#include <XercesParserLiaison/XercesParserLiaison.hpp>
class ContentHandler;
class DTDHandler;
class LexicalHandler;
class XalanSourceTreeDOMSupport;
class XalanSourceTreeDocument;
class XALAN_XALANSOURCETREE_EXPORT XalanSourceTreeParserLiaison : public XMLParserLiaison
{
public:
/**
* Construct a XalanSourceTreeParserLiaison instance.
*
* @param theSupport instance of DOMSupport object
* @param theStartingNumber the starting number for documents
*
* @deprecated This constructor is deprecated. Use the next constructor instead.
*/
XalanSourceTreeParserLiaison(
XalanSourceTreeDOMSupport& theSupport,
DocumentNumberType theStartingNumber = 0);
/**
* Construct a XalanSourceTreeParserLiaison instance.
*
* @param theStartingNumber the starting number for documents
*/
XalanSourceTreeParserLiaison(DocumentNumberType theStartingNumber = 0);
virtual
~XalanSourceTreeParserLiaison();
/**
* Get the value of the flag which determines if the data of all
* text nodes are pooled, or just whitespace text nodes.
*
* @return true if the data of all text nodes are pooled, false otherwise.
*/
bool
getPoolAllText() const
{
return m_poolAllText;
}
/**
* Set the value of the flag which determines if the data of all
* text nodes are pooled, or just whitespace text nodes.
*
* @param fValue The new value for the flag.
*/
void
setPoolAllText(bool fValue)
{
m_poolAllText = fValue;
}
// These interfaces are inherited from XMLParserLiaison...
virtual void
reset();
virtual ExecutionContext*
getExecutionContext() const;
virtual void
setExecutionContext(ExecutionContext& theContext);
virtual XalanDocument*
parseXMLStream(
const InputSource& reader,
const XalanDOMString& identifier = XalanDOMString());
virtual void
parseXMLStream(
const InputSource& inputSource,
DocumentHandler& handler,
const XalanDOMString& identifier = XalanDOMString());
virtual XalanDocument*
createDocument();
virtual XalanDocument*
createDOMFactory();
virtual void
destroyDocument(XalanDocument* theDocument);
virtual DocumentNumberType
getNextDocumentNumber();
virtual int
getIndent() const;
virtual void
setIndent(int i);
virtual bool
getUseValidation() const;
virtual void
setUseValidation(bool b);
virtual const XalanDOMString
getParserDescription() const;
virtual EntityResolver*
getEntityResolver() const;
virtual void
setEntityResolver(EntityResolver* resolver);
// These interfaces are new to XalanSourceTreeParserLiaison...
/**
* Parse using a SAX2 ContentHandler, DTDHandler, and LexicalHandler.
*
* @param theInputSource The input source for the parser
* @param theContentHandler The ContentHandler to use
* @param theDTDHandler The DTDHandler to use. May be null.
* @param theLexicalHandler The LexicalHandler to use. May be null.
* @param identifier Used for error reporting only.
*/
virtual void
parseXMLStream(
const InputSource& theInputSource,
ContentHandler& theContentHandler,
DTDHandler* theDTDHandler = 0,
LexicalHandler* theLexicalHandler = 0,
const XalanDOMString& theIdentifier = XalanDOMString());
/** Get the 'include ignorable whitespace' flag.
*
* This method returns the state of the parser's include ignorable
* whitespace flag.
*
* @return 'true' if the include ignorable whitespace flag is set on
* the parser, 'false' otherwise.
*
* @see #setIncludeIgnorableWhitespace
*/
virtual bool
getIncludeIgnorableWhitespace() const;
/** Set the 'include ignorable whitespace' flag
*
* This method allows the user to specify whether a validating parser
* should include ignorable whitespaces as text nodes. It has no effect
* on non-validating parsers which always include non-markup text.
* <p>When set to true (also the default), ignorable whitespaces will be
* added to the DOM tree as text nodes. The method
* DOM_Text::isIgnorableWhitespace() will return true for those text
* nodes only.
* <p>When set to false, all ignorable whitespace will be discarded and
* no text node is added to the DOM tree. Note: applications intended
* to process the "xml:space" attribute should not set this flag to false.
*
* @param include The new state of the include ignorable whitespace
* flag.
*
* @see #getIncludeIgnorableWhitespace
*/
virtual void
setIncludeIgnorableWhitespace(bool include);
/**
* This method returns the installed error handler.
*
* @return A pointer to the installed error handler object.
*/
virtual ErrorHandler*
getErrorHandler() const;
/**
* This method installs the user specified error handler on
* the parser.
*
* @param handler A pointer to the error handler to be called
* when the parser comes across 'error' events
* as per the SAX specification.
*
* @see Parser#setErrorHandler
*/
virtual void
setErrorHandler(ErrorHandler* handler);
/**
* This method returns the state of the parser's namespace
* handling capability.
*
* @return true, if the parser is currently configured to
* understand namespaces, false otherwise.
*
* @see #setDoNamespaces
*/
virtual bool
getDoNamespaces() const;
/**
* This method allows users to enable or disable the parser's
* namespace processing. When set to true, parser starts enforcing
* all the constraints / rules specified by the NameSpace
* specification.
*
* <p>The parser's default state is: false.</p>
*
* <p>This flag is ignored by the underlying scanner if the installed
* validator indicates that namespace constraints should be
* enforced.</p>
*
* @param newState The value specifying whether NameSpace rules should
* be enforced or not.
*
* @see #getDoNamespaces
*/
virtual void
setDoNamespaces(bool newState);
/**
* This method returns the state of the parser's
* exit-on-First-Fatal-Error flag.
*
* @return true, if the parser is currently configured to
* exit on the first fatal error, false otherwise.
*
* @see #setExitOnFirstFatalError
*/
virtual bool
getExitOnFirstFatalError() const;
/**
* This method allows users to set the parser's behaviour when it
* encounters the first fatal error. If set to true, the parser
* will exit at the first fatal error. If false, then it will
* report the error and continue processing.
*
* <p>The default value is 'true' and the parser exits on the
* first fatal error.</p>
*
* @param newState The value specifying whether the parser should
* continue or exit when it encounters the first
* fatal error.
*
* @see #getExitOnFirstFatalError
*/
virtual void
setExitOnFirstFatalError(bool newState);
/**
* Map a pointer to a XalanDocument instance to its implementation
* class pointer. Normally, you should have no reason for doing
* this. The liaison will return a null pointer if it did not
* create the instance passed.
*
* @param theDocument A pointer to a XalanDocument instance.
* @return A pointer to the XalanSourceTreeDocument instance.
*/
XalanSourceTreeDocument*
mapDocument(const XalanDocument* theDocument) const;
/**
* Create a XalanSourceTreeDocument instance.
*
* @return A pointer to the XalanSourceTreeDocument instance.
*/
XalanSourceTreeDocument*
createXalanSourceTreeDocument();
bool
setPersistent(XalanSourceTreeDocument* theDocument);
bool
unsetPersistent(XalanSourceTreeDocument* theDocument);
#if defined(XALAN_NO_NAMESPACES)
typedef map<const XalanDocument*,
XalanSourceTreeDocument*,
less<const XalanDocument*> > DocumentMapType;
#else
typedef std::map<const XalanDocument*,
XalanSourceTreeDocument*> DocumentMapType;
#endif
DocumentNumberType
getDocumentNumber() const
{
return m_documentNumber;
}
private:
// Not implemented...
XalanSourceTreeParserLiaison(const XalanSourceTreeParserLiaison&);
XalanSourceTreeParserLiaison&
operator=(const XalanSourceTreeParserLiaison&);
// Data members...
DocumentNumberType m_documentNumber;
XercesParserLiaison m_xercesParserLiaison;
DocumentMapType m_documentMap;
DocumentMapType m_persistentDocumentMap;
bool m_poolAllText;
static const XalanDOMChar validationString[];
};
#endif // XALANSOURCETREEPARSERLIAISON_HEADER_GUARD_1357924680
<|endoftext|> |
<commit_before>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* libtest
*
* Copyright (C) 2011 Data Differential, http://datadifferential.com/
*
* 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 3 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
*/
#include <config.h>
#include <libtest/common.h>
#include <cassert>
#include <cerrno>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <functional>
#include <locale>
// trim from end
static inline std::string &rtrim(std::string &s)
{
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
#include <libtest/server.h>
#include <libtest/stream.h>
#include <libtest/killpid.h>
namespace libtest {
std::ostream& operator<<(std::ostream& output, const Server &arg)
{
if (arg.is_socket())
{
output << arg.hostname();
}
else
{
output << arg.hostname() << ":" << arg.port();
}
if (arg.has_pid())
{
output << " Pid:" << arg.pid();
}
if (arg.has_socket())
{
output << " Socket:" << arg.socket();
}
if (arg.running().empty() == false)
{
output << " Exec:" << arg.running();
}
return output; // for multiple << operators
}
#define MAGIC_MEMORY 123570
Server::Server(const std::string& host_arg, const in_port_t port_arg,
const std::string& executable, const bool _is_libtool,
bool is_socket_arg) :
_magic(MAGIC_MEMORY),
_is_socket(is_socket_arg),
_pid(-1),
_port(port_arg),
_hostname(host_arg),
_app(executable, _is_libtool)
{
}
Server::~Server()
{
if (has_pid() and not kill(_pid))
{
Error << "Unable to kill:" << *this;
}
Application::error_t ret;
if (Application::SUCCESS != (ret= _app.wait()))
{
Error << "Application::wait() " << _running << " " << ret << ": " << _app.stderr_result();
}
}
bool Server::validate()
{
return _magic == MAGIC_MEMORY;
}
// If the server exists, kill it
bool Server::cycle()
{
uint32_t limit= 3;
// Try to ping, and kill the server #limit number of times
pid_t current_pid;
while (--limit and
is_pid_valid(current_pid= get_pid()))
{
if (kill(current_pid))
{
Log << "Killed existing server," << *this << " with pid:" << current_pid;
dream(0, 50000);
continue;
}
}
// For whatever reason we could not kill it, and we reached limit
if (limit == 0)
{
Error << "Reached limit, could not kill server pid:" << current_pid;
return false;
}
return true;
}
bool Server::wait_for_pidfile() const
{
Wait wait(pid_file(), 4);
return wait.successful();
}
bool Server::start()
{
// If we find that we already have a pid then kill it.
if (has_pid() and kill(_pid) == false)
{
Error << "Could not kill() existing server during start() pid:" << _pid;
return false;
}
if (has_pid() == false)
{
fatal_message("has_pid() failed, programer error");
}
if (gdb_is_caller())
{
_app.use_gdb();
}
if (args(_app) == false)
{
Error << "Could not build command()";
return false;
}
Application::error_t ret;
if (Application::SUCCESS != (ret= _app.run()))
{
Error << "Application::run() " << ret;
return false;
}
_running= _app.print();
if (valgrind_is_caller())
{
dream(5, 50000);
}
if (pid_file().empty() == false)
{
Wait wait(pid_file(), 8);
if (wait.successful() == false)
{
libtest::fatal(LIBYATL_DEFAULT_PARAM,
"Unable to open pidfile for: %s",
_running.c_str());
}
}
bool pinged= false;
{
uint32_t timeout= 20; // This number should be high enough for valgrind startup (which is slow)
uint32_t waited;
uint32_t this_wait;
uint32_t retry;
for (waited= 0, retry= 1; ; retry++, waited+= this_wait)
{
if ((pinged= ping()) == true)
{
break;
}
else if (waited >= timeout)
{
break;
}
this_wait= retry * retry / 3 + 1;
libtest::dream(this_wait, 0);
}
}
if (pinged == false)
{
// If we happen to have a pid file, lets try to kill it
if (pid_file().empty() == false)
{
if (kill_file(pid_file()) == false)
{
fatal_message("Failed to kill off server after startup occurred, when pinging failed");
}
Error << "Failed to ping() server started, having pid_file. exec:" << _running;
}
else
{
Error << "Failed to ping() server started. exec:" << _running;
}
_running.clear();
return false;
}
// A failing get_pid() at this point is considered an error
_pid= get_pid(true);
return has_pid();
}
void Server::reset_pid()
{
_running.clear();
_pid_file.clear();
_pid= -1;
}
pid_t Server::pid()
{
return _pid;
}
void Server::add_option(const std::string& arg)
{
_options.push_back(std::make_pair(arg, std::string()));
}
void Server::add_option(const std::string& name, const std::string& value)
{
_options.push_back(std::make_pair(name, value));
}
bool Server::set_socket_file()
{
char file_buffer[FILENAME_MAX];
file_buffer[0]= 0;
if (broken_pid_file())
{
snprintf(file_buffer, sizeof(file_buffer), "/tmp/%s.socketXXXXXX", name());
}
else
{
snprintf(file_buffer, sizeof(file_buffer), "var/run/%s.socketXXXXXX", name());
}
int fd;
if ((fd= mkstemp(file_buffer)) == -1)
{
perror(file_buffer);
return false;
}
close(fd);
unlink(file_buffer);
_socket= file_buffer;
return true;
}
bool Server::set_pid_file()
{
char file_buffer[FILENAME_MAX];
file_buffer[0]= 0;
if (broken_pid_file())
{
snprintf(file_buffer, sizeof(file_buffer), "/tmp/%s.pidXXXXXX", name());
}
else
{
snprintf(file_buffer, sizeof(file_buffer), "var/run/%s.pidXXXXXX", name());
}
int fd;
if ((fd= mkstemp(file_buffer)) == -1)
{
perror(file_buffer);
return false;
}
close(fd);
unlink(file_buffer);
_pid_file= file_buffer;
return true;
}
bool Server::set_log_file()
{
char file_buffer[FILENAME_MAX];
file_buffer[0]= 0;
snprintf(file_buffer, sizeof(file_buffer), "var/log/%s.logXXXXXX", name());
int fd;
if ((fd= mkstemp(file_buffer)) == -1)
{
libtest::fatal(LIBYATL_DEFAULT_PARAM, "mkstemp() failed on %s with %s", file_buffer, strerror(errno));
}
close(fd);
_log_file= file_buffer;
return true;
}
bool Server::args(Application& app)
{
// Set a log file if it was requested (and we can)
if (has_log_file_option())
{
set_log_file();
log_file_option(app, _log_file);
}
if (getenv("LIBTEST_SYSLOG") and has_syslog())
{
app.add_option("--syslog");
}
// Update pid_file
{
if (_pid_file.empty() and set_pid_file() == false)
{
return false;
}
pid_file_option(app, pid_file());
}
if (has_socket_file_option())
{
if (set_socket_file() == false)
{
return false;
}
socket_file_option(app, _socket);
}
if (has_port_option())
{
port_option(app, _port);
}
for (Options::const_iterator iter= _options.begin(); iter != _options.end(); iter++)
{
if ((*iter).second.empty() == false)
{
app.add_option((*iter).first, (*iter).second);
}
else
{
app.add_option((*iter).first);
}
}
return true;
}
bool Server::kill(pid_t pid_arg)
{
if (check_pid(pid_arg) and kill_pid(pid_arg)) // If we kill it, reset
{
if (broken_pid_file() and pid_file().empty() == false)
{
unlink(pid_file().c_str());
}
if (broken_socket_cleanup() and has_socket() and not socket().empty())
{
unlink(socket().c_str());
}
reset_pid();
return true;
}
return false;
}
} // namespace libtest
<commit_msg>Update for having gdb no additionally started in server binary.<commit_after>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* libtest
*
* Copyright (C) 2011 Data Differential, http://datadifferential.com/
*
* 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 3 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
*/
#include <config.h>
#include <libtest/common.h>
#include <cassert>
#include <cerrno>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <functional>
#include <locale>
// trim from end
static inline std::string &rtrim(std::string &s)
{
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
#include <libtest/server.h>
#include <libtest/stream.h>
#include <libtest/killpid.h>
namespace libtest {
std::ostream& operator<<(std::ostream& output, const Server &arg)
{
if (arg.is_socket())
{
output << arg.hostname();
}
else
{
output << arg.hostname() << ":" << arg.port();
}
if (arg.has_pid())
{
output << " Pid:" << arg.pid();
}
if (arg.has_socket())
{
output << " Socket:" << arg.socket();
}
if (arg.running().empty() == false)
{
output << " Exec:" << arg.running();
}
return output; // for multiple << operators
}
#define MAGIC_MEMORY 123570
Server::Server(const std::string& host_arg, const in_port_t port_arg,
const std::string& executable, const bool _is_libtool,
bool is_socket_arg) :
_magic(MAGIC_MEMORY),
_is_socket(is_socket_arg),
_pid(-1),
_port(port_arg),
_hostname(host_arg),
_app(executable, _is_libtool)
{
}
Server::~Server()
{
if (has_pid() and not kill(_pid))
{
Error << "Unable to kill:" << *this;
}
Application::error_t ret;
if (Application::SUCCESS != (ret= _app.wait()))
{
Error << "Application::wait() " << _running << " " << ret << ": " << _app.stderr_result();
}
}
bool Server::validate()
{
return _magic == MAGIC_MEMORY;
}
// If the server exists, kill it
bool Server::cycle()
{
uint32_t limit= 3;
// Try to ping, and kill the server #limit number of times
pid_t current_pid;
while (--limit and
is_pid_valid(current_pid= get_pid()))
{
if (kill(current_pid))
{
Log << "Killed existing server," << *this << " with pid:" << current_pid;
dream(0, 50000);
continue;
}
}
// For whatever reason we could not kill it, and we reached limit
if (limit == 0)
{
Error << "Reached limit, could not kill server pid:" << current_pid;
return false;
}
return true;
}
bool Server::wait_for_pidfile() const
{
Wait wait(pid_file(), 4);
return wait.successful();
}
bool Server::start()
{
// If we find that we already have a pid then kill it.
if (has_pid() and kill(_pid) == false)
{
Error << "Could not kill() existing server during start() pid:" << _pid;
return false;
}
if (has_pid() == false)
{
fatal_message("has_pid() failed, programer error");
}
// This needs more work.
#if 0
if (gdb_is_caller())
{
_app.use_gdb();
}
#endif
if (args(_app) == false)
{
Error << "Could not build command()";
return false;
}
Application::error_t ret;
if (Application::SUCCESS != (ret= _app.run()))
{
Error << "Application::run() " << ret;
return false;
}
_running= _app.print();
if (valgrind_is_caller())
{
dream(5, 50000);
}
if (pid_file().empty() == false)
{
Wait wait(pid_file(), 8);
if (wait.successful() == false)
{
libtest::fatal(LIBYATL_DEFAULT_PARAM,
"Unable to open pidfile for: %s",
_running.c_str());
}
}
bool pinged= false;
{
uint32_t timeout= 20; // This number should be high enough for valgrind startup (which is slow)
uint32_t waited;
uint32_t this_wait;
uint32_t retry;
for (waited= 0, retry= 1; ; retry++, waited+= this_wait)
{
if ((pinged= ping()) == true)
{
break;
}
else if (waited >= timeout)
{
break;
}
this_wait= retry * retry / 3 + 1;
libtest::dream(this_wait, 0);
}
}
if (pinged == false)
{
// If we happen to have a pid file, lets try to kill it
if (pid_file().empty() == false)
{
if (kill_file(pid_file()) == false)
{
fatal_message("Failed to kill off server after startup occurred, when pinging failed");
}
Error << "Failed to ping() server started, having pid_file. exec:" << _running;
}
else
{
Error << "Failed to ping() server started. exec:" << _running;
}
_running.clear();
return false;
}
// A failing get_pid() at this point is considered an error
_pid= get_pid(true);
return has_pid();
}
void Server::reset_pid()
{
_running.clear();
_pid_file.clear();
_pid= -1;
}
pid_t Server::pid()
{
return _pid;
}
void Server::add_option(const std::string& arg)
{
_options.push_back(std::make_pair(arg, std::string()));
}
void Server::add_option(const std::string& name, const std::string& value)
{
_options.push_back(std::make_pair(name, value));
}
bool Server::set_socket_file()
{
char file_buffer[FILENAME_MAX];
file_buffer[0]= 0;
if (broken_pid_file())
{
snprintf(file_buffer, sizeof(file_buffer), "/tmp/%s.socketXXXXXX", name());
}
else
{
snprintf(file_buffer, sizeof(file_buffer), "var/run/%s.socketXXXXXX", name());
}
int fd;
if ((fd= mkstemp(file_buffer)) == -1)
{
perror(file_buffer);
return false;
}
close(fd);
unlink(file_buffer);
_socket= file_buffer;
return true;
}
bool Server::set_pid_file()
{
char file_buffer[FILENAME_MAX];
file_buffer[0]= 0;
if (broken_pid_file())
{
snprintf(file_buffer, sizeof(file_buffer), "/tmp/%s.pidXXXXXX", name());
}
else
{
snprintf(file_buffer, sizeof(file_buffer), "var/run/%s.pidXXXXXX", name());
}
int fd;
if ((fd= mkstemp(file_buffer)) == -1)
{
perror(file_buffer);
return false;
}
close(fd);
unlink(file_buffer);
_pid_file= file_buffer;
return true;
}
bool Server::set_log_file()
{
char file_buffer[FILENAME_MAX];
file_buffer[0]= 0;
snprintf(file_buffer, sizeof(file_buffer), "var/log/%s.logXXXXXX", name());
int fd;
if ((fd= mkstemp(file_buffer)) == -1)
{
libtest::fatal(LIBYATL_DEFAULT_PARAM, "mkstemp() failed on %s with %s", file_buffer, strerror(errno));
}
close(fd);
_log_file= file_buffer;
return true;
}
bool Server::args(Application& app)
{
// Set a log file if it was requested (and we can)
if (has_log_file_option())
{
set_log_file();
log_file_option(app, _log_file);
}
if (getenv("LIBTEST_SYSLOG") and has_syslog())
{
app.add_option("--syslog");
}
// Update pid_file
{
if (_pid_file.empty() and set_pid_file() == false)
{
return false;
}
pid_file_option(app, pid_file());
}
if (has_socket_file_option())
{
if (set_socket_file() == false)
{
return false;
}
socket_file_option(app, _socket);
}
if (has_port_option())
{
port_option(app, _port);
}
for (Options::const_iterator iter= _options.begin(); iter != _options.end(); iter++)
{
if ((*iter).second.empty() == false)
{
app.add_option((*iter).first, (*iter).second);
}
else
{
app.add_option((*iter).first);
}
}
return true;
}
bool Server::kill(pid_t pid_arg)
{
if (check_pid(pid_arg) and kill_pid(pid_arg)) // If we kill it, reset
{
if (broken_pid_file() and pid_file().empty() == false)
{
unlink(pid_file().c_str());
}
if (broken_socket_cleanup() and has_socket() and not socket().empty())
{
unlink(socket().c_str());
}
reset_pid();
return true;
}
return false;
}
} // namespace libtest
<|endoftext|> |
<commit_before><commit_msg>workaround: make padding not supported by ConvOclDirectFwd1x1<commit_after><|endoftext|> |
<commit_before>/* This file is part of the KDE project
Copyright (C) 2007 Matthias Kretz <[email protected]>
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) version 3, or any
later version accepted by the membership of KDE e.V. (or its
successor approved by the membership of KDE e.V.), Nokia Corporation
(or its successors, if any) and the KDE Free Qt Foundation, which shall
act as a proxy defined in Section 6 of version 3 of the license.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "path.h"
#include "path_p.h"
#include "phononnamespace_p.h"
#include "backendinterface.h"
#include "factory_p.h"
#include "medianode.h"
#include "medianode_p.h"
QT_BEGIN_NAMESPACE
namespace Phonon
{
class ConnectionTransaction
{
public:
ConnectionTransaction(BackendInterface *b, const QSet<QObject*> &x) : backend(b), list(x)
{
success = backend->startConnectionChange(list);
}
~ConnectionTransaction()
{
backend->endConnectionChange(list);
}
operator bool()
{
return success;
}
private:
bool success;
BackendInterface *const backend;
const QSet<QObject*> list;
};
PathPrivate::~PathPrivate()
{
#ifndef QT_NO_PHONON_EFFECT
foreach (Effect *e, effects) {
e->k_ptr->removeDestructionHandler(this);
}
delete effectsParent;
#endif
}
Path::~Path()
{
}
Path::Path()
: d(new PathPrivate)
{
}
Path::Path(const Path &rhs)
: d(rhs.d)
{
}
bool Path::isValid() const
{
return d->sourceNode != 0 && d->sinkNode != 0;
}
#ifndef QT_NO_PHONON_EFFECT
Effect *Path::insertEffect(const EffectDescription &desc, Effect *insertBefore)
{
if (!d->effectsParent) {
d->effectsParent = new QObject;
}
Effect *e = new Effect(desc, d->effectsParent);
if (!e->isValid()) {
delete e;
return 0;
}
bool success = insertEffect(e, insertBefore);
if (!success) {
delete e;
return 0;
}
return e;
}
bool Path::insertEffect(Effect *newEffect, Effect *insertBefore)
{
QObject *newEffectBackend = newEffect ? newEffect->k_ptr->backendObject() : 0;
if (!isValid() || !newEffectBackend || d->effects.contains(newEffect) ||
(insertBefore && (!d->effects.contains(insertBefore) || !insertBefore->k_ptr->backendObject()))) {
return false;
}
QObject *leftNode = 0;
QObject *rightNode = 0;
const int insertIndex = insertBefore ? d->effects.indexOf(insertBefore) : d->effects.size();
if (insertIndex == 0) {
//prepend
leftNode = d->sourceNode->k_ptr->backendObject();
} else {
leftNode = d->effects[insertIndex - 1]->k_ptr->backendObject();
}
if (insertIndex == d->effects.size()) {
//append
rightNode = d->sinkNode->k_ptr->backendObject();
} else {
Q_ASSERT(insertBefore);
rightNode = insertBefore->k_ptr->backendObject();
}
QList<QObjectPair> disconnections, connections;
disconnections << QObjectPair(leftNode, rightNode);
connections << QObjectPair(leftNode, newEffectBackend)
<< QObjectPair(newEffectBackend, rightNode);
if (d->executeTransaction(disconnections, connections)) {
newEffect->k_ptr->addDestructionHandler(d.data());
d->effects.insert(insertIndex, newEffect);
return true;
} else {
return false;
}
}
bool Path::removeEffect(Effect *effect)
{
return d->removeEffect(effect);
}
QList<Effect *> Path::effects() const
{
return d->effects;
}
#endif //QT_NO_PHONON_EFFECT
bool Path::reconnect(MediaNode *source, MediaNode *sink)
{
if (!source || !sink || !source->k_ptr->backendObject() || !sink->k_ptr->backendObject()) {
if (!sink->k_ptr->backendObject()) qWarning() << "no backend object in sink";
if (!source->k_ptr->backendObject()) qWarning() << "no backend object in sink";
return false;
}
QList<QObjectPair> disconnections, connections;
//backend objects
QObject *bnewSource = source->k_ptr->backendObject();
QObject *bnewSink = sink->k_ptr->backendObject();
QObject *bcurrentSource = d->sourceNode ? d->sourceNode->k_ptr->backendObject() : 0;
QObject *bcurrentSink = d->sinkNode ? d->sinkNode->k_ptr->backendObject() : 0;
if (bnewSource != bcurrentSource) {
//we need to change the source
#ifndef QT_NO_PHONON_EFFECT
MediaNode *next = d->effects.isEmpty() ? sink : d->effects.first();
#else
MediaNode *next = sink;
#endif //QT_NO_PHONON_EFFECT
QObject *bnext = next->k_ptr->backendObject();
if (bcurrentSource)
disconnections << QObjectPair(bcurrentSource, bnext);
connections << QObjectPair(bnewSource, bnext);
}
if (bnewSink != bcurrentSink) {
#ifndef QT_NO_PHONON_EFFECT
MediaNode *previous = d->effects.isEmpty() ? source : d->effects.last();
#else
MediaNode *previous = source;
#endif //QT_NO_PHONON_EFFECT
QObject *bprevious = previous->k_ptr->backendObject();
if (bcurrentSink)
disconnections << QObjectPair(bprevious, bcurrentSink);
QObjectPair pair(bprevious, bnewSink);
if (!connections.contains(pair)) //avoid connecting twice
connections << pair;
}
if (d->executeTransaction(disconnections, connections)) {
//everything went well: let's update the path and the sink node
if (d->sinkNode != sink) {
if (d->sinkNode) {
d->sinkNode->k_ptr->removeInputPath(*this);
d->sinkNode->k_ptr->removeDestructionHandler(d.data());
}
sink->k_ptr->addInputPath(*this);
d->sinkNode = sink;
d->sinkNode->k_ptr->addDestructionHandler(d.data());
}
//everything went well: let's update the path and the source node
if (d->sourceNode != source) {
source->k_ptr->addOutputPath(*this);
if (d->sourceNode) {
d->sourceNode->k_ptr->removeOutputPath(*this);
d->sourceNode->k_ptr->removeDestructionHandler(d.data());
}
d->sourceNode = source;
d->sourceNode->k_ptr->addDestructionHandler(d.data());
}
return true;
} else {
return false;
}
}
bool Path::disconnect()
{
if (!isValid()) {
return false;
}
QObjectList list;
if (d->sourceNode)
list << d->sourceNode->k_ptr->backendObject();
#ifndef QT_NO_PHONON_EFFECT
foreach(Effect *e, d->effects) {
list << e->k_ptr->backendObject();
}
#endif
if (d->sinkNode) {
list << d->sinkNode->k_ptr->backendObject();
}
//lets build the disconnection list
QList<QObjectPair> disco;
if (list.count() >=2 ) {
QObjectList::const_iterator it = list.constBegin();
for(;it+1 != list.constEnd();++it) {
disco << QObjectPair(*it, *(it+1));
}
}
if (d->executeTransaction(disco, QList<QObjectPair>())) {
//everything went well, let's remove the reference
//to the paths from the source and sink
if (d->sourceNode) {
d->sourceNode->k_ptr->removeOutputPath(*this);
d->sourceNode->k_ptr->removeDestructionHandler(d.data());
}
d->sourceNode = 0;
#ifndef QT_NO_PHONON_EFFECT
foreach(Effect *e, d->effects) {
e->k_ptr->removeDestructionHandler(d.data());
}
d->effects.clear();
#endif
if (d->sinkNode) {
d->sinkNode->k_ptr->removeInputPath(*this);
d->sinkNode->k_ptr->removeDestructionHandler(d.data());
}
d->sinkNode = 0;
return true;
} else {
return false;
}
}
MediaNode *Path::source() const
{
return d->sourceNode;
}
MediaNode *Path::sink() const
{
return d->sinkNode;
}
bool PathPrivate::executeTransaction( const QList<QObjectPair> &disconnections, const QList<QObjectPair> &connections)
{
QSet<QObject*> nodesForTransaction;
foreach(const QObjectPair &pair, disconnections) {
nodesForTransaction << pair.first;
nodesForTransaction << pair.second;
}
foreach(const QObjectPair &pair, connections) {
nodesForTransaction << pair.first;
nodesForTransaction << pair.second;
}
BackendInterface *backend = qobject_cast<BackendInterface *>(Factory::backend());
if (!backend)
return false;
ConnectionTransaction transaction(backend, nodesForTransaction);
if (!transaction)
return false;
QList<QObjectPair>::const_iterator it = disconnections.begin();
for(;it != disconnections.end();++it) {
const QObjectPair &pair = *it;
if (!backend->disconnectNodes(pair.first, pair.second)) {
//Error: a disconnection failed
QList<QObjectPair>::const_iterator it2 = disconnections.begin();
for(; it2 != it; ++it2) {
const QObjectPair &pair = *it2;
bool success = backend->connectNodes(pair.first, pair.second);
Q_ASSERT(success); //a failure here means it is impossible to reestablish the connection
Q_UNUSED(success);
}
qWarning() << Q_FUNC_INFO << "disconnection failed!";
return false;
}
}
for(it = connections.begin(); it != connections.end();++it) {
const QObjectPair &pair = *it;
if (!backend->connectNodes(pair.first, pair.second)) {
//Error: a connection failed
QList<QObjectPair>::const_iterator it2 = connections.begin();
for(; it2 != it; ++it2) {
const QObjectPair &pair = *it2;
bool success = backend->disconnectNodes(pair.first, pair.second);
Q_ASSERT(success); //a failure here means it is impossible to reestablish the connection
Q_UNUSED(success);
}
//and now let's reconnect the nodes that were disconnected: rollback
foreach(const QObjectPair &pair, disconnections) {
bool success = backend->connectNodes(pair.first, pair.second);
Q_ASSERT(success); //a failure here means it is impossible to reestablish the connection
Q_UNUSED(success);
}
qWarning() << Q_FUNC_INFO << "connection failed, rollback succeeded";
return false;
}
}
return true;
}
#ifndef QT_NO_PHONON_EFFECT
bool PathPrivate::removeEffect(Effect *effect)
{
if (!effects.contains(effect))
return false;
QObject *leftNode = 0;
QObject *rightNode = 0;
const int index = effects.indexOf(effect);
if (index == 0) {
leftNode = sourceNode->k_ptr->backendObject(); //append
} else {
leftNode = effects[index - 1]->k_ptr->backendObject();
}
if (index == effects.size()-1) {
rightNode = sinkNode->k_ptr->backendObject(); //prepend
} else {
rightNode = effects[index + 1]->k_ptr->backendObject();
}
QList<QObjectPair> disconnections, connections;
QObject *beffect = effect->k_ptr->backendObject();
disconnections << QObjectPair(leftNode, beffect) << QObjectPair(beffect, rightNode);
connections << QObjectPair(leftNode, rightNode);
if (executeTransaction(disconnections, connections)) {
effect->k_ptr->removeDestructionHandler(this);
effects.removeAt(index);
return true;
}
return false;
}
#endif //QT_NO_PHONON_EFFECT
void PathPrivate::phononObjectDestroyed(MediaNodePrivate *mediaNodePrivate)
{
Q_ASSERT(mediaNodePrivate);
if (mediaNodePrivate == sinkNode->k_ptr || mediaNodePrivate == sourceNode->k_ptr) {
//let's first disconnectq the path from its source and sink
QObject *bsink = sinkNode->k_ptr->backendObject();
QObject *bsource = sourceNode->k_ptr->backendObject();
QList<QObjectPair> disconnections;
#ifndef QT_NO_PHONON_EFFECT
disconnections << QObjectPair(bsource, effects.isEmpty() ? bsink : effects.first()->k_ptr->backendObject());
if (!effects.isEmpty())
disconnections << QObjectPair(effects.last()->k_ptr->backendObject(), bsink);
#else
disconnections << QObjectPair(bsource, bsink);
#endif //QT_NO_PHONON_EFFECT
executeTransaction(disconnections, QList<QObjectPair>());
Path p; //temporary path
p.d = this;
if (mediaNodePrivate == sinkNode->k_ptr) {
sourceNode->k_ptr->removeOutputPath(p);
sourceNode->k_ptr->removeDestructionHandler(this);
} else {
sinkNode->k_ptr->removeInputPath(p);
sinkNode->k_ptr->removeDestructionHandler(this);
}
sourceNode = 0;
sinkNode = 0;
} else {
#ifndef QT_NO_PHONON_EFFECT
foreach (Effect *e, effects) {
if (e->k_ptr == mediaNodePrivate) {
removeEffect(e);
}
}
#endif //QT_NO_PHONON_EFFECT
}
}
Path createPath(MediaNode *source, MediaNode *sink)
{
Path p;
if (!p.reconnect(source, sink)) {
const QObject *const src = source ? (source->k_ptr->qObject()
#ifndef QT_NO_DYNAMIC_CAST
? source->k_ptr->qObject() : dynamic_cast<QObject *>(source)
#endif
) : 0;
const QObject *const snk = sink ? (sink->k_ptr->qObject()
#ifndef QT_NO_DYNAMIC_CAST
? sink->k_ptr->qObject() : dynamic_cast<QObject *>(sink)
#endif
) : 0;
pWarning() << "Phonon::createPath: Cannot connect "
<< (src ? src->metaObject()->className() : "")
<< '(' << (src ? (src->objectName().isEmpty() ? "no objectName" : qPrintable(src->objectName())) : "null") << ") to "
<< (snk ? snk->metaObject()->className() : "")
<< '(' << (snk ? (snk->objectName().isEmpty() ? "no objectName" : qPrintable(snk->objectName())) : "null")
<< ").";
}
return p;
}
Path & Path::operator=(const Path &other)
{
d = other.d;
return *this;
}
bool Path::operator==(const Path &other) const
{
return d == other.d;
}
bool Path::operator!=(const Path &other) const
{
return !operator==(other);
}
} // namespace Phonon
QT_END_NAMESPACE
<commit_msg>remove some debug information not really generally necessary<commit_after>/* This file is part of the KDE project
Copyright (C) 2007 Matthias Kretz <[email protected]>
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) version 3, or any
later version accepted by the membership of KDE e.V. (or its
successor approved by the membership of KDE e.V.), Nokia Corporation
(or its successors, if any) and the KDE Free Qt Foundation, which shall
act as a proxy defined in Section 6 of version 3 of the license.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "path.h"
#include "path_p.h"
#include "phononnamespace_p.h"
#include "backendinterface.h"
#include "factory_p.h"
#include "medianode.h"
#include "medianode_p.h"
QT_BEGIN_NAMESPACE
namespace Phonon
{
class ConnectionTransaction
{
public:
ConnectionTransaction(BackendInterface *b, const QSet<QObject*> &x) : backend(b), list(x)
{
success = backend->startConnectionChange(list);
}
~ConnectionTransaction()
{
backend->endConnectionChange(list);
}
operator bool()
{
return success;
}
private:
bool success;
BackendInterface *const backend;
const QSet<QObject*> list;
};
PathPrivate::~PathPrivate()
{
#ifndef QT_NO_PHONON_EFFECT
foreach (Effect *e, effects) {
e->k_ptr->removeDestructionHandler(this);
}
delete effectsParent;
#endif
}
Path::~Path()
{
}
Path::Path()
: d(new PathPrivate)
{
}
Path::Path(const Path &rhs)
: d(rhs.d)
{
}
bool Path::isValid() const
{
return d->sourceNode != 0 && d->sinkNode != 0;
}
#ifndef QT_NO_PHONON_EFFECT
Effect *Path::insertEffect(const EffectDescription &desc, Effect *insertBefore)
{
if (!d->effectsParent) {
d->effectsParent = new QObject;
}
Effect *e = new Effect(desc, d->effectsParent);
if (!e->isValid()) {
delete e;
return 0;
}
bool success = insertEffect(e, insertBefore);
if (!success) {
delete e;
return 0;
}
return e;
}
bool Path::insertEffect(Effect *newEffect, Effect *insertBefore)
{
QObject *newEffectBackend = newEffect ? newEffect->k_ptr->backendObject() : 0;
if (!isValid() || !newEffectBackend || d->effects.contains(newEffect) ||
(insertBefore && (!d->effects.contains(insertBefore) || !insertBefore->k_ptr->backendObject()))) {
return false;
}
QObject *leftNode = 0;
QObject *rightNode = 0;
const int insertIndex = insertBefore ? d->effects.indexOf(insertBefore) : d->effects.size();
if (insertIndex == 0) {
//prepend
leftNode = d->sourceNode->k_ptr->backendObject();
} else {
leftNode = d->effects[insertIndex - 1]->k_ptr->backendObject();
}
if (insertIndex == d->effects.size()) {
//append
rightNode = d->sinkNode->k_ptr->backendObject();
} else {
Q_ASSERT(insertBefore);
rightNode = insertBefore->k_ptr->backendObject();
}
QList<QObjectPair> disconnections, connections;
disconnections << QObjectPair(leftNode, rightNode);
connections << QObjectPair(leftNode, newEffectBackend)
<< QObjectPair(newEffectBackend, rightNode);
if (d->executeTransaction(disconnections, connections)) {
newEffect->k_ptr->addDestructionHandler(d.data());
d->effects.insert(insertIndex, newEffect);
return true;
} else {
return false;
}
}
bool Path::removeEffect(Effect *effect)
{
return d->removeEffect(effect);
}
QList<Effect *> Path::effects() const
{
return d->effects;
}
#endif //QT_NO_PHONON_EFFECT
bool Path::reconnect(MediaNode *source, MediaNode *sink)
{
if (!source || !sink || !source->k_ptr->backendObject() || !sink->k_ptr->backendObject()) {
return false;
}
QList<QObjectPair> disconnections, connections;
//backend objects
QObject *bnewSource = source->k_ptr->backendObject();
QObject *bnewSink = sink->k_ptr->backendObject();
QObject *bcurrentSource = d->sourceNode ? d->sourceNode->k_ptr->backendObject() : 0;
QObject *bcurrentSink = d->sinkNode ? d->sinkNode->k_ptr->backendObject() : 0;
if (bnewSource != bcurrentSource) {
//we need to change the source
#ifndef QT_NO_PHONON_EFFECT
MediaNode *next = d->effects.isEmpty() ? sink : d->effects.first();
#else
MediaNode *next = sink;
#endif //QT_NO_PHONON_EFFECT
QObject *bnext = next->k_ptr->backendObject();
if (bcurrentSource)
disconnections << QObjectPair(bcurrentSource, bnext);
connections << QObjectPair(bnewSource, bnext);
}
if (bnewSink != bcurrentSink) {
#ifndef QT_NO_PHONON_EFFECT
MediaNode *previous = d->effects.isEmpty() ? source : d->effects.last();
#else
MediaNode *previous = source;
#endif //QT_NO_PHONON_EFFECT
QObject *bprevious = previous->k_ptr->backendObject();
if (bcurrentSink)
disconnections << QObjectPair(bprevious, bcurrentSink);
QObjectPair pair(bprevious, bnewSink);
if (!connections.contains(pair)) //avoid connecting twice
connections << pair;
}
if (d->executeTransaction(disconnections, connections)) {
//everything went well: let's update the path and the sink node
if (d->sinkNode != sink) {
if (d->sinkNode) {
d->sinkNode->k_ptr->removeInputPath(*this);
d->sinkNode->k_ptr->removeDestructionHandler(d.data());
}
sink->k_ptr->addInputPath(*this);
d->sinkNode = sink;
d->sinkNode->k_ptr->addDestructionHandler(d.data());
}
//everything went well: let's update the path and the source node
if (d->sourceNode != source) {
source->k_ptr->addOutputPath(*this);
if (d->sourceNode) {
d->sourceNode->k_ptr->removeOutputPath(*this);
d->sourceNode->k_ptr->removeDestructionHandler(d.data());
}
d->sourceNode = source;
d->sourceNode->k_ptr->addDestructionHandler(d.data());
}
return true;
} else {
return false;
}
}
bool Path::disconnect()
{
if (!isValid()) {
return false;
}
QObjectList list;
if (d->sourceNode)
list << d->sourceNode->k_ptr->backendObject();
#ifndef QT_NO_PHONON_EFFECT
foreach(Effect *e, d->effects) {
list << e->k_ptr->backendObject();
}
#endif
if (d->sinkNode) {
list << d->sinkNode->k_ptr->backendObject();
}
//lets build the disconnection list
QList<QObjectPair> disco;
if (list.count() >=2 ) {
QObjectList::const_iterator it = list.constBegin();
for(;it+1 != list.constEnd();++it) {
disco << QObjectPair(*it, *(it+1));
}
}
if (d->executeTransaction(disco, QList<QObjectPair>())) {
//everything went well, let's remove the reference
//to the paths from the source and sink
if (d->sourceNode) {
d->sourceNode->k_ptr->removeOutputPath(*this);
d->sourceNode->k_ptr->removeDestructionHandler(d.data());
}
d->sourceNode = 0;
#ifndef QT_NO_PHONON_EFFECT
foreach(Effect *e, d->effects) {
e->k_ptr->removeDestructionHandler(d.data());
}
d->effects.clear();
#endif
if (d->sinkNode) {
d->sinkNode->k_ptr->removeInputPath(*this);
d->sinkNode->k_ptr->removeDestructionHandler(d.data());
}
d->sinkNode = 0;
return true;
} else {
return false;
}
}
MediaNode *Path::source() const
{
return d->sourceNode;
}
MediaNode *Path::sink() const
{
return d->sinkNode;
}
bool PathPrivate::executeTransaction( const QList<QObjectPair> &disconnections, const QList<QObjectPair> &connections)
{
QSet<QObject*> nodesForTransaction;
foreach(const QObjectPair &pair, disconnections) {
nodesForTransaction << pair.first;
nodesForTransaction << pair.second;
}
foreach(const QObjectPair &pair, connections) {
nodesForTransaction << pair.first;
nodesForTransaction << pair.second;
}
BackendInterface *backend = qobject_cast<BackendInterface *>(Factory::backend());
if (!backend)
return false;
ConnectionTransaction transaction(backend, nodesForTransaction);
if (!transaction)
return false;
QList<QObjectPair>::const_iterator it = disconnections.begin();
for(;it != disconnections.end();++it) {
const QObjectPair &pair = *it;
if (!backend->disconnectNodes(pair.first, pair.second)) {
//Error: a disconnection failed
QList<QObjectPair>::const_iterator it2 = disconnections.begin();
for(; it2 != it; ++it2) {
const QObjectPair &pair = *it2;
bool success = backend->connectNodes(pair.first, pair.second);
Q_ASSERT(success); //a failure here means it is impossible to reestablish the connection
Q_UNUSED(success);
}
return false;
}
}
for(it = connections.begin(); it != connections.end();++it) {
const QObjectPair &pair = *it;
if (!backend->connectNodes(pair.first, pair.second)) {
//Error: a connection failed
QList<QObjectPair>::const_iterator it2 = connections.begin();
for(; it2 != it; ++it2) {
const QObjectPair &pair = *it2;
bool success = backend->disconnectNodes(pair.first, pair.second);
Q_ASSERT(success); //a failure here means it is impossible to reestablish the connection
Q_UNUSED(success);
}
//and now let's reconnect the nodes that were disconnected: rollback
foreach(const QObjectPair &pair, disconnections) {
bool success = backend->connectNodes(pair.first, pair.second);
Q_ASSERT(success); //a failure here means it is impossible to reestablish the connection
Q_UNUSED(success);
}
return false;
}
}
return true;
}
#ifndef QT_NO_PHONON_EFFECT
bool PathPrivate::removeEffect(Effect *effect)
{
if (!effects.contains(effect))
return false;
QObject *leftNode = 0;
QObject *rightNode = 0;
const int index = effects.indexOf(effect);
if (index == 0) {
leftNode = sourceNode->k_ptr->backendObject(); //append
} else {
leftNode = effects[index - 1]->k_ptr->backendObject();
}
if (index == effects.size()-1) {
rightNode = sinkNode->k_ptr->backendObject(); //prepend
} else {
rightNode = effects[index + 1]->k_ptr->backendObject();
}
QList<QObjectPair> disconnections, connections;
QObject *beffect = effect->k_ptr->backendObject();
disconnections << QObjectPair(leftNode, beffect) << QObjectPair(beffect, rightNode);
connections << QObjectPair(leftNode, rightNode);
if (executeTransaction(disconnections, connections)) {
effect->k_ptr->removeDestructionHandler(this);
effects.removeAt(index);
return true;
}
return false;
}
#endif //QT_NO_PHONON_EFFECT
void PathPrivate::phononObjectDestroyed(MediaNodePrivate *mediaNodePrivate)
{
Q_ASSERT(mediaNodePrivate);
if (mediaNodePrivate == sinkNode->k_ptr || mediaNodePrivate == sourceNode->k_ptr) {
//let's first disconnectq the path from its source and sink
QObject *bsink = sinkNode->k_ptr->backendObject();
QObject *bsource = sourceNode->k_ptr->backendObject();
QList<QObjectPair> disconnections;
#ifndef QT_NO_PHONON_EFFECT
disconnections << QObjectPair(bsource, effects.isEmpty() ? bsink : effects.first()->k_ptr->backendObject());
if (!effects.isEmpty())
disconnections << QObjectPair(effects.last()->k_ptr->backendObject(), bsink);
#else
disconnections << QObjectPair(bsource, bsink);
#endif //QT_NO_PHONON_EFFECT
executeTransaction(disconnections, QList<QObjectPair>());
Path p; //temporary path
p.d = this;
if (mediaNodePrivate == sinkNode->k_ptr) {
sourceNode->k_ptr->removeOutputPath(p);
sourceNode->k_ptr->removeDestructionHandler(this);
} else {
sinkNode->k_ptr->removeInputPath(p);
sinkNode->k_ptr->removeDestructionHandler(this);
}
sourceNode = 0;
sinkNode = 0;
} else {
#ifndef QT_NO_PHONON_EFFECT
foreach (Effect *e, effects) {
if (e->k_ptr == mediaNodePrivate) {
removeEffect(e);
}
}
#endif //QT_NO_PHONON_EFFECT
}
}
Path createPath(MediaNode *source, MediaNode *sink)
{
Path p;
if (!p.reconnect(source, sink)) {
const QObject *const src = source ? (source->k_ptr->qObject()
#ifndef QT_NO_DYNAMIC_CAST
? source->k_ptr->qObject() : dynamic_cast<QObject *>(source)
#endif
) : 0;
const QObject *const snk = sink ? (sink->k_ptr->qObject()
#ifndef QT_NO_DYNAMIC_CAST
? sink->k_ptr->qObject() : dynamic_cast<QObject *>(sink)
#endif
) : 0;
pWarning() << "Phonon::createPath: Cannot connect "
<< (src ? src->metaObject()->className() : "")
<< '(' << (src ? (src->objectName().isEmpty() ? "no objectName" : qPrintable(src->objectName())) : "null") << ") to "
<< (snk ? snk->metaObject()->className() : "")
<< '(' << (snk ? (snk->objectName().isEmpty() ? "no objectName" : qPrintable(snk->objectName())) : "null")
<< ").";
}
return p;
}
Path & Path::operator=(const Path &other)
{
d = other.d;
return *this;
}
bool Path::operator==(const Path &other) const
{
return d == other.d;
}
bool Path::operator!=(const Path &other) const
{
return !operator==(other);
}
} // namespace Phonon
QT_END_NAMESPACE
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2019 Red Hat, Inc.
*
* Licensed under the GNU Lesser General Public License Version 2.1
*
* 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
*/
#include "os-release.hpp"
#include "File.hpp"
#include "utils.hpp"
#include "libdnf/dnf-context.h"
#include <algorithm>
#include <array>
#include <map>
#include <rpm/rpmlib.h>
#include <sstream>
#include <string>
#include <vector>
namespace libdnf {
// sorted by precedence (see os-release(5) for details)
std::array<const std::string, 2> paths = {"/etc/os-release", "/usr/lib/os-release"};
// whitelists used for sanity-checking the os-release data when constructing a
// User-Agent string (to avoid reporting rare systems or platforms that could
// be tracked)
std::map<std::string, std::vector<std::string>> distros = {
// taken from the {fedora,generic}-release.spec files
{ "Fedora", { "cinnamon", "cloud", "container", "coreos", "generic", "iot",
"kde", "matecompiz", "server", "silverblue", "snappy", "soas",
"workstation", "xfce" } },
};
std::array<const std::string, 1> canons = { "Linux" };
std::map<std::string, std::string> getOsReleaseData()
{
std::map<std::string, std::string> result;
// find the first existing file path
auto it = std::find_if(paths.begin(), paths.end(), libdnf::filesystem::exists);
if (it == paths.end())
throw std::runtime_error("os-release file not found");
std::string path = *it;
auto file = libdnf::File::newFile(path);
file->open("r");
std::string line;
while (file->readLine(line)) {
// remove trailing spaces and newline
line.erase(line.find_last_not_of(" \n") + 1);
// skip empty lines
if (line.empty()) continue;
// skip comments
if (line.front() == '#') continue;
// split string by '=' into key and value
auto pos = line.find('=');
if (pos == line.npos)
throw std::runtime_error("Invalid format (missing '='): " + line);
auto key = string::trim(line.substr(0, pos));
auto value = string::trim(line.substr(pos + 1, line.length()));
// remove quotes if present
if (!value.empty() && value.front() == '"' && value.back() == '"') {
value = value.substr(1, value.length() - 2);
}
result.insert({key, value});
}
return result;
}
static void initLibRpm()
{
static bool libRpmInitiated{false};
if (libRpmInitiated) return;
if (rpmReadConfigFiles(NULL, NULL) != 0) {
throw std::runtime_error("failed to read rpm config files\n");
}
libRpmInitiated = true;
}
static std::string getBaseArch()
{
const char *value;
initLibRpm();
rpmGetArchInfo(&value, NULL);
value = find_base_arch(value);
return value ? std::string(value) : "";
}
static std::string getCanonOs()
{
const char *value;
initLibRpm();
rpmGetOsInfo(&value, NULL);
return value;
}
std::string getUserAgent(const std::map<std::string, std::string> & osReleaseData)
{
std::ostringstream oss;
// start with the basic libdnf string
oss << USER_AGENT;
// mandatory OS data (bail out if missing or unknown)
if (!osReleaseData.count("NAME") || !osReleaseData.count("VERSION_ID"))
return oss.str();
std::string name = osReleaseData.at("NAME");
std::string version = osReleaseData.at("VERSION_ID");
if (!distros.count(name))
return oss.str();
// mandatory platform data from RPM (bail out if missing or unknown)
std::string canon = getCanonOs();
std::string arch = getBaseArch();
if (canon.empty() || arch.empty()
|| std::find(canons.begin(), canons.end(), canon) == canons.end())
return oss.str();
// optional OS data (use fallback values if missing or unknown)
std::string variant = "generic";
auto list = distros[name];
if (osReleaseData.count("VARIANT_ID")) {
std::string value = osReleaseData.at("VARIANT_ID");
if (std::find(list.begin(), list.end(), value) != list.end())
variant = value;
}
// good to go!
oss << " (" << name << " " << version << "; " << variant << "; "
<< canon << "." << arch << ")";
return oss.str();
}
std::string getUserAgent()
{
std::map<std::string, std::string> osdata;
try {
osdata = getOsReleaseData();
} catch (...) {}
return getUserAgent(osdata);
}
}
<commit_msg>[user-agent] Add debug logging<commit_after>/*
* Copyright (C) 2019 Red Hat, Inc.
*
* Licensed under the GNU Lesser General Public License Version 2.1
*
* 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
*/
#include "os-release.hpp"
#include "File.hpp"
#include "utils.hpp"
#include "libdnf/dnf-context.h"
#include "libdnf/log.hpp"
#include "tinyformat/tinyformat.hpp"
#include <algorithm>
#include <array>
#include <map>
#include <rpm/rpmlib.h>
#include <sstream>
#include <string>
#include <vector>
namespace libdnf {
// sorted by precedence (see os-release(5) for details)
std::array<const std::string, 2> paths = {"/etc/os-release", "/usr/lib/os-release"};
// whitelists used for sanity-checking the os-release data when constructing a
// User-Agent string (to avoid reporting rare systems or platforms that could
// be tracked)
std::map<std::string, std::vector<std::string>> distros = {
// taken from the {fedora,generic}-release.spec files
{ "Fedora", { "cinnamon", "cloud", "container", "coreos", "generic", "iot",
"kde", "matecompiz", "server", "silverblue", "snappy", "soas",
"workstation", "xfce" } },
};
std::array<const std::string, 1> canons = { "Linux" };
std::map<std::string, std::string> getOsReleaseData()
{
std::map<std::string, std::string> result;
// find the first existing file path
auto it = std::find_if(paths.begin(), paths.end(), libdnf::filesystem::exists);
if (it == paths.end())
throw std::runtime_error("os-release file not found");
std::string path = *it;
auto file = libdnf::File::newFile(path);
file->open("r");
std::string line;
while (file->readLine(line)) {
// remove trailing spaces and newline
line.erase(line.find_last_not_of(" \n") + 1);
// skip empty lines
if (line.empty()) continue;
// skip comments
if (line.front() == '#') continue;
// split string by '=' into key and value
auto pos = line.find('=');
if (pos == line.npos)
throw std::runtime_error("Invalid format (missing '='): " + line);
auto key = string::trim(line.substr(0, pos));
auto value = string::trim(line.substr(pos + 1, line.length()));
// remove quotes if present
if (!value.empty() && value.front() == '"' && value.back() == '"') {
value = value.substr(1, value.length() - 2);
}
result.insert({key, value});
}
return result;
}
static void initLibRpm()
{
static bool libRpmInitiated{false};
if (libRpmInitiated) return;
if (rpmReadConfigFiles(NULL, NULL) != 0) {
throw std::runtime_error("failed to read rpm config files\n");
}
libRpmInitiated = true;
}
static std::string getBaseArch()
{
const char *value;
initLibRpm();
rpmGetArchInfo(&value, NULL);
value = find_base_arch(value);
return value ? std::string(value) : "";
}
static std::string getCanonOs()
{
const char *value;
initLibRpm();
rpmGetOsInfo(&value, NULL);
return value;
}
std::string getUserAgent(const std::map<std::string, std::string> & osReleaseData)
{
std::ostringstream oss;
auto logger(Log::getLogger());
std::string msg = "os-release: falling back to basic User-Agent";
// start with the basic libdnf string
oss << USER_AGENT;
// mandatory OS data (bail out if missing or unknown)
if (!osReleaseData.count("NAME") || !osReleaseData.count("VERSION_ID")) {
logger->debug(tfm::format("%s: missing NAME or VERSION_ID", msg));
return oss.str();
}
std::string name = osReleaseData.at("NAME");
std::string version = osReleaseData.at("VERSION_ID");
if (!distros.count(name)) {
logger->debug(tfm::format("%s: distro %s not whitelisted", msg, name));
return oss.str();
}
// mandatory platform data from RPM (bail out if missing or unknown)
std::string canon = getCanonOs();
std::string arch = getBaseArch();
if (canon.empty() || arch.empty()
|| std::find(canons.begin(), canons.end(), canon) == canons.end()) {
logger->debug(tfm::format("%s: could not detect canonical OS or basearch", msg));
return oss.str();
}
// optional OS data (use fallback values if missing or unknown)
std::string variant = "generic";
auto list = distros[name];
if (osReleaseData.count("VARIANT_ID")) {
std::string value = osReleaseData.at("VARIANT_ID");
if (std::find(list.begin(), list.end(), value) != list.end())
variant = value;
}
// good to go!
oss << " (" << name << " " << version << "; " << variant << "; "
<< canon << "." << arch << ")";
std::string result = oss.str();
logger->debug(tfm::format("os-release: User-Agent constructed: %s", result));
return result;
}
std::string getUserAgent()
{
std::map<std::string, std::string> osdata;
try {
osdata = getOsReleaseData();
} catch (std::exception & ex) {
Log::getLogger()->debug(ex.what());
}
return getUserAgent(osdata);
}
}
<|endoftext|> |
<commit_before>/***********************************************************************
filename: FalTooltip.cpp
created: Thu Jul 7 2005
author: Paul D Turner <[email protected]>
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS 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 "FalTooltip.h"
#include "falagard/CEGUIFalWidgetLookManager.h"
#include "falagard/CEGUIFalWidgetLookFeel.h"
// Start of CEGUI namespace section
namespace CEGUI
{
const utf8 FalagardTooltip::TypeName[] = "Falagard/Tooltip";
FalagardTooltip::FalagardTooltip(const String& type) :
TooltipWindowRenderer(type)
{
}
void FalagardTooltip::render()
{
// get WidgetLookFeel for the assigned look.
const WidgetLookFeel& wlf = getLookNFeel();
// try and get imagery for our current state
const StateImagery* imagery = &wlf.getStateImagery(d_window->isDisabled() ? "Disabled" : "Enabled");
// peform the rendering operation.
imagery->render(*d_window);
}
Size FalagardTooltip::getTextSize() const
{
Tooltip* w = (Tooltip*)d_window;
Size sz(w->getTextSize_impl());
// get WidgetLookFeel for the assigned look.
const WidgetLookFeel& wlf = getLookNFeel();
Rect textArea(wlf.getNamedArea("TextArea").getArea().getPixelRect(*w));
Rect wndArea(w->getArea().asAbsolute(w->getParentPixelSize()));
sz.d_width += wndArea.getWidth() - textArea.getWidth();
sz.d_height += wndArea.getHeight() - textArea.getHeight();
return sz;
}
} // End of CEGUI namespace section
<commit_msg>FIX: Resolve issue where tooltip window area was not always correctly pixel aligned.<commit_after>/***********************************************************************
filename: FalTooltip.cpp
created: Thu Jul 7 2005
author: Paul D Turner <[email protected]>
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS 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 "FalTooltip.h"
#include "falagard/CEGUIFalWidgetLookManager.h"
#include "falagard/CEGUIFalWidgetLookFeel.h"
// Start of CEGUI namespace section
namespace CEGUI
{
const utf8 FalagardTooltip::TypeName[] = "Falagard/Tooltip";
FalagardTooltip::FalagardTooltip(const String& type) :
TooltipWindowRenderer(type)
{
}
void FalagardTooltip::render()
{
// get WidgetLookFeel for the assigned look.
const WidgetLookFeel& wlf = getLookNFeel();
// try and get imagery for our current state
const StateImagery* imagery = &wlf.getStateImagery(d_window->isDisabled() ? "Disabled" : "Enabled");
// peform the rendering operation.
imagery->render(*d_window);
}
Size FalagardTooltip::getTextSize() const
{
Tooltip* w = (Tooltip*)d_window;
Size sz(w->getTextSize_impl());
// get WidgetLookFeel for the assigned look.
const WidgetLookFeel& wlf = getLookNFeel();
Rect textArea(wlf.getNamedArea("TextArea").getArea().getPixelRect(*w));
Rect wndArea(w->getArea().asAbsolute(w->getParentPixelSize()));
sz.d_width = PixelAligned(sz.d_width + wndArea.getWidth() - textArea.getWidth());
sz.d_height = PixelAligned(sz.d_height + wndArea.getHeight() - textArea.getHeight());
return sz;
}
} // End of CEGUI namespace section
<|endoftext|> |
<commit_before>#include <cassert>
#include <vSMC/internal/random.hpp>
#ifdef V_SMC_USE_STD_RANDOM
using std::binomial_distribution;
using std::discrete_distribution;
using std::gamma_distribution;
using std::lognormal_distribution;
using std::normal_distribution;
using std::uniform_int_distribution;
using std::uniform_real_distribution;
#else
#include <boost/random/discrete_distribution.hpp>
#include <boost/random/gamma_distribution.hpp>
#include <boost/random/lognormal_distribution.hpp>
#include <boost/random/normal_distribution.hpp>
#if BOOST_VERSION < 104700
using boost::binomial_distribution;
using boost::discrete_distribution;
using boost::gamma_distribution;
using boost::lognormal_distribution;
using boost::normal_distribution;
using boost::uniform_int_distribution;
using boost::uniform_real_distribution;
#else
using boost::random::binomial_distribution;
using boost::random::discrete_distribution;
using boost::random::gamma_distribution;
using boost::random::lognormal_distribution;
using boost::random::normal_distribution;
using boost::random::uniform_int_distribution;
using boost::random::uniform_real_distribution;
#endif
#endif
int main ()
{
int N = 100000;
r123::Engine<V_SMC_CRNG_TYPE> eng(V_SMC_CRNG_SEED);
binomial_distribution<> rbinom(20, 0.7);
for (int i = 0; i != N; ++i) {
int b = rbinom(eng);
assert(b >= 0 && b <= 20);
}
double prob[] = {1, 2, 3, 4};
discrete_distribution<> rsample(prob, prob + 4);
for (int i = 0; i != N; ++i) {
int s = rsample(eng);
assert(s >= 0 && s <= 3);
}
gamma_distribution<> rgamma(1, 1);
for (int i = 0; i != N; ++i) {
double g = rgamma(eng);
assert(g >= 0);
}
lognormal_distribution<> rlnom(1, 1);
for (int i = 0; i != N; ++i) {
double l = rlnom(eng);
assert(l >= 0);
}
normal_distribution<> rnorm(0, 1);
for (int i = 0; i != N; ++i) {
double n = rnorm(eng);
}
uniform_real_distribution<> ruint(1, 100);
for (int i = 0; i != N; ++i) {
int u = ruint(eng);
assert(u >= 1 && u <= 100);
}
uniform_real_distribution<> runif(0, 1);
for (int i = 0; i != N; ++i) {
double u = runif(eng);
assert(u >= 0 && u <= 1);
}
return 0;
}
<commit_msg>preparing for rjmcmc<commit_after>#include <cassert>
#include <vSMC/internal/random.hpp>
#ifdef V_SMC_USE_STD_RANDOM
using std::bernoulli_distribution;
using std::binomial_distribution;
using std::gamma_distribution;
using std::lognormal_distribution;
using std::normal_distribution;
using std::uniform_int_distribution;
using std::uniform_real_distribution;
#else
#include <boost/random/bernoulli_distribution.hpp>
#include <boost/random/gamma_distribution.hpp>
#include <boost/random/lognormal_distribution.hpp>
#include <boost/random/normal_distribution.hpp>
#include <boost/ranodm/uniform_int_distribution.hpp>
#if BOOST_VERSION < 104700
using boost::bernoulli_distribution;
using boost::binomial_distribution;
using boost::gamma_distribution;
using boost::lognormal_distribution;
using boost::normal_distribution;
using boost::uniform_int_distribution;
using boost::uniform_real_distribution;
#else
using boost::random::bernoulli_distribution;
using boost::random::binomial_distribution;
using boost::random::gamma_distribution;
using boost::random::lognormal_distribution;
using boost::random::normal_distribution;
using boost::random::uniform_int_distribution;
using boost::random::uniform_real_distribution;
#endif
#endif
int main ()
{
int N = 100000;
r123::Engine<V_SMC_CRNG_TYPE> eng(V_SMC_CRNG_SEED);
binomial_distribution<> rbinom(20, 0.7);
for (int i = 0; i != N; ++i) {
int b = rbinom(eng);
assert(b >= 0 && b <= 20);
}
gamma_distribution<> rgamma(1, 1);
for (int i = 0; i != N; ++i) {
double g = rgamma(eng);
assert(g >= 0);
}
lognormal_distribution<> rlnom(1, 1);
for (int i = 0; i != N; ++i) {
double l = rlnom(eng);
assert(l >= 0);
}
normal_distribution<> rnorm(0, 1);
for (int i = 0; i != N; ++i) {
double n = rnorm(eng);
}
uniform_real_distribution<> ruint(1, 100);
for (int i = 0; i != N; ++i) {
int u = ruint(eng);
assert(u >= 1 && u <= 100);
}
uniform_real_distribution<> runif(0, 1);
for (int i = 0; i != N; ++i) {
double u = runif(eng);
assert(u >= 0 && u <= 1);
}
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: ZipPackageEntry.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: mtg $ $Date: 2001-09-14 15:46:37 $
*
* 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): Martin Gallwey ([email protected])
*
*
************************************************************************/
#ifndef _ZIP_PACKAGE_ENTRY_HXX
#define _ZIP_PACKAGE_ENTRY_HXX
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_
#include <com/sun/star/container/XChild.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_
#include <com/sun/star/container/XNamed.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _ZIP_ENTRY_HXX_
#include <ZipEntry.hxx>
#endif
class ZipPackageFolder;
class ZipPackageEntry : public com::sun::star::container::XNamed,
public com::sun::star::container::XChild,
public com::sun::star::lang::XUnoTunnel,
public com::sun::star::beans::XPropertySet
{
protected:
bool mbIsFolder:1;
com::sun::star::uno::Reference < com::sun::star::container::XNameContainer > xParent;
::rtl::OUString sMediaType;
ZipPackageFolder * pParent;
public:
ZipEntry aEntry;
ZipPackageEntry ( bool bNewFolder );
virtual ~ZipPackageEntry( void );
::rtl::OUString & GetMediaType () { return sMediaType; }
void SetMediaType ( ::rtl::OUString & sNewType) { sMediaType = sNewType; }
void doSetParent ( ZipPackageFolder * pNewParent, sal_Bool bInsert );
bool IsFolder ( ) { return mbIsFolder; }
ZipPackageFolder* GetParent ( ) { return pParent; }
void SetFolder ( bool bSetFolder ) { mbIsFolder = bSetFolder; }
inline void clearParent ( void )
{
xParent = com::sun::star::uno::Reference < com::sun::star::container::XNameContainer > ();
}
// XInterface
virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& rType )
throw(::com::sun::star::uno::RuntimeException) = 0;
virtual void SAL_CALL acquire( )
throw() = 0;
virtual void SAL_CALL release( )
throw() = 0;
// XNamed
virtual ::rtl::OUString SAL_CALL getName( )
throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setName( const ::rtl::OUString& aName )
throw(::com::sun::star::uno::RuntimeException);
// XChild
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL getParent( )
throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setParent( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& Parent )
throw(::com::sun::star::lang::NoSupportException, ::com::sun::star::uno::RuntimeException);
// XUnoTunnel
virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier )
throw(::com::sun::star::uno::RuntimeException) = 0;
com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId( void )
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) = 0;
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) = 0;
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>#92664# don't include unnecessary pure virtual functions or implementation Id anymore<commit_after>/*************************************************************************
*
* $RCSfile: ZipPackageEntry.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: mtg $ $Date: 2001-10-02 22:13:16 $
*
* 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): Martin Gallwey ([email protected])
*
*
************************************************************************/
#ifndef _ZIP_PACKAGE_ENTRY_HXX
#define _ZIP_PACKAGE_ENTRY_HXX
#ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_
#include <com/sun/star/container/XChild.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_
#include <com/sun/star/container/XNamed.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _ZIP_ENTRY_HXX_
#include <ZipEntry.hxx>
#endif
class ZipPackageFolder;
class ZipPackageEntry : public com::sun::star::container::XNamed,
public com::sun::star::container::XChild,
public com::sun::star::lang::XUnoTunnel,
public com::sun::star::beans::XPropertySet
{
protected:
bool mbIsFolder:1;
com::sun::star::uno::Reference < com::sun::star::container::XNameContainer > xParent;
::rtl::OUString sMediaType;
ZipPackageFolder * pParent;
public:
ZipEntry aEntry;
ZipPackageEntry ( bool bNewFolder );
virtual ~ZipPackageEntry( void );
::rtl::OUString & GetMediaType () { return sMediaType; }
void SetMediaType ( ::rtl::OUString & sNewType) { sMediaType = sNewType; }
void doSetParent ( ZipPackageFolder * pNewParent, sal_Bool bInsert );
bool IsFolder ( ) { return mbIsFolder; }
ZipPackageFolder* GetParent ( ) { return pParent; }
void SetFolder ( bool bSetFolder ) { mbIsFolder = bSetFolder; }
inline void clearParent ( void )
{
xParent = com::sun::star::uno::Reference < com::sun::star::container::XNameContainer > ();
}
// XNamed
virtual ::rtl::OUString SAL_CALL getName( )
throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setName( const ::rtl::OUString& aName )
throw(::com::sun::star::uno::RuntimeException);
// XChild
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL getParent( )
throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setParent( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& Parent )
throw(::com::sun::star::lang::NoSupportException, ::com::sun::star::uno::RuntimeException);
// XUnoTunnel
virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier )
throw(::com::sun::star::uno::RuntimeException) = 0;
// 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) = 0;
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) = 0;
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>//=======================================================================
// Copyright (c) 2013-2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef CPP_UTILS_PARALLEL_HPP
#define CPP_UTILS_PARALLEL_HPP
#include<thread>
#include<future>
#include<vector>
#include<deque>
#include<functional>
namespace cpp {
template<typename Iterator, typename Functor>
void parallel_foreach(Iterator first, Iterator last, Functor&& fun){
std::vector<std::future<void>> futures;
futures.reserve(std::distance(first, last));
for(; first != last; ++first){
futures.push_back(std::move(std::async(std::launch::async, fun, *first)));
}
//No need to wait for the futures, the destructor will do it for us
}
template<typename Container, typename Functor>
void parallel_foreach_i(const Container& container, Functor&& fun){
std::vector<std::future<void>> futures;
futures.reserve(container.size());
for(std::size_t i = 0; i < container.size(); ++i){
futures.push_back(std::move(std::async(std::launch::async, fun, i)));
}
//No need to wait for the futures, the destructor will do it for us
}
template<typename Lock, typename Functor>
void with_lock(Lock& lock, Functor&& fun){
std::unique_lock<Lock> l(lock);
fun();
}
enum class thread_status {
WAITING,
WORKING
};
template<template<typename...> class queue_t = std::deque>
struct default_thread_pool {
private:
std::vector<std::thread> threads;
std::vector<thread_status> status;
queue_t<std::function<void()>> tasks;
std::mutex main_lock;
std::condition_variable condition;
volatile bool stop_flag = false;
public:
default_thread_pool(std::size_t n) : status(n, thread_status::WAITING) {
for(std::size_t t = 0; t < n; ++t){
threads.emplace_back(
[this, t]
{
while(true){
std::function<void()> task;
{
std::unique_lock<std::mutex> ulock(main_lock);
status[t] = thread_status::WAITING;
condition.wait(ulock, [this]{return stop_flag || !tasks.empty(); });
if(stop_flag && tasks.empty()){
return;
}
task = std::move(tasks.front());
tasks.pop_front();
status[t] = thread_status::WORKING;
}
task();
}
});
}
}
default_thread_pool() : default_thread_pool(std::thread::hardware_concurrency()) {}
~default_thread_pool(){
{
std::unique_lock<std::mutex> ulock(main_lock);
stop_flag = true;
}
condition.notify_all();
for(auto& thread : threads){
thread.join();
}
}
//TODO DO better than busy waiting
void wait(){
while(true){
std::unique_lock<std::mutex> ulock(main_lock);
if(tasks.empty()){
bool still_working = false;
for(auto s : status){
if(s == thread_status::WORKING){
still_working = true;
break;
}
}
if(!still_working){
return;
}
}
}
}
template<class Functor, typename... Args>
void do_task(Functor&& fun, Args&&... args){
{
std::unique_lock<std::mutex> ulock(main_lock);
if(stop_flag){
throw std::runtime_error("enqueue on stopped ThreadPool");
}
tasks.emplace_back([&fun, args...](){ fun(args...); });
}
condition.notify_one();
}
};
} //end of the cpp namespace
#endif //CPP_UTILS_PARALLEL_HPP
<commit_msg>Refactorings<commit_after>//=======================================================================
// Copyright (c) 2013-2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef CPP_UTILS_PARALLEL_HPP
#define CPP_UTILS_PARALLEL_HPP
#include<thread>
#include<future>
#include<vector>
#include<deque>
#include<functional>
namespace cpp {
template<typename Iterator, typename Functor>
void parallel_foreach(Iterator first, Iterator last, Functor&& fun){
std::vector<std::future<void>> futures;
futures.reserve(std::distance(first, last));
for(; first != last; ++first){
futures.push_back(std::move(std::async(std::launch::async, fun, *first)));
}
//No need to wait for the futures, the destructor will do it for us
}
template<typename Container, typename Functor>
void parallel_foreach_i(const Container& container, Functor&& fun){
std::vector<std::future<void>> futures;
futures.reserve(container.size());
for(std::size_t i = 0; i < container.size(); ++i){
futures.push_back(std::move(std::async(std::launch::async, fun, i)));
}
//No need to wait for the futures, the destructor will do it for us
}
template<typename Lock, typename Functor>
void with_lock(Lock& lock, Functor&& fun){
std::unique_lock<Lock> l(lock);
fun();
}
template<template<typename...> class queue_t = std::deque>
struct default_thread_pool {
enum class thread_status {
WAITING,
WORKING
};
private:
std::vector<std::thread> threads;
std::vector<thread_status> status;
queue_t<std::function<void()>> tasks;
std::mutex main_lock;
std::condition_variable condition;
volatile bool stop_flag = false;
public:
default_thread_pool(std::size_t n) : status(n, thread_status::WAITING) {
for(std::size_t t = 0; t < n; ++t){
threads.emplace_back(
[this, t]
{
while(true){
std::function<void()> task;
{
std::unique_lock<std::mutex> ulock(main_lock);
status[t] = thread_status::WAITING;
condition.wait(ulock, [this]{return stop_flag || !tasks.empty(); });
if(stop_flag && tasks.empty()){
return;
}
task = std::move(tasks.front());
tasks.pop_front();
status[t] = thread_status::WORKING;
}
task();
}
});
}
}
default_thread_pool() : default_thread_pool(std::thread::hardware_concurrency()) {}
~default_thread_pool(){
with_lock(main_lock, [this](){ stop_flag = true; });
condition.notify_all();
for(auto& thread : threads){
thread.join();
}
}
//TODO DO better than busy waiting
void wait(){
while(true){
std::unique_lock<std::mutex> ulock(main_lock);
if(tasks.empty()){
bool still_working = false;
for(auto s : status){
if(s == thread_status::WORKING){
still_working = true;
break;
}
}
if(!still_working){
return;
}
}
}
}
template<class Functor, typename... Args>
void do_task(Functor&& fun, Args&&... args){
with_lock(main_lock, [fun, &args..., this](){
if(stop_flag){
throw std::runtime_error("enqueue on stopped ThreadPool");
}
tasks.emplace_back([&fun, args...](){ fun(args...); });
});
condition.notify_one();
}
};
} //end of the cpp namespace
#endif //CPP_UTILS_PARALLEL_HPP
<|endoftext|> |
<commit_before>#include <QVector3D>
#include "coverage.h"
#include "featurecoverage.h"
#include "feature.h"
#include "geometryhelper.h"
#include "drawers/attributevisualproperties.h"
#include "drawers/drawerattributesetterfactory.h"
#include "simplelinesetter.h"
using namespace Ilwis;
using namespace Geodrawer;
REGISTER_DRAWER_ATTRIBUTE_SETTER(SimpleLineSetter)
SimpleLineSetter::SimpleLineSetter(const IOOptions &options) : BaseSpatialAttributeSetter(options)
{
}
SimpleLineSetter::~SimpleLineSetter()
{
}
DrawerAttributeSetter *SimpleLineSetter::create(const IOOptions &options)
{
return new SimpleLineSetter(options);
}
std::vector<VertexIndex> SimpleLineSetter::setSpatialAttributes(const Ilwis::SPFeatureI &feature,
QVector<QVector3D> &vertices,
QVector<QVector3D> &) const
{
const UPGeometry& geometry = feature->geometry();
bool conversionNeeded = _targetSystem != _sourceSystem;
std::vector<VertexIndex> indices;
int n = geometry->getNumGeometries();
for(int geom = 0; geom < n; ++geom ){
const geos::geom::Geometry *subgeom = geometry->getGeometryN(geom);
if (!subgeom)
continue;
auto *coords = subgeom->getCoordinates();
quint32 oldend = vertices.size();
indices.push_back(VertexIndex(oldend, coords->size(), itLINE, GL_LINE_STRIP, feature->featureid()));
vertices.resize(oldend + coords->size());
Coordinate crd;
for(int i = 0; i < coords->size(); ++i){
coords->getAt(i, crd);
if ( conversionNeeded){
crd = _targetSystem->coord2coord(_sourceSystem, crd);
}
vertices[oldend + i] = QVector3D(crd.x, crd.y, crd.z);
}
delete coords;
}
return indices;
}
void SimpleLineSetter::setColorAttributes(const AttributeVisualProperties &attr, const QVariant &value, quint32 startIndex, quint32 count, std::vector<VertexColor> &colors) const
{
if ( value.isValid() && value.toInt() != iUNDEF) {
for(int i =startIndex; i < startIndex + count; ++i){
QColor clr = attr.value2color(value);
colors.push_back(VertexColor(clr.redF(), clr.greenF(), clr.blueF(), 1.0));
}
}
}
<commit_msg>need for conversion isn now encapsulated in the base class<commit_after>#include <QVector3D>
#include "coverage.h"
#include "featurecoverage.h"
#include "feature.h"
#include "geometryhelper.h"
#include "drawers/attributevisualproperties.h"
#include "drawers/drawerattributesetterfactory.h"
#include "simplelinesetter.h"
using namespace Ilwis;
using namespace Geodrawer;
REGISTER_DRAWER_ATTRIBUTE_SETTER(SimpleLineSetter)
SimpleLineSetter::SimpleLineSetter(const IOOptions &options) : BaseSpatialAttributeSetter(options)
{
}
SimpleLineSetter::~SimpleLineSetter()
{
}
DrawerAttributeSetter *SimpleLineSetter::create(const IOOptions &options)
{
return new SimpleLineSetter(options);
}
std::vector<VertexIndex> SimpleLineSetter::setSpatialAttributes(const Ilwis::SPFeatureI &feature,
QVector<QVector3D> &vertices,
QVector<QVector3D> &) const
{
const UPGeometry& geometry = feature->geometry();
std::vector<VertexIndex> indices;
int n = geometry->getNumGeometries();
for(int geom = 0; geom < n; ++geom ){
const geos::geom::Geometry *subgeom = geometry->getGeometryN(geom);
if (!subgeom)
continue;
auto *coords = subgeom->getCoordinates();
quint32 oldend = vertices.size();
indices.push_back(VertexIndex(oldend, coords->size(), itLINE, GL_LINE_STRIP, feature->featureid()));
vertices.resize(oldend + coords->size());
Coordinate crd;
for(int i = 0; i < coords->size(); ++i){
coords->getAt(i, crd);
if ( coordinateConversionNeeded()){
crd = _targetSystem->coord2coord(_sourceSystem, crd);
}
vertices[oldend + i] = QVector3D(crd.x, crd.y, crd.z);
}
delete coords;
}
return indices;
}
void SimpleLineSetter::setColorAttributes(const AttributeVisualProperties &attr, const QVariant &value, quint32 startIndex, quint32 count, std::vector<VertexColor> &colors) const
{
if ( value.isValid() && value.toInt() != iUNDEF) {
for(int i =startIndex; i < startIndex + count; ++i){
QColor clr = attr.value2color(value);
colors.push_back(VertexColor(clr.redF(), clr.greenF(), clr.blueF(), 1.0));
}
}
}
<|endoftext|> |
<commit_before><commit_msg>typo<commit_after><|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) Qxt Foundation. Some rights reserved.
**
** This file is part of the QxtCore module of the Qxt library.
**
** This library is free software; you can redistribute it and/or modify it
** under the terms of the Common Public License, version 1.0, as published
** by IBM, and/or under the terms of the GNU Lesser General Public License,
** version 2.1, as published by the Free Software Foundation.
**
** This file is provided "AS IS", without WARRANTIES OR CONDITIONS OF ANY
** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY
** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR
** FITNESS FOR A PARTICULAR PURPOSE.
**
** You should have received a copy of the CPL and the LGPL along with this
** file. See the LICENSE file and the cpl1.0.txt/lgpl-2.1.txt files
** included with the source distribution for more information.
** If you did not receive a copy of the licenses, contact the Qxt Foundation.
**
** <http://libqxt.org> <[email protected]>
**
****************************************************************************/
/*!
\namespace QxtMetaObject
\inmodule QxtCore
\brief The QxtMetaObject namespace provides extensions to QMetaObject
including QxtMetaObject::bind
*/
#include "qxtmetaobject.h"
#include "qxtboundfunction.h"
#include "qxtboundcfunction.h"
#include "qxtmetatype.h"
#include <QByteArray>
#include <QMetaObject>
#include <QMetaMethod>
#include <QtDebug>
#ifndef QXT_DOXYGEN_RUN
class QxtBoundArgument
{
// This class intentionally left blank
};
Q_DECLARE_METATYPE(QxtBoundArgument)
class QxtBoundFunctionBase;
QxtBoundFunction::QxtBoundFunction(QObject* parent) : QObject(parent)
{
// initializer only
}
#endif
bool QxtBoundFunction::invoke(Qt::ConnectionType type, QXT_IMPL_10ARGS(QVariant))
{
return invoke(type, QXT_VAR_ARG(1), QXT_VAR_ARG(2), QXT_VAR_ARG(3), QXT_VAR_ARG(4), QXT_VAR_ARG(5), QXT_VAR_ARG(6), QXT_VAR_ARG(7), QXT_VAR_ARG(8), QXT_VAR_ARG(9), QXT_VAR_ARG(10));
}
bool QxtBoundFunction::invoke(Qt::ConnectionType type, QGenericReturnArgument returnValue, QXT_IMPL_10ARGS(QVariant))
{
return invoke(type, returnValue, QXT_VAR_ARG(1), QXT_VAR_ARG(2), QXT_VAR_ARG(3), QXT_VAR_ARG(4), QXT_VAR_ARG(5), QXT_VAR_ARG(6), QXT_VAR_ARG(7), QXT_VAR_ARG(8), QXT_VAR_ARG(9), QXT_VAR_ARG(10));
}
QxtBoundFunctionBase::QxtBoundFunctionBase(QObject* parent, QGenericArgument* params[10], QByteArray types[10]) : QxtBoundFunction(parent)
{
for (int i = 0; i < 10; i++)
{
if (!params[i]) break;
if (QByteArray(params[i]->name()) == "QxtBoundArgument")
{
arg[i] = QGenericArgument("QxtBoundArgument", params[i]->data());
}
else
{
data[i] = qxtConstructFromGenericArgument(*params[i]);
arg[i] = p[i] = QGenericArgument(params[i]->name(), data[i]);
}
bindTypes[i] = types[i];
}
}
QxtBoundFunctionBase::~QxtBoundFunctionBase()
{
for (int i = 0; i < 10; i++)
{
if (arg[i].name() == 0) return;
if (QByteArray(arg[i].name()) != "QxtBoundArgument") qxtDestroyFromGenericArgument(arg[i]);
}
}
int QxtBoundFunctionBase::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod)
{
if (_id == 0)
{
for (int i = 0; i < 10; i++)
{
if (QByteArray(arg[i].name()) == "QxtBoundArgument")
{
p[i] = QGenericArgument(bindTypes[i].constData(), _a[(quintptr)(arg[i].data())]);
}
}
invokeImpl(Qt::DirectConnection, QGenericReturnArgument(), p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9]);
}
_id = -1;
}
return _id;
}
bool QxtBoundFunctionBase::invokeBase(Qt::ConnectionType type, QGenericReturnArgument returnValue, QXT_IMPL_10ARGS(QGenericArgument))
{
QGenericArgument* args[10] = { &p1, &p2, &p3, &p4, &p5, &p6, &p7, &p8, &p9, &p10 };
for (int i = 0; i < 10; i++)
{
if (QByteArray(arg[i].name()) == "QxtBoundArgument")
{
p[i] = *args[(quintptr)(arg[i].data()) - 1];
}
}
return invokeImpl(type, returnValue, p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9]);
}
bool QxtBoundFunction::invoke(Qt::ConnectionType type, QGenericReturnArgument returnValue, QXT_IMPL_10ARGS(QGenericArgument))
{
return reinterpret_cast<QxtBoundFunctionBase*>(this)->invokeBase(type, returnValue, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10);
}
#ifndef QXT_DOXYGEN_RUN
class QxtBoundSlot : public QxtBoundFunctionBase
{
public:
QByteArray sig;
QxtBoundSlot(QObject* receiver, const char* invokable, QGenericArgument* params[10], QByteArray types[10]) : QxtBoundFunctionBase(receiver, params, types), sig(invokable)
{
// initializers only
}
virtual bool invokeImpl(Qt::ConnectionType type, QGenericReturnArgument returnValue, QXT_IMPL_10ARGS(QGenericArgument))
{
if (!QMetaObject::invokeMethod(parent(), QxtMetaObject::methodName(sig.constData()), type, returnValue, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10))
{
qWarning() << "QxtBoundFunction: call to" << sig << "failed";
return false;
}
return true;
}
};
#endif
namespace QxtMetaObject
{
/*!
Returns the name of the given method.
Example usage:
\code
QByteArray method = QxtMetaObject::methodName(" int foo ( int bar, double baz )");
// method is now "foo"
\endcode
*/
QByteArray methodName(const char* method)
{
QByteArray name = methodSignature(method);
const int idx = name.indexOf("(");
if (idx != -1)
name.truncate(idx);
return name;
}
/*!
Returns the signature of the given method.
*/
QByteArray methodSignature(const char* method)
{
QByteArray name = QMetaObject::normalizedSignature(method);
if(name[0] >= '0' && name[0] <= '9')
return name.mid(1);
return name;
}
/*!
Checks if \a method contains parentheses and begins with 1 or 2.
*/
bool isSignalOrSlot(const char* method)
{
QByteArray m(method);
return (m.count() && (m[0] >= '0' && m[0] <= '9') && m.contains('(') && m.contains(')'));
}
/*!
* Creates a binding to the provided signal, slot, or Q_INVOKABLE method using the
* provided parameter list. The type of each argument is deduced from the type of
* the QVariant. This function cannot bind positional arguments; see the
* overload using QGenericArgument.
*
* If the provided QObject does not implement the requested method, or if the
* argument list is incompatible with the method's function signature, this
* function returns NULL.
*
* The returned QxtBoundFunction is created as a child of the receiver.
* Changing the parent will result in undefined behavior.
*
* \sa QxtMetaObject::connect, QxtBoundFunction
*/
QxtBoundFunction* bind(QObject* recv, const char* invokable, QXT_IMPL_10ARGS(QVariant))
{
if (!recv)
{
qWarning() << "QxtMetaObject::bind: cannot connect to null QObject";
return 0;
}
QVariant* args[10] = { &p1, &p2, &p3, &p4, &p5, &p6, &p7, &p8, &p9, &p10 };
QByteArray connSlot("2"), recvSlot(QMetaObject::normalizedSignature(invokable));
const QMetaObject* meta = recv->metaObject();
int methodID = meta->indexOfMethod(QxtMetaObject::methodSignature(recvSlot.constData()));
if (methodID == -1)
{
qWarning() << "QxtMetaObject::bind: no such method " << recvSlot;
return 0;
}
QMetaMethod method = meta->method(methodID);
int argCount = method.parameterTypes().count();
const QList<QByteArray> paramTypes = method.parameterTypes();
for (int i = 0; i < argCount; i++)
{
if (paramTypes[i] == "QxtBoundArgument") continue;
int type = QMetaType::type(paramTypes[i].constData());
if (!args[i]->canConvert((QVariant::Type)type))
{
qWarning() << "QxtMetaObject::bind: incompatible parameter list for " << recvSlot;
return 0;
}
}
return QxtMetaObject::bind(recv, invokable, QXT_ARG(1), QXT_ARG(2), QXT_ARG(3), QXT_ARG(4), QXT_ARG(5), QXT_ARG(6), QXT_ARG(7), QXT_ARG(8), QXT_ARG(9), QXT_ARG(10));
}
/*!
* Creates a binding to the provided signal, slot, or Q_INVOKABLE method using the
* provided parameter list. Use the Q_ARG macro to specify constant parameters, or
* use the QXT_BIND macro to relay a parameter from a connected signal or passed
* via the QxtBoundFunction::invoke() method.
*
* If the provided QObject does not implement the requested method, or if the
* argument list is incompatible with the method's function signature, this
* function returns NULL.
*
* The returned QxtBoundFunction is created as a child of the receiver.
* Changing the parent will result in undefined behavior.
*
* \sa QxtMetaObject::connect, QxtBoundFunction, QXT_BIND
*/
QxtBoundFunction* bind(QObject* recv, const char* invokable, QXT_IMPL_10ARGS(QGenericArgument))
{
if (!recv)
{
qWarning() << "QxtMetaObject::bind: cannot connect to null QObject";
return 0;
}
QGenericArgument* args[10] = { &p1, &p2, &p3, &p4, &p5, &p6, &p7, &p8, &p9, &p10 };
QByteArray connSlot("2"), recvSlot(QMetaObject::normalizedSignature(invokable)), bindTypes[10];
const QMetaObject* meta = recv->metaObject();
int methodID = meta->indexOfMethod(QxtMetaObject::methodSignature(recvSlot.constData()).constData());
if (methodID == -1)
{
qWarning() << "QxtMetaObject::bind: no such method " << recvSlot;
return 0;
}
QMetaMethod method = meta->method(methodID);
int argCount = method.parameterTypes().count();
connSlot += QxtMetaObject::methodName(invokable) + '(';
for (int i = 0; i < 10; i++)
{
if (args[i]->name() == 0) break; // done
if (i >= argCount)
{
qWarning() << "QxtMetaObject::bind: too many arguments passed to " << invokable;
return 0;
}
if (i > 0) connSlot += ','; // argument separator
if (QByteArray(args[i]->name()) == "QxtBoundArgument")
{
Q_ASSERT_X((quintptr)(args[i]->data()) > 0 && (quintptr)(args[i]->data()) <= 10, "QXT_BIND", "invalid argument number");
connSlot += method.parameterTypes()[i];
bindTypes[i] = method.parameterTypes()[i];
}
else
{
connSlot += args[i]->name(); // type name
}
}
connSlot = QMetaObject::normalizedSignature(connSlot += ')');
if (!QMetaObject::checkConnectArgs(recvSlot.constData(), connSlot.constData()))
{
qWarning() << "QxtMetaObject::bind: provided parameters " << connSlot.mid(connSlot.indexOf('(')) << " is incompatible with " << invokable;
return 0;
}
return new QxtBoundSlot(recv, invokable, args, bindTypes);
}
/*!
Connects a signal to a QxtBoundFunction.
*/
bool connect(QObject* sender, const char* signal, QxtBoundFunction* slot, Qt::ConnectionType type)
{
const QMetaObject* meta = sender->metaObject();
int methodID = meta->indexOfMethod(meta->normalizedSignature(signal).mid(1).constData());
if (methodID < 0)
{
qWarning() << "QxtMetaObject::connect: no such signal: " << QByteArray(signal).mid(1);
return false;
}
return QMetaObject::connect(sender, methodID, slot, QObject::staticMetaObject.methodCount(), (int)(type));
}
/*!
\relates QxtMetaObject
This overload always invokes the member using the connection type Qt::AutoConnection.
\sa QMetaObject::invokeMethod()
*/
bool invokeMethod(QObject* object, const char* member, const QVariant& arg0,
const QVariant& arg1, const QVariant& arg2, const QVariant& arg3,
const QVariant& arg4, const QVariant& arg5, const QVariant& arg6,
const QVariant& arg7, const QVariant& arg8, const QVariant& arg9)
{
return invokeMethod(object, member, Qt::AutoConnection,
arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9);
}
/*!
\relates QxtMetaObject
Invokes the \a member (a signal or a slot name) on the \a object.
Returns \c true if the member could be invoked. Returns \c false
if there is no such member or the parameters did not match.
\sa QMetaObject::invokeMethod()
*/
bool invokeMethod(QObject* object, const char* member, Qt::ConnectionType type,
const QVariant& arg0, const QVariant& arg1, const QVariant& arg2,
const QVariant& arg3, const QVariant& arg4, const QVariant& arg5,
const QVariant& arg6, const QVariant& arg7, const QVariant& arg8, const QVariant& arg9)
{
#define QXT_ARG(i) QGenericArgument(arg ## i.typeName(), arg ## i.constData())
return QMetaObject::invokeMethod(object, methodName(member), type,
QXT_ARG(0), QXT_ARG(1), QXT_ARG(2), QXT_ARG(3), QXT_ARG(4),
QXT_ARG(5), QXT_ARG(6), QXT_ARG(7), QXT_ARG(8), QXT_ARG(9));
}
}
<commit_msg>Fixed conflicting QXT_ARG.<commit_after>/****************************************************************************
**
** Copyright (C) Qxt Foundation. Some rights reserved.
**
** This file is part of the QxtCore module of the Qxt library.
**
** This library is free software; you can redistribute it and/or modify it
** under the terms of the Common Public License, version 1.0, as published
** by IBM, and/or under the terms of the GNU Lesser General Public License,
** version 2.1, as published by the Free Software Foundation.
**
** This file is provided "AS IS", without WARRANTIES OR CONDITIONS OF ANY
** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY
** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR
** FITNESS FOR A PARTICULAR PURPOSE.
**
** You should have received a copy of the CPL and the LGPL along with this
** file. See the LICENSE file and the cpl1.0.txt/lgpl-2.1.txt files
** included with the source distribution for more information.
** If you did not receive a copy of the licenses, contact the Qxt Foundation.
**
** <http://libqxt.org> <[email protected]>
**
****************************************************************************/
/*!
\namespace QxtMetaObject
\inmodule QxtCore
\brief The QxtMetaObject namespace provides extensions to QMetaObject
including QxtMetaObject::bind
*/
#include "qxtmetaobject.h"
#include "qxtboundfunction.h"
#include "qxtboundcfunction.h"
#include "qxtmetatype.h"
#include <QByteArray>
#include <QMetaObject>
#include <QMetaMethod>
#include <QtDebug>
#ifndef QXT_DOXYGEN_RUN
class QxtBoundArgument
{
// This class intentionally left blank
};
Q_DECLARE_METATYPE(QxtBoundArgument)
class QxtBoundFunctionBase;
QxtBoundFunction::QxtBoundFunction(QObject* parent) : QObject(parent)
{
// initializer only
}
#endif
bool QxtBoundFunction::invoke(Qt::ConnectionType type, QXT_IMPL_10ARGS(QVariant))
{
return invoke(type, QXT_VAR_ARG(1), QXT_VAR_ARG(2), QXT_VAR_ARG(3), QXT_VAR_ARG(4), QXT_VAR_ARG(5), QXT_VAR_ARG(6), QXT_VAR_ARG(7), QXT_VAR_ARG(8), QXT_VAR_ARG(9), QXT_VAR_ARG(10));
}
bool QxtBoundFunction::invoke(Qt::ConnectionType type, QGenericReturnArgument returnValue, QXT_IMPL_10ARGS(QVariant))
{
return invoke(type, returnValue, QXT_VAR_ARG(1), QXT_VAR_ARG(2), QXT_VAR_ARG(3), QXT_VAR_ARG(4), QXT_VAR_ARG(5), QXT_VAR_ARG(6), QXT_VAR_ARG(7), QXT_VAR_ARG(8), QXT_VAR_ARG(9), QXT_VAR_ARG(10));
}
QxtBoundFunctionBase::QxtBoundFunctionBase(QObject* parent, QGenericArgument* params[10], QByteArray types[10]) : QxtBoundFunction(parent)
{
for (int i = 0; i < 10; i++)
{
if (!params[i]) break;
if (QByteArray(params[i]->name()) == "QxtBoundArgument")
{
arg[i] = QGenericArgument("QxtBoundArgument", params[i]->data());
}
else
{
data[i] = qxtConstructFromGenericArgument(*params[i]);
arg[i] = p[i] = QGenericArgument(params[i]->name(), data[i]);
}
bindTypes[i] = types[i];
}
}
QxtBoundFunctionBase::~QxtBoundFunctionBase()
{
for (int i = 0; i < 10; i++)
{
if (arg[i].name() == 0) return;
if (QByteArray(arg[i].name()) != "QxtBoundArgument") qxtDestroyFromGenericArgument(arg[i]);
}
}
int QxtBoundFunctionBase::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod)
{
if (_id == 0)
{
for (int i = 0; i < 10; i++)
{
if (QByteArray(arg[i].name()) == "QxtBoundArgument")
{
p[i] = QGenericArgument(bindTypes[i].constData(), _a[(quintptr)(arg[i].data())]);
}
}
invokeImpl(Qt::DirectConnection, QGenericReturnArgument(), p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9]);
}
_id = -1;
}
return _id;
}
bool QxtBoundFunctionBase::invokeBase(Qt::ConnectionType type, QGenericReturnArgument returnValue, QXT_IMPL_10ARGS(QGenericArgument))
{
QGenericArgument* args[10] = { &p1, &p2, &p3, &p4, &p5, &p6, &p7, &p8, &p9, &p10 };
for (int i = 0; i < 10; i++)
{
if (QByteArray(arg[i].name()) == "QxtBoundArgument")
{
p[i] = *args[(quintptr)(arg[i].data()) - 1];
}
}
return invokeImpl(type, returnValue, p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9]);
}
bool QxtBoundFunction::invoke(Qt::ConnectionType type, QGenericReturnArgument returnValue, QXT_IMPL_10ARGS(QGenericArgument))
{
return reinterpret_cast<QxtBoundFunctionBase*>(this)->invokeBase(type, returnValue, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10);
}
#ifndef QXT_DOXYGEN_RUN
class QxtBoundSlot : public QxtBoundFunctionBase
{
public:
QByteArray sig;
QxtBoundSlot(QObject* receiver, const char* invokable, QGenericArgument* params[10], QByteArray types[10]) : QxtBoundFunctionBase(receiver, params, types), sig(invokable)
{
// initializers only
}
virtual bool invokeImpl(Qt::ConnectionType type, QGenericReturnArgument returnValue, QXT_IMPL_10ARGS(QGenericArgument))
{
if (!QMetaObject::invokeMethod(parent(), QxtMetaObject::methodName(sig.constData()), type, returnValue, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10))
{
qWarning() << "QxtBoundFunction: call to" << sig << "failed";
return false;
}
return true;
}
};
#endif
namespace QxtMetaObject
{
/*!
Returns the name of the given method.
Example usage:
\code
QByteArray method = QxtMetaObject::methodName(" int foo ( int bar, double baz )");
// method is now "foo"
\endcode
*/
QByteArray methodName(const char* method)
{
QByteArray name = methodSignature(method);
const int idx = name.indexOf("(");
if (idx != -1)
name.truncate(idx);
return name;
}
/*!
Returns the signature of the given method.
*/
QByteArray methodSignature(const char* method)
{
QByteArray name = QMetaObject::normalizedSignature(method);
if(name[0] >= '0' && name[0] <= '9')
return name.mid(1);
return name;
}
/*!
Checks if \a method contains parentheses and begins with 1 or 2.
*/
bool isSignalOrSlot(const char* method)
{
QByteArray m(method);
return (m.count() && (m[0] >= '0' && m[0] <= '9') && m.contains('(') && m.contains(')'));
}
/*!
* Creates a binding to the provided signal, slot, or Q_INVOKABLE method using the
* provided parameter list. The type of each argument is deduced from the type of
* the QVariant. This function cannot bind positional arguments; see the
* overload using QGenericArgument.
*
* If the provided QObject does not implement the requested method, or if the
* argument list is incompatible with the method's function signature, this
* function returns NULL.
*
* The returned QxtBoundFunction is created as a child of the receiver.
* Changing the parent will result in undefined behavior.
*
* \sa QxtMetaObject::connect, QxtBoundFunction
*/
QxtBoundFunction* bind(QObject* recv, const char* invokable, QXT_IMPL_10ARGS(QVariant))
{
if (!recv)
{
qWarning() << "QxtMetaObject::bind: cannot connect to null QObject";
return 0;
}
QVariant* args[10] = { &p1, &p2, &p3, &p4, &p5, &p6, &p7, &p8, &p9, &p10 };
QByteArray connSlot("2"), recvSlot(QMetaObject::normalizedSignature(invokable));
const QMetaObject* meta = recv->metaObject();
int methodID = meta->indexOfMethod(QxtMetaObject::methodSignature(recvSlot.constData()));
if (methodID == -1)
{
qWarning() << "QxtMetaObject::bind: no such method " << recvSlot;
return 0;
}
QMetaMethod method = meta->method(methodID);
int argCount = method.parameterTypes().count();
const QList<QByteArray> paramTypes = method.parameterTypes();
for (int i = 0; i < argCount; i++)
{
if (paramTypes[i] == "QxtBoundArgument") continue;
int type = QMetaType::type(paramTypes[i].constData());
if (!args[i]->canConvert((QVariant::Type)type))
{
qWarning() << "QxtMetaObject::bind: incompatible parameter list for " << recvSlot;
return 0;
}
}
return QxtMetaObject::bind(recv, invokable, QXT_ARG(1), QXT_ARG(2), QXT_ARG(3), QXT_ARG(4), QXT_ARG(5), QXT_ARG(6), QXT_ARG(7), QXT_ARG(8), QXT_ARG(9), QXT_ARG(10));
}
/*!
* Creates a binding to the provided signal, slot, or Q_INVOKABLE method using the
* provided parameter list. Use the Q_ARG macro to specify constant parameters, or
* use the QXT_BIND macro to relay a parameter from a connected signal or passed
* via the QxtBoundFunction::invoke() method.
*
* If the provided QObject does not implement the requested method, or if the
* argument list is incompatible with the method's function signature, this
* function returns NULL.
*
* The returned QxtBoundFunction is created as a child of the receiver.
* Changing the parent will result in undefined behavior.
*
* \sa QxtMetaObject::connect, QxtBoundFunction, QXT_BIND
*/
QxtBoundFunction* bind(QObject* recv, const char* invokable, QXT_IMPL_10ARGS(QGenericArgument))
{
if (!recv)
{
qWarning() << "QxtMetaObject::bind: cannot connect to null QObject";
return 0;
}
QGenericArgument* args[10] = { &p1, &p2, &p3, &p4, &p5, &p6, &p7, &p8, &p9, &p10 };
QByteArray connSlot("2"), recvSlot(QMetaObject::normalizedSignature(invokable)), bindTypes[10];
const QMetaObject* meta = recv->metaObject();
int methodID = meta->indexOfMethod(QxtMetaObject::methodSignature(recvSlot.constData()).constData());
if (methodID == -1)
{
qWarning() << "QxtMetaObject::bind: no such method " << recvSlot;
return 0;
}
QMetaMethod method = meta->method(methodID);
int argCount = method.parameterTypes().count();
connSlot += QxtMetaObject::methodName(invokable) + '(';
for (int i = 0; i < 10; i++)
{
if (args[i]->name() == 0) break; // done
if (i >= argCount)
{
qWarning() << "QxtMetaObject::bind: too many arguments passed to " << invokable;
return 0;
}
if (i > 0) connSlot += ','; // argument separator
if (QByteArray(args[i]->name()) == "QxtBoundArgument")
{
Q_ASSERT_X((quintptr)(args[i]->data()) > 0 && (quintptr)(args[i]->data()) <= 10, "QXT_BIND", "invalid argument number");
connSlot += method.parameterTypes()[i];
bindTypes[i] = method.parameterTypes()[i];
}
else
{
connSlot += args[i]->name(); // type name
}
}
connSlot = QMetaObject::normalizedSignature(connSlot += ')');
if (!QMetaObject::checkConnectArgs(recvSlot.constData(), connSlot.constData()))
{
qWarning() << "QxtMetaObject::bind: provided parameters " << connSlot.mid(connSlot.indexOf('(')) << " is incompatible with " << invokable;
return 0;
}
return new QxtBoundSlot(recv, invokable, args, bindTypes);
}
/*!
Connects a signal to a QxtBoundFunction.
*/
bool connect(QObject* sender, const char* signal, QxtBoundFunction* slot, Qt::ConnectionType type)
{
const QMetaObject* meta = sender->metaObject();
int methodID = meta->indexOfMethod(meta->normalizedSignature(signal).mid(1).constData());
if (methodID < 0)
{
qWarning() << "QxtMetaObject::connect: no such signal: " << QByteArray(signal).mid(1);
return false;
}
return QMetaObject::connect(sender, methodID, slot, QObject::staticMetaObject.methodCount(), (int)(type));
}
/*!
\relates QxtMetaObject
This overload always invokes the member using the connection type Qt::AutoConnection.
\sa QMetaObject::invokeMethod()
*/
bool invokeMethod(QObject* object, const char* member, const QVariant& arg0,
const QVariant& arg1, const QVariant& arg2, const QVariant& arg3,
const QVariant& arg4, const QVariant& arg5, const QVariant& arg6,
const QVariant& arg7, const QVariant& arg8, const QVariant& arg9)
{
return invokeMethod(object, member, Qt::AutoConnection,
arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9);
}
/*!
\relates QxtMetaObject
Invokes the \a member (a signal or a slot name) on the \a object.
Returns \c true if the member could be invoked. Returns \c false
if there is no such member or the parameters did not match.
\sa QMetaObject::invokeMethod()
*/
bool invokeMethod(QObject* object, const char* member, Qt::ConnectionType type,
const QVariant& arg0, const QVariant& arg1, const QVariant& arg2,
const QVariant& arg3, const QVariant& arg4, const QVariant& arg5,
const QVariant& arg6, const QVariant& arg7, const QVariant& arg8, const QVariant& arg9)
{
#define QXT_MO_ARG(i) QGenericArgument(arg ## i.typeName(), arg ## i.constData())
return QMetaObject::invokeMethod(object, methodName(member), type,
QXT_MO_ARG(0), QXT_MO_ARG(1), QXT_MO_ARG(2), QXT_MO_ARG(3), QXT_MO_ARG(4),
QXT_MO_ARG(5), QXT_MO_ARG(6), QXT_MO_ARG(7), QXT_MO_ARG(8), QXT_MO_ARG(9));
}
}
<|endoftext|> |
<commit_before>#include "huffman.hpp"
#include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <utility>
#include <string>
#include <cstring>
#include <limits>
#include "heap.hpp"
#include "binarystream.hpp"
using namespace algorithm;
void
Huffman
::CompressFile(StreamInType & fin, StreamOutType & fout)
{
CollectRuns(fin);
PrintAllRuns();
fin.clear(); /** Remove eofbit */
WriteHeader(fin, fout);
CreateHuffmanTree();
AssignCodeword(root_, 0, 0);
PrintHuffmanTree();
CreateRunList(root_);
WriteEncode(fin, fout);
}
void
Huffman
::DecompressFile(StreamInType & fin, StreamOutType & fout)
{
ReadHeader(fin);
PrintAllRuns();
CreateHuffmanTree();
AssignCodeword(root_, 0, 0);
PrintHuffmanTree();
WriteDecode(fin, fout);
}
void
Huffman
::PrintAllRuns(FILE * f)
{
fprintf(f, "SYM LENG FREQ\n"); /** Header of data */
for(auto run : runs_)
fprintf(f, " %02x %4lu %lu\n", run.symbol, run.run_len, run.freq);
}
void
Huffman
::CollectRuns(StreamInType & fin)
{
typedef std::map<MetaSymbolType, unsigned int> CacheType;
typedef CacheType::iterator CacheIterType;
CacheType cache; /**< Caching a position of the run in the vector(runs_) */
fin.clear(); /** Reset the input position indicator */
fin.seekg(0, fin.beg);
while(! fin.eof())
{
ByteType symbol;
SizeType run_len = 1;
BinaryStream::Read<ByteType>(fin, symbol);
if(fin.eof())
break;
//BinaryStream::Read<SizeType>(fin, run_len);
/** Insert the pair into runs_;
key: pair(symbol, run_len)
value: appearance frequency of key
*/
MetaSymbolType meta_symbol = std::make_pair(symbol, run_len);
CacheIterType cache_iter = cache.find(meta_symbol); /** Get the position from cache */
if(cache_iter == cache.end())
{
runs_.push_back(RunType(meta_symbol, 1)); /** First appreance; freq is 1 */
cache.emplace(meta_symbol, runs_.size() - 1); /** Cache the position */
}
else
++runs_.at(cache_iter->second); /** Add freq */
}
}
void
Huffman
::CreateHuffmanTree(void)
{
Heap<RunType> heap;
for(auto run : runs_)
heap.Push(run);
while(heap.size() > 1)
{
RunType * left = new RunType(heap.Peek());
heap.Pop();
RunType * right = new RunType(heap.Peek());
heap.Pop();
RunType temp(left, right);
heap.Push(temp);
}
root_ = new RunType(heap.Peek());
heap.Pop();
}
void
Huffman
::AssignCodeword(RunType * node, const CodewordType & codeword, const SizeType & codeword_len)
{
if(node->left == nullptr && node->right == nullptr)
{
node->codeword = codeword;
node->codeword_len = codeword_len;
}
else
{
AssignCodeword(node->left, (codeword << 1) + 0, codeword_len + 1);
AssignCodeword(node->right, (codeword << 1) + 1, codeword_len + 1);
}
}
void
Huffman
::CreateRunList(RunType * node)
{
if(node->left == nullptr && node->right == nullptr)
{
//printf("[%4d] %02x:%d:%d:%d %x\n", ++count, node->symbol, node->run_len, node->freq, node->codeword_len, node->codeword);
if(list_.at(node->symbol) == nullptr)
list_.at(node->symbol) = node;
else
{
node->next = list_.at(node->symbol);
list_.at(node->symbol) = node;
}
}
else
{
if(node->left != nullptr)
CreateRunList(node->left);
if(node->right != nullptr)
CreateRunList(node->right);
}
}
Huffman
::SizeType
Huffman
::GetCodeword(CodewordType & codeword, const ByteType & symbol, const SizeType & run_len)
{
RunType * n = list_.at(symbol);
for(; n != nullptr && n->run_len != run_len; n = n->next);
if(n == nullptr)
return 0;
else
{
codeword = n->codeword;
return n->codeword_len;
}
}
void
Huffman
::WriteHeader(StreamInType & fin, StreamOutType & fout)
{
uint16_t run_size = uint16_t(runs_.size());
BinaryStream::Write<uint16_t>(fout, run_size);
fin.clear();
fin.seekg(0, fin.end);
uint32_t fin_size = uint32_t(fin.tellg());
BinaryStream::Write<uint32_t>(fout, SizeType(fin.tellg()));
for(auto run : runs_)
{
BinaryStream::Write<ByteType>(fout, run.symbol);
BinaryStream::Write<SizeType>(fout, run.run_len);
BinaryStream::Write<SizeType>(fout, run.freq);
}
}
void
Huffman
::WriteEncode(StreamInType & fin, StreamOutType & fout)
{
const SizeType bufstat_max = buffer_size;
SizeType bufstat_free = bufstat_max;
CodewordType buffer = 0;
/** Reset the input position indicator */
fin.clear();
fin.seekg(0, fin.beg);
while(! fin.eof())
{
ByteType symbol;
SizeType run_len = 1;
BinaryStream::Read<ByteType>(fin, symbol);
if(fin.eof())
break;
/** Write the codeword to fout */
CodewordType codeword;
SizeType codeword_len = GetCodeword(codeword, symbol, run_len);
if(codeword_len == 0)
return; /* TODO: Exception(Codeword not found) */
while(codeword_len >= bufstat_free)
{
buffer <<= bufstat_free;
buffer += (codeword >> (codeword_len - bufstat_free));
codeword = codeword % (0x1 << codeword_len - bufstat_free);
codeword_len -= bufstat_free;
BinaryStream::Write<CodewordType>(fout, buffer, false);
buffer = 0;
bufstat_free = bufstat_max;
}
buffer <<= codeword_len;
buffer += codeword;
bufstat_free -= codeword_len;
}
}
void
Huffman
::PrintHuffmanTree(FILE * f, const RunType * node, const SizeType & depth)
{
for(int i = 0; i < depth; ++i)
fprintf(f, " ");
if(node == nullptr)
fprintf(f, "null\n");
else
{
fprintf(f, "%02x:%lu:%lu:%lu %x\n"
, node->symbol
, node->run_len
, node->freq
, node->codeword_len
, node->codeword);
PrintHuffmanTree(f, node->left, depth + 1);
PrintHuffmanTree(f, node->right, depth + 1);
}
}
Huffman::
SizeType
Huffman::
ReadHeader(StreamInType & fin)
{
typedef std::map<MetaSymbolType, unsigned int> CacheType;
typedef CacheType::iterator CacheIterType;
fin.clear();
fin.seekg(0, fin.beg);
uint16_t run_size;
BinaryStream::Read<uint16_t>(fin, run_size);
uint32_t fin_size;
BinaryStream::Read<uint32_t>(fin, fin_size);
runs_.clear();
for(int i = 0; i < run_size; ++i)
{
ByteType symbol;
BinaryStream::Read<ByteType>(fin, symbol);
SizeType run_len;
BinaryStream::Read<SizeType>(fin, run_len);
SizeType freq;
BinaryStream::Read<SizeType>(fin, freq);
Run temp = Run(symbol, run_len, freq);
runs_.push_back(temp);
}
}
void
Huffman::
WriteDecode(StreamInType & fin, StreamOutType & fout)
{
const SizeType bufstat_max = buffer_size;
SizeType bufstat_free = bufstat_max;
CodewordType buffer = 0;
Run * run = root_;
fout.clear();
fout.seekp(0, fin.beg);
while(! fin.eof())
{
BinaryStream::Read<CodewordType>(fin, buffer);
bufstat_free = 0;
while(bufstat_free < bufstat_max)
{
if(buffer % 2 == zerobit)
run = run->left;
else
run = run->right;
buffer >>= 0x1;
++bufstat_free;
if(run->codeword_len > 0)
{
for(int i = 0; i < run->run_len; ++i)
BinaryStream::Write<ByteType>(fout, run->symbol);
run = root_;
}
}
}
}
<commit_msg>Reverse the decompress buffer direction<commit_after>#include "huffman.hpp"
#include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <utility>
#include <string>
#include <cstring>
#include <limits>
#include "heap.hpp"
#include "binarystream.hpp"
using namespace algorithm;
void
Huffman
::CompressFile(StreamInType & fin, StreamOutType & fout)
{
CollectRuns(fin);
PrintAllRuns();
fin.clear(); /** Remove eofbit */
WriteHeader(fin, fout);
CreateHuffmanTree();
AssignCodeword(root_, 0, 0);
PrintHuffmanTree();
CreateRunList(root_);
WriteEncode(fin, fout);
}
void
Huffman
::DecompressFile(StreamInType & fin, StreamOutType & fout)
{
ReadHeader(fin);
PrintAllRuns();
CreateHuffmanTree();
AssignCodeword(root_, 0, 0);
PrintHuffmanTree();
WriteDecode(fin, fout);
}
void
Huffman
::PrintAllRuns(FILE * f)
{
fprintf(f, "SYM LENG FREQ\n"); /** Header of data */
for(auto run : runs_)
fprintf(f, " %02x %4lu %lu\n", run.symbol, run.run_len, run.freq);
}
void
Huffman
::CollectRuns(StreamInType & fin)
{
typedef std::map<MetaSymbolType, unsigned int> CacheType;
typedef CacheType::iterator CacheIterType;
CacheType cache; /**< Caching a position of the run in the vector(runs_) */
fin.clear(); /** Reset the input position indicator */
fin.seekg(0, fin.beg);
while(! fin.eof())
{
ByteType symbol;
SizeType run_len = 1;
BinaryStream::Read<ByteType>(fin, symbol);
if(fin.eof())
break;
//BinaryStream::Read<SizeType>(fin, run_len);
/** Insert the pair into runs_;
key: pair(symbol, run_len)
value: appearance frequency of key
*/
MetaSymbolType meta_symbol = std::make_pair(symbol, run_len);
CacheIterType cache_iter = cache.find(meta_symbol); /** Get the position from cache */
if(cache_iter == cache.end())
{
runs_.push_back(RunType(meta_symbol, 1)); /** First appreance; freq is 1 */
cache.emplace(meta_symbol, runs_.size() - 1); /** Cache the position */
}
else
++runs_.at(cache_iter->second); /** Add freq */
}
}
void
Huffman
::CreateHuffmanTree(void)
{
Heap<RunType> heap;
for(auto run : runs_)
heap.Push(run);
while(heap.size() > 1)
{
RunType * left = new RunType(heap.Peek());
heap.Pop();
RunType * right = new RunType(heap.Peek());
heap.Pop();
RunType temp(left, right);
heap.Push(temp);
}
root_ = new RunType(heap.Peek());
heap.Pop();
}
void
Huffman
::AssignCodeword(RunType * node, const CodewordType & codeword, const SizeType & codeword_len)
{
if(node->left == nullptr && node->right == nullptr)
{
node->codeword = codeword;
node->codeword_len = codeword_len;
}
else
{
AssignCodeword(node->left, (codeword << 1) + 0, codeword_len + 1);
AssignCodeword(node->right, (codeword << 1) + 1, codeword_len + 1);
}
}
void
Huffman
::CreateRunList(RunType * node)
{
if(node->left == nullptr && node->right == nullptr)
{
//printf("[%4d] %02x:%d:%d:%d %x\n", ++count, node->symbol, node->run_len, node->freq, node->codeword_len, node->codeword);
if(list_.at(node->symbol) == nullptr)
list_.at(node->symbol) = node;
else
{
node->next = list_.at(node->symbol);
list_.at(node->symbol) = node;
}
}
else
{
if(node->left != nullptr)
CreateRunList(node->left);
if(node->right != nullptr)
CreateRunList(node->right);
}
}
Huffman
::SizeType
Huffman
::GetCodeword(CodewordType & codeword, const ByteType & symbol, const SizeType & run_len)
{
RunType * n = list_.at(symbol);
for(; n != nullptr && n->run_len != run_len; n = n->next);
if(n == nullptr)
return 0;
else
{
codeword = n->codeword;
return n->codeword_len;
}
}
void
Huffman
::WriteHeader(StreamInType & fin, StreamOutType & fout)
{
uint16_t run_size = uint16_t(runs_.size());
BinaryStream::Write<uint16_t>(fout, run_size);
fin.clear();
fin.seekg(0, fin.end);
uint32_t fin_size = uint32_t(fin.tellg());
BinaryStream::Write<uint32_t>(fout, SizeType(fin.tellg()));
for(auto run : runs_)
{
BinaryStream::Write<ByteType>(fout, run.symbol);
BinaryStream::Write<SizeType>(fout, run.run_len);
BinaryStream::Write<SizeType>(fout, run.freq);
}
}
void
Huffman
::WriteEncode(StreamInType & fin, StreamOutType & fout)
{
const SizeType bufstat_max = buffer_size;
SizeType bufstat_free = bufstat_max;
CodewordType buffer = 0;
/** Reset the input position indicator */
fin.clear();
fin.seekg(0, fin.beg);
while(! fin.eof())
{
ByteType symbol;
SizeType run_len = 1;
BinaryStream::Read<ByteType>(fin, symbol);
if(fin.eof())
break;
/** Write the codeword to fout */
CodewordType codeword;
SizeType codeword_len = GetCodeword(codeword, symbol, run_len);
if(codeword_len == 0)
return; /* TODO: Exception(Codeword not found) */
while(codeword_len >= bufstat_free)
{
buffer <<= bufstat_free;
buffer += (codeword >> (codeword_len - bufstat_free));
codeword = codeword % (0x1 << codeword_len - bufstat_free);
codeword_len -= bufstat_free;
BinaryStream::Write<CodewordType>(fout, buffer, false);
buffer = 0;
bufstat_free = bufstat_max;
}
buffer <<= codeword_len;
buffer += codeword;
bufstat_free -= codeword_len;
}
}
void
Huffman
::PrintHuffmanTree(FILE * f, const RunType * node, const SizeType & depth)
{
for(int i = 0; i < depth; ++i)
fprintf(f, " ");
if(node == nullptr)
fprintf(f, "null\n");
else
{
fprintf(f, "%02x:%lu:%lu:%lu %x\n"
, node->symbol
, node->run_len
, node->freq
, node->codeword_len
, node->codeword);
PrintHuffmanTree(f, node->left, depth + 1);
PrintHuffmanTree(f, node->right, depth + 1);
}
}
Huffman::
SizeType
Huffman::
ReadHeader(StreamInType & fin)
{
typedef std::map<MetaSymbolType, unsigned int> CacheType;
typedef CacheType::iterator CacheIterType;
fin.clear();
fin.seekg(0, fin.beg);
uint16_t run_size;
BinaryStream::Read<uint16_t>(fin, run_size);
uint32_t fin_size;
BinaryStream::Read<uint32_t>(fin, fin_size);
runs_.clear();
for(int i = 0; i < run_size; ++i)
{
ByteType symbol;
BinaryStream::Read<ByteType>(fin, symbol);
SizeType run_len;
BinaryStream::Read<SizeType>(fin, run_len);
SizeType freq;
BinaryStream::Read<SizeType>(fin, freq);
Run temp = Run(symbol, run_len, freq);
runs_.push_back(temp);
}
}
void
Huffman::
WriteDecode(StreamInType & fin, StreamOutType & fout)
{
const SizeType bufstat_max = buffer_size;
SizeType bufstat_free = bufstat_max;
CodewordType buffer = 0;
Run * run = root_;
fout.clear();
fout.seekp(0, fin.beg);
while(! fin.eof())
{
BinaryStream::Read<CodewordType>(fin, buffer);
bufstat_free = 0;
while(bufstat_free < bufstat_max)
{
if(buffer / (0x1 << (buffer_size - 1)) == zerobit)
run = run->left;
else
run = run->right;
buffer <<= 0x1;
++bufstat_free;
if(run->codeword_len > 0)
{
for(int i = 0; i < run->run_len; ++i)
BinaryStream::Write<ByteType>(fout, run->symbol);
run = root_;
}
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2014 GitHub, Inc. All rights reserved.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/web_dialog_helper.h"
#include <string>
#include <vector>
#include "atom/browser/atom_browser_context.h"
#include "atom/browser/native_window.h"
#include "atom/browser/ui/file_dialog.h"
#include "base/bind.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/common/pref_names.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/file_chooser_file_info.h"
#include "content/public/common/file_chooser_params.h"
#include "net/base/mime_util.h"
#include "ui/shell_dialogs/selected_file_info.h"
namespace {
class FileSelectHelper : public base::RefCounted<FileSelectHelper>,
public content::WebContentsObserver {
public:
FileSelectHelper(content::RenderFrameHost* render_frame_host,
const content::FileChooserParams::Mode& mode)
: render_frame_host_(render_frame_host), mode_(mode) {
auto web_contents = content::WebContents::FromRenderFrameHost(
render_frame_host);
content::WebContentsObserver::Observe(web_contents);
// Add ref that will be released when the dialog is completed
AddRef();
}
void ShowOpenDialog(const file_dialog::DialogSettings& settings) {
auto callback = base::Bind(&FileSelectHelper::OnOpenDialogDone, this);
file_dialog::ShowOpenDialog(settings, callback);
}
void ShowSaveDialog(const file_dialog::DialogSettings& settings) {
auto callback = base::Bind(&FileSelectHelper::OnSaveDialogDone, this);
file_dialog::ShowSaveDialog(settings, callback);
}
private:
friend class base::RefCounted<FileSelectHelper>;
~FileSelectHelper() override {}
void OnOpenDialogDone(bool result, const std::vector<base::FilePath>& paths) {
std::vector<content::FileChooserFileInfo> file_info;
if (result) {
for (auto& path : paths) {
content::FileChooserFileInfo info;
info.file_path = path;
info.display_name = path.BaseName().value();
file_info.push_back(info);
}
if (!paths.empty()) {
auto browser_context = static_cast<atom::AtomBrowserContext*>(
render_frame_host_->GetProcess()->GetBrowserContext());
browser_context->prefs()->SetFilePath(prefs::kSelectFileLastDirectory,
paths[0].DirName());
}
}
OnFilesSelected(file_info);
}
void OnSaveDialogDone(bool result, const base::FilePath& path) {
std::vector<content::FileChooserFileInfo> file_info;
if (result) {
content::FileChooserFileInfo info;
info.file_path = path;
info.display_name = path.BaseName().value();
file_info.push_back(info);
}
OnFilesSelected(file_info);
}
void OnFilesSelected(
const std::vector<content::FileChooserFileInfo>& file_info) {
if (render_frame_host_)
render_frame_host_->FilesSelectedInChooser(file_info, mode_);
Release();
}
// content::WebContentsObserver:
void RenderFrameHostChanged(content::RenderFrameHost* old_host,
content::RenderFrameHost* new_host) override {
if (old_host == render_frame_host_)
render_frame_host_ = nullptr;
}
// content::WebContentsObserver:
void RenderFrameDeleted(content::RenderFrameHost* deleted_host) override {
if (deleted_host == render_frame_host_)
render_frame_host_ = nullptr;
}
// content::WebContentsObserver:
void WebContentsDestroyed() override {
render_frame_host_ = nullptr;
}
content::RenderFrameHost* render_frame_host_;
content::FileChooserParams::Mode mode_;
};
file_dialog::Filters GetFileTypesFromAcceptType(
const std::vector<base::string16>& accept_types) {
file_dialog::Filters filters;
if (accept_types.empty())
return filters;
std::vector<base::FilePath::StringType> extensions;
for (const auto& accept_type : accept_types) {
std::string ascii_type = base::UTF16ToASCII(accept_type);
if (ascii_type[0] == '.') {
// If the type starts with a period it is assumed to be a file extension,
// like `.txt`, // so we just have to add it to the list.
base::FilePath::StringType extension(
ascii_type.begin(), ascii_type.end());
// Skip the first character.
extensions.push_back(extension.substr(1));
} else {
// For MIME Type, `audio/*, vidio/*, image/*
net::GetExtensionsForMimeType(ascii_type, &extensions);
}
}
// If no valid exntesion is added, return empty filters.
if (extensions.empty())
return filters;
filters.push_back(file_dialog::Filter());
for (const auto& extension : extensions) {
#if defined(OS_WIN)
filters[0].second.push_back(base::UTF16ToASCII(extension));
#else
filters[0].second.push_back(extension);
#endif
}
return filters;
}
} // namespace
namespace atom {
WebDialogHelper::WebDialogHelper(NativeWindow* window)
: window_(window),
weak_factory_(this) {
}
WebDialogHelper::~WebDialogHelper() {
}
void WebDialogHelper::RunFileChooser(
content::RenderFrameHost* render_frame_host,
const content::FileChooserParams& params) {
std::vector<content::FileChooserFileInfo> result;
file_dialog::DialogSettings settings;
settings.filters = GetFileTypesFromAcceptType(params.accept_types);
settings.parent_window = window_;
settings.title = base::UTF16ToUTF8(params.title);
scoped_refptr<FileSelectHelper> file_select_helper(
new FileSelectHelper(render_frame_host, params.mode));
if (params.mode == content::FileChooserParams::Save) {
settings.default_path = params.default_file_name;
file_select_helper->ShowSaveDialog(settings);
} else {
int flags = file_dialog::FILE_DIALOG_CREATE_DIRECTORY;
switch (params.mode) {
case content::FileChooserParams::OpenMultiple:
flags |= file_dialog::FILE_DIALOG_MULTI_SELECTIONS;
case content::FileChooserParams::Open:
flags |= file_dialog::FILE_DIALOG_OPEN_FILE;
break;
case content::FileChooserParams::UploadFolder:
flags |= file_dialog::FILE_DIALOG_OPEN_DIRECTORY;
break;
default:
NOTREACHED();
}
AtomBrowserContext* browser_context = static_cast<AtomBrowserContext*>(
window_->web_contents()->GetBrowserContext());
settings.default_path = browser_context->prefs()->GetFilePath(
prefs::kSelectFileLastDirectory).Append(params.default_file_name);
settings.properties = flags;
file_select_helper->ShowOpenDialog(settings);
}
}
void WebDialogHelper::EnumerateDirectory(content::WebContents* web_contents,
int request_id,
const base::FilePath& dir) {
int types = base::FileEnumerator::FILES |
base::FileEnumerator::DIRECTORIES |
base::FileEnumerator::INCLUDE_DOT_DOT;
base::FileEnumerator file_enum(dir, false, types);
base::FilePath path;
std::vector<base::FilePath> paths;
while (!(path = file_enum.Next()).empty())
paths.push_back(path);
web_contents->GetRenderViewHost()->DirectoryEnumerationFinished(
request_id, paths);
}
} // namespace atom
<commit_msg>Check render frame host before getting context<commit_after>// Copyright (c) 2014 GitHub, Inc. All rights reserved.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/web_dialog_helper.h"
#include <string>
#include <vector>
#include "atom/browser/atom_browser_context.h"
#include "atom/browser/native_window.h"
#include "atom/browser/ui/file_dialog.h"
#include "base/bind.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/common/pref_names.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/file_chooser_file_info.h"
#include "content/public/common/file_chooser_params.h"
#include "net/base/mime_util.h"
#include "ui/shell_dialogs/selected_file_info.h"
namespace {
class FileSelectHelper : public base::RefCounted<FileSelectHelper>,
public content::WebContentsObserver {
public:
FileSelectHelper(content::RenderFrameHost* render_frame_host,
const content::FileChooserParams::Mode& mode)
: render_frame_host_(render_frame_host), mode_(mode) {
auto web_contents = content::WebContents::FromRenderFrameHost(
render_frame_host);
content::WebContentsObserver::Observe(web_contents);
// Add ref that will be released when the dialog is completed
AddRef();
}
void ShowOpenDialog(const file_dialog::DialogSettings& settings) {
auto callback = base::Bind(&FileSelectHelper::OnOpenDialogDone, this);
file_dialog::ShowOpenDialog(settings, callback);
}
void ShowSaveDialog(const file_dialog::DialogSettings& settings) {
auto callback = base::Bind(&FileSelectHelper::OnSaveDialogDone, this);
file_dialog::ShowSaveDialog(settings, callback);
}
private:
friend class base::RefCounted<FileSelectHelper>;
~FileSelectHelper() override {}
void OnOpenDialogDone(bool result, const std::vector<base::FilePath>& paths) {
std::vector<content::FileChooserFileInfo> file_info;
if (result) {
for (auto& path : paths) {
content::FileChooserFileInfo info;
info.file_path = path;
info.display_name = path.BaseName().value();
file_info.push_back(info);
}
if (render_frame_host_ && !paths.empty()) {
auto browser_context = static_cast<atom::AtomBrowserContext*>(
render_frame_host_->GetProcess()->GetBrowserContext());
browser_context->prefs()->SetFilePath(prefs::kSelectFileLastDirectory,
paths[0].DirName());
}
}
OnFilesSelected(file_info);
}
void OnSaveDialogDone(bool result, const base::FilePath& path) {
std::vector<content::FileChooserFileInfo> file_info;
if (result) {
content::FileChooserFileInfo info;
info.file_path = path;
info.display_name = path.BaseName().value();
file_info.push_back(info);
}
OnFilesSelected(file_info);
}
void OnFilesSelected(
const std::vector<content::FileChooserFileInfo>& file_info) {
if (render_frame_host_)
render_frame_host_->FilesSelectedInChooser(file_info, mode_);
Release();
}
// content::WebContentsObserver:
void RenderFrameHostChanged(content::RenderFrameHost* old_host,
content::RenderFrameHost* new_host) override {
if (old_host == render_frame_host_)
render_frame_host_ = nullptr;
}
// content::WebContentsObserver:
void RenderFrameDeleted(content::RenderFrameHost* deleted_host) override {
if (deleted_host == render_frame_host_)
render_frame_host_ = nullptr;
}
// content::WebContentsObserver:
void WebContentsDestroyed() override {
render_frame_host_ = nullptr;
}
content::RenderFrameHost* render_frame_host_;
content::FileChooserParams::Mode mode_;
};
file_dialog::Filters GetFileTypesFromAcceptType(
const std::vector<base::string16>& accept_types) {
file_dialog::Filters filters;
if (accept_types.empty())
return filters;
std::vector<base::FilePath::StringType> extensions;
for (const auto& accept_type : accept_types) {
std::string ascii_type = base::UTF16ToASCII(accept_type);
if (ascii_type[0] == '.') {
// If the type starts with a period it is assumed to be a file extension,
// like `.txt`, // so we just have to add it to the list.
base::FilePath::StringType extension(
ascii_type.begin(), ascii_type.end());
// Skip the first character.
extensions.push_back(extension.substr(1));
} else {
// For MIME Type, `audio/*, vidio/*, image/*
net::GetExtensionsForMimeType(ascii_type, &extensions);
}
}
// If no valid exntesion is added, return empty filters.
if (extensions.empty())
return filters;
filters.push_back(file_dialog::Filter());
for (const auto& extension : extensions) {
#if defined(OS_WIN)
filters[0].second.push_back(base::UTF16ToASCII(extension));
#else
filters[0].second.push_back(extension);
#endif
}
return filters;
}
} // namespace
namespace atom {
WebDialogHelper::WebDialogHelper(NativeWindow* window)
: window_(window),
weak_factory_(this) {
}
WebDialogHelper::~WebDialogHelper() {
}
void WebDialogHelper::RunFileChooser(
content::RenderFrameHost* render_frame_host,
const content::FileChooserParams& params) {
std::vector<content::FileChooserFileInfo> result;
file_dialog::DialogSettings settings;
settings.filters = GetFileTypesFromAcceptType(params.accept_types);
settings.parent_window = window_;
settings.title = base::UTF16ToUTF8(params.title);
scoped_refptr<FileSelectHelper> file_select_helper(
new FileSelectHelper(render_frame_host, params.mode));
if (params.mode == content::FileChooserParams::Save) {
settings.default_path = params.default_file_name;
file_select_helper->ShowSaveDialog(settings);
} else {
int flags = file_dialog::FILE_DIALOG_CREATE_DIRECTORY;
switch (params.mode) {
case content::FileChooserParams::OpenMultiple:
flags |= file_dialog::FILE_DIALOG_MULTI_SELECTIONS;
case content::FileChooserParams::Open:
flags |= file_dialog::FILE_DIALOG_OPEN_FILE;
break;
case content::FileChooserParams::UploadFolder:
flags |= file_dialog::FILE_DIALOG_OPEN_DIRECTORY;
break;
default:
NOTREACHED();
}
AtomBrowserContext* browser_context = static_cast<AtomBrowserContext*>(
window_->web_contents()->GetBrowserContext());
settings.default_path = browser_context->prefs()->GetFilePath(
prefs::kSelectFileLastDirectory).Append(params.default_file_name);
settings.properties = flags;
file_select_helper->ShowOpenDialog(settings);
}
}
void WebDialogHelper::EnumerateDirectory(content::WebContents* web_contents,
int request_id,
const base::FilePath& dir) {
int types = base::FileEnumerator::FILES |
base::FileEnumerator::DIRECTORIES |
base::FileEnumerator::INCLUDE_DOT_DOT;
base::FileEnumerator file_enum(dir, false, types);
base::FilePath path;
std::vector<base::FilePath> paths;
while (!(path = file_enum.Next()).empty())
paths.push_back(path);
web_contents->GetRenderViewHost()->DirectoryEnumerationFinished(
request_id, paths);
}
} // namespace atom
<|endoftext|> |
<commit_before>#include "GL.h"
#include "VBO.h"
#include <cassert>
#include <iostream>
using namespace std;
static GLenum getGLDrawType(VBO::DrawType type) {
switch (type) {
case VBO::NONE: break;
case VBO::POINTS: return GL_POINTS;
case VBO::LINES: return GL_LINES;
case VBO::TRIANGLES: return GL_TRIANGLES;
case VBO::TRIANGLE_STRIP: return GL_TRIANGLE_STRIP;
case VBO::TRIANGLE_FAN: return GL_TRIANGLE_FAN;
}
assert(0);
return 0;
}
VBO::~VBO() {
clear();
}
void
VBO::clear() {
if (vbo) {
glDeleteBuffers(1, &vbo);
vbo = 0;
}
if (indexVbo) {
glDeleteBuffers(1, &indexVbo);
indexVbo = 0;
}
num_indices = num_elements = 0;
}
void
VBO::bind() {
// assert(num_elements > 0);
if (getTexture().get()) {
glBindTexture(GL_TEXTURE_2D, texture.getTextureId());
}
if (vbo) {
glBindBuffer(GL_ARRAY_BUFFER, vbo);
switch (getDataType()) {
case T2F_N3F_V3F:
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, getStride(), (void *)(0 * sizeof(float)));
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, getStride(), (void *)(5 * sizeof(float)));
break;
case NODE_BILLBOARDS:
glVertexAttribPointer(0, 4, GL_UNSIGNED_BYTE, GL_TRUE, getStride(), (void *)(0)); // color
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, getStride(), (void *)(4)); // center position
glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, getStride(), (void *)(16)); // age
glVertexAttribPointer(3, 1, GL_FLOAT, GL_FALSE, getStride(), (void *)(20)); // size
glVertexAttribPointer(4, 1, GL_FLOAT, GL_FALSE, getStride(), (void *)(24)); // scaling
glVertexAttribPointer(5, 2, GL_UNSIGNED_SHORT, GL_FALSE, getStride(), (void *)(28)); // texture / flags
break;
case BILLBOARDS:
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, getStride(), (void *)(0 * sizeof(float)));
glVertexAttribPointer(1, 2, GL_HALF_FLOAT, GL_FALSE, getStride(), (void *)(3 * sizeof(float)));
glVertexAttribPointer(2, 2, GL_HALF_FLOAT, GL_FALSE, getStride(), (void *)(4 * sizeof(float)));
glVertexAttribPointer(3, 2, GL_HALF_FLOAT, GL_FALSE, getStride(), (void *)(5 * sizeof(float)));
glVertexAttribPointer(4, 4, GL_UNSIGNED_BYTE, GL_TRUE, getStride(), (void *)(6 * sizeof(float)));
glVertexAttribPointer(5, 4, GL_UNSIGNED_BYTE, GL_TRUE, getStride(), (void *)(7 * sizeof(float)));
break;
case EDGES:
glVertexAttribPointer(0, 4, GL_UNSIGNED_BYTE, GL_TRUE, getStride(), (void *)(0 * sizeof(float)));
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, getStride(), (void *)(1 * sizeof(float)));
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, getStride(), (void *)(4 * sizeof(float)));
glVertexAttribPointer(3, 1, GL_FLOAT, GL_FALSE, getStride(), (void *)(7 * sizeof(float)));
glVertexAttribPointer(4, 1, GL_FLOAT, GL_FALSE, getStride(), (void *)(8 * sizeof(float)));
glVertexAttribPointer(5, 1, GL_FLOAT, GL_FALSE, getStride(), (void *)(9 * sizeof(float)));
break;
case ARCS_2D:
glVertexAttribPointer(0, 4, GL_UNSIGNED_BYTE, GL_TRUE, getStride(), (void *)(0 * sizeof(float)));
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, getStride(), (void *)(1 * sizeof(float)));
break;
case ARCS_3D:
glVertexAttribPointer(0, 4, GL_UNSIGNED_BYTE, GL_TRUE, getStride(), (void *)(0 * sizeof(float)));
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, getStride(), (void *)(1 * sizeof(float)));
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, getStride(), (void *)(4 * sizeof(float)));
break;
}
}
if (indexVbo) {
// assert(num_indices > 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexVbo);
}
}
void
VBO::unbind() {
if (vbo) {
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
if (indexVbo) {
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
if (texture.get()) {
glBindTexture(GL_TEXTURE_2D, 0);
}
}
void
VBO::upload(DataType type, const void * ptr, size_t size) {
// assert(size > 0);
data_type = type;
switch (type) {
#if 0
case VBO::C4F_N3F_V3F: stride = 10 * sizeof(float); break;
case VBO::T2F_C4F_N3F_V3F: stride = 12 * sizeof(float); break;
#endif
case VBO::T2F_N3F_V3F: stride = 8 * sizeof(float); break;
case VBO::NODE_BILLBOARDS: stride = sizeof(node_billboard_vbo_s); break; // ?
case VBO::BILLBOARDS: stride = sizeof(billboard_data_s); break;
case VBO::EDGES: stride = sizeof(line_data_s); break;
case VBO::ARCS_2D: stride = sizeof(arc_data_2d_s); break;
case VBO::ARCS_3D: stride = sizeof(arc_data_3d_s); break;
}
assert(sizeof(node_vbo_s) == 7 * 4);
num_elements = size / stride;
if (!vao) {
// glGenVertexArrays(1, &vao);
// glBindVertexArray(vao);
}
if (!vbo) {
glGenBuffers(1, &vbo);
}
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, size, ptr, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void
VBO::uploadIndices(const void * ptr, size_t size) {
assert(size > 0);
if (!indexVbo) {
glGenBuffers(1, &indexVbo);
}
num_indices = size / 4;
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexVbo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, ptr, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
void
VBO::draw(DrawType type, const vector<int> & _indices) {
cerr << "wrong draw\n";
bind();
const int & first_index = _indices.front();
glDrawElements(getGLDrawType(type), _indices.size(), GL_UNSIGNED_INT, &first_index);
unbind();
}
void
VBO::draw(DrawType type) {
if (!type) type = default_draw_type;
bind();
if (!num_indices) {
glDrawArrays(getGLDrawType(type), 0, num_elements);
} else {
glDrawElements(getGLDrawType(type), num_indices, GL_UNSIGNED_INT, 0);
}
unbind();
}
void
VBO::quad2d(float x1, float y1,
float x2, float y2,
float x3, float y3,
float x4, float y4) {
default_draw_type = TRIANGLE_FAN;
vbo_data_s * data = new vbo_data_s[4];
unsigned int * indices = new unsigned int[4];
data[0] = { glm::vec2(0, 0), glm::vec3(0, 0, 1), glm::vec3(x1, y1, 0) };
data[1] = { glm::vec2(0, 1), glm::vec3(0, 0, 1), glm::vec3(x2, y2, 0) };
data[2] = { glm::vec2(1, 1), glm::vec3(0, 0, 1), glm::vec3(x3, y3, 0) };
data[3] = { glm::vec2(1, 0), glm::vec3(0, 0, 1), glm::vec3(x4, y4, 0) };
upload(T2F_N3F_V3F, data, 4 * sizeof(vbo_data_s));
indices[0] = 0;
indices[1] = 1;
indices[2] = 2;
indices[3] = 3;
uploadIndices(indices, 4 * sizeof(unsigned int));
delete[] indices;
delete[] data;
}
void
VBO::quad2d(float x1, float y1, float tx1, float ty1,
float x2, float y2, float tx2, float ty2,
float x3, float y3, float tx3, float ty3,
float x4, float y4, float tx4, float ty4) {
default_draw_type = TRIANGLE_FAN;
vbo_data_s * data = new vbo_data_s[4];
unsigned int * indices = new unsigned int[4];
data[0] = { glm::vec2(tx1, ty1), glm::vec3(0, 0, 1), glm::vec3(x1, y1, 0) };
data[1] = { glm::vec2(tx2, ty2), glm::vec3(0, 0, 1), glm::vec3(x2, y2, 0) };
data[2] = { glm::vec2(tx3, ty3), glm::vec3(0, 0, 1), glm::vec3(x3, y3, 0) };
data[3] = { glm::vec2(tx4, ty4), glm::vec3(0, 0, 1), glm::vec3(x4, y4, 0) };
upload(T2F_N3F_V3F, data, 4 * sizeof(vbo_data_s));
indices[0] = 0;
indices[1] = 1;
indices[2] = 2;
indices[3] = 3;
uploadIndices(indices, 4 * sizeof(unsigned int));
delete[] indices;
delete[] data;
}
void
VBO::sphere(float radius, unsigned int u, unsigned int v) {
default_draw_type = TRIANGLES;
vbo_data_s * data = new vbo_data_s[u * v];
unsigned int * indices = new unsigned int[6 * u * v];
unsigned int in = 0, vn = 0;
for (unsigned int i = 0; i < u; i++) {
for (unsigned int j = 0; j < v; j++) {
float tx = (float)i / (u - 1), ty = (float)j / (v - 1);
float i2 = (float)i / u * 2 * M_PI, j2 = ((float)j / v - 0.5f) * M_PI;
float x = -radius * cos(j2) * cos(i2);
float y = -radius * sin(j2);
float z = radius * cos(j2) * sin(i2);
indices[in++] = i * v + j;
indices[in++] = i * v + (j + 1) % v;
indices[in++] = ((i + 1) % u) * v + (j + 1) % v;
indices[in++] = i * v + j;
indices[in++] = ((i + 1) % u) * v + (j + 1) % v;
indices[in++] = ((i + 1) % u) * v + j;
data[vn++] = { glm::vec2(tx, ty), glm::vec3(0, 0, 1), glm::vec3(x, y, z) };
}
}
uploadIndices(indices, in * sizeof(unsigned int));
upload(T2F_N3F_V3F, data, vn * sizeof(vbo_data_s));
delete[] indices;
delete[] data;
}
void
VBO::ring(float outer_radius, float inner_radius, unsigned int n, float dx, float dy) {
default_draw_type = TRIANGLE_STRIP;
vbo_data_s * data = new vbo_data_s[2 * n];
unsigned int * indices = new unsigned int[2 * n];
unsigned int vn = 0, in = 0;
for (unsigned int i = 0; i < n; i++) {
float a = 2 * M_PI / (n - 1);
float x1 = outer_radius * cos(a) + dx, y1 = outer_radius * sin(a) + dy;
float x2 = inner_radius * cos(a) + dx, y2 = inner_radius * sin(a) + dy;
if (i % 2 == 0) {
indices[in++] = vn + 0;
indices[in++] = vn + 1;
} else {
indices[in++] = vn + 1;
indices[in++] = vn + 0;
}
data[vn++] = { glm::vec2(0.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(x1, y1, 0.0f) };
data[vn++] = { glm::vec2(0.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(x2, y2, 0.0f) };
}
cerr << "vbo ring vn = " << vn << ", in = " << in << endl;
upload(T2F_N3F_V3F, data, vn * sizeof(vbo_data_s));
uploadIndices(indices, in * sizeof(unsigned int));
delete[] data;
delete[] indices;
}
<commit_msg>remove unnecessary code<commit_after>#include "GL.h"
#include "VBO.h"
#include <cassert>
#include <iostream>
using namespace std;
static GLenum getGLDrawType(VBO::DrawType type) {
switch (type) {
case VBO::NONE: break;
case VBO::POINTS: return GL_POINTS;
case VBO::LINES: return GL_LINES;
case VBO::TRIANGLES: return GL_TRIANGLES;
case VBO::TRIANGLE_STRIP: return GL_TRIANGLE_STRIP;
case VBO::TRIANGLE_FAN: return GL_TRIANGLE_FAN;
}
assert(0);
return 0;
}
VBO::~VBO() {
clear();
}
void
VBO::clear() {
if (vbo) {
glDeleteBuffers(1, &vbo);
vbo = 0;
}
if (indexVbo) {
glDeleteBuffers(1, &indexVbo);
indexVbo = 0;
}
num_indices = num_elements = 0;
}
void
VBO::bind() {
// assert(num_elements > 0);
if (getTexture().get()) {
glBindTexture(GL_TEXTURE_2D, texture.getTextureId());
}
if (vbo) {
glBindBuffer(GL_ARRAY_BUFFER, vbo);
switch (getDataType()) {
case T2F_N3F_V3F:
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, getStride(), (void *)(0 * sizeof(float)));
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, getStride(), (void *)(5 * sizeof(float)));
break;
case NODE_BILLBOARDS:
glVertexAttribPointer(0, 4, GL_UNSIGNED_BYTE, GL_TRUE, getStride(), (void *)(0)); // color
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, getStride(), (void *)(4)); // center position
glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, getStride(), (void *)(16)); // age
glVertexAttribPointer(3, 1, GL_FLOAT, GL_FALSE, getStride(), (void *)(20)); // size
glVertexAttribPointer(4, 1, GL_FLOAT, GL_FALSE, getStride(), (void *)(24)); // scaling
glVertexAttribPointer(5, 2, GL_UNSIGNED_SHORT, GL_FALSE, getStride(), (void *)(28)); // texture / flags
break;
case BILLBOARDS:
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, getStride(), (void *)(0 * sizeof(float)));
glVertexAttribPointer(1, 2, GL_HALF_FLOAT, GL_FALSE, getStride(), (void *)(3 * sizeof(float)));
glVertexAttribPointer(2, 2, GL_HALF_FLOAT, GL_FALSE, getStride(), (void *)(4 * sizeof(float)));
glVertexAttribPointer(3, 2, GL_HALF_FLOAT, GL_FALSE, getStride(), (void *)(5 * sizeof(float)));
glVertexAttribPointer(4, 4, GL_UNSIGNED_BYTE, GL_TRUE, getStride(), (void *)(6 * sizeof(float)));
glVertexAttribPointer(5, 4, GL_UNSIGNED_BYTE, GL_TRUE, getStride(), (void *)(7 * sizeof(float)));
break;
case EDGES:
glVertexAttribPointer(0, 4, GL_UNSIGNED_BYTE, GL_TRUE, getStride(), (void *)(0 * sizeof(float)));
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, getStride(), (void *)(1 * sizeof(float)));
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, getStride(), (void *)(4 * sizeof(float)));
glVertexAttribPointer(3, 1, GL_FLOAT, GL_FALSE, getStride(), (void *)(7 * sizeof(float)));
glVertexAttribPointer(4, 1, GL_FLOAT, GL_FALSE, getStride(), (void *)(8 * sizeof(float)));
glVertexAttribPointer(5, 1, GL_FLOAT, GL_FALSE, getStride(), (void *)(9 * sizeof(float)));
break;
case ARCS_2D:
glVertexAttribPointer(0, 4, GL_UNSIGNED_BYTE, GL_TRUE, getStride(), (void *)(0 * sizeof(float)));
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, getStride(), (void *)(1 * sizeof(float)));
break;
case ARCS_3D:
glVertexAttribPointer(0, 4, GL_UNSIGNED_BYTE, GL_TRUE, getStride(), (void *)(0 * sizeof(float)));
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, getStride(), (void *)(1 * sizeof(float)));
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, getStride(), (void *)(4 * sizeof(float)));
break;
}
}
if (indexVbo) {
// assert(num_indices > 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexVbo);
}
}
void
VBO::unbind() {
if (vbo) {
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
if (indexVbo) {
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
if (texture.get()) {
glBindTexture(GL_TEXTURE_2D, 0);
}
}
void
VBO::upload(DataType type, const void * ptr, size_t size) {
// assert(size > 0);
data_type = type;
switch (type) {
case VBO::T2F_N3F_V3F: stride = 8 * sizeof(float); break;
case VBO::NODE_BILLBOARDS: stride = sizeof(node_billboard_vbo_s); break; // ?
case VBO::BILLBOARDS: stride = sizeof(billboard_data_s); break;
case VBO::EDGES: stride = sizeof(line_data_s); break;
case VBO::ARCS_2D: stride = sizeof(arc_data_2d_s); break;
case VBO::ARCS_3D: stride = sizeof(arc_data_3d_s); break;
}
num_elements = size / stride;
if (!vao) {
// glGenVertexArrays(1, &vao);
// glBindVertexArray(vao);
}
if (!vbo) {
glGenBuffers(1, &vbo);
}
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, size, ptr, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void
VBO::uploadIndices(const void * ptr, size_t size) {
assert(size > 0);
if (!indexVbo) {
glGenBuffers(1, &indexVbo);
}
num_indices = size / 4;
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexVbo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, ptr, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
void
VBO::draw(DrawType type, const vector<int> & _indices) {
cerr << "wrong draw\n";
bind();
const int & first_index = _indices.front();
glDrawElements(getGLDrawType(type), _indices.size(), GL_UNSIGNED_INT, &first_index);
unbind();
}
void
VBO::draw(DrawType type) {
if (!type) type = default_draw_type;
bind();
if (!num_indices) {
glDrawArrays(getGLDrawType(type), 0, num_elements);
} else {
glDrawElements(getGLDrawType(type), num_indices, GL_UNSIGNED_INT, 0);
}
unbind();
}
void
VBO::quad2d(float x1, float y1,
float x2, float y2,
float x3, float y3,
float x4, float y4) {
default_draw_type = TRIANGLE_FAN;
vbo_data_s * data = new vbo_data_s[4];
unsigned int * indices = new unsigned int[4];
data[0] = { glm::vec2(0, 0), glm::vec3(0, 0, 1), glm::vec3(x1, y1, 0) };
data[1] = { glm::vec2(0, 1), glm::vec3(0, 0, 1), glm::vec3(x2, y2, 0) };
data[2] = { glm::vec2(1, 1), glm::vec3(0, 0, 1), glm::vec3(x3, y3, 0) };
data[3] = { glm::vec2(1, 0), glm::vec3(0, 0, 1), glm::vec3(x4, y4, 0) };
upload(T2F_N3F_V3F, data, 4 * sizeof(vbo_data_s));
indices[0] = 0;
indices[1] = 1;
indices[2] = 2;
indices[3] = 3;
uploadIndices(indices, 4 * sizeof(unsigned int));
delete[] indices;
delete[] data;
}
void
VBO::quad2d(float x1, float y1, float tx1, float ty1,
float x2, float y2, float tx2, float ty2,
float x3, float y3, float tx3, float ty3,
float x4, float y4, float tx4, float ty4) {
default_draw_type = TRIANGLE_FAN;
vbo_data_s * data = new vbo_data_s[4];
unsigned int * indices = new unsigned int[4];
data[0] = { glm::vec2(tx1, ty1), glm::vec3(0, 0, 1), glm::vec3(x1, y1, 0) };
data[1] = { glm::vec2(tx2, ty2), glm::vec3(0, 0, 1), glm::vec3(x2, y2, 0) };
data[2] = { glm::vec2(tx3, ty3), glm::vec3(0, 0, 1), glm::vec3(x3, y3, 0) };
data[3] = { glm::vec2(tx4, ty4), glm::vec3(0, 0, 1), glm::vec3(x4, y4, 0) };
upload(T2F_N3F_V3F, data, 4 * sizeof(vbo_data_s));
indices[0] = 0;
indices[1] = 1;
indices[2] = 2;
indices[3] = 3;
uploadIndices(indices, 4 * sizeof(unsigned int));
delete[] indices;
delete[] data;
}
void
VBO::sphere(float radius, unsigned int u, unsigned int v) {
default_draw_type = TRIANGLES;
vbo_data_s * data = new vbo_data_s[u * v];
unsigned int * indices = new unsigned int[6 * u * v];
unsigned int in = 0, vn = 0;
for (unsigned int i = 0; i < u; i++) {
for (unsigned int j = 0; j < v; j++) {
float tx = (float)i / (u - 1), ty = (float)j / (v - 1);
float i2 = (float)i / u * 2 * M_PI, j2 = ((float)j / v - 0.5f) * M_PI;
float x = -radius * cos(j2) * cos(i2);
float y = -radius * sin(j2);
float z = radius * cos(j2) * sin(i2);
indices[in++] = i * v + j;
indices[in++] = i * v + (j + 1) % v;
indices[in++] = ((i + 1) % u) * v + (j + 1) % v;
indices[in++] = i * v + j;
indices[in++] = ((i + 1) % u) * v + (j + 1) % v;
indices[in++] = ((i + 1) % u) * v + j;
data[vn++] = { glm::vec2(tx, ty), glm::vec3(0, 0, 1), glm::vec3(x, y, z) };
}
}
uploadIndices(indices, in * sizeof(unsigned int));
upload(T2F_N3F_V3F, data, vn * sizeof(vbo_data_s));
delete[] indices;
delete[] data;
}
void
VBO::ring(float outer_radius, float inner_radius, unsigned int n, float dx, float dy) {
default_draw_type = TRIANGLE_STRIP;
vbo_data_s * data = new vbo_data_s[2 * n];
unsigned int * indices = new unsigned int[2 * n];
unsigned int vn = 0, in = 0;
for (unsigned int i = 0; i < n; i++) {
float a = 2 * M_PI / (n - 1);
float x1 = outer_radius * cos(a) + dx, y1 = outer_radius * sin(a) + dy;
float x2 = inner_radius * cos(a) + dx, y2 = inner_radius * sin(a) + dy;
if (i % 2 == 0) {
indices[in++] = vn + 0;
indices[in++] = vn + 1;
} else {
indices[in++] = vn + 1;
indices[in++] = vn + 0;
}
data[vn++] = { glm::vec2(0.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(x1, y1, 0.0f) };
data[vn++] = { glm::vec2(0.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(x2, y2, 0.0f) };
}
cerr << "vbo ring vn = " << vn << ", in = " << in << endl;
upload(T2F_N3F_V3F, data, vn * sizeof(vbo_data_s));
uploadIndices(indices, in * sizeof(unsigned int));
delete[] data;
delete[] indices;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: ik_struct.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: np $ $Date: 2002-11-29 10:20:03 $
*
* 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 ARY_IDL_IK_STRUCT_HXX
#define ARY_IDL_IK_STRUCT_HXX
// USED SERVICES
// BASE CLASSES
#include <ary/idl/ik_ce.hxx>
// COMPONENTS
// PARAMETERS
namespace ary
{
namespace idl
{
namespace ifc_struct
{
using ifc_ce::Dyn_CeIterator;
using ifc_ce::DocText;
struct attr: public ifc_ce::attr
{
static Type_id Base(
const CodeEntity & i_ce );
static void Get_Elements(
Dyn_CeIterator & o_result,
const CodeEntity & i_ce );
};
struct xref : public ifc_ce::xref
{
static void Get_Derivations(
Dyn_CeIterator & o_result,
const CodeEntity & i_ce );
static void Get_SynonymTypedefs(
Dyn_CeIterator & o_result,
const CodeEntity & i_ce );
static void Get_AsReturns(
Dyn_CeIterator & o_result,
const CodeEntity & i_ce );
static void Get_AsParameters(
Dyn_CeIterator & o_result,
const CodeEntity & i_ce );
static void Get_AsDataTypes(
Dyn_CeIterator & o_result,
const CodeEntity & i_ce );
};
struct doc : public ifc_ce::doc
{
};
} // namespace ifc_struct
} // namespace idl
} // namespace ary
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.132); FILE MERGED 2005/09/05 13:09:28 rt 1.2.132.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ik_struct.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-07 16:18:08 $
*
* 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 ARY_IDL_IK_STRUCT_HXX
#define ARY_IDL_IK_STRUCT_HXX
// USED SERVICES
// BASE CLASSES
#include <ary/idl/ik_ce.hxx>
// COMPONENTS
// PARAMETERS
namespace ary
{
namespace idl
{
namespace ifc_struct
{
using ifc_ce::Dyn_CeIterator;
using ifc_ce::DocText;
struct attr: public ifc_ce::attr
{
static Type_id Base(
const CodeEntity & i_ce );
static void Get_Elements(
Dyn_CeIterator & o_result,
const CodeEntity & i_ce );
};
struct xref : public ifc_ce::xref
{
static void Get_Derivations(
Dyn_CeIterator & o_result,
const CodeEntity & i_ce );
static void Get_SynonymTypedefs(
Dyn_CeIterator & o_result,
const CodeEntity & i_ce );
static void Get_AsReturns(
Dyn_CeIterator & o_result,
const CodeEntity & i_ce );
static void Get_AsParameters(
Dyn_CeIterator & o_result,
const CodeEntity & i_ce );
static void Get_AsDataTypes(
Dyn_CeIterator & o_result,
const CodeEntity & i_ce );
};
struct doc : public ifc_ce::doc
{
};
} // namespace ifc_struct
} // namespace idl
} // namespace ary
#endif
<|endoftext|> |
<commit_before>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 "zorbaerrors/Assert.h"
#include "zorbaerrors/error_messages.h"
#include "zorbatypes/zorbatypesError.h"
#include "zorbatypes/URI.h"
#include "zorbatypes/numconversions.h"
#include "runtime/context/ContextImpl.h"
#include "runtime/api/runtimecb.h"
#include "store/api/item_factory.h"
#include "store/api/store.h"
#include "store/api/collection.h"
#include "api/collectionimpl.h"
#include "system/globalenv.h"
#include "context/static_context.h"
#include "CollectionsImpl.h"
namespace zorba {
bool
ZorbaCollectionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
ZORBA_ERROR_LOC_DESC (FOER0000, loc, "ZorbaCollectionIterator not implemented");
STACK_END (state);
}
void
ZorbaListCollectionsState::init(PlanState& planState)
{
PlanIteratorState::init(planState);
uriItState = NULL;
}
void
ZorbaListCollectionsState::reset(PlanState& planState)
{
PlanIteratorState::reset(planState);
uriItState = NULL;
}
bool
ZorbaListCollectionsIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
ZorbaListCollectionsState * state;
store::Iterator_t uriItState;
store::Item_t uriItem;
DEFAULT_STACK_INIT(ZorbaListCollectionsState, state, planState);
for ((state->uriItState = GENV_STORE.listCollectionsUri())->open ();
state->uriItState->next(uriItem); )
{
result = uriItem;
STACK_PUSH( true, state);
}
STACK_END (state);
}
bool
ZorbaCreateCollectionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Item_t itemUri, itemNode;
xqpStringStore_t strURI, strResult, strBaseURI;
// URI::error_t err;
store::Collection_t theColl;
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
if (consumeNext(itemUri, theChildren[0].getp(), planState))
strURI = itemUri->getStringValue();
/*
//if it is not a valix xs:anyURI
if(!URI::is_valid(strURI, true) && !URI::is_valid(strURI, false))
ZORBA_ERROR_LOC_DESC (FORG0002, loc, "Invalid uri given to fn:CreateCollection");
//if this is a relative URI resolve it against the baseuri() property of the static context
else if(URI::is_valid(strURI, false))
{
strBaseURI = planState.theRuntimeCB->theStaticContext->baseuri().getStore();
err = URI::resolve_relative (strBaseURI, strURI, strResult);
switch (err)
{
case URI::INVALID_URI:
ZORBA_ERROR_LOC_DESC (FORG0002, loc, "Invalid uri given to fn:CreateCollection");
break;
case URI::RESOLUTION_ERROR:
ZORBA_ERROR_LOC_DESC (FORG0009, loc, "Error in resolving a relative URI against a base URI in fn:resolve-uri.");
break;
case URI::MAX_ERROR_CODE:
break;
}
theColl = GENV_STORE.createCollection(strResult);
}
else
*/
theColl = GENV_STORE.createCollection(strURI);
if(theChildren.size() == 2)
//add the nodes to the newly created collection
while (consumeNext(itemNode, theChildren[1].getp(), planState))
((CollectionImpl*)theColl.getp())->addNode(itemNode.getp());
STACK_END (state);
}
bool
ZorbaDeleteCollectionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
PlanIteratorState *state;
store::Item_t itemUri;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
if (consumeNext(itemUri, theChildren[0].getp(), planState ))
GENV_STORE.deleteCollection(itemUri->getStringValue());
STACK_END (state);
}
bool
ZorbaDeleteAllCollectionsIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
GENV_STORE.deleteAllCollections();
STACK_END (state);
}
bool
ZorbaInsertNodeFirstIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Collection_t theColl;
store::Item_t itemUri, itemNode;
xqpStringStore_t strURI;
int pos = 0;
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
if (consumeNext(itemUri, theChildren[0].getp(), planState))
strURI = itemUri->getStringValue();
theColl = GENV_STORE.getCollection(strURI);
//add the nodes to the newly created collection
while (consumeNext(itemNode, theChildren[1].getp(), planState))
((CollectionImpl*)theColl.getp())->addNode(itemNode.getp(), pos++);
STACK_END (state);
}
bool
ZorbaInsertNodeLastIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Collection_t theColl;
store::Item_t itemUri, itemNode;
xqpStringStore_t strURI;
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
if (consumeNext(itemUri, theChildren[0].getp(), planState))
strURI = itemUri->getStringValue();
theColl = GENV_STORE.getCollection(strURI);
//add the nodes to the newly created collection
while (consumeNext(itemNode, theChildren[1].getp(), planState))
((CollectionImpl*)theColl.getp())->addNode(itemNode.getp(), -1);
STACK_END (state);
}
bool
ZorbaInsertNodeBeforeIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Collection_t theColl;
xqpStringStore_t strURI;
store::Item_t itemUri, itemTarget, itemNewNode;
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
if (consumeNext(itemUri, theChildren[0].getp(), planState))
strURI = itemUri->getStringValue();
theColl = GENV_STORE.getCollection(strURI);
if(consumeNext(itemTarget, theChildren[1].getp(), planState))
{
//add the nodes to the newly created collection
while (consumeNext(itemNewNode, theChildren[2].getp(), planState))
((CollectionImpl*)theColl.getp())->addNode(itemNewNode.getp(), itemTarget.getp(), true);
}
STACK_END (state);
}
bool
ZorbaInsertNodeAfterIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Collection_t theColl;
xqpStringStore_t strURI;
store::Item_t itemUri, itemTarget, itemNewNode;
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
if (consumeNext(itemUri, theChildren[0].getp(), planState))
strURI = itemUri->getStringValue();
theColl = GENV_STORE.getCollection(strURI);
if(consumeNext(itemTarget, theChildren[1].getp(), planState))
{
//add the nodes to the newly created collection
while (consumeNext(itemNewNode, theChildren[2].getp(), planState))
((CollectionImpl*)theColl.getp())->addNode(itemNewNode.getp(), itemTarget.getp(), false);
}
STACK_END (state);
}
bool
ZorbaInsertNodeAtIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Collection_t theColl;
store::Item_t itemUri, itemPos, itemNode;
xqpStringStore_t strURI;
int pos = 0;
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
if (consumeNext(itemUri, theChildren[0].getp(), planState))
strURI = itemUri->getStringValue();
theColl = GENV_STORE.getCollection(strURI);
if(consumeNext(itemPos, theChildren[1].getp(), planState))
{
if(itemPos->getIntegerValue() < Integer::zero())
pos = itemPos->getIntValue();
//add the nodes to the newly created collection
while (consumeNext(itemNode, theChildren[2].getp(), planState))
((CollectionImpl*)theColl.getp())->addNode(itemNode.getp(), pos++);
}
STACK_END (state);
}
bool
ZorbaRemoveNodeIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Collection_t theColl;
xqpStringStore_t strURI;
store::Item_t itemUri, itemTarget;
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
if (consumeNext(itemUri, theChildren[0].getp(), planState))
strURI = itemUri->getStringValue();
theColl = GENV_STORE.getCollection(strURI);
//delete the nodes
while (consumeNext(itemTarget, theChildren[1].getp(), planState))
((CollectionImpl*)theColl.getp())->deleteNode(itemTarget.getp());
STACK_END (state);
}
bool
ZorbaRemoveNodeAtIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Collection_t theColl;
xqpStringStore_t strURI;
store::Item_t itemUri, itemPos;
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
if (consumeNext(itemUri, theChildren[0].getp(), planState))
strURI = itemUri->getStringValue();
theColl = GENV_STORE.getCollection(strURI);
//delete the node
if (consumeNext(itemPos, theChildren[1].getp(), planState))
{
if(itemPos->getIntegerValue() >= Integer::zero())
((CollectionImpl*)theColl.getp())->deleteNode(itemPos->getIntValue());
}
STACK_END (state);
}
bool
ZorbaNodeCountIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Collection_t theColl;
store::Item_t itemUri;
xqpStringStore_t strURI;
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
if (consumeNext(itemUri, theChildren[0].getp(), planState))
strURI = itemUri->getStringValue();
theColl = GENV_STORE.getCollection(strURI);
STACK_PUSH(GENV_ITEMFACTORY->createInteger(
result,
Integer::parseInt(((CollectionImpl*)theColl.getp())->size())), state);
STACK_END (state);
}
bool
ZorbaNodeAtIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Collection_t theColl;
store::Item_t itemUri, itemPos;
xqpStringStore_t strURI;
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
if (consumeNext(itemUri, theChildren[0].getp(), planState))
strURI = itemUri->getStringValue();
theColl = GENV_STORE.getCollection(strURI);
if (consumeNext(itemPos, theChildren[1].getp(), planState))
{
if(itemPos->getIntegerValue() >= Integer::zero())
STACK_PUSH(theColl->nodeAt(itemPos->getIntValue()), state);
}
STACK_END (state);
}
bool
ZorbaExportCollectionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
ZORBA_ERROR_LOC_DESC (FOER0000, loc, "ZorbaExportCollectionIterator not implemented");
STACK_END (state);
}
} /* namespace zorba */
<commit_msg>Fixed some errors in ZorbaNodeAtIterator.<commit_after>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 "zorbaerrors/Assert.h"
#include "zorbaerrors/error_messages.h"
#include "zorbatypes/zorbatypesError.h"
#include "zorbatypes/URI.h"
#include "zorbatypes/numconversions.h"
#include "runtime/context/ContextImpl.h"
#include "runtime/api/runtimecb.h"
#include "store/api/item_factory.h"
#include "store/api/store.h"
#include "store/api/collection.h"
#include "api/collectionimpl.h"
#include "system/globalenv.h"
#include "context/static_context.h"
#include "CollectionsImpl.h"
namespace zorba {
bool
ZorbaCollectionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
ZORBA_ERROR_LOC_DESC (FOER0000, loc, "ZorbaCollectionIterator not implemented");
STACK_END (state);
}
void
ZorbaListCollectionsState::init(PlanState& planState)
{
PlanIteratorState::init(planState);
uriItState = NULL;
}
void
ZorbaListCollectionsState::reset(PlanState& planState)
{
PlanIteratorState::reset(planState);
uriItState = NULL;
}
bool
ZorbaListCollectionsIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
ZorbaListCollectionsState * state;
store::Iterator_t uriItState;
store::Item_t uriItem;
DEFAULT_STACK_INIT(ZorbaListCollectionsState, state, planState);
for ((state->uriItState = GENV_STORE.listCollectionsUri())->open ();
state->uriItState->next(uriItem); )
{
result = uriItem;
STACK_PUSH( true, state);
}
STACK_END (state);
}
bool
ZorbaCreateCollectionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Item_t itemUri, itemNode;
xqpStringStore_t strURI, strResult, strBaseURI;
// URI::error_t err;
store::Collection_t theColl;
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
if (consumeNext(itemUri, theChildren[0].getp(), planState))
strURI = itemUri->getStringValue();
/*
//if it is not a valix xs:anyURI
if(!URI::is_valid(strURI, true) && !URI::is_valid(strURI, false))
ZORBA_ERROR_LOC_DESC (FORG0002, loc, "Invalid uri given to fn:CreateCollection");
//if this is a relative URI resolve it against the baseuri() property of the static context
else if(URI::is_valid(strURI, false))
{
strBaseURI = planState.theRuntimeCB->theStaticContext->baseuri().getStore();
err = URI::resolve_relative (strBaseURI, strURI, strResult);
switch (err)
{
case URI::INVALID_URI:
ZORBA_ERROR_LOC_DESC (FORG0002, loc, "Invalid uri given to fn:CreateCollection");
break;
case URI::RESOLUTION_ERROR:
ZORBA_ERROR_LOC_DESC (FORG0009, loc, "Error in resolving a relative URI against a base URI in fn:resolve-uri.");
break;
case URI::MAX_ERROR_CODE:
break;
}
theColl = GENV_STORE.createCollection(strResult);
}
else
*/
theColl = GENV_STORE.createCollection(strURI);
if(theChildren.size() == 2)
//add the nodes to the newly created collection
while (consumeNext(itemNode, theChildren[1].getp(), planState))
((CollectionImpl*)theColl.getp())->addNode(itemNode.getp());
STACK_END (state);
}
bool
ZorbaDeleteCollectionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
PlanIteratorState *state;
store::Item_t itemUri;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
if (consumeNext(itemUri, theChildren[0].getp(), planState ))
GENV_STORE.deleteCollection(itemUri->getStringValue());
STACK_END (state);
}
bool
ZorbaDeleteAllCollectionsIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
GENV_STORE.deleteAllCollections();
STACK_END (state);
}
bool
ZorbaInsertNodeFirstIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Collection_t theColl;
store::Item_t itemUri, itemNode;
xqpStringStore_t strURI;
int pos = 0;
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
if (consumeNext(itemUri, theChildren[0].getp(), planState))
strURI = itemUri->getStringValue();
theColl = GENV_STORE.getCollection(strURI);
//add the nodes to the newly created collection
while (consumeNext(itemNode, theChildren[1].getp(), planState))
((CollectionImpl*)theColl.getp())->addNode(itemNode.getp(), pos++);
STACK_END (state);
}
bool
ZorbaInsertNodeLastIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Collection_t theColl;
store::Item_t itemUri, itemNode;
xqpStringStore_t strURI;
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
if (consumeNext(itemUri, theChildren[0].getp(), planState))
strURI = itemUri->getStringValue();
theColl = GENV_STORE.getCollection(strURI);
//add the nodes to the newly created collection
while (consumeNext(itemNode, theChildren[1].getp(), planState))
((CollectionImpl*)theColl.getp())->addNode(itemNode.getp(), -1);
STACK_END (state);
}
bool
ZorbaInsertNodeBeforeIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Collection_t theColl;
xqpStringStore_t strURI;
store::Item_t itemUri, itemTarget, itemNewNode;
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
if (consumeNext(itemUri, theChildren[0].getp(), planState))
strURI = itemUri->getStringValue();
theColl = GENV_STORE.getCollection(strURI);
if(consumeNext(itemTarget, theChildren[1].getp(), planState))
{
//add the nodes to the newly created collection
while (consumeNext(itemNewNode, theChildren[2].getp(), planState))
((CollectionImpl*)theColl.getp())->addNode(itemNewNode.getp(), itemTarget.getp(), true);
}
STACK_END (state);
}
bool
ZorbaInsertNodeAfterIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Collection_t theColl;
xqpStringStore_t strURI;
store::Item_t itemUri, itemTarget, itemNewNode;
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
if (consumeNext(itemUri, theChildren[0].getp(), planState))
strURI = itemUri->getStringValue();
theColl = GENV_STORE.getCollection(strURI);
if(consumeNext(itemTarget, theChildren[1].getp(), planState))
{
//add the nodes to the newly created collection
while (consumeNext(itemNewNode, theChildren[2].getp(), planState))
((CollectionImpl*)theColl.getp())->addNode(itemNewNode.getp(), itemTarget.getp(), false);
}
STACK_END (state);
}
bool
ZorbaInsertNodeAtIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Collection_t theColl;
store::Item_t itemUri, itemPos, itemNode;
xqpStringStore_t strURI;
int pos = 0;
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
if (consumeNext(itemUri, theChildren[0].getp(), planState))
strURI = itemUri->getStringValue();
theColl = GENV_STORE.getCollection(strURI);
if(consumeNext(itemPos, theChildren[1].getp(), planState))
{
if(itemPos->getIntegerValue() < Integer::zero())
pos = itemPos->getIntValue();
//add the nodes to the newly created collection
while (consumeNext(itemNode, theChildren[2].getp(), planState))
((CollectionImpl*)theColl.getp())->addNode(itemNode.getp(), pos++);
}
STACK_END (state);
}
bool
ZorbaRemoveNodeIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Collection_t theColl;
xqpStringStore_t strURI;
store::Item_t itemUri, itemTarget;
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
if (consumeNext(itemUri, theChildren[0].getp(), planState))
strURI = itemUri->getStringValue();
theColl = GENV_STORE.getCollection(strURI);
//delete the nodes
while (consumeNext(itemTarget, theChildren[1].getp(), planState))
((CollectionImpl*)theColl.getp())->deleteNode(itemTarget.getp());
STACK_END (state);
}
bool
ZorbaRemoveNodeAtIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Collection_t theColl;
xqpStringStore_t strURI;
store::Item_t itemUri, itemPos;
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
if (consumeNext(itemUri, theChildren[0].getp(), planState))
strURI = itemUri->getStringValue();
theColl = GENV_STORE.getCollection(strURI);
//delete the node
if (consumeNext(itemPos, theChildren[1].getp(), planState))
{
if(itemPos->getIntegerValue() >= Integer::zero())
((CollectionImpl*)theColl.getp())->deleteNode(itemPos->getIntValue());
}
STACK_END (state);
}
bool
ZorbaNodeCountIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Collection_t theColl;
store::Item_t itemUri;
xqpStringStore_t strURI;
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
if (consumeNext(itemUri, theChildren[0].getp(), planState))
strURI = itemUri->getStringValue();
theColl = GENV_STORE.getCollection(strURI);
STACK_PUSH(GENV_ITEMFACTORY->createInteger(
result,
Integer::parseInt(((CollectionImpl*)theColl.getp())->size())), state);
STACK_END (state);
}
bool
ZorbaNodeAtIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Collection_t theColl;
store::Item_t itemUri, itemPos;
xqpStringStore_t strURI;
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
if (consumeNext(itemUri, theChildren[0].getp(), planState))
strURI = itemUri->getStringValue();
theColl = GENV_STORE.getCollection(strURI);
if (consumeNext(itemPos, theChildren[1].getp(), planState))
{
if(itemPos->getIntegerValue() >= Integer::zero())
{
result = theColl->nodeAt(itemPos->getIntValue());
STACK_PUSH(true, state);
}
}
STACK_END (state);
}
bool
ZorbaExportCollectionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
ZORBA_ERROR_LOC_DESC (FOER0000, loc, "ZorbaExportCollectionIterator not implemented");
STACK_END (state);
}
} /* namespace zorba */
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include "ros/ros.h"
#include "std_msgs/MultiArrayLayout.h"
#include "std_msgs/MultiArrayDimension.h"
#include "std_msgs/Int32MultiArray.h"
int main(int argc, char **argv) {
ros::init(argc, argv, "arrayPublisher");
ros::NodeHandle n;
ros::Publisher pub = n.advertise<std_msgs::Int32MultiArray>("/some_publisher", 100);
while (ros::ok())
{
vector < vector <Int> > V (
std_msgs::Int8MultiArray matrix_ma;
matrix.data.clear();
matrix.data.push_back();
for (int i = 0; i < w*h; i++) {
oneDReversed[i] = twoD[(i / w)][(i%w)];
}
//for loop, pushing data in the size of the array
for (int i = 0; i < 200; i++)
{
for (int j = 0; j < 200; j++) {
//assign array a random number between 0 and 255.
array.data.push_back(rand() % 255);
}
}
//Publish array
pub.publish(array);
//Let the world know
ROS_INFO("TEST: Outer layer has been published");
//Do this.
ros::spinOnce();
//Added a delay so not to spam
sleep(2);
}
}
<commit_msg>Add test publisher template<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include "ros/ros.h"
#include "std_msgs/MultiArrayLayout.h"
#include "std_msgs/MultiArrayDimension.h"
#include "std_msgs/Int8MultiArray.h"
int main(int argc, char **argv) {
ros::init(argc, argv, "arrayPublisher");
ros::NodeHandle n;
ros::Publisher pub = n.advertise<std_msgs::Int8MultiArray>("/some_publisher", 100);
while (ros::ok())
{
// some vectors of vectors here
std::vector < std::vector<int> > matrix;
std_msgs::Int8MultiArray matrix_ma;
matrix_ma.data.clear();
int WIDTH_MATRIX = 200;
int HEIGHT_MATRIX = 200;
// linearise matrix
for (int i = 0; i < WIDTH_MATRIX*HEIGHT_MATRIX; i++) {
matrix_ma.data.push_back(matrix[i / WIDTH_MATRIX][i % WIDTH_MATRIX]);
}
pub.publish(matrix_ma);
ROS_INFO("TEST: Outer layer has been published");
ros::spinOnce();
sleep(1);
}
}
<|endoftext|> |
<commit_before>// csabbg_member-names.t.cpp -*-C++-*-
class A
{
public:
int d_i;
protected:
int d_j;
private:
void private_f();
int private_a;
static int private_b;
char *private_c;
static char *private_d;
int private_a_p;
static int private_b_p;
char *private_c_p;
static char *private_d_p;
int d_private_a;
static int d_private_b;
char *d_private_c;
static char *d_private_d;
int s_private_a;
static int s_private_b;
char *s_private_c;
static char *s_private_d;
int d_private_a_p;
static int d_private_b_p;
char *d_private_c_p;
static char *d_private_d_p;
int s_private_a_p;
static int s_private_b_p;
char *s_private_c_p;
static char *s_private_d_p;
};
struct B
{
int d_i;
static const int k_a = 1;
static const int s_a = 2;
typedef char *c_t;
c_t d_x;
};
// ----------------------------------------------------------------------------
// Copyright (C) 205 Bloomberg Finance L.P.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// ----------------------------- END-OF-FILE ----------------------------------
<commit_msg>Add another typedef name test.<commit_after>// csabbg_member-names.t.cpp -*-C++-*-
class A
{
public:
int d_i;
protected:
int d_j;
private:
void private_f();
int private_a;
static int private_b;
char *private_c;
static char *private_d;
int private_a_p;
static int private_b_p;
char *private_c_p;
static char *private_d_p;
int d_private_a;
static int d_private_b;
char *d_private_c;
static char *d_private_d;
int s_private_a;
static int s_private_b;
char *s_private_c;
static char *s_private_d;
int d_private_a_p;
static int d_private_b_p;
char *d_private_c_p;
static char *d_private_d_p;
int s_private_a_p;
static int s_private_b_p;
char *s_private_c_p;
static char *s_private_d_p;
};
struct B
{
int d_i;
static const int k_a = 1;
static const int s_a = 2;
typedef char *c_t;
c_t d_x;
typedef int i_t;
i_t d_p;
};
// ----------------------------------------------------------------------------
// Copyright (C) 205 Bloomberg Finance L.P.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// ----------------------------- END-OF-FILE ----------------------------------
<|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/basictypes.h"
#include "base/string16.h"
#include "chrome/browser/autofill/autofill_common_unittest.h"
#include "chrome/browser/autofill/autofill_profile.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
// Tests different possibilities for summary string generation.
// Based on existence of first name, last name, and address line 1.
TEST(AutoFillProfileTest, PreviewSummaryString) {
// Case 0/null: ""
AutoFillProfile profile0(string16(), 0);
string16 summary0 = profile0.PreviewSummary();
EXPECT_EQ(summary0, string16());
// Case 0/empty: ""
AutoFillProfile profile00(string16(), 0);
autofill_unittest::SetProfileInfo(
&profile00,
"Billing",
"",
"Mitchell",
"",
"[email protected]",
"Fox",
"",
"unit 5",
"Hollywood", "CA",
"91601",
"US",
"12345678910",
"01987654321");
string16 summary00 = profile00.PreviewSummary();
EXPECT_EQ(summary00, string16());
// Case 1: "<address>"
AutoFillProfile profile1(string16(), 0);
autofill_unittest::SetProfileInfo(
&profile1,
"Billing",
"",
"Mitchell",
"",
"[email protected]",
"Fox",
"123 Zoo St.",
"unit 5",
"Hollywood", "CA",
"91601",
"US",
"12345678910",
"01987654321");
string16 summary1 = profile1.PreviewSummary();
EXPECT_EQ(summary1, string16(ASCIIToUTF16("123 Zoo St.")));
// Case 2: "<lastname>"
AutoFillProfile profile2(string16(), 0);
autofill_unittest::SetProfileInfo(
&profile2,
"Billing",
"",
"Mitchell",
"Morrison",
"[email protected]",
"Fox",
"",
"unit 5",
"Hollywood", "CA",
"91601",
"US",
"12345678910",
"01987654321");
string16 summary2 = profile2.PreviewSummary();
EXPECT_EQ(summary2, string16(ASCIIToUTF16("Morrison")));
// Case 3: "<lastname>, <address>"
AutoFillProfile profile3(string16(), 0);
autofill_unittest::SetProfileInfo(
&profile3,
"Billing",
"",
"Mitchell",
"Morrison",
"[email protected]",
"Fox",
"123 Zoo St.",
"unit 5",
"Hollywood", "CA",
"91601",
"US",
"12345678910",
"01987654321");
string16 summary3 = profile3.PreviewSummary();
EXPECT_EQ(summary3, string16(ASCIIToUTF16("Morrison, 123 Zoo St.")));
// Case 4: "<firstname>"
AutoFillProfile profile4(string16(), 0);
autofill_unittest::SetProfileInfo(
&profile4,
"Billing",
"Marion",
"Mitchell",
"",
"[email protected]",
"Fox",
"",
"unit 5",
"Hollywood", "CA",
"91601",
"US",
"12345678910",
"01987654321");
string16 summary4 = profile4.PreviewSummary();
EXPECT_EQ(summary4, string16(ASCIIToUTF16("Marion")));
// Case 5: "<firstname>, <address>"
AutoFillProfile profile5(string16(), 0);
autofill_unittest::SetProfileInfo(
&profile5,
"Billing",
"Marion",
"Mitchell",
"",
"[email protected]",
"Fox",
"123 Zoo St.",
"unit 5",
"Hollywood", "CA",
"91601",
"US",
"12345678910",
"01987654321");
string16 summary5 = profile5.PreviewSummary();
EXPECT_EQ(summary5, string16(ASCIIToUTF16("Marion, 123 Zoo St.")));
// Case 6: "<firstname> <lastname>"
AutoFillProfile profile6(string16(), 0);
autofill_unittest::SetProfileInfo(
&profile6,
"Billing",
"Marion",
"Mitchell",
"Morrison",
"[email protected]",
"Fox",
"",
"unit 5",
"Hollywood", "CA",
"91601",
"US",
"12345678910",
"01987654321");
string16 summary6 = profile6.PreviewSummary();
EXPECT_EQ(summary6, string16(ASCIIToUTF16("Marion Morrison")));
// Case 7: "<firstname> <lastname>, <address>"
AutoFillProfile profile7(string16(), 0);
autofill_unittest::SetProfileInfo(
&profile7,
"Billing",
"Marion",
"Mitchell",
"Morrison",
"[email protected]",
"Fox",
"123 Zoo St.",
"unit 5",
"Hollywood", "CA",
"91601",
"US",
"12345678910",
"01987654321");
string16 summary7 = profile7.PreviewSummary();
EXPECT_EQ(summary7, string16(ASCIIToUTF16("Marion Morrison, 123 Zoo St.")));
}
} // namespace
<commit_msg>AutoFill unit test cleanup for AutoFillProfileTest.<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/basictypes.h"
#include "base/string16.h"
#include "chrome/browser/autofill/autofill_common_unittest.h"
#include "chrome/browser/autofill/autofill_profile.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
// Tests different possibilities for summary string generation.
// Based on existence of first name, last name, and address line 1.
TEST(AutoFillProfileTest, PreviewSummaryString) {
// Case 0/null: ""
AutoFillProfile profile0(string16(), 0);
string16 summary0 = profile0.PreviewSummary();
EXPECT_EQ(string16(), summary0);
// Case 0/empty: ""
AutoFillProfile profile00(string16(), 0);
autofill_unittest::SetProfileInfo(
&profile00,
"Billing",
"",
"Mitchell",
"",
"[email protected]",
"Fox",
"",
"unit 5",
"Hollywood", "CA",
"91601",
"US",
"12345678910",
"01987654321");
string16 summary00 = profile00.PreviewSummary();
EXPECT_EQ(string16(), summary00);
// Case 1: "<address>"
AutoFillProfile profile1(string16(), 0);
autofill_unittest::SetProfileInfo(
&profile1,
"Billing",
"",
"Mitchell",
"",
"[email protected]",
"Fox",
"123 Zoo St.",
"unit 5",
"Hollywood", "CA",
"91601",
"US",
"12345678910",
"01987654321");
string16 summary1 = profile1.PreviewSummary();
EXPECT_EQ(string16(ASCIIToUTF16("123 Zoo St.")), summary1);
// Case 2: "<lastname>"
AutoFillProfile profile2(string16(), 0);
autofill_unittest::SetProfileInfo(
&profile2,
"Billing",
"",
"Mitchell",
"Morrison",
"[email protected]",
"Fox",
"",
"unit 5",
"Hollywood", "CA",
"91601",
"US",
"12345678910",
"01987654321");
string16 summary2 = profile2.PreviewSummary();
EXPECT_EQ(string16(ASCIIToUTF16("Morrison")), summary2);
// Case 3: "<lastname>, <address>"
AutoFillProfile profile3(string16(), 0);
autofill_unittest::SetProfileInfo(
&profile3,
"Billing",
"",
"Mitchell",
"Morrison",
"[email protected]",
"Fox",
"123 Zoo St.",
"unit 5",
"Hollywood", "CA",
"91601",
"US",
"12345678910",
"01987654321");
string16 summary3 = profile3.PreviewSummary();
EXPECT_EQ(string16(ASCIIToUTF16("Morrison, 123 Zoo St.")), summary3);
// Case 4: "<firstname>"
AutoFillProfile profile4(string16(), 0);
autofill_unittest::SetProfileInfo(
&profile4,
"Billing",
"Marion",
"Mitchell",
"",
"[email protected]",
"Fox",
"",
"unit 5",
"Hollywood", "CA",
"91601",
"US",
"12345678910",
"01987654321");
string16 summary4 = profile4.PreviewSummary();
EXPECT_EQ(string16(ASCIIToUTF16("Marion")), summary4);
// Case 5: "<firstname>, <address>"
AutoFillProfile profile5(string16(), 0);
autofill_unittest::SetProfileInfo(
&profile5,
"Billing",
"Marion",
"Mitchell",
"",
"[email protected]",
"Fox",
"123 Zoo St.",
"unit 5",
"Hollywood", "CA",
"91601",
"US",
"12345678910",
"01987654321");
string16 summary5 = profile5.PreviewSummary();
EXPECT_EQ(string16(ASCIIToUTF16("Marion, 123 Zoo St.")), summary5);
// Case 6: "<firstname> <lastname>"
AutoFillProfile profile6(string16(), 0);
autofill_unittest::SetProfileInfo(
&profile6,
"Billing",
"Marion",
"Mitchell",
"Morrison",
"[email protected]",
"Fox",
"",
"unit 5",
"Hollywood", "CA",
"91601",
"US",
"12345678910",
"01987654321");
string16 summary6 = profile6.PreviewSummary();
EXPECT_EQ(string16(ASCIIToUTF16("Marion Morrison")), summary6);
// Case 7: "<firstname> <lastname>, <address>"
AutoFillProfile profile7(string16(), 0);
autofill_unittest::SetProfileInfo(
&profile7,
"Billing",
"Marion",
"Mitchell",
"Morrison",
"[email protected]",
"Fox",
"123 Zoo St.",
"unit 5",
"Hollywood", "CA",
"91601",
"US",
"12345678910",
"01987654321");
string16 summary7 = profile7.PreviewSummary();
EXPECT_EQ(string16(ASCIIToUTF16("Marion Morrison, 123 Zoo St.")), summary7);
}
} // namespace
<|endoftext|> |
<commit_before>// Copyright (c) 2006-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/browser/automation/automation_profile_impl.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/net/chrome_url_request_context.h"
#include "chrome/test/automation/automation_messages.h"
namespace {
// A special Request context for automation. Substitute a few things
// like cookie store, proxy settings etc to handle them differently
// for automation.
class AutomationURLRequestContext : public ChromeURLRequestContext {
public:
AutomationURLRequestContext(ChromeURLRequestContext* original_context,
net::CookieStore* automation_cookie_store)
: ChromeURLRequestContext(original_context),
// We must hold a reference to |original_context|, since many
// of the dependencies that ChromeURLRequestContext(original_context)
// copied are scoped to |original_context|.
original_context_(original_context) {
cookie_store_ = automation_cookie_store;
}
private:
virtual ~AutomationURLRequestContext() {
// Clear out members before calling base class dtor since we don't
// own any of them.
// Clear URLRequestContext members.
host_resolver_ = NULL;
proxy_service_ = NULL;
http_transaction_factory_ = NULL;
ftp_transaction_factory_ = NULL;
cookie_store_ = NULL;
strict_transport_security_state_ = NULL;
// Clear ChromeURLRequestContext members.
blacklist_ = NULL;
}
scoped_refptr<ChromeURLRequestContext> original_context_;
DISALLOW_COPY_AND_ASSIGN(AutomationURLRequestContext);
};
// CookieStore specialization to have automation specific
// behavior for cookies.
class AutomationCookieStore : public net::CookieStore {
public:
AutomationCookieStore(AutomationProfileImpl* profile,
net::CookieStore* original_cookie_store,
IPC::Message::Sender* automation_client)
: profile_(profile),
original_cookie_store_(original_cookie_store),
automation_client_(automation_client) {
}
// CookieStore implementation.
virtual bool SetCookie(const GURL& url, const std::string& cookie_line) {
bool cookie_set = original_cookie_store_->SetCookie(url, cookie_line);
if (cookie_set) {
// TODO(eroman): Should NOT be accessing the profile from here, as this
// is running on the IO thread.
automation_client_->Send(new AutomationMsg_SetCookieAsync(0,
profile_->tab_handle(), url, cookie_line));
}
return cookie_set;
}
virtual bool SetCookieWithOptions(const GURL& url,
const std::string& cookie_line,
const net::CookieOptions& options) {
return original_cookie_store_->SetCookieWithOptions(url, cookie_line,
options);
}
virtual bool SetCookieWithCreationTime(const GURL& url,
const std::string& cookie_line,
const base::Time& creation_time) {
return original_cookie_store_->SetCookieWithCreationTime(url, cookie_line,
creation_time);
}
virtual bool SetCookieWithCreationTimeWithOptions(
const GURL& url,
const std::string& cookie_line,
const base::Time& creation_time,
const net::CookieOptions& options) {
return original_cookie_store_->SetCookieWithCreationTimeWithOptions(url,
cookie_line, creation_time, options);
}
virtual void SetCookies(const GURL& url,
const std::vector<std::string>& cookies) {
original_cookie_store_->SetCookies(url, cookies);
}
virtual void SetCookiesWithOptions(const GURL& url,
const std::vector<std::string>& cookies,
const net::CookieOptions& options) {
original_cookie_store_->SetCookiesWithOptions(url, cookies, options);
}
virtual std::string GetCookies(const GURL& url) {
return original_cookie_store_->GetCookies(url);
}
virtual std::string GetCookiesWithOptions(const GURL& url,
const net::CookieOptions& options) {
return original_cookie_store_->GetCookiesWithOptions(url, options);
}
protected:
AutomationProfileImpl* profile_;
net::CookieStore* original_cookie_store_;
IPC::Message::Sender* automation_client_;
private:
DISALLOW_COPY_AND_ASSIGN(AutomationCookieStore);
};
class Factory : public ChromeURLRequestContextFactory {
public:
Factory(ChromeURLRequestContextGetter* original_context_getter,
AutomationProfileImpl* profile,
IPC::Message::Sender* automation_client)
: ChromeURLRequestContextFactory(profile),
original_context_getter_(original_context_getter),
profile_(profile),
automation_client_(automation_client) {
}
virtual ChromeURLRequestContext* Create() {
ChromeURLRequestContext* original_context =
original_context_getter_->GetIOContext();
// Create an automation cookie store.
scoped_refptr<net::CookieStore> automation_cookie_store =
new AutomationCookieStore(profile_,
original_context->cookie_store(),
automation_client_);
return new AutomationURLRequestContext(original_context,
automation_cookie_store);
}
private:
scoped_refptr<ChromeURLRequestContextGetter> original_context_getter_;
AutomationProfileImpl* profile_;
IPC::Message::Sender* automation_client_;
};
// TODO(eroman): This duplicates CleanupRequestContext() from profile.cc.
void CleanupRequestContext(ChromeURLRequestContextGetter* context) {
context->CleanupOnUIThread();
// Clean up request context on IO thread.
ChromeThread::ReleaseSoon(ChromeThread::IO, FROM_HERE, context);
}
} // namespace
AutomationProfileImpl::~AutomationProfileImpl() {
CleanupRequestContext(alternate_request_context_);
}
void AutomationProfileImpl::Initialize(Profile* original_profile,
IPC::Message::Sender* automation_client) {
DCHECK(original_profile);
original_profile_ = original_profile;
ChromeURLRequestContextGetter* original_context =
static_cast<ChromeURLRequestContextGetter*>(
original_profile_->GetRequestContext());
alternate_request_context_ = new ChromeURLRequestContextGetter(
NULL, // Don't register an observer on PrefService.
new Factory(original_context, this, automation_client));
alternate_request_context_->AddRef(); // Balananced in the destructor.
}
<commit_msg>Ensure AutomationMsg_SetCookieAsync is sent on IO thread. If SetCookie is invoked via automation and load_requests_via_automation is true, the IPC will be sent back from the UI thread. BUG=27568<commit_after>// Copyright (c) 2006-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/browser/automation/automation_profile_impl.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/net/chrome_url_request_context.h"
#include "chrome/test/automation/automation_messages.h"
namespace {
// A special Request context for automation. Substitute a few things
// like cookie store, proxy settings etc to handle them differently
// for automation.
class AutomationURLRequestContext : public ChromeURLRequestContext {
public:
AutomationURLRequestContext(ChromeURLRequestContext* original_context,
net::CookieStore* automation_cookie_store)
: ChromeURLRequestContext(original_context),
// We must hold a reference to |original_context|, since many
// of the dependencies that ChromeURLRequestContext(original_context)
// copied are scoped to |original_context|.
original_context_(original_context) {
cookie_store_ = automation_cookie_store;
}
private:
virtual ~AutomationURLRequestContext() {
// Clear out members before calling base class dtor since we don't
// own any of them.
// Clear URLRequestContext members.
host_resolver_ = NULL;
proxy_service_ = NULL;
http_transaction_factory_ = NULL;
ftp_transaction_factory_ = NULL;
cookie_store_ = NULL;
strict_transport_security_state_ = NULL;
// Clear ChromeURLRequestContext members.
blacklist_ = NULL;
}
scoped_refptr<ChromeURLRequestContext> original_context_;
DISALLOW_COPY_AND_ASSIGN(AutomationURLRequestContext);
};
// CookieStore specialization to have automation specific
// behavior for cookies.
class AutomationCookieStore : public net::CookieStore {
public:
AutomationCookieStore(AutomationProfileImpl* profile,
net::CookieStore* original_cookie_store,
IPC::Message::Sender* automation_client)
: profile_(profile),
original_cookie_store_(original_cookie_store),
automation_client_(automation_client) {
}
// CookieStore implementation.
virtual bool SetCookie(const GURL& url, const std::string& cookie_line) {
bool cookie_set = original_cookie_store_->SetCookie(url, cookie_line);
if (cookie_set) {
// TODO(eroman): Should NOT be accessing the profile from here, as this
// is running on the IO thread.
SendIPCMessageOnIOThread(new AutomationMsg_SetCookieAsync(0,
profile_->tab_handle(), url, cookie_line));
}
return cookie_set;
}
virtual bool SetCookieWithOptions(const GURL& url,
const std::string& cookie_line,
const net::CookieOptions& options) {
return original_cookie_store_->SetCookieWithOptions(url, cookie_line,
options);
}
virtual bool SetCookieWithCreationTime(const GURL& url,
const std::string& cookie_line,
const base::Time& creation_time) {
return original_cookie_store_->SetCookieWithCreationTime(url, cookie_line,
creation_time);
}
virtual bool SetCookieWithCreationTimeWithOptions(
const GURL& url,
const std::string& cookie_line,
const base::Time& creation_time,
const net::CookieOptions& options) {
return original_cookie_store_->SetCookieWithCreationTimeWithOptions(url,
cookie_line, creation_time, options);
}
virtual void SetCookies(const GURL& url,
const std::vector<std::string>& cookies) {
original_cookie_store_->SetCookies(url, cookies);
}
virtual void SetCookiesWithOptions(const GURL& url,
const std::vector<std::string>& cookies,
const net::CookieOptions& options) {
original_cookie_store_->SetCookiesWithOptions(url, cookies, options);
}
virtual std::string GetCookies(const GURL& url) {
return original_cookie_store_->GetCookies(url);
}
virtual std::string GetCookiesWithOptions(const GURL& url,
const net::CookieOptions& options) {
return original_cookie_store_->GetCookiesWithOptions(url, options);
}
protected:
void SendIPCMessageOnIOThread(IPC::Message* m) {
if (ChromeThread::CurrentlyOn(ChromeThread::IO)) {
automation_client_->Send(m);
} else {
Task* task = NewRunnableMethod(this,
&AutomationCookieStore::SendIPCMessageOnIOThread, m);
ChromeThread::PostTask(ChromeThread::IO, FROM_HERE, task);
}
}
AutomationProfileImpl* profile_;
net::CookieStore* original_cookie_store_;
IPC::Message::Sender* automation_client_;
private:
DISALLOW_COPY_AND_ASSIGN(AutomationCookieStore);
};
class Factory : public ChromeURLRequestContextFactory {
public:
Factory(ChromeURLRequestContextGetter* original_context_getter,
AutomationProfileImpl* profile,
IPC::Message::Sender* automation_client)
: ChromeURLRequestContextFactory(profile),
original_context_getter_(original_context_getter),
profile_(profile),
automation_client_(automation_client) {
}
virtual ChromeURLRequestContext* Create() {
ChromeURLRequestContext* original_context =
original_context_getter_->GetIOContext();
// Create an automation cookie store.
scoped_refptr<net::CookieStore> automation_cookie_store =
new AutomationCookieStore(profile_,
original_context->cookie_store(),
automation_client_);
return new AutomationURLRequestContext(original_context,
automation_cookie_store);
}
private:
scoped_refptr<ChromeURLRequestContextGetter> original_context_getter_;
AutomationProfileImpl* profile_;
IPC::Message::Sender* automation_client_;
};
// TODO(eroman): This duplicates CleanupRequestContext() from profile.cc.
void CleanupRequestContext(ChromeURLRequestContextGetter* context) {
context->CleanupOnUIThread();
// Clean up request context on IO thread.
ChromeThread::ReleaseSoon(ChromeThread::IO, FROM_HERE, context);
}
} // namespace
AutomationProfileImpl::~AutomationProfileImpl() {
CleanupRequestContext(alternate_request_context_);
}
void AutomationProfileImpl::Initialize(Profile* original_profile,
IPC::Message::Sender* automation_client) {
DCHECK(original_profile);
original_profile_ = original_profile;
ChromeURLRequestContextGetter* original_context =
static_cast<ChromeURLRequestContextGetter*>(
original_profile_->GetRequestContext());
alternate_request_context_ = new ChromeURLRequestContextGetter(
NULL, // Don't register an observer on PrefService.
new Factory(original_context, this, automation_client));
alternate_request_context_->AddRef(); // Balananced in the destructor.
}
<|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/browser/views/options/exceptions_page_view.h"
#include "app/l10n_util.h"
#include "base/string_util.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#include "grit/generated_resources.h"
#include "views/background.h"
#include "views/controls/button/native_button.h"
#include "views/grid_layout.h"
#include "views/standard_layout.h"
using views::ColumnSet;
using views::GridLayout;
using webkit_glue::PasswordForm;
///////////////////////////////////////////////////////////////////////////////
// ExceptionsTableModel
ExceptionsTableModel::ExceptionsTableModel(Profile* profile)
: PasswordsTableModel(profile) {
}
ExceptionsTableModel::~ExceptionsTableModel() {
}
std::wstring ExceptionsTableModel::GetText(int row, int col_id) {
DCHECK_EQ(col_id, IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN);
return PasswordsTableModel::GetText(row, col_id);
}
int ExceptionsTableModel::CompareValues(int row1, int row2,
int col_id) {
DCHECK_EQ(col_id, IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN);
return PasswordsTableModel::CompareValues(row1, row2, col_id);
}
void ExceptionsTableModel::GetAllExceptionsForProfile() {
DCHECK(!pending_login_query_);
pending_login_query_ = password_store()->GetBlacklistLogins(this);
}
void ExceptionsTableModel::OnPasswordStoreRequestDone(
int handle, const std::vector<webkit_glue::PasswordForm*>& result) {
DCHECK_EQ(pending_login_query_, handle);
pending_login_query_ = NULL;
STLDeleteElements<PasswordRows>(&saved_signons_);
std::wstring languages =
profile_->GetPrefs()->GetString(prefs::kAcceptLanguages);
for (size_t i = 0; i < result.size(); ++i) {
saved_signons_.push_back(new PasswordRow(
gfx::SortedDisplayURL(result[i]->origin, languages), result[i]));
}
if (observer_)
observer_->OnModelChanged();
if (row_count_observer_)
row_count_observer_->OnRowCountChanged(RowCount());
}
///////////////////////////////////////////////////////////////////////////////
// ExceptionsPageView, public
ExceptionsPageView::ExceptionsPageView(Profile* profile)
: OptionsPageView(profile),
ALLOW_THIS_IN_INITIALIZER_LIST(show_button_(
this,
l10n_util::GetString(IDS_PASSWORDS_PAGE_VIEW_SHOW_BUTTON),
l10n_util::GetString(IDS_PASSWORDS_PAGE_VIEW_HIDE_BUTTON))),
ALLOW_THIS_IN_INITIALIZER_LIST(remove_button_(
this,
l10n_util::GetString(IDS_EXCEPTIONS_PAGE_VIEW_REMOVE_BUTTON))),
ALLOW_THIS_IN_INITIALIZER_LIST(remove_all_button_(
this,
l10n_util::GetString(IDS_EXCEPTIONS_PAGE_VIEW_REMOVE_ALL_BUTTON))),
table_model_(profile),
table_view_(NULL) {
}
void ExceptionsPageView::OnSelectionChanged() {
bool has_selection = table_view_->SelectedRowCount() > 0;
remove_button_.SetEnabled(has_selection);
}
void ExceptionsPageView::ButtonPressed(
views::Button* sender, const views::Event& event) {
// Close will result in our destruction.
if (sender == &remove_all_button_) {
table_model_.ForgetAndRemoveAllSignons();
return;
}
// The following require a selection (and only one, since table is single-
// select only).
views::TableSelectionIterator iter = table_view_->SelectionBegin();
int row = *iter;
PasswordForm* selected = table_model_.GetPasswordFormAt(row);
DCHECK(++iter == table_view_->SelectionEnd());
if (sender == &remove_button_) {
table_model_.ForgetAndRemoveSignon(row);
} else {
NOTREACHED() << "Invalid button.";
}
}
void ExceptionsPageView::OnRowCountChanged(size_t rows) {
remove_all_button_.SetEnabled(rows > 0);
}
///////////////////////////////////////////////////////////////////////////////
// ExceptionsPageView, protected
void ExceptionsPageView::InitControlLayout() {
SetupButtons();
SetupTable();
// Do the layout thing.
GridLayout* layout = CreatePanelGridLayout(this);
SetLayoutManager(layout);
const int top_column_set_id = 0;
// Design the grid.
ColumnSet* column_set = layout->AddColumnSet(top_column_set_id);
column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing);
column_set->AddColumn(GridLayout::FILL, GridLayout::CENTER, 0,
GridLayout::USE_PREF, 0, 0);
// Fill the grid.
layout->StartRow(0, top_column_set_id);
layout->AddView(table_view_, 1, 6, GridLayout::FILL,
GridLayout::FILL);
layout->AddView(&remove_button_);
layout->StartRowWithPadding(0, top_column_set_id, 0,
kRelatedControlVerticalSpacing);
layout->SkipColumns(1);
layout->AddView(&remove_all_button_);
layout->StartRowWithPadding(0, top_column_set_id, 0,
kRelatedControlVerticalSpacing);
layout->SkipColumns(1);
layout->AddView(&show_button_);
layout->AddPaddingRow(1, 0);
// Ask the database for exception data.
table_model_.GetAllExceptionsForProfile();
}
///////////////////////////////////////////////////////////////////////////////
// ExceptionsPageView, private
void ExceptionsPageView::SetupButtons() {
// Disable all buttons in the first place.
remove_button_.SetParentOwned(false);
remove_button_.SetEnabled(false);
remove_all_button_.SetParentOwned(false);
remove_all_button_.SetEnabled(false);
show_button_.SetParentOwned(false);
show_button_.SetEnabled(false);
show_button_.SetVisible(false);
}
void ExceptionsPageView::SetupTable() {
// Tell the table model we are concerned about how many rows it has.
table_model_.set_row_count_observer(this);
// Creates the different columns for the table.
// The float resize values are the result of much tinkering.
std::vector<TableColumn> columns;
columns.push_back(TableColumn(IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN,
TableColumn::LEFT, -1, 0.55f));
columns.back().sortable = true;
table_view_ = new views::TableView(&table_model_, columns, views::TEXT_ONLY,
true, true, true);
// Make the table initially sorted by host.
views::TableView::SortDescriptors sort;
sort.push_back(views::TableView::SortDescriptor(
IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN, true));
table_view_->SetSortDescriptors(sort);
table_view_->SetObserver(this);
}
<commit_msg>Coverity: Remove unnecessary GetPasswordFormAt call.<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/browser/views/options/exceptions_page_view.h"
#include "app/l10n_util.h"
#include "base/string_util.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#include "grit/generated_resources.h"
#include "views/background.h"
#include "views/controls/button/native_button.h"
#include "views/grid_layout.h"
#include "views/standard_layout.h"
using views::ColumnSet;
using views::GridLayout;
using webkit_glue::PasswordForm;
///////////////////////////////////////////////////////////////////////////////
// ExceptionsTableModel
ExceptionsTableModel::ExceptionsTableModel(Profile* profile)
: PasswordsTableModel(profile) {
}
ExceptionsTableModel::~ExceptionsTableModel() {
}
std::wstring ExceptionsTableModel::GetText(int row, int col_id) {
DCHECK_EQ(col_id, IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN);
return PasswordsTableModel::GetText(row, col_id);
}
int ExceptionsTableModel::CompareValues(int row1, int row2,
int col_id) {
DCHECK_EQ(col_id, IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN);
return PasswordsTableModel::CompareValues(row1, row2, col_id);
}
void ExceptionsTableModel::GetAllExceptionsForProfile() {
DCHECK(!pending_login_query_);
pending_login_query_ = password_store()->GetBlacklistLogins(this);
}
void ExceptionsTableModel::OnPasswordStoreRequestDone(
int handle, const std::vector<webkit_glue::PasswordForm*>& result) {
DCHECK_EQ(pending_login_query_, handle);
pending_login_query_ = NULL;
STLDeleteElements<PasswordRows>(&saved_signons_);
std::wstring languages =
profile_->GetPrefs()->GetString(prefs::kAcceptLanguages);
for (size_t i = 0; i < result.size(); ++i) {
saved_signons_.push_back(new PasswordRow(
gfx::SortedDisplayURL(result[i]->origin, languages), result[i]));
}
if (observer_)
observer_->OnModelChanged();
if (row_count_observer_)
row_count_observer_->OnRowCountChanged(RowCount());
}
///////////////////////////////////////////////////////////////////////////////
// ExceptionsPageView, public
ExceptionsPageView::ExceptionsPageView(Profile* profile)
: OptionsPageView(profile),
ALLOW_THIS_IN_INITIALIZER_LIST(show_button_(
this,
l10n_util::GetString(IDS_PASSWORDS_PAGE_VIEW_SHOW_BUTTON),
l10n_util::GetString(IDS_PASSWORDS_PAGE_VIEW_HIDE_BUTTON))),
ALLOW_THIS_IN_INITIALIZER_LIST(remove_button_(
this,
l10n_util::GetString(IDS_EXCEPTIONS_PAGE_VIEW_REMOVE_BUTTON))),
ALLOW_THIS_IN_INITIALIZER_LIST(remove_all_button_(
this,
l10n_util::GetString(IDS_EXCEPTIONS_PAGE_VIEW_REMOVE_ALL_BUTTON))),
table_model_(profile),
table_view_(NULL) {
}
void ExceptionsPageView::OnSelectionChanged() {
bool has_selection = table_view_->SelectedRowCount() > 0;
remove_button_.SetEnabled(has_selection);
}
void ExceptionsPageView::ButtonPressed(
views::Button* sender, const views::Event& event) {
// Close will result in our destruction.
if (sender == &remove_all_button_) {
table_model_.ForgetAndRemoveAllSignons();
return;
}
// The following require a selection (and only one, since table is single-
// select only).
views::TableSelectionIterator iter = table_view_->SelectionBegin();
int row = *iter;
DCHECK(++iter == table_view_->SelectionEnd());
if (sender == &remove_button_) {
table_model_.ForgetAndRemoveSignon(row);
} else {
NOTREACHED() << "Invalid button.";
}
}
void ExceptionsPageView::OnRowCountChanged(size_t rows) {
remove_all_button_.SetEnabled(rows > 0);
}
///////////////////////////////////////////////////////////////////////////////
// ExceptionsPageView, protected
void ExceptionsPageView::InitControlLayout() {
SetupButtons();
SetupTable();
// Do the layout thing.
GridLayout* layout = CreatePanelGridLayout(this);
SetLayoutManager(layout);
const int top_column_set_id = 0;
// Design the grid.
ColumnSet* column_set = layout->AddColumnSet(top_column_set_id);
column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing);
column_set->AddColumn(GridLayout::FILL, GridLayout::CENTER, 0,
GridLayout::USE_PREF, 0, 0);
// Fill the grid.
layout->StartRow(0, top_column_set_id);
layout->AddView(table_view_, 1, 6, GridLayout::FILL,
GridLayout::FILL);
layout->AddView(&remove_button_);
layout->StartRowWithPadding(0, top_column_set_id, 0,
kRelatedControlVerticalSpacing);
layout->SkipColumns(1);
layout->AddView(&remove_all_button_);
layout->StartRowWithPadding(0, top_column_set_id, 0,
kRelatedControlVerticalSpacing);
layout->SkipColumns(1);
layout->AddView(&show_button_);
layout->AddPaddingRow(1, 0);
// Ask the database for exception data.
table_model_.GetAllExceptionsForProfile();
}
///////////////////////////////////////////////////////////////////////////////
// ExceptionsPageView, private
void ExceptionsPageView::SetupButtons() {
// Disable all buttons in the first place.
remove_button_.SetParentOwned(false);
remove_button_.SetEnabled(false);
remove_all_button_.SetParentOwned(false);
remove_all_button_.SetEnabled(false);
show_button_.SetParentOwned(false);
show_button_.SetEnabled(false);
show_button_.SetVisible(false);
}
void ExceptionsPageView::SetupTable() {
// Tell the table model we are concerned about how many rows it has.
table_model_.set_row_count_observer(this);
// Creates the different columns for the table.
// The float resize values are the result of much tinkering.
std::vector<TableColumn> columns;
columns.push_back(TableColumn(IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN,
TableColumn::LEFT, -1, 0.55f));
columns.back().sortable = true;
table_view_ = new views::TableView(&table_model_, columns, views::TEXT_ONLY,
true, true, true);
// Make the table initially sorted by host.
views::TableView::SortDescriptors sort;
sort.push_back(views::TableView::SortDescriptor(
IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN, true));
table_view_->SetSortDescriptors(sort);
table_view_->SetObserver(this);
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2016-2018 mvs developers
*
* This file is part of metaverse-explorer.
*
* metaverse-explorer is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <metaverse/explorer/define.hpp>
#include <metaverse/explorer/extensions/command_extension.hpp>
#include <metaverse/explorer/extensions/command_extension_func.hpp>
#include <metaverse/explorer/extensions/command_assistant.hpp>
namespace libbitcoin {
namespace explorer {
namespace commands {
/************************ submitwork *************************/
class submitwork: public command_extension
{
public:
static const char* symbol(){ return "submitwork";}
const char* name() override { return symbol();}
bool category(int bs) override { return (ex_online & bs ) == bs; }
const char* description() override { return "submitwork to submit mining result."; }
arguments_metadata& load_arguments() override
{
return get_argument_metadata()
.add("NOUNCE", 1)
.add("HEADERHASH", 1)
.add("MIXHASH", 1);
}
void load_fallbacks (std::istream& input,
po::variables_map& variables) override
{
const auto raw = requires_raw_input();
load_input(argument_.nounce, "NOUNCE", variables, input, raw);
load_input(argument_.header_hash, "HEADERHASH", variables, input, raw);
load_input(argument_.mix_hash, "MIXHASH", variables, input, raw);
}
options_metadata& load_options() override
{
using namespace po;
options_description& options = get_option_metadata();
options.add_options()
(
BX_HELP_VARIABLE ",h",
value<bool>()->zero_tokens(),
"Get a description and instructions for this command."
)
(
"NOUNCE",
value<std::string>(&argument_.nounce)->required(),
"nounce."
)
(
"HEADERHASH",
value<std::string>(&argument_.header_hash)->required(),
"header hash."
)
(
"MIXHASH",
value<std::string>(&argument_.mix_hash)->required(),
"mix hash."
);
return options;
}
void set_defaults_from_config (po::variables_map& variables) override
{
}
console_result invoke (Json::Value& jv_output,
libbitcoin::server::server_node& node) override;
struct argument
{
std::string nounce;
std::string mix_hash;
std::string header_hash;
} argument_;
struct option
{
} option_;
};
} // namespace commands
} // namespace explorer
} // namespace libbitcoin
<commit_msg>add more description to submitwork parameters<commit_after>/**
* Copyright (c) 2016-2018 mvs developers
*
* This file is part of metaverse-explorer.
*
* metaverse-explorer is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <metaverse/explorer/define.hpp>
#include <metaverse/explorer/extensions/command_extension.hpp>
#include <metaverse/explorer/extensions/command_extension_func.hpp>
#include <metaverse/explorer/extensions/command_assistant.hpp>
namespace libbitcoin {
namespace explorer {
namespace commands {
/************************ submitwork *************************/
class submitwork: public command_extension
{
public:
static const char* symbol(){ return "submitwork";}
const char* name() override { return symbol();}
bool category(int bs) override { return (ex_online & bs ) == bs; }
const char* description() override { return "submitwork to submit mining result."; }
arguments_metadata& load_arguments() override
{
return get_argument_metadata()
.add("NOUNCE", 1)
.add("HEADERHASH", 1)
.add("MIXHASH", 1);
}
void load_fallbacks (std::istream& input,
po::variables_map& variables) override
{
const auto raw = requires_raw_input();
load_input(argument_.nounce, "NOUNCE", variables, input, raw);
load_input(argument_.header_hash, "HEADERHASH", variables, input, raw);
load_input(argument_.mix_hash, "MIXHASH", variables, input, raw);
}
options_metadata& load_options() override
{
using namespace po;
options_description& options = get_option_metadata();
options.add_options()
(
BX_HELP_VARIABLE ",h",
value<bool>()->zero_tokens(),
"Get a description and instructions for this command."
)
(
"NOUNCE",
value<std::string>(&argument_.nounce)->required(),
"nounce. without leading 0x"
)
(
"HEADERHASH",
value<std::string>(&argument_.header_hash)->required(),
"header hash. with leading 0x"
)
(
"MIXHASH",
value<std::string>(&argument_.mix_hash)->required(),
"mix hash. with leading 0x"
);
return options;
}
void set_defaults_from_config (po::variables_map& variables) override
{
}
console_result invoke (Json::Value& jv_output,
libbitcoin::server::server_node& node) override;
struct argument
{
std::string nounce;
std::string mix_hash;
std::string header_hash;
} argument_;
struct option
{
} option_;
};
} // namespace commands
} // namespace explorer
} // namespace libbitcoin
<|endoftext|> |
<commit_before><commit_msg>TDBStore: pad record header to whole program size before storing it<commit_after><|endoftext|> |
<commit_before>/**
* Copyright (C) 2015 Dato, Inc.
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*/
#include <cstdlib>
#include <time.h>
#include <unistd.h>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include <cppipc/cppipc.hpp>
#include <cppipc/common/authentication_token_method.hpp>
#include <minipsutil/minipsutil.h>
#include <logger/logger.hpp>
#include <logger/log_rotate.hpp>
#include <unity/lib/unity_global.hpp>
#include <unity/lib/unity_global_singleton.hpp>
#include <unity/lib/toolkit_class_registry.hpp>
#include <unity/lib/toolkit_function_registry.hpp>
#include <startup_teardown/startup_teardown.hpp>
#include <lambda/lambda_master.hpp>
#include "unity_server.hpp"
namespace graphlab {
unity_server::unity_server(unity_server_options options) : options(options) {
toolkit_functions = new toolkit_function_registry();
toolkit_classes = new toolkit_class_registry();
}
void unity_server::start(const unity_server_initializer& server_initializer) {
// log files
if (!options.log_file.empty()) {
if (options.log_rotation_interval) {
graphlab::begin_log_rotation(options.log_file,
options.log_rotation_interval,
options.log_rotation_truncate);
} else {
global_logger().set_log_file(options.log_file);
}
}
graphlab::configure_global_environment(options.root_path);
graphlab::global_startup::get_instance().perform_startup();
// server address
options.server_address = parse_server_address(options.server_address);
// construct the server
server = new cppipc::comm_server(std::vector<std::string>(), "",
options.server_address,
options.control_address,
options.publish_address,
options.secret_key);
set_log_progress(true);
// initialize built-in data structures, toolkits and models, defined in unity_server_init.cpp
server_initializer.init_toolkits(*toolkit_functions);
server_initializer.init_models(*toolkit_classes);
create_unity_global_singleton(toolkit_functions,
toolkit_classes,
server);
auto unity_global_ptr = get_unity_global_singleton();
server_initializer.register_base_classes(server, unity_global_ptr);
// initialize extension modules and lambda workers
server_initializer.init_extensions(options.root_path, unity_global_ptr);
lambda::set_pylambda_worker_binary_from_environment_variables();
// start the cppipc server
server->start();
logstream(LOG_EMPH) << "Unity server listening on: " << options.server_address << std::endl;
logstream(LOG_EMPH) << "Total System Memory Detected: " << total_mem() << std::endl;
log_thread.launch([=]() {
do {
std::pair<std::string, bool> queueelem = this->log_queue.dequeue();
if (queueelem.second == false) {
break;
} else {
// we need to read it before trying to do the callback
// Otherwise we might accidentally call a null pointer
volatile progress_callback_type cback = this->log_progress_callback;
if (cback != nullptr) cback(queueelem.first);
}
} while(1);
});
}
/**
* Cleanup the server state
*/
void unity_server::stop() {
delete server;
server = nullptr;
set_log_progress(false);
log_queue.stop_blocking();
graphlab::global_teardown::get_instance().perform_teardown();
}
/**
* Parse the server_address and return the parsed address.
*
* \param server_address can begin with different protocols: ipc, tcp or inproc
*/
std::string unity_server::parse_server_address(std::string server_address) {
namespace fs = boost::filesystem;
// Prevent multiple server listen on the same ipc device.
if (boost::starts_with(server_address, "ipc://") &&
fs::exists(fs::path(server_address.substr(6)))) {
logstream(LOG_FATAL) << "Cannot start graphlab server at "
<< server_address<< ". File already exists" << "\n";
exit(-1);
}
// Form default server address using process_id and client's timestamp:
// ipc://graphlab_server-$pid-$timestamp
if (boost::starts_with(server_address, "default")) {
std::string path = "/tmp/graphlab_server-" + std::to_string(getpid());
{ // parse server address: "default-$timestamp"
// append timestamp to the address
std::vector<std::string> _tmp;
boost::split(_tmp, server_address, boost::is_any_of("-"));
if (_tmp.size() == 2)
path += "-" + _tmp[1];
}
server_address = "ipc://" + path;
if (fs::exists(fs::path(path))) {
// It could be a leftover of a previous crashed process, try to delete the file
if (remove(path.c_str()) != 0) {
logstream(LOG_FATAL) << "Cannot start graphlab server at "
<< server_address
<< ". File already exists, and cannot be deleted." << "\n";
exit(-1);
}
}
}
return server_address;
}
EXPORT void unity_server::set_log_progress(bool enable) {
global_logger().add_observer(LOG_PROGRESS, NULL);
if (enable == true) {
// set the progress observer
global_logger().add_observer(
LOG_PROGRESS,
[=](int lineloglevel, const char* buf, size_t len){
std::cout << "PROGRESS: " << std::string(buf, len);
});
}
}
void unity_server::set_log_progress_callback(progress_callback_type callback) {
if (callback == nullptr) {
log_progress_callback = nullptr;
global_logger().add_observer(LOG_PROGRESS, NULL);
} else {
log_progress_callback = callback;
global_logger().add_observer(
LOG_PROGRESS,
[=](int lineloglevel, const char* buf, size_t len){
this->log_queue.enqueue(std::string(buf, len));
});
}
}
} // end of graphlab
<commit_msg>fix logprogress miss the very first print<commit_after>/**
* Copyright (C) 2015 Dato, Inc.
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*/
#include <cstdlib>
#include <time.h>
#include <unistd.h>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include <cppipc/cppipc.hpp>
#include <cppipc/common/authentication_token_method.hpp>
#include <minipsutil/minipsutil.h>
#include <logger/logger.hpp>
#include <logger/log_rotate.hpp>
#include <unity/lib/unity_global.hpp>
#include <unity/lib/unity_global_singleton.hpp>
#include <unity/lib/toolkit_class_registry.hpp>
#include <unity/lib/toolkit_function_registry.hpp>
#include <startup_teardown/startup_teardown.hpp>
#include <lambda/lambda_master.hpp>
#include "unity_server.hpp"
namespace graphlab {
unity_server::unity_server(unity_server_options options) : options(options) {
toolkit_functions = new toolkit_function_registry();
toolkit_classes = new toolkit_class_registry();
}
void unity_server::start(const unity_server_initializer& server_initializer) {
// log files
if (!options.log_file.empty()) {
if (options.log_rotation_interval) {
graphlab::begin_log_rotation(options.log_file,
options.log_rotation_interval,
options.log_rotation_truncate);
} else {
global_logger().set_log_file(options.log_file);
}
}
graphlab::configure_global_environment(options.root_path);
graphlab::global_startup::get_instance().perform_startup();
// server address
options.server_address = parse_server_address(options.server_address);
// construct the server
server = new cppipc::comm_server(std::vector<std::string>(), "",
options.server_address,
options.control_address,
options.publish_address,
options.secret_key);
// initialize built-in data structures, toolkits and models, defined in unity_server_init.cpp
server_initializer.init_toolkits(*toolkit_functions);
server_initializer.init_models(*toolkit_classes);
create_unity_global_singleton(toolkit_functions,
toolkit_classes,
server);
auto unity_global_ptr = get_unity_global_singleton();
server_initializer.register_base_classes(server, unity_global_ptr);
// initialize extension modules and lambda workers
server_initializer.init_extensions(options.root_path, unity_global_ptr);
lambda::set_pylambda_worker_binary_from_environment_variables();
// start the cppipc server
server->start();
logstream(LOG_EMPH) << "Unity server listening on: " << options.server_address << std::endl;
logstream(LOG_EMPH) << "Total System Memory Detected: " << total_mem() << std::endl;
log_thread.launch([=]() {
do {
std::pair<std::string, bool> queueelem = this->log_queue.dequeue();
if (queueelem.second == false) {
break;
} else {
// we need to read it before trying to do the callback
// Otherwise we might accidentally call a null pointer
volatile progress_callback_type cback = this->log_progress_callback;
if (cback != nullptr) cback(queueelem.first);
}
} while(1);
});
}
/**
* Cleanup the server state
*/
void unity_server::stop() {
delete server;
server = nullptr;
set_log_progress(false);
log_queue.stop_blocking();
graphlab::global_teardown::get_instance().perform_teardown();
}
/**
* Parse the server_address and return the parsed address.
*
* \param server_address can begin with different protocols: ipc, tcp or inproc
*/
std::string unity_server::parse_server_address(std::string server_address) {
namespace fs = boost::filesystem;
// Prevent multiple server listen on the same ipc device.
if (boost::starts_with(server_address, "ipc://") &&
fs::exists(fs::path(server_address.substr(6)))) {
logstream(LOG_FATAL) << "Cannot start graphlab server at "
<< server_address<< ". File already exists" << "\n";
exit(-1);
}
// Form default server address using process_id and client's timestamp:
// ipc://graphlab_server-$pid-$timestamp
if (boost::starts_with(server_address, "default")) {
std::string path = "/tmp/graphlab_server-" + std::to_string(getpid());
{ // parse server address: "default-$timestamp"
// append timestamp to the address
std::vector<std::string> _tmp;
boost::split(_tmp, server_address, boost::is_any_of("-"));
if (_tmp.size() == 2)
path += "-" + _tmp[1];
}
server_address = "ipc://" + path;
if (fs::exists(fs::path(path))) {
// It could be a leftover of a previous crashed process, try to delete the file
if (remove(path.c_str()) != 0) {
logstream(LOG_FATAL) << "Cannot start graphlab server at "
<< server_address
<< ". File already exists, and cannot be deleted." << "\n";
exit(-1);
}
}
}
return server_address;
}
EXPORT void unity_server::set_log_progress(bool enable) {
global_logger().add_observer(LOG_PROGRESS, NULL);
if (enable == true) {
// set the progress observer
global_logger().add_observer(
LOG_PROGRESS,
[=](int lineloglevel, const char* buf, size_t len){
std::cout << "PROGRESS: " << std::string(buf, len);
});
}
}
void unity_server::set_log_progress_callback(progress_callback_type callback) {
if (callback == nullptr) {
log_progress_callback = nullptr;
global_logger().add_observer(LOG_PROGRESS, NULL);
} else {
log_progress_callback = callback;
global_logger().add_observer(
LOG_PROGRESS,
[=](int lineloglevel, const char* buf, size_t len){
this->log_queue.enqueue(std::string(buf, len));
});
}
}
} // end of graphlab
<|endoftext|> |
<commit_before>#include "chainerx/cuda/cusolver.h"
<<<<<<< HEAD
#include <cublas_v2.h>
=======
>>>>>>> ivan-add-cusolver-handle
#include <cusolverDn.h>
#include <cuda_runtime.h>
#include <string>
#include "chainerx/cuda/cuda_set_device_scope.h"
#include "chainerx/error.h"
#include "chainerx/macro.h"
namespace chainerx {
namespace cuda {
namespace cuda_internal {
CusolverDnHandle::~CusolverDnHandle() {
if (handle_ != nullptr) {
// NOTE: CudaSetDeviceScope is not available because it may throw
int orig_index{0};
cudaGetDevice(&orig_index);
cudaSetDevice(device_index_);
cusolverDnDestroy(handle_);
cudaSetDevice(orig_index);
}
}
cusolverDnHandle_t CusolverDnHandle::handle() {
if (handle_ == nullptr) {
CudaSetDeviceScope scope{device_index_};
CheckCusolverError(cusolverDnCreate(&handle_));
}
return handle_;
}
} // namespace cuda_internal
namespace {
std::string BuildErrorMessage(cusolverStatus_t error) {
switch (error) {
#define CHAINERX_MATCH_AND_RETURN_MSG(msg) \
case msg: \
return #msg
CHAINERX_MATCH_AND_RETURN_MSG(CUSOLVER_STATUS_SUCCESS);
CHAINERX_MATCH_AND_RETURN_MSG(CUSOLVER_STATUS_NOT_INITIALIZED);
CHAINERX_MATCH_AND_RETURN_MSG(CUSOLVER_STATUS_ALLOC_FAILED);
CHAINERX_MATCH_AND_RETURN_MSG(CUSOLVER_STATUS_INVALID_VALUE);
CHAINERX_MATCH_AND_RETURN_MSG(CUSOLVER_STATUS_ARCH_MISMATCH);
CHAINERX_MATCH_AND_RETURN_MSG(CUSOLVER_STATUS_MAPPING_ERROR);
CHAINERX_MATCH_AND_RETURN_MSG(CUSOLVER_STATUS_EXECUTION_FAILED);
CHAINERX_MATCH_AND_RETURN_MSG(CUSOLVER_STATUS_INTERNAL_ERROR);
CHAINERX_MATCH_AND_RETURN_MSG(CUSOLVER_STATUS_MATRIX_TYPE_NOT_SUPPORTED);
CHAINERX_MATCH_AND_RETURN_MSG(CUSOLVER_STATUS_NOT_SUPPORTED);
CHAINERX_MATCH_AND_RETURN_MSG(CUSOLVER_STATUS_ZERO_PIVOT);
CHAINERX_MATCH_AND_RETURN_MSG(CUSOLVER_STATUS_INVALID_LICENSE);
#undef CHAINERX_MATCH_AND_RETURN_MSG
}
CHAINERX_NEVER_REACH();
}
} // namespace
CusolverError::CusolverError(cusolverStatus_t status) : ChainerxError{BuildErrorMessage(status)}, status_{status} {}
void CheckCusolverError(cusolverStatus_t status) {
if (status != CUSOLVER_STATUS_SUCCESS) {
throw CusolverError{status};
}
}
} // namespace cuda
} // namespace chainerx
<commit_msg>Resolve merge conflict<commit_after>#include "chainerx/cuda/cusolver.h"
#include <cusolverDn.h>
#include <cuda_runtime.h>
#include <string>
#include "chainerx/cuda/cuda_set_device_scope.h"
#include "chainerx/error.h"
#include "chainerx/macro.h"
namespace chainerx {
namespace cuda {
namespace cuda_internal {
CusolverDnHandle::~CusolverDnHandle() {
if (handle_ != nullptr) {
// NOTE: CudaSetDeviceScope is not available because it may throw
int orig_index{0};
cudaGetDevice(&orig_index);
cudaSetDevice(device_index_);
cusolverDnDestroy(handle_);
cudaSetDevice(orig_index);
}
}
cusolverDnHandle_t CusolverDnHandle::handle() {
if (handle_ == nullptr) {
CudaSetDeviceScope scope{device_index_};
CheckCusolverError(cusolverDnCreate(&handle_));
}
return handle_;
}
} // namespace cuda_internal
namespace {
std::string BuildErrorMessage(cusolverStatus_t error) {
switch (error) {
#define CHAINERX_MATCH_AND_RETURN_MSG(msg) \
case msg: \
return #msg
CHAINERX_MATCH_AND_RETURN_MSG(CUSOLVER_STATUS_SUCCESS);
CHAINERX_MATCH_AND_RETURN_MSG(CUSOLVER_STATUS_NOT_INITIALIZED);
CHAINERX_MATCH_AND_RETURN_MSG(CUSOLVER_STATUS_ALLOC_FAILED);
CHAINERX_MATCH_AND_RETURN_MSG(CUSOLVER_STATUS_INVALID_VALUE);
CHAINERX_MATCH_AND_RETURN_MSG(CUSOLVER_STATUS_ARCH_MISMATCH);
CHAINERX_MATCH_AND_RETURN_MSG(CUSOLVER_STATUS_MAPPING_ERROR);
CHAINERX_MATCH_AND_RETURN_MSG(CUSOLVER_STATUS_EXECUTION_FAILED);
CHAINERX_MATCH_AND_RETURN_MSG(CUSOLVER_STATUS_INTERNAL_ERROR);
CHAINERX_MATCH_AND_RETURN_MSG(CUSOLVER_STATUS_MATRIX_TYPE_NOT_SUPPORTED);
CHAINERX_MATCH_AND_RETURN_MSG(CUSOLVER_STATUS_NOT_SUPPORTED);
CHAINERX_MATCH_AND_RETURN_MSG(CUSOLVER_STATUS_ZERO_PIVOT);
CHAINERX_MATCH_AND_RETURN_MSG(CUSOLVER_STATUS_INVALID_LICENSE);
#undef CHAINERX_MATCH_AND_RETURN_MSG
}
CHAINERX_NEVER_REACH();
}
} // namespace
CusolverError::CusolverError(cusolverStatus_t status) : ChainerxError{BuildErrorMessage(status)}, status_{status} {}
void CheckCusolverError(cusolverStatus_t status) {
if (status != CUSOLVER_STATUS_SUCCESS) {
throw CusolverError{status};
}
}
} // namespace cuda
} // namespace chainerx
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 deipi.com LLC and contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "database_autocommit.h"
std::mutex DatabaseAutocommit::mtx;
std::condition_variable DatabaseAutocommit::wakeup_signal;
std::unordered_map<Endpoints, DatabaseCommitStatus> DatabaseAutocommit::databases;
std::chrono::time_point<std::chrono::system_clock> DatabaseAutocommit::next_wakeup_time(std::chrono::system_clock::now() + 10s);
std::chrono::time_point<std::chrono::system_clock>
DatabaseCommitStatus::next_wakeup_time()
{
return max_commit_time < commit_time ? max_commit_time : commit_time;
}
DatabaseAutocommit::DatabaseAutocommit(const std::shared_ptr<XapiandManager>& manager_)
: running(true),
manager(manager_) { }
DatabaseAutocommit::~DatabaseAutocommit()
{
running.store(false);
}
void
DatabaseAutocommit::signal_changed(const std::shared_ptr<Database>& database)
{
//std::unique_lock<std::mutex> lk(DatabaseAutocommit::mtx, std::defer_lock);
DatabaseCommitStatus& status = DatabaseAutocommit::databases[database->endpoints];
auto now = std::chrono::system_clock::now();
if (!status.database.lock()) {
status.database = database;
status.max_commit_time = now + 9s;
}
status.commit_time = now + 3s;
if (DatabaseAutocommit::next_wakeup_time > status.next_wakeup_time()) {
DatabaseAutocommit::wakeup_signal.notify_one();
}
}
void
DatabaseAutocommit::run()
{
LOG_OBJ(this, "Committer started...\n");
while (running) {
std::unique_lock<std::mutex> lk(DatabaseAutocommit::mtx);
DatabaseAutocommit::wakeup_signal.wait_until(lk, DatabaseAutocommit::next_wakeup_time);
auto now = std::chrono::system_clock::now();
for (auto it = DatabaseAutocommit::databases.begin(); it != DatabaseAutocommit::databases.end(); ) {
auto endpoints = it->first;
auto status = it->second;
if (status.database.lock()) {
auto next_wakeup_time = status.next_wakeup_time();
if (next_wakeup_time <= now) {
DatabaseAutocommit::databases.erase(it);
lk.unlock();
std::shared_ptr<Database> database;
if (manager->database_pool.checkout(database, endpoints, DB_WRITABLE)) {
database->commit();
manager->database_pool.checkin(database);
}
lk.lock();
it = DatabaseAutocommit::databases.begin();
} else if (DatabaseAutocommit::next_wakeup_time > next_wakeup_time) {
DatabaseAutocommit::next_wakeup_time = next_wakeup_time;
++it;
} else {
++it;
}
} else {
it = DatabaseAutocommit::databases.erase(it);
}
}
}
LOG_OBJ(this, "Committer ended!...\n");
}
<commit_msg>Format code (and comment warning)<commit_after>/*
* Copyright (C) 2015 deipi.com LLC and contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "database_autocommit.h"
std::mutex DatabaseAutocommit::mtx;
std::condition_variable DatabaseAutocommit::wakeup_signal;
std::unordered_map<Endpoints, DatabaseCommitStatus> DatabaseAutocommit::databases;
std::chrono::time_point<std::chrono::system_clock> DatabaseAutocommit::next_wakeup_time(std::chrono::system_clock::now() + 10s);
std::chrono::time_point<std::chrono::system_clock>
DatabaseCommitStatus::next_wakeup_time()
{
return max_commit_time < commit_time ? max_commit_time : commit_time;
}
DatabaseAutocommit::DatabaseAutocommit(const std::shared_ptr<XapiandManager>& manager_)
: running(true),
manager(manager_) { }
DatabaseAutocommit::~DatabaseAutocommit()
{
running.store(false);
}
void
DatabaseAutocommit::signal_changed(const std::shared_ptr<Database>& database)
{
//Window open perhaps
//std::unique_lock<std::mutex> lk(DatabaseAutocommit::mtx, std::defer_lock);
DatabaseCommitStatus& status = DatabaseAutocommit::databases[database->endpoints];
auto now = std::chrono::system_clock::now();
if (!status.database.lock()) {
status.database = database;
status.max_commit_time = now + 9s;
}
status.commit_time = now + 3s;
if (DatabaseAutocommit::next_wakeup_time > status.next_wakeup_time()) {
DatabaseAutocommit::wakeup_signal.notify_one();
}
}
void
DatabaseAutocommit::run()
{
LOG_OBJ(this, "Committer started...\n");
while (running) {
std::unique_lock<std::mutex> lk(DatabaseAutocommit::mtx);
DatabaseAutocommit::wakeup_signal.wait_until(lk, DatabaseAutocommit::next_wakeup_time);
auto now = std::chrono::system_clock::now();
for (auto it = DatabaseAutocommit::databases.begin(); it != DatabaseAutocommit::databases.end(); ) {
auto endpoints = it->first;
auto status = it->second;
if (status.database.lock()) {
auto next_wakeup_time = status.next_wakeup_time();
if (next_wakeup_time <= now) {
DatabaseAutocommit::databases.erase(it);
lk.unlock();
std::shared_ptr<Database> database;
if (manager->database_pool.checkout(database, endpoints, DB_WRITABLE)) {
database->commit();
manager->database_pool.checkin(database);
}
lk.lock();
it = DatabaseAutocommit::databases.begin();
} else if (DatabaseAutocommit::next_wakeup_time > next_wakeup_time) {
DatabaseAutocommit::next_wakeup_time = next_wakeup_time;
++it;
} else {
++it;
}
} else {
it = DatabaseAutocommit::databases.erase(it);
}
}
}
LOG_OBJ(this, "Committer ended!...\n");
}
<|endoftext|> |
<commit_before>/*
*
* MIT License
*
* Copyright (c) 2016-2017 The Cats Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#ifndef CATS_CORECAT_UTIL_COMMANDLINE_HPP
#define CATS_CORECAT_UTIL_COMMANDLINE_HPP
#include <cstddef>
#include <exception>
#include <functional>
#include <memory>
#include <vector>
#include "../ArrayView.hpp"
#include "../String.hpp"
namespace Cats {
namespace Corecat {
namespace Util {
namespace CommandLine {
class CommandLineOptionParser;
class CommandLineParseException : public std::exception {
private:
String8 data;
public:
CommandLineParseException(const String8& data_) : data("CommandLineParseException: " + data_) {}
const char* what() const noexcept override { return data.getData(); }
};
class CommandLineOption {
private:
std::function<void(StringView8)> callback;
bool required = false;
std::vector<std::pair<CommandLineOptionParser*, String8>> parsers;
String8 argument;
String8 help;
public:
CommandLineOption(std::function<void(StringView8)> callback_) : callback(std::move(callback_)) {}
CommandLineOption(const CommandLineOption& src) = delete;
CommandLineOption(CommandLineOption&& src) = default;
CommandLineOption& operator =(const CommandLineOption& src) = delete;
CommandLineOption& operator =(CommandLineOption&& src) = default;
template <typename T, typename... Arg>
CommandLineOption& set(T&& parser, Arg&&... arg) { parser.set(*this, std::forward<Arg>(arg)...); return *this; }
const std::function<void(StringView8)>& getCallback() const noexcept { return callback; }
CommandLineOption& setCallback(std::function<void(StringView8)> callback_) noexcept { callback = std::move(callback_); return *this; }
bool getRequired() const noexcept { return required; }
CommandLineOption& setRequired(bool required_ = true) noexcept { required = required_; return *this; }
const std::vector<std::pair<CommandLineOptionParser*, String8>>& getParsers() const noexcept { return parsers; }
CommandLineOption& addParser(CommandLineOptionParser& parser, String8 name) { parsers.emplace_back(&parser, std::move(name)); return *this; }
const String8& getArgument() const noexcept { return argument; }
CommandLineOption& setArgument(String8 argument_) { argument = std::move(argument_); return *this; }
const String8& getHelp() const noexcept { return help; }
CommandLineOption& setHelp(String8 help_) { help = std::move(help_); return *this; }
};
class CommandLineOptionParser {
public:
virtual ~CommandLineOptionParser() = default;
virtual String8 getName(const CommandLineOption& option, const String8& name) const = 0;
virtual std::size_t parse(ArrayView<const StringView8> arg) const = 0;
};
class CommandLineLongOptionParser : public CommandLineOptionParser {
private:
std::vector<std::pair<String8, CommandLineOption*>> options;
public:
CommandLineLongOptionParser() = default;
CommandLineLongOptionParser(const CommandLineLongOptionParser& src) = delete;
CommandLineLongOptionParser& operator =(const CommandLineLongOptionParser& src) = delete;
void set(CommandLineOption& option, String8 name) {
option.addParser(*this, name);
options.emplace_back(std::move(name), &option);
}
String8 getName(const CommandLineOption& option, const String8& name) const override {
if(option.getRequired()) return "--" + name + "=<" + option.getArgument() + '>';
else return "--" + name;
}
std::size_t parse(ArrayView<const StringView8> arg) const override {
if(arg.isEmpty()) return 0;
if(!arg[0].startsWith("--")) return 0;
for(auto&& x : options) {
auto& name = x.first;
auto& option = *x.second;
if(!arg[0].slice(2).startsWith(name)) continue;
auto argument = arg[0].slice(2 + name.getLength());
if(!argument.isEmpty() && !argument.startsWith("=")) continue;
auto& callback = option.getCallback();
if(option.getRequired()) {
if(argument.isEmpty()) {
if(arg.getSize() == 1) throw CommandLineParseException("missing argument after --" + name);
callback(arg[1]);
return 2;
} else {
callback(argument.slice(1));
return 1;
}
} else {
if(!argument.isEmpty()) throw CommandLineParseException("unexcepted argument after --" + name);
callback({});
return 1;
}
}
throw CommandLineParseException("unexcepted option " + arg[0]);
}
};
class CommandLineShortOptionParser : public CommandLineOptionParser {
private:
std::vector<std::pair<String8, CommandLineOption*>> options;
public:
CommandLineShortOptionParser() = default;
CommandLineShortOptionParser(const CommandLineShortOptionParser& src) = delete;
CommandLineShortOptionParser& operator =(const CommandLineShortOptionParser& src) = delete;
void set(CommandLineOption& option, String8 name) {
option.addParser(*this, name);
options.emplace_back(std::move(name), &option);
}
String8 getName(const CommandLineOption& option, const String8& name) const override {
if(option.getRequired()) return '-' + name + " <" + option.getArgument() + '>';
else return '-' + name;
}
std::size_t parse(ArrayView<const StringView8> arg) const override {
if(arg.isEmpty()) return 0;
if(!arg[0].startsWith("-")) return 0;
for(auto&& x : options) {
auto& name = x.first;
auto& option = *x.second;
if(!arg[0].slice(1).startsWith(name)) continue;
auto argument = arg[0].slice(1 + name.getLength());
auto& callback = option.getCallback();
if(option.getRequired()) {
if(argument.isEmpty()) {
if(arg.getSize() == 1) throw CommandLineParseException("missing argument after -" + name);
callback(arg[1]);
return 2;
} else {
callback(argument);
return 1;
}
} else {
if(!argument.isEmpty()) throw CommandLineParseException("unexcepted argument after -" + name);
callback({});
return 1;
}
}
throw CommandLineParseException("unexcepted option " + arg[0]);
}
};
class CommandLineArgumentOptionParser : public CommandLineOptionParser {
private:
std::vector<CommandLineOption*> options;
public:
CommandLineArgumentOptionParser() = default;
CommandLineArgumentOptionParser(const CommandLineArgumentOptionParser& src) = delete;
CommandLineArgumentOptionParser& operator =(const CommandLineArgumentOptionParser& src) = delete;
void set(CommandLineOption& option) {
option.addParser(*this, {});
options.emplace_back(&option);
}
String8 getName(const CommandLineOption& /*option*/, const String8& /*name*/) const override { return {}; }
std::size_t parse(ArrayView<const StringView8> arg) const override {
if(arg.isEmpty()) return 0;
for(auto&& x : options) {
auto& callback = x->getCallback();
callback(arg[0]);
}
return 1;
}
};
class CommandLineOptionList {
private:
String8 name;
std::vector<std::unique_ptr<CommandLineOption>> options;
public:
CommandLineOptionList(String8 name_ = "Options") : name(std::move(name_)) {}
CommandLineOptionList(const CommandLineOptionList& src) = delete;
CommandLineOptionList(CommandLineOptionList&& src) = default;
CommandLineOptionList& operator =(const CommandLineOptionList& src) = delete;
CommandLineOptionList& operator =(CommandLineOptionList&& src) = default;
template <typename T>
CommandLineOption& add(T&& t) { return *this << std::forward<T>(t); }
const String8& getName() const { return name; }
void setName(String8 name_) { name = std::move(name_); }
const std::vector<std::unique_ptr<CommandLineOption>>& getOptions() const { return options; }
CommandLineOption& addOption(std::function<void(StringView8)> callback) {
options.emplace_back(new CommandLineOption(std::move(callback)));
return *options.back();
}
};
inline CommandLineOption& operator <<(CommandLineOptionList& optionList, std::function<void(StringView8)> callback) {
return optionList.addOption(std::move(callback));
}
inline CommandLineOption& operator <<(CommandLineOptionList& optionList, bool& x) {
return optionList << [&x](StringView8 /*str*/) { x = true; };
}
inline CommandLineOption& operator <<(CommandLineOptionList& optionList, String8& x) {
return (optionList << [&x](StringView8 str) { x = str; }).setRequired();
}
inline CommandLineOption& operator <<(CommandLineOptionList& optionList, std::vector<String8>& x) {
return (optionList << [&x](StringView8 str) { x.emplace_back(str); }).setRequired();
}
class CommandLineParser {
private:
std::vector<const CommandLineOptionList*> optionLists;
std::vector<const CommandLineOptionParser*> parsers;
public:
CommandLineParser() = default;
CommandLineParser& add(const CommandLineOptionList& optionList) { optionLists.emplace_back(&optionList); return *this; }
CommandLineParser& add(const CommandLineOptionParser& parser) { parsers.emplace_back(&parser); return *this; }
void parse(const std::vector<StringView8>& arg) const {
ArrayView<const StringView8> a(arg.data(), arg.size());
while(!a.isEmpty()) {
bool matched = false;
for(auto&& x : parsers) {
std::size_t ret = x->parse(a);
if(ret) {
a = {a.getData() + ret, a.getSize() - ret};
matched = true;
break;
}
}
if(!matched) throw CommandLineParseException("unexcepted argument " + a[0]);
}
}
void parse(int argc, char** argv) const { parse({argv + 1, argv + argc}); }
String8 getHelp() const {
String8 helpText;
for(auto&& optionList : optionLists) {
helpText += optionList->getName() + ":\n";
for(auto&& option : optionList->getOptions()) {
if(option->getHelp().isEmpty()) continue;
String8 optionText;
bool first = true;
for(auto&& z : option->getParsers()) {
auto& parser = *z.first;
auto& name = z.second;
auto text = parser.getName(*option, name);
if(!text.isEmpty()) {
if(first) first = false;
else optionText += ", ";
optionText += text;
}
}
if(optionText.isEmpty()) continue;
helpText += " " + optionText;
if(optionText.getLength() <= 26)
helpText += String8(' ', 28 - optionText.getLength());
else
helpText += '\n' + String8(' ', 32);
helpText += option->getHelp() + '\n';
}
}
return helpText;
}
};
}
}
}
}
#endif
<commit_msg>Update CommandLine<commit_after>/*
*
* MIT License
*
* Copyright (c) 2016-2017 The Cats Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#ifndef CATS_CORECAT_UTIL_COMMANDLINE_HPP
#define CATS_CORECAT_UTIL_COMMANDLINE_HPP
#include <cstddef>
#include <deque>
#include <exception>
#include <functional>
#include <memory>
#include <vector>
#include "../ArrayView.hpp"
#include "../String.hpp"
namespace Cats {
namespace Corecat {
namespace Util {
namespace CommandLine {
class CommandLineOptionParser;
class CommandLineParseException : public std::exception {
private:
std::shared_ptr<const String8> data;
public:
CommandLineParseException(const String8& data_) : data(std::make_shared<const String8>("CommandLineParseException: " + data_)) {}
const char* what() const noexcept override { return data->getData(); }
};
class CommandLineOption {
private:
std::function<void(StringView8)> callback;
bool required = false;
std::vector<std::pair<CommandLineOptionParser*, String8>> parsers;
String8 argument;
String8 help;
public:
CommandLineOption(std::function<void(StringView8)> callback_) : callback(std::move(callback_)) {}
CommandLineOption(const CommandLineOption& src) = delete;
CommandLineOption(CommandLineOption&& src) = default;
CommandLineOption& operator =(const CommandLineOption& src) = delete;
CommandLineOption& operator =(CommandLineOption&& src) = default;
template <typename T, typename... Arg>
CommandLineOption& set(T&& parser, Arg&&... arg) { parser.set(*this, std::forward<Arg>(arg)...); return *this; }
const std::function<void(StringView8)>& getCallback() const noexcept { return callback; }
CommandLineOption& setCallback(std::function<void(StringView8)> callback_) noexcept { callback = std::move(callback_); return *this; }
bool getRequired() const noexcept { return required; }
CommandLineOption& setRequired(bool required_ = true) noexcept { required = required_; return *this; }
const std::vector<std::pair<CommandLineOptionParser*, String8>>& getParsers() const noexcept { return parsers; }
CommandLineOption& addParser(CommandLineOptionParser& parser, String8 name) { parsers.emplace_back(&parser, std::move(name)); return *this; }
const String8& getArgument() const noexcept { return argument; }
CommandLineOption& setArgument(String8 argument_) { argument = std::move(argument_); return *this; }
const String8& getHelp() const noexcept { return help; }
CommandLineOption& setHelp(String8 help_) { help = std::move(help_); return *this; }
};
class CommandLineOptionParser {
public:
virtual ~CommandLineOptionParser() = default;
virtual String8 getName(const CommandLineOption& option, const String8& name) const = 0;
virtual std::size_t parse(ArrayView<const StringView8> arg) const = 0;
};
class CommandLineLongOptionParser : public CommandLineOptionParser {
private:
std::vector<std::pair<String8, CommandLineOption*>> options;
public:
CommandLineLongOptionParser() = default;
CommandLineLongOptionParser(const CommandLineLongOptionParser& src) = delete;
CommandLineLongOptionParser& operator =(const CommandLineLongOptionParser& src) = delete;
void set(CommandLineOption& option, String8 name) {
option.addParser(*this, name);
options.emplace_back(std::move(name), &option);
}
String8 getName(const CommandLineOption& option, const String8& name) const override {
if(option.getRequired()) return "--" + name + "=<" + option.getArgument() + '>';
else return "--" + name;
}
std::size_t parse(ArrayView<const StringView8> arg) const override {
if(arg.isEmpty()) return 0;
if(!arg[0].startsWith("--")) return 0;
for(auto&& x : options) {
auto& name = x.first;
auto& option = *x.second;
if(!arg[0].slice(2).startsWith(name)) continue;
auto argument = arg[0].slice(2 + name.getLength());
if(!argument.isEmpty() && !argument.startsWith("=")) continue;
auto& callback = option.getCallback();
if(option.getRequired()) {
if(argument.isEmpty()) {
if(arg.getSize() == 1) throw CommandLineParseException("missing argument after --" + name);
callback(arg[1]);
return 2;
} else {
callback(argument.slice(1));
return 1;
}
} else {
if(!argument.isEmpty()) throw CommandLineParseException("unexcepted argument after --" + name);
callback({});
return 1;
}
}
throw CommandLineParseException("unexcepted option " + arg[0]);
}
};
class CommandLineShortOptionParser : public CommandLineOptionParser {
private:
std::vector<std::pair<String8, CommandLineOption*>> options;
public:
CommandLineShortOptionParser() = default;
CommandLineShortOptionParser(const CommandLineShortOptionParser& src) = delete;
CommandLineShortOptionParser& operator =(const CommandLineShortOptionParser& src) = delete;
void set(CommandLineOption& option, String8 name) {
option.addParser(*this, name);
options.emplace_back(std::move(name), &option);
}
String8 getName(const CommandLineOption& option, const String8& name) const override {
if(option.getRequired()) return '-' + name + " <" + option.getArgument() + '>';
else return '-' + name;
}
std::size_t parse(ArrayView<const StringView8> arg) const override {
if(arg.isEmpty()) return 0;
if(!arg[0].startsWith("-")) return 0;
for(auto&& x : options) {
auto& name = x.first;
auto& option = *x.second;
if(!arg[0].slice(1).startsWith(name)) continue;
auto argument = arg[0].slice(1 + name.getLength());
auto& callback = option.getCallback();
if(option.getRequired()) {
if(argument.isEmpty()) {
if(arg.getSize() == 1) throw CommandLineParseException("missing argument after -" + name);
callback(arg[1]);
return 2;
} else {
callback(argument);
return 1;
}
} else {
if(!argument.isEmpty()) throw CommandLineParseException("unexcepted argument after -" + name);
callback({});
return 1;
}
}
throw CommandLineParseException("unexcepted option " + arg[0]);
}
};
class CommandLineArgumentOptionParser : public CommandLineOptionParser {
private:
std::vector<CommandLineOption*> options;
public:
CommandLineArgumentOptionParser() = default;
CommandLineArgumentOptionParser(const CommandLineArgumentOptionParser& src) = delete;
CommandLineArgumentOptionParser& operator =(const CommandLineArgumentOptionParser& src) = delete;
void set(CommandLineOption& option) {
option.addParser(*this, {});
options.emplace_back(&option);
}
String8 getName(const CommandLineOption& /*option*/, const String8& /*name*/) const override { return {}; }
std::size_t parse(ArrayView<const StringView8> arg) const override {
if(arg.isEmpty()) return 0;
for(auto&& x : options) {
auto& callback = x->getCallback();
callback(arg[0]);
}
return 1;
}
};
class CommandLineOptionList {
private:
String8 name;
std::deque<CommandLineOption> options;
public:
CommandLineOptionList(String8 name_ = "Options") : name(std::move(name_)) {}
CommandLineOptionList(const CommandLineOptionList& src) = delete;
CommandLineOptionList(CommandLineOptionList&& src) = default;
CommandLineOptionList& operator =(const CommandLineOptionList& src) = delete;
CommandLineOptionList& operator =(CommandLineOptionList&& src) = default;
template <typename T>
CommandLineOption& add(T&& t) { return *this << std::forward<T>(t); }
const String8& getName() const { return name; }
void setName(String8 name_) { name = std::move(name_); }
const std::deque<CommandLineOption>& getOptions() const { return options; }
CommandLineOption& addOption(std::function<void(StringView8)> callback) {
options.emplace_back(std::move(callback));
return options.back();
}
};
inline CommandLineOption& operator <<(CommandLineOptionList& optionList, std::function<void(StringView8)> callback) {
return optionList.addOption(std::move(callback));
}
inline CommandLineOption& operator <<(CommandLineOptionList& optionList, bool& x) {
return optionList << [&x](StringView8 /*str*/) { x = true; };
}
inline CommandLineOption& operator <<(CommandLineOptionList& optionList, String8& x) {
return (optionList << [&x](StringView8 str) { x = str; }).setRequired();
}
inline CommandLineOption& operator <<(CommandLineOptionList& optionList, std::vector<String8>& x) {
return (optionList << [&x](StringView8 str) { x.emplace_back(str); }).setRequired();
}
class CommandLineParser {
private:
std::vector<const CommandLineOptionList*> optionLists;
std::vector<const CommandLineOptionParser*> parsers;
public:
CommandLineParser() = default;
CommandLineParser& add(const CommandLineOptionList& optionList) { optionLists.emplace_back(&optionList); return *this; }
CommandLineParser& add(const CommandLineOptionParser& parser) { parsers.emplace_back(&parser); return *this; }
void parse(const std::vector<StringView8>& arg) const {
ArrayView<const StringView8> a(arg.data(), arg.size());
while(!a.isEmpty()) {
bool matched = false;
for(auto&& x : parsers) {
std::size_t ret = x->parse(a);
if(ret) {
a = {a.getData() + ret, a.getSize() - ret};
matched = true;
break;
}
}
if(!matched) throw CommandLineParseException("unexcepted argument " + a[0]);
}
}
void parse(int argc, char** argv) const { parse({argv + 1, argv + argc}); }
String8 getHelp() const {
String8 helpText;
for(auto&& optionList : optionLists) {
helpText += optionList->getName() + ":\n";
for(auto&& option : optionList->getOptions()) {
if(option.getHelp().isEmpty()) continue;
String8 optionText;
bool first = true;
for(auto&& z : option.getParsers()) {
auto& parser = *z.first;
auto& name = z.second;
auto text = parser.getName(option, name);
if(!text.isEmpty()) {
if(first) first = false;
else optionText += ", ";
optionText += text;
}
}
if(optionText.isEmpty()) continue;
helpText += " " + optionText;
if(optionText.getLength() <= 26)
helpText += String8(' ', 28 - optionText.getLength());
else
helpText += '\n' + String8(' ', 32);
helpText += option.getHelp() + '\n';
}
}
return helpText;
}
};
}
}
}
}
#endif
<|endoftext|> |
<commit_before><commit_msg>SwTxtAttr::dumpAsXml: show hyperlink URLs<commit_after><|endoftext|> |
<commit_before>#include <rss.h>
#include <config.h>
#include <stringprep.h>
#include <cache.h>
#include <xmlpullparser.h>
#include <utils.h>
#include <logger.h>
#include <sstream>
#include <iostream>
#include <configcontainer.h>
using namespace newsbeuter;
rss_parser::rss_parser(const char * uri, cache * c, configcontainer * cfg) : my_uri(uri), ch(c), cfgcont(cfg), mrss(0) { }
rss_parser::~rss_parser() { }
rss_feed rss_parser::parse() {
rss_feed feed(ch);
feed.set_rssurl(my_uri);
char * proxy = NULL;
char * proxy_auth = NULL;
if (cfgcont->get_configvalue_as_bool("use-proxy") == true) {
proxy = const_cast<char *>(cfgcont->get_configvalue("proxy").c_str());
proxy_auth = const_cast<char *>(cfgcont->get_configvalue("proxy-auth").c_str());
}
mrss_options_t * options = mrss_options_new(30, proxy, proxy_auth, NULL, NULL, NULL, 0, NULL, USER_AGENT);
mrss_error_t err = mrss_parse_url_with_options(const_cast<char *>(my_uri.c_str()), &mrss, options);
mrss_options_free(options);
if (err != MRSS_OK) {
GetLogger().log(LOG_ERROR,"rss_parser::parse: mrss_parse_url_with_options failed: err = %s (%d)",mrss_strerror(err), err);
if (mrss) {
mrss_free(mrss);
}
throw std::string(mrss_strerror(err));
}
const char * encoding = mrss->encoding ? mrss->encoding : "utf-8";
if (mrss->title) {
char * str = stringprep_convert(mrss->title, stringprep_locale_charset(), encoding);
if (str) {
feed.set_title(str);
free(str);
}
}
if (mrss->description) {
char * str = stringprep_convert(mrss->description, stringprep_locale_charset(), encoding);
if (str) {
feed.set_description(str);
free(str);
}
}
if (mrss->link) feed.set_link(mrss->link);
if (mrss->pubDate)
feed.set_pubDate(parse_date(mrss->pubDate));
else
feed.set_pubDate(::time(NULL));
GetLogger().log(LOG_DEBUG, "rss_parser::parse: feed title = `%s' link = `%s'", feed.title().c_str(), feed.link().c_str());
for (mrss_item_t * item = mrss->item; item != NULL; item = item->next ) {
rss_item x(ch);
if (item->title) {
char * str = stringprep_convert(item->title,stringprep_locale_charset(), encoding);
if (str) {
x.set_title(str);
free(str);
}
}
if (item->link) x.set_link(item->link);
if (item->author) x.set_author(item->author);
mrss_tag_t * content;
if (mrss->version == MRSS_VERSION_2_0 && mrss_search_tag(item, "encoded", "http://purl.org/rss/1.0/modules/content/", &content) == MRSS_OK && content) {
/* RSS 2.0 content:encoded */
GetLogger().log(LOG_DEBUG, "rss_parser::parse: found rss 2.0 content:encoded: %s\n", content->value);
if (content->value) {
char * str = stringprep_convert(content->value, stringprep_locale_charset(), encoding);
if (str) {
x.set_description(str);
free(str);
GetLogger().log(LOG_DEBUG, "rss_parser::parse: conversion was successful: %s\n", x.description().c_str());
} else {
GetLogger().log(LOG_WARN, "rss_parser::parse: stringprep_convert() failed for %s, but trying anyway...", x.link().c_str());
x.set_description(content->value);
}
}
} else {
GetLogger().log(LOG_DEBUG, "rss_parser::parse: found no rss 2.0 content:encoded");
}
if ((mrss->version == MRSS_VERSION_ATOM_0_3 || mrss->version == MRSS_VERSION_ATOM_1_0)) {
int rc;
if (((rc = mrss_search_tag(item, "content", "http://www.w3.org/2005/Atom", &content)) == MRSS_OK && content) ||
((rc = mrss_search_tag(item, "content", "http://purl.org/atom/ns#", &content)) == MRSS_OK && content)) {
GetLogger().log(LOG_DEBUG, "rss_parser::parse: found atom content: %s\n", content ? content->value : "(content = null)");
if (content && content->value) {
char * str = stringprep_convert(content->value, stringprep_locale_charset(), encoding);
if (str) {
x.set_description(str);
free(str);
} else {
x.set_description(content->value);
}
}
} else {
GetLogger().log(LOG_DEBUG, "rss_parser::parse: mrss_search_tag(content) failed with rc = %d content = %p", rc, content);
}
} else {
GetLogger().log(LOG_DEBUG, "rss_parser::parse: not an atom feed");
}
/* last resort: search for itunes:summary tag (may be a podcast) */
if (x.description().length() == 0 && mrss_search_tag(item, "summary", "http://www.itunes.com/dtds/podcast-1.0.dtd", &content) == MRSS_OK && content) {
GetLogger().log(LOG_DEBUG, "rss_parser::parse: found itunes:summary: %s\n", content->value);
if (content->value) {
char * str = stringprep_convert(content->value, stringprep_locale_charset(), encoding);
if (str) {
std::string desc = "<pre>";
desc.append(str);
desc.append("</pre>");
x.set_description(desc);
free(str);
GetLogger().log(LOG_DEBUG, "rss_parser::parse: conversion was successful: %s\n", x.description().c_str());
} else {
GetLogger().log(LOG_WARN, "rss_parser::parse: stringprep_convert() failed for %s, but trying anyway...", x.link().c_str());
x.set_description(content->value);
}
}
} else {
GetLogger().log(LOG_DEBUG, "rss_parser::parse: no luck with itunes:summary");
}
if (x.description().length() == 0 && item->description) {
char * str = stringprep_convert(item->description,stringprep_locale_charset(), encoding);
if (str) {
x.set_description(str);
free(str);
}
}
if (item->pubDate)
x.set_pubDate(parse_date(item->pubDate));
else
x.set_pubDate(::time(NULL));
if (item->guid)
x.set_guid(item->guid);
else
x.set_guid(item->link); // XXX hash something to get a better alternative GUID
if (item->enclosure_url) {
x.set_enclosure_url(item->enclosure_url);
GetLogger().log(LOG_DEBUG, "rss_parser::parse: found enclosure_url: %s", item->enclosure_url);
}
if (item->enclosure_type) {
x.set_enclosure_type(item->enclosure_type);
GetLogger().log(LOG_DEBUG, "rss_parser::parse: found enclosure_type: %s", item->enclosure_type);
}
GetLogger().log(LOG_DEBUG, "rss_parser::parse: item title = `%s' link = `%s' pubDate = `%s' (%d) description = `%s'",
x.title().c_str(), x.link().c_str(), x.pubDate().c_str(), x.pubDate_timestamp(), x.description().c_str());
feed.items().push_back(x);
}
mrss_free(mrss);
return feed;
}
// rss_item setters
void rss_item::set_title(const std::string& t) {
title_ = t;
}
void rss_item::set_link(const std::string& l) {
link_ = l;
}
void rss_item::set_author(const std::string& a) {
author_ = a;
}
void rss_item::set_description(const std::string& d) {
description_ = d;
}
void rss_item::set_pubDate(time_t t) {
pubDate_ = t;
}
void rss_item::set_guid(const std::string& g) {
guid_ = g;
}
void rss_item::set_unread(bool u) {
if (unread_ != u) {
unread_ = u;
if (ch) ch->update_rssitem_unread_and_enqueued(*this, feedurl_);
}
}
std::string rss_item::pubDate() const {
char text[1024];
strftime(text,sizeof(text),"%a, %d %b %Y %T", gmtime(&pubDate_));
return std::string(text);
}
unsigned int rss_feed::unread_item_count() const {
unsigned int count = 0;
for (std::vector<rss_item>::const_iterator it=items_.begin();it!=items_.end();++it) {
if (it->unread())
++count;
}
return count;
}
time_t rss_parser::parse_date(const std::string& datestr) {
// TODO: refactor
std::istringstream is(datestr);
std::string monthstr, time, tmp;
struct tm stm;
memset(&stm,0,sizeof(stm));
is >> tmp;
if (tmp[tmp.length()-1] == ',')
is >> tmp;
std::istringstream dayis(tmp);
dayis >> stm.tm_mday;
is >> monthstr;
if (monthstr == "Jan")
stm.tm_mon = 0;
else if (monthstr == "Feb")
stm.tm_mon = 1;
else if (monthstr == "Mar")
stm.tm_mon = 2;
else if (monthstr == "Apr")
stm.tm_mon = 3;
else if (monthstr == "May")
stm.tm_mon = 4;
else if (monthstr == "Jun")
stm.tm_mon = 5;
else if (monthstr == "Jul")
stm.tm_mon = 6;
else if (monthstr == "Aug")
stm.tm_mon = 7;
else if (monthstr == "Sep")
stm.tm_mon = 8;
else if (monthstr == "Oct")
stm.tm_mon = 9;
else if (monthstr == "Nov")
stm.tm_mon = 10;
else if (monthstr == "Dec")
stm.tm_mon = 11;
int year;
is >> year;
stm.tm_year = year - 1900;
is >> time;
stm.tm_hour = stm.tm_min = stm.tm_sec = 0;
std::vector<std::string> tkns = utils::tokenize(time,":");
if (tkns.size() > 0) {
std::istringstream hs(tkns[0]);
hs >> stm.tm_hour;
if (tkns.size() > 1) {
std::istringstream ms(tkns[1]);
ms >> stm.tm_min;
if (tkns.size() > 2) {
std::istringstream ss(tkns[2]);
ss >> stm.tm_sec;
}
}
}
time_t value = mktime(&stm);
return value;
}
bool rss_feed::matches_tag(const std::string& tag) {
for (std::vector<std::string>::iterator it=tags_.begin();it!=tags_.end();++it) {
if (tag == *it)
return true;
}
return false;
}
std::string rss_feed::get_tags() {
std::string tags;
for (std::vector<std::string>::iterator it=tags_.begin();it!=tags_.end();++it) {
tags.append(*it);
tags.append(" ");
}
return tags;
}
void rss_feed::set_tags(const std::vector<std::string>& tags) {
if (tags_.size() > 0)
tags_.erase(tags_.begin(), tags_.end());
for (std::vector<std::string>::const_iterator it=tags.begin();it!=tags.end();++it) {
tags_.push_back(*it);
}
}
void rss_item::set_enclosure_url(const std::string& url) {
enclosure_url_ = url;
}
void rss_item::set_enclosure_type(const std::string& type) {
enclosure_type_ = type;
}
<commit_msg>Andreas Krennmair: fixed crash when a totally empty item was found (thanks for Jochen Schweizer for pointing me to this bug).<commit_after>#include <rss.h>
#include <config.h>
#include <stringprep.h>
#include <cache.h>
#include <xmlpullparser.h>
#include <utils.h>
#include <logger.h>
#include <sstream>
#include <iostream>
#include <configcontainer.h>
using namespace newsbeuter;
rss_parser::rss_parser(const char * uri, cache * c, configcontainer * cfg) : my_uri(uri), ch(c), cfgcont(cfg), mrss(0) { }
rss_parser::~rss_parser() { }
rss_feed rss_parser::parse() {
rss_feed feed(ch);
feed.set_rssurl(my_uri);
char * proxy = NULL;
char * proxy_auth = NULL;
if (cfgcont->get_configvalue_as_bool("use-proxy") == true) {
proxy = const_cast<char *>(cfgcont->get_configvalue("proxy").c_str());
proxy_auth = const_cast<char *>(cfgcont->get_configvalue("proxy-auth").c_str());
}
mrss_options_t * options = mrss_options_new(30, proxy, proxy_auth, NULL, NULL, NULL, 0, NULL, USER_AGENT);
mrss_error_t err = mrss_parse_url_with_options(const_cast<char *>(my_uri.c_str()), &mrss, options);
mrss_options_free(options);
if (err != MRSS_OK) {
GetLogger().log(LOG_ERROR,"rss_parser::parse: mrss_parse_url_with_options failed: err = %s (%d)",mrss_strerror(err), err);
if (mrss) {
mrss_free(mrss);
}
throw std::string(mrss_strerror(err));
}
const char * encoding = mrss->encoding ? mrss->encoding : "utf-8";
if (mrss->title) {
char * str = stringprep_convert(mrss->title, stringprep_locale_charset(), encoding);
if (str) {
feed.set_title(str);
free(str);
}
}
if (mrss->description) {
char * str = stringprep_convert(mrss->description, stringprep_locale_charset(), encoding);
if (str) {
feed.set_description(str);
free(str);
}
}
if (mrss->link) feed.set_link(mrss->link);
if (mrss->pubDate)
feed.set_pubDate(parse_date(mrss->pubDate));
else
feed.set_pubDate(::time(NULL));
GetLogger().log(LOG_DEBUG, "rss_parser::parse: feed title = `%s' link = `%s'", feed.title().c_str(), feed.link().c_str());
for (mrss_item_t * item = mrss->item; item != NULL; item = item->next ) {
rss_item x(ch);
if (item->title) {
char * str = stringprep_convert(item->title,stringprep_locale_charset(), encoding);
if (str) {
x.set_title(str);
free(str);
}
}
if (item->link) x.set_link(item->link);
if (item->author) x.set_author(item->author);
mrss_tag_t * content;
if (mrss->version == MRSS_VERSION_2_0 && mrss_search_tag(item, "encoded", "http://purl.org/rss/1.0/modules/content/", &content) == MRSS_OK && content) {
/* RSS 2.0 content:encoded */
GetLogger().log(LOG_DEBUG, "rss_parser::parse: found rss 2.0 content:encoded: %s\n", content->value);
if (content->value) {
char * str = stringprep_convert(content->value, stringprep_locale_charset(), encoding);
if (str) {
x.set_description(str);
free(str);
GetLogger().log(LOG_DEBUG, "rss_parser::parse: conversion was successful: %s\n", x.description().c_str());
} else {
GetLogger().log(LOG_WARN, "rss_parser::parse: stringprep_convert() failed for %s, but trying anyway...", x.link().c_str());
x.set_description(content->value);
}
}
} else {
GetLogger().log(LOG_DEBUG, "rss_parser::parse: found no rss 2.0 content:encoded");
}
if ((mrss->version == MRSS_VERSION_ATOM_0_3 || mrss->version == MRSS_VERSION_ATOM_1_0)) {
int rc;
if (((rc = mrss_search_tag(item, "content", "http://www.w3.org/2005/Atom", &content)) == MRSS_OK && content) ||
((rc = mrss_search_tag(item, "content", "http://purl.org/atom/ns#", &content)) == MRSS_OK && content)) {
GetLogger().log(LOG_DEBUG, "rss_parser::parse: found atom content: %s\n", content ? content->value : "(content = null)");
if (content && content->value) {
char * str = stringprep_convert(content->value, stringprep_locale_charset(), encoding);
if (str) {
x.set_description(str);
free(str);
} else {
x.set_description(content->value);
}
}
} else {
GetLogger().log(LOG_DEBUG, "rss_parser::parse: mrss_search_tag(content) failed with rc = %d content = %p", rc, content);
}
} else {
GetLogger().log(LOG_DEBUG, "rss_parser::parse: not an atom feed");
}
/* last resort: search for itunes:summary tag (may be a podcast) */
if (x.description().length() == 0 && mrss_search_tag(item, "summary", "http://www.itunes.com/dtds/podcast-1.0.dtd", &content) == MRSS_OK && content) {
GetLogger().log(LOG_DEBUG, "rss_parser::parse: found itunes:summary: %s\n", content->value);
if (content->value) {
char * str = stringprep_convert(content->value, stringprep_locale_charset(), encoding);
if (str) {
std::string desc = "<pre>";
desc.append(str);
desc.append("</pre>");
x.set_description(desc);
free(str);
GetLogger().log(LOG_DEBUG, "rss_parser::parse: conversion was successful: %s\n", x.description().c_str());
} else {
GetLogger().log(LOG_WARN, "rss_parser::parse: stringprep_convert() failed for %s, but trying anyway...", x.link().c_str());
x.set_description(content->value);
}
}
} else {
GetLogger().log(LOG_DEBUG, "rss_parser::parse: no luck with itunes:summary");
}
if (x.description().length() == 0 && item->description) {
char * str = stringprep_convert(item->description,stringprep_locale_charset(), encoding);
if (str) {
x.set_description(str);
free(str);
}
}
if (item->pubDate)
x.set_pubDate(parse_date(item->pubDate));
else
x.set_pubDate(::time(NULL));
if (item->guid)
x.set_guid(item->guid);
else if (item->link)
x.set_guid(item->link); // XXX hash something to get a better alternative GUID
else if (item->title)
x.set_guid(item->title);
// ...else?! that's too bad.
if (item->enclosure_url) {
x.set_enclosure_url(item->enclosure_url);
GetLogger().log(LOG_DEBUG, "rss_parser::parse: found enclosure_url: %s", item->enclosure_url);
}
if (item->enclosure_type) {
x.set_enclosure_type(item->enclosure_type);
GetLogger().log(LOG_DEBUG, "rss_parser::parse: found enclosure_type: %s", item->enclosure_type);
}
GetLogger().log(LOG_DEBUG, "rss_parser::parse: item title = `%s' link = `%s' pubDate = `%s' (%d) description = `%s'",
x.title().c_str(), x.link().c_str(), x.pubDate().c_str(), x.pubDate_timestamp(), x.description().c_str());
feed.items().push_back(x);
}
mrss_free(mrss);
return feed;
}
// rss_item setters
void rss_item::set_title(const std::string& t) {
title_ = t;
}
void rss_item::set_link(const std::string& l) {
link_ = l;
}
void rss_item::set_author(const std::string& a) {
author_ = a;
}
void rss_item::set_description(const std::string& d) {
description_ = d;
}
void rss_item::set_pubDate(time_t t) {
pubDate_ = t;
}
void rss_item::set_guid(const std::string& g) {
guid_ = g;
}
void rss_item::set_unread(bool u) {
if (unread_ != u) {
unread_ = u;
if (ch) ch->update_rssitem_unread_and_enqueued(*this, feedurl_);
}
}
std::string rss_item::pubDate() const {
char text[1024];
strftime(text,sizeof(text),"%a, %d %b %Y %T", gmtime(&pubDate_));
return std::string(text);
}
unsigned int rss_feed::unread_item_count() const {
unsigned int count = 0;
for (std::vector<rss_item>::const_iterator it=items_.begin();it!=items_.end();++it) {
if (it->unread())
++count;
}
return count;
}
time_t rss_parser::parse_date(const std::string& datestr) {
// TODO: refactor
std::istringstream is(datestr);
std::string monthstr, time, tmp;
struct tm stm;
memset(&stm,0,sizeof(stm));
is >> tmp;
if (tmp[tmp.length()-1] == ',')
is >> tmp;
std::istringstream dayis(tmp);
dayis >> stm.tm_mday;
is >> monthstr;
if (monthstr == "Jan")
stm.tm_mon = 0;
else if (monthstr == "Feb")
stm.tm_mon = 1;
else if (monthstr == "Mar")
stm.tm_mon = 2;
else if (monthstr == "Apr")
stm.tm_mon = 3;
else if (monthstr == "May")
stm.tm_mon = 4;
else if (monthstr == "Jun")
stm.tm_mon = 5;
else if (monthstr == "Jul")
stm.tm_mon = 6;
else if (monthstr == "Aug")
stm.tm_mon = 7;
else if (monthstr == "Sep")
stm.tm_mon = 8;
else if (monthstr == "Oct")
stm.tm_mon = 9;
else if (monthstr == "Nov")
stm.tm_mon = 10;
else if (monthstr == "Dec")
stm.tm_mon = 11;
int year;
is >> year;
stm.tm_year = year - 1900;
is >> time;
stm.tm_hour = stm.tm_min = stm.tm_sec = 0;
std::vector<std::string> tkns = utils::tokenize(time,":");
if (tkns.size() > 0) {
std::istringstream hs(tkns[0]);
hs >> stm.tm_hour;
if (tkns.size() > 1) {
std::istringstream ms(tkns[1]);
ms >> stm.tm_min;
if (tkns.size() > 2) {
std::istringstream ss(tkns[2]);
ss >> stm.tm_sec;
}
}
}
time_t value = mktime(&stm);
return value;
}
bool rss_feed::matches_tag(const std::string& tag) {
for (std::vector<std::string>::iterator it=tags_.begin();it!=tags_.end();++it) {
if (tag == *it)
return true;
}
return false;
}
std::string rss_feed::get_tags() {
std::string tags;
for (std::vector<std::string>::iterator it=tags_.begin();it!=tags_.end();++it) {
tags.append(*it);
tags.append(" ");
}
return tags;
}
void rss_feed::set_tags(const std::vector<std::string>& tags) {
if (tags_.size() > 0)
tags_.erase(tags_.begin(), tags_.end());
for (std::vector<std::string>::const_iterator it=tags.begin();it!=tags.end();++it) {
tags_.push_back(*it);
}
}
void rss_item::set_enclosure_url(const std::string& url) {
enclosure_url_ = url;
}
void rss_item::set_enclosure_type(const std::string& type) {
enclosure_type_ = type;
}
<|endoftext|> |
<commit_before>//===- DWARFDebugLoc.cpp --------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/DWARF/DWARFDebugLoc.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/BinaryFormat/Dwarf.h"
#include "llvm/DebugInfo/DWARF/DWARFContext.h"
#include "llvm/DebugInfo/DWARF/DWARFExpression.h"
#include "llvm/DebugInfo/DWARF/DWARFRelocMap.h"
#include "llvm/DebugInfo/DWARF/DWARFUnit.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/WithColor.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cinttypes>
#include <cstdint>
using namespace llvm;
// When directly dumping the .debug_loc without a compile unit, we have to guess
// at the DWARF version. This only affects DW_OP_call_ref, which is a rare
// expression that LLVM doesn't produce. Guessing the wrong version means we
// won't be able to pretty print expressions in DWARF2 binaries produced by
// non-LLVM tools.
static void dumpExpression(raw_ostream &OS, ArrayRef<char> Data,
bool IsLittleEndian, unsigned AddressSize,
const MCRegisterInfo *MRI) {
DWARFDataExtractor Extractor(StringRef(Data.data(), Data.size()),
IsLittleEndian, AddressSize);
DWARFExpression(Extractor, dwarf::DWARF_VERSION, AddressSize).print(OS, MRI);
}
void DWARFDebugLoc::LocationList::dump(raw_ostream &OS, bool IsLittleEndian,
unsigned AddressSize,
const MCRegisterInfo *MRI,
uint64_t BaseAddress,
unsigned Indent) const {
for (const Entry &E : Entries) {
OS << '\n';
OS.indent(Indent);
OS << format("[0x%*.*" PRIx64 ", ", AddressSize * 2, AddressSize * 2,
BaseAddress + E.Begin);
OS << format(" 0x%*.*" PRIx64 ")", AddressSize * 2, AddressSize * 2,
BaseAddress + E.End);
OS << ": ";
dumpExpression(OS, E.Loc, IsLittleEndian, AddressSize, MRI);
}
}
DWARFDebugLoc::LocationList const *
DWARFDebugLoc::getLocationListAtOffset(uint64_t Offset) const {
auto It = std::lower_bound(
Locations.begin(), Locations.end(), Offset,
[](const LocationList &L, uint64_t Offset) { return L.Offset < Offset; });
if (It != Locations.end() && It->Offset == Offset)
return &(*It);
return nullptr;
}
void DWARFDebugLoc::dump(raw_ostream &OS, const MCRegisterInfo *MRI,
Optional<uint64_t> Offset) const {
auto DumpLocationList = [&](const LocationList &L) {
OS << format("0x%8.8x: ", L.Offset);
L.dump(OS, IsLittleEndian, AddressSize, MRI, 0, 12);
OS << "\n\n";
};
if (Offset) {
if (auto *L = getLocationListAtOffset(*Offset))
DumpLocationList(*L);
return;
}
for (const LocationList &L : Locations) {
DumpLocationList(L);
}
}
Optional<DWARFDebugLoc::LocationList>
DWARFDebugLoc::parseOneLocationList(DWARFDataExtractor Data, unsigned *Offset) {
LocationList LL;
LL.Offset = *Offset;
// 2.6.2 Location Lists
// A location list entry consists of:
while (true) {
Entry E;
if (!Data.isValidOffsetForDataOfSize(*Offset, 2 * Data.getAddressSize())) {
WithColor::error() << "location list overflows the debug_loc section.\n";
return None;
}
// 1. A beginning address offset. ...
E.Begin = Data.getRelocatedAddress(Offset);
// 2. An ending address offset. ...
E.End = Data.getRelocatedAddress(Offset);
// The end of any given location list is marked by an end of list entry,
// which consists of a 0 for the beginning address offset and a 0 for the
// ending address offset.
if (E.Begin == 0 && E.End == 0)
return LL;
if (!Data.isValidOffsetForDataOfSize(*Offset, 2)) {
WithColor::error() << "location list overflows the debug_loc section.\n";
return None;
}
unsigned Bytes = Data.getU16(Offset);
if (!Data.isValidOffsetForDataOfSize(*Offset, Bytes)) {
WithColor::error() << "location list overflows the debug_loc section.\n";
return None;
}
// A single location description describing the location of the object...
StringRef str = Data.getData().substr(*Offset, Bytes);
*Offset += Bytes;
E.Loc.reserve(str.size());
std::copy(str.begin(), str.end(), std::back_inserter(E.Loc));
LL.Entries.push_back(std::move(E));
}
}
void DWARFDebugLoc::parse(const DWARFDataExtractor &data) {
IsLittleEndian = data.isLittleEndian();
AddressSize = data.getAddressSize();
uint32_t Offset = 0;
while (data.isValidOffset(Offset + data.getAddressSize() - 1)) {
if (auto LL = parseOneLocationList(data, &Offset))
Locations.push_back(std::move(*LL));
else
break;
}
if (data.isValidOffset(Offset))
WithColor::error() << "failed to consume entire .debug_loc section\n";
}
Optional<DWARFDebugLoclists::LocationList>
DWARFDebugLoclists::parseOneLocationList(DataExtractor Data, unsigned *Offset,
unsigned Version) {
LocationList LL;
LL.Offset = *Offset;
// dwarf::DW_LLE_end_of_list_entry is 0 and indicates the end of the list.
while (auto Kind =
static_cast<dwarf::LocationListEntry>(Data.getU8(Offset))) {
Entry E;
E.Kind = Kind;
switch (Kind) {
case dwarf::DW_LLE_startx_length:
E.Value0 = Data.getULEB128(Offset);
// Pre-DWARF 5 has different interpretation of the length field. We have
// to support both pre- and standartized styles for the compatibility.
if (Version < 5)
E.Value1 = Data.getU32(Offset);
else
E.Value1 = Data.getULEB128(Offset);
break;
case dwarf::DW_LLE_start_length:
E.Value0 = Data.getAddress(Offset);
E.Value1 = Data.getULEB128(Offset);
break;
case dwarf::DW_LLE_offset_pair:
E.Value0 = Data.getULEB128(Offset);
E.Value1 = Data.getULEB128(Offset);
break;
case dwarf::DW_LLE_base_address:
E.Value0 = Data.getAddress(Offset);
break;
default:
WithColor::error() << "dumping support for LLE of kind " << (int)Kind
<< " not implemented\n";
return None;
}
if (Kind != dwarf::DW_LLE_base_address) {
unsigned Bytes = Data.getU16(Offset);
// A single location description describing the location of the object...
StringRef str = Data.getData().substr(*Offset, Bytes);
*Offset += Bytes;
E.Loc.resize(str.size());
std::copy(str.begin(), str.end(), E.Loc.begin());
}
LL.Entries.push_back(std::move(E));
}
return LL;
}
void DWARFDebugLoclists::parse(DataExtractor data, unsigned Version) {
IsLittleEndian = data.isLittleEndian();
AddressSize = data.getAddressSize();
uint32_t Offset = 0;
while (data.isValidOffset(Offset)) {
if (auto LL = parseOneLocationList(data, &Offset, Version))
Locations.push_back(std::move(*LL));
else
return;
}
}
DWARFDebugLoclists::LocationList const *
DWARFDebugLoclists::getLocationListAtOffset(uint64_t Offset) const {
auto It = std::lower_bound(
Locations.begin(), Locations.end(), Offset,
[](const LocationList &L, uint64_t Offset) { return L.Offset < Offset; });
if (It != Locations.end() && It->Offset == Offset)
return &(*It);
return nullptr;
}
void DWARFDebugLoclists::LocationList::dump(raw_ostream &OS, uint64_t BaseAddr,
bool IsLittleEndian,
unsigned AddressSize,
const MCRegisterInfo *MRI,
unsigned Indent) const {
for (const Entry &E : Entries) {
switch (E.Kind) {
case dwarf::DW_LLE_startx_length:
OS << '\n';
OS.indent(Indent);
OS << "Addr idx " << E.Value0 << " (w/ length " << E.Value1 << "): ";
break;
case dwarf::DW_LLE_start_length:
OS << '\n';
OS.indent(Indent);
OS << format("[0x%*.*" PRIx64 ", 0x%*.*x): ", AddressSize * 2,
AddressSize * 2, E.Value0, AddressSize * 2, AddressSize * 2,
E.Value0 + E.Value1);
break;
case dwarf::DW_LLE_offset_pair:
OS << '\n';
OS.indent(Indent);
OS << format("[0x%*.*" PRIx64 ", 0x%*.*x): ", AddressSize * 2,
AddressSize * 2, BaseAddr + E.Value0, AddressSize * 2,
AddressSize * 2, BaseAddr + E.Value1);
break;
case dwarf::DW_LLE_base_address:
BaseAddr = E.Value0;
break;
default:
llvm_unreachable("unreachable locations list kind");
}
dumpExpression(OS, E.Loc, IsLittleEndian, AddressSize, MRI);
}
}
void DWARFDebugLoclists::dump(raw_ostream &OS, uint64_t BaseAddr,
const MCRegisterInfo *MRI,
Optional<uint64_t> Offset) const {
auto DumpLocationList = [&](const LocationList &L) {
OS << format("0x%8.8x: ", L.Offset);
L.dump(OS, BaseAddr, IsLittleEndian, AddressSize, MRI, /*Indent=*/12);
OS << "\n\n";
};
if (Offset) {
if (auto *L = getLocationListAtOffset(*Offset))
DumpLocationList(*L);
return;
}
for (const LocationList &L : Locations) {
DumpLocationList(L);
}
}
<commit_msg>[DWARF] Use PRIx64 instead of 'x' to format 64-bit values<commit_after>//===- DWARFDebugLoc.cpp --------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/DWARF/DWARFDebugLoc.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/BinaryFormat/Dwarf.h"
#include "llvm/DebugInfo/DWARF/DWARFContext.h"
#include "llvm/DebugInfo/DWARF/DWARFExpression.h"
#include "llvm/DebugInfo/DWARF/DWARFRelocMap.h"
#include "llvm/DebugInfo/DWARF/DWARFUnit.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/WithColor.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cinttypes>
#include <cstdint>
using namespace llvm;
// When directly dumping the .debug_loc without a compile unit, we have to guess
// at the DWARF version. This only affects DW_OP_call_ref, which is a rare
// expression that LLVM doesn't produce. Guessing the wrong version means we
// won't be able to pretty print expressions in DWARF2 binaries produced by
// non-LLVM tools.
static void dumpExpression(raw_ostream &OS, ArrayRef<char> Data,
bool IsLittleEndian, unsigned AddressSize,
const MCRegisterInfo *MRI) {
DWARFDataExtractor Extractor(StringRef(Data.data(), Data.size()),
IsLittleEndian, AddressSize);
DWARFExpression(Extractor, dwarf::DWARF_VERSION, AddressSize).print(OS, MRI);
}
void DWARFDebugLoc::LocationList::dump(raw_ostream &OS, bool IsLittleEndian,
unsigned AddressSize,
const MCRegisterInfo *MRI,
uint64_t BaseAddress,
unsigned Indent) const {
for (const Entry &E : Entries) {
OS << '\n';
OS.indent(Indent);
OS << format("[0x%*.*" PRIx64 ", ", AddressSize * 2, AddressSize * 2,
BaseAddress + E.Begin);
OS << format(" 0x%*.*" PRIx64 ")", AddressSize * 2, AddressSize * 2,
BaseAddress + E.End);
OS << ": ";
dumpExpression(OS, E.Loc, IsLittleEndian, AddressSize, MRI);
}
}
DWARFDebugLoc::LocationList const *
DWARFDebugLoc::getLocationListAtOffset(uint64_t Offset) const {
auto It = std::lower_bound(
Locations.begin(), Locations.end(), Offset,
[](const LocationList &L, uint64_t Offset) { return L.Offset < Offset; });
if (It != Locations.end() && It->Offset == Offset)
return &(*It);
return nullptr;
}
void DWARFDebugLoc::dump(raw_ostream &OS, const MCRegisterInfo *MRI,
Optional<uint64_t> Offset) const {
auto DumpLocationList = [&](const LocationList &L) {
OS << format("0x%8.8x: ", L.Offset);
L.dump(OS, IsLittleEndian, AddressSize, MRI, 0, 12);
OS << "\n\n";
};
if (Offset) {
if (auto *L = getLocationListAtOffset(*Offset))
DumpLocationList(*L);
return;
}
for (const LocationList &L : Locations) {
DumpLocationList(L);
}
}
Optional<DWARFDebugLoc::LocationList>
DWARFDebugLoc::parseOneLocationList(DWARFDataExtractor Data, unsigned *Offset) {
LocationList LL;
LL.Offset = *Offset;
// 2.6.2 Location Lists
// A location list entry consists of:
while (true) {
Entry E;
if (!Data.isValidOffsetForDataOfSize(*Offset, 2 * Data.getAddressSize())) {
WithColor::error() << "location list overflows the debug_loc section.\n";
return None;
}
// 1. A beginning address offset. ...
E.Begin = Data.getRelocatedAddress(Offset);
// 2. An ending address offset. ...
E.End = Data.getRelocatedAddress(Offset);
// The end of any given location list is marked by an end of list entry,
// which consists of a 0 for the beginning address offset and a 0 for the
// ending address offset.
if (E.Begin == 0 && E.End == 0)
return LL;
if (!Data.isValidOffsetForDataOfSize(*Offset, 2)) {
WithColor::error() << "location list overflows the debug_loc section.\n";
return None;
}
unsigned Bytes = Data.getU16(Offset);
if (!Data.isValidOffsetForDataOfSize(*Offset, Bytes)) {
WithColor::error() << "location list overflows the debug_loc section.\n";
return None;
}
// A single location description describing the location of the object...
StringRef str = Data.getData().substr(*Offset, Bytes);
*Offset += Bytes;
E.Loc.reserve(str.size());
std::copy(str.begin(), str.end(), std::back_inserter(E.Loc));
LL.Entries.push_back(std::move(E));
}
}
void DWARFDebugLoc::parse(const DWARFDataExtractor &data) {
IsLittleEndian = data.isLittleEndian();
AddressSize = data.getAddressSize();
uint32_t Offset = 0;
while (data.isValidOffset(Offset + data.getAddressSize() - 1)) {
if (auto LL = parseOneLocationList(data, &Offset))
Locations.push_back(std::move(*LL));
else
break;
}
if (data.isValidOffset(Offset))
WithColor::error() << "failed to consume entire .debug_loc section\n";
}
Optional<DWARFDebugLoclists::LocationList>
DWARFDebugLoclists::parseOneLocationList(DataExtractor Data, unsigned *Offset,
unsigned Version) {
LocationList LL;
LL.Offset = *Offset;
// dwarf::DW_LLE_end_of_list_entry is 0 and indicates the end of the list.
while (auto Kind =
static_cast<dwarf::LocationListEntry>(Data.getU8(Offset))) {
Entry E;
E.Kind = Kind;
switch (Kind) {
case dwarf::DW_LLE_startx_length:
E.Value0 = Data.getULEB128(Offset);
// Pre-DWARF 5 has different interpretation of the length field. We have
// to support both pre- and standartized styles for the compatibility.
if (Version < 5)
E.Value1 = Data.getU32(Offset);
else
E.Value1 = Data.getULEB128(Offset);
break;
case dwarf::DW_LLE_start_length:
E.Value0 = Data.getAddress(Offset);
E.Value1 = Data.getULEB128(Offset);
break;
case dwarf::DW_LLE_offset_pair:
E.Value0 = Data.getULEB128(Offset);
E.Value1 = Data.getULEB128(Offset);
break;
case dwarf::DW_LLE_base_address:
E.Value0 = Data.getAddress(Offset);
break;
default:
WithColor::error() << "dumping support for LLE of kind " << (int)Kind
<< " not implemented\n";
return None;
}
if (Kind != dwarf::DW_LLE_base_address) {
unsigned Bytes = Data.getU16(Offset);
// A single location description describing the location of the object...
StringRef str = Data.getData().substr(*Offset, Bytes);
*Offset += Bytes;
E.Loc.resize(str.size());
std::copy(str.begin(), str.end(), E.Loc.begin());
}
LL.Entries.push_back(std::move(E));
}
return LL;
}
void DWARFDebugLoclists::parse(DataExtractor data, unsigned Version) {
IsLittleEndian = data.isLittleEndian();
AddressSize = data.getAddressSize();
uint32_t Offset = 0;
while (data.isValidOffset(Offset)) {
if (auto LL = parseOneLocationList(data, &Offset, Version))
Locations.push_back(std::move(*LL));
else
return;
}
}
DWARFDebugLoclists::LocationList const *
DWARFDebugLoclists::getLocationListAtOffset(uint64_t Offset) const {
auto It = std::lower_bound(
Locations.begin(), Locations.end(), Offset,
[](const LocationList &L, uint64_t Offset) { return L.Offset < Offset; });
if (It != Locations.end() && It->Offset == Offset)
return &(*It);
return nullptr;
}
void DWARFDebugLoclists::LocationList::dump(raw_ostream &OS, uint64_t BaseAddr,
bool IsLittleEndian,
unsigned AddressSize,
const MCRegisterInfo *MRI,
unsigned Indent) const {
for (const Entry &E : Entries) {
switch (E.Kind) {
case dwarf::DW_LLE_startx_length:
OS << '\n';
OS.indent(Indent);
OS << "Addr idx " << E.Value0 << " (w/ length " << E.Value1 << "): ";
break;
case dwarf::DW_LLE_start_length:
OS << '\n';
OS.indent(Indent);
OS << format("[0x%*.*" PRIx64 ", 0x%*.*" PRIx64 "): ", AddressSize * 2,
AddressSize * 2, E.Value0, AddressSize * 2, AddressSize * 2,
E.Value0 + E.Value1);
break;
case dwarf::DW_LLE_offset_pair:
OS << '\n';
OS.indent(Indent);
OS << format("[0x%*.*" PRIx64 ", 0x%*.*" PRIx64 "): ", AddressSize * 2,
AddressSize * 2, BaseAddr + E.Value0, AddressSize * 2,
AddressSize * 2, BaseAddr + E.Value1);
break;
case dwarf::DW_LLE_base_address:
BaseAddr = E.Value0;
break;
default:
llvm_unreachable("unreachable locations list kind");
}
dumpExpression(OS, E.Loc, IsLittleEndian, AddressSize, MRI);
}
}
void DWARFDebugLoclists::dump(raw_ostream &OS, uint64_t BaseAddr,
const MCRegisterInfo *MRI,
Optional<uint64_t> Offset) const {
auto DumpLocationList = [&](const LocationList &L) {
OS << format("0x%8.8x: ", L.Offset);
L.dump(OS, BaseAddr, IsLittleEndian, AddressSize, MRI, /*Indent=*/12);
OS << "\n\n";
};
if (Offset) {
if (auto *L = getLocationListAtOffset(*Offset))
DumpLocationList(*L);
return;
}
for (const LocationList &L : Locations) {
DumpLocationList(L);
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2009 Nokia Corporation.
*
* Contact: Marius Vollmer <[email protected]>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <QtTest/QtTest>
#include <QtCore>
#include "nanoxml.h"
#include "fileutils.h"
#include "contexttypeinfo.h"
#include "contexttyperegistryinfo.h"
ContextTypeRegistryInfo* ContextTypeRegistryInfo::registryInstance = new ContextTypeRegistryInfo();
/* Mocked ContextTypeRegistryInfo */
ContextTypeRegistryInfo::ContextTypeRegistryInfo()
{
}
ContextTypeRegistryInfo* ContextTypeRegistryInfo::instance()
{
return registryInstance;
}
NanoTree ContextTypeRegistryInfo::typeDefinitionForName(QString name)
{
if (name == "double") {
QVariantList tree;
QVariantList doc;
QVariantList name;
name << QVariant("name");
name << QVariant("double");
doc << QVariant("doc");
doc << QVariant("double doc");
tree << QVariant("type");
tree << QVariant(name);
tree << QVariant(doc);
return ContextTypeInfo(QVariant(tree));
} else if (name == "complex") {
QVariantList tree;
QVariantList doc;
QVariantList base;
QVariantList name;
QVariantList params;
QVariantList p1;
QVariantList p1Doc;
name << QVariant("name");
name << QVariant("complex");
doc << QVariant("doc");
doc << QVariant("complex doc");
base << QVariant("base");
base << QVariant("double");
p1 << QVariant("p1");
p1Doc << QVariant("doc");
p1Doc << QVariant("p1 doc");
p1 << QVariant(p1Doc);
params << QVariant("params");
params << QVariant(p1);
tree << QVariant("type");
tree << QVariant(name);
tree << QVariant(params);
tree << QVariant(doc);
tree << QVariant(base);
return ContextTypeInfo(QVariant(tree));
} else
return ContextTypeInfo();
}
class ContextTypeInfoUnitTest : public QObject
{
Q_OBJECT
private slots:
void name();
void doc();
void base();
void definition();
void parameterDoc();
void ensureNewTypes();
void parameterValue();
};
void ContextTypeInfoUnitTest::name()
{
QCOMPARE(ContextTypeInfo(QString("bool")).name(), QString("bool"));
QCOMPARE(ContextTypeInfo(QString("string")).name(), QString("string"));
QVariantList lst;
lst << QVariant("int32");
QCOMPARE(ContextTypeInfo(QVariant(lst)).name(), QString("int32"));
}
void ContextTypeInfoUnitTest::doc()
{
QCOMPARE(ContextTypeInfo(QString("double")).doc(), QString("double doc"));
}
void ContextTypeInfoUnitTest::definition()
{
NanoTree def = ContextTypeInfo(QString("double")).definition();
QCOMPARE(def.keyValue("name").toString(), QString("double"));
QCOMPARE(def.keyValue("doc").toString(), QString("double doc"));
}
void ContextTypeInfoUnitTest::base()
{
ContextTypeInfo base = ContextTypeInfo(QString("complex")).base();
QCOMPARE(base.name(), QString("double"));
QCOMPARE(base.doc(), QString("double doc"));
}
void ContextTypeInfoUnitTest::parameterDoc()
{
ContextTypeInfo typeInfo = ContextTypeInfo(QString("complex"));
QCOMPARE(typeInfo.parameterDoc("p1"), QString("p1 doc"));
}
void ContextTypeInfoUnitTest::ensureNewTypes()
{
QCOMPARE(ContextTypeInfo(QString("INTEGER")).ensureNewTypes().name(), QString("int32"));
QCOMPARE(ContextTypeInfo(QString("INT")).ensureNewTypes().name(), QString("int32"));
QCOMPARE(ContextTypeInfo(QString("TRUTH")).ensureNewTypes().name(), QString("bool"));
QCOMPARE(ContextTypeInfo(QString("STRING")).ensureNewTypes().name(), QString("string"));
QCOMPARE(ContextTypeInfo(QString("DOUBLE")).ensureNewTypes().name(), QString("double"));
QCOMPARE(ContextTypeInfo(QString("bool")).ensureNewTypes().name(), QString("bool"));
}
void ContextTypeInfoUnitTest::parameterValue()
{
QVariantList lst;
QVariantList minParam;
lst << QVariant("complex");
minParam << QVariant("min");
minParam << QVariant("0");
lst << QVariant(minParam);
QVariant tree(lst);
ContextTypeInfo typeInfo(tree);
QCOMPARE(typeInfo.parameterValue("min").toString(), QString("0"));
}
#include "contexttypeinfounittest.moc"
QTEST_MAIN(ContextTypeInfoUnitTest);
<commit_msg>ContextTypeInfo::parameterSub unit test.<commit_after>/*
* Copyright (C) 2009 Nokia Corporation.
*
* Contact: Marius Vollmer <[email protected]>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <QtTest/QtTest>
#include <QtCore>
#include "nanoxml.h"
#include "fileutils.h"
#include "contexttypeinfo.h"
#include "contexttyperegistryinfo.h"
ContextTypeRegistryInfo* ContextTypeRegistryInfo::registryInstance = new ContextTypeRegistryInfo();
/* Mocked ContextTypeRegistryInfo */
ContextTypeRegistryInfo::ContextTypeRegistryInfo()
{
}
ContextTypeRegistryInfo* ContextTypeRegistryInfo::instance()
{
return registryInstance;
}
NanoTree ContextTypeRegistryInfo::typeDefinitionForName(QString name)
{
if (name == "double") {
QVariantList tree;
QVariantList doc;
QVariantList name;
name << QVariant("name");
name << QVariant("double");
doc << QVariant("doc");
doc << QVariant("double doc");
tree << QVariant("type");
tree << QVariant(name);
tree << QVariant(doc);
return ContextTypeInfo(QVariant(tree));
} else if (name == "complex") {
QVariantList tree;
QVariantList doc;
QVariantList base;
QVariantList name;
QVariantList params;
QVariantList p1;
QVariantList p1Doc;
name << QVariant("name");
name << QVariant("complex");
doc << QVariant("doc");
doc << QVariant("complex doc");
base << QVariant("base");
base << QVariant("double");
p1 << QVariant("p1");
p1Doc << QVariant("doc");
p1Doc << QVariant("p1 doc");
p1 << QVariant(p1Doc);
params << QVariant("params");
params << QVariant(p1);
tree << QVariant("type");
tree << QVariant(name);
tree << QVariant(params);
tree << QVariant(doc);
tree << QVariant(base);
return ContextTypeInfo(QVariant(tree));
} else
return ContextTypeInfo();
}
class ContextTypeInfoUnitTest : public QObject
{
Q_OBJECT
private slots:
void name();
void doc();
void base();
void definition();
void parameterDoc();
void ensureNewTypes();
void parameterValue();
void parameterSub();
};
void ContextTypeInfoUnitTest::name()
{
QCOMPARE(ContextTypeInfo(QString("bool")).name(), QString("bool"));
QCOMPARE(ContextTypeInfo(QString("string")).name(), QString("string"));
QVariantList lst;
lst << QVariant("int32");
QCOMPARE(ContextTypeInfo(QVariant(lst)).name(), QString("int32"));
}
void ContextTypeInfoUnitTest::doc()
{
QCOMPARE(ContextTypeInfo(QString("double")).doc(), QString("double doc"));
}
void ContextTypeInfoUnitTest::definition()
{
NanoTree def = ContextTypeInfo(QString("double")).definition();
QCOMPARE(def.keyValue("name").toString(), QString("double"));
QCOMPARE(def.keyValue("doc").toString(), QString("double doc"));
}
void ContextTypeInfoUnitTest::base()
{
ContextTypeInfo base = ContextTypeInfo(QString("complex")).base();
QCOMPARE(base.name(), QString("double"));
QCOMPARE(base.doc(), QString("double doc"));
}
void ContextTypeInfoUnitTest::parameterDoc()
{
ContextTypeInfo typeInfo = ContextTypeInfo(QString("complex"));
QCOMPARE(typeInfo.parameterDoc("p1"), QString("p1 doc"));
}
void ContextTypeInfoUnitTest::ensureNewTypes()
{
QCOMPARE(ContextTypeInfo(QString("INTEGER")).ensureNewTypes().name(), QString("int32"));
QCOMPARE(ContextTypeInfo(QString("INT")).ensureNewTypes().name(), QString("int32"));
QCOMPARE(ContextTypeInfo(QString("TRUTH")).ensureNewTypes().name(), QString("bool"));
QCOMPARE(ContextTypeInfo(QString("STRING")).ensureNewTypes().name(), QString("string"));
QCOMPARE(ContextTypeInfo(QString("DOUBLE")).ensureNewTypes().name(), QString("double"));
QCOMPARE(ContextTypeInfo(QString("bool")).ensureNewTypes().name(), QString("bool"));
}
void ContextTypeInfoUnitTest::parameterValue()
{
QVariantList lst;
QVariantList minParam;
lst << QVariant("complex");
minParam << QVariant("min");
minParam << QVariant("0");
lst << QVariant(minParam);
QVariant tree(lst);
ContextTypeInfo typeInfo(tree);
QCOMPARE(typeInfo.parameterValue("min").toString(), QString("0"));
}
void ContextTypeInfoUnitTest::parameterSub()
{
QVariantList lst;
QVariantList minParam;
lst << QVariant("complex");
minParam << QVariant("min");
minParam << QVariant("0");
lst << QVariant(minParam);
QVariant tree(lst);
ContextTypeInfo typeInfo(tree);
QCOMPARE(typeInfo.parameterSub("min").toList().at(0).toString(), QString("0"));
}
#include "contexttypeinfounittest.moc"
QTEST_MAIN(ContextTypeInfoUnitTest);
<|endoftext|> |
<commit_before><commit_msg>#79344# service name corrected; revision log removed<commit_after><|endoftext|> |
<commit_before>#ifndef __SOTA_AST__
#define __SOTA_AST__ = 1
#include <string>
#include <vector>
#include <iostream>
#include "z2h/ast.hpp"
#include "z2h/token.hpp"
namespace sota {
inline void sepby(std::ostream &os, std::string sep, std::vector<z2h::Ast *> items) {
if (items.size()) {
size_t i = 0;
for (; i < items.size() - 1; ++i) {
os << *items[i] << sep;
}
os << *items[i];
}
}
struct NewlineAst : public z2h::Ast {
~NewlineAst() {}
NewlineAst(z2h::Token *token)
: z2h::Ast(token) {}
protected:
void Print(std::ostream &os) const {
os << "(nl " + token->value + ")";
}
};
struct IdentifierAst : public z2h::Ast {
~IdentifierAst() {}
IdentifierAst(z2h::Token *token)
: z2h::Ast(token) {}
protected:
void Print(std::ostream &os) const {
os << "(id " + token->value + ")";
}
};
struct NumberAst : public z2h::Ast {
~NumberAst() {}
NumberAst(z2h::Token *token)
: z2h::Ast(token) {}
protected:
void Print(std::ostream &os) const {
os << "(num " + token->value + ")";
}
};
struct ExpressionsAst : public z2h::Ast {
std::vector<z2h::Ast *> expressions;
~ExpressionsAst() {}
ExpressionsAst(std::vector<z2h::Ast *> expressions) {
for (auto expression : expressions)
this->expressions.push_back(expression);
}
protected:
void Print(std::ostream &os) const {
os << "( ";
sepby(os, " ", expressions);
os << " )";
}
};
struct ParensAst : public ExpressionsAst {
~ParensAst() {}
ParensAst(std::vector<z2h::Ast *> expressions)
: ExpressionsAst(expressions) {}
protected:
void Print(std::ostream &os) const {
os << "(() ";
sepby(os, " ", expressions);
os << " )";
}
};
struct InfixAst : public z2h::Ast {
z2h::Ast *left;
z2h::Ast *right;
~InfixAst() {}
InfixAst(z2h::Token *token, z2h::Ast *left, z2h::Ast *right)
: z2h::Ast(token)
, left(left)
, right(right) {}
protected:
void Print(std::ostream &os) const {
os << "(" + token->value + " " << *left << " " << *right << ")";
}
};
struct PrefixAst : public z2h::Ast {
z2h::Ast *right;
~PrefixAst() {}
PrefixAst(z2h::Token *token, z2h::Ast *right)
: z2h::Ast(token)
, right(right) {}
protected:
void Print(std::ostream &os) const {
os << "(" + token->value + " " << *right << ")";
}
};
struct AssignAst : public z2h::Ast {
z2h::Ast *left;
z2h::Ast *right;
~AssignAst() {}
AssignAst(z2h::Token *token, z2h::Ast *left, z2h::Ast *right)
: z2h::Ast(token)
, left(left)
, right(right) {}
protected:
void Print(std::ostream &os) const {
os << "(" + token->value + " " << *left << " " << *right << ")";
}
};
struct FuncAst : public z2h::Ast {
z2h::Ast *args;
z2h::Ast *body;
~FuncAst() {}
FuncAst(z2h::Token *token, z2h::Ast *args, z2h::Ast *body)
: z2h::Ast(token)
, args(args)
, body(body) {}
protected:
void Print(std::ostream &os) const {
os << "(-> " << *args << " " << *body << ")";
}
};
struct ConditionalAst : public z2h::Ast {
struct Pair {
z2h::Ast *predicate;
z2h::Ast *action;
Pair(z2h::Ast *predicate, z2h::Ast *action)
: predicate(predicate)
, action(action) {}
protected:
friend std::ostream & operator <<(std::ostream &os, const Pair &pair) {
os << "(pair " << *pair.predicate << " " << *pair.action << ")";
return os;
}
};
std::vector<Pair> pairs;
z2h::Ast *action;
~ConditionalAst() {}
ConditionalAst(z2h::Token *token, std::initializer_list<Pair> pairs)
: z2h::Ast(token)
, pairs(pairs)
, action(nullptr) {}
ConditionalAst(z2h::Token *token, std::initializer_list<Pair> pairs, z2h::Ast *action)
: z2h::Ast(token)
, pairs(pairs)
, action(action) {}
protected:
void Print(std::ostream &os) const {
os << "(cond";
for (auto pair : pairs) {
os << " " << pair;
}
if (nullptr != action)
os << " " << *action;
os << ")";
}
};
}
#endif /*__SOTA_AST__*/
<commit_msg>added Braces and Brackets... -sai<commit_after>#ifndef __SOTA_AST__
#define __SOTA_AST__ = 1
#include <string>
#include <vector>
#include <iostream>
#include "z2h/ast.hpp"
#include "z2h/token.hpp"
namespace sota {
inline void sepby(std::ostream &os, std::string sep, std::vector<z2h::Ast *> items) {
if (items.size()) {
size_t i = 0;
for (; i < items.size() - 1; ++i) {
os << *items[i] << sep;
}
os << *items[i];
}
}
struct NewlineAst : public z2h::Ast {
~NewlineAst() {}
NewlineAst(z2h::Token *token)
: z2h::Ast(token) {}
protected:
void Print(std::ostream &os) const {
os << "(nl " + token->value + ")";
}
};
struct IdentifierAst : public z2h::Ast {
~IdentifierAst() {}
IdentifierAst(z2h::Token *token)
: z2h::Ast(token) {}
protected:
void Print(std::ostream &os) const {
os << "(id " + token->value + ")";
}
};
struct NumberAst : public z2h::Ast {
~NumberAst() {}
NumberAst(z2h::Token *token)
: z2h::Ast(token) {}
protected:
void Print(std::ostream &os) const {
os << "(num " + token->value + ")";
}
};
struct ExpressionsAst : public z2h::Ast {
std::vector<z2h::Ast *> expressions;
~ExpressionsAst() {}
ExpressionsAst(std::vector<z2h::Ast *> expressions) {
for (auto expression : expressions)
this->expressions.push_back(expression);
}
protected:
void Print(std::ostream &os) const {
os << "( ";
sepby(os, " ", expressions);
os << ")";
}
};
struct ParensAst : public ExpressionsAst {
~ParensAst() {}
ParensAst(std::vector<z2h::Ast *> expressions)
: ExpressionsAst(expressions) {}
protected:
void Print(std::ostream &os) const {
os << "(() ";
sepby(os, " ", expressions);
os << ")";
}
};
struct BracesAst : public ExpressionsAst {
~BracesAst() {}
BracesAst(std::vector<z2h::Ast *> expressions)
: ExpressionsAst(expressions) {}
protected:
void Print(std::ostream &os) const {
os << "({} ";
sepby(os, " ", expressions);
os << ")";
}
};
struct BracketsAst : public ExpressionsAst {
~BracketsAst() {}
BracketsAst(std::vector<z2h::Ast *> expressions)
: ExpressionsAst(expressions) {}
protected:
void Print(std::ostream &os) const {
os << "([] ";
sepby(os, " ", expressions);
os << ")";
}
};
struct InfixAst : public z2h::Ast {
z2h::Ast *left;
z2h::Ast *right;
~InfixAst() {}
InfixAst(z2h::Token *token, z2h::Ast *left, z2h::Ast *right)
: z2h::Ast(token)
, left(left)
, right(right) {}
protected:
void Print(std::ostream &os) const {
os << "(" + token->value + " " << *left << " " << *right << ")";
}
};
struct PrefixAst : public z2h::Ast {
z2h::Ast *right;
~PrefixAst() {}
PrefixAst(z2h::Token *token, z2h::Ast *right)
: z2h::Ast(token)
, right(right) {}
protected:
void Print(std::ostream &os) const {
os << "(" + token->value + " " << *right << ")";
}
};
struct AssignAst : public z2h::Ast {
z2h::Ast *left;
z2h::Ast *right;
~AssignAst() {}
AssignAst(z2h::Token *token, z2h::Ast *left, z2h::Ast *right)
: z2h::Ast(token)
, left(left)
, right(right) {}
protected:
void Print(std::ostream &os) const {
os << "(" + token->value + " " << *left << " " << *right << ")";
}
};
struct FuncAst : public z2h::Ast {
z2h::Ast *args;
z2h::Ast *body;
~FuncAst() {}
FuncAst(z2h::Token *token, z2h::Ast *args, z2h::Ast *body)
: z2h::Ast(token)
, args(args)
, body(body) {}
protected:
void Print(std::ostream &os) const {
os << "(-> " << *args << " " << *body << ")";
}
};
struct ConditionalAst : public z2h::Ast {
struct Pair {
z2h::Ast *predicate;
z2h::Ast *action;
Pair(z2h::Ast *predicate, z2h::Ast *action)
: predicate(predicate)
, action(action) {}
protected:
friend std::ostream & operator <<(std::ostream &os, const Pair &pair) {
os << "(pair " << *pair.predicate << " " << *pair.action << ")";
return os;
}
};
std::vector<Pair> pairs;
z2h::Ast *action;
~ConditionalAst() {}
ConditionalAst(z2h::Token *token, std::initializer_list<Pair> pairs)
: z2h::Ast(token)
, pairs(pairs)
, action(nullptr) {}
ConditionalAst(z2h::Token *token, std::initializer_list<Pair> pairs, z2h::Ast *action)
: z2h::Ast(token)
, pairs(pairs)
, action(action) {}
protected:
void Print(std::ostream &os) const {
os << "(cond";
for (auto pair : pairs) {
os << " " << pair;
}
if (nullptr != action)
os << " " << *action;
os << ")";
}
};
}
#endif /*__SOTA_AST__*/
<|endoftext|> |
<commit_before><commit_msg>#92198# Admit that SwXPageStyle supports com.sun.star.style.PageProperties<commit_after><|endoftext|> |
<commit_before>//===-- Intercept.cpp - System function interception routines -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// If a function call occurs to an external function, the JIT is designed to use
// the dynamic loader interface to find a function to call. This is useful for
// calling system calls and library functions that are not available in LLVM.
// Some system calls, however, need to be handled specially. For this reason,
// we intercept some of them here and use our own stubs to handle them.
//
//===----------------------------------------------------------------------===//
#include "JIT.h"
#include "llvm/System/DynamicLibrary.h"
#include <iostream>
#if defined(__linux__)
#include <sys/stat.h>
#endif
using namespace llvm;
// AtExitHandlers - List of functions to call when the program exits,
// registered with the atexit() library function.
static std::vector<void (*)()> AtExitHandlers;
/// runAtExitHandlers - Run any functions registered by the program's
/// calls to atexit(3), which we intercept and store in
/// AtExitHandlers.
///
static void runAtExitHandlers() {
while (!AtExitHandlers.empty()) {
void (*Fn)() = AtExitHandlers.back();
AtExitHandlers.pop_back();
Fn();
}
}
//===----------------------------------------------------------------------===//
// Function stubs that are invoked instead of certain library calls
//===----------------------------------------------------------------------===//
// Force the following functions to be linked in to anything that uses the
// JIT. This is a hack designed to work around the all-too-clever Glibc
// strategy of making these functions work differently when inlined vs. when
// not inlined, and hiding their real definitions in a separate archive file
// that the dynamic linker can't see. For more info, search for
// 'libc_nonshared.a' on Google, or read http://llvm.cs.uiuc.edu/PR274.
#if defined(__linux__)
void *FunctionPointers[] = {
(void *) stat,
(void *) fstat,
(void *) lstat,
(void *) stat64,
(void *) fstat64,
(void *) lstat64,
(void *) atexit,
(void *) mknod
};
#endif // __linux__
// __mainFunc - If the program does not have a linked in __main function, allow
// it to run, but print a warning.
static void __mainFunc() {
fprintf(stderr, "WARNING: Program called __main but was not linked to "
"libcrtend.a.\nThis probably won't hurt anything unless the "
"program is written in C++.\n");
}
// jit_exit - Used to intercept the "exit" library call.
static void jit_exit(int Status) {
runAtExitHandlers(); // Run atexit handlers...
exit(Status);
}
// jit_atexit - Used to intercept the "atexit" library call.
static int jit_atexit(void (*Fn)(void)) {
AtExitHandlers.push_back(Fn); // Take note of atexit handler...
return 0; // Always successful
}
//===----------------------------------------------------------------------===//
//
/// getPointerToNamedFunction - This method returns the address of the specified
/// function by using the dynamic loader interface. As such it is only useful
/// for resolving library symbols, not code generated symbols.
///
void *JIT::getPointerToNamedFunction(const std::string &Name) {
// Check to see if this is one of the functions we want to intercept...
if (Name == "exit") return (void*)&jit_exit;
if (Name == "atexit") return (void*)&jit_atexit;
// If the program does not have a linked in __main function, allow it to run,
// but print a warning.
if (Name == "__main") return (void*)&__mainFunc;
// If it's an external function, look it up in the process image...
void *Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(Name);
if (Ptr) return Ptr;
std::cerr << "ERROR: Program used external function '" << Name
<< "' which could not be resolved!\n";
abort();
return 0;
}
<commit_msg>Move the #include of sys/stat.h inside the linux "hack" for the stat family of functions so it gets noticed if we ever remove this.<commit_after>//===-- Intercept.cpp - System function interception routines -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// If a function call occurs to an external function, the JIT is designed to use
// the dynamic loader interface to find a function to call. This is useful for
// calling system calls and library functions that are not available in LLVM.
// Some system calls, however, need to be handled specially. For this reason,
// we intercept some of them here and use our own stubs to handle them.
//
//===----------------------------------------------------------------------===//
#include "JIT.h"
#include "llvm/System/DynamicLibrary.h"
#include <iostream>
using namespace llvm;
// AtExitHandlers - List of functions to call when the program exits,
// registered with the atexit() library function.
static std::vector<void (*)()> AtExitHandlers;
/// runAtExitHandlers - Run any functions registered by the program's
/// calls to atexit(3), which we intercept and store in
/// AtExitHandlers.
///
static void runAtExitHandlers() {
while (!AtExitHandlers.empty()) {
void (*Fn)() = AtExitHandlers.back();
AtExitHandlers.pop_back();
Fn();
}
}
//===----------------------------------------------------------------------===//
// Function stubs that are invoked instead of certain library calls
//===----------------------------------------------------------------------===//
// Force the following functions to be linked in to anything that uses the
// JIT. This is a hack designed to work around the all-too-clever Glibc
// strategy of making these functions work differently when inlined vs. when
// not inlined, and hiding their real definitions in a separate archive file
// that the dynamic linker can't see. For more info, search for
// 'libc_nonshared.a' on Google, or read http://llvm.cs.uiuc.edu/PR274.
#if defined(__linux__)
#include <sys/stat.h>
void *FunctionPointers[] = {
(void *) stat,
(void *) fstat,
(void *) lstat,
(void *) stat64,
(void *) fstat64,
(void *) lstat64,
(void *) atexit,
(void *) mknod
};
#endif // __linux__
// __mainFunc - If the program does not have a linked in __main function, allow
// it to run, but print a warning.
static void __mainFunc() {
fprintf(stderr, "WARNING: Program called __main but was not linked to "
"libcrtend.a.\nThis probably won't hurt anything unless the "
"program is written in C++.\n");
}
// jit_exit - Used to intercept the "exit" library call.
static void jit_exit(int Status) {
runAtExitHandlers(); // Run atexit handlers...
exit(Status);
}
// jit_atexit - Used to intercept the "atexit" library call.
static int jit_atexit(void (*Fn)(void)) {
AtExitHandlers.push_back(Fn); // Take note of atexit handler...
return 0; // Always successful
}
//===----------------------------------------------------------------------===//
//
/// getPointerToNamedFunction - This method returns the address of the specified
/// function by using the dynamic loader interface. As such it is only useful
/// for resolving library symbols, not code generated symbols.
///
void *JIT::getPointerToNamedFunction(const std::string &Name) {
// Check to see if this is one of the functions we want to intercept...
if (Name == "exit") return (void*)&jit_exit;
if (Name == "atexit") return (void*)&jit_atexit;
// If the program does not have a linked in __main function, allow it to run,
// but print a warning.
if (Name == "__main") return (void*)&__mainFunc;
// If it's an external function, look it up in the process image...
void *Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(Name);
if (Ptr) return Ptr;
std::cerr << "ERROR: Program used external function '" << Name
<< "' which could not be resolved!\n";
abort();
return 0;
}
<|endoftext|> |
<commit_before>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2009 Alexander Binder
* Copyright (C) 2009 Fraunhofer Institute FIRST and Max-Planck-Society
*/
#include <shogun/multiclass/MulticlassOneVsRestStrategy.h>
#include <shogun/classifier/mkl/MKLMulticlass.h>
#include <shogun/io/SGIO.h>
using namespace shogun;
CMKLMulticlass::CMKLMulticlass()
: CMulticlassSVM(new CMulticlassOneVsRestStrategy())
{
svm=NULL;
lpw=NULL;
mkl_eps=0.01;
max_num_mkl_iters=999;
pnorm=1;
}
CMKLMulticlass::CMKLMulticlass(float64_t C, CKernel* k, CLabels* lab)
: CMulticlassSVM(new CMulticlassOneVsRestStrategy(), C, k, lab)
{
svm=NULL;
lpw=NULL;
mkl_eps=0.01;
max_num_mkl_iters=999;
pnorm=1;
}
CMKLMulticlass::~CMKLMulticlass()
{
SG_UNREF(svm);
svm=NULL;
delete lpw;
lpw=NULL;
}
CMKLMulticlass::CMKLMulticlass( const CMKLMulticlass & cm)
: CMulticlassSVM(new CMulticlassOneVsRestStrategy())
{
svm=NULL;
lpw=NULL;
SG_ERROR(
" CMKLMulticlass::CMKLMulticlass(const CMKLMulticlass & cm): must "
"not be called, glpk structure is currently not copyable");
}
CMKLMulticlass CMKLMulticlass::operator=( const CMKLMulticlass & cm)
{
SG_ERROR(
" CMKLMulticlass CMKLMulticlass::operator=(...): must "
"not be called, glpk structure is currently not copyable");
return (*this);
}
void CMKLMulticlass::initsvm()
{
if (!m_labels)
{
SG_ERROR("CMKLMulticlass::initsvm(): the set labels is NULL\n");
}
SG_UNREF(svm);
svm=new CGMNPSVM;
SG_REF(svm);
svm->set_C(get_C1(),get_C2());
svm->set_epsilon(get_epsilon());
if (m_labels->get_num_labels()<=0)
{
SG_ERROR("CMKLMulticlass::initsvm(): the number of labels is "
"nonpositive, do not know how to handle this!\n");
}
svm->set_labels(m_labels);
}
void CMKLMulticlass::initlpsolver()
{
if (!m_kernel)
{
SG_ERROR("CMKLMulticlass::initlpsolver(): the set kernel is NULL\n");
}
if (m_kernel->get_kernel_type()!=K_COMBINED)
{
SG_ERROR("CMKLMulticlass::initlpsolver(): given kernel is not of type"
" K_COMBINED %d required by Multiclass Mkl \n",
m_kernel->get_kernel_type());
}
int numker=dynamic_cast<CCombinedKernel *>(m_kernel)->get_num_subkernels();
ASSERT(numker>0);
/*
if (lpw)
{
delete lpw;
}
*/
//lpw=new MKLMulticlassGLPK;
if(pnorm>1)
{
lpw=new MKLMulticlassGradient;
lpw->set_mkl_norm(pnorm);
}
else
{
lpw=new MKLMulticlassGLPK;
}
lpw->setup(numker);
}
bool CMKLMulticlass::evaluatefinishcriterion(const int32_t
numberofsilpiterations)
{
if ( (max_num_mkl_iters>0) && (numberofsilpiterations>=max_num_mkl_iters) )
{
return(true);
}
if (weightshistory.size()>1)
{
std::vector<float64_t> wold,wnew;
wold=weightshistory[ weightshistory.size()-2 ];
wnew=weightshistory.back();
float64_t delta=0;
ASSERT (wold.size()==wnew.size());
if((pnorm<=1)&&(!normweightssquared.empty()))
{
delta=0;
for (size_t i=0;i< wnew.size();++i)
{
delta+=(wold[i]-wnew[i])*(wold[i]-wnew[i]);
}
delta=sqrt(delta);
SG_SDEBUG("L1 Norm chosen, weight delta %f \n",delta);
//check dual gap part for mkl
int32_t maxind=0;
float64_t maxval=normweightssquared[maxind];
delta=0;
for (size_t i=0;i< wnew.size();++i)
{
delta+=normweightssquared[i]*wnew[i];
if(wnew[i]>maxval)
{
maxind=i;
maxval=wnew[i];
}
}
delta-=normweightssquared[maxind];
delta=fabs(delta);
SG_SDEBUG("L1 Norm chosen, MKL part of duality gap %f \n",delta);
if( (delta < mkl_eps) && (numberofsilpiterations>=1) )
{
return(true);
}
}
else
{
delta=0;
for (size_t i=0;i< wnew.size();++i)
{
delta+=(wold[i]-wnew[i])*(wold[i]-wnew[i]);
}
delta=sqrt(delta);
SG_SDEBUG("Lp Norm chosen, weight delta %f \n",delta);
if( (delta < mkl_eps) && (numberofsilpiterations>=1) )
{
return(true);
}
}
}
return(false);
}
void CMKLMulticlass::addingweightsstep( const std::vector<float64_t> &
curweights)
{
if (weightshistory.size()>2)
{
weightshistory.erase(weightshistory.begin());
}
float64_t* weights(NULL);
weights=SG_MALLOC(float64_t, curweights.size());
std::copy(curweights.begin(),curweights.end(),weights);
m_kernel->set_subkernel_weights(SGVector<float64_t>(weights, curweights.size()));
SG_FREE(weights);
weights=NULL;
initsvm();
svm->set_kernel(m_kernel);
svm->train();
float64_t sumofsignfreealphas=getsumofsignfreealphas();
int32_t numkernels=
dynamic_cast<CCombinedKernel *>(m_kernel)->get_num_subkernels();
normweightssquared.resize(numkernels);
for (int32_t ind=0; ind < numkernels; ++ind )
{
normweightssquared[ind]=getsquarenormofprimalcoefficients( ind );
}
lpw->addconstraint(normweightssquared,sumofsignfreealphas);
}
float64_t CMKLMulticlass::getsumofsignfreealphas()
{
std::vector<int> trainlabels2(m_labels->get_num_labels());
SGVector<int32_t> lab=m_labels->get_int_labels();
std::copy(lab.vector,lab.vector+lab.vlen, trainlabels2.begin());
ASSERT (trainlabels2.size()>0);
float64_t sum=0;
for (int32_t nc=0; nc< m_labels->get_num_classes();++nc)
{
CSVM * sm=svm->get_svm(nc);
float64_t bia=sm->get_bias();
sum+= bia*bia;
SG_UNREF(sm);
}
index_t basealphas_y = 0, basealphas_x = 0;
float64_t* basealphas = svm->get_basealphas_ptr(&basealphas_y,
&basealphas_x);
for (size_t lb=0; lb< trainlabels2.size();++lb)
{
for (int32_t nc=0; nc< m_labels->get_num_classes();++nc)
{
CSVM * sm=svm->get_svm(nc);
if ((int)nc!=trainlabels2[lb])
{
CSVM * sm2=svm->get_svm(trainlabels2[lb]);
float64_t bia1=sm2->get_bias();
float64_t bia2=sm->get_bias();
SG_UNREF(sm2);
sum+= -basealphas[lb*basealphas_y + nc]*(bia1-bia2-1);
}
SG_UNREF(sm);
}
}
return(sum);
}
float64_t CMKLMulticlass::getsquarenormofprimalcoefficients(
const int32_t ind)
{
CKernel * ker=dynamic_cast<CCombinedKernel *>(m_kernel)->get_kernel(ind);
float64_t tmp=0;
for (int32_t classindex=0; classindex< m_labels->get_num_classes();
++classindex)
{
CSVM * sm=svm->get_svm(classindex);
for (int32_t i=0; i < sm->get_num_support_vectors(); ++i)
{
float64_t alphai=sm->get_alpha(i);
int32_t svindi= sm->get_support_vector(i);
for (int32_t k=0; k < sm->get_num_support_vectors(); ++k)
{
float64_t alphak=sm->get_alpha(k);
int32_t svindk=sm->get_support_vector(k);
tmp+=alphai*ker->kernel(svindi,svindk)
*alphak;
}
}
SG_UNREF(sm);
}
SG_UNREF(ker);
ker=NULL;
return(tmp);
}
bool CMKLMulticlass::train_machine(CFeatures* data)
{
int numcl=m_labels->get_num_classes();
ASSERT(m_kernel);
ASSERT(m_labels && m_labels->get_num_labels());
if (data)
{
if (m_labels->get_num_labels() != data->get_num_vectors())
SG_ERROR("Number of training vectors does not match number of "
"labels\n");
m_kernel->init(data, data);
}
initlpsolver();
weightshistory.clear();
int32_t numkernels=
dynamic_cast<CCombinedKernel *>(m_kernel)->get_num_subkernels();
::std::vector<float64_t> curweights(numkernels,1.0/numkernels);
weightshistory.push_back(curweights);
addingweightsstep(curweights);
int32_t numberofsilpiterations=0;
bool final=false;
while (!final)
{
//curweights.clear();
lpw->computeweights(curweights);
weightshistory.push_back(curweights);
final=evaluatefinishcriterion(numberofsilpiterations);
++numberofsilpiterations;
addingweightsstep(curweights);
} // while(false==final)
//set alphas, bias, support vecs
ASSERT(numcl>=1);
create_multiclass_svm(numcl);
for (int32_t i=0; i<numcl; i++)
{
CSVM* osvm=svm->get_svm(i);
CSVM* nsvm=new CSVM(osvm->get_num_support_vectors());
for (int32_t k=0; k<osvm->get_num_support_vectors() ; k++)
{
nsvm->set_alpha(k, osvm->get_alpha(k) );
nsvm->set_support_vector(k,osvm->get_support_vector(k) );
}
nsvm->set_bias(osvm->get_bias() );
set_svm(i, nsvm);
SG_UNREF(osvm);
osvm=NULL;
}
SG_UNREF(svm);
svm=NULL;
if (lpw)
{
delete lpw;
}
lpw=NULL;
return(true);
}
float64_t* CMKLMulticlass::getsubkernelweights(int32_t & numweights)
{
if ( weightshistory.empty() )
{
numweights=0;
return NULL;
}
std::vector<float64_t> subkerw=weightshistory.back();
numweights=weightshistory.back().size();
float64_t* res=SG_MALLOC(float64_t, numweights);
std::copy(weightshistory.back().begin(), weightshistory.back().end(),res);
return res;
}
void CMKLMulticlass::set_mkl_epsilon(float64_t eps )
{
mkl_eps=eps;
}
void CMKLMulticlass::set_max_num_mkliters(int32_t maxnum)
{
max_num_mkl_iters=maxnum;
}
void CMKLMulticlass::set_mkl_norm(float64_t norm)
{
pnorm=norm;
if(pnorm<1 )
SG_ERROR("CMKLMulticlass::set_mkl_norm(float64_t norm) : parameter pnorm<1");
}
<commit_msg>fix mkl multiclass sgvector bug<commit_after>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2009 Alexander Binder
* Copyright (C) 2009 Fraunhofer Institute FIRST and Max-Planck-Society
*/
#include <shogun/multiclass/MulticlassOneVsRestStrategy.h>
#include <shogun/classifier/mkl/MKLMulticlass.h>
#include <shogun/io/SGIO.h>
using namespace shogun;
CMKLMulticlass::CMKLMulticlass()
: CMulticlassSVM(new CMulticlassOneVsRestStrategy())
{
svm=NULL;
lpw=NULL;
mkl_eps=0.01;
max_num_mkl_iters=999;
pnorm=1;
}
CMKLMulticlass::CMKLMulticlass(float64_t C, CKernel* k, CLabels* lab)
: CMulticlassSVM(new CMulticlassOneVsRestStrategy(), C, k, lab)
{
svm=NULL;
lpw=NULL;
mkl_eps=0.01;
max_num_mkl_iters=999;
pnorm=1;
}
CMKLMulticlass::~CMKLMulticlass()
{
SG_UNREF(svm);
svm=NULL;
delete lpw;
lpw=NULL;
}
CMKLMulticlass::CMKLMulticlass( const CMKLMulticlass & cm)
: CMulticlassSVM(new CMulticlassOneVsRestStrategy())
{
svm=NULL;
lpw=NULL;
SG_ERROR(
" CMKLMulticlass::CMKLMulticlass(const CMKLMulticlass & cm): must "
"not be called, glpk structure is currently not copyable");
}
CMKLMulticlass CMKLMulticlass::operator=( const CMKLMulticlass & cm)
{
SG_ERROR(
" CMKLMulticlass CMKLMulticlass::operator=(...): must "
"not be called, glpk structure is currently not copyable");
return (*this);
}
void CMKLMulticlass::initsvm()
{
if (!m_labels)
{
SG_ERROR("CMKLMulticlass::initsvm(): the set labels is NULL\n");
}
SG_UNREF(svm);
svm=new CGMNPSVM;
SG_REF(svm);
svm->set_C(get_C1(),get_C2());
svm->set_epsilon(get_epsilon());
if (m_labels->get_num_labels()<=0)
{
SG_ERROR("CMKLMulticlass::initsvm(): the number of labels is "
"nonpositive, do not know how to handle this!\n");
}
svm->set_labels(m_labels);
}
void CMKLMulticlass::initlpsolver()
{
if (!m_kernel)
{
SG_ERROR("CMKLMulticlass::initlpsolver(): the set kernel is NULL\n");
}
if (m_kernel->get_kernel_type()!=K_COMBINED)
{
SG_ERROR("CMKLMulticlass::initlpsolver(): given kernel is not of type"
" K_COMBINED %d required by Multiclass Mkl \n",
m_kernel->get_kernel_type());
}
int numker=dynamic_cast<CCombinedKernel *>(m_kernel)->get_num_subkernels();
ASSERT(numker>0);
/*
if (lpw)
{
delete lpw;
}
*/
//lpw=new MKLMulticlassGLPK;
if(pnorm>1)
{
lpw=new MKLMulticlassGradient;
lpw->set_mkl_norm(pnorm);
}
else
{
lpw=new MKLMulticlassGLPK;
}
lpw->setup(numker);
}
bool CMKLMulticlass::evaluatefinishcriterion(const int32_t
numberofsilpiterations)
{
if ( (max_num_mkl_iters>0) && (numberofsilpiterations>=max_num_mkl_iters) )
{
return(true);
}
if (weightshistory.size()>1)
{
std::vector<float64_t> wold,wnew;
wold=weightshistory[ weightshistory.size()-2 ];
wnew=weightshistory.back();
float64_t delta=0;
ASSERT (wold.size()==wnew.size());
if((pnorm<=1)&&(!normweightssquared.empty()))
{
delta=0;
for (size_t i=0;i< wnew.size();++i)
{
delta+=(wold[i]-wnew[i])*(wold[i]-wnew[i]);
}
delta=sqrt(delta);
SG_SDEBUG("L1 Norm chosen, weight delta %f \n",delta);
//check dual gap part for mkl
int32_t maxind=0;
float64_t maxval=normweightssquared[maxind];
delta=0;
for (size_t i=0;i< wnew.size();++i)
{
delta+=normweightssquared[i]*wnew[i];
if(wnew[i]>maxval)
{
maxind=i;
maxval=wnew[i];
}
}
delta-=normweightssquared[maxind];
delta=fabs(delta);
SG_SDEBUG("L1 Norm chosen, MKL part of duality gap %f \n",delta);
if( (delta < mkl_eps) && (numberofsilpiterations>=1) )
{
return(true);
}
}
else
{
delta=0;
for (size_t i=0;i< wnew.size();++i)
{
delta+=(wold[i]-wnew[i])*(wold[i]-wnew[i]);
}
delta=sqrt(delta);
SG_SDEBUG("Lp Norm chosen, weight delta %f \n",delta);
if( (delta < mkl_eps) && (numberofsilpiterations>=1) )
{
return(true);
}
}
}
return(false);
}
void CMKLMulticlass::addingweightsstep( const std::vector<float64_t> &
curweights)
{
if (weightshistory.size()>2)
{
weightshistory.erase(weightshistory.begin());
}
SGVector<float64_t> weights(curweights.size());
std::copy(curweights.begin(),curweights.end(),weights.vector);
m_kernel->set_subkernel_weights(weights);
initsvm();
svm->set_kernel(m_kernel);
svm->train();
float64_t sumofsignfreealphas=getsumofsignfreealphas();
int32_t numkernels=
dynamic_cast<CCombinedKernel *>(m_kernel)->get_num_subkernels();
normweightssquared.resize(numkernels);
for (int32_t ind=0; ind < numkernels; ++ind )
{
normweightssquared[ind]=getsquarenormofprimalcoefficients( ind );
}
lpw->addconstraint(normweightssquared,sumofsignfreealphas);
}
float64_t CMKLMulticlass::getsumofsignfreealphas()
{
std::vector<int> trainlabels2(m_labels->get_num_labels());
SGVector<int32_t> lab=m_labels->get_int_labels();
std::copy(lab.vector,lab.vector+lab.vlen, trainlabels2.begin());
ASSERT (trainlabels2.size()>0);
float64_t sum=0;
for (int32_t nc=0; nc< m_labels->get_num_classes();++nc)
{
CSVM * sm=svm->get_svm(nc);
float64_t bia=sm->get_bias();
sum+= bia*bia;
SG_UNREF(sm);
}
index_t basealphas_y = 0, basealphas_x = 0;
float64_t* basealphas = svm->get_basealphas_ptr(&basealphas_y,
&basealphas_x);
for (size_t lb=0; lb< trainlabels2.size();++lb)
{
for (int32_t nc=0; nc< m_labels->get_num_classes();++nc)
{
CSVM * sm=svm->get_svm(nc);
if ((int)nc!=trainlabels2[lb])
{
CSVM * sm2=svm->get_svm(trainlabels2[lb]);
float64_t bia1=sm2->get_bias();
float64_t bia2=sm->get_bias();
SG_UNREF(sm2);
sum+= -basealphas[lb*basealphas_y + nc]*(bia1-bia2-1);
}
SG_UNREF(sm);
}
}
return(sum);
}
float64_t CMKLMulticlass::getsquarenormofprimalcoefficients(
const int32_t ind)
{
CKernel * ker=dynamic_cast<CCombinedKernel *>(m_kernel)->get_kernel(ind);
float64_t tmp=0;
for (int32_t classindex=0; classindex< m_labels->get_num_classes();
++classindex)
{
CSVM * sm=svm->get_svm(classindex);
for (int32_t i=0; i < sm->get_num_support_vectors(); ++i)
{
float64_t alphai=sm->get_alpha(i);
int32_t svindi= sm->get_support_vector(i);
for (int32_t k=0; k < sm->get_num_support_vectors(); ++k)
{
float64_t alphak=sm->get_alpha(k);
int32_t svindk=sm->get_support_vector(k);
tmp+=alphai*ker->kernel(svindi,svindk)
*alphak;
}
}
SG_UNREF(sm);
}
SG_UNREF(ker);
ker=NULL;
return(tmp);
}
bool CMKLMulticlass::train_machine(CFeatures* data)
{
int numcl=m_labels->get_num_classes();
ASSERT(m_kernel);
ASSERT(m_labels && m_labels->get_num_labels());
if (data)
{
if (m_labels->get_num_labels() != data->get_num_vectors())
SG_ERROR("Number of training vectors does not match number of "
"labels\n");
m_kernel->init(data, data);
}
initlpsolver();
weightshistory.clear();
int32_t numkernels=
dynamic_cast<CCombinedKernel *>(m_kernel)->get_num_subkernels();
::std::vector<float64_t> curweights(numkernels,1.0/numkernels);
weightshistory.push_back(curweights);
addingweightsstep(curweights);
int32_t numberofsilpiterations=0;
bool final=false;
while (!final)
{
//curweights.clear();
lpw->computeweights(curweights);
weightshistory.push_back(curweights);
final=evaluatefinishcriterion(numberofsilpiterations);
++numberofsilpiterations;
addingweightsstep(curweights);
} // while(false==final)
//set alphas, bias, support vecs
ASSERT(numcl>=1);
create_multiclass_svm(numcl);
for (int32_t i=0; i<numcl; i++)
{
CSVM* osvm=svm->get_svm(i);
CSVM* nsvm=new CSVM(osvm->get_num_support_vectors());
for (int32_t k=0; k<osvm->get_num_support_vectors() ; k++)
{
nsvm->set_alpha(k, osvm->get_alpha(k) );
nsvm->set_support_vector(k,osvm->get_support_vector(k) );
}
nsvm->set_bias(osvm->get_bias() );
set_svm(i, nsvm);
SG_UNREF(osvm);
osvm=NULL;
}
SG_UNREF(svm);
svm=NULL;
if (lpw)
{
delete lpw;
}
lpw=NULL;
return(true);
}
float64_t* CMKLMulticlass::getsubkernelweights(int32_t & numweights)
{
if ( weightshistory.empty() )
{
numweights=0;
return NULL;
}
std::vector<float64_t> subkerw=weightshistory.back();
numweights=weightshistory.back().size();
float64_t* res=SG_MALLOC(float64_t, numweights);
std::copy(weightshistory.back().begin(), weightshistory.back().end(),res);
return res;
}
void CMKLMulticlass::set_mkl_epsilon(float64_t eps )
{
mkl_eps=eps;
}
void CMKLMulticlass::set_max_num_mkliters(int32_t maxnum)
{
max_num_mkl_iters=maxnum;
}
void CMKLMulticlass::set_mkl_norm(float64_t norm)
{
pnorm=norm;
if(pnorm<1 )
SG_ERROR("CMKLMulticlass::set_mkl_norm(float64_t norm) : parameter pnorm<1");
}
<|endoftext|> |
<commit_before>/*
* Copyright Andrey Semashev 2007 - 2015.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
/*!
* \file visible_type.hpp
* \author Andrey Semashev
* \date 08.03.2007
*
* \brief This header is the Boost.Log library implementation, see the library documentation
* at http://www.boost.org/doc/libs/release/libs/log/doc/html/index.html. In this file
* internal configuration macros are defined.
*/
#ifndef BOOST_LOG_DETAIL_VISIBLE_TYPE_HPP_INCLUDED_
#define BOOST_LOG_DETAIL_VISIBLE_TYPE_HPP_INCLUDED_
#include <boost/log/detail/config.hpp>
#include <boost/log/detail/header.hpp>
#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif
namespace boost {
BOOST_LOG_OPEN_NAMESPACE
namespace aux {
//! The wrapper type whose type_info is always visible
template< typename T >
struct BOOST_SYMBOL_VISIBLE visible_type
{
typedef T wrapped_type;
};
} // namespace aux
BOOST_LOG_CLOSE_NAMESPACE // namespace log
} // namespace boost
#include <boost/log/detail/footer.hpp>
#endif // BOOST_LOG_DETAIL_VISIBLE_TYPE_HPP_INCLUDED_
<commit_msg>Removed unused header.<commit_after><|endoftext|> |
<commit_before>/**
* This file defines the `FilesystemDispatcher` class.
*/
#ifndef D2_CORE_FILESYSTEM_DISPATCHER_HPP
#define D2_CORE_FILESYSTEM_DISPATCHER_HPP
#include <d2/core/filesystem.hpp>
#include <d2/detail/mutex.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/config.hpp>
#include <boost/interprocess/smart_ptr/unique_ptr.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/make_shared.hpp>
#include <boost/move/utility.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread/lock_guard.hpp>
#include <dyno/serializing_stream.hpp>
#include <fstream>
#include <ios>
#include <string>
namespace d2 {
namespace filesystem_dispatcher_detail {
typedef core::filesystem<
dyno::serializing_stream<
std::ofstream,
boost::archive::text_oarchive
>
> Filesystem;
/**
* Class dispatching thread and process level events to a repository.
*
* This class is meant to be used concurrently by several threads.
*/
class FilesystemDispatcher {
struct default_deleter {
template <typename T>
void operator()(T* ptr) const { delete ptr; }
};
// We use `shared_ptr` because the `dispatch` methods will be writing into
// repositories after a call to `set_repository` might have happened into
// another thread. The `dispatch` method atomically get the value of the
// current repository, do its business and then the repository is
// released automatically if the repository is not referenced anymore
// because a call to `set_repository` happened.
boost::shared_ptr<Filesystem> repository_;
detail::mutex mutable repository_lock_;
typedef boost::lock_guard<detail::mutex> scoped_lock;
boost::shared_ptr<Filesystem> get_repository() {
scoped_lock lock(repository_lock_);
return repository_;
}
public:
FilesystemDispatcher()
: repository_()
{ }
template <typename Path>
explicit FilesystemDispatcher(BOOST_FWD_REF(Path) root)
: repository_(boost::make_shared<Filesystem>(
root, std::ios::out | std::ios::ate))
{ }
/**
* Set a new repository for the event dispatcher. If setting the
* repository fails, an exception is thrown.
*
* @note The method offers the strong exception safety guarantee. If
* setting the repository fails, the repository is left unmodified
* (as-if the call never happened) and logging continues in the same
* repository as before the call.
*/
template <typename Path>
void set_repository(BOOST_FWD_REF(Path) new_root) {
// Try to create a new repository.
// If it throws, the repository won't be modified in any way.
typedef boost::interprocess::unique_ptr<
Filesystem, default_deleter
> FilesystemPtr;
FilesystemPtr new_fs(new Filesystem(
boost::forward<Path>(new_root), std::ios::out | std::ios::ate));
// "Atomically" exchange the old repository with the new one.
// This has noexcept guarantee.
{
scoped_lock lock(repository_lock_);
repository_.reset(new_fs.release());
}
}
/**
* Unset the current repository.
*/
void unset_repository() {
scoped_lock lock(repository_lock_);
repository_.reset();
}
/**
* Same as `set_repository`, but offers the `noexcept` guarantee. Instead
* of reporting the success or failure using an exception, it will do so
* using its return value.
*
* @return Whether setting a new repository succeeded.
*/
template <typename Path>
bool set_repository_noexcept(BOOST_FWD_REF(Path) root) BOOST_NOEXCEPT {
try {
set_repository(boost::forward<Path>(root));
} catch (std::exception const&) {
return false;
}
return true;
}
/**
* Return whether the `FilesystemDispatcher` currently has a repository
* in which events are dispatched.
*/
bool has_repository() const {
scoped_lock lock(repository_lock_);
return static_cast<bool>(repository_);
}
template <typename Event>
void dispatch(BOOST_FWD_REF(Event) event) {
boost::shared_ptr<Filesystem> repository = get_repository();
if (repository)
repository->dispatch(boost::forward<Event>(event));
}
};
} // end namespace filesystem_dispatcher_detail
namespace core {
using filesystem_dispatcher_detail::FilesystemDispatcher;
}
} // end namespace d2
#endif // !D2_CORE_FILESYSTEM_DISPATCHER_HPP
<commit_msg>Overwrite the repository if it already exists.<commit_after>/**
* This file defines the `FilesystemDispatcher` class.
*/
#ifndef D2_CORE_FILESYSTEM_DISPATCHER_HPP
#define D2_CORE_FILESYSTEM_DISPATCHER_HPP
#include <d2/core/filesystem.hpp>
#include <d2/detail/mutex.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/config.hpp>
#include <boost/interprocess/smart_ptr/unique_ptr.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/make_shared.hpp>
#include <boost/move/utility.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread/lock_guard.hpp>
#include <dyno/serializing_stream.hpp>
#include <fstream>
#include <ios>
#include <string>
namespace d2 {
namespace filesystem_dispatcher_detail {
typedef core::filesystem<
dyno::serializing_stream<
std::ofstream,
boost::archive::text_oarchive
>
> Filesystem;
/**
* Class dispatching thread and process level events to a repository.
*
* This class is meant to be used concurrently by several threads.
*/
class FilesystemDispatcher {
struct default_deleter {
template <typename T>
void operator()(T* ptr) const { delete ptr; }
};
// We use `shared_ptr` because the `dispatch` methods will be writing into
// repositories after a call to `set_repository` might have happened into
// another thread. The `dispatch` method atomically get the value of the
// current repository, do its business and then the repository is
// released automatically if the repository is not referenced anymore
// because a call to `set_repository` happened.
boost::shared_ptr<Filesystem> repository_;
detail::mutex mutable repository_lock_;
typedef boost::lock_guard<detail::mutex> scoped_lock;
boost::shared_ptr<Filesystem> get_repository() {
scoped_lock lock(repository_lock_);
return repository_;
}
public:
FilesystemDispatcher()
: repository_()
{ }
template <typename Path>
explicit FilesystemDispatcher(BOOST_FWD_REF(Path) root)
: repository_(boost::make_shared<Filesystem>(
root, dyno::filesystem_overwrite))
{ }
/**
* Set a new repository for the event dispatcher. If setting the
* repository fails, an exception is thrown.
*
* @note The method offers the strong exception safety guarantee. If
* setting the repository fails, the repository is left unmodified
* (as-if the call never happened) and logging continues in the same
* repository as before the call.
*/
template <typename Path>
void set_repository(BOOST_FWD_REF(Path) new_root) {
// Try to create a new repository.
// If it throws, the repository won't be modified in any way.
typedef boost::interprocess::unique_ptr<
Filesystem, default_deleter
> FilesystemPtr;
FilesystemPtr new_fs(new Filesystem(
boost::forward<Path>(new_root), std::ios::out | std::ios::ate));
// "Atomically" exchange the old repository with the new one.
// This has noexcept guarantee.
{
scoped_lock lock(repository_lock_);
repository_.reset(new_fs.release());
}
}
/**
* Unset the current repository.
*/
void unset_repository() {
scoped_lock lock(repository_lock_);
repository_.reset();
}
/**
* Same as `set_repository`, but offers the `noexcept` guarantee. Instead
* of reporting the success or failure using an exception, it will do so
* using its return value.
*
* @return Whether setting a new repository succeeded.
*/
template <typename Path>
bool set_repository_noexcept(BOOST_FWD_REF(Path) root) BOOST_NOEXCEPT {
try {
set_repository(boost::forward<Path>(root));
} catch (std::exception const&) {
return false;
}
return true;
}
/**
* Return whether the `FilesystemDispatcher` currently has a repository
* in which events are dispatched.
*/
bool has_repository() const {
scoped_lock lock(repository_lock_);
return static_cast<bool>(repository_);
}
template <typename Event>
void dispatch(BOOST_FWD_REF(Event) event) {
boost::shared_ptr<Filesystem> repository = get_repository();
if (repository)
repository->dispatch(boost::forward<Event>(event));
}
};
} // end namespace filesystem_dispatcher_detail
namespace core {
using filesystem_dispatcher_detail::FilesystemDispatcher;
}
} // end namespace d2
#endif // !D2_CORE_FILESYSTEM_DISPATCHER_HPP
<|endoftext|> |
<commit_before>#ifndef STAN_MCMC_HMC_HAMILTONIANS_PS_POINT_HPP
#define STAN_MCMC_HMC_HAMILTONIANS_PS_POINT_HPP
#include <stan/callbacks/writer.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <boost/lexical_cast.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <string>
#include <vector>
namespace stan {
namespace mcmc {
using Eigen::Dynamic;
/**
* Point in a generic phase space
*/
class ps_point {
public:
explicit ps_point(int n) : q(n), p(n), g(n) {}
Eigen::VectorXd q;
Eigen::VectorXd p;
Eigen::VectorXd g;
double V{0};
virtual inline void get_param_names(std::vector<std::string>& model_names,
std::vector<std::string>& names) {
names.reserve(q.size() + p.size() + g.size());
for (int i = 0; i < q.size(); ++i)
names.emplace_back(model_names[i]);
for (int i = 0; i < p.size(); ++i)
names.emplace_back(std::string("p_") + model_names[i]);
for (int i = 0; i < g.size(); ++i)
names.emplace_back(std::string("g_") + model_names[i]);
}
virtual inline void get_params(std::vector<double>& values) {
values.reserve(q.size() + p.size() + g.size());
for (int i = 0; i < q.size(); ++i)
values.push_back(q[i]);
for (int i = 0; i < p.size(); ++i)
values.push_back(p[i]);
for (int i = 0; i < g.size(); ++i)
values.push_back(g[i]);
}
/**
* Writes the metric
*
* @param writer writer callback
*/
virtual inline void write_metric(stan::callbacks::writer& writer) {}
};
} // namespace mcmc
} // namespace stan
#endif
<commit_msg>fix double include<commit_after>#ifndef STAN_MCMC_HMC_HAMILTONIANS_PS_POINT_HPP
#define STAN_MCMC_HMC_HAMILTONIANS_PS_POINT_HPP
#include <stan/callbacks/writer.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <boost/lexical_cast.hpp>
#include <string>
#include <vector>
namespace stan {
namespace mcmc {
using Eigen::Dynamic;
/**
* Point in a generic phase space
*/
class ps_point {
public:
explicit ps_point(int n) : q(n), p(n), g(n) {}
Eigen::VectorXd q;
Eigen::VectorXd p;
Eigen::VectorXd g;
double V{0};
virtual inline void get_param_names(std::vector<std::string>& model_names,
std::vector<std::string>& names) {
names.reserve(q.size() + p.size() + g.size());
for (int i = 0; i < q.size(); ++i)
names.emplace_back(model_names[i]);
for (int i = 0; i < p.size(); ++i)
names.emplace_back(std::string("p_") + model_names[i]);
for (int i = 0; i < g.size(); ++i)
names.emplace_back(std::string("g_") + model_names[i]);
}
virtual inline void get_params(std::vector<double>& values) {
values.reserve(q.size() + p.size() + g.size());
for (int i = 0; i < q.size(); ++i)
values.push_back(q[i]);
for (int i = 0; i < p.size(); ++i)
values.push_back(p[i]);
for (int i = 0; i < g.size(); ++i)
values.push_back(g[i]);
}
/**
* Writes the metric
*
* @param writer writer callback
*/
virtual inline void write_metric(stan::callbacks::writer& writer) {}
};
} // namespace mcmc
} // namespace stan
#endif
<|endoftext|> |
<commit_before>/*
Dwarf Therapist
Copyright (c) 2009 Trey Stout (chmod)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "gridviewdock.h"
#include "ui_gridviewdock.h"
#include "viewmanager.h"
#include "gridview.h"
#include "gridviewdialog.h"
#include "truncatingfilelogger.h"
GridViewDock::GridViewDock(ViewManager *mgr, QWidget *parent,
Qt::WindowFlags flags)
: QDockWidget(parent, flags)
, m_manager(mgr)
, ui(new Ui::GridViewDock)
, m_tmp_item(0)
{
ui->setupUi(this);
setFeatures(QDockWidget::AllDockWidgetFeatures);
setAllowedAreas(Qt::AllDockWidgetAreas);
draw_views();
connect(ui->list_views, SIGNAL(itemActivated(QListWidgetItem*)),
SLOT(edit_view(QListWidgetItem*)));
connect(ui->list_views, SIGNAL(customContextMenuRequested(const QPoint &)),
SLOT(draw_list_context_menu(const QPoint &)));
connect(ui->btn_add, SIGNAL(clicked()), this, SLOT(add_new_view()));
}
void GridViewDock::draw_views() {
ui->list_views->clear();
QStringList view_names;
foreach(GridView *v, m_manager->views()) {
view_names << v->name();
}
qSort(view_names);
foreach(QString name, view_names) {
foreach(GridView *v, m_manager->views()) {
if (v->name() == name) {
QListWidgetItem *item = new QListWidgetItem(v->name(),
ui->list_views);
if (!v->is_custom()) {
item->setForeground(Qt::gray);
item->setToolTip(tr("Built-in View. Copy this view to "
"customize it."));
}
}
}
}
}
void GridViewDock::draw_list_context_menu(const QPoint &pos) {
m_tmp_item = ui->list_views->itemAt(pos);
QString item_text;
if (m_tmp_item)
item_text = m_tmp_item->text();
GridView *gv = m_manager->get_view(item_text);
QMenu m(this);
if (gv) {
if (gv->is_custom())
m.addAction(QIcon(":/img/pencil.png"), tr("Edit..."),
this, SLOT(edit_view()));
m.addAction(QIcon(":/img/page_copy.png"), tr("Copy..."),
this, SLOT(copy_view()));
if (gv->is_custom()) {
m.addAction(QIcon(":/img/table--minus.png"), tr("Delete..."),
this, SLOT(delete_view()));
}
} else { // whitespace
m.addAction(QIcon(":img/table--plus.png"), tr("Add New GridView"),
this, SLOT(add_new_view()));
}
m.exec(ui->list_views->mapToGlobal(pos));
}
void GridViewDock::add_new_view() {
GridView *view = new GridView("", m_manager);
GridViewDialog *d = new GridViewDialog(m_manager, view, this);
int accepted = d->exec();
if (accepted == QDialog::Accepted) {
GridView *new_view = d->pending_view();
new_view->set_active(false);
m_manager->add_view(new_view);
draw_views();
}
}
void GridViewDock::edit_view(QListWidgetItem *item) {
m_tmp_item = item;
edit_view();
}
void GridViewDock::edit_view() {
if (!m_tmp_item)
return;
GridView *view = m_manager->get_view(m_tmp_item->text());
if (!view)
return;
if (!view->is_custom()) {
return; // can't edit non-custom views
}
GridViewDialog *d = new GridViewDialog(m_manager, view, this);
int accepted = d->exec();
if (accepted == QDialog::Accepted) {
m_manager->replace_view(view, d->pending_view());
draw_views();
}
m_tmp_item = 0;
}
void GridViewDock::copy_view() {
if (!m_tmp_item)
return;
GridView *view = m_manager->get_view(m_tmp_item->text());
if (!view)
return;
GridView *copy = new GridView(*view);
copy->set_is_custom(true); // all copies are custom
copy->set_name(view->name() + "(COPY)");
m_manager->add_view(copy);
m_manager->write_views();
draw_views();
m_tmp_item = 0;
}
void GridViewDock::delete_view() {
if (!m_tmp_item)
return;
GridView *view = m_manager->get_view(m_tmp_item->text());
if (!view)
return;
int answer = QMessageBox::question(
0, tr("Delete View"),
tr("Deleting '%1' will permanently delete it from disk. <h1>Really "
"delete '%1'?</h1><h2>There is no undo!</h2>").arg(view->name()),
QMessageBox::Yes | QMessageBox::No);
if (answer == QMessageBox::Yes) {
LOGI << "permanently deleting set" << view->name();
m_manager->remove_view(view);
draw_views();
view->deleteLater();
}
m_tmp_item = 0;
}
<commit_msg>- forgot a change to hide the built-in weapons view from being copied<commit_after>/*
Dwarf Therapist
Copyright (c) 2009 Trey Stout (chmod)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "gridviewdock.h"
#include "ui_gridviewdock.h"
#include "viewmanager.h"
#include "gridview.h"
#include "gridviewdialog.h"
#include "truncatingfilelogger.h"
GridViewDock::GridViewDock(ViewManager *mgr, QWidget *parent,
Qt::WindowFlags flags)
: QDockWidget(parent, flags)
, m_manager(mgr)
, ui(new Ui::GridViewDock)
, m_tmp_item(0)
{
ui->setupUi(this);
setFeatures(QDockWidget::AllDockWidgetFeatures);
setAllowedAreas(Qt::AllDockWidgetAreas);
draw_views();
connect(ui->list_views, SIGNAL(itemActivated(QListWidgetItem*)),
SLOT(edit_view(QListWidgetItem*)));
connect(ui->list_views, SIGNAL(customContextMenuRequested(const QPoint &)),
SLOT(draw_list_context_menu(const QPoint &)));
connect(ui->btn_add, SIGNAL(clicked()), this, SLOT(add_new_view()));
}
void GridViewDock::draw_views() {
ui->list_views->clear();
QStringList view_names;
foreach(GridView *v, m_manager->views()) {
//exclude the built in weapons view from being copied as the columns are currently custom groups
if(!v->is_custom() && v->name() != tr("Weapons"))
view_names << v->name();
}
qSort(view_names);
foreach(QString name, view_names) {
foreach(GridView *v, m_manager->views()) {
if (v->name() == name) {
QListWidgetItem *item = new QListWidgetItem(v->name(),ui->list_views);
if (!v->is_custom()) {
item->setForeground(Qt::gray);
item->setToolTip(tr("Built-in View. Copy this view to customize it."));
}
}
}
}
}
void GridViewDock::draw_list_context_menu(const QPoint &pos) {
m_tmp_item = ui->list_views->itemAt(pos);
QString item_text;
if (m_tmp_item)
item_text = m_tmp_item->text();
GridView *gv = m_manager->get_view(item_text);
QMenu m(this);
if (gv) {
if (gv->is_custom())
m.addAction(QIcon(":/img/pencil.png"), tr("Edit..."),
this, SLOT(edit_view()));
m.addAction(QIcon(":/img/page_copy.png"), tr("Copy..."),
this, SLOT(copy_view()));
if (gv->is_custom()) {
m.addAction(QIcon(":/img/table--minus.png"), tr("Delete..."),
this, SLOT(delete_view()));
}
} else { // whitespace
m.addAction(QIcon(":img/table--plus.png"), tr("Add New GridView"),
this, SLOT(add_new_view()));
}
m.exec(ui->list_views->mapToGlobal(pos));
}
void GridViewDock::add_new_view() {
GridView *view = new GridView("", m_manager);
GridViewDialog *d = new GridViewDialog(m_manager, view, this);
int accepted = d->exec();
if (accepted == QDialog::Accepted) {
GridView *new_view = d->pending_view();
new_view->set_active(false);
m_manager->add_view(new_view);
draw_views();
}
}
void GridViewDock::edit_view(QListWidgetItem *item) {
m_tmp_item = item;
edit_view();
}
void GridViewDock::edit_view() {
if (!m_tmp_item)
return;
GridView *view = m_manager->get_view(m_tmp_item->text());
if (!view)
return;
if (!view->is_custom()) {
return; // can't edit non-custom views
}
GridViewDialog *d = new GridViewDialog(m_manager, view, this);
int accepted = d->exec();
if (accepted == QDialog::Accepted) {
m_manager->replace_view(view, d->pending_view());
draw_views();
}
m_tmp_item = 0;
}
void GridViewDock::copy_view() {
if (!m_tmp_item)
return;
GridView *view = m_manager->get_view(m_tmp_item->text());
if (!view)
return;
GridView *copy = new GridView(*view);
copy->set_is_custom(true); // all copies are custom
copy->set_name(view->name() + "(COPY)");
m_manager->add_view(copy);
m_manager->write_views();
draw_views();
m_tmp_item = 0;
}
void GridViewDock::delete_view() {
if (!m_tmp_item)
return;
GridView *view = m_manager->get_view(m_tmp_item->text());
if (!view)
return;
int answer = QMessageBox::question(
0, tr("Delete View"),
tr("Deleting '%1' will permanently delete it from disk. <h1>Really "
"delete '%1'?</h1><h2>There is no undo!</h2>").arg(view->name()),
QMessageBox::Yes | QMessageBox::No);
if (answer == QMessageBox::Yes) {
LOGI << "permanently deleting set" << view->name();
m_manager->remove_view(view);
draw_views();
view->deleteLater();
}
m_tmp_item = 0;
}
<|endoftext|> |
<commit_before>#pragma once
#include"stdafx.h"
#include"../../../../server/serverBoostModel/serverBoostModel/protocol.h"
#include"../Server_Code/ClientClass.h"
#include "ObjMgr.h"
#include "Obj.h"
#include "RenderMgr.h"
#include "OtherPlayer.h"
#include "SceneMgr.h"
#include "Player.h"
void AsynchronousClientClass::processPacket(Packet* buf)
{
switch (buf[1])
{
case CHANGED_POSITION: {
if (CSceneMgr::GetInstance()->GetScene() != SCENE_LOGO)
{
player_data *data = CObjMgr::GetInstance()->Get_PlayerServerData(*reinterpret_cast<unsigned int*>(&buf[sizeof(position)+2]));
if (nullptr != data)
{
memcpy(&data->pos, &buf[2], sizeof(position));
list<CObj*>::iterator iter = CObjMgr::GetInstance()->Get_ObjList(L"OtherPlayer")->begin();
list<CObj*>::iterator iter_end = CObjMgr::GetInstance()->Get_ObjList(L"OtherPlayer")->end();
for (iter; iter != iter_end;)
{
if ((*iter)->GetPacketData()->id == reinterpret_cast<player_data*>(data)->id)
{
if (((COtherPlayer*)(*iter))->GetAniState() == PLAYER_IDLE)
{
((COtherPlayer*)(*iter))->m_bKey = true;
((COtherPlayer*)(*iter))->SetAniState(PLAYER_MOVE);
}
break;
}
else
{
++iter;
}
}
}
else
break;
}
}
break;
case CHANGED_DIRECTION: {
if (CSceneMgr::GetInstance()->GetScene() != SCENE_LOGO)
{
player_data *data = CObjMgr::GetInstance()->Get_PlayerServerData(*reinterpret_cast<unsigned int*>(&buf[sizeof(char)+2]));
if (nullptr != data) { memcpy(&data->dir, &buf[2], sizeof(char)); }
else
break;
}
}
break;
case SERVER_MESSAGE_HP_CHANGED: {
if (CSceneMgr::GetInstance()->GetScene() != SCENE_LOGO)
{
if (m_player.id == *(reinterpret_cast<UINT*>(&buf[sizeof(int) + 2]))) {
m_player.state.hp = *(reinterpret_cast<int*>(&buf[2]));
list<CObj*>::iterator iter = CObjMgr::GetInstance()->Get_ObjList(L"Player")->begin();
(*iter)->SetPacketData(&m_player);
break;
}
// ƴ϶ ٸ hp
player_data *data = CObjMgr::GetInstance()->Get_PlayerServerData(*reinterpret_cast<unsigned int*>(&buf[sizeof(int) + 2]));
data->state.hp = *(reinterpret_cast<int*>(&buf[2]));
}
}
break;
case KEYINPUT_ATTACK: {
if (CSceneMgr::GetInstance()->GetScene() != SCENE_LOGO)
{
// Į ߴ ̵ Ȯ , ༮ ִϸ̼ ( ̵ ƴϸ ϴ ִϸ̼ ۵ Ѿ )
/// ġ id ִٸ, ̹ Ű ִϸ̼ ߱ , ׳ if Ѿ.
if (m_player.id != *(reinterpret_cast<UINT*>(&buf[sizeof(int) + sizeof(int) + 2]))) {
player_data *data = CObjMgr::GetInstance()->Get_PlayerServerData(*reinterpret_cast<unsigned int*>(&buf[sizeof(int) + sizeof(int) + 2]));
list<CObj*>::iterator iter = CObjMgr::GetInstance()->Get_ObjList(L"OtherPlayer")->begin();
list<CObj*>::iterator iter_end = CObjMgr::GetInstance()->Get_ObjList(L"OtherPlayer")->end();
for (iter; iter != iter_end;)
{
if ((*iter)->GetPacketData()->id == reinterpret_cast<player_data*>(data)->id)
{
if (((COtherPlayer*)(*iter))->GetAniState() == PLAYER_IDLE)
{
((COtherPlayer*)(*iter))->m_bKey = true;
((COtherPlayer*)(*iter))->SetAniState(PLAYER_ATT1);
}
break;
}
else
++iter;
}
// *(reinterpret_cast<UINT*>(&buf[sizeof(int) + sizeof(int) + 2])) ȣ Ŭ̾Ʈ ִϸ̼ ۵Ѿ Ѵ.
/// ϴ , þ߿ , Ϳ Ȳ ֱ, Ŭ̾Ʈ ó ־ Ѵ.
/// ȿ ϱ ؼ, ʿ ī ۿ ġ Ŭ̾Ʈ ؼ ó ϴ° ...?
}
// ظ ̶, hp break;
/// -> Ȯ hp ü ѷ ̴. ʵ
/// ٽøϸ, hp , Ŷ Ƶ hp ̸ ؼ ǥ־ Ѵ.
/// ϸ, ̴ Ŷ .
if (m_player.id == *(reinterpret_cast<UINT*>(&buf[sizeof(int) + 2]))) {
m_player.state.hp = *(reinterpret_cast<int*>(&buf[2]));
list<CObj*>::iterator iter = CObjMgr::GetInstance()->Get_ObjList(L"Player")->begin();
(*iter)->SetPacketData(&m_player);
break;
}
// ƴ϶ ٸ hp
player_data *data = CObjMgr::GetInstance()->Get_PlayerServerData(*reinterpret_cast<unsigned int*>(&buf[sizeof(int) + 2]));
data->state.hp = *(reinterpret_cast<int*>(&buf[2]));
}
}
break;
default: // Ⱦ̴ Ŷ
switch (buf[1])
{
case TEST:
#ifdef _DEBUG
// ̰ Ʈ ̴ϱ ׳ θ ǰ
cout << "Server is Running. TEST Packet Recived Successfully.\n";
#endif
break;
case INIT_CLIENT: {
m_player = *(reinterpret_cast<player_data*>(&buf[2]));
// ü Ǵ, ϴ ÷̾ Ͱ ϱ
// ̶ ġ ϴ ´
}
break;
case INIT_OTHER_CLIENT: {
/*unordered_map<UINT, player_data>::iterator ptr = m_other_players.find(reinterpret_cast<player_data*>(&buf[2])->id);
if (m_other_players.end() == ptr) { m_other_players.insert(make_pair(reinterpret_cast<player_data*>(&buf[2])->id, *reinterpret_cast<player_data*>(&buf[2]))); }
else { ptr->second.pos = *reinterpret_cast<position*>(&buf[2]); }
InvalidateRect(m_hWnd, NULL, TRUE);*/
//if (CSceneMgr::GetInstance()->GetScene() != SCENE_LOGO)
{
player_data *data = CObjMgr::GetInstance()->Get_PlayerServerData(reinterpret_cast<player_data*>(&buf[2])->id);
if (nullptr != data) { break; }
else {
// ߰ ?
// data end ġ, Ͱ µ ϴ°ݾ
// ο ÷̾ Ǿٴ ̴ϱ
// ü ߰ؼ ־߰? ?
CObj* pObj = NULL;
pObj = COtherPlayer::Create();
pObj->SetPos(D3DXVECTOR3(m_player.pos.x, 1.f, m_player.pos.y));
pObj->SetPacketData(reinterpret_cast<player_data*>(&buf[2]));
CObjMgr::GetInstance()->AddObject(L"OtherPlayer", pObj);
CRenderMgr::GetInstance()->AddRenderGroup(TYPE_NONEALPHA, pObj);
}
}
}
break;
case PLAYER_DISCONNECTED: {
// , id ãƼ, ̵ ã ü ؾ߰? ?
player_data *data = CObjMgr::GetInstance()->Get_PlayerServerData(reinterpret_cast<player_data*>(&buf[2])->id);
list<CObj*>::iterator iter = CObjMgr::GetInstance()->Get_ObjList(L"OtherPlayer")->begin();
list<CObj*>::iterator iter_end = CObjMgr::GetInstance()->Get_ObjList(L"OtherPlayer")->end();
for (iter; iter != iter_end;)
{
if ((*iter)->GetPacketData()->id == reinterpret_cast<player_data*>(data)->id)
{
CRenderMgr::GetInstance()->DelRenderGroup(TYPE_NONEALPHA, *iter);
::Safe_Release(*iter);
CObjMgr::GetInstance()->Get_ObjList(L"OtherPlayer")->erase(iter++);
}
else
++iter;
}
}
break;
default:
break;
}
// default break;
break;
}
}
<commit_msg>[홍승필]npc 0될시 삭제되는거 본 클라 추가<commit_after>#pragma once
#include"stdafx.h"
#include"../../../../server/serverBoostModel/serverBoostModel/protocol.h"
#include"../Server_Code/ClientClass.h"
#include "ObjMgr.h"
#include "Obj.h"
#include "RenderMgr.h"
#include "OtherPlayer.h"
#include "SceneMgr.h"
#include "Player.h"
void AsynchronousClientClass::processPacket(Packet* buf)
{
switch (buf[1])
{
case CHANGED_POSITION: {
if (CSceneMgr::GetInstance()->GetScene() != SCENE_LOGO)
{
player_data *data = CObjMgr::GetInstance()->Get_PlayerServerData(*reinterpret_cast<unsigned int*>(&buf[sizeof(position)+2]));
if (nullptr != data)
{
memcpy(&data->pos, &buf[2], sizeof(position));
list<CObj*>::iterator iter = CObjMgr::GetInstance()->Get_ObjList(L"OtherPlayer")->begin();
list<CObj*>::iterator iter_end = CObjMgr::GetInstance()->Get_ObjList(L"OtherPlayer")->end();
for (iter; iter != iter_end;)
{
if ((*iter)->GetPacketData()->id == reinterpret_cast<player_data*>(data)->id)
{
if (((COtherPlayer*)(*iter))->GetAniState() == PLAYER_IDLE)
{
((COtherPlayer*)(*iter))->m_bKey = true;
((COtherPlayer*)(*iter))->SetAniState(PLAYER_MOVE);
}
break;
}
else
{
++iter;
}
}
}
else
break;
}
}
break;
case CHANGED_DIRECTION: {
if (CSceneMgr::GetInstance()->GetScene() != SCENE_LOGO)
{
player_data *data = CObjMgr::GetInstance()->Get_PlayerServerData(*reinterpret_cast<unsigned int*>(&buf[sizeof(char)+2]));
if (nullptr != data) { memcpy(&data->dir, &buf[2], sizeof(char)); }
else
break;
}
}
break;
case SERVER_MESSAGE_HP_CHANGED: {
if (CSceneMgr::GetInstance()->GetScene() != SCENE_LOGO)
{
if (m_player.id == *(reinterpret_cast<UINT*>(&buf[sizeof(int) + 2]))) {
m_player.state.hp = *(reinterpret_cast<int*>(&buf[2]));
list<CObj*>::iterator iter = CObjMgr::GetInstance()->Get_ObjList(L"Player")->begin();
(*iter)->SetPacketData(&m_player);
break;
}
// ƴ϶ ٸ hp
player_data *data = CObjMgr::GetInstance()->Get_PlayerServerData(*reinterpret_cast<unsigned int*>(&buf[sizeof(int) + 2]));
data->state.hp = *(reinterpret_cast<int*>(&buf[2]));
}
}
break;
case KEYINPUT_ATTACK: {
if (CSceneMgr::GetInstance()->GetScene() != SCENE_LOGO)
{
// Į ߴ ̵ Ȯ , ༮ ִϸ̼ ( ̵ ƴϸ ϴ ִϸ̼ ۵ Ѿ )
/// ġ id ִٸ, ̹ Ű ִϸ̼ ߱ , ׳ if Ѿ.
if (m_player.id != *(reinterpret_cast<UINT*>(&buf[sizeof(int) + sizeof(int) + 2]))) {
player_data *data = CObjMgr::GetInstance()->Get_PlayerServerData(*reinterpret_cast<unsigned int*>(&buf[sizeof(int) + sizeof(int) + 2]));
list<CObj*>::iterator iter = CObjMgr::GetInstance()->Get_ObjList(L"OtherPlayer")->begin();
list<CObj*>::iterator iter_end = CObjMgr::GetInstance()->Get_ObjList(L"OtherPlayer")->end();
for (iter; iter != iter_end;)
{
if ((*iter)->GetPacketData()->id == reinterpret_cast<player_data*>(data)->id)
{
if (((COtherPlayer*)(*iter))->GetAniState() == PLAYER_IDLE)
{
((COtherPlayer*)(*iter))->m_bKey = true;
((COtherPlayer*)(*iter))->SetAniState(PLAYER_ATT1);
}
break;
}
else
++iter;
}
// *(reinterpret_cast<UINT*>(&buf[sizeof(int) + sizeof(int) + 2])) ȣ Ŭ̾Ʈ ִϸ̼ ۵Ѿ Ѵ.
/// ϴ , þ߿ , Ϳ Ȳ ֱ, Ŭ̾Ʈ ó ־ Ѵ.
/// ȿ ϱ ؼ, ʿ ī ۿ ġ Ŭ̾Ʈ ؼ ó ϴ° ...?
}
// ظ ̶, hp break;
/// -> Ȯ hp ü ѷ ̴. ʵ
/// ٽøϸ, hp , Ŷ Ƶ hp ̸ ؼ ǥ־ Ѵ.
/// ϸ, ̴ Ŷ .
if (m_player.id == *(reinterpret_cast<UINT*>(&buf[sizeof(int) + 2]))) {
m_player.state.hp = *(reinterpret_cast<int*>(&buf[2]));
list<CObj*>::iterator iter = CObjMgr::GetInstance()->Get_ObjList(L"Player")->begin();
(*iter)->SetPacketData(&m_player);
break;
}
// ƴ϶ ٸ hp
player_data *data = CObjMgr::GetInstance()->Get_PlayerServerData(*reinterpret_cast<unsigned int*>(&buf[sizeof(int) + 2]));
data->state.hp = *(reinterpret_cast<int*>(&buf[2]));
if (0 >= *(reinterpret_cast<int*>(&buf[2])))
{
list<CObj*>::iterator iter = CObjMgr::GetInstance()->Get_ObjList(L"OtherPlayer")->begin();
list<CObj*>::iterator iter_end = CObjMgr::GetInstance()->Get_ObjList(L"OtherPlayer")->end();
for (iter; iter != iter_end;)
{
if ((*iter)->GetPacketData()->id == reinterpret_cast<player_data*>(data)->id)
{
CRenderMgr::GetInstance()->DelRenderGroup(TYPE_NONEALPHA, *iter);
::Safe_Release(*iter);
CObjMgr::GetInstance()->Get_ObjList(L"OtherPlayer")->erase(iter++);
}
else
++iter;
}
}
}
}
break;
default: // Ⱦ̴ Ŷ
switch (buf[1])
{
case TEST:
#ifdef _DEBUG
// ̰ Ʈ ̴ϱ ׳ θ ǰ
cout << "Server is Running. TEST Packet Recived Successfully.\n";
#endif
break;
case INIT_CLIENT: {
m_player = *(reinterpret_cast<player_data*>(&buf[2]));
// ü Ǵ, ϴ ÷̾ Ͱ ϱ
// ̶ ġ ϴ ´
}
break;
case INIT_OTHER_CLIENT: {
/*unordered_map<UINT, player_data>::iterator ptr = m_other_players.find(reinterpret_cast<player_data*>(&buf[2])->id);
if (m_other_players.end() == ptr) { m_other_players.insert(make_pair(reinterpret_cast<player_data*>(&buf[2])->id, *reinterpret_cast<player_data*>(&buf[2]))); }
else { ptr->second.pos = *reinterpret_cast<position*>(&buf[2]); }
InvalidateRect(m_hWnd, NULL, TRUE);*/
//if (CSceneMgr::GetInstance()->GetScene() != SCENE_LOGO)
{
player_data *data = CObjMgr::GetInstance()->Get_PlayerServerData(reinterpret_cast<player_data*>(&buf[2])->id);
if (nullptr != data) { break; }
else {
// ߰ ?
// data end ġ, Ͱ µ ϴ°ݾ
// ο ÷̾ Ǿٴ ̴ϱ
// ü ߰ؼ ־߰? ?
CObj* pObj = NULL;
pObj = COtherPlayer::Create();
pObj->SetPos(D3DXVECTOR3(m_player.pos.x, 1.f, m_player.pos.y));
pObj->SetPacketData(reinterpret_cast<player_data*>(&buf[2]));
CObjMgr::GetInstance()->AddObject(L"OtherPlayer", pObj);
CRenderMgr::GetInstance()->AddRenderGroup(TYPE_NONEALPHA, pObj);
}
}
}
break;
case PLAYER_DISCONNECTED: {
// , id ãƼ, ̵ ã ü ؾ߰? ?
player_data *data = CObjMgr::GetInstance()->Get_PlayerServerData(reinterpret_cast<player_data*>(&buf[2])->id);
list<CObj*>::iterator iter = CObjMgr::GetInstance()->Get_ObjList(L"OtherPlayer")->begin();
list<CObj*>::iterator iter_end = CObjMgr::GetInstance()->Get_ObjList(L"OtherPlayer")->end();
for (iter; iter != iter_end;)
{
if ((*iter)->GetPacketData()->id == reinterpret_cast<player_data*>(data)->id)
{
CRenderMgr::GetInstance()->DelRenderGroup(TYPE_NONEALPHA, *iter);
::Safe_Release(*iter);
CObjMgr::GetInstance()->Get_ObjList(L"OtherPlayer")->erase(iter++);
}
else
++iter;
}
}
break;
default:
break;
}
// default break;
break;
}
}
<|endoftext|> |
<commit_before>// Copyright (C) 2017 Rob Caelers <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#ifndef OS_CLOSURE_HPP
#define OS_CLOSURE_HPP
#include "os/MainLoop.hpp"
namespace os
{
class ClosureBase
{
public:
virtual void operator()() = 0;
};
template<typename F, typename... Args>
class Closure : public ClosureBase
{
public:
using function_type = std::function<void(Args...)>;
using tuple_type = std::tuple<Args...>;
Closure() = default;
~Closure() = default;
Closure(Closure &&lhs)
: fn(std::move(lhs.fn)),
args(std::move(lhs.args))
{
}
Closure &operator=(Closure &&lhs)
{
if (this != &lhs)
{
fn = std::move(lhs.fn);
args = std::move(lhs.args);
}
return *this;
}
Closure(const Closure &lhs)
: fn(lhs.fn),
args(lhs.args)
{
}
Closure &operator=(const Closure &lhs)
{
if (this != &lhs)
{
fn = lhs.fn;
args = lhs.args;
}
return *this;
}
Closure(F fn, Args... args) :
fn(fn),
args(std::make_tuple(std::move(args)...))
{
}
void operator()()
{
invoke_helper(std::index_sequence_for<Args...>());
}
private:
template<std::size_t... Is>
void invoke_helper(std::index_sequence<Is...>)
{
fn(std::get<Is>(args)...);
}
private:
function_type fn;
std::tuple<Args...> args;
};
template<typename F, typename... Args>
auto make_closure(F &&fn, Args&&... args)
{
return Closure<F, Args...>(std::forward<F>(fn), std::forward<Args>(args)...);
}
}
#endif // OS_CLOSURE_HPP
<commit_msg>Add Closure for std:function<commit_after>// Copyright (C) 2017 Rob Caelers <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#ifndef OS_CLOSURE_HPP
#define OS_CLOSURE_HPP
#include "os/MainLoop.hpp"
namespace os
{
class ClosureBase
{
public:
virtual void operator()() = 0;
};
template<typename F>
class FunctionClosure : public ClosureBase
{
public:
FunctionClosure() = default;
~FunctionClosure() = default;
FunctionClosure(std::function<F> fn) :
fn(fn)
{
}
void operator()()
{
fn();
}
private:
std::function<F> fn;
};
template<typename F, typename... Args>
class Closure : public ClosureBase
{
public:
using function_type = std::function<void(Args...)>;
using tuple_type = std::tuple<Args...>;
Closure() = default;
~Closure() = default;
Closure(Closure &&lhs)
: fn(std::move(lhs.fn)),
args(std::move(lhs.args))
{
}
Closure &operator=(Closure &&lhs)
{
if (this != &lhs)
{
fn = std::move(lhs.fn);
args = std::move(lhs.args);
}
return *this;
}
Closure(const Closure &lhs)
: fn(lhs.fn),
args(lhs.args)
{
}
Closure &operator=(const Closure &lhs)
{
if (this != &lhs)
{
fn = lhs.fn;
args = lhs.args;
}
return *this;
}
Closure(F fn, Args... args) :
fn(fn),
args(std::make_tuple(std::move(args)...))
{
}
void operator()()
{
invoke_helper(std::index_sequence_for<Args...>());
}
private:
template<std::size_t... Is>
void invoke_helper(std::index_sequence<Is...>)
{
fn(std::get<Is>(args)...);
}
private:
function_type fn;
std::tuple<Args...> args;
};
template<typename F, typename... Args>
auto make_closure(F &&fn, Args&&... args)
{
return Closure<F, Args...>(std::forward<F>(fn), std::forward<Args>(args)...);
}
}
#endif // OS_CLOSURE_HPP
<|endoftext|> |
<commit_before>//===-- PPC32CodeEmitter.cpp - JIT Code Emitter for PowerPC32 -----*- C++ -*-=//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the PowerPC 32-bit CodeEmitter and associated machinery to
// JIT-compile bytecode to native PowerPC.
//
//===----------------------------------------------------------------------===//
#include "PPC32TargetMachine.h"
#include "PPC32Relocations.h"
#include "PowerPC.h"
#include "llvm/Module.h"
#include "llvm/CodeGen/MachineCodeEmitter.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Support/Debug.h"
using namespace llvm;
namespace {
class PPC32CodeEmitter : public MachineFunctionPass {
TargetMachine &TM;
MachineCodeEmitter &MCE;
/// MovePCtoLROffset - When/if we see a MovePCtoLR instruction, we record
/// its address in the function into this pointer.
void *MovePCtoLROffset;
// Tracks which instruction references which BasicBlock
std::vector<std::pair<MachineBasicBlock*, unsigned*> > BBRefs;
// Tracks where each BasicBlock starts
std::map<MachineBasicBlock*, long> BBLocations;
/// getMachineOpValue - evaluates the MachineOperand of a given MachineInstr
///
int getMachineOpValue(MachineInstr &MI, MachineOperand &MO);
public:
PPC32CodeEmitter(TargetMachine &T, MachineCodeEmitter &M)
: TM(T), MCE(M) {}
const char *getPassName() const { return "PowerPC Machine Code Emitter"; }
/// runOnMachineFunction - emits the given MachineFunction to memory
///
bool runOnMachineFunction(MachineFunction &MF);
/// emitBasicBlock - emits the given MachineBasicBlock to memory
///
void emitBasicBlock(MachineBasicBlock &MBB);
/// emitWord - write a 32-bit word to memory at the current PC
///
void emitWord(unsigned w) { MCE.emitWord(w); }
/// getValueBit - return the particular bit of Val
///
unsigned getValueBit(int64_t Val, unsigned bit) { return (Val >> bit) & 1; }
/// getBinaryCodeForInstr - This function, generated by the
/// CodeEmitterGenerator using TableGen, produces the binary encoding for
/// machine instructions.
///
unsigned getBinaryCodeForInstr(MachineInstr &MI);
};
}
/// addPassesToEmitMachineCode - Add passes to the specified pass manager to get
/// machine code emitted. This uses a MachineCodeEmitter object to handle
/// actually outputting the machine code and resolving things like the address
/// of functions. This method should returns true if machine code emission is
/// not supported.
///
bool PPC32TargetMachine::addPassesToEmitMachineCode(FunctionPassManager &PM,
MachineCodeEmitter &MCE) {
// Machine code emitter pass for PowerPC
PM.add(new PPC32CodeEmitter(*this, MCE));
// Delete machine code for this function after emitting it
PM.add(createMachineCodeDeleter());
return false;
}
bool PPC32CodeEmitter::runOnMachineFunction(MachineFunction &MF) {
MovePCtoLROffset = 0;
MCE.startFunction(MF);
MCE.emitConstantPool(MF.getConstantPool());
for (MachineFunction::iterator BB = MF.begin(), E = MF.end(); BB != E; ++BB)
emitBasicBlock(*BB);
MCE.finishFunction(MF);
// Resolve branches to BasicBlocks for the entire function
for (unsigned i = 0, e = BBRefs.size(); i != e; ++i) {
intptr_t Location = BBLocations[BBRefs[i].first];
unsigned *Ref = BBRefs[i].second;
DEBUG(std::cerr << "Fixup @ " << (void*)Ref << " to " << (void*)Location
<< "\n");
unsigned Instr = *Ref;
intptr_t BranchTargetDisp = (Location - (intptr_t)Ref) >> 2;
switch (Instr >> 26) {
default: assert(0 && "Unknown branch user!");
case 18: // This is B or BL
*Ref |= (BranchTargetDisp & ((1 << 24)-1)) << 2;
break;
case 16: // This is BLT,BLE,BEQ,BGE,BGT,BNE, or other bcx instruction
*Ref |= (BranchTargetDisp & ((1 << 14)-1)) << 2;
break;
}
}
BBRefs.clear();
BBLocations.clear();
return false;
}
void PPC32CodeEmitter::emitBasicBlock(MachineBasicBlock &MBB) {
BBLocations[&MBB] = MCE.getCurrentPCValue();
for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I){
MachineInstr &MI = *I;
unsigned Opcode = MI.getOpcode();
switch (MI.getOpcode()) {
default:
emitWord(getBinaryCodeForInstr(*I));
break;
case PPC::IMPLICIT_DEF:
break; // pseudo opcode, no side effects
case PPC::MovePCtoLR:
assert(MovePCtoLROffset == 0 &&
"Multiple MovePCtoLR instructions in the function?");
MovePCtoLROffset = (void*)(intptr_t)MCE.getCurrentPCValue();
emitWord(0x48000005); // bl 1
break;
}
}
}
static unsigned enumRegToMachineReg(unsigned enumReg) {
switch (enumReg) {
case PPC::R0 : case PPC::F0 : case PPC::CR0: return 0;
case PPC::R1 : case PPC::F1 : case PPC::CR1: return 1;
case PPC::R2 : case PPC::F2 : case PPC::CR2: return 2;
case PPC::R3 : case PPC::F3 : case PPC::CR3: return 3;
case PPC::R4 : case PPC::F4 : case PPC::CR4: return 4;
case PPC::R5 : case PPC::F5 : case PPC::CR5: return 5;
case PPC::R6 : case PPC::F6 : case PPC::CR6: return 6;
case PPC::R7 : case PPC::F7 : case PPC::CR7: return 7;
case PPC::R8 : case PPC::F8 : return 8;
case PPC::R9 : case PPC::F9 : return 9;
case PPC::R10: case PPC::F10: return 10;
case PPC::R11: case PPC::F11: return 11;
case PPC::R12: case PPC::F12: return 12;
case PPC::R13: case PPC::F13: return 13;
case PPC::R14: case PPC::F14: return 14;
case PPC::R15: case PPC::F15: return 15;
case PPC::R16: case PPC::F16: return 16;
case PPC::R17: case PPC::F17: return 17;
case PPC::R18: case PPC::F18: return 18;
case PPC::R19: case PPC::F19: return 19;
case PPC::R20: case PPC::F20: return 20;
case PPC::R21: case PPC::F21: return 21;
case PPC::R22: case PPC::F22: return 22;
case PPC::R23: case PPC::F23: return 23;
case PPC::R24: case PPC::F24: return 24;
case PPC::R25: case PPC::F25: return 25;
case PPC::R26: case PPC::F26: return 26;
case PPC::R27: case PPC::F27: return 27;
case PPC::R28: case PPC::F28: return 28;
case PPC::R29: case PPC::F29: return 29;
case PPC::R30: case PPC::F30: return 30;
case PPC::R31: case PPC::F31: return 31;
default:
std::cerr << "Unhandled reg in enumRegToRealReg!\n";
abort();
}
}
int PPC32CodeEmitter::getMachineOpValue(MachineInstr &MI, MachineOperand &MO) {
int rv = 0; // Return value; defaults to 0 for unhandled cases
// or things that get fixed up later by the JIT.
if (MO.isRegister()) {
rv = enumRegToMachineReg(MO.getReg());
} else if (MO.isImmediate()) {
rv = MO.getImmedValue();
} else if (MO.isGlobalAddress() || MO.isExternalSymbol()) {
bool isExternal = MO.isExternalSymbol() ||
MO.getGlobal()->hasWeakLinkage() ||
MO.getGlobal()->isExternal();
unsigned Reloc = 0;
int Offset = 0;
if (MI.getOpcode() == PPC::CALLpcrel)
Reloc = PPC::reloc_pcrel_bx;
else {
assert(MovePCtoLROffset && "MovePCtoLR not seen yet?");
Offset = -((intptr_t)MovePCtoLROffset+4);
if (MI.getOpcode() == PPC::LOADHiAddr) {
if (isExternal)
Reloc = PPC::reloc_absolute_ptr_high; // Pointer to stub
else
Reloc = PPC::reloc_absolute_high; // Pointer to symbol
} else if (MI.getOpcode() == PPC::LA) {
assert(!isExternal && "Something in the ISEL changed\n");
Reloc = PPC::reloc_absolute_low;
} else if (MI.getOpcode() == PPC::LWZ) {
Reloc = PPC::reloc_absolute_ptr_low;
assert(isExternal && "Something in the ISEL changed\n");
} else {
// These don't show up for global value references AFAIK, only for
// constant pool refs: PPC::LFS, PPC::LFD
assert(0 && "Unknown instruction for relocation!");
}
}
if (MO.isGlobalAddress())
MCE.addRelocation(MachineRelocation(MCE.getCurrentPCOffset(),
Reloc, MO.getGlobal(), Offset));
else
MCE.addRelocation(MachineRelocation(MCE.getCurrentPCOffset(),
Reloc, MO.getSymbolName(), Offset));
} else if (MO.isMachineBasicBlock()) {
unsigned* CurrPC = (unsigned*)(intptr_t)MCE.getCurrentPCValue();
BBRefs.push_back(std::make_pair(MO.getMachineBasicBlock(), CurrPC));
} else if (MO.isConstantPoolIndex()) {
unsigned index = MO.getConstantPoolIndex();
assert(MovePCtoLROffset && "MovePCtoLR not seen yet?");
rv = MCE.getConstantPoolEntryAddress(index) - (intptr_t)MovePCtoLROffset-4;
unsigned Opcode = MI.getOpcode();
if (Opcode == PPC::LOADHiAddr) {
// LoadHiAddr wants hi16(addr - &MovePCtoLR)
if ((short)rv < 0) rv += 1 << 16;
rv >>= 16;
} else if (Opcode == PPC::LWZ || Opcode == PPC::LA ||
Opcode == PPC::LFS || Opcode == PPC::LFD) {
// These load opcodes want lo16(addr - &MovePCtoLR)
rv &= 0xffff;
} else {
assert(0 && "Unknown constant pool using instruction!");
}
} else {
std::cerr << "ERROR: Unknown type of MachineOperand: " << MO << "\n";
abort();
}
return rv;
}
#include "PPC32GenCodeEmitter.inc"
<commit_msg>Add completely untested support for mtcrf/mfcrf encoding<commit_after>//===-- PPC32CodeEmitter.cpp - JIT Code Emitter for PowerPC32 -----*- C++ -*-=//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the PowerPC 32-bit CodeEmitter and associated machinery to
// JIT-compile bytecode to native PowerPC.
//
//===----------------------------------------------------------------------===//
#include "PPC32TargetMachine.h"
#include "PPC32Relocations.h"
#include "PowerPC.h"
#include "llvm/Module.h"
#include "llvm/CodeGen/MachineCodeEmitter.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Support/Debug.h"
using namespace llvm;
namespace {
class PPC32CodeEmitter : public MachineFunctionPass {
TargetMachine &TM;
MachineCodeEmitter &MCE;
/// MovePCtoLROffset - When/if we see a MovePCtoLR instruction, we record
/// its address in the function into this pointer.
void *MovePCtoLROffset;
// Tracks which instruction references which BasicBlock
std::vector<std::pair<MachineBasicBlock*, unsigned*> > BBRefs;
// Tracks where each BasicBlock starts
std::map<MachineBasicBlock*, long> BBLocations;
/// getMachineOpValue - evaluates the MachineOperand of a given MachineInstr
///
int getMachineOpValue(MachineInstr &MI, MachineOperand &MO);
public:
PPC32CodeEmitter(TargetMachine &T, MachineCodeEmitter &M)
: TM(T), MCE(M) {}
const char *getPassName() const { return "PowerPC Machine Code Emitter"; }
/// runOnMachineFunction - emits the given MachineFunction to memory
///
bool runOnMachineFunction(MachineFunction &MF);
/// emitBasicBlock - emits the given MachineBasicBlock to memory
///
void emitBasicBlock(MachineBasicBlock &MBB);
/// emitWord - write a 32-bit word to memory at the current PC
///
void emitWord(unsigned w) { MCE.emitWord(w); }
/// getValueBit - return the particular bit of Val
///
unsigned getValueBit(int64_t Val, unsigned bit) { return (Val >> bit) & 1; }
/// getBinaryCodeForInstr - This function, generated by the
/// CodeEmitterGenerator using TableGen, produces the binary encoding for
/// machine instructions.
///
unsigned getBinaryCodeForInstr(MachineInstr &MI);
};
}
/// addPassesToEmitMachineCode - Add passes to the specified pass manager to get
/// machine code emitted. This uses a MachineCodeEmitter object to handle
/// actually outputting the machine code and resolving things like the address
/// of functions. This method should returns true if machine code emission is
/// not supported.
///
bool PPC32TargetMachine::addPassesToEmitMachineCode(FunctionPassManager &PM,
MachineCodeEmitter &MCE) {
// Machine code emitter pass for PowerPC
PM.add(new PPC32CodeEmitter(*this, MCE));
// Delete machine code for this function after emitting it
PM.add(createMachineCodeDeleter());
return false;
}
bool PPC32CodeEmitter::runOnMachineFunction(MachineFunction &MF) {
MovePCtoLROffset = 0;
MCE.startFunction(MF);
MCE.emitConstantPool(MF.getConstantPool());
for (MachineFunction::iterator BB = MF.begin(), E = MF.end(); BB != E; ++BB)
emitBasicBlock(*BB);
MCE.finishFunction(MF);
// Resolve branches to BasicBlocks for the entire function
for (unsigned i = 0, e = BBRefs.size(); i != e; ++i) {
intptr_t Location = BBLocations[BBRefs[i].first];
unsigned *Ref = BBRefs[i].second;
DEBUG(std::cerr << "Fixup @ " << (void*)Ref << " to " << (void*)Location
<< "\n");
unsigned Instr = *Ref;
intptr_t BranchTargetDisp = (Location - (intptr_t)Ref) >> 2;
switch (Instr >> 26) {
default: assert(0 && "Unknown branch user!");
case 18: // This is B or BL
*Ref |= (BranchTargetDisp & ((1 << 24)-1)) << 2;
break;
case 16: // This is BLT,BLE,BEQ,BGE,BGT,BNE, or other bcx instruction
*Ref |= (BranchTargetDisp & ((1 << 14)-1)) << 2;
break;
}
}
BBRefs.clear();
BBLocations.clear();
return false;
}
void PPC32CodeEmitter::emitBasicBlock(MachineBasicBlock &MBB) {
BBLocations[&MBB] = MCE.getCurrentPCValue();
for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I){
MachineInstr &MI = *I;
unsigned Opcode = MI.getOpcode();
switch (MI.getOpcode()) {
default:
emitWord(getBinaryCodeForInstr(*I));
break;
case PPC::IMPLICIT_DEF:
break; // pseudo opcode, no side effects
case PPC::MovePCtoLR:
assert(MovePCtoLROffset == 0 &&
"Multiple MovePCtoLR instructions in the function?");
MovePCtoLROffset = (void*)(intptr_t)MCE.getCurrentPCValue();
emitWord(0x48000005); // bl 1
break;
}
}
}
static unsigned enumRegToMachineReg(unsigned enumReg) {
switch (enumReg) {
case PPC::R0 : case PPC::F0 : case PPC::CR0: return 0;
case PPC::R1 : case PPC::F1 : case PPC::CR1: return 1;
case PPC::R2 : case PPC::F2 : case PPC::CR2: return 2;
case PPC::R3 : case PPC::F3 : case PPC::CR3: return 3;
case PPC::R4 : case PPC::F4 : case PPC::CR4: return 4;
case PPC::R5 : case PPC::F5 : case PPC::CR5: return 5;
case PPC::R6 : case PPC::F6 : case PPC::CR6: return 6;
case PPC::R7 : case PPC::F7 : case PPC::CR7: return 7;
case PPC::R8 : case PPC::F8 : return 8;
case PPC::R9 : case PPC::F9 : return 9;
case PPC::R10: case PPC::F10: return 10;
case PPC::R11: case PPC::F11: return 11;
case PPC::R12: case PPC::F12: return 12;
case PPC::R13: case PPC::F13: return 13;
case PPC::R14: case PPC::F14: return 14;
case PPC::R15: case PPC::F15: return 15;
case PPC::R16: case PPC::F16: return 16;
case PPC::R17: case PPC::F17: return 17;
case PPC::R18: case PPC::F18: return 18;
case PPC::R19: case PPC::F19: return 19;
case PPC::R20: case PPC::F20: return 20;
case PPC::R21: case PPC::F21: return 21;
case PPC::R22: case PPC::F22: return 22;
case PPC::R23: case PPC::F23: return 23;
case PPC::R24: case PPC::F24: return 24;
case PPC::R25: case PPC::F25: return 25;
case PPC::R26: case PPC::F26: return 26;
case PPC::R27: case PPC::F27: return 27;
case PPC::R28: case PPC::F28: return 28;
case PPC::R29: case PPC::F29: return 29;
case PPC::R30: case PPC::F30: return 30;
case PPC::R31: case PPC::F31: return 31;
default:
std::cerr << "Unhandled reg in enumRegToRealReg!\n";
abort();
}
}
int PPC32CodeEmitter::getMachineOpValue(MachineInstr &MI, MachineOperand &MO) {
int rv = 0; // Return value; defaults to 0 for unhandled cases
// or things that get fixed up later by the JIT.
if (MO.isRegister()) {
rv = enumRegToMachineReg(MO.getReg());
// Special encoding for MTCRF and MFCRF, which uses a bit mask for the
// register, not the register number directly.
if ((MI.getOpcode() == PPC::MTCRF || MI.getOpcode() == PPC::MFCRF) &&
(MO.getReg() >= PPC::CR0 && MO.getReg() <= PPC::CR7)) {
rv = 0x80 >> rv;
}
} else if (MO.isImmediate()) {
rv = MO.getImmedValue();
} else if (MO.isGlobalAddress() || MO.isExternalSymbol()) {
bool isExternal = MO.isExternalSymbol() ||
MO.getGlobal()->hasWeakLinkage() ||
MO.getGlobal()->isExternal();
unsigned Reloc = 0;
int Offset = 0;
if (MI.getOpcode() == PPC::CALLpcrel)
Reloc = PPC::reloc_pcrel_bx;
else {
assert(MovePCtoLROffset && "MovePCtoLR not seen yet?");
Offset = -((intptr_t)MovePCtoLROffset+4);
if (MI.getOpcode() == PPC::LOADHiAddr) {
if (isExternal)
Reloc = PPC::reloc_absolute_ptr_high; // Pointer to stub
else
Reloc = PPC::reloc_absolute_high; // Pointer to symbol
} else if (MI.getOpcode() == PPC::LA) {
assert(!isExternal && "Something in the ISEL changed\n");
Reloc = PPC::reloc_absolute_low;
} else if (MI.getOpcode() == PPC::LWZ) {
Reloc = PPC::reloc_absolute_ptr_low;
assert(isExternal && "Something in the ISEL changed\n");
} else {
// These don't show up for global value references AFAIK, only for
// constant pool refs: PPC::LFS, PPC::LFD
assert(0 && "Unknown instruction for relocation!");
}
}
if (MO.isGlobalAddress())
MCE.addRelocation(MachineRelocation(MCE.getCurrentPCOffset(),
Reloc, MO.getGlobal(), Offset));
else
MCE.addRelocation(MachineRelocation(MCE.getCurrentPCOffset(),
Reloc, MO.getSymbolName(), Offset));
} else if (MO.isMachineBasicBlock()) {
unsigned* CurrPC = (unsigned*)(intptr_t)MCE.getCurrentPCValue();
BBRefs.push_back(std::make_pair(MO.getMachineBasicBlock(), CurrPC));
} else if (MO.isConstantPoolIndex()) {
unsigned index = MO.getConstantPoolIndex();
assert(MovePCtoLROffset && "MovePCtoLR not seen yet?");
rv = MCE.getConstantPoolEntryAddress(index) - (intptr_t)MovePCtoLROffset-4;
unsigned Opcode = MI.getOpcode();
if (Opcode == PPC::LOADHiAddr) {
// LoadHiAddr wants hi16(addr - &MovePCtoLR)
if ((short)rv < 0) rv += 1 << 16;
rv >>= 16;
} else if (Opcode == PPC::LWZ || Opcode == PPC::LA ||
Opcode == PPC::LFS || Opcode == PPC::LFD) {
// These load opcodes want lo16(addr - &MovePCtoLR)
rv &= 0xffff;
} else {
assert(0 && "Unknown constant pool using instruction!");
}
} else {
std::cerr << "ERROR: Unknown type of MachineOperand: " << MO << "\n";
abort();
}
return rv;
}
#include "PPC32GenCodeEmitter.inc"
<|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/common/gfx/chrome_font.h"
#include "base/logging.h"
#include "base/sys_string_conversions.h"
#include "skia/include/SkTypeface.h"
#include "skia/include/SkPaint.h"
ChromeFont::ChromeFont(const ChromeFont& other) {
CopyChromeFont(other);
}
ChromeFont& ChromeFont::operator=(const ChromeFont& other) {
CopyChromeFont(other);
return *this;
}
ChromeFont::ChromeFont(SkTypeface* tf, const std::wstring& font_name,
int font_size, int style)
: typeface_helper_(new SkAutoUnref(tf)),
typeface_(tf),
font_name_(font_name),
font_size_(font_size),
style_(style) {
calculateMetrics();
}
void ChromeFont::calculateMetrics() {
SkPaint paint;
SkPaint::FontMetrics metrics;
PaintSetup(&paint);
paint.getFontMetrics(&metrics);
if (metrics.fVDMXMetricsValid) {
ascent_ = metrics.fVDMXAscent;
height_ = ascent_ + metrics.fVDMXDescent;
} else {
ascent_ = SkScalarRound(-metrics.fAscent);
height_ = SkScalarRound(metrics.fHeight);
}
if (metrics.fAvgCharWidth) {
avg_width_ = SkScalarRound(metrics.fAvgCharWidth);
} else {
static const char x_char = 'x';
paint.setTextEncoding(SkPaint::kUTF8_TextEncoding);
SkScalar width = paint.measureText(&x_char, 1);
avg_width_ = static_cast<int>(ceilf(SkScalarToFloat(width)));
}
}
void ChromeFont::CopyChromeFont(const ChromeFont& other) {
typeface_helper_.reset(new SkAutoUnref(other.typeface_));
typeface_ = other.typeface_;
font_name_ = other.font_name_;
font_size_ = other.font_size_;
style_ = other.style_;
height_ = other.height_;
ascent_ = other.ascent_;
avg_width_ = other.avg_width_;
}
int ChromeFont::height() const {
return height_;
}
int ChromeFont::baseline() const {
return ascent_;
}
int ChromeFont::ave_char_width() const {
return avg_width_;
}
ChromeFont ChromeFont::CreateFont(const std::wstring& font_name,
int font_size) {
DCHECK_GT(font_size, 0);
SkTypeface* tf = SkTypeface::Create(base::SysWideToUTF8(font_name).c_str(),
SkTypeface::kNormal);
SkAutoUnref tf_helper(tf);
return ChromeFont(tf, font_name, font_size, NORMAL);
}
ChromeFont ChromeFont::DeriveFont(int size_delta, int style) const {
// If the delta is negative, if must not push the size below 1
if (size_delta < 0) {
DCHECK_LT(-size_delta, font_size_);
}
if (style == style_) {
// Fast path, we just use the same typeface at a different size
return ChromeFont(typeface_, font_name_, font_size_ + size_delta, style_);
}
// If the style has changed we may need to load a new face
int skstyle = SkTypeface::kNormal;
if (BOLD & style)
skstyle |= SkTypeface::kBold;
if (ITALIC & style)
skstyle |= SkTypeface::kItalic;
SkTypeface* tf = SkTypeface::Create(base::SysWideToUTF8(font_name_).c_str(),
static_cast<SkTypeface::Style>(skstyle));
SkAutoUnref tf_helper(tf);
return ChromeFont(tf, font_name_, font_size_ + size_delta, skstyle);
}
void ChromeFont::PaintSetup(SkPaint* paint) const {
paint->setAntiAlias(false);
paint->setSubpixelText(false);
paint->setTextSize(SkFloatToScalar(font_size_));
paint->setTypeface(typeface_);
paint->setFakeBoldText((BOLD & style_) && !typeface_->isBold());
paint->setTextSkewX((ITALIC & style_) && !typeface_->isItalic() ?
-SK_Scalar1/4 : 0);
}
int ChromeFont::GetStringWidth(const std::wstring& text) const {
const std::string utf8(base::SysWideToUTF8(text));
SkPaint paint;
PaintSetup(&paint);
paint.setTextEncoding(SkPaint::kUTF8_TextEncoding);
SkScalar width = paint.measureText(utf8.data(), utf8.size());
int breadth = static_cast<int>(ceilf(SkScalarToFloat(width)));
// Check for overflow. We should probably be returning an unsigned
// int, but in practice we'll never have a screen massive enough
// to show that much text anyway.
if (breadth < 0)
return INT_MAX;
return breadth;
}
int ChromeFont::GetExpectedTextWidth(int length) const {
return length * avg_width_;
}
int ChromeFont::style() const {
return style_;
}
std::wstring ChromeFont::FontName() {
return font_name_;
}
int ChromeFont::FontSize() {
return font_size_;
}
NativeFont ChromeFont::nativeFont() const {
return typeface_;
}
<commit_msg>Fix refcounting bug in ChromeFont's default constructor. Found via 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/common/gfx/chrome_font.h"
#include "base/logging.h"
#include "base/sys_string_conversions.h"
#include "skia/include/SkTypeface.h"
#include "skia/include/SkPaint.h"
ChromeFont::ChromeFont(const ChromeFont& other) {
CopyChromeFont(other);
}
ChromeFont& ChromeFont::operator=(const ChromeFont& other) {
CopyChromeFont(other);
return *this;
}
ChromeFont::ChromeFont(SkTypeface* tf, const std::wstring& font_name,
int font_size, int style)
: typeface_helper_(new SkAutoUnref(tf)),
typeface_(tf),
font_name_(font_name),
font_size_(font_size),
style_(style) {
calculateMetrics();
}
void ChromeFont::calculateMetrics() {
SkPaint paint;
SkPaint::FontMetrics metrics;
PaintSetup(&paint);
paint.getFontMetrics(&metrics);
if (metrics.fVDMXMetricsValid) {
ascent_ = metrics.fVDMXAscent;
height_ = ascent_ + metrics.fVDMXDescent;
} else {
ascent_ = SkScalarRound(-metrics.fAscent);
height_ = SkScalarRound(metrics.fHeight);
}
if (metrics.fAvgCharWidth) {
avg_width_ = SkScalarRound(metrics.fAvgCharWidth);
} else {
static const char x_char = 'x';
paint.setTextEncoding(SkPaint::kUTF8_TextEncoding);
SkScalar width = paint.measureText(&x_char, 1);
avg_width_ = static_cast<int>(ceilf(SkScalarToFloat(width)));
}
}
void ChromeFont::CopyChromeFont(const ChromeFont& other) {
typeface_helper_.reset(new SkAutoUnref(other.typeface_));
typeface_ = other.typeface_;
typeface_->ref();
font_name_ = other.font_name_;
font_size_ = other.font_size_;
style_ = other.style_;
height_ = other.height_;
ascent_ = other.ascent_;
avg_width_ = other.avg_width_;
}
int ChromeFont::height() const {
return height_;
}
int ChromeFont::baseline() const {
return ascent_;
}
int ChromeFont::ave_char_width() const {
return avg_width_;
}
ChromeFont ChromeFont::CreateFont(const std::wstring& font_name,
int font_size) {
DCHECK_GT(font_size, 0);
SkTypeface* tf = SkTypeface::Create(base::SysWideToUTF8(font_name).c_str(),
SkTypeface::kNormal);
SkAutoUnref tf_helper(tf);
return ChromeFont(tf, font_name, font_size, NORMAL);
}
ChromeFont ChromeFont::DeriveFont(int size_delta, int style) const {
// If the delta is negative, if must not push the size below 1
if (size_delta < 0) {
DCHECK_LT(-size_delta, font_size_);
}
if (style == style_) {
// Fast path, we just use the same typeface at a different size
return ChromeFont(typeface_, font_name_, font_size_ + size_delta, style_);
}
// If the style has changed we may need to load a new face
int skstyle = SkTypeface::kNormal;
if (BOLD & style)
skstyle |= SkTypeface::kBold;
if (ITALIC & style)
skstyle |= SkTypeface::kItalic;
SkTypeface* tf = SkTypeface::Create(base::SysWideToUTF8(font_name_).c_str(),
static_cast<SkTypeface::Style>(skstyle));
SkAutoUnref tf_helper(tf);
return ChromeFont(tf, font_name_, font_size_ + size_delta, skstyle);
}
void ChromeFont::PaintSetup(SkPaint* paint) const {
paint->setAntiAlias(false);
paint->setSubpixelText(false);
paint->setTextSize(SkFloatToScalar(font_size_));
paint->setTypeface(typeface_);
paint->setFakeBoldText((BOLD & style_) && !typeface_->isBold());
paint->setTextSkewX((ITALIC & style_) && !typeface_->isItalic() ?
-SK_Scalar1/4 : 0);
}
int ChromeFont::GetStringWidth(const std::wstring& text) const {
const std::string utf8(base::SysWideToUTF8(text));
SkPaint paint;
PaintSetup(&paint);
paint.setTextEncoding(SkPaint::kUTF8_TextEncoding);
SkScalar width = paint.measureText(utf8.data(), utf8.size());
int breadth = static_cast<int>(ceilf(SkScalarToFloat(width)));
// Check for overflow. We should probably be returning an unsigned
// int, but in practice we'll never have a screen massive enough
// to show that much text anyway.
if (breadth < 0)
return INT_MAX;
return breadth;
}
int ChromeFont::GetExpectedTextWidth(int length) const {
return length * avg_width_;
}
int ChromeFont::style() const {
return style_;
}
std::wstring ChromeFont::FontName() {
return font_name_;
}
int ChromeFont::FontSize() {
return font_size_;
}
NativeFont ChromeFont::nativeFont() const {
return typeface_;
}
<|endoftext|> |
<commit_before>// ******************************************************************************************
// * This project is licensed under the GNU Affero GPL v3. Copyright © 2014 A3Wasteland.com *
// ******************************************************************************************
#include "player_sys.sqf"
class playerSettings {
idd = playersys_DIALOG;
movingEnable = true;
enableSimulation = true;
onLoad = "[] execVM 'client\systems\playerMenu\item_list.sqf'";
class controlsBackground {
class MainBG : IGUIBack {
idc = -1;
colorText[] = {1, 1, 1, 1};
colorBackground[] = {0,0,0,0.6};
moving = true;
x = 0.0; y = 0.1;
w = .745; h = 0.65;
};
class TopBar: IGUIBack
{
idc = -1;
colorText[] = {1, 1, 1, 1};
colorBackground[] = {A3W_UICOLOR_R, A3W_UICOLOR_G, A3W_UICOLOR_B, 0.8};
x = 0;
y = 0.1;
w = 0.745;
h = 0.05;
};
class MainTitle : w_RscText {
idc = -1;
text = "Player Inventory";
sizeEx = 0.04;
shadow = 2;
x = 0.260; y = 0.1;
w = 0.3; h = 0.05;
};
class waterIcon : w_RscPicture {
idc = -1;
text = "client\icons\tt.paa";
x = 0.022; y = 0.2;
w = 0.04 / (4/3); h = 0.04;
};
class foodIcon : w_RscPicture {
idc = -1;
text = "client\icons\support.paa";
x = 0.022; y = 0.26;
w = 0.04 / (4/3); h = 0.04;
};
class moneyIcon : w_RscPicture {
idc = -1;
text = "client\icons\money.paa";
x = 0.022; y = 0.32;
w = 0.04 / (4/3); h = 0.04;
};
class waterText : w_RscText {
idc = water_text;
text = "";
sizeEx = 0.03;
x = 0.06; y = 0.193;
w = 0.3; h = 0.05;
};
class foodText : w_RscText {
idc = food_text;
sizeEx = 0.03;
text = "";
x = 0.06; y = 0.254;
w = 0.3; h = 0.05;
};
class moneyText : w_RscText {
idc = money_text;
text = "";
sizeEx = 0.03;
x = 0.06; y = 0.313;
w = 0.3; h = 0.05;
};
/*class distanceText : w_RscText {
idc = view_range_text;
text = "View range:";
sizeEx = 0.025;
x = 0.03; y = 0.40;
w = 0.3; h = 0.02;
};*/
class uptimeText : w_RscText {
idc = uptime_text;
text = "";
sizeEx = 0.030;
x = 0.52; y = 0.69;
w = 0.225; h = 0.03;
};
};
class controls {
class itemList : w_Rsclist {
idc = item_list;
x = 0.49; y = 0.185;
w = 0.235; h = 0.325;
};
class DropButton : w_RscButton {
idc = -1;
text = "Drop";
onButtonClick = "[1] execVM 'client\systems\playerMenu\itemfnc.sqf'";
x = 0.610; y = 0.525;
w = 0.116; h = 0.033 * safezoneH;
};
class UseButton : w_RscButton {
idc = -1;
text = "Use";
onButtonClick = "[0] execVM 'client\systems\playerMenu\itemfnc.sqf'";
x = 0.489; y = 0.525;
w = 0.116; h = 0.033 * safezoneH;
};
class moneyInput: w_RscCombo {
idc = money_value;
x = 0.610; y = 0.618;
w = .116; h = .030;
};
class DropcButton : w_RscButton {
idc = -1;
text = "Drop";
onButtonClick = "[] execVM 'client\systems\playerMenu\dropMoney.sqf'";
x = 0.489; y = 0.60;
w = 0.116; h = 0.033 * safezoneH;
};
class CloseButton : w_RscButton {
idc = close_button;
text = "Close";
onButtonClick = "[] execVM 'client\systems\playerMenu\closePlayerMenu.sqf'";
x = 0.02; y = 0.66;
w = 0.125; h = 0.033 * safezoneH;
};
class GroupsButton : w_RscButton {
idc = groupButton;
text = "Group Management";
onButtonClick = "[] execVM 'client\systems\groups\loadGroupManagement.sqf'";
x = 0.158; y = 0.66;
w = 0.225; h = 0.033 * safezoneH;
};
/*class btnDistanceNear : w_RscButton {
idc = -1;
text = "Near";
onButtonClick = "setViewDistance 1100;";
x = 0.02; y = 0.43;
w = 0.125; h = 0.033 * safezoneH;
};
class btnDistanceMedium : w_RscButton {
idc = -1;
text = "Medium";
onButtonClick = "setViewDistance 2200;";
x = 0.02; y = 0.5;
w = 0.125; h = 0.033 * safezoneH;
};
class btnDistanceFar : w_RscButton {
idc = -1;
text = "Far";
onButtonClick = "setViewDistance 3500;";
x = 0.02; y = 0.57;
w = 0.125; h = 0.033 * safezoneH;
};
/*class btnDistanceInsane : w_RscButton {
text = "Insane";
onButtonClick = "setViewDistance 4000;";
x = 0.02; y = 0.60;
w = 0.125; h = 0.033 * safezoneH;
};*/
class btnDistanceEffects : w_RscButton {
idc = -1;
text = "Effects";
onButtonClick = "[] execVM 'addons\disableEnvironment\disableEnvironment.sqf'";
x = 0.158; y = 0.57;
w = 0.125; h = 0.033 * safezoneH;
};
class btnDistanceCHVD : w_RscButton {
idc = -1;
text = "Viewdist.";
onButtonClick = "call CHVD_fnc_openDialog";
x = 0.02; y = 0.57;
w = 0.125; h = 0.033 * safezoneH;
};
};
};<commit_msg>remove disable environment button<commit_after>// ******************************************************************************************
// * This project is licensed under the GNU Affero GPL v3. Copyright © 2014 A3Wasteland.com *
// ******************************************************************************************
#include "player_sys.sqf"
class playerSettings {
idd = playersys_DIALOG;
movingEnable = true;
enableSimulation = true;
onLoad = "[] execVM 'client\systems\playerMenu\item_list.sqf'";
class controlsBackground {
class MainBG : IGUIBack {
idc = -1;
colorText[] = {1, 1, 1, 1};
colorBackground[] = {0,0,0,0.6};
moving = true;
x = 0.0; y = 0.1;
w = .745; h = 0.65;
};
class TopBar: IGUIBack
{
idc = -1;
colorText[] = {1, 1, 1, 1};
colorBackground[] = {A3W_UICOLOR_R, A3W_UICOLOR_G, A3W_UICOLOR_B, 0.8};
x = 0;
y = 0.1;
w = 0.745;
h = 0.05;
};
class MainTitle : w_RscText {
idc = -1;
text = "Player Inventory";
sizeEx = 0.04;
shadow = 2;
x = 0.260; y = 0.1;
w = 0.3; h = 0.05;
};
class waterIcon : w_RscPicture {
idc = -1;
text = "client\icons\tt.paa";
x = 0.022; y = 0.2;
w = 0.04 / (4/3); h = 0.04;
};
class foodIcon : w_RscPicture {
idc = -1;
text = "client\icons\support.paa";
x = 0.022; y = 0.26;
w = 0.04 / (4/3); h = 0.04;
};
class moneyIcon : w_RscPicture {
idc = -1;
text = "client\icons\money.paa";
x = 0.022; y = 0.32;
w = 0.04 / (4/3); h = 0.04;
};
class waterText : w_RscText {
idc = water_text;
text = "";
sizeEx = 0.03;
x = 0.06; y = 0.193;
w = 0.3; h = 0.05;
};
class foodText : w_RscText {
idc = food_text;
sizeEx = 0.03;
text = "";
x = 0.06; y = 0.254;
w = 0.3; h = 0.05;
};
class moneyText : w_RscText {
idc = money_text;
text = "";
sizeEx = 0.03;
x = 0.06; y = 0.313;
w = 0.3; h = 0.05;
};
/*class distanceText : w_RscText {
idc = view_range_text;
text = "View range:";
sizeEx = 0.025;
x = 0.03; y = 0.40;
w = 0.3; h = 0.02;
};*/
class uptimeText : w_RscText {
idc = uptime_text;
text = "";
sizeEx = 0.030;
x = 0.52; y = 0.69;
w = 0.225; h = 0.03;
};
};
class controls {
class itemList : w_Rsclist {
idc = item_list;
x = 0.49; y = 0.185;
w = 0.235; h = 0.325;
};
class DropButton : w_RscButton {
idc = -1;
text = "Drop";
onButtonClick = "[1] execVM 'client\systems\playerMenu\itemfnc.sqf'";
x = 0.610; y = 0.525;
w = 0.116; h = 0.033 * safezoneH;
};
class UseButton : w_RscButton {
idc = -1;
text = "Use";
onButtonClick = "[0] execVM 'client\systems\playerMenu\itemfnc.sqf'";
x = 0.489; y = 0.525;
w = 0.116; h = 0.033 * safezoneH;
};
class moneyInput: w_RscCombo {
idc = money_value;
x = 0.610; y = 0.618;
w = .116; h = .030;
};
class DropcButton : w_RscButton {
idc = -1;
text = "Drop";
onButtonClick = "[] execVM 'client\systems\playerMenu\dropMoney.sqf'";
x = 0.489; y = 0.60;
w = 0.116; h = 0.033 * safezoneH;
};
class CloseButton : w_RscButton {
idc = close_button;
text = "Close";
onButtonClick = "[] execVM 'client\systems\playerMenu\closePlayerMenu.sqf'";
x = 0.02; y = 0.66;
w = 0.125; h = 0.033 * safezoneH;
};
class GroupsButton : w_RscButton {
idc = groupButton;
text = "Group Management";
onButtonClick = "[] execVM 'client\systems\groups\loadGroupManagement.sqf'";
x = 0.158; y = 0.66;
w = 0.225; h = 0.033 * safezoneH;
};
/*class btnDistanceNear : w_RscButton {
idc = -1;
text = "Near";
onButtonClick = "setViewDistance 1100;";
x = 0.02; y = 0.43;
w = 0.125; h = 0.033 * safezoneH;
};
class btnDistanceMedium : w_RscButton {
idc = -1;
text = "Medium";
onButtonClick = "setViewDistance 2200;";
x = 0.02; y = 0.5;
w = 0.125; h = 0.033 * safezoneH;
};
class btnDistanceFar : w_RscButton {
idc = -1;
text = "Far";
onButtonClick = "setViewDistance 3500;";
x = 0.02; y = 0.57;
w = 0.125; h = 0.033 * safezoneH;
};
/*class btnDistanceInsane : w_RscButton {
text = "Insane";
onButtonClick = "setViewDistance 4000;";
x = 0.02; y = 0.60;
w = 0.125; h = 0.033 * safezoneH;
};
class btnDistanceEffects : w_RscButton {
idc = -1;
text = "Effects";
onButtonClick = "[] execVM 'addons\disableEnvironment\disableEnvironment.sqf'";
x = 0.158; y = 0.57;
w = 0.125; h = 0.033 * safezoneH;
};*/
class btnDistanceCHVD : w_RscButton {
idc = -1;
text = "Viewdist.";
onButtonClick = "call CHVD_fnc_openDialog";
x = 0.02; y = 0.57;
w = 0.125; h = 0.033 * safezoneH;
};
};
};<|endoftext|> |
<commit_before>/*
Copyright (c) 2009, Arvid Norberg
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 author 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.
*/
#ifndef TORRENT_UTP_SOCKET_MANAGER_HPP_INCLUDED
#define TORRENT_UTP_SOCKET_MANAGER_HPP_INCLUDED
#include <boost/shared_ptr.hpp>
#include <map>
namespace libtorrent
{
struct udp_socket;
struct utp_stream;
typedef void (*incoming_utp_fun)(void*, boost::shared_ptr<utp_stream> const&);
struct utp_socket_manager
{
utp_socket_manager(udp_socket& s, incoming_utp_fun cb, void* userdata);
// return false if this is not a uTP packet
bool incoming_packet(char const* p, int size);
void tick();
// internal, used by utp_stream
void remove_socket(boost::uint16_t id);
private:
udp_socket& m_sock;
// replace with a hash-map
typedef std::map<boost::uint16_t, utp_stream*> socket_map_t;
socket_map_t m_utp_sockets;
void add_socket(boost::uint16_t id, utp_stream* s);
};
}
#endif
<commit_msg>Added m_cb and m_userdata members to utp_socket_manager.hpp.<commit_after>/*
Copyright (c) 2009, Arvid Norberg
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 author 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.
*/
#ifndef TORRENT_UTP_SOCKET_MANAGER_HPP_INCLUDED
#define TORRENT_UTP_SOCKET_MANAGER_HPP_INCLUDED
#include <boost/shared_ptr.hpp>
#include <map>
namespace libtorrent
{
struct udp_socket;
struct utp_stream;
typedef void (*incoming_utp_fun)(void*, boost::shared_ptr<utp_stream> const&);
struct utp_socket_manager
{
utp_socket_manager(udp_socket& s, incoming_utp_fun cb, void* userdata);
// return false if this is not a uTP packet
bool incoming_packet(char const* p, int size);
void tick();
// internal, used by utp_stream
void remove_socket(boost::uint16_t id);
private:
udp_socket& m_sock;
incoming_utp_fun m_cb;
void* m_userdata;
// replace with a hash-map
typedef std::map<boost::uint16_t, utp_stream*> socket_map_t;
socket_map_t m_utp_sockets;
void add_socket(boost::uint16_t id, utp_stream* s);
};
}
#endif
<|endoftext|> |
<commit_before>/*******************************************************************************
* Copyright (c) 2012, Dougal J. Sutherland ([email protected]). *
* 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 Carnegie Mellon University nor the *
* names of the 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 "np-divs/div-funcs/from_str.hpp"
#include "np-divs/div-funcs/div_func.hpp"
#include "np-divs/div-funcs/div_alpha.hpp"
#include "np-divs/div-funcs/div_bc.hpp"
#include "np-divs/div-funcs/div_hellinger.hpp"
#include "np-divs/div-funcs/div_l2.hpp"
#include "np-divs/div-funcs/div_linear.hpp"
#include "np-divs/div-funcs/div_renyi.hpp"
#include <functional>
#include <stdexcept>
#include <string>
#include <vector>
#include <boost/algorithm/string/split.hpp>
#include <boost/bind.hpp>
#include <boost/throw_exception.hpp>
using std::bind2nd;
using std::equal_to;
using std::string;
using std::vector;
using boost::algorithm::split;
namespace npdivs {
#define THROW_DOM(x)\
BOOST_THROW_EXCEPTION(std::domain_error(x))
DivFunc* div_func_from_str(const string &spec) {
vector<string> tokens;
split(tokens, spec, bind2nd(equal_to<char>(), ':'));
size_t num_toks = tokens.size();
if (num_toks == 0)
THROW_DOM("can't handle empty div func specification");
const string &kind = tokens[0];
vector<double> args;
args.reserve(num_toks - 1);
for (size_t i = 1; i < num_toks; i++)
args.push_back(atof(tokens[i].c_str()));
if (kind == "alpha") {
switch (num_toks) {
case 3: return new DivAlpha(args[0], args[1]);
case 2: return new DivAlpha(args[0]);
case 1: return new DivAlpha();
default: THROW_DOM("too many arguments for DivAlpha");
}
} else if (kind == "bc") {
switch (num_toks) {
case 2: return new DivBC(args[0]);
case 1: return new DivBC();
default: THROW_DOM("too many arguments for DivBC");
}
} else if (kind == "hellinger") {
switch (num_toks) {
case 2: return new DivHellinger(args[0]);
case 1: return new DivHellinger();
default: THROW_DOM("too many arguments for DivHellinger");
}
} else if (kind == "l2") {
switch (num_toks) {
case 2: return new DivL2(args[0]);
case 1: return new DivL2();
default: THROW_DOM("too many arguments for DivL2");
}
} else if (kind == "linear") {
switch (num_toks) {
case 2: return new DivLinear(args[0]);
case 1: return new DivLinear();
default: THROW_DOM("too many arguments for DivLinear");
}
} else if (kind == "renyi") {
switch (num_toks) {
case 3: return new DivRenyi(args[0], args[1]);
case 2: return new DivRenyi(args[0]);
case 1: return new DivRenyi();
default: THROW_DOM("too many arguments for DivRenyi");
}
} else {
THROW_DOM("unknown div func type " + kind);
}
}
}
<commit_msg>error message tweak<commit_after>/*******************************************************************************
* Copyright (c) 2012, Dougal J. Sutherland ([email protected]). *
* 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 Carnegie Mellon University nor the *
* names of the 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 "np-divs/div-funcs/from_str.hpp"
#include "np-divs/div-funcs/div_func.hpp"
#include "np-divs/div-funcs/div_alpha.hpp"
#include "np-divs/div-funcs/div_bc.hpp"
#include "np-divs/div-funcs/div_hellinger.hpp"
#include "np-divs/div-funcs/div_l2.hpp"
#include "np-divs/div-funcs/div_linear.hpp"
#include "np-divs/div-funcs/div_renyi.hpp"
#include <functional>
#include <stdexcept>
#include <string>
#include <vector>
#include <boost/algorithm/string/split.hpp>
#include <boost/bind.hpp>
#include <boost/throw_exception.hpp>
using std::bind2nd;
using std::equal_to;
using std::string;
using std::vector;
using boost::algorithm::split;
namespace npdivs {
#define THROW_DOM(x)\
BOOST_THROW_EXCEPTION(std::domain_error(x))
DivFunc* div_func_from_str(const string &spec) {
vector<string> tokens;
split(tokens, spec, bind2nd(equal_to<char>(), ':'));
size_t num_toks = tokens.size();
if (num_toks == 0)
THROW_DOM("can't handle empty div func specification");
const string &kind = tokens[0];
vector<double> args;
args.reserve(num_toks - 1);
for (size_t i = 1; i < num_toks; i++)
args.push_back(atof(tokens[i].c_str()));
if (kind == "alpha") {
switch (num_toks) {
case 3: return new DivAlpha(args[0], args[1]);
case 2: return new DivAlpha(args[0]);
case 1: return new DivAlpha();
default: THROW_DOM("too many arguments for DivAlpha");
}
} else if (kind == "bc") {
switch (num_toks) {
case 2: return new DivBC(args[0]);
case 1: return new DivBC();
default: THROW_DOM("too many arguments for DivBC");
}
} else if (kind == "hellinger") {
switch (num_toks) {
case 2: return new DivHellinger(args[0]);
case 1: return new DivHellinger();
default: THROW_DOM("too many arguments for DivHellinger");
}
} else if (kind == "l2") {
switch (num_toks) {
case 2: return new DivL2(args[0]);
case 1: return new DivL2();
default: THROW_DOM("too many arguments for DivL2");
}
} else if (kind == "linear") {
switch (num_toks) {
case 2: return new DivLinear(args[0]);
case 1: return new DivLinear();
default: THROW_DOM("too many arguments for DivLinear");
}
} else if (kind == "renyi") {
switch (num_toks) {
case 3: return new DivRenyi(args[0], args[1]);
case 2: return new DivRenyi(args[0]);
case 1: return new DivRenyi();
default: THROW_DOM("too many arguments for DivRenyi");
}
} else {
THROW_DOM("unknown div func type '" + kind + "'");
}
}
}
<|endoftext|> |
<commit_before>/*
* CallRenderViewGL.cpp
*
* Copyright (C) 2009 by VISUS (Universitaet Stuttgart).
* Alle Rechte vorbehalten.
*/
#include "stdafx.h"
#include "mmcore/view/CallRenderViewGL.h"
using namespace megamol::core;
/*
* view::CallRenderViewGL::CallRenderViewGL
*/
view::CallRenderViewGL::CallRenderViewGL(void) : AbstractCallRenderView() {
// intentionally empty
}
/*
* view::CallRenderViewGL::CallRenderViewGL
*/
view::CallRenderViewGL::CallRenderViewGL(const CallRenderViewGL& src)
: AbstractCallRenderView() {
*this = src;
}
/*
* view::CallRenderViewGL::~CallRenderViewGL
*/
view::CallRenderViewGL::~CallRenderViewGL(void) {
// intentionally empty
}
/*
* view::CallRenderViewGL::operator=
*/
view::CallRenderViewGL& view::CallRenderViewGL::operator=(const view::CallRenderViewGL& rhs) {
view::AbstractCallRenderView::operator=(rhs);
_framebuffer = rhs._framebuffer;
return *this;
}
<commit_msg>callrenderviewgl caps<commit_after>/*
* CallRenderViewGL.cpp
*
* Copyright (C) 2009 by VISUS (Universitaet Stuttgart).
* Alle Rechte vorbehalten.
*/
#include "stdafx.h"
#include "mmcore/view/CallRenderViewGL.h"
using namespace megamol::core;
/*
* view::CallRenderViewGL::CallRenderViewGL
*/
view::CallRenderViewGL::CallRenderViewGL(void) : AbstractCallRenderView() {
caps.RequireOpenGL();
}
/*
* view::CallRenderViewGL::CallRenderViewGL
*/
view::CallRenderViewGL::CallRenderViewGL(const CallRenderViewGL& src)
: AbstractCallRenderView() {
*this = src;
}
/*
* view::CallRenderViewGL::~CallRenderViewGL
*/
view::CallRenderViewGL::~CallRenderViewGL(void) {
// intentionally empty
}
/*
* view::CallRenderViewGL::operator=
*/
view::CallRenderViewGL& view::CallRenderViewGL::operator=(const view::CallRenderViewGL& rhs) {
view::AbstractCallRenderView::operator=(rhs);
_framebuffer = rhs._framebuffer;
return *this;
}
<|endoftext|> |
<commit_before>#pragma once
#include <memory>
#include <utility>
#include <type_traits>
#include "signal.hpp"
namespace eventpp {
namespace details {
template<class E>
struct event_tag { using type = E; };
template<int N, int M>
struct choice: public choice<N+1, M> { };
template<int N>
struct choice<N, N> { };
}
template<class D>
struct Receiver: public std::enable_shared_from_this<D>
{ };
template<int S, class... T>
class BusBase;
template<int S, class E, class... O>
class BusBase<S, E, O...>: public BusBase<S, O...> {
using Base = BusBase<S, O...>;
protected:
using Base::get;
using Base::reg;
Signal<E>& get(details::event_tag<E>) {
return signal;
}
template<class C>
auto reg(details::choice<S-(sizeof...(O)+1), S>, std::weak_ptr<C> ptr)
-> decltype(std::declval<C>().receive(std::declval<E>())) {
signal.template add<C, &C::receive>(ptr);
Base::reg(details::choice<S-sizeof...(O), S>{}, ptr);
}
std::size_t size() const noexcept {
return signal.size() + Base::size();
}
private:
Signal<E> signal;
};
template<int S>
class BusBase<S> {
protected:
virtual ~BusBase() { }
void get();
void reg(details::choice<S, S>, std::weak_ptr<void>) { }
std::size_t size() const noexcept { return 0; }
};
template<class... T>
class Bus: public BusBase<sizeof...(T), T...> {
using Base = BusBase<sizeof...(T), T...>;
public:
using Base::size;
template<class E, void(*F)(const E &)>
void add() {
Signal<E> &signal = Base::get(details::event_tag<E>{});
signal.template add<F>();
}
template<class C, template<typename> class P>
typename std::enable_if<std::is_convertible<P<C>, std::weak_ptr<C>>::value, void>::type
reg(P<C> &ptr) {
auto wptr = static_cast<std::weak_ptr<C>>(ptr);
Base::reg(details::choice<0, sizeof...(T)>{}, wptr);
}
template<class E, class C, void(C::*M)(const E &) = &C::receive, template<typename> class P>
typename std::enable_if<std::is_convertible<P<C>, std::weak_ptr<C>>::value, void>::type
add(P<C> &ptr) {
Signal<E> &signal = Base::get(details::event_tag<E>{});
auto wptr = static_cast<std::weak_ptr<C>>(ptr);
signal.template add<C, M>(wptr);
}
template<class E, void(*F)(const E &)>
void remove() {
Signal<E> &signal = Base::get(details::event_tag<E>{});
signal.template remove<F>();
}
template<class E, class C, void(C::*M)(const E &) = &C::receive, template<typename> class P>
typename std::enable_if<std::is_convertible<P<C>, std::weak_ptr<C>>::value, void>::type
remove(P<C> &ptr) {
Signal<E> &signal = Base::get(details::event_tag<E>{});
auto wptr = static_cast<std::weak_ptr<C>>(ptr);
signal.template remove<C, M>(wptr);
}
template<class E, class... A>
void publish(A&&... args) {
Signal<E> &signal = Base::get(details::event_tag<E>{});
E e(std::forward<A>(args)...);
signal.publish(e);
}
};
}
<commit_msg>renaming<commit_after>#pragma once
#include <memory>
#include <utility>
#include <type_traits>
#include "signal.hpp"
namespace eventpp {
namespace details {
template<class E>
struct ETag { using type = E; };
template<int N, int M>
struct Choice: public Choice<N+1, M> { };
template<int N>
struct Choice<N, N> { };
}
template<class D>
struct Receiver: public std::enable_shared_from_this<D>
{ };
template<int S, class... T>
class BusBase;
template<int S, class E, class... O>
class BusBase<S, E, O...>: public BusBase<S, O...> {
using Base = BusBase<S, O...>;
protected:
using Base::get;
using Base::reg;
Signal<E>& get(details::ETag<E>) {
return signal;
}
template<class C>
auto reg(details::Choice<S-(sizeof...(O)+1), S>, std::weak_ptr<C> ptr)
-> decltype(std::declval<C>().receive(std::declval<E>())) {
signal.template add<C, &C::receive>(ptr);
Base::reg(details::Choice<S-sizeof...(O), S>{}, ptr);
}
std::size_t size() const noexcept {
return signal.size() + Base::size();
}
private:
Signal<E> signal;
};
template<int S>
class BusBase<S> {
protected:
virtual ~BusBase() { }
void get();
void reg(details::Choice<S, S>, std::weak_ptr<void>) { }
std::size_t size() const noexcept { return 0; }
};
template<class... T>
class Bus: public BusBase<sizeof...(T), T...> {
using Base = BusBase<sizeof...(T), T...>;
public:
using Base::size;
template<class E, void(*F)(const E &)>
void add() {
Signal<E> &signal = Base::get(details::ETag<E>{});
signal.template add<F>();
}
template<class C, template<typename> class P>
typename std::enable_if<std::is_convertible<P<C>, std::weak_ptr<C>>::value, void>::type
reg(P<C> &ptr) {
auto wptr = static_cast<std::weak_ptr<C>>(ptr);
Base::reg(details::Choice<0, sizeof...(T)>{}, wptr);
}
template<class E, class C, void(C::*M)(const E &) = &C::receive, template<typename> class P>
typename std::enable_if<std::is_convertible<P<C>, std::weak_ptr<C>>::value, void>::type
add(P<C> &ptr) {
Signal<E> &signal = Base::get(details::ETag<E>{});
auto wptr = static_cast<std::weak_ptr<C>>(ptr);
signal.template add<C, M>(wptr);
}
template<class E, void(*F)(const E &)>
void remove() {
Signal<E> &signal = Base::get(details::ETag<E>{});
signal.template remove<F>();
}
template<class E, class C, void(C::*M)(const E &) = &C::receive, template<typename> class P>
typename std::enable_if<std::is_convertible<P<C>, std::weak_ptr<C>>::value, void>::type
remove(P<C> &ptr) {
Signal<E> &signal = Base::get(details::ETag<E>{});
auto wptr = static_cast<std::weak_ptr<C>>(ptr);
signal.template remove<C, M>(wptr);
}
template<class E, class... A>
void publish(A&&... args) {
Signal<E> &signal = Base::get(details::ETag<E>{});
E e(std::forward<A>(args)...);
signal.publish(e);
}
};
}
<|endoftext|> |
<commit_before>/*
* Copyright 2009, 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.
*/
// This file contains the definition of class TextWriter. The
// tests are in string_writer_test.cc.
#include <stdarg.h>
#include "utils/cross/text_writer.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
using std::string;
namespace o3d {
TextWriter::TextWriter(NewLine new_line)
: new_line_(new_line) {
}
TextWriter::~TextWriter() {
}
void TextWriter::WriteString(const string& s) {
for (size_t i = 0; i != s.length(); ++i) {
WriteChar(s[i]);
}
}
void TextWriter::WriteBool(bool value) {
if (value) {
WriteString(string("true"));
} else {
WriteString(string("false"));
}
}
void TextWriter::WriteInt(int value) {
WriteString(StringPrintf("%d", value));
}
void TextWriter::WriteUnsignedInt(unsigned int value) {
WriteString(StringPrintf("%u", value));
}
void TextWriter::WriteFloat(float value) {
WriteString(StringPrintf("%g", value));
}
void TextWriter::WriteFormatted(const char* format, ...) {
va_list args;
va_start(args, format);
string formatted;
base::StringAppendV(&formatted, format, args);
va_end(args);
WriteString(formatted);
}
void TextWriter::WriteNewLine() {
switch (new_line_) {
case CR:
WriteChar('\r');
break;
case CR_LF:
WriteChar('\r');
WriteChar('\n');
break;
case LF:
WriteChar('\n');
break;
}
}
void TextWriter::Close() {
}
} // namespace o3d
<commit_msg>o3d: Fix o3d build.<commit_after>/*
* Copyright 2009, 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.
*/
// This file contains the definition of class TextWriter. The
// tests are in string_writer_test.cc.
#include <stdarg.h>
#include "utils/cross/text_writer.h"
#include "base/string_util.h"
using std::string;
namespace o3d {
TextWriter::TextWriter(NewLine new_line)
: new_line_(new_line) {
}
TextWriter::~TextWriter() {
}
void TextWriter::WriteString(const string& s) {
for (size_t i = 0; i != s.length(); ++i) {
WriteChar(s[i]);
}
}
void TextWriter::WriteBool(bool value) {
if (value) {
WriteString(string("true"));
} else {
WriteString(string("false"));
}
}
void TextWriter::WriteInt(int value) {
WriteString(StringPrintf("%d", value));
}
void TextWriter::WriteUnsignedInt(unsigned int value) {
WriteString(StringPrintf("%u", value));
}
void TextWriter::WriteFloat(float value) {
WriteString(StringPrintf("%g", value));
}
void TextWriter::WriteFormatted(const char* format, ...) {
va_list args;
va_start(args, format);
string formatted;
StringAppendV(&formatted, format, args);
va_end(args);
WriteString(formatted);
}
void TextWriter::WriteNewLine() {
switch (new_line_) {
case CR:
WriteChar('\r');
break;
case CR_LF:
WriteChar('\r');
WriteChar('\n');
break;
case LF:
WriteChar('\n');
break;
}
}
void TextWriter::Close() {
}
} // namespace o3d
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ppapi/native_client/src/trusted/plugin/pnacl_resources.h"
#include "native_client/src/include/portability_io.h"
#include "native_client/src/shared/platform/nacl_check.h"
#include "native_client/src/trusted/desc/nacl_desc_wrapper.h"
#include "ppapi/c/pp_errors.h"
#include "ppapi/native_client/src/trusted/plugin/file_utils.h"
#include "ppapi/native_client/src/trusted/plugin/manifest.h"
#include "ppapi/native_client/src/trusted/plugin/plugin.h"
#include "ppapi/native_client/src/trusted/plugin/pnacl_coordinator.h"
#include "ppapi/native_client/src/trusted/plugin/utility.h"
#include "third_party/jsoncpp/source/include/json/reader.h"
#include "third_party/jsoncpp/source/include/json/value.h"
namespace plugin {
namespace {
const PPB_NaCl_Private* GetNaClInterface() {
pp::Module *module = pp::Module::Get();
CHECK(module);
return static_cast<const PPB_NaCl_Private*>(
module->GetBrowserInterface(PPB_NACL_PRIVATE_INTERFACE));
}
} // namespace
static const char kPnaclBaseUrl[] = "chrome://pnacl-translator/";
const char PnaclUrls::kResourceInfoUrl[] = "pnacl.json";
nacl::string PnaclUrls::GetBaseUrl() {
return nacl::string(kPnaclBaseUrl);
}
// Determine if a URL is for a pnacl-component file, or if it is some other
// type of URL (e.g., http://, https://, chrome-extension://).
// The URL could be one of the other variants for shared libraries
// served from the web.
bool PnaclUrls::IsPnaclComponent(const nacl::string& full_url) {
return full_url.find(kPnaclBaseUrl, 0) == 0;
}
// Convert a URL to a filename accepted by GetReadonlyPnaclFd.
// Must be kept in sync with chrome/browser/nacl_host/nacl_file_host.
nacl::string PnaclUrls::PnaclComponentURLToFilename(
const nacl::string& full_url) {
// strip component scheme.
nacl::string r = full_url.substr(nacl::string(kPnaclBaseUrl).length());
// Use white-listed-chars.
size_t replace_pos;
static const char* white_list = "abcdefghijklmnopqrstuvwxyz0123456789_";
replace_pos = r.find_first_not_of(white_list);
while(replace_pos != nacl::string::npos) {
r = r.replace(replace_pos, 1, "_");
replace_pos = r.find_first_not_of(white_list);
}
return r;
}
//////////////////////////////////////////////////////////////////////
PnaclResources::~PnaclResources() {
for (std::map<nacl::string, nacl::DescWrapper*>::iterator
i = resource_wrappers_.begin(), e = resource_wrappers_.end();
i != e;
++i) {
delete i->second;
}
resource_wrappers_.clear();
}
// static
int32_t PnaclResources::GetPnaclFD(Plugin* plugin, const char* filename) {
PP_FileHandle file_handle =
plugin->nacl_interface()->GetReadonlyPnaclFd(filename);
if (file_handle == PP_kInvalidFileHandle)
return -1;
#if NACL_WINDOWS
//////// Now try the posix view.
int32_t posix_desc = _open_osfhandle(reinterpret_cast<intptr_t>(file_handle),
_O_RDONLY | _O_BINARY);
if (posix_desc == -1) {
PLUGIN_PRINTF((
"PnaclResources::GetPnaclFD failed to convert HANDLE to posix\n"));
// Close the Windows HANDLE if it can't be converted.
CloseHandle(file_handle);
}
return posix_desc;
#else
return file_handle;
#endif
}
nacl::DescWrapper* PnaclResources::WrapperForUrl(const nacl::string& url) {
CHECK(resource_wrappers_.find(url) != resource_wrappers_.end());
return resource_wrappers_[url];
}
void PnaclResources::ReadResourceInfo(
const nacl::string& resource_info_url,
const pp::CompletionCallback& resource_info_read_cb) {
PLUGIN_PRINTF(("PnaclResources::ReadResourceInfo\n"));
nacl::string full_url;
ErrorInfo error_info;
if (!manifest_->ResolveURL(resource_info_url, &full_url, &error_info)) {
ReadResourceInfoError(nacl::string("failed to resolve ") +
resource_info_url + ": " +
error_info.message() + ".");
return;
}
PLUGIN_PRINTF(("Resolved resources info url: %s\n", full_url.c_str()));
nacl::string resource_info_filename =
PnaclUrls::PnaclComponentURLToFilename(full_url);
PLUGIN_PRINTF(("Pnacl-converted resources info url: %s\n",
resource_info_filename.c_str()));
int32_t fd = GetPnaclFD(plugin_, resource_info_filename.c_str());
if (fd < 0) {
// File-open failed. Assume this means that the file is
// not actually installed.
ReadResourceInfoError(
nacl::string("The Portable Native Client (pnacl) component is not "
"installed. Please consult chrome://components for more "
"information."));
return;
}
nacl::string json_buffer;
file_utils::StatusCode status = file_utils::SlurpFile(fd, json_buffer);
if (status != file_utils::PLUGIN_FILE_SUCCESS) {
ReadResourceInfoError(
nacl::string("PnaclResources::ReadResourceInfo reading "
"failed for: ") + resource_info_filename);
return;
}
// Finally, we have the resource info JSON data in json_buffer.
PLUGIN_PRINTF(("Resource info JSON data:\n%s\n", json_buffer.c_str()));
nacl::string error_message;
if (!ParseResourceInfo(json_buffer, error_message)) {
ReadResourceInfoError(nacl::string("Parsing resource info failed: ") +
error_message + "\n");
return;
}
// Done. Queue the completion callback.
pp::Core* core = pp::Module::Get()->core();
core->CallOnMainThread(0, resource_info_read_cb, PP_OK);
}
void PnaclResources::ReadResourceInfoError(const nacl::string& msg) {
coordinator_->ReportNonPpapiError(PP_NACL_ERROR_PNACL_RESOURCE_FETCH, msg);
}
bool PnaclResources::ParseResourceInfo(const nacl::string& buf,
nacl::string& errmsg) {
// Expect the JSON file to contain a top-level object (dictionary).
Json::Reader json_reader;
Json::Value json_data;
if (!json_reader.parse(buf, json_data)) {
errmsg = nacl::string("JSON parse error: ") +
json_reader.getFormatedErrorMessages();
return false;
}
if (!json_data.isObject()) {
errmsg = nacl::string("Malformed JSON dictionary");
return false;
}
if (json_data.isMember("pnacl-llc-name")) {
Json::Value json_name = json_data["pnacl-llc-name"];
if (json_name.isString()) {
llc_tool_name = json_name.asString();
PLUGIN_PRINTF(("Set llc_tool_name=%s\n", llc_tool_name.c_str()));
}
}
if (json_data.isMember("pnacl-ld-name")) {
Json::Value json_name = json_data["pnacl-ld-name"];
if (json_name.isString()) {
ld_tool_name = json_name.asString();
PLUGIN_PRINTF(("Set ld_tool_name=%s\n", ld_tool_name.c_str()));
}
}
return true;
}
nacl::string PnaclResources::GetFullUrl(
const nacl::string& partial_url, const nacl::string& sandbox_arch) const {
nacl::string full_url;
ErrorInfo error_info;
const nacl::string& url_with_platform_prefix =
sandbox_arch + "/" + partial_url;
if (!manifest_->ResolveURL(url_with_platform_prefix,
&full_url,
&error_info)) {
PLUGIN_PRINTF(("PnaclResources::GetFullUrl failed: %s.\n",
error_info.message().c_str()));
return "";
}
return full_url;
}
void PnaclResources::StartLoad(
const pp::CompletionCallback& all_loaded_callback) {
PLUGIN_PRINTF(("PnaclResources::StartLoad\n"));
std::vector<nacl::string> resource_urls;
resource_urls.push_back(GetLlcUrl());
resource_urls.push_back(GetLdUrl());
PLUGIN_PRINTF(("PnaclResources::StartLoad -- local install of PNaCl.\n"));
// Do a blocking load of each of the resources.
int32_t result = PP_OK;
for (size_t i = 0; i < resource_urls.size(); ++i) {
nacl::string full_url = GetFullUrl(
resource_urls[i], plugin_->nacl_interface()->GetSandboxArch());
if (full_url == "") {
coordinator_->ReportNonPpapiError(
PP_NACL_ERROR_PNACL_RESOURCE_FETCH,
nacl::string("failed to resolve ") + resource_urls[i] + ".");
break;
}
nacl::string filename = PnaclUrls::PnaclComponentURLToFilename(full_url);
int32_t fd = PnaclResources::GetPnaclFD(plugin_, filename.c_str());
if (fd < 0) {
// File-open failed. Assume this means that the file is
// not actually installed. This shouldn't actually occur since
// ReadResourceInfo() should happen first, and error out.
coordinator_->ReportNonPpapiError(
PP_NACL_ERROR_PNACL_RESOURCE_FETCH,
nacl::string("The Portable Native Client (pnacl) component is not "
"installed. Please consult chrome://components for more "
"information."));
result = PP_ERROR_FILENOTFOUND;
break;
} else {
resource_wrappers_[resource_urls[i]] =
plugin_->wrapper_factory()->MakeFileDesc(fd, O_RDONLY);
}
}
// We're done! Queue the callback.
pp::Core* core = pp::Module::Get()->core();
core->CallOnMainThread(0, all_loaded_callback, result);
}
} // namespace plugin
<commit_msg>Remove unused function {anonymous}::GetNaClInterface() in pnacl_resources.cc<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ppapi/native_client/src/trusted/plugin/pnacl_resources.h"
#include "native_client/src/include/portability_io.h"
#include "native_client/src/shared/platform/nacl_check.h"
#include "native_client/src/trusted/desc/nacl_desc_wrapper.h"
#include "ppapi/c/pp_errors.h"
#include "ppapi/native_client/src/trusted/plugin/file_utils.h"
#include "ppapi/native_client/src/trusted/plugin/manifest.h"
#include "ppapi/native_client/src/trusted/plugin/plugin.h"
#include "ppapi/native_client/src/trusted/plugin/pnacl_coordinator.h"
#include "ppapi/native_client/src/trusted/plugin/utility.h"
#include "third_party/jsoncpp/source/include/json/reader.h"
#include "third_party/jsoncpp/source/include/json/value.h"
namespace plugin {
static const char kPnaclBaseUrl[] = "chrome://pnacl-translator/";
const char PnaclUrls::kResourceInfoUrl[] = "pnacl.json";
nacl::string PnaclUrls::GetBaseUrl() {
return nacl::string(kPnaclBaseUrl);
}
// Determine if a URL is for a pnacl-component file, or if it is some other
// type of URL (e.g., http://, https://, chrome-extension://).
// The URL could be one of the other variants for shared libraries
// served from the web.
bool PnaclUrls::IsPnaclComponent(const nacl::string& full_url) {
return full_url.find(kPnaclBaseUrl, 0) == 0;
}
// Convert a URL to a filename accepted by GetReadonlyPnaclFd.
// Must be kept in sync with chrome/browser/nacl_host/nacl_file_host.
nacl::string PnaclUrls::PnaclComponentURLToFilename(
const nacl::string& full_url) {
// strip component scheme.
nacl::string r = full_url.substr(nacl::string(kPnaclBaseUrl).length());
// Use white-listed-chars.
size_t replace_pos;
static const char* white_list = "abcdefghijklmnopqrstuvwxyz0123456789_";
replace_pos = r.find_first_not_of(white_list);
while(replace_pos != nacl::string::npos) {
r = r.replace(replace_pos, 1, "_");
replace_pos = r.find_first_not_of(white_list);
}
return r;
}
//////////////////////////////////////////////////////////////////////
PnaclResources::~PnaclResources() {
for (std::map<nacl::string, nacl::DescWrapper*>::iterator
i = resource_wrappers_.begin(), e = resource_wrappers_.end();
i != e;
++i) {
delete i->second;
}
resource_wrappers_.clear();
}
// static
int32_t PnaclResources::GetPnaclFD(Plugin* plugin, const char* filename) {
PP_FileHandle file_handle =
plugin->nacl_interface()->GetReadonlyPnaclFd(filename);
if (file_handle == PP_kInvalidFileHandle)
return -1;
#if NACL_WINDOWS
//////// Now try the posix view.
int32_t posix_desc = _open_osfhandle(reinterpret_cast<intptr_t>(file_handle),
_O_RDONLY | _O_BINARY);
if (posix_desc == -1) {
PLUGIN_PRINTF((
"PnaclResources::GetPnaclFD failed to convert HANDLE to posix\n"));
// Close the Windows HANDLE if it can't be converted.
CloseHandle(file_handle);
}
return posix_desc;
#else
return file_handle;
#endif
}
nacl::DescWrapper* PnaclResources::WrapperForUrl(const nacl::string& url) {
CHECK(resource_wrappers_.find(url) != resource_wrappers_.end());
return resource_wrappers_[url];
}
void PnaclResources::ReadResourceInfo(
const nacl::string& resource_info_url,
const pp::CompletionCallback& resource_info_read_cb) {
PLUGIN_PRINTF(("PnaclResources::ReadResourceInfo\n"));
nacl::string full_url;
ErrorInfo error_info;
if (!manifest_->ResolveURL(resource_info_url, &full_url, &error_info)) {
ReadResourceInfoError(nacl::string("failed to resolve ") +
resource_info_url + ": " +
error_info.message() + ".");
return;
}
PLUGIN_PRINTF(("Resolved resources info url: %s\n", full_url.c_str()));
nacl::string resource_info_filename =
PnaclUrls::PnaclComponentURLToFilename(full_url);
PLUGIN_PRINTF(("Pnacl-converted resources info url: %s\n",
resource_info_filename.c_str()));
int32_t fd = GetPnaclFD(plugin_, resource_info_filename.c_str());
if (fd < 0) {
// File-open failed. Assume this means that the file is
// not actually installed.
ReadResourceInfoError(
nacl::string("The Portable Native Client (pnacl) component is not "
"installed. Please consult chrome://components for more "
"information."));
return;
}
nacl::string json_buffer;
file_utils::StatusCode status = file_utils::SlurpFile(fd, json_buffer);
if (status != file_utils::PLUGIN_FILE_SUCCESS) {
ReadResourceInfoError(
nacl::string("PnaclResources::ReadResourceInfo reading "
"failed for: ") + resource_info_filename);
return;
}
// Finally, we have the resource info JSON data in json_buffer.
PLUGIN_PRINTF(("Resource info JSON data:\n%s\n", json_buffer.c_str()));
nacl::string error_message;
if (!ParseResourceInfo(json_buffer, error_message)) {
ReadResourceInfoError(nacl::string("Parsing resource info failed: ") +
error_message + "\n");
return;
}
// Done. Queue the completion callback.
pp::Core* core = pp::Module::Get()->core();
core->CallOnMainThread(0, resource_info_read_cb, PP_OK);
}
void PnaclResources::ReadResourceInfoError(const nacl::string& msg) {
coordinator_->ReportNonPpapiError(PP_NACL_ERROR_PNACL_RESOURCE_FETCH, msg);
}
bool PnaclResources::ParseResourceInfo(const nacl::string& buf,
nacl::string& errmsg) {
// Expect the JSON file to contain a top-level object (dictionary).
Json::Reader json_reader;
Json::Value json_data;
if (!json_reader.parse(buf, json_data)) {
errmsg = nacl::string("JSON parse error: ") +
json_reader.getFormatedErrorMessages();
return false;
}
if (!json_data.isObject()) {
errmsg = nacl::string("Malformed JSON dictionary");
return false;
}
if (json_data.isMember("pnacl-llc-name")) {
Json::Value json_name = json_data["pnacl-llc-name"];
if (json_name.isString()) {
llc_tool_name = json_name.asString();
PLUGIN_PRINTF(("Set llc_tool_name=%s\n", llc_tool_name.c_str()));
}
}
if (json_data.isMember("pnacl-ld-name")) {
Json::Value json_name = json_data["pnacl-ld-name"];
if (json_name.isString()) {
ld_tool_name = json_name.asString();
PLUGIN_PRINTF(("Set ld_tool_name=%s\n", ld_tool_name.c_str()));
}
}
return true;
}
nacl::string PnaclResources::GetFullUrl(
const nacl::string& partial_url, const nacl::string& sandbox_arch) const {
nacl::string full_url;
ErrorInfo error_info;
const nacl::string& url_with_platform_prefix =
sandbox_arch + "/" + partial_url;
if (!manifest_->ResolveURL(url_with_platform_prefix,
&full_url,
&error_info)) {
PLUGIN_PRINTF(("PnaclResources::GetFullUrl failed: %s.\n",
error_info.message().c_str()));
return "";
}
return full_url;
}
void PnaclResources::StartLoad(
const pp::CompletionCallback& all_loaded_callback) {
PLUGIN_PRINTF(("PnaclResources::StartLoad\n"));
std::vector<nacl::string> resource_urls;
resource_urls.push_back(GetLlcUrl());
resource_urls.push_back(GetLdUrl());
PLUGIN_PRINTF(("PnaclResources::StartLoad -- local install of PNaCl.\n"));
// Do a blocking load of each of the resources.
int32_t result = PP_OK;
for (size_t i = 0; i < resource_urls.size(); ++i) {
nacl::string full_url = GetFullUrl(
resource_urls[i], plugin_->nacl_interface()->GetSandboxArch());
if (full_url == "") {
coordinator_->ReportNonPpapiError(
PP_NACL_ERROR_PNACL_RESOURCE_FETCH,
nacl::string("failed to resolve ") + resource_urls[i] + ".");
break;
}
nacl::string filename = PnaclUrls::PnaclComponentURLToFilename(full_url);
int32_t fd = PnaclResources::GetPnaclFD(plugin_, filename.c_str());
if (fd < 0) {
// File-open failed. Assume this means that the file is
// not actually installed. This shouldn't actually occur since
// ReadResourceInfo() should happen first, and error out.
coordinator_->ReportNonPpapiError(
PP_NACL_ERROR_PNACL_RESOURCE_FETCH,
nacl::string("The Portable Native Client (pnacl) component is not "
"installed. Please consult chrome://components for more "
"information."));
result = PP_ERROR_FILENOTFOUND;
break;
} else {
resource_wrappers_[resource_urls[i]] =
plugin_->wrapper_factory()->MakeFileDesc(fd, O_RDONLY);
}
}
// We're done! Queue the callback.
pp::Core* core = pp::Module::Get()->core();
core->CallOnMainThread(0, all_loaded_callback, result);
}
} // namespace plugin
<|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 .
*/
#ifndef INCLUDED_OOX_HELPER_BINARYOUTPUTSTREAM_HXX
#define INCLUDED_OOX_HELPER_BINARYOUTPUTSTREAM_HXX
#include <oox/helper/binarystreambase.hxx>
namespace com { namespace sun { namespace star {
namespace io { class XOutputStream; }
} } }
namespace oox {
/** Interface for binary output stream classes.
The binary data in the stream is written in little-endian format.
*/
class BinaryOutputStream : public virtual BinaryStreamBase
{
public:
/** Derived classes implement writing the contents of the passed data
sequence.
@param nAtomSize
The size of the elements in the memory block, if available. Derived
classes may be interested in this information.
*/
virtual void writeData( const StreamDataSequence& rData, size_t nAtomSize = 1 ) = 0;
/** Derived classes implement writing the contents of the (preallocated!)
memory buffer pMem.
@param nAtomSize
The size of the elements in the memory block, if available. Derived
classes may be interested in this information.
*/
virtual void writeMemory( const void* pMem, sal_Int32 nBytes, size_t nAtomSize = 1 ) = 0;
/** Writes a value to the stream and converts it to platform byte order.
All data types supported by the ByteOrderConverter class can be used.
*/
template< typename Type >
void writeValue( Type nValue );
template< typename Type >
void writeArray( Type* opnArray, sal_Int32 nElemCount );
/** Stream operator for all data types supported by the writeValue() function. */
template< typename Type >
BinaryOutputStream& operator<<( Type nValue ) { writeValue( nValue ); return *this; }
void writeCompressedUnicodeArray( const OUString& rString, bool bCompressed, bool bAllowNulChars = false );
void writeCharArrayUC( const OUString& rString, rtl_TextEncoding eTextEnc, bool bAllowNulChars = false );
void writeUnicodeArray( const OUString& rString, bool bAllowNulChars = false );
protected:
/** This dummy default c'tor will never call the c'tor of the virtual base
class BinaryStreamBase as this class cannot be instantiated directly. */
BinaryOutputStream() : BinaryStreamBase( false ) {}
};
template< typename Type >
void BinaryOutputStream::writeArray( Type* opnArray, sal_Int32 nElemCount )
{
sal_Int32 nWriteSize = getLimitedValue< sal_Int32, sal_Int32 >( nElemCount, 0, SAL_MAX_INT32 / sizeof( Type ) ) * sizeof( Type );
ByteOrderConverter::convertLittleEndianArray( opnArray, static_cast< size_t >( nElemCount ) );
writeMemory( opnArray, nWriteSize, sizeof( Type ) );
}
typedef ::boost::shared_ptr< BinaryOutputStream > BinaryOutputStreamRef;
template< typename Type >
void BinaryOutputStream::writeValue( Type nValue )
{
ByteOrderConverter::convertLittleEndian( nValue );
writeMemory( &nValue, static_cast< sal_Int32 >( sizeof( Type ) ), sizeof( Type ) );
}
/** Wraps a UNO output stream and provides convenient access functions.
The binary data in the stream is written in little-endian format.
*/
class BinaryXOutputStream : public BinaryXSeekableStream, public BinaryOutputStream
{
public:
/** Constructs the wrapper object for the passed output stream.
@param rxOutStream
The com.sun.star.io.XOutputStream interface of the output stream to
be wrapped.
@param bAutoClose
True = automatically close the wrapped output stream on destruction
of this wrapper or when close() is called.
*/
explicit BinaryXOutputStream(
const ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >& rxOutStrm,
bool bAutoClose );
virtual ~BinaryXOutputStream();
/** Flushes and closes the output stream. Does also close the wrapped UNO
output stream if bAutoClose has been set to true in the constructor. */
void close() SAL_OVERRIDE;
/** Writes the passed data sequence. */
virtual void writeData( const StreamDataSequence& rData, size_t nAtomSize = 1 ) SAL_OVERRIDE;
/** Write nBytes bytes from the (preallocated!) buffer pMem. */
virtual void writeMemory( const void* pMem, sal_Int32 nBytes, size_t nAtomSize = 1 ) SAL_OVERRIDE;
/** Stream operator for all data types supported by the writeValue() function. */
template< typename Type >
BinaryXOutputStream& operator<<( Type nValue ) { writeValue( nValue ); return *this; }
/** Returns the XOutputStream interface of the wrapped output stream. */
::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >
getXOutputStream() const { return mxOutStrm; }
private:
StreamDataSequence maBuffer; ///< Data buffer used in writeMemory() function.
::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >
mxOutStrm; ///< Reference to the output stream.
bool mbAutoClose; ///< True = automatically close stream on destruction.
};
/** Wraps a StreamDataSequence and provides convenient access functions.
The binary data in the stream is written in little-endian format. After
construction, the stream points to the beginning of the passed data
sequence. The data sequence is expanded automatically while writing to it.
*/
class OOX_DLLPUBLIC SequenceOutputStream : public SequenceSeekableStream, public BinaryOutputStream
{
public:
/** Constructs the wrapper object for the passed data sequence.
@attention
The passed data sequence MUST live at least as long as this stream
wrapper. The data sequence MUST NOT be changed from outside as long
as this stream wrapper is used to write to it.
*/
explicit SequenceOutputStream( StreamDataSequence& rData );
/** Writes the passed data sequence. */
virtual void writeData( const StreamDataSequence& rData, size_t nAtomSize = 1 ) SAL_OVERRIDE;
/** Write nBytes bytes from the (preallocated!) buffer pMem. */
virtual void writeMemory( const void* pMem, sal_Int32 nBytes, size_t nAtomSize = 1 ) SAL_OVERRIDE;
/** Stream operator for all data types supported by the writeValue() function. */
template< typename Type >
SequenceOutputStream& operator<<( Type nValue ) { writeValue( nValue ); return *this; }
};
} // namespace oox
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>fix writing const arrays on big endian<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 .
*/
#ifndef INCLUDED_OOX_HELPER_BINARYOUTPUTSTREAM_HXX
#define INCLUDED_OOX_HELPER_BINARYOUTPUTSTREAM_HXX
#include <memory>
#include <boost/shared_array.hpp>
#include <oox/helper/binarystreambase.hxx>
namespace com { namespace sun { namespace star {
namespace io { class XOutputStream; }
} } }
namespace oox {
/** Interface for binary output stream classes.
The binary data in the stream is written in little-endian format.
*/
class BinaryOutputStream : public virtual BinaryStreamBase
{
public:
/** Derived classes implement writing the contents of the passed data
sequence.
@param nAtomSize
The size of the elements in the memory block, if available. Derived
classes may be interested in this information.
*/
virtual void writeData( const StreamDataSequence& rData, size_t nAtomSize = 1 ) = 0;
/** Derived classes implement writing the contents of the (preallocated!)
memory buffer pMem.
@param nAtomSize
The size of the elements in the memory block, if available. Derived
classes may be interested in this information.
*/
virtual void writeMemory( const void* pMem, sal_Int32 nBytes, size_t nAtomSize = 1 ) = 0;
/** Writes a value to the stream and converts it to platform byte order.
All data types supported by the ByteOrderConverter class can be used.
*/
template< typename Type >
void writeValue( Type nValue );
template< typename Type >
void writeArray( Type* opnArray, sal_Int32 nElemCount );
template< typename Type >
void writeArray( const Type* opnArray, sal_Int32 nElemCount );
/** Stream operator for all data types supported by the writeValue() function. */
template< typename Type >
BinaryOutputStream& operator<<( Type nValue ) { writeValue( nValue ); return *this; }
void writeCompressedUnicodeArray( const OUString& rString, bool bCompressed, bool bAllowNulChars = false );
void writeCharArrayUC( const OUString& rString, rtl_TextEncoding eTextEnc, bool bAllowNulChars = false );
void writeUnicodeArray( const OUString& rString, bool bAllowNulChars = false );
protected:
/** This dummy default c'tor will never call the c'tor of the virtual base
class BinaryStreamBase as this class cannot be instantiated directly. */
BinaryOutputStream() : BinaryStreamBase( false ) {}
};
template< typename Type >
void BinaryOutputStream::writeArray( Type* opnArray, sal_Int32 nElemCount )
{
sal_Int32 nWriteSize = getLimitedValue< sal_Int32, sal_Int32 >( nElemCount, 0, SAL_MAX_INT32 / sizeof( Type ) ) * sizeof( Type );
ByteOrderConverter::convertLittleEndianArray( opnArray, static_cast< size_t >( nElemCount ) );
writeMemory( opnArray, nWriteSize, sizeof( Type ) );
}
template< typename Type >
void BinaryOutputStream::writeArray( const Type* opnArray, sal_Int32 nElemCount )
{
boost::shared_array<Type> pArray(new Type[nElemCount]);
std::uninitialized_copy(opnArray, opnArray + nElemCount, pArray.get());
writeArray(pArray.get(), nElemCount);
}
typedef ::boost::shared_ptr< BinaryOutputStream > BinaryOutputStreamRef;
template< typename Type >
void BinaryOutputStream::writeValue( Type nValue )
{
ByteOrderConverter::convertLittleEndian( nValue );
writeMemory( &nValue, static_cast< sal_Int32 >( sizeof( Type ) ), sizeof( Type ) );
}
/** Wraps a UNO output stream and provides convenient access functions.
The binary data in the stream is written in little-endian format.
*/
class BinaryXOutputStream : public BinaryXSeekableStream, public BinaryOutputStream
{
public:
/** Constructs the wrapper object for the passed output stream.
@param rxOutStream
The com.sun.star.io.XOutputStream interface of the output stream to
be wrapped.
@param bAutoClose
True = automatically close the wrapped output stream on destruction
of this wrapper or when close() is called.
*/
explicit BinaryXOutputStream(
const ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >& rxOutStrm,
bool bAutoClose );
virtual ~BinaryXOutputStream();
/** Flushes and closes the output stream. Does also close the wrapped UNO
output stream if bAutoClose has been set to true in the constructor. */
void close() SAL_OVERRIDE;
/** Writes the passed data sequence. */
virtual void writeData( const StreamDataSequence& rData, size_t nAtomSize = 1 ) SAL_OVERRIDE;
/** Write nBytes bytes from the (preallocated!) buffer pMem. */
virtual void writeMemory( const void* pMem, sal_Int32 nBytes, size_t nAtomSize = 1 ) SAL_OVERRIDE;
/** Stream operator for all data types supported by the writeValue() function. */
template< typename Type >
BinaryXOutputStream& operator<<( Type nValue ) { writeValue( nValue ); return *this; }
/** Returns the XOutputStream interface of the wrapped output stream. */
::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >
getXOutputStream() const { return mxOutStrm; }
private:
StreamDataSequence maBuffer; ///< Data buffer used in writeMemory() function.
::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >
mxOutStrm; ///< Reference to the output stream.
bool mbAutoClose; ///< True = automatically close stream on destruction.
};
/** Wraps a StreamDataSequence and provides convenient access functions.
The binary data in the stream is written in little-endian format. After
construction, the stream points to the beginning of the passed data
sequence. The data sequence is expanded automatically while writing to it.
*/
class OOX_DLLPUBLIC SequenceOutputStream : public SequenceSeekableStream, public BinaryOutputStream
{
public:
/** Constructs the wrapper object for the passed data sequence.
@attention
The passed data sequence MUST live at least as long as this stream
wrapper. The data sequence MUST NOT be changed from outside as long
as this stream wrapper is used to write to it.
*/
explicit SequenceOutputStream( StreamDataSequence& rData );
/** Writes the passed data sequence. */
virtual void writeData( const StreamDataSequence& rData, size_t nAtomSize = 1 ) SAL_OVERRIDE;
/** Write nBytes bytes from the (preallocated!) buffer pMem. */
virtual void writeMemory( const void* pMem, sal_Int32 nBytes, size_t nAtomSize = 1 ) SAL_OVERRIDE;
/** Stream operator for all data types supported by the writeValue() function. */
template< typename Type >
SequenceOutputStream& operator<<( Type nValue ) { writeValue( nValue ); return *this; }
};
} // namespace oox
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*
* This file is part of accounts-ui
*
* Copyright (C) 2009-2010 Nokia Corporation.
*
* Contact: Alberto Mardegan <[email protected]>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include "provider-plugin-process.h"
#include "add-account-page.h"
#include "accountsettingspage.h"
#include "generic-account-setup-context.h"
#include "provider-plugin-process-priv.h"
#include <Accounts/Account>
#include <Accounts/Manager>
#include <MComponentCache>
#include <MApplication>
#include <MApplicationWindow>
#include <QDebug>
#include <QFile>
#include <QLocalSocket>
#include <QProcess>
namespace AccountsUI {
static ProviderPluginProcess *plugin_instance = 0;
void ProviderPluginProcessPrivate::printAccountId()
{
Accounts::Account *account = context()->account();
QByteArray ba = QString("%1 %2").arg(account->id()).arg(QString::number(returnToApp)).toAscii();
if (!serverName.isEmpty()) {
QLocalSocket *socket = new QLocalSocket();
connect(socket, SIGNAL(error(QLocalSocket::LocalSocketError)),
this, SLOT(socketConnectionError(QLocalSocket::LocalSocketError)));
socket->connectToServer(serverName);
socket->write(ba);
socket->flush();
socket->close();
} else {
QFile output;
output.open(STDOUT_FILENO, QIODevice::WriteOnly);
output.write(ba.constData());
output.close();
}
}
void ProviderPluginProcessPrivate::socketConnectionError(QLocalSocket::LocalSocketError status)
{
qDebug() << Q_FUNC_INFO << status;
}
AbstractAccountSetupContext *ProviderPluginProcessPrivate::context() const
{
if (!m_context) {
m_context = q_ptr->accountSetupContext(account, setupType, q_ptr);
m_context->setServiceType(serviceType);
}
return m_context;
}
void ProviderPluginProcessPrivate::serviceEnabled(Accounts::Service *service)
{
qDebug() << Q_FUNC_INFO << service->name();
QDomElement root = service->domDocument().documentElement();
QDomElement handler = root.firstChildElement("handler");
if (!handler.isNull()) {
QString type = handler.attribute("type");
if (type == "command") {
/* Syntax for the service file:
*
* <handler type="command">/usr/bin/appname [args]...</handler>
*/
QString command = handler.text();
qDebug() << "Executing" << command;
/* The account plugin process is going to die very soon; the
* handler must be started as a detached process, for it to
* continue to live. */
bool ok = QProcess::startDetached(command);
if (!ok)
qWarning() << "Could not execute:" << command;
}
/* support more types (e.g., D-Bus services) here */
}
}
void ProviderPluginProcessPrivate::accountSaved()
{
qDebug() << Q_FUNC_INFO;
account->selectService();
if (account->enabled()) {
/* Go through the enabled services and run the activation command, if
* present */
foreach (Accounts::Service *service, account->services()) {
account->selectService(service);
if (account->enabled() && !enabledServices.contains(service))
serviceEnabled(service);
}
}
}
void ProviderPluginProcessPrivate::monitorServices()
{
connect(account, SIGNAL(synced()), this, SLOT(accountSaved()));
/* If we are editing an account, get the list of services initially
* enabled, to avoid starting up their handlers for no reason */
account->selectService();
if (setupType == EditExisting && account->enabled()) {
foreach (Accounts::Service *service, account->services()) {
account->selectService(service);
if (account->enabled())
enabledServices.append(service);
}
}
}
ProviderPluginProcess::ProviderPluginProcess(AccountPluginInterface *plugin,
int &argc, char **argv)
: d_ptr(new ProviderPluginProcessPrivate(plugin, argc, argv))
{
Q_D(ProviderPluginProcess);
init(argc, argv);
d->m_context = plugin->accountSetupContext(d->account, d->setupType, this);
d->m_context->setServiceType(d->serviceType);
}
ProviderPluginProcess::ProviderPluginProcess(int &argc, char **argv)
: d_ptr(new ProviderPluginProcessPrivate(argc, argv))
{
init(argc, argv);
}
void ProviderPluginProcess::init(int &argc, char **argv)
{
Q_UNUSED(argc);
Q_UNUSED(argv);
Q_D(ProviderPluginProcess);
d->q_ptr = this;
if (plugin_instance != 0)
qWarning() << "ProviderPluginProcess already instantiated";
plugin_instance = this;
}
ProviderPluginProcess::~ProviderPluginProcess()
{
Q_D(ProviderPluginProcess);
delete d;
}
ProviderPluginProcess *ProviderPluginProcess::instance()
{
return plugin_instance;
}
MApplicationPage * ProviderPluginProcess::mainPage()
{
Q_D(ProviderPluginProcess);
AbstractAccountSetupContext *context = d->context();
if (context->setupType() == CreateNew)
return new AddAccountPage(context);
if (context->setupType() == EditExisting)
return new AccountSettingsPage(context);
/* we should never come to this point */
Q_ASSERT(false);
return 0;
}
int ProviderPluginProcess::exec()
{
Q_D(ProviderPluginProcess);
/* if we the account is invalid (either because it does not exists or
* couldn't be loaded because of some DB error), return immediately */
if (d->account == 0) {
qWarning() << Q_FUNC_INFO << "account() is NULL";
return 1;
}
d->window->show();
MApplicationPage *page = mainPage();
if (page == 0) {
qWarning() << Q_FUNC_INFO << "The mainPage() returned 0";
return 1;
}
page->appear(d->window);
return d->application->exec();
}
void ProviderPluginProcess::quit()
{
Q_D(ProviderPluginProcess);
d->printAccountId();
QCoreApplication::exit(0);
}
AbstractAccountSetupContext *ProviderPluginProcess::setupContext() const
{
Q_D(const ProviderPluginProcess);
return d->context();
}
AbstractAccountSetupContext *ProviderPluginProcess::accountSetupContext(
Accounts::Account *account,
SetupType type,
QObject *parent)
{
return new GenericAccountSetupContext(account, type, parent);
}
void ProviderPluginProcess::setReturnToApp(bool returnToApp)
{
Q_D(ProviderPluginProcess);
d->returnToApp = returnToApp;
}
const LastPageActions &ProviderPluginProcess::lastPageActions() const
{
Q_D(const ProviderPluginProcess);
return d->lastPageActions;
}
} // namespace
<commit_msg>Fixing bug 207001 - fixing metabug about deletion order<commit_after>/*
* This file is part of accounts-ui
*
* Copyright (C) 2009-2010 Nokia Corporation.
*
* Contact: Alberto Mardegan <[email protected]>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include "provider-plugin-process.h"
#include "add-account-page.h"
#include "accountsettingspage.h"
#include "generic-account-setup-context.h"
#include "provider-plugin-process-priv.h"
#include <Accounts/Account>
#include <Accounts/Manager>
#include <MComponentCache>
#include <MApplication>
#include <MApplicationWindow>
#include <QDebug>
#include <QFile>
#include <QLocalSocket>
#include <QProcess>
namespace AccountsUI {
static ProviderPluginProcess *plugin_instance = 0;
void ProviderPluginProcessPrivate::printAccountId()
{
Accounts::Account *account = context()->account();
QByteArray ba = QString("%1 %2").arg(account->id()).arg(QString::number(returnToApp)).toAscii();
if (!serverName.isEmpty()) {
QLocalSocket *socket = new QLocalSocket();
connect(socket, SIGNAL(error(QLocalSocket::LocalSocketError)),
this, SLOT(socketConnectionError(QLocalSocket::LocalSocketError)));
socket->connectToServer(serverName);
socket->write(ba);
socket->flush();
socket->close();
} else {
QFile output;
output.open(STDOUT_FILENO, QIODevice::WriteOnly);
output.write(ba.constData());
output.close();
}
}
void ProviderPluginProcessPrivate::socketConnectionError(QLocalSocket::LocalSocketError status)
{
qDebug() << Q_FUNC_INFO << status;
}
AbstractAccountSetupContext *ProviderPluginProcessPrivate::context() const
{
if (!m_context) {
m_context = q_ptr->accountSetupContext(account, setupType, q_ptr);
m_context->setServiceType(serviceType);
}
return m_context;
}
void ProviderPluginProcessPrivate::serviceEnabled(Accounts::Service *service)
{
qDebug() << Q_FUNC_INFO << service->name();
QDomElement root = service->domDocument().documentElement();
QDomElement handler = root.firstChildElement("handler");
if (!handler.isNull()) {
QString type = handler.attribute("type");
if (type == "command") {
/* Syntax for the service file:
*
* <handler type="command">/usr/bin/appname [args]...</handler>
*/
QString command = handler.text();
qDebug() << "Executing" << command;
/* The account plugin process is going to die very soon; the
* handler must be started as a detached process, for it to
* continue to live. */
bool ok = QProcess::startDetached(command);
if (!ok)
qWarning() << "Could not execute:" << command;
}
/* support more types (e.g., D-Bus services) here */
}
}
void ProviderPluginProcessPrivate::accountSaved()
{
qDebug() << Q_FUNC_INFO;
account->selectService();
if (account->enabled()) {
/* Go through the enabled services and run the activation command, if
* present */
foreach (Accounts::Service *service, account->services()) {
account->selectService(service);
if (account->enabled() && !enabledServices.contains(service))
serviceEnabled(service);
}
}
}
void ProviderPluginProcessPrivate::monitorServices()
{
connect(account, SIGNAL(synced()), this, SLOT(accountSaved()));
/* If we are editing an account, get the list of services initially
* enabled, to avoid starting up their handlers for no reason */
account->selectService();
if (setupType == EditExisting && account->enabled()) {
foreach (Accounts::Service *service, account->services()) {
account->selectService(service);
if (account->enabled())
enabledServices.append(service);
}
}
}
ProviderPluginProcess::ProviderPluginProcess(AccountPluginInterface *plugin,
int &argc, char **argv)
: d_ptr(new ProviderPluginProcessPrivate(plugin, argc, argv))
{
Q_D(ProviderPluginProcess);
init(argc, argv);
d->m_context = plugin->accountSetupContext(d->account, d->setupType, this);
d->m_context->setServiceType(d->serviceType);
}
ProviderPluginProcess::ProviderPluginProcess(int &argc, char **argv)
: d_ptr(new ProviderPluginProcessPrivate(argc, argv))
{
init(argc, argv);
}
void ProviderPluginProcess::init(int &argc, char **argv)
{
Q_UNUSED(argc);
Q_UNUSED(argv);
Q_D(ProviderPluginProcess);
d->q_ptr = this;
if (plugin_instance != 0)
qWarning() << "ProviderPluginProcess already instantiated";
plugin_instance = this;
}
ProviderPluginProcess::~ProviderPluginProcess()
{
Q_D(ProviderPluginProcess);
delete d;
}
ProviderPluginProcess *ProviderPluginProcess::instance()
{
return plugin_instance;
}
MApplicationPage * ProviderPluginProcess::mainPage()
{
Q_D(ProviderPluginProcess);
AbstractAccountSetupContext *context = d->context();
if (context->setupType() == CreateNew)
return new AddAccountPage(context);
if (context->setupType() == EditExisting)
return new AccountSettingsPage(context);
/* we should never come to this point */
Q_ASSERT(false);
return 0;
}
int ProviderPluginProcess::exec()
{
Q_D(ProviderPluginProcess);
/* if we the account is invalid (either because it does not exists or
* couldn't be loaded because of some DB error), return immediately */
if (d->account == 0) {
qWarning() << Q_FUNC_INFO << "account() is NULL";
return 1;
}
d->window->show();
MApplicationPage *page = mainPage();
if (page == 0) {
qWarning() << Q_FUNC_INFO << "The mainPage() returned 0";
return 1;
}
page->appear(d->window);
int result = d->application->exec();
delete page;
delete d->window;
delete d->application;
return result;
}
void ProviderPluginProcess::quit()
{
Q_D(ProviderPluginProcess);
d->printAccountId();
QCoreApplication::exit(0);
}
AbstractAccountSetupContext *ProviderPluginProcess::setupContext() const
{
Q_D(const ProviderPluginProcess);
return d->context();
}
AbstractAccountSetupContext *ProviderPluginProcess::accountSetupContext(
Accounts::Account *account,
SetupType type,
QObject *parent)
{
return new GenericAccountSetupContext(account, type, parent);
}
void ProviderPluginProcess::setReturnToApp(bool returnToApp)
{
Q_D(ProviderPluginProcess);
d->returnToApp = returnToApp;
}
const LastPageActions &ProviderPluginProcess::lastPageActions() const
{
Q_D(const ProviderPluginProcess);
return d->lastPageActions;
}
} // namespace
<|endoftext|> |
<commit_before>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//
#ifndef RJ_SHARED_DATA_MANAGER_HPP
#define RJ_SHARED_DATA_MANAGER_HPP
#include <mlk/filesystem/filesystem.h>
#include <mlk/tools/compiletime.h>
#include <mlk/types/types.h>
#include <map>
namespace rj
{
using data_id = std::string;
class data_manager
{
mlk::fs::dir_handle m_dirh;
mlk::fs::file_handle m_fileh;
const std::string& m_abs_path;
std::map<std::string, mlk::data_packet> m_data;
bool m_valid{false};
public:
data_manager(const std::string& abs_datapath, bool auto_load = false) :
m_dirh{abs_datapath},
m_abs_path{m_dirh.get_path()},
m_valid{m_dirh.exists()}
{
this->init();
if(auto_load) this->load_all();
}
// interface
// get: don't loads the data to manager
// just 'gets' it
mlk::data_packet get_raw(const data_id& id)
{
if(!this->exists_id(id))
return {};
return m_data[id];
}
template<typename T>
T get_as(const data_id& id)
{return this->get_as_impl<T>(id);}
template<typename... Types, typename... Ids>
std::tuple<Types...> get_multiple_as(Ids&&... ids)
{
static_assert(sizeof...(Types) == sizeof...(Ids), "Amount of types must match the amount of passed ids.");
std::tuple<Types...> result;
this->get_multiple_as_impl<mlk::get_upper(-1)>(result, std::forward<Ids>(ids)...);
return result;
}
// load: gets AND loads the data to manager
mlk::data_packet load_raw(const data_id& id)
{
this->load_raw_impl(id, this->make_path(id));
return m_data[id];
}
template<typename T>
T load_as(const data_id& id)
{return this->load_as_impl<T>(id);}
template<typename... Types, typename... Ids>
std::tuple<Types...> load_multiple_as(Ids&&... ids)
{
static_assert(sizeof...(Types) == sizeof...(Ids), "Amount of types must match the amount of passed ids.");
std::tuple<Types...> result;
this->load_multiple_as_impl<mlk::get_upper(-1)>(result, std::forward<Ids>(ids)...);
return result;
}
private:
void init()
{}
// utils
std::string make_path(const data_id& id)
{return m_abs_path + id;}
bool exists_id(const data_id& id)
{return m_data.find(id) != std::end(m_data);}
// loads all data recursive
// from absolute directory
void load_all()
{
auto content(m_dirh.get_content<true>());
for(auto& a : content)
if(a.type == mlk::fs::item_type::file)
this->load_raw_impl(a.name, a.path);
}
// tuple impls
template<int tup_index, typename Id_Head, typename... Types, typename... Id_Tail>
void get_multiple_as_impl(std::tuple<Types...>& tup, const Id_Head& head, Id_Tail&&... tail)
{
std::get<tup_index>(tup) = this->get_as_impl<typename std::tuple_element<tup_index, std::tuple<Types...>>::type>(head);
this->get_multiple_as_impl<mlk::get_upper(tup_index)>(tup, std::forward<Id_Tail>(tail)...);
}
template<int tup_index, typename... Types>
void get_multiple_as_impl(std::tuple<Types...> &tup)
{/* case: no args; do nothing */}
template<int tup_index, typename Id_Head, typename... Types, typename... Id_Tail>
void load_multiple_as_impl(std::tuple<Types...>& tup, const Id_Head& head, Id_Tail&&... tail)
{
std::get<tup_index>(tup) = this->load_as_impl<typename std::tuple_element<tup_index, std::tuple<Types...>>::type>(head);
this->load_multiple_as_impl<mlk::get_upper(tup_index)>(tup, std::forward<Id_Tail>(tail)...);
}
template<int tup_index, typename... Types>
void load_multiple_as_impl(std::tuple<Types...>& tup)
{/* case: no args; do nothing */}
// lowest level impls
void load_raw_impl(const data_id& id, const std::string& path)
{
if(this->exists_id(id))
return;
m_fileh.reopen(path, std::ios::in);
m_data[id] = m_fileh.read_all();
}
template<typename T>
T load_as_impl(const data_id& id)
{
this->load_raw_impl(id, this->make_path(id));
return this->get_as_impl<T>(id);
}
template<typename T>
T get_as_impl(const data_id& id)
{
if(!this->exists_id(id))
return T{};
T result;
result.loadFromMemory(m_data[id].data(), m_data[id].size());
return result;
}
};
}
#endif // RJ_SHARED_DATA_MANAGER_HPP
<commit_msg>done some logging<commit_after>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//
#ifndef RJ_SHARED_DATA_MANAGER_HPP
#define RJ_SHARED_DATA_MANAGER_HPP
#include <mlk/filesystem/filesystem.h>
#include <mlk/log/log.h>
#include <mlk/tools/compiletime.h>
#include <mlk/types/types.h>
#include <map>
namespace rj
{
using data_id = std::string;
class data_manager
{
mlk::fs::dir_handle m_dirh;
mlk::fs::file_handle m_fileh;
const std::string& m_abs_path;
std::map<std::string, mlk::data_packet> m_data;
bool m_valid{false};
public:
data_manager(const std::string& abs_datapath, bool auto_load = false) :
m_dirh{abs_datapath},
m_abs_path{m_dirh.get_path()},
m_valid{m_dirh.exists()}
{
this->init();
if(auto_load) this->load_all();
}
// interface
// get: don't loads the data to manager
// just 'gets' it
mlk::data_packet get_raw(const data_id& id)
{
if(!this->exists_id(id))
return {};
return m_data[id];
}
template<typename T>
T get_as(const data_id& id)
{return this->get_as_impl<T>(id);}
template<typename... Types, typename... Ids>
std::tuple<Types...> get_multiple_as(Ids&&... ids)
{
static_assert(sizeof...(Types) == sizeof...(Ids), "Amount of types must match the amount of passed ids.");
std::tuple<Types...> result;
this->get_multiple_as_impl<mlk::get_upper(-1)>(result, std::forward<Ids>(ids)...);
return result;
}
// load: gets AND loads the data to manager
mlk::data_packet load_raw(const data_id& id)
{
this->load_raw_impl(id, this->make_path(id));
return m_data[id];
}
template<typename T>
T load_as(const data_id& id)
{return this->load_as_impl<T>(id);}
template<typename... Types, typename... Ids>
std::tuple<Types...> load_multiple_as(Ids&&... ids)
{
static_assert(sizeof...(Types) == sizeof...(Ids), "Amount of types must match the amount of passed ids.");
std::tuple<Types...> result;
this->load_multiple_as_impl<mlk::get_upper(-1)>(result, std::forward<Ids>(ids)...);
return result;
}
private:
void init()
{}
// utils
std::string make_path(const data_id& id)
{return m_abs_path + id;}
bool exists_id(const data_id& id)
{return m_data.find(id) != std::end(m_data);}
// loads all data recursive
// from absolute directory
void load_all()
{
mlk::lout("data_manager") << "loading files recursive from directory '" << m_abs_path << "'...";
auto content(m_dirh.get_content<true>());
for(auto& a : content)
if(a.type == mlk::fs::item_type::file)
this->load_raw_impl(a.name, a.path);
}
// tuple impls
template<int tup_index, typename Id_Head, typename... Types, typename... Id_Tail>
void get_multiple_as_impl(std::tuple<Types...>& tup, const Id_Head& head, Id_Tail&&... tail)
{
std::get<tup_index>(tup) = this->get_as_impl<typename std::tuple_element<tup_index, std::tuple<Types...>>::type>(head);
this->get_multiple_as_impl<mlk::get_upper(tup_index)>(tup, std::forward<Id_Tail>(tail)...);
}
template<int tup_index, typename... Types>
void get_multiple_as_impl(std::tuple<Types...> &tup)
{/* case: no args; do nothing */}
template<int tup_index, typename Id_Head, typename... Types, typename... Id_Tail>
void load_multiple_as_impl(std::tuple<Types...>& tup, const Id_Head& head, Id_Tail&&... tail)
{
std::get<tup_index>(tup) = this->load_as_impl<typename std::tuple_element<tup_index, std::tuple<Types...>>::type>(head);
this->load_multiple_as_impl<mlk::get_upper(tup_index)>(tup, std::forward<Id_Tail>(tail)...);
}
template<int tup_index, typename... Types>
void load_multiple_as_impl(std::tuple<Types...>& tup)
{/* case: no args; do nothing */}
// lowest level impls
void load_raw_impl(const data_id& id, const std::string& path)
{
if(this->exists_id(id))
{
mlk::lerr()["data_manager"] << "object with id '" << id << "' already loaded";
return;
}
m_fileh.reopen(path, std::ios::in);
m_data[id] = m_fileh.read_all();
}
template<typename T>
T load_as_impl(const data_id& id)
{
this->load_raw_impl(id, this->make_path(id));
return this->get_as_impl<T>(id);
}
template<typename T>
T get_as_impl(const data_id& id)
{
if(!this->exists_id(id))
{
mlk::lerr()["data_manager"] << "object with id '" << id << "' not found";
return T{};
}
T result;
result.loadFromMemory(m_data[id].data(), m_data[id].size());
return result;
}
};
}
#endif // RJ_SHARED_DATA_MANAGER_HPP
<|endoftext|> |
<commit_before>//===- Steensgaard.cpp - Context Insensitive Alias Analysis ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass uses the data structure graphs to implement a simple context
// insensitive alias analysis. It does this by computing the local analysis
// graphs for all of the functions, then merging them together into a single big
// graph without cloning.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/DataStructure.h"
#include "llvm/Analysis/DSGraph.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Module.h"
#include "Support/Debug.h"
using namespace llvm;
namespace {
class Steens : public Pass, public AliasAnalysis {
DSGraph *ResultGraph;
DSGraph *GlobalsGraph; // FIXME: Eliminate globals graph stuff from DNE
public:
Steens() : ResultGraph(0), GlobalsGraph(0) {}
~Steens() {
releaseMyMemory();
assert(ResultGraph == 0 && "releaseMemory not called?");
}
//------------------------------------------------
// Implement the Pass API
//
// run - Build up the result graph, representing the pointer graph for the
// program.
//
bool run(Module &M);
virtual void releaseMyMemory() { delete ResultGraph; ResultGraph = 0; }
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AliasAnalysis::getAnalysisUsage(AU);
AU.setPreservesAll(); // Does not transform code...
AU.addRequired<LocalDataStructures>(); // Uses local dsgraph
AU.addRequired<AliasAnalysis>(); // Chains to another AA impl...
}
// print - Implement the Pass::print method...
void print(std::ostream &O, const Module *M) const {
assert(ResultGraph && "Result graph has not yet been computed!");
ResultGraph->writeGraphToFile(O, "steensgaards");
}
//------------------------------------------------
// Implement the AliasAnalysis API
//
// alias - This is the only method here that does anything interesting...
AliasResult alias(const Value *V1, unsigned V1Size,
const Value *V2, unsigned V2Size);
bool pointsToConstantMemory(const Value *P) {
return getAnalysis<AliasAnalysis>().pointsToConstantMemory(P);
}
private:
void ResolveFunctionCall(Function *F, const DSCallSite &Call,
DSNodeHandle &RetVal);
};
// Register the pass...
RegisterOpt<Steens> X("steens-aa",
"Steensgaard's alias analysis (DSGraph based)");
// Register as an implementation of AliasAnalysis
RegisterAnalysisGroup<AliasAnalysis, Steens> Y;
}
/// ResolveFunctionCall - Resolve the actual arguments of a call to function F
/// with the specified call site descriptor. This function links the arguments
/// and the return value for the call site context-insensitively.
///
void Steens::ResolveFunctionCall(Function *F, const DSCallSite &Call,
DSNodeHandle &RetVal) {
assert(ResultGraph != 0 && "Result graph not allocated!");
DSGraph::ScalarMapTy &ValMap = ResultGraph->getScalarMap();
// Handle the return value of the function...
if (Call.getRetVal().getNode() && RetVal.getNode())
RetVal.mergeWith(Call.getRetVal());
// Loop over all pointer arguments, resolving them to their provided pointers
unsigned PtrArgIdx = 0;
for (Function::aiterator AI = F->abegin(), AE = F->aend();
AI != AE && PtrArgIdx < Call.getNumPtrArgs(); ++AI) {
DSGraph::ScalarMapTy::iterator I = ValMap.find(AI);
if (I != ValMap.end()) // If its a pointer argument...
I->second.mergeWith(Call.getPtrArg(PtrArgIdx++));
}
}
/// run - Build up the result graph, representing the pointer graph for the
/// program.
///
bool Steens::run(Module &M) {
InitializeAliasAnalysis(this);
assert(ResultGraph == 0 && "Result graph already allocated!");
LocalDataStructures &LDS = getAnalysis<LocalDataStructures>();
// Create a new, empty, graph...
ResultGraph = new DSGraph(getTargetData());
GlobalsGraph = new DSGraph(getTargetData());
ResultGraph->setGlobalsGraph(GlobalsGraph);
ResultGraph->setPrintAuxCalls();
// RetValMap - Keep track of the return values for all functions that return
// valid pointers.
//
DSGraph::ReturnNodesTy RetValMap;
// Loop over the rest of the module, merging graphs for non-external functions
// into this graph.
//
unsigned Count = 0;
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
if (!I->isExternal()) {
DSGraph::ScalarMapTy ValMap;
{ // Scope to free NodeMap memory ASAP
DSGraph::NodeMapTy NodeMap;
const DSGraph &FDSG = LDS.getDSGraph(*I);
ResultGraph->cloneInto(FDSG, ValMap, RetValMap, NodeMap,
DSGraph::UpdateInlinedGlobals);
}
// Incorporate the inlined Function's ScalarMap into the global
// ScalarMap...
DSGraph::ScalarMapTy &GVM = ResultGraph->getScalarMap();
for (DSGraph::ScalarMapTy::iterator I = ValMap.begin(),
E = ValMap.end(); I != E; ++I)
GVM[I->first].mergeWith(I->second);
if ((++Count & 1) == 0) // Prune nodes out every other time...
ResultGraph->removeTriviallyDeadNodes();
}
// FIXME: Must recalculate and use the Incomplete markers!!
// Now that we have all of the graphs inlined, we can go about eliminating
// call nodes...
//
std::vector<DSCallSite> &Calls =
ResultGraph->getAuxFunctionCalls();
assert(Calls.empty() && "Aux call list is already in use??");
// Start with a copy of the original call sites...
Calls = ResultGraph->getFunctionCalls();
for (unsigned i = 0; i != Calls.size(); ) {
DSCallSite &CurCall = Calls[i];
// Loop over the called functions, eliminating as many as possible...
std::vector<GlobalValue*> CallTargets;
if (CurCall.isDirectCall())
CallTargets.push_back(CurCall.getCalleeFunc());
else
CallTargets = CurCall.getCalleeNode()->getGlobals();
for (unsigned c = 0; c != CallTargets.size(); ) {
// If we can eliminate this function call, do so!
bool Eliminated = false;
if (Function *F = dyn_cast<Function>(CallTargets[c]))
if (!F->isExternal()) {
ResolveFunctionCall(F, CurCall, RetValMap[F]);
Eliminated = true;
}
if (Eliminated) {
CallTargets[c] = CallTargets.back();
CallTargets.pop_back();
} else
++c; // Cannot eliminate this call, skip over it...
}
if (CallTargets.empty()) { // Eliminated all calls?
CurCall = Calls.back(); // Remove entry
Calls.pop_back();
} else
++i; // Skip this call site...
}
RetValMap.clear();
// Update the "incomplete" markers on the nodes, ignoring unknownness due to
// incoming arguments...
ResultGraph->maskIncompleteMarkers();
ResultGraph->markIncompleteNodes(DSGraph::IgnoreFormalArgs);
// Remove any nodes that are dead after all of the merging we have done...
// FIXME: We should be able to disable the globals graph for steens!
ResultGraph->removeDeadNodes(DSGraph::KeepUnreachableGlobals);
DEBUG(print(std::cerr, &M));
return false;
}
// alias - This is the only method here that does anything interesting...
AliasAnalysis::AliasResult Steens::alias(const Value *V1, unsigned V1Size,
const Value *V2, unsigned V2Size) {
// FIXME: HANDLE Size argument!
assert(ResultGraph && "Result graph has not been computed yet!");
DSGraph::ScalarMapTy &GSM = ResultGraph->getScalarMap();
DSGraph::ScalarMapTy::iterator I = GSM.find(const_cast<Value*>(V1));
if (I != GSM.end() && I->second.getNode()) {
DSNodeHandle &V1H = I->second;
DSGraph::ScalarMapTy::iterator J=GSM.find(const_cast<Value*>(V2));
if (J != GSM.end() && J->second.getNode()) {
DSNodeHandle &V2H = J->second;
// If the two pointers point to different data structure graph nodes, they
// cannot alias!
if (V1H.getNode() != V2H.getNode()) // FIXME: Handle incompleteness!
return NoAlias;
// FIXME: If the two pointers point to the same node, and the offsets are
// different, and the LinkIndex vector doesn't alias the section, then the
// two pointers do not alias. We need access size information for the two
// accesses though!
//
}
}
// If we cannot determine alias properties based on our graph, fall back on
// some other AA implementation.
//
return getAnalysis<AliasAnalysis>().alias(V1, V1Size, V2, V2Size);
}
<commit_msg>Update to match the autochaining interface that the AA interface uses<commit_after>//===- Steensgaard.cpp - Context Insensitive Alias Analysis ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass uses the data structure graphs to implement a simple context
// insensitive alias analysis. It does this by computing the local analysis
// graphs for all of the functions, then merging them together into a single big
// graph without cloning.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/DataStructure.h"
#include "llvm/Analysis/DSGraph.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Module.h"
#include "Support/Debug.h"
using namespace llvm;
namespace {
class Steens : public Pass, public AliasAnalysis {
DSGraph *ResultGraph;
DSGraph *GlobalsGraph; // FIXME: Eliminate globals graph stuff from DNE
public:
Steens() : ResultGraph(0), GlobalsGraph(0) {}
~Steens() {
releaseMyMemory();
assert(ResultGraph == 0 && "releaseMemory not called?");
}
//------------------------------------------------
// Implement the Pass API
//
// run - Build up the result graph, representing the pointer graph for the
// program.
//
bool run(Module &M);
virtual void releaseMyMemory() { delete ResultGraph; ResultGraph = 0; }
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AliasAnalysis::getAnalysisUsage(AU);
AU.setPreservesAll(); // Does not transform code...
AU.addRequired<LocalDataStructures>(); // Uses local dsgraph
}
// print - Implement the Pass::print method...
void print(std::ostream &O, const Module *M) const {
assert(ResultGraph && "Result graph has not yet been computed!");
ResultGraph->writeGraphToFile(O, "steensgaards");
}
//------------------------------------------------
// Implement the AliasAnalysis API
//
// alias - This is the only method here that does anything interesting...
AliasResult alias(const Value *V1, unsigned V1Size,
const Value *V2, unsigned V2Size);
private:
void ResolveFunctionCall(Function *F, const DSCallSite &Call,
DSNodeHandle &RetVal);
};
// Register the pass...
RegisterOpt<Steens> X("steens-aa",
"Steensgaard's alias analysis (DSGraph based)");
// Register as an implementation of AliasAnalysis
RegisterAnalysisGroup<AliasAnalysis, Steens> Y;
}
/// ResolveFunctionCall - Resolve the actual arguments of a call to function F
/// with the specified call site descriptor. This function links the arguments
/// and the return value for the call site context-insensitively.
///
void Steens::ResolveFunctionCall(Function *F, const DSCallSite &Call,
DSNodeHandle &RetVal) {
assert(ResultGraph != 0 && "Result graph not allocated!");
DSGraph::ScalarMapTy &ValMap = ResultGraph->getScalarMap();
// Handle the return value of the function...
if (Call.getRetVal().getNode() && RetVal.getNode())
RetVal.mergeWith(Call.getRetVal());
// Loop over all pointer arguments, resolving them to their provided pointers
unsigned PtrArgIdx = 0;
for (Function::aiterator AI = F->abegin(), AE = F->aend();
AI != AE && PtrArgIdx < Call.getNumPtrArgs(); ++AI) {
DSGraph::ScalarMapTy::iterator I = ValMap.find(AI);
if (I != ValMap.end()) // If its a pointer argument...
I->second.mergeWith(Call.getPtrArg(PtrArgIdx++));
}
}
/// run - Build up the result graph, representing the pointer graph for the
/// program.
///
bool Steens::run(Module &M) {
InitializeAliasAnalysis(this);
assert(ResultGraph == 0 && "Result graph already allocated!");
LocalDataStructures &LDS = getAnalysis<LocalDataStructures>();
// Create a new, empty, graph...
ResultGraph = new DSGraph(getTargetData());
GlobalsGraph = new DSGraph(getTargetData());
ResultGraph->setGlobalsGraph(GlobalsGraph);
ResultGraph->setPrintAuxCalls();
// RetValMap - Keep track of the return values for all functions that return
// valid pointers.
//
DSGraph::ReturnNodesTy RetValMap;
// Loop over the rest of the module, merging graphs for non-external functions
// into this graph.
//
unsigned Count = 0;
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
if (!I->isExternal()) {
DSGraph::ScalarMapTy ValMap;
{ // Scope to free NodeMap memory ASAP
DSGraph::NodeMapTy NodeMap;
const DSGraph &FDSG = LDS.getDSGraph(*I);
ResultGraph->cloneInto(FDSG, ValMap, RetValMap, NodeMap,
DSGraph::UpdateInlinedGlobals);
}
// Incorporate the inlined Function's ScalarMap into the global
// ScalarMap...
DSGraph::ScalarMapTy &GVM = ResultGraph->getScalarMap();
for (DSGraph::ScalarMapTy::iterator I = ValMap.begin(),
E = ValMap.end(); I != E; ++I)
GVM[I->first].mergeWith(I->second);
if ((++Count & 1) == 0) // Prune nodes out every other time...
ResultGraph->removeTriviallyDeadNodes();
}
// FIXME: Must recalculate and use the Incomplete markers!!
// Now that we have all of the graphs inlined, we can go about eliminating
// call nodes...
//
std::vector<DSCallSite> &Calls =
ResultGraph->getAuxFunctionCalls();
assert(Calls.empty() && "Aux call list is already in use??");
// Start with a copy of the original call sites...
Calls = ResultGraph->getFunctionCalls();
for (unsigned i = 0; i != Calls.size(); ) {
DSCallSite &CurCall = Calls[i];
// Loop over the called functions, eliminating as many as possible...
std::vector<GlobalValue*> CallTargets;
if (CurCall.isDirectCall())
CallTargets.push_back(CurCall.getCalleeFunc());
else
CallTargets = CurCall.getCalleeNode()->getGlobals();
for (unsigned c = 0; c != CallTargets.size(); ) {
// If we can eliminate this function call, do so!
bool Eliminated = false;
if (Function *F = dyn_cast<Function>(CallTargets[c]))
if (!F->isExternal()) {
ResolveFunctionCall(F, CurCall, RetValMap[F]);
Eliminated = true;
}
if (Eliminated) {
CallTargets[c] = CallTargets.back();
CallTargets.pop_back();
} else
++c; // Cannot eliminate this call, skip over it...
}
if (CallTargets.empty()) { // Eliminated all calls?
CurCall = Calls.back(); // Remove entry
Calls.pop_back();
} else
++i; // Skip this call site...
}
RetValMap.clear();
// Update the "incomplete" markers on the nodes, ignoring unknownness due to
// incoming arguments...
ResultGraph->maskIncompleteMarkers();
ResultGraph->markIncompleteNodes(DSGraph::IgnoreFormalArgs);
// Remove any nodes that are dead after all of the merging we have done...
// FIXME: We should be able to disable the globals graph for steens!
ResultGraph->removeDeadNodes(DSGraph::KeepUnreachableGlobals);
DEBUG(print(std::cerr, &M));
return false;
}
// alias - This is the only method here that does anything interesting...
AliasAnalysis::AliasResult Steens::alias(const Value *V1, unsigned V1Size,
const Value *V2, unsigned V2Size) {
// FIXME: HANDLE Size argument!
assert(ResultGraph && "Result graph has not been computed yet!");
DSGraph::ScalarMapTy &GSM = ResultGraph->getScalarMap();
DSGraph::ScalarMapTy::iterator I = GSM.find(const_cast<Value*>(V1));
if (I != GSM.end() && I->second.getNode()) {
DSNodeHandle &V1H = I->second;
DSGraph::ScalarMapTy::iterator J=GSM.find(const_cast<Value*>(V2));
if (J != GSM.end() && J->second.getNode()) {
DSNodeHandle &V2H = J->second;
// If the two pointers point to different data structure graph nodes, they
// cannot alias!
if (V1H.getNode() != V2H.getNode()) // FIXME: Handle incompleteness!
return NoAlias;
// FIXME: If the two pointers point to the same node, and the offsets are
// different, and the LinkIndex vector doesn't alias the section, then the
// two pointers do not alias. We need access size information for the two
// accesses though!
//
}
}
// If we cannot determine alias properties based on our graph, fall back on
// some other AA implementation.
//
return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
}
<|endoftext|> |
<commit_before>/** \file
* \author Johannes Riedl
*
* A tool for generating a sorted list of works that are part of the
*/
/*
Copyright (C) 2017, Library of the University of Tübingen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include <iostream>
#include <cstring>
#include "Compiler.h"
#include "FileUtil.h"
#include "TextUtil.h"
#include "MarcRecord.h"
#include "RegexMatcher.h"
#include "util.h"
static unsigned extracted_count(0);
static std::set<std::string> de21_ppns;
static const RegexMatcher * const tue_sigil_matcher(RegexMatcher::RegexMatcherFactory("^DE-21.*"));
void Usage() {
std::cerr << "Usage: " << ::progname << " marc_input de21_output_ppns\n";
std::exit(EXIT_FAILURE);
}
void ProcessRecord(const MarcRecord &record) {
// We are done if this is not a superior work
if (record.getFieldData("SPR").empty())
return;
std::vector<std::pair<size_t, size_t>> local_block_boundaries;
ssize_t local_data_count = record.findAllLocalDataBlocks(&local_block_boundaries);
if (local_data_count == 0)
return;
for (const auto &block_start_and_end : local_block_boundaries) {
std::vector<size_t> field_indices;
record.findFieldsInLocalBlock("852", "??", block_start_and_end, &field_indices);
for (size_t field_index : field_indices) {
const std::string field_data(record.getFieldData(field_index));
const Subfields subfields(field_data);
std::string sigil;
if (subfields.extractSubfieldWithPattern('a', *tue_sigil_matcher, &sigil)) {
de21_ppns.insert(record.getControlNumber());
++extracted_count;
}
}
}
}
void WriteDE21Output(const std::unique_ptr<File> &output) {
for (const auto ppn : de21_ppns) {
output->write(ppn + '\n');
}
}
void LoadDE21PPNs(MarcReader * const marc_reader) {
while (MarcRecord record = marc_reader->read())
ProcessRecord(record);
}
int main(int argc, char **argv) {
::progname = argv[0];
if (argc != 3)
Usage();
const std::unique_ptr<MarcReader> marc_reader(MarcReader::Factory(argv[1], MarcReader::BINARY));
const std::unique_ptr<File> de21_output(FileUtil::OpenOutputFileOrDie(argv[2]));
try {
LoadDE21PPNs(marc_reader.get());
WriteDE21Output(de21_output);
std::cerr << "Extracted " << extracted_count << " PPNs\n";
} catch (const std::exception &x) {
Error("caught exception: " + std::string(x.what()));
}
}
<commit_msg>Added augmentation<commit_after>/** \file
* \author Johannes Riedl
*
* A tool for generating a sorted list of works that are part of the
*/
/*
Copyright (C) 2017, Library of the University of Tübingen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include <iostream>
#include <cstring>
#include "Compiler.h"
#include "FileUtil.h"
#include "TextUtil.h"
#include "MarcRecord.h"
#include "RegexMatcher.h"
#include "util.h"
static unsigned extracted_count(0);
static unsigned modified_count(0);
static std::set<std::string> de21_superior_ppns;
static const RegexMatcher * const tue_sigil_matcher(RegexMatcher::RegexMatcherFactory("^DE-21.*"));
static const RegexMatcher * const superior_ppn_matcher(RegexMatcher::RegexMatcherFactory(".DE-576.(.*)"));
void Usage() {
std::cerr << "Usage: " << ::progname << " marc_input marc_output\n";
std::cerr << " " << "Notice that this program requires \"add_superior_and_alertable_flags\"\n";
std::cerr << " " << "to be run on the input data\n";
std::exit(EXIT_FAILURE);
}
void ProcessSuperiorRecord(const MarcRecord &record) {
// We are done if this is not a superior work
if (record.getFieldData("SPR").empty())
return;
std::vector<std::pair<size_t, size_t>> local_block_boundaries;
ssize_t local_data_count = record.findAllLocalDataBlocks(&local_block_boundaries);
if (local_data_count == 0)
return;
for (const auto &block_start_and_end : local_block_boundaries) {
std::vector<size_t> field_indices;
record.findFieldsInLocalBlock("852", "??", block_start_and_end, &field_indices);
for (size_t field_index : field_indices) {
const std::string field_data(record.getFieldData(field_index));
const Subfields subfields(field_data);
std::string sigil;
if (subfields.extractSubfieldWithPattern('a', *tue_sigil_matcher, &sigil)) {
de21_superior_ppns.insert(record.getControlNumber());
++extracted_count;
}
}
}
}
void LoadDE21PPNs(MarcReader * const marc_reader) {
while (MarcRecord record = marc_reader->read())
ProcessSuperiorRecord(record);
}
void CollectSuperiorPPNs(const MarcRecord &record, std::set<std::string> * const superior_ppn_bag) {
// Determine superior PPNs from 800w:810w:830w:773w:776w
std::vector<std::string> superior_ppn_vector;
const std::vector<std::string> tags({ "800", "810", "830", "773", "776" });
for (const auto &tag : tags) {
superior_ppn_vector.clear();
record.extractSubfields(tag , "w", &superior_ppn_vector);
// Remove superfluous prefices
for (auto &superior_ppn : superior_ppn_vector) {
std::string err_msg;
if (not superior_ppn_matcher->matched(superior_ppn, &err_msg)) {
if (not err_msg.empty())
Error("Error with regex für superior works " + err_msg);
continue;
}
superior_ppn = (*superior_ppn_matcher)[1];
}
std::copy(superior_ppn_vector.begin(), superior_ppn_vector.end(), std::inserter(*superior_ppn_bag, superior_ppn_bag->end()));
}
}
void InsertDE21ToLOK852(MarcRecord * const record) {
record->insertField("LOK", " ""\x1F""0852""\x1F""aDE-21");
++modified_count;
}
bool AlreadyHasLOK852DE21(const MarcRecord &record) {
std::vector<std::pair<size_t, size_t>> local_block_boundaries;
ssize_t local_data_count = record.findAllLocalDataBlocks(&local_block_boundaries);
if (local_data_count == 0)
return false;
for (const auto &block_start_and_end : local_block_boundaries) {
std::vector<size_t> field_indices;
record.findFieldsInLocalBlock("852", "??", block_start_and_end, &field_indices);
for (size_t field_index : field_indices) {
const std::string field_data(record.getFieldData(field_index));
const Subfields subfields(field_data);
std::string sigil;
if (subfields.extractSubfieldWithPattern('a', *tue_sigil_matcher, &sigil)) {
return true;
}
}
}
return false;
}
void ProcessRecord(MarcRecord * const record, MarcWriter * const marc_writer) {
const Leader &leader(record->getLeader());
if (not leader.isArticle()) {
marc_writer->write(*record);
return;
}
if (not AlreadyHasLOK852DE21(*record)) {
marc_writer->write(*record);
return;
}
std::set<std::string> superior_ppn_bag;
CollectSuperiorPPNs(*record, &superior_ppn_bag);
// Do we have superior PPN that has DE-21
for (const auto &superior_ppn : superior_ppn_bag) {
if (de21_superior_ppns.find(superior_ppn) != de21_superior_ppns.end()) {
InsertDE21ToLOK852(record);
marc_writer->write(*record);
return;
}
}
}
void AugmentRecords(MarcReader * const marc_reader, MarcWriter * const marc_writer) {
marc_reader->rewind();
while (MarcRecord record = marc_reader->read())
ProcessRecord(&record, marc_writer);
}
int main(int argc, char **argv) {
::progname = argv[0];
if (argc != 3)
Usage();
const std::unique_ptr<MarcReader> marc_reader(MarcReader::Factory(argv[1], MarcReader::BINARY));
const std::unique_ptr<MarcWriter> marc_writer(MarcWriter::Factory(argv[2], MarcWriter::BINARY));
try {
LoadDE21PPNs(marc_reader.get());
AugmentRecords(marc_reader.get(), marc_writer.get());
std::cerr << "Extracted " << extracted_count << " superior PPNs with DE21 and modified " << modified_count << " records\n";
} catch (const std::exception &x) {
Error("caught exception: " + std::string(x.what()));
}
}
<|endoftext|> |
<commit_before>//----------------------------------------------------------------------------
/// \file async_file_logger.cpp
/// \author Serge Aleynikov
//----------------------------------------------------------------------------
/// \brief Asynchronous file logger
//----------------------------------------------------------------------------
// Copyright (c) 2012 Omnibius, LLC
// Created: 2012-03-20
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****
This file is part of utxx open-source project.
Copyright (C) 2012 Serge Aleynikov <[email protected]>
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
***** END LICENSE BLOCK *****
*/
#pragma once
#include <utxx/atomic.hpp>
#include <utxx/synch.hpp>
#include <iostream>
#include <functional>
#include <thread>
#include <memory>
#include <string>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
namespace utxx {
#ifdef DEBUG_ASYNC_LOGGER
# define ASYNC_TRACE(...) printf(__VA_ARGS__);
#else
# define ASYNC_TRACE(...)
#endif
//-----------------------------------------------------------------------------
/// Traits of asynchronous logger using file stream writing
//-----------------------------------------------------------------------------
struct async_file_logger_traits {
using allocator = std::allocator<char>;
using event_type = futex;
using file_type = FILE*;
static constexpr const file_type s_null_file_type = nullptr;
//-------------------------------------------------------------------------
/// Represents a text message to be logged by the logger
//-------------------------------------------------------------------------
class msg_type {
size_t m_size;
char* m_data;
public:
explicit msg_type(const char* a_data, size_t a_size)
: m_size(a_size)
, m_data(const_cast<char*>(a_data))
{}
bool empty() const { return m_size; }
size_t size() const { return m_size; }
const char* data() const { return m_data; }
char* data() { return m_data; }
};
static file_type file_open(const std::string& a_filename) {
return fopen(a_filename.c_str(), "a+");
};
static int file_write(file_type a_fd, const char* a_data, size_t a_sz) {
return fwrite(a_data, a_sz, 1, a_fd);
};
static int file_close(file_type a_fd) { return fclose(a_fd); }
static int file_flush(file_type a_fd) { return fflush(a_fd); }
enum {
commit_timeout = 1000 // commit interval in usecs
, write_buf_sz = 256
};
};
//-----------------------------------------------------------------------------
/// Traits of asynchronous logger using direct file I/O writing
//-----------------------------------------------------------------------------
struct async_fd_logger_traits : public async_file_logger_traits {
using file_type = int;
static constexpr const file_type s_null_file_type = -1;
static file_type file_open(const std::string& a_filename) {
return ::open(a_filename.c_str(), O_CREAT | O_APPEND | O_RDWR);
};
static int file_write(file_type a_fd, const char* a_data, size_t a_sz) {
return ::write(a_fd, a_data, a_sz);
};
static int file_close(file_type a_fd) { return ::close(a_fd); }
static int file_flush(file_type a_fd) { return 0; }
enum {
commit_timeout = 1000 // commit interval in usecs
, write_buf_sz = 256
};
};
//-----------------------------------------------------------------------------
/// Asynchronous logger of text messages.
//-----------------------------------------------------------------------------
template<typename traits = async_file_logger_traits>
class basic_async_logger {
protected:
class cons: public traits::msg_type {
using base = typename traits::msg_type;
using allocator = typename traits::allocator;
public:
cons(const char* a_data, size_t a_sz) : base(a_data, a_sz) {}
cons* next() { return m_next; }
void next(cons* p) { m_next = p; }
private:
cons* m_next = nullptr;
};
using allocator = typename traits::allocator;
using event_type = typename traits::event_type;
using log_msg_type = cons;
using file_type = typename traits::file_type;
std::unique_ptr<std::thread> m_thread;
allocator m_allocator;
file_type m_file;
std::atomic<log_msg_type*> m_head;
bool m_cancel;
int m_max_queue_size;
std::string m_filename;
event_type m_event;
bool m_notify_immediate;
// Invoked by the async thread to flush messages from queue to file
int commit(const struct timespec* tsp = NULL);
// Invoked by the async thread
void run(std::condition_variable* a_cv);
// Print error message
void print_error(int, const char* what, int line);
public:
explicit basic_async_logger(const allocator& alloc = allocator())
: m_allocator(alloc)
, m_file(traits::s_null_file_type)
, m_head(nullptr)
, m_cancel(false)
, m_max_queue_size(0)
, m_notify_immediate(true)
{}
~basic_async_logger() {
if (m_file != traits::s_null_file_type)
stop();
}
/// Initialize and start asynchronous file writer
/// @param a_filename - name of the file
/// @param a_notify_immediate - whether to notify the I/O thread on write
int start(const std::string& filename, bool a_notify_immediate = true);
/// Stop asynchronous file writering thread
void stop();
/// @return name of the log file
const std::string& filename() const { return m_filename; }
/// @return max size of the commit queue
const int max_queue_size() const { return m_max_queue_size; }
/// @return indicates if async thread must be notified immediately
/// when message is written to queue
int notify_immediate() const { return m_notify_immediate; }
/// Allocate a message of size \a a_sz.
/// The content of the message is accessible via its data() property
log_msg_type* allocate(size_t a_sz);
/// Deallocate an object previously allocated by call to allocate().
void deallocate(log_msg_type* a_msg);
/// Write a message to the logger by making of copy of
int write_copy(const void* a_data, size_t a_sz);
// Enqueues msg to internal queue
int write(log_msg_type* msg);
/// Callback to be called on file I/O error
std::function<void (int, const char*)> on_error;
};
//-----------------------------------------------------------------------------
/// Asynchronous text logger
//-----------------------------------------------------------------------------
template <class Traits = async_file_logger_traits>
struct text_file_logger: public basic_async_logger<Traits> {
using base = basic_async_logger<Traits>;
using log_msg_type = typename base::log_msg_type;
using allocator = typename base::allocator;
explicit text_file_logger(const allocator& alloc = allocator())
: base(alloc)
{}
/// Formatted write with arguments
int fwrite(const char* fmt, ...) {
va_list ap;
va_start(ap, fmt);
int result = vwrite(fmt, ap);
va_end(ap);
return result;
}
/// Write string to file
int write(const char* a) {
return (!this->m_file || this->m_cancel)
? -1 : this->write_copy((void*)a, strlen(a));
}
/// Write \a s to file asynchronously
int write(const std::string& a) {
return (!this->m_file || this->m_cancel)
? -1 : this->write_copy((void*)a.c_str(), a.size());
}
/// Formatted write with argumets
int vwrite(const char* fmt, va_list ap) {
if (!this->m_file || this->m_cancel)
return -1;
char buf[Traits::write_buf_sz];
int n = vsnprintf(buf, sizeof(buf)-1, fmt, ap);
return this->write_copy(buf, n);
}
};
//-----------------------------------------------------------------------------
// Implementation
//-----------------------------------------------------------------------------
template<typename traits>
int basic_async_logger<traits>::
start(const std::string& a_filename, bool a_notify_immediate)
{
if (m_file)
return -1;
m_event.reset();
m_filename = a_filename;
m_head = nullptr;
m_cancel = false;
m_notify_immediate = a_notify_immediate;
if (!(m_file = traits::file_open(m_filename))) {
print_error(-1, strerror(errno), __LINE__);
return -2;
}
std::condition_variable cv;
std::mutex mtx;
std::unique_lock<std::mutex> guard(mtx);
m_thread.reset(new std::thread([this, &cv]() { run(&cv); }));
cv.wait(guard);
return 0;
}
//-----------------------------------------------------------------------------
template<typename traits>
void basic_async_logger<traits>::stop()
{
if (m_file == traits::s_null_file_type)
return;
m_cancel = true;
ASYNC_TRACE("Stopping async logger (head %p)\n", m_head);
m_event.signal();
if (m_thread) {
m_thread->join();
m_thread.reset();
}
}
//-----------------------------------------------------------------------------
template<typename traits>
void basic_async_logger<traits>::run(std::condition_variable* a_cv)
{
// Notify the caller this thread is ready
a_cv->notify_one();
ASYNC_TRACE("Started async logging thread (cancel=%s)\n",
m_cancel ? "true" : "false");
static const timespec ts{
traits::commit_timeout / 1000,
(traits::commit_timeout % 1000) * 1000000
};
while (true) {
int n = commit(&ts);
ASYNC_TRACE("Async thread result: %d (head=%p, cancel=%s)\n",
n, m_head, m_cancel ? "true" : "false" );
if (n || (!m_head && m_cancel))
break;
}
traits::file_close(m_file);
m_file = traits::s_null_file_type;
}
//-----------------------------------------------------------------------------
template<typename traits>
int basic_async_logger<traits>::commit(const struct timespec* tsp)
{
ASYNC_TRACE("Committing head: %p\n", m_head);
int old_val = m_event.value();
while (!m_head.load(std::memory_order_relaxed)) {
m_event.wait(tsp, &old_val);
if (m_cancel && !m_head.load(std::memory_order_relaxed))
return 0;
}
log_msg_type* cur_head;
do {
cur_head = m_head.load(std::memory_order_relaxed);
} while (!m_head.compare_exchange_weak(cur_head, nullptr,
std::memory_order_release,
std::memory_order_relaxed));
ASYNC_TRACE(" --> cur head: %p, new head: %p\n", cur_head, m_head);
assert(cur_head);
int count = 0;
log_msg_type* last = nullptr;
log_msg_type* next = cur_head;
// Reverse the section of this list
for (auto p = cur_head; next; count++, p = next) {
ASYNC_TRACE("Set last[%p] -> next[%p]\n", next, last);
next = p->next();
p->next(last);
last = p;
}
assert(last);
ASYNC_TRACE("Total (%d). Sublist's head: %p (%s)\n",
count, last, last->c_str());
if (m_max_queue_size < count)
m_max_queue_size = count;
next = last;
for (auto p = last; next; p = next) {
if (traits::file_write(m_file, p->data(), p->size()) < 0)
return -1;
next = p->next();
p->next(nullptr);
ASYNC_TRACE("Wrote (%ld bytes): %p (next: %p): %s\n",
p->size(), p, next, p->c_str());
deallocate(p);
}
if (traits::file_flush(m_file) < 0)
return -2;
return 0;
}
//-----------------------------------------------------------------------------
template<typename traits>
inline typename basic_async_logger<traits>::log_msg_type*
basic_async_logger<traits>::
allocate(size_t a_sz)
{
auto size = sizeof(log_msg_type) + a_sz;
char* p = m_allocator.allocate(size);
char* data = p + sizeof(log_msg_type);
auto q = reinterpret_cast<log_msg_type*>(p);
new (q) log_msg_type(data, a_sz);
return q;
}
//-----------------------------------------------------------------------------
template<typename traits>
inline void basic_async_logger<traits>::
deallocate(log_msg_type* a_msg)
{
auto size = sizeof(log_msg_type) + a_msg->size();
a_msg->~log_msg_type();
m_allocator.deallocate(reinterpret_cast<char*>(a_msg), size);
}
//-----------------------------------------------------------------------------
template<typename traits>
inline int basic_async_logger<traits>::
write_copy(const void* a_data, size_t a_sz)
{
auto msg = allocate(a_sz);
memcpy(msg->data(), a_data, a_sz);
return write(msg);
}
//-----------------------------------------------------------------------------
template<typename traits>
inline int basic_async_logger<traits>::write(log_msg_type* msg)
{
if (!msg)
return -3;
int n = msg->size();
log_msg_type* last_head;
do {
last_head = m_head.load(std::memory_order_relaxed);
msg->next(last_head);
} while (!m_head.compare_exchange_weak(last_head, msg,
std::memory_order_release,
std::memory_order_relaxed));
if (!last_head && m_notify_immediate)
m_event.signal();
ASYNC_TRACE("write - cur head: %p, prev head: %p\n",
m_head, last_head);
return n;
}
//-----------------------------------------------------------------------------
template<typename traits>
void basic_async_logger<traits>::
print_error(int a_errno, const char* a_what, int a_line) {
if (on_error)
on_error(a_errno, a_what);
else
std::cerr << "Error " << a_errno << " writing to file \"" << m_filename
<< "\": " << a_what << " [" << __FILE__ << ':' << a_line
<< ']' << std::endl;
}
} // namespace utxx
<commit_msg>Cleanup<commit_after>//----------------------------------------------------------------------------
/// \file async_file_logger.cpp
/// \author Serge Aleynikov
//----------------------------------------------------------------------------
/// \brief Asynchronous file logger
//----------------------------------------------------------------------------
// Copyright (c) 2012 Omnibius, LLC
// Created: 2012-03-20
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****
This file is part of utxx open-source project.
Copyright (C) 2012 Serge Aleynikov <[email protected]>
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
***** END LICENSE BLOCK *****
*/
#pragma once
#include <utxx/atomic.hpp>
#include <utxx/synch.hpp>
#include <iostream>
#include <functional>
#include <thread>
#include <memory>
#include <string>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
namespace utxx {
#ifdef DEBUG_ASYNC_LOGGER
# define ASYNC_TRACE(...) printf(__VA_ARGS__);
#else
# define ASYNC_TRACE(...)
#endif
//-----------------------------------------------------------------------------
/// Traits of asynchronous logger using file stream writing
//-----------------------------------------------------------------------------
struct async_file_logger_traits {
using allocator = std::allocator<char>;
using event_type = futex;
using file_type = FILE*;
static constexpr const file_type null_file_value = nullptr;
//-------------------------------------------------------------------------
/// Represents a text message to be logged by the logger
//-------------------------------------------------------------------------
class msg_type {
size_t m_size;
char* m_data;
public:
explicit msg_type(const char* a_data, size_t a_size)
: m_size(a_size)
, m_data(const_cast<char*>(a_data))
{}
bool empty() const { return m_size; }
size_t size() const { return m_size; }
const char* data() const { return m_data; }
char* data() { return m_data; }
};
static file_type file_open(const std::string& a_filename) {
return fopen(a_filename.c_str(), "a+");
};
static int file_write(file_type a_fd, const char* a_data, size_t a_sz) {
return fwrite(a_data, a_sz, 1, a_fd);
};
static int file_close(file_type a_fd) { return fclose(a_fd); }
static int file_flush(file_type a_fd) { return fflush(a_fd); }
static const int commit_timeout = 1000; // commit interval in usecs
static const int write_buf_sz = 256;
};
//-----------------------------------------------------------------------------
/// Traits of asynchronous logger using direct file I/O writing
//-----------------------------------------------------------------------------
struct async_fd_logger_traits : public async_file_logger_traits {
using file_type = int;
static constexpr const file_type null_file_value = -1;
static file_type file_open(const std::string& a_filename) {
return ::open(a_filename.c_str(), O_CREAT | O_APPEND | O_RDWR);
};
static int file_write(file_type a_fd, const char* a_data, size_t a_sz) {
return ::write(a_fd, a_data, a_sz);
};
static int file_close(file_type a_fd) { return ::close(a_fd); }
static int file_flush(file_type a_fd) { return 0; }
};
//-----------------------------------------------------------------------------
/// Asynchronous logger of text messages.
//-----------------------------------------------------------------------------
template<typename traits = async_file_logger_traits>
class basic_async_logger {
protected:
class cons: public traits::msg_type {
using base = typename traits::msg_type;
using allocator = typename traits::allocator;
public:
cons(const char* a_data, size_t a_sz) : base(a_data, a_sz) {}
cons* next() { return m_next; }
void next(cons* p) { m_next = p; }
private:
cons* m_next = nullptr;
};
using allocator = typename traits::allocator;
using event_type = typename traits::event_type;
using log_msg_type = cons;
using file_type = typename traits::file_type;
std::unique_ptr<std::thread> m_thread;
allocator m_allocator;
file_type m_file;
std::atomic<log_msg_type*> m_head;
bool m_cancel;
int m_max_queue_size;
std::string m_filename;
event_type m_event;
bool m_notify_immediate;
// Invoked by the async thread to flush messages from queue to file
int commit(const struct timespec* tsp = NULL);
// Invoked by the async thread
void run(std::condition_variable* a_cv);
// Print error message
void print_error(int, const char* what, int line);
public:
explicit basic_async_logger(const allocator& alloc = allocator())
: m_allocator(alloc)
, m_file(traits::null_file_value)
, m_head(nullptr)
, m_cancel(false)
, m_max_queue_size(0)
, m_notify_immediate(true)
{}
~basic_async_logger() {
if (m_file != traits::null_file_value)
stop();
}
/// Initialize and start asynchronous file writer
/// @param a_filename - name of the file
/// @param a_notify_immediate - whether to notify the I/O thread on write
int start(const std::string& filename, bool a_notify_immediate = true);
/// Stop asynchronous file writering thread
void stop();
/// @return name of the log file
const std::string& filename() const { return m_filename; }
/// @return max size of the commit queue
const int max_queue_size() const { return m_max_queue_size; }
/// @return indicates if async thread must be notified immediately
/// when message is written to queue
int notify_immediate() const { return m_notify_immediate; }
/// Allocate a message of size \a a_sz.
/// The content of the message is accessible via its data() property
log_msg_type* allocate(size_t a_sz);
/// Deallocate an object previously allocated by call to allocate().
void deallocate(log_msg_type* a_msg);
/// Write a message to the logger by making of copy of
int write_copy(const void* a_data, size_t a_sz);
// Enqueues msg to internal queue
int write(log_msg_type* msg);
/// Callback to be called on file I/O error
std::function<void (int, const char*)> on_error;
};
//-----------------------------------------------------------------------------
/// Asynchronous text logger
//-----------------------------------------------------------------------------
template <class Traits = async_file_logger_traits>
struct text_file_logger: public basic_async_logger<Traits> {
using base = basic_async_logger<Traits>;
using log_msg_type = typename base::log_msg_type;
using allocator = typename base::allocator;
explicit text_file_logger(const allocator& alloc = allocator())
: base(alloc)
{}
/// Formatted write with arguments
int fwrite(const char* fmt, ...) {
va_list ap;
va_start(ap, fmt);
int result = vwrite(fmt, ap);
va_end(ap);
return result;
}
/// Write string to file
int write(const char* a) {
return (!this->m_file || this->m_cancel)
? -1 : this->write_copy((void*)a, strlen(a));
}
/// Write \a s to file asynchronously
int write(const std::string& a) {
return (!this->m_file || this->m_cancel)
? -1 : this->write_copy((void*)a.c_str(), a.size());
}
/// Formatted write with argumets
int vwrite(const char* fmt, va_list ap) {
if (!this->m_file || this->m_cancel)
return -1;
char buf[Traits::write_buf_sz];
int n = vsnprintf(buf, sizeof(buf)-1, fmt, ap);
return this->write_copy(buf, n);
}
};
//-----------------------------------------------------------------------------
// Implementation
//-----------------------------------------------------------------------------
template<typename traits>
int basic_async_logger<traits>::
start(const std::string& a_filename, bool a_notify_immediate)
{
if (m_file)
return -1;
m_event.reset();
m_filename = a_filename;
m_head = nullptr;
m_cancel = false;
m_notify_immediate = a_notify_immediate;
if (!(m_file = traits::file_open(m_filename))) {
print_error(-1, strerror(errno), __LINE__);
return -2;
}
std::condition_variable cv;
std::mutex mtx;
std::unique_lock<std::mutex> guard(mtx);
m_thread.reset(new std::thread([this, &cv]() { run(&cv); }));
cv.wait(guard);
return 0;
}
//-----------------------------------------------------------------------------
template<typename traits>
void basic_async_logger<traits>::stop()
{
if (m_file == traits::null_file_value)
return;
m_cancel = true;
ASYNC_TRACE("Stopping async logger (head %p)\n", m_head);
m_event.signal();
if (m_thread) {
m_thread->join();
m_thread.reset();
}
}
//-----------------------------------------------------------------------------
template<typename traits>
void basic_async_logger<traits>::run(std::condition_variable* a_cv)
{
// Notify the caller this thread is ready
a_cv->notify_one();
ASYNC_TRACE("Started async logging thread (cancel=%s)\n",
m_cancel ? "true" : "false");
static const timespec ts{
traits::commit_timeout / 1000,
(traits::commit_timeout % 1000) * 1000000
};
while (true) {
int n = commit(&ts);
ASYNC_TRACE("Async thread result: %d (head=%p, cancel=%s)\n",
n, m_head, m_cancel ? "true" : "false" );
if (n || (!m_head && m_cancel))
break;
}
traits::file_close(m_file);
m_file = traits::null_file_value;
}
//-----------------------------------------------------------------------------
template<typename traits>
int basic_async_logger<traits>::commit(const struct timespec* tsp)
{
ASYNC_TRACE("Committing head: %p\n", m_head);
int old_val = m_event.value();
while (!m_head.load(std::memory_order_relaxed)) {
m_event.wait(tsp, &old_val);
if (m_cancel && !m_head.load(std::memory_order_relaxed))
return 0;
}
log_msg_type* cur_head;
do {
cur_head = m_head.load(std::memory_order_relaxed);
} while (!m_head.compare_exchange_weak(cur_head, nullptr,
std::memory_order_release,
std::memory_order_relaxed));
ASYNC_TRACE(" --> cur head: %p, new head: %p\n", cur_head, m_head);
assert(cur_head);
int count = 0;
log_msg_type* last = nullptr;
log_msg_type* next = cur_head;
// Reverse the section of this list
for (auto p = cur_head; next; count++, p = next) {
ASYNC_TRACE("Set last[%p] -> next[%p]\n", next, last);
next = p->next();
p->next(last);
last = p;
}
assert(last);
ASYNC_TRACE("Total (%d). Sublist's head: %p (%s)\n",
count, last, last->c_str());
if (m_max_queue_size < count)
m_max_queue_size = count;
next = last;
for (auto p = last; next; p = next) {
if (traits::file_write(m_file, p->data(), p->size()) < 0)
return -1;
next = p->next();
p->next(nullptr);
ASYNC_TRACE("Wrote (%ld bytes): %p (next: %p): %s\n",
p->size(), p, next, p->c_str());
deallocate(p);
}
if (traits::file_flush(m_file) < 0)
return -2;
return 0;
}
//-----------------------------------------------------------------------------
template<typename traits>
inline typename basic_async_logger<traits>::log_msg_type*
basic_async_logger<traits>::
allocate(size_t a_sz)
{
auto size = sizeof(log_msg_type) + a_sz;
char* p = m_allocator.allocate(size);
char* data = p + sizeof(log_msg_type);
auto q = reinterpret_cast<log_msg_type*>(p);
new (q) log_msg_type(data, a_sz);
return q;
}
//-----------------------------------------------------------------------------
template<typename traits>
inline void basic_async_logger<traits>::
deallocate(log_msg_type* a_msg)
{
auto size = sizeof(log_msg_type) + a_msg->size();
a_msg->~log_msg_type();
m_allocator.deallocate(reinterpret_cast<char*>(a_msg), size);
}
//-----------------------------------------------------------------------------
template<typename traits>
inline int basic_async_logger<traits>::
write_copy(const void* a_data, size_t a_sz)
{
auto msg = allocate(a_sz);
memcpy(msg->data(), a_data, a_sz);
return write(msg);
}
//-----------------------------------------------------------------------------
template<typename traits>
inline int basic_async_logger<traits>::write(log_msg_type* msg)
{
if (!msg)
return -3;
int n = msg->size();
log_msg_type* last_head;
do {
last_head = m_head.load(std::memory_order_relaxed);
msg->next(last_head);
} while (!m_head.compare_exchange_weak(last_head, msg,
std::memory_order_release,
std::memory_order_relaxed));
if (!last_head && m_notify_immediate)
m_event.signal();
ASYNC_TRACE("write - cur head: %p, prev head: %p\n",
m_head, last_head);
return n;
}
//-----------------------------------------------------------------------------
template<typename traits>
void basic_async_logger<traits>::
print_error(int a_errno, const char* a_what, int a_line) {
if (on_error)
on_error(a_errno, a_what);
else
std::cerr << "Error " << a_errno << " writing to file \"" << m_filename
<< "\": " << a_what << " [" << __FILE__ << ':' << a_line
<< ']' << std::endl;
}
} // namespace utxx
<|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 "arrow/dataset/partition.h"
#include <algorithm>
#include <map>
#include <memory>
#include <regex>
#include <utility>
#include <vector>
#include "arrow/dataset/dataset_internal.h"
#include "arrow/dataset/filter.h"
#include "arrow/dataset/scanner.h"
#include "arrow/filesystem/filesystem.h"
#include "arrow/filesystem/path_util.h"
#include "arrow/scalar.h"
#include "arrow/util/iterator.h"
#include "arrow/util/string_view.h"
namespace arrow {
namespace dataset {
using util::string_view;
Result<std::shared_ptr<Expression>> PartitionScheme::Parse(
const std::string& path) const {
ExpressionVector expressions;
int i = 0;
for (auto segment : fs::internal::SplitAbstractPath(path)) {
ARROW_ASSIGN_OR_RAISE(auto expr, Parse(segment, i++));
if (expr->Equals(true)) {
continue;
}
expressions.push_back(std::move(expr));
}
return and_(std::move(expressions));
}
std::shared_ptr<PartitionScheme> PartitionScheme::Default() {
return std::make_shared<DefaultPartitionScheme>();
}
Result<std::shared_ptr<Expression>> SegmentDictionaryPartitionScheme::Parse(
const std::string& segment, int i) const {
if (static_cast<size_t>(i) < dictionaries_.size()) {
auto it = dictionaries_[i].find(segment);
if (it != dictionaries_[i].end()) {
return it->second;
}
}
return scalar(true);
}
Result<std::shared_ptr<Expression>> PartitionKeysScheme::ConvertKey(
const Key& key, const Schema& schema) {
auto field = schema.GetFieldByName(key.name);
if (field == nullptr) {
return scalar(true);
}
ARROW_ASSIGN_OR_RAISE(auto converted, Scalar::Parse(field->type(), key.value));
return equal(field_ref(field->name()), scalar(converted));
}
Result<std::shared_ptr<Expression>> PartitionKeysScheme::Parse(const std::string& segment,
int i) const {
if (auto key = ParseKey(segment, i)) {
return ConvertKey(*key, *schema_);
}
return scalar(true);
}
util::optional<PartitionKeysScheme::Key> SchemaPartitionScheme::ParseKey(
const std::string& segment, int i) const {
if (i >= schema_->num_fields()) {
return util::nullopt;
}
return Key{schema_->field(i)->name(), segment};
}
inline bool AllIntegral(const std::vector<std::string>& reprs) {
return std::all_of(reprs.begin(), reprs.end(), [](string_view repr) {
// TODO(bkietz) use ParseUnsigned or so
return repr.find_first_not_of("0123456789") == string_view::npos;
});
}
inline std::shared_ptr<Schema> InferSchema(
const std::map<std::string, std::vector<std::string>>& name_to_values) {
std::vector<std::shared_ptr<Field>> fields(name_to_values.size());
size_t field_index = 0;
for (const auto& name_values : name_to_values) {
auto type = AllIntegral(name_values.second) ? int32() : utf8();
fields[field_index++] = field(name_values.first, type);
}
return ::arrow::schema(std::move(fields));
}
class SchemaPartitionSchemeDiscovery : public PartitionSchemeDiscovery {
public:
explicit SchemaPartitionSchemeDiscovery(std::vector<std::string> field_names)
: field_names_(std::move(field_names)) {}
Result<std::shared_ptr<Schema>> Inspect(
const std::vector<string_view>& paths) const override {
std::map<std::string, std::vector<std::string>> name_to_values;
for (auto path : paths) {
size_t field_index = 0;
for (auto&& segment : fs::internal::SplitAbstractPath(path.to_string())) {
if (field_index == field_names_.size()) break;
name_to_values[field_names_[field_index++]].push_back(std::move(segment));
}
}
// ensure that the fields are ordered by field_names_
return SchemaFromColumnNames(InferSchema(name_to_values), field_names_);
}
Result<std::shared_ptr<PartitionScheme>> Finish(
const std::shared_ptr<Schema>& schema) const override {
for (const auto& field_name : field_names_) {
if (schema->GetFieldIndex(field_name) == -1) {
return Status::TypeError("no field named '", field_name, "' in schema", *schema);
}
}
// drop fields which aren't in field_names_
auto out_schema = SchemaFromColumnNames(schema, field_names_);
return std::make_shared<SchemaPartitionScheme>(std::move(out_schema));
}
private:
std::vector<std::string> field_names_;
};
std::shared_ptr<PartitionSchemeDiscovery> SchemaPartitionScheme::MakeDiscovery(
std::vector<std::string> field_names) {
return std::shared_ptr<PartitionSchemeDiscovery>(
new SchemaPartitionSchemeDiscovery(std::move(field_names)));
}
util::optional<PartitionKeysScheme::Key> HivePartitionScheme::ParseKey(
const std::string& segment) {
static std::regex hive_style("^([^=]+)=(.*)$");
std::smatch matches;
if (!std::regex_match(segment, matches, hive_style) || matches.size() != 3) {
return util::nullopt;
}
return Key{matches[1].str(), matches[2].str()};
}
class HivePartitionSchemeDiscovery : public PartitionSchemeDiscovery {
public:
Result<std::shared_ptr<Schema>> Inspect(
const std::vector<string_view>& paths) const override {
std::map<std::string, std::vector<std::string>> name_to_values;
for (auto path : paths) {
for (auto&& segment : fs::internal::SplitAbstractPath(path.to_string())) {
if (auto key = HivePartitionScheme::ParseKey(segment)) {
name_to_values[key->name].push_back(std::move(key->value));
}
}
}
return InferSchema(name_to_values);
}
Result<std::shared_ptr<PartitionScheme>> Finish(
const std::shared_ptr<Schema>& schema) const override {
return std::shared_ptr<PartitionScheme>(new HivePartitionScheme(schema));
}
};
std::shared_ptr<PartitionSchemeDiscovery> HivePartitionScheme::MakeDiscovery() {
return std::shared_ptr<PartitionSchemeDiscovery>(new HivePartitionSchemeDiscovery());
}
} // namespace dataset
} // namespace arrow
<commit_msg>ARROW-7500: [C++][Dataset] Remove std::regex usage<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 "arrow/dataset/partition.h"
#include <algorithm>
#include <map>
#include <memory>
#include <utility>
#include <vector>
#include "arrow/dataset/dataset_internal.h"
#include "arrow/dataset/filter.h"
#include "arrow/dataset/scanner.h"
#include "arrow/filesystem/filesystem.h"
#include "arrow/filesystem/path_util.h"
#include "arrow/scalar.h"
#include "arrow/util/iterator.h"
#include "arrow/util/string_view.h"
namespace arrow {
namespace dataset {
using util::string_view;
Result<std::shared_ptr<Expression>> PartitionScheme::Parse(
const std::string& path) const {
ExpressionVector expressions;
int i = 0;
for (auto segment : fs::internal::SplitAbstractPath(path)) {
ARROW_ASSIGN_OR_RAISE(auto expr, Parse(segment, i++));
if (expr->Equals(true)) {
continue;
}
expressions.push_back(std::move(expr));
}
return and_(std::move(expressions));
}
std::shared_ptr<PartitionScheme> PartitionScheme::Default() {
return std::make_shared<DefaultPartitionScheme>();
}
Result<std::shared_ptr<Expression>> SegmentDictionaryPartitionScheme::Parse(
const std::string& segment, int i) const {
if (static_cast<size_t>(i) < dictionaries_.size()) {
auto it = dictionaries_[i].find(segment);
if (it != dictionaries_[i].end()) {
return it->second;
}
}
return scalar(true);
}
Result<std::shared_ptr<Expression>> PartitionKeysScheme::ConvertKey(
const Key& key, const Schema& schema) {
auto field = schema.GetFieldByName(key.name);
if (field == nullptr) {
return scalar(true);
}
ARROW_ASSIGN_OR_RAISE(auto converted, Scalar::Parse(field->type(), key.value));
return equal(field_ref(field->name()), scalar(converted));
}
Result<std::shared_ptr<Expression>> PartitionKeysScheme::Parse(const std::string& segment,
int i) const {
if (auto key = ParseKey(segment, i)) {
return ConvertKey(*key, *schema_);
}
return scalar(true);
}
util::optional<PartitionKeysScheme::Key> SchemaPartitionScheme::ParseKey(
const std::string& segment, int i) const {
if (i >= schema_->num_fields()) {
return util::nullopt;
}
return Key{schema_->field(i)->name(), segment};
}
inline bool AllIntegral(const std::vector<std::string>& reprs) {
return std::all_of(reprs.begin(), reprs.end(), [](string_view repr) {
// TODO(bkietz) use ParseUnsigned or so
return repr.find_first_not_of("0123456789") == string_view::npos;
});
}
inline std::shared_ptr<Schema> InferSchema(
const std::map<std::string, std::vector<std::string>>& name_to_values) {
std::vector<std::shared_ptr<Field>> fields(name_to_values.size());
size_t field_index = 0;
for (const auto& name_values : name_to_values) {
auto type = AllIntegral(name_values.second) ? int32() : utf8();
fields[field_index++] = field(name_values.first, type);
}
return ::arrow::schema(std::move(fields));
}
class SchemaPartitionSchemeDiscovery : public PartitionSchemeDiscovery {
public:
explicit SchemaPartitionSchemeDiscovery(std::vector<std::string> field_names)
: field_names_(std::move(field_names)) {}
Result<std::shared_ptr<Schema>> Inspect(
const std::vector<string_view>& paths) const override {
std::map<std::string, std::vector<std::string>> name_to_values;
for (auto path : paths) {
size_t field_index = 0;
for (auto&& segment : fs::internal::SplitAbstractPath(path.to_string())) {
if (field_index == field_names_.size()) break;
name_to_values[field_names_[field_index++]].push_back(std::move(segment));
}
}
// ensure that the fields are ordered by field_names_
return SchemaFromColumnNames(InferSchema(name_to_values), field_names_);
}
Result<std::shared_ptr<PartitionScheme>> Finish(
const std::shared_ptr<Schema>& schema) const override {
for (const auto& field_name : field_names_) {
if (schema->GetFieldIndex(field_name) == -1) {
return Status::TypeError("no field named '", field_name, "' in schema", *schema);
}
}
// drop fields which aren't in field_names_
auto out_schema = SchemaFromColumnNames(schema, field_names_);
return std::make_shared<SchemaPartitionScheme>(std::move(out_schema));
}
private:
std::vector<std::string> field_names_;
};
std::shared_ptr<PartitionSchemeDiscovery> SchemaPartitionScheme::MakeDiscovery(
std::vector<std::string> field_names) {
return std::shared_ptr<PartitionSchemeDiscovery>(
new SchemaPartitionSchemeDiscovery(std::move(field_names)));
}
util::optional<PartitionKeysScheme::Key> HivePartitionScheme::ParseKey(
const std::string& segment) {
auto name_end = string_view(segment).find_first_of('=');
if (name_end == string_view::npos) {
return util::nullopt;
}
return Key{segment.substr(0, name_end), segment.substr(name_end + 1)};
}
class HivePartitionSchemeDiscovery : public PartitionSchemeDiscovery {
public:
Result<std::shared_ptr<Schema>> Inspect(
const std::vector<string_view>& paths) const override {
std::map<std::string, std::vector<std::string>> name_to_values;
for (auto path : paths) {
for (auto&& segment : fs::internal::SplitAbstractPath(path.to_string())) {
if (auto key = HivePartitionScheme::ParseKey(segment)) {
name_to_values[key->name].push_back(std::move(key->value));
}
}
}
return InferSchema(name_to_values);
}
Result<std::shared_ptr<PartitionScheme>> Finish(
const std::shared_ptr<Schema>& schema) const override {
return std::shared_ptr<PartitionScheme>(new HivePartitionScheme(schema));
}
};
std::shared_ptr<PartitionSchemeDiscovery> HivePartitionScheme::MakeDiscovery() {
return std::shared_ptr<PartitionSchemeDiscovery>(new HivePartitionSchemeDiscovery());
}
} // namespace dataset
} // namespace arrow
<|endoftext|> |
<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#pragma once
#ifndef VSNRAY_PATHTRACING_INL
#define VSNRAY_PATHTRACING_INL 1
#ifndef NDEBUG
#include <iostream>
#include <ostream>
#endif
#include <visionaray/get_surface.h>
#include <visionaray/result_record.h>
#include <visionaray/traverse.h>
namespace visionaray
{
namespace pathtracing
{
template <typename Params>
struct kernel
{
Params params;
template <typename Intersector, typename R, typename Sampler>
VSNRAY_FUNC result_record<typename R::scalar_type> operator()(
Intersector& isect,
R ray,
Sampler& s
) const
{
using S = typename R::scalar_type;
using V = typename result_record<S>::vec_type;
using C = spectrum<S>;
result_record<S> result;
auto hit_rec = closest_hit(ray, params.prims.begin, params.prims.end, isect);
auto exited = !hit_rec.hit;
auto active_rays = hit_rec.hit;
result.color = params.bg_color;
if (any(hit_rec.hit))
{
result.hit = hit_rec.hit;
result.isect_pos = ray.ori + ray.dir * hit_rec.t;
}
else
{
result.hit = false;
return result;
}
C dst(1.0);
for (unsigned d = 0; d < params.num_bounces; ++d)
{
if ( any(active_rays) )
{
V refl_dir;
V view_dir = -ray.dir;
auto surf = get_surface(hit_rec, params);
auto n = surf.shading_normal;
#if 1 // two-sided
n = faceforward( n, view_dir, surf.geometric_normal );
#endif
S pdf(0.0);
auto sr = make_shade_record<Params, S>();
sr.active = active_rays;
sr.normal = n;
sr.view_dir = view_dir;
auto src = surf.sample(sr, refl_dir, pdf, s);
auto zero_pdf = pdf <= S(0.0);
auto emissive = has_emissive_material(surf);
src = mul( src, dot(n, refl_dir) / pdf, !emissive, src ); // TODO: maybe have emissive material return refl_dir so that dot(N,R) = 1?
dst = mul( dst, src, active_rays && !zero_pdf, dst );
dst = select( zero_pdf && active_rays, C(0.0), dst );
active_rays &= !emissive;
active_rays &= !zero_pdf;
if (!any(active_rays))
{
break;
}
auto isect_pos = ray.ori + ray.dir * hit_rec.t; // TODO: store in hit_rec?!?
ray.ori = isect_pos + refl_dir * S(params.epsilon);
ray.dir = refl_dir;
hit_rec = closest_hit(ray, params.prims.begin, params.prims.end, isect);
exited = active_rays & !hit_rec.hit;
active_rays &= hit_rec.hit;
}
dst = mul( dst, C(from_rgba(params.ambient_color)), exited, dst );
}
dst = mul( dst, C(0.0), active_rays, dst );
result.color = select( result.hit, to_rgba(dst), result.color );
return result;
}
template <typename R, typename Sampler>
VSNRAY_FUNC result_record<typename R::scalar_type> operator()(
R ray,
Sampler& s
) const
{
default_intersector ignore;
return (*this)(ignore, ray, s);
}
};
} // pathtracing
} // visionaray
#endif // VSNRAY_PATHTRACING_INL
<commit_msg>Simpler control flow for naive path tracer<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#pragma once
#ifndef VSNRAY_PATHTRACING_INL
#define VSNRAY_PATHTRACING_INL 1
#ifndef NDEBUG
#include <iostream>
#include <ostream>
#endif
#include <visionaray/get_surface.h>
#include <visionaray/result_record.h>
#include <visionaray/traverse.h>
namespace visionaray
{
namespace pathtracing
{
template <typename Params>
struct kernel
{
Params params;
template <typename Intersector, typename R, typename Sampler>
VSNRAY_FUNC result_record<typename R::scalar_type> operator()(
Intersector& isect,
R ray,
Sampler& s
) const
{
using S = typename R::scalar_type;
using V = typename result_record<S>::vec_type;
using C = spectrum<S>;
simd::mask_type_t<S> active_rays = true;
C dst(1.0);
result_record<S> result;
result.color = params.bg_color;
for (unsigned bounce = 0; bounce < params.num_bounces; ++bounce)
{
auto hit_rec = closest_hit(ray, params.prims.begin, params.prims.end, isect);
// Handle rays that just exited
auto exited = active_rays & !hit_rec.hit;
dst = mul( dst, C(from_rgba(params.ambient_color)), exited, dst );
// Exit if no ray is active anymore
active_rays &= hit_rec.hit;
if (!any(active_rays))
{
break;
}
// Special handling for first bounce
if (bounce == 0)
{
result.hit = hit_rec.hit;
result.isect_pos = ray.ori + ray.dir * hit_rec.t;
}
// Process the current bounce
V refl_dir;
V view_dir = -ray.dir;
auto surf = get_surface(hit_rec, params);
auto n = surf.shading_normal;
#if 1 // two-sided
n = faceforward( n, view_dir, surf.geometric_normal );
#endif
S pdf(0.0);
auto sr = make_shade_record<Params, S>();
sr.active = active_rays;
sr.normal = n;
sr.view_dir = view_dir;
auto src = surf.sample(sr, refl_dir, pdf, s);
auto zero_pdf = pdf <= S(0.0);
auto emissive = has_emissive_material(surf);
src = mul( src, dot(n, refl_dir) / pdf, !emissive, src ); // TODO: maybe have emissive material return refl_dir so that dot(N,R) = 1?
dst = mul( dst, src, active_rays && !zero_pdf, dst );
dst = select( zero_pdf && active_rays, C(0.0), dst );
active_rays &= !emissive;
active_rays &= !zero_pdf;
if (!any(active_rays))
{
break;
}
hit_rec.isect_pos = ray.ori + ray.dir * hit_rec.t;
ray.ori = hit_rec.isect_pos + refl_dir * S(params.epsilon);
ray.dir = refl_dir;
}
// Terminate paths that are still active
dst = select(active_rays, C(0.0), dst);
result.color = select( result.hit, to_rgba(dst), result.color );
return result;
}
template <typename R, typename Sampler>
VSNRAY_FUNC result_record<typename R::scalar_type> operator()(
R ray,
Sampler& s
) const
{
default_intersector ignore;
return (*this)(ignore, ray, s);
}
};
} // pathtracing
} // visionaray
#endif // VSNRAY_PATHTRACING_INL
<|endoftext|> |
<commit_before>#include "TextTestResult.h"
#include "Exception.h"
#include "estring.h"
#include "Test.h"
using namespace std;
using namespace CppUnit;
std::ostream&
CppUnit::operator<< (std::ostream& stream, TextTestResult& result)
{
result.print (stream); return stream;
}
void
TextTestResult::addError (Test *test, Exception *e)
{
TestResult::addError (test, e);
cerr << "E\n";
}
void
TextTestResult::addFailure (Test *test, Exception *e)
{
TestResult::addFailure (test, e);
cerr << "F\n";
}
void
TextTestResult::startTest (Test *test)
{
cerr << "Running " << test->getName() << " ";
TestResult::startTest (test);
cerr << ".\n";
}
void
TextTestResult::printErrors (ostream& stream)
{
if (testErrors () != 0) {
if (testErrors () == 1)
stream << "There was " << testErrors () << " error: " << endl;
else
stream << "There were " << testErrors () << " errors: " << endl;
int i = 1;
for (vector<TestFailure *>::iterator it = errors ().begin (); it != errors ().end (); ++it) {
TestFailure *failure = *it;
Exception *e = failure->thrownException ();
stream << i
<< ") "
<< "line: " << (e ? estring (e->lineNumber ()) : "") << " "
<< (e ? e->fileName () : "") << " "
<< "\"" << failure->thrownException ()->what () << "\""
<< endl;
i++;
}
}
}
void
TextTestResult::printFailures (ostream& stream)
{
if (testFailures () != 0) {
if (testFailures () == 1)
stream << "There was " << testFailures () << " failure: " << endl;
else
stream << "There were " << testFailures () << " failures: " << endl;
int i = 1;
for (vector<TestFailure *>::iterator it = failures ().begin (); it != failures ().end (); ++it) {
TestFailure *failure = *it;
Exception *e = failure->thrownException ();
stream << i
<< ") "
<< "line: " << (e ? estring (e->lineNumber ()) : "") << " "
<< (e ? e->fileName () : "") << " "
<< "\"" << failure->thrownException ()->what () << "\""
<< endl;
i++;
}
}
}
void
TextTestResult::print (ostream& stream)
{
printHeader (stream);
printErrors (stream);
printFailures (stream);
}
void
TextTestResult::printHeader (ostream& stream)
{
if (wasSuccessful ())
cout << endl << "OK (" << runTests () << " tests)" << endl;
else
cout << endl
<< "!!!FAILURES!!!" << endl
<< "Test Results:" << endl
<< "Run: "
<< runTests ()
<< " Failures: "
<< testFailures ()
<< " Errors: "
<< testErrors ()
<< endl;
}
<commit_msg>Fix bug #232636: TextTestResult::printHeader(ostream& stream) outputs to cout.<commit_after>#include "TextTestResult.h"
#include "Exception.h"
#include "estring.h"
#include "Test.h"
using namespace std;
using namespace CppUnit;
std::ostream&
CppUnit::operator<< (std::ostream& stream, TextTestResult& result)
{
result.print (stream); return stream;
}
void
TextTestResult::addError (Test *test, Exception *e)
{
TestResult::addError (test, e);
cerr << "E\n";
}
void
TextTestResult::addFailure (Test *test, Exception *e)
{
TestResult::addFailure (test, e);
cerr << "F\n";
}
void
TextTestResult::startTest (Test *test)
{
cerr << "Running " << test->getName() << " ";
TestResult::startTest (test);
cerr << ".\n";
}
void
TextTestResult::printErrors (ostream& stream)
{
if (testErrors () != 0) {
if (testErrors () == 1)
stream << "There was " << testErrors () << " error: " << endl;
else
stream << "There were " << testErrors () << " errors: " << endl;
int i = 1;
for (vector<TestFailure *>::iterator it = errors ().begin (); it != errors ().end (); ++it) {
TestFailure *failure = *it;
Exception *e = failure->thrownException ();
stream << i
<< ") "
<< "line: " << (e ? estring (e->lineNumber ()) : "") << " "
<< (e ? e->fileName () : "") << " "
<< "\"" << failure->thrownException ()->what () << "\""
<< endl;
i++;
}
}
}
void
TextTestResult::printFailures (ostream& stream)
{
if (testFailures () != 0) {
if (testFailures () == 1)
stream << "There was " << testFailures () << " failure: " << endl;
else
stream << "There were " << testFailures () << " failures: " << endl;
int i = 1;
for (vector<TestFailure *>::iterator it = failures ().begin (); it != failures ().end (); ++it) {
TestFailure *failure = *it;
Exception *e = failure->thrownException ();
stream << i
<< ") "
<< "line: " << (e ? estring (e->lineNumber ()) : "") << " "
<< (e ? e->fileName () : "") << " "
<< "\"" << failure->thrownException ()->what () << "\""
<< endl;
i++;
}
}
}
void
TextTestResult::print (ostream& stream)
{
printHeader (stream);
printErrors (stream);
printFailures (stream);
}
void
TextTestResult::printHeader (ostream& stream)
{
if (wasSuccessful ())
stream << endl << "OK (" << runTests () << " tests)" << endl;
else
stream << endl
<< "!!!FAILURES!!!" << endl
<< "Test Results:" << endl
<< "Run: "
<< runTests ()
<< " Failures: "
<< testFailures ()
<< " Errors: "
<< testErrors ()
<< endl;
}
<|endoftext|> |
<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <atomic>
#include <cassert>
#include <condition_variable>
#include <functional>
#include <thread>
#include <utility>
#include <visionaray/math/math.h>
#include <visionaray/random_sampler.h>
#include "macros.h"
#include "sched_common.h"
#include "semaphore.h"
namespace visionaray
{
namespace detail
{
static const int tile_width = 16;
static const int tile_height = 16;
struct sync_params
{
sync_params()
: render_loop_exit(false)
{
}
std::mutex mutex;
std::condition_variable threads_start;
visionaray::semaphore threads_ready;
std::atomic<long> tile_idx_counter;
std::atomic<long> tile_fin_counter;
std::atomic<long> tile_num;
std::atomic<bool> render_loop_exit;
};
} // detail
//-------------------------------------------------------------------------------------------------
// Private implementation
//
template <typename R>
struct tiled_sched<R>::impl
{
// TODO: any sampler
typedef std::function<void(recti const&, random_sampler<typename R::scalar_type>&)> render_tile_func;
void init_threads(unsigned num_threads);
void destroy_threads();
void render_loop();
template <typename K, typename SP>
void init_render_func(K kernel, SP sparams, unsigned frame_num, std::true_type /* has matrix */);
template <typename K, typename SP>
void init_render_func(K kernel, SP sparams, unsigned frame_num, std::false_type /* has matrix */);
template <typename K, typename SP, typename Sampler, typename ...Args>
void call_sample_pixel(
std::false_type /* has intersector */,
K kernel,
SP sparams,
Sampler& samp,
unsigned frame_num,
Args&&... args
)
{
auto r = detail::make_primary_rays(
R{},
typename SP::pixel_sampler_type{},
samp,
args...
);
sample_pixel(
kernel,
typename SP::pixel_sampler_type(),
r,
samp,
frame_num,
sparams.rt.ref(),
std::forward<Args>(args)...
);
}
template <typename K, typename SP, typename Sampler, typename ...Args>
void call_sample_pixel(
std::true_type /* has intersector */,
K kernel,
SP sparams,
Sampler& samp,
unsigned frame_num,
Args&&... args
)
{
auto r = detail::make_primary_rays(
R{},
typename SP::pixel_sampler_type{},
samp,
args...
);
sample_pixel(
detail::have_intersector_tag(),
sparams.intersector,
kernel,
typename SP::pixel_sampler_type(),
r,
samp,
frame_num,
sparams.rt.ref(),
std::forward<Args>(args)...
);
}
std::vector<std::thread> threads;
detail::sync_params sync_params;
int width;
int height;
recti scissor_box;
render_tile_func render_tile;
};
template <typename R>
void tiled_sched<R>::impl::init_threads(unsigned num_threads)
{
for (unsigned i = 0; i < num_threads; ++i)
{
threads.emplace_back([this](){ render_loop(); });
}
}
template <typename R>
void tiled_sched<R>::impl::destroy_threads()
{
if (threads.size() == 0)
{
return;
}
sync_params.render_loop_exit = true;
sync_params.threads_start.notify_all();
for (auto& t : threads)
{
if (t.joinable())
{
t.join();
}
}
sync_params.render_loop_exit = false;
threads.clear();
}
//-------------------------------------------------------------------------------------------------
// Main render loop
//
template <typename R>
void tiled_sched<R>::impl::render_loop()
{
for (;;)
{
{
std::unique_lock<std::mutex> l( sync_params.mutex );
sync_params.threads_start.wait(l);
}
// case event.exit:
if (sync_params.render_loop_exit)
{
break;
}
// case event.render:
random_sampler<typename R::scalar_type> samp(detail::tic());
for (;;)
{
auto tile_idx = sync_params.tile_idx_counter.fetch_add(1);
if (tile_idx >= sync_params.tile_num)
{
break;
}
auto tilew = detail::tile_width;
auto tileh = detail::tile_height;
auto numtilesx = div_up( width, tilew );
recti tile(
(tile_idx % numtilesx) * tilew,
(tile_idx / numtilesx) * tileh,
tilew,
tileh
);
render_tile(tile, samp);
auto num_tiles_fin = sync_params.tile_fin_counter.fetch_add(1);
if (num_tiles_fin >= sync_params.tile_num - 1)
{
assert(num_tiles_fin == sync_params.tile_num - 1);
sync_params.threads_ready.notify();
break;
}
}
}
}
template <typename R>
template <typename K, typename SP>
void tiled_sched<R>::impl::init_render_func(K kernel, SP sparams, unsigned frame_num, std::true_type)
{
// overload for two matrices
using T = typename R::scalar_type;
using matrix_type = matrix<4, 4, T>;
width = sparams.rt.width();
height = sparams.rt.height();
scissor_box = sparams.scissor_box;
auto view_matrix = matrix_type( sparams.view_matrix );
auto proj_matrix = matrix_type( sparams.proj_matrix );
auto inv_view_matrix = matrix_type( inverse(sparams.view_matrix) );
auto inv_proj_matrix = matrix_type( inverse(sparams.proj_matrix) );
recti clip_rect(scissor_box.x, scissor_box.y, scissor_box.w - 1, scissor_box.h - 1);
render_tile = [=](recti const& tile, random_sampler<T>& samp)
{
using namespace detail;
unsigned numx = tile_width / packet_size<T>::w;
unsigned numy = tile_height / packet_size<T>::h;
for (unsigned i = 0; i < numx * numy; ++i)
{
auto pos = vec2i(i % numx, i / numx);
auto x = tile.x + pos.x * packet_size<T>::w;
auto y = tile.y + pos.y * packet_size<T>::h;
recti xpixel(x, y, packet_size<T>::w - 1, packet_size<T>::h - 1);
if ( !overlapping(clip_rect, xpixel) )
{
continue;
}
call_sample_pixel(
typename detail::sched_params_has_intersector<SP>::type(),
kernel,
sparams,
samp,
frame_num,
x,
y,
sparams.rt.width(),
sparams.rt.height(),
view_matrix,
inv_view_matrix,
proj_matrix,
inv_proj_matrix
);
}
};
}
template <typename R>
template <typename K, typename SP>
void tiled_sched<R>::impl::init_render_func(K kernel, SP sparams, unsigned frame_num, std::false_type)
{
// overload for pinhole cam
using T = typename R::scalar_type;
width = sparams.rt.width();
height = sparams.rt.height();
scissor_box = sparams.scissor_box;
recti clip_rect(scissor_box.x, scissor_box.y, scissor_box.w - 1, scissor_box.h - 1);
// front, side, and up vectors form an orthonormal basis
auto f = normalize( sparams.cam.eye() - sparams.cam.center() );
auto s = normalize( cross(sparams.cam.up(), f) );
auto u = cross(f, s);
vec3 eye = sparams.cam.eye();
vec3 cam_u = s * tan(sparams.cam.fovy() / 2.0f) * sparams.cam.aspect();
vec3 cam_v = u * tan(sparams.cam.fovy() / 2.0f);
vec3 cam_w = -f;
render_tile = [=](recti const& tile, random_sampler<T>& samp)
{
using namespace detail;
unsigned numx = tile_width / packet_size<T>::w;
unsigned numy = tile_height / packet_size<T>::h;
for (unsigned i = 0; i < numx * numy; ++i)
{
auto pos = vec2i(i % numx, i / numx);
auto x = tile.x + pos.x * packet_size<T>::w;
auto y = tile.y + pos.y * packet_size<T>::h;
recti xpixel(x, y, packet_size<T>::w - 1, packet_size<T>::h - 1);
if ( !overlapping(clip_rect, xpixel) )
{
continue;
}
call_sample_pixel(
typename detail::sched_params_has_intersector<SP>::type(),
kernel,
sparams,
samp,
frame_num,
x,
y,
sparams.rt.width(),
sparams.rt.height(),
vector<3, T>(eye),
vector<3, T>(cam_u),
vector<3, T>(cam_v),
vector<3, T>(cam_w)
);
}
};
}
//-------------------------------------------------------------------------------------------------
// tiled_sched implementation
//
template <typename R>
tiled_sched<R>::tiled_sched(unsigned num_threads)
: impl_(new impl())
{
impl_->init_threads(num_threads);
}
template <typename R>
tiled_sched<R>::~tiled_sched()
{
impl_->destroy_threads();
}
template <typename R>
template <typename K, typename SP>
void tiled_sched<R>::frame(K kernel, SP sched_params, unsigned frame_num)
{
sched_params.rt.begin_frame();
impl_->init_render_func(
kernel,
sched_params,
frame_num,
typename detail::sched_params_has_view_matrix<SP>::type()
);
auto numtilesx = div_up(impl_->width, detail::tile_width);
auto numtilesy = div_up(impl_->height, detail::tile_height);
auto& sparams = impl_->sync_params;
sparams.tile_idx_counter = 0;
sparams.tile_fin_counter = 0;
sparams.tile_num = numtilesx * numtilesy;
// render frame
sparams.threads_start.notify_all();
sparams.threads_ready.wait();
sched_params.rt.end_frame();
}
template <typename R>
void tiled_sched<R>::set_num_threads(unsigned num_threads)
{
if ( get_num_threads() == num_threads )
{
return;
}
impl_->destroy_threads();
impl_->init_threads(num_threads);
}
template <typename R>
unsigned tiled_sched<R>::get_num_threads() const
{
return static_cast<unsigned>( impl_->threads.size() );
}
} // visionaray
<commit_msg>Perfect forwarding<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <atomic>
#include <cassert>
#include <condition_variable>
#include <functional>
#include <thread>
#include <utility>
#include <visionaray/math/math.h>
#include <visionaray/random_sampler.h>
#include "macros.h"
#include "sched_common.h"
#include "semaphore.h"
namespace visionaray
{
namespace detail
{
static const int tile_width = 16;
static const int tile_height = 16;
struct sync_params
{
sync_params()
: render_loop_exit(false)
{
}
std::mutex mutex;
std::condition_variable threads_start;
visionaray::semaphore threads_ready;
std::atomic<long> tile_idx_counter;
std::atomic<long> tile_fin_counter;
std::atomic<long> tile_num;
std::atomic<bool> render_loop_exit;
};
} // detail
//-------------------------------------------------------------------------------------------------
// Private implementation
//
template <typename R>
struct tiled_sched<R>::impl
{
// TODO: any sampler
typedef std::function<void(recti const&, random_sampler<typename R::scalar_type>&)> render_tile_func;
void init_threads(unsigned num_threads);
void destroy_threads();
void render_loop();
template <typename K, typename SP>
void init_render_func(K kernel, SP sparams, unsigned frame_num, std::true_type /* has matrix */);
template <typename K, typename SP>
void init_render_func(K kernel, SP sparams, unsigned frame_num, std::false_type /* has matrix */);
template <typename K, typename SP, typename Sampler, typename ...Args>
void call_sample_pixel(
std::false_type /* has intersector */,
K kernel,
SP sparams,
Sampler& samp,
unsigned frame_num,
Args&&... args
)
{
auto r = detail::make_primary_rays(
R{},
typename SP::pixel_sampler_type{},
samp,
std::forward<Args>(args)...
);
sample_pixel(
kernel,
typename SP::pixel_sampler_type(),
r,
samp,
frame_num,
sparams.rt.ref(),
std::forward<Args>(args)...
);
}
template <typename K, typename SP, typename Sampler, typename ...Args>
void call_sample_pixel(
std::true_type /* has intersector */,
K kernel,
SP sparams,
Sampler& samp,
unsigned frame_num,
Args&&... args
)
{
auto r = detail::make_primary_rays(
R{},
typename SP::pixel_sampler_type{},
samp,
std::forward<Args>(args)...
);
sample_pixel(
detail::have_intersector_tag(),
sparams.intersector,
kernel,
typename SP::pixel_sampler_type(),
r,
samp,
frame_num,
sparams.rt.ref(),
std::forward<Args>(args)...
);
}
std::vector<std::thread> threads;
detail::sync_params sync_params;
int width;
int height;
recti scissor_box;
render_tile_func render_tile;
};
template <typename R>
void tiled_sched<R>::impl::init_threads(unsigned num_threads)
{
for (unsigned i = 0; i < num_threads; ++i)
{
threads.emplace_back([this](){ render_loop(); });
}
}
template <typename R>
void tiled_sched<R>::impl::destroy_threads()
{
if (threads.size() == 0)
{
return;
}
sync_params.render_loop_exit = true;
sync_params.threads_start.notify_all();
for (auto& t : threads)
{
if (t.joinable())
{
t.join();
}
}
sync_params.render_loop_exit = false;
threads.clear();
}
//-------------------------------------------------------------------------------------------------
// Main render loop
//
template <typename R>
void tiled_sched<R>::impl::render_loop()
{
for (;;)
{
{
std::unique_lock<std::mutex> l( sync_params.mutex );
sync_params.threads_start.wait(l);
}
// case event.exit:
if (sync_params.render_loop_exit)
{
break;
}
// case event.render:
random_sampler<typename R::scalar_type> samp(detail::tic());
for (;;)
{
auto tile_idx = sync_params.tile_idx_counter.fetch_add(1);
if (tile_idx >= sync_params.tile_num)
{
break;
}
auto tilew = detail::tile_width;
auto tileh = detail::tile_height;
auto numtilesx = div_up( width, tilew );
recti tile(
(tile_idx % numtilesx) * tilew,
(tile_idx / numtilesx) * tileh,
tilew,
tileh
);
render_tile(tile, samp);
auto num_tiles_fin = sync_params.tile_fin_counter.fetch_add(1);
if (num_tiles_fin >= sync_params.tile_num - 1)
{
assert(num_tiles_fin == sync_params.tile_num - 1);
sync_params.threads_ready.notify();
break;
}
}
}
}
template <typename R>
template <typename K, typename SP>
void tiled_sched<R>::impl::init_render_func(K kernel, SP sparams, unsigned frame_num, std::true_type)
{
// overload for two matrices
using T = typename R::scalar_type;
using matrix_type = matrix<4, 4, T>;
width = sparams.rt.width();
height = sparams.rt.height();
scissor_box = sparams.scissor_box;
auto view_matrix = matrix_type( sparams.view_matrix );
auto proj_matrix = matrix_type( sparams.proj_matrix );
auto inv_view_matrix = matrix_type( inverse(sparams.view_matrix) );
auto inv_proj_matrix = matrix_type( inverse(sparams.proj_matrix) );
recti clip_rect(scissor_box.x, scissor_box.y, scissor_box.w - 1, scissor_box.h - 1);
render_tile = [=](recti const& tile, random_sampler<T>& samp)
{
using namespace detail;
unsigned numx = tile_width / packet_size<T>::w;
unsigned numy = tile_height / packet_size<T>::h;
for (unsigned i = 0; i < numx * numy; ++i)
{
auto pos = vec2i(i % numx, i / numx);
auto x = tile.x + pos.x * packet_size<T>::w;
auto y = tile.y + pos.y * packet_size<T>::h;
recti xpixel(x, y, packet_size<T>::w - 1, packet_size<T>::h - 1);
if ( !overlapping(clip_rect, xpixel) )
{
continue;
}
call_sample_pixel(
typename detail::sched_params_has_intersector<SP>::type(),
kernel,
sparams,
samp,
frame_num,
x,
y,
sparams.rt.width(),
sparams.rt.height(),
view_matrix,
inv_view_matrix,
proj_matrix,
inv_proj_matrix
);
}
};
}
template <typename R>
template <typename K, typename SP>
void tiled_sched<R>::impl::init_render_func(K kernel, SP sparams, unsigned frame_num, std::false_type)
{
// overload for pinhole cam
using T = typename R::scalar_type;
width = sparams.rt.width();
height = sparams.rt.height();
scissor_box = sparams.scissor_box;
recti clip_rect(scissor_box.x, scissor_box.y, scissor_box.w - 1, scissor_box.h - 1);
// front, side, and up vectors form an orthonormal basis
auto f = normalize( sparams.cam.eye() - sparams.cam.center() );
auto s = normalize( cross(sparams.cam.up(), f) );
auto u = cross(f, s);
vec3 eye = sparams.cam.eye();
vec3 cam_u = s * tan(sparams.cam.fovy() / 2.0f) * sparams.cam.aspect();
vec3 cam_v = u * tan(sparams.cam.fovy() / 2.0f);
vec3 cam_w = -f;
render_tile = [=](recti const& tile, random_sampler<T>& samp)
{
using namespace detail;
unsigned numx = tile_width / packet_size<T>::w;
unsigned numy = tile_height / packet_size<T>::h;
for (unsigned i = 0; i < numx * numy; ++i)
{
auto pos = vec2i(i % numx, i / numx);
auto x = tile.x + pos.x * packet_size<T>::w;
auto y = tile.y + pos.y * packet_size<T>::h;
recti xpixel(x, y, packet_size<T>::w - 1, packet_size<T>::h - 1);
if ( !overlapping(clip_rect, xpixel) )
{
continue;
}
call_sample_pixel(
typename detail::sched_params_has_intersector<SP>::type(),
kernel,
sparams,
samp,
frame_num,
x,
y,
sparams.rt.width(),
sparams.rt.height(),
vector<3, T>(eye),
vector<3, T>(cam_u),
vector<3, T>(cam_v),
vector<3, T>(cam_w)
);
}
};
}
//-------------------------------------------------------------------------------------------------
// tiled_sched implementation
//
template <typename R>
tiled_sched<R>::tiled_sched(unsigned num_threads)
: impl_(new impl())
{
impl_->init_threads(num_threads);
}
template <typename R>
tiled_sched<R>::~tiled_sched()
{
impl_->destroy_threads();
}
template <typename R>
template <typename K, typename SP>
void tiled_sched<R>::frame(K kernel, SP sched_params, unsigned frame_num)
{
sched_params.rt.begin_frame();
impl_->init_render_func(
kernel,
sched_params,
frame_num,
typename detail::sched_params_has_view_matrix<SP>::type()
);
auto numtilesx = div_up(impl_->width, detail::tile_width);
auto numtilesy = div_up(impl_->height, detail::tile_height);
auto& sparams = impl_->sync_params;
sparams.tile_idx_counter = 0;
sparams.tile_fin_counter = 0;
sparams.tile_num = numtilesx * numtilesy;
// render frame
sparams.threads_start.notify_all();
sparams.threads_ready.wait();
sched_params.rt.end_frame();
}
template <typename R>
void tiled_sched<R>::set_num_threads(unsigned num_threads)
{
if ( get_num_threads() == num_threads )
{
return;
}
impl_->destroy_threads();
impl_->init_threads(num_threads);
}
template <typename R>
unsigned tiled_sched<R>::get_num_threads() const
{
return static_cast<unsigned>( impl_->threads.size() );
}
} // visionaray
<|endoftext|> |
<commit_before>#include "../../base/SRC_FIRST.hpp"
#include "feature_routine.hpp"
#include "../../platform/platform.hpp"
#include "../../coding/file_writer.hpp"
void WriteToFile(string const & fName, vector<char> const & buffer)
{
FileWriter writer(fName);
if (!buffer.empty())
writer.Write(&buffer[0], buffer.size());
}
void FeatureBuilder2Feature(FeatureBuilderGeomRef const & fb, FeatureGeomRef & f)
{
string const datFile = GetPlatform().WritableDir() + "indexer_tests_tmp.dat";
FeatureBuilderGeomRef::buffers_holder_t buffers;
buffers.m_lineOffset = buffers.m_trgOffset = 0;
fb.Serialize(buffers);
WriteToFile(datFile + ".geom", buffers.m_buffers[1]);
WriteToFile(datFile + ".trg", buffers.m_buffers[2]);
static FeatureGeomRef::read_source_t g_source(datFile);
g_source.m_data.swap(buffers.m_buffers[0]);
f.Deserialize(g_source);
}
void Feature2FeatureBuilder(FeatureGeomRef const & f, FeatureBuilderGeomRef & fb)
{
f.InitFeatureBuilder(fb);
}
void FeatureBuilder2Feature(FeatureBuilderGeom const & fb, FeatureGeom & f)
{
FeatureBuilderGeom::buffers_holder_t buffers;
fb.Serialize(buffers);
FeatureGeom::read_source_t source;
source.m_data.swap(buffers);
f.Deserialize(source);
}
void Feature2FeatureBuilder(FeatureGeom const & f, FeatureBuilderGeom & fb)
{
f.InitFeatureBuilder(fb);
}
<commit_msg>Write temporary test files into current directory (not data directory).<commit_after>#include "../../base/SRC_FIRST.hpp"
#include "feature_routine.hpp"
#include "../../coding/file_writer.hpp"
void WriteToFile(string const & fName, vector<char> const & buffer)
{
FileWriter writer(fName);
if (!buffer.empty())
writer.Write(&buffer[0], buffer.size());
}
void FeatureBuilder2Feature(FeatureBuilderGeomRef const & fb, FeatureGeomRef & f)
{
string const datFile = "indexer_tests_tmp.dat";
FeatureBuilderGeomRef::buffers_holder_t buffers;
buffers.m_lineOffset = buffers.m_trgOffset = 0;
fb.Serialize(buffers);
WriteToFile(datFile + ".geom", buffers.m_buffers[1]);
WriteToFile(datFile + ".trg", buffers.m_buffers[2]);
static FeatureGeomRef::read_source_t g_source(datFile);
g_source.m_data.swap(buffers.m_buffers[0]);
f.Deserialize(g_source);
}
void Feature2FeatureBuilder(FeatureGeomRef const & f, FeatureBuilderGeomRef & fb)
{
f.InitFeatureBuilder(fb);
}
void FeatureBuilder2Feature(FeatureBuilderGeom const & fb, FeatureGeom & f)
{
FeatureBuilderGeom::buffers_holder_t buffers;
fb.Serialize(buffers);
FeatureGeom::read_source_t source;
source.m_data.swap(buffers);
f.Deserialize(source);
}
void Feature2FeatureBuilder(FeatureGeom const & f, FeatureBuilderGeom & fb)
{
f.InitFeatureBuilder(fb);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "pqrs/xml_compiler.hpp"
namespace pqrs {
xml_compiler::symbol_map::symbol_map(void) {
clear();
}
void xml_compiler::symbol_map::clear(void) {
symbol_map_.clear();
symbol_map_["ConfigIndex::VK__AUTOINDEX__BEGIN__"] = 0;
map_for_get_name_.clear();
}
void xml_compiler::symbol_map::dump(void) const {
for (const auto& it : symbol_map_) {
std::cout << it.first << " " << it.second << std::endl;
}
}
uint32_t
xml_compiler::symbol_map::get(const std::string& name) const {
auto v = get_optional(name);
if (!v) {
throw xml_compiler_runtime_error("Unknown symbol:\n\n" + name);
}
return *v;
}
uint32_t
xml_compiler::symbol_map::get(const std::string& type, const std::string& name) const {
return get(type + "::" + name);
}
boost::optional<uint32_t>
xml_compiler::symbol_map::get_optional(const std::string& name) const {
auto it = symbol_map_.find(name);
if (it == symbol_map_.end()) {
// XXX::RawValue::YYY does not appear frequently.
// Therefore, we don't check "XXX::RawValue::" prefix at first in order to improve performance.
// Treat XXX::RawValue::XXX at here.
auto found = name.find("::RawValue::");
if (found != std::string::npos) {
return pqrs::string::to_uint32_t(name.c_str() + found + strlen("::RawValue::"));
}
return boost::none;
}
return it->second;
}
boost::optional<uint32_t>
xml_compiler::symbol_map::get_optional(const std::string& type, const std::string& name) const {
return get_optional(type + "::" + name);
}
uint32_t
xml_compiler::symbol_map::add(const std::string& type, const std::string& name, uint32_t value) {
assert(!type.empty());
assert(!name.empty());
// register value if the definition does not exists.
auto n = type + "::" + name;
symbol_map_.emplace(n, value);
map_for_get_name_.emplace(type + "::" + boost::lexical_cast<std::string>(value), n);
return value;
}
uint32_t
xml_compiler::symbol_map::add(const std::string& type, const std::string& name) {
auto n = type + "::VK__AUTOINDEX__BEGIN__";
auto v = get_optional(n);
assert(v);
assert(*v != std::numeric_limits<uint32_t>::max());
symbol_map_[n] = *v + 1;
return add(type, name, *v);
}
boost::optional<const std::string&>
xml_compiler::symbol_map::get_name(const std::string& type, uint32_t value) const {
auto it = map_for_get_name_.find(type + "::" + boost::lexical_cast<std::string>(value));
if (it == map_for_get_name_.end()) {
return boost::none;
}
return it->second;
}
// ============================================================
void xml_compiler::symbol_map_loader::traverse(const extracted_ptree& pt) const {
for (const auto& it : pt) {
if (it.get_tag_name() != "symbol_map") {
if (!it.children_empty()) {
traverse(it.children_extracted_ptree());
}
} else {
std::vector<boost::optional<std::string>> vector;
const char* attrs[] = {
"<xmlattr>.type",
"<xmlattr>.name",
"<xmlattr>.value",
};
for (const auto& attr : attrs) {
const char* attrname = attr + strlen("<xmlattr>.");
auto v = it.get_optional(attr);
if (!v) {
xml_compiler_.error_information_.set(std::string("No '") + attrname + "' Attribute within <symbol_map>.");
break;
}
std::string value = pqrs::string::remove_whitespaces_copy(*v);
if (value.empty()) {
xml_compiler_.error_information_.set(std::string("Empty '") + attrname + "' Attribute within <symbol_map>.");
continue;
}
vector.push_back(value);
}
// An error has occured when vector.size != attrs.size.
if (vector.size() != sizeof(attrs) / sizeof(attrs[0])) {
continue;
}
auto value = pqrs::string::to_uint32_t(vector[2]);
if (!value) {
xml_compiler_.error_information_.set(boost::format("Invalid 'value' Attribute within <symbol_map>:\n"
"\n"
"<symbol_map type=\"%1%\" name=\"%2%\" value=\"%3%\" />") %
*(vector[0]) % *(vector[1]) % *(vector[2]));
continue;
}
symbol_map_.add(*(vector[0]), *(vector[1]), *value);
}
}
}
}
<commit_msg>remove VK__AUTOINDEX__BEGIN__ from map_for_get_name_<commit_after>#include <iostream>
#include "pqrs/xml_compiler.hpp"
namespace pqrs {
xml_compiler::symbol_map::symbol_map(void) {
clear();
}
void xml_compiler::symbol_map::clear(void) {
symbol_map_.clear();
symbol_map_["ConfigIndex::VK__AUTOINDEX__BEGIN__"] = 0;
map_for_get_name_.clear();
}
void xml_compiler::symbol_map::dump(void) const {
for (const auto& it : symbol_map_) {
std::cout << it.first << " " << it.second << std::endl;
}
}
uint32_t
xml_compiler::symbol_map::get(const std::string& name) const {
auto v = get_optional(name);
if (!v) {
throw xml_compiler_runtime_error("Unknown symbol:\n\n" + name);
}
return *v;
}
uint32_t
xml_compiler::symbol_map::get(const std::string& type, const std::string& name) const {
return get(type + "::" + name);
}
boost::optional<uint32_t>
xml_compiler::symbol_map::get_optional(const std::string& name) const {
auto it = symbol_map_.find(name);
if (it == symbol_map_.end()) {
// XXX::RawValue::YYY does not appear frequently.
// Therefore, we don't check "XXX::RawValue::" prefix at first in order to improve performance.
// Treat XXX::RawValue::XXX at here.
auto found = name.find("::RawValue::");
if (found != std::string::npos) {
return pqrs::string::to_uint32_t(name.c_str() + found + strlen("::RawValue::"));
}
return boost::none;
}
return it->second;
}
boost::optional<uint32_t>
xml_compiler::symbol_map::get_optional(const std::string& type, const std::string& name) const {
return get_optional(type + "::" + name);
}
uint32_t
xml_compiler::symbol_map::add(const std::string& type, const std::string& name, uint32_t value) {
assert(!type.empty());
assert(!name.empty());
// register value if the definition does not exists.
auto n = type + "::" + name;
symbol_map_.emplace(n, value);
if (name != "VK__AUTOINDEX__BEGIN__") {
map_for_get_name_.emplace(type + "::" + boost::lexical_cast<std::string>(value), n);
}
return value;
}
uint32_t
xml_compiler::symbol_map::add(const std::string& type, const std::string& name) {
auto n = type + "::VK__AUTOINDEX__BEGIN__";
auto v = get_optional(n);
assert(v);
assert(*v != std::numeric_limits<uint32_t>::max());
symbol_map_[n] = *v + 1;
return add(type, name, *v);
}
boost::optional<const std::string&>
xml_compiler::symbol_map::get_name(const std::string& type, uint32_t value) const {
auto it = map_for_get_name_.find(type + "::" + boost::lexical_cast<std::string>(value));
if (it == map_for_get_name_.end()) {
return boost::none;
}
return it->second;
}
// ============================================================
void xml_compiler::symbol_map_loader::traverse(const extracted_ptree& pt) const {
for (const auto& it : pt) {
if (it.get_tag_name() != "symbol_map") {
if (!it.children_empty()) {
traverse(it.children_extracted_ptree());
}
} else {
std::vector<boost::optional<std::string>> vector;
const char* attrs[] = {
"<xmlattr>.type",
"<xmlattr>.name",
"<xmlattr>.value",
};
for (const auto& attr : attrs) {
const char* attrname = attr + strlen("<xmlattr>.");
auto v = it.get_optional(attr);
if (!v) {
xml_compiler_.error_information_.set(std::string("No '") + attrname + "' Attribute within <symbol_map>.");
break;
}
std::string value = pqrs::string::remove_whitespaces_copy(*v);
if (value.empty()) {
xml_compiler_.error_information_.set(std::string("Empty '") + attrname + "' Attribute within <symbol_map>.");
continue;
}
vector.push_back(value);
}
// An error has occured when vector.size != attrs.size.
if (vector.size() != sizeof(attrs) / sizeof(attrs[0])) {
continue;
}
auto value = pqrs::string::to_uint32_t(vector[2]);
if (!value) {
xml_compiler_.error_information_.set(boost::format("Invalid 'value' Attribute within <symbol_map>:\n"
"\n"
"<symbol_map type=\"%1%\" name=\"%2%\" value=\"%3%\" />") %
*(vector[0]) % *(vector[1]) % *(vector[2]));
continue;
}
symbol_map_.add(*(vector[0]), *(vector[1]), *value);
}
}
}
}
<|endoftext|> |
<commit_before>/* mbed Microcontroller Library
* Copyright (c) 2015 ARM Limited
*
* 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 <stdio.h>
#include "TestHarness.h"
#include "mbed.h"
/* EEPROM 24LC256 Test Unit, to test I2C asynchronous communication.
*/
#if !DEVICE_I2C || !DEVICE_I2C_ASYNCH
#error i2c_master_eeprom_asynch requires asynch I2C
#endif
#if defined(TARGET_K64F)
#define TEST_SDA_PIN PTE25
#define TEST_SCL_PIN PTE24
#elif defined(TARGET_EFM32LG_STK3600) || defined(TARGET_EFM32GG_STK3700) || defined(TARGET_EFM32WG_STK3800)
#define TEST_SDA_PIN PD6
#define TEST_SCL_PIN PD7
#elif defined(TARGET_EFM32ZG_STK3200)
#define TEST_SDA_PIN PE12
#define TEST_SCL_PIN PE13
#elif defined(TARGET_EFM32HG_STK3400)
#define TEST_SDA_PIN PD6
#define TEST_SCL_PIN PD7
#elif defined(TARGET_RZ_A1H)
#define TEST_MOSI_PIN P10_14
#define TEST_MISO_PIN P10_15
#define TEST_SCLK_PIN P10_12
#define TEST_CS_PIN P10_13
#elif defined(TARGET_RZ_A1H)
#define TEST_SDA_PIN P1_3
#define TEST_SCL_PIN P1_2
void sleep()
{
}
#else
#error Target not supported
#endif
#define PATTERN_MASK 0x66, ~0x66, 0x00, 0xFF, 0xA5, 0x5A, 0xF0, 0x0F
volatile int why;
volatile bool complete;
void cbdone(int event) {
complete = true;
why = event;
}
const unsigned char pattern[] = { PATTERN_MASK };
TEST_GROUP(I2C_Master_EEPROM_Asynchronous)
{
I2C *obj;
const int eeprom_address = 0xA0;
event_callback_t callback;
void setup() {
obj = new I2C(TEST_SDA_PIN, TEST_SCL_PIN);
obj->frequency(400000);
complete = false;
why = 0;
callback.attach(cbdone);
}
void teardown() {
delete obj;
obj = NULL;
}
};
TEST(I2C_Master_EEPROM_Asynchronous, tx_rx_one_byte_separate_transactions)
{
int rc;
char data[] = { 0, 0, 0x66};
rc = obj->transfer(eeprom_address, data, sizeof(data), NULL, 0, callback, I2C_EVENT_ALL, false);
CHECK_EQUAL(0, rc);
while (!complete) {
sleep();
}
CHECK_EQUAL(why, I2C_EVENT_TRANSFER_COMPLETE);
// wait until slave is ready
do {
complete = 0;
why = 0;
obj->transfer(eeprom_address, NULL, 0, NULL, 0, callback, I2C_EVENT_ALL, false);
while (!complete) {
sleep();
}
} while (why != I2C_EVENT_TRANSFER_COMPLETE);
// write the address for reading (0,0) then start reading data
data[0] = 0;
data[1] = 0;
data[2] = 0;
why = 0;
complete = 0;
obj->transfer(eeprom_address, data, 2, NULL, 0, callback, I2C_EVENT_ALL, true);
while (!complete) {
sleep();
}
CHECK_EQUAL(why, I2C_EVENT_TRANSFER_COMPLETE);
data[0] = 0;
data[1] = 0;
data[2] = 0;
why = 0;
complete = 0;
rc = obj->transfer(eeprom_address, NULL, 0, data, 1, callback, I2C_EVENT_ALL, false);
CHECK_EQUAL(0, rc);
while (!complete) {
sleep();
}
CHECK_EQUAL(why, I2C_EVENT_TRANSFER_COMPLETE);
CHECK_EQUAL(data[0], 0x66);
}
TEST(I2C_Master_EEPROM_Asynchronous, tx_rx_one_byte_one_transactions)
{
int rc;
char send_data[] = { 0, 0, 0x66};
rc = obj->transfer(eeprom_address, send_data, sizeof(send_data), NULL, 0, callback, I2C_EVENT_ALL, false);
CHECK_EQUAL(0, rc)
while (!complete) {
sleep();
}
CHECK_EQUAL(why, I2C_EVENT_TRANSFER_COMPLETE);
// wait until slave is ready
do {
complete = 0;
why = 0;
obj->transfer(eeprom_address, NULL, 0, NULL, 0, callback, I2C_EVENT_ALL, false);
while (!complete) {
sleep();
}
} while (why != I2C_EVENT_TRANSFER_COMPLETE);
send_data[0] = 0;
send_data[1] = 0;
send_data[2] = 0;
char receive_data[1] = {0};
why = 0;
complete = 0;
rc = obj->transfer(eeprom_address, send_data, 2, receive_data, 1, callback, I2C_EVENT_ALL, false);
CHECK_EQUAL(0, rc);
while (!complete) {
sleep();
}
CHECK_EQUAL(why, I2C_EVENT_TRANSFER_COMPLETE);
CHECK_EQUAL(receive_data[0], 0x66);
}
TEST(I2C_Master_EEPROM_Asynchronous, tx_rx_pattern)
{
int rc;
char data[] = { 0, 0, PATTERN_MASK};
// write 8 bytes to 0x0, then read them
rc = obj->transfer(eeprom_address, data, sizeof(data), NULL, 0, callback, I2C_EVENT_ALL, false);
CHECK_EQUAL(0, rc);
while (!complete) {
sleep();
}
CHECK_EQUAL(why, I2C_EVENT_TRANSFER_COMPLETE);
// wait until slave is ready
do {
complete = 0;
why = 0;
obj->transfer(eeprom_address, NULL, 0, NULL, 0, callback, I2C_EVENT_ALL, false);
while (!complete) {
sleep();
}
} while (why != I2C_EVENT_TRANSFER_COMPLETE);
complete = 0;
why = 0;
char rec_data[8] = {0};
rc = obj->transfer(eeprom_address, rec_data, 2, NULL, 0, callback, I2C_EVENT_ALL, true);
CHECK_EQUAL(0, rc);
while (!complete) {
sleep();
}
CHECK_EQUAL(why, I2C_EVENT_TRANSFER_COMPLETE);
complete = 0;
why = 0;
rc = obj->transfer(eeprom_address, NULL, 0, rec_data, 8, callback, I2C_EVENT_ALL, false);
CHECK_EQUAL(0, rc);
while (!complete) {
sleep();
}
CHECK_EQUAL(why, I2C_EVENT_TRANSFER_COMPLETE);
// received buffer match with pattern
rc = memcmp(pattern, rec_data, sizeof(rec_data));
CHECK_EQUAL(0, rc);
}
<commit_msg>Add support for Renesas RZ/A1H<commit_after>/* mbed Microcontroller Library
* Copyright (c) 2015 ARM Limited
*
* 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 <stdio.h>
#include "TestHarness.h"
#include "mbed.h"
/* EEPROM 24LC256 Test Unit, to test I2C asynchronous communication.
*/
#if !DEVICE_I2C || !DEVICE_I2C_ASYNCH
#error i2c_master_eeprom_asynch requires asynch I2C
#endif
#if defined(TARGET_K64F)
#define TEST_SDA_PIN PTE25
#define TEST_SCL_PIN PTE24
#elif defined(TARGET_EFM32LG_STK3600) || defined(TARGET_EFM32GG_STK3700) || defined(TARGET_EFM32WG_STK3800)
#define TEST_SDA_PIN PD6
#define TEST_SCL_PIN PD7
#elif defined(TARGET_EFM32ZG_STK3200)
#define TEST_SDA_PIN PE12
#define TEST_SCL_PIN PE13
#elif defined(TARGET_EFM32HG_STK3400)
#define TEST_SDA_PIN PD6
#define TEST_SCL_PIN PD7
#elif defined(TARGET_RZ_A1H)
#define TEST_SDA_PIN P1_3
#define TEST_SCL_PIN P1_2
void sleep()
{
}
#else
#error Target not supported
#endif
#define PATTERN_MASK 0x66, ~0x66, 0x00, 0xFF, 0xA5, 0x5A, 0xF0, 0x0F
volatile int why;
volatile bool complete;
void cbdone(int event) {
complete = true;
why = event;
}
const unsigned char pattern[] = { PATTERN_MASK };
TEST_GROUP(I2C_Master_EEPROM_Asynchronous)
{
I2C *obj;
const int eeprom_address = 0xA0;
event_callback_t callback;
void setup() {
obj = new I2C(TEST_SDA_PIN, TEST_SCL_PIN);
obj->frequency(400000);
complete = false;
why = 0;
callback.attach(cbdone);
}
void teardown() {
delete obj;
obj = NULL;
}
};
TEST(I2C_Master_EEPROM_Asynchronous, tx_rx_one_byte_separate_transactions)
{
int rc;
char data[] = { 0, 0, 0x66};
rc = obj->transfer(eeprom_address, data, sizeof(data), NULL, 0, callback, I2C_EVENT_ALL, false);
CHECK_EQUAL(0, rc);
while (!complete) {
sleep();
}
CHECK_EQUAL(why, I2C_EVENT_TRANSFER_COMPLETE);
// wait until slave is ready
do {
complete = 0;
why = 0;
obj->transfer(eeprom_address, NULL, 0, NULL, 0, callback, I2C_EVENT_ALL, false);
while (!complete) {
sleep();
}
} while (why != I2C_EVENT_TRANSFER_COMPLETE);
// write the address for reading (0,0) then start reading data
data[0] = 0;
data[1] = 0;
data[2] = 0;
why = 0;
complete = 0;
obj->transfer(eeprom_address, data, 2, NULL, 0, callback, I2C_EVENT_ALL, true);
while (!complete) {
sleep();
}
CHECK_EQUAL(why, I2C_EVENT_TRANSFER_COMPLETE);
data[0] = 0;
data[1] = 0;
data[2] = 0;
why = 0;
complete = 0;
rc = obj->transfer(eeprom_address, NULL, 0, data, 1, callback, I2C_EVENT_ALL, false);
CHECK_EQUAL(0, rc);
while (!complete) {
sleep();
}
CHECK_EQUAL(why, I2C_EVENT_TRANSFER_COMPLETE);
CHECK_EQUAL(data[0], 0x66);
}
TEST(I2C_Master_EEPROM_Asynchronous, tx_rx_one_byte_one_transactions)
{
int rc;
char send_data[] = { 0, 0, 0x66};
rc = obj->transfer(eeprom_address, send_data, sizeof(send_data), NULL, 0, callback, I2C_EVENT_ALL, false);
CHECK_EQUAL(0, rc)
while (!complete) {
sleep();
}
CHECK_EQUAL(why, I2C_EVENT_TRANSFER_COMPLETE);
// wait until slave is ready
do {
complete = 0;
why = 0;
obj->transfer(eeprom_address, NULL, 0, NULL, 0, callback, I2C_EVENT_ALL, false);
while (!complete) {
sleep();
}
} while (why != I2C_EVENT_TRANSFER_COMPLETE);
send_data[0] = 0;
send_data[1] = 0;
send_data[2] = 0;
char receive_data[1] = {0};
why = 0;
complete = 0;
rc = obj->transfer(eeprom_address, send_data, 2, receive_data, 1, callback, I2C_EVENT_ALL, false);
CHECK_EQUAL(0, rc);
while (!complete) {
sleep();
}
CHECK_EQUAL(why, I2C_EVENT_TRANSFER_COMPLETE);
CHECK_EQUAL(receive_data[0], 0x66);
}
TEST(I2C_Master_EEPROM_Asynchronous, tx_rx_pattern)
{
int rc;
char data[] = { 0, 0, PATTERN_MASK};
// write 8 bytes to 0x0, then read them
rc = obj->transfer(eeprom_address, data, sizeof(data), NULL, 0, callback, I2C_EVENT_ALL, false);
CHECK_EQUAL(0, rc);
while (!complete) {
sleep();
}
CHECK_EQUAL(why, I2C_EVENT_TRANSFER_COMPLETE);
// wait until slave is ready
do {
complete = 0;
why = 0;
obj->transfer(eeprom_address, NULL, 0, NULL, 0, callback, I2C_EVENT_ALL, false);
while (!complete) {
sleep();
}
} while (why != I2C_EVENT_TRANSFER_COMPLETE);
complete = 0;
why = 0;
char rec_data[8] = {0};
rc = obj->transfer(eeprom_address, rec_data, 2, NULL, 0, callback, I2C_EVENT_ALL, true);
CHECK_EQUAL(0, rc);
while (!complete) {
sleep();
}
CHECK_EQUAL(why, I2C_EVENT_TRANSFER_COMPLETE);
complete = 0;
why = 0;
rc = obj->transfer(eeprom_address, NULL, 0, rec_data, 8, callback, I2C_EVENT_ALL, false);
CHECK_EQUAL(0, rc);
while (!complete) {
sleep();
}
CHECK_EQUAL(why, I2C_EVENT_TRANSFER_COMPLETE);
// received buffer match with pattern
rc = memcmp(pattern, rec_data, sizeof(rec_data));
CHECK_EQUAL(0, rc);
}
<|endoftext|> |
<commit_before>#include "./VERSION"
#include "./mcmap.h"
SETUP_LOGGER
#define SUCCESS 0
#define ERROR 1
void printHelp(char *binary) {
logger::info(
"Usage: {} <options> WORLDPATH\n\n"
" -from X Z coordinates of the block to start rendering at\n"
" -to X Z coordinates of the block to stop rendering at\n"
" -min/max VAL minimum/maximum Y index of blocks to render\n"
" -file NAME output file; default is 'output.png'\n"
" -colors NAME color file to use; default is 'colors.json'\n"
" -nw -ne -se -sw the orientation of the map\n"
" -nether render the nether\n"
" -end render the end\n"
" -dim[ension] NAME render a dimension by namespaced ID\n"
" -nowater do not render water\n"
" -nobeacons do not render beacon beams\n"
" -shading toggle shading (brightens blocks depending on "
"height)\n"
" -mb int (=3500) use the specified amount of memory (in MB)\n"
" -tile int (=1024) render terrain in tiles of the specified size\n"
" -marker X Z color draw a marker at X Z of the desired color\n"
" -padding int (=5) padding to use around the image\n"
" -h[elp] display an option summary\n"
" -v[erbose] toggle debug mode (-vv for more)\n"
" -dumpcolors dump a json with all defined colors\n",
binary);
}
int main(int argc, char **argv) {
Settings::WorldOptions options;
Colors::Palette colors;
if (argc < 2 || !parseArgs(argc, argv, &options)) {
printHelp(argv[0]);
return ERROR;
}
// Load colors from the text segment
Colors::load(&colors);
// If requested, load colors from file
if (!options.colorFile.empty())
Colors::load(options.colorFile, &colors);
if (options.mode == Settings::DUMPCOLORS) {
logger::info("{}", json(colors).dump());
return 0;
} else {
logger::info(VERSION " {}bit (" COMMENT ")\n",
8 * static_cast<int>(sizeof(size_t)));
}
// Overwrite water if asked to
// TODO expand this to other blocks
if (options.hideWater)
colors["minecraft:water"] = Colors::Block();
if (options.hideBeacons)
colors["mcmap:beacon_beam"] = Colors::Block();
return render(options, colors);
}
<commit_msg>Return 0 on success again<commit_after>#include "./VERSION"
#include "./mcmap.h"
SETUP_LOGGER
#define SUCCESS 0
#define ERROR 1
void printHelp(char *binary) {
logger::info(
"Usage: {} <options> WORLDPATH\n\n"
" -from X Z coordinates of the block to start rendering at\n"
" -to X Z coordinates of the block to stop rendering at\n"
" -min/max VAL minimum/maximum Y index of blocks to render\n"
" -file NAME output file; default is 'output.png'\n"
" -colors NAME color file to use; default is 'colors.json'\n"
" -nw -ne -se -sw the orientation of the map\n"
" -nether render the nether\n"
" -end render the end\n"
" -dim[ension] NAME render a dimension by namespaced ID\n"
" -nowater do not render water\n"
" -nobeacons do not render beacon beams\n"
" -shading toggle shading (brightens blocks depending on "
"height)\n"
" -mb int (=3500) use the specified amount of memory (in MB)\n"
" -tile int (=1024) render terrain in tiles of the specified size\n"
" -marker X Z color draw a marker at X Z of the desired color\n"
" -padding int (=5) padding to use around the image\n"
" -h[elp] display an option summary\n"
" -v[erbose] toggle debug mode (-vv for more)\n"
" -dumpcolors dump a json with all defined colors\n",
binary);
}
int main(int argc, char **argv) {
Settings::WorldOptions options;
Colors::Palette colors;
if (argc < 2 || !parseArgs(argc, argv, &options)) {
printHelp(argv[0]);
return ERROR;
}
// Load colors from the text segment
Colors::load(&colors);
// If requested, load colors from file
if (!options.colorFile.empty())
Colors::load(options.colorFile, &colors);
if (options.mode == Settings::DUMPCOLORS) {
logger::info("{}", json(colors).dump());
return 0;
} else {
logger::info(VERSION " {}bit (" COMMENT ")\n",
8 * static_cast<int>(sizeof(size_t)));
}
// Overwrite water if asked to
// TODO expand this to other blocks
if (options.hideWater)
colors["minecraft:water"] = Colors::Block();
if (options.hideBeacons)
colors["mcmap:beacon_beam"] = Colors::Block();
if (!render(options, colors)) {
logger::error("Error rendering terrain.\n");
return ERROR;
}
return SUCCESS;
}
<|endoftext|> |
<commit_before>#include "convertingMethods.h"
using namespace editorPluginTestingFramework;
using namespace qReal;
QStringList ConvertingMethods::convertQListExplosionDataIntoStringList(const QList<EditorInterface::ExplosionData> &explDataList)
{
QStringList resultList;
for (const EditorInterface::ExplosionData &element : explDataList) {
resultList.append(element.targetElement);
}
return resultList;
}
QStringList ConvertingMethods::convertingQPairListIntoStringList(const QList<QPair<QString, QString>> &qPairList)
{
QStringList resultList;
for (const auto &element : qPairList ) {
resultList.append(element.first);
resultList.append(element.second);
}
return resultList;
}
QStringList ConvertingMethods::convertIdListIntoStringList(const IdList &idList)
{
QStringList resultList;
for (const Id &id : idList) {
resultList += id.toString();
}
return resultList;
}
QStringList ConvertingMethods::convertStringIntoStringList(const QString &string)
{
QStringList result;
result.append(string);
return result;
}
QStringList ConvertingMethods::convertBoolIntoStringList(const bool &boolValue)
{
QString stringRepresentation = (boolValue) ? "true" : "false";
return convertStringIntoStringList(stringRepresentation);
}
QStringList ConvertingMethods::convertIdIntoStringList(const Id &id)
{
QString stringRepresentation = id.toString();
return convertStringIntoStringList(stringRepresentation);
}
QStringList ConvertingMethods::convertIntIntoStringList(int const &integer)
{
QString stringRepresentation = (integer == 1) ? "1" : "0";
return convertStringIntoStringList(stringRepresentation);
}
QStringList ConvertingMethods::convertExplosionListIntoStringList(const QList<Explosion> &explosionList)
{
QStringList result;
for (const Explosion &explosion : explosionList) {
const QString &target = explosion.target().toString();
result.append(target);
}
return result;
}
QString ConvertingMethods::transformateOutput(
const QStringList &output
, const Id &id
, const QString &name
)
{
QString result;
if (name == "") {
result.append(id.toString() + "-");
} else {
result.append(name + "-");
}
for (const auto &outputElement : output) {
result.append(outputElement + ",");
}
return result;
}
QSet<QString> ConvertingMethods::resultToCompare(const QString &method)
{
QStringList methodOutput = method.split("|");
QStringList result;
for (const QString &string : methodOutput) {
QString output = string.split("-").last();
QStringList outputToList = output.split(",");
result.append(outputToList);
}
QSet<QString> methodParsed = result.toSet();
return methodParsed;
}
<commit_msg>forgotten corrections<commit_after>#include "convertingMethods.h"
using namespace editorPluginTestingFramework;
using namespace qReal;
QStringList ConvertingMethods::convertQListExplosionDataIntoStringList(const QList<EditorInterface::ExplosionData> &explDataList)
{
QStringList resultList;
for (const EditorInterface::ExplosionData &element : explDataList) {
resultList.append(element.targetElement);
}
return resultList;
}
QStringList ConvertingMethods::convertingQPairListIntoStringList(const QList<QPair<QString, QString>> &qPairList)
{
QStringList resultList;
for (const auto &element : qPairList ) {
resultList.append(element.first);
resultList.append(element.second);
}
return resultList;
}
QStringList ConvertingMethods::convertIdListIntoStringList(const IdList &idList)
{
QStringList resultList;
for (const Id &id : idList) {
resultList += id.toString();
}
return resultList;
}
QStringList ConvertingMethods::convertStringIntoStringList(const QString &string)
{
QStringList result;
result.append(string);
return result;
}
QStringList ConvertingMethods::convertBoolIntoStringList(const bool &boolValue)
{
QString stringRepresentation = (boolValue) ? "true" : "false";
return convertStringIntoStringList(stringRepresentation);
}
QStringList ConvertingMethods::convertIdIntoStringList(const Id &id)
{
QString stringRepresentation = id.toString();
return convertStringIntoStringList(stringRepresentation);
}
QStringList ConvertingMethods::convertIntIntoStringList(int const &integer)
{
QString stringRepresentation = (integer == 1) ? "1" : "0";
return convertStringIntoStringList(stringRepresentation);
}
QStringList ConvertingMethods::convertExplosionListIntoStringList(const QList<Explosion> &explosionList)
{
QStringList result;
for (const Explosion &explosion : explosionList) {
const QString &target = explosion.target().toString();
result.append(target);
}
return result;
}
QString ConvertingMethods::transformateOutput(
const QStringList &output
, const Id &id
, const QString &name
)
{
QString result;
if (name.isEmpty()) {
result.append(id.toString() + "-");
} else {
result.append(name + "-");
}
for (const auto &outputElement : output) {
result.append(outputElement + ",");
}
return result;
}
QSet<QString> ConvertingMethods::resultToCompare(const QString &method)
{
const QStringList methodOutput = method.split("|");
QStringList result;
for (const QString &string : methodOutput) {
QString output = string.split("-").last();
QStringList outputToList = output.split(",");
result.append(outputToList);
}
const QSet<QString> methodParsed = result.toSet();
return methodParsed;
}
<|endoftext|> |
<commit_before>#include "precompiled.h"
#include "engine/AI/AISystem.h"
namespace engine {
namespace AI {
AISystem::AISystem(scene::SceneSystem *sceneSystem)
: sceneSystem(sceneSystem)
{}
bool AISystem::init(){
LOG_INFO("AISystem init");
return true;
}
void AISystem::uninit(){
LOG_INFO("AISystem uninit");
}
void AISystem::update(){
LOG_INFO("AISystem update");
//TODO: This is still just a skeleton
}
}
}
<commit_msg>Fixing travis build ?<commit_after>#include "precompiled.h"
#include "engine/AI/AISystem.h"
namespace engine {
namespace AI {
AISystem::AISystem(scene::SceneSystem *sceneSystem)
: sceneSystem(sceneSystem)
{}
bool AISystem::init(){
LOG_INFO("AISystem init");
return true;
}
void AISystem::uninit(){
LOG_INFO("AISystem uninit");
}
void AISystem::update(){
LOG_INFO("AISystem update");
//TODO: This is still just a skeleton
sceneSystem->getActorList();
}
}
}
<|endoftext|> |
<commit_before>#ifndef ENTT_ENTITY_HANDLE_HPP
#define ENTT_ENTITY_HANDLE_HPP
#include <iterator>
#include <tuple>
#include <type_traits>
#include <utility>
#include "../core/iterator.hpp"
#include "../core/type_traits.hpp"
#include "entity.hpp"
#include "fwd.hpp"
namespace entt {
/**
* @cond TURN_OFF_DOXYGEN
* Internal details not to be documented.
*/
namespace internal {
template<typename It>
class handle_storage_iterator final {
template<typename Other>
friend class handle_storage_iterator;
using underlying_type = std::remove_reference_t<typename It::value_type::second_type>;
using entity_type = typename underlying_type::entity_type;
public:
using value_type = typename std::iterator_traits<It>::value_type;
using pointer = input_iterator_pointer<value_type>;
using reference = value_type;
using difference_type = std::ptrdiff_t;
using iterator_category = std::input_iterator_tag;
constexpr handle_storage_iterator() noexcept
: entt{null},
it{},
last{} {}
constexpr handle_storage_iterator(entity_type value, It from, It to) noexcept
: entt{value},
it{from},
last{to} {
while(it != last && !it->second.contains(entt)) { ++it; }
}
constexpr handle_storage_iterator &operator++() noexcept {
while(++it != last && !it->second.contains(entt)) {}
return *this;
}
constexpr handle_storage_iterator operator++(int) noexcept {
handle_storage_iterator orig = *this;
return ++(*this), orig;
}
[[nodiscard]] constexpr reference operator*() const noexcept {
return *it;
}
[[nodiscard]] constexpr pointer operator->() const noexcept {
return operator*();
}
template<typename ILhs, typename IRhs>
friend constexpr bool operator==(const handle_storage_iterator<ILhs> &, const handle_storage_iterator<IRhs> &) noexcept;
private:
entity_type entt;
It it;
It last;
};
template<typename ILhs, typename IRhs>
[[nodiscard]] constexpr bool operator==(const handle_storage_iterator<ILhs> &lhs, const handle_storage_iterator<IRhs> &rhs) noexcept {
return lhs.it == rhs.it;
}
template<typename ILhs, typename IRhs>
[[nodiscard]] constexpr bool operator!=(const handle_storage_iterator<ILhs> &lhs, const handle_storage_iterator<IRhs> &rhs) noexcept {
return !(lhs == rhs);
}
} // namespace internal
/**
* Internal details not to be documented.
* @endcond
*/
/**
* @brief Non-owning handle to an entity.
*
* Tiny wrapper around a registry and an entity.
*
* @tparam Registry Basic registry type.
* @tparam Scope Types to which to restrict the scope of a handle.
*/
template<typename Registry, typename... Scope>
struct basic_handle {
/*! @brief Type of registry accepted by the handle. */
using registry_type = Registry;
/*! @brief Underlying entity identifier. */
using entity_type = typename registry_type::entity_type;
/*! @brief Underlying version type. */
using version_type = typename registry_type::version_type;
/*! @brief Unsigned integer type. */
using size_type = typename registry_type::size_type;
/*! @brief Constructs an invalid handle. */
basic_handle() noexcept
: reg{},
entt{null} {}
/**
* @brief Constructs a handle from a given registry and entity.
* @param ref An instance of the registry class.
* @param value A valid identifier.
*/
basic_handle(registry_type &ref, entity_type value) noexcept
: reg{&ref},
entt{value} {}
/**
* @brief Returns an iterable object to use to _visit_ a handle.
*
* The iterable object returns a pair that contains the name and a reference
* to the current storage.<br/>
* Returned storage are those that contain the entity associated with the
* handle.
*
* @return An iterable object to use to _visit_ the handle.
*/
[[nodiscard]] auto storage() const noexcept {
auto iterable = reg->storage();
using iterator_type = internal::handle_storage_iterator<typename decltype(iterable)::iterator>;
return iterable_adaptor{iterator_type{entt, iterable.begin(), iterable.end()}, iterator_type{entt, iterable.end(), iterable.end()}};
}
/**
* @brief Constructs a const handle from a non-const one.
* @tparam Other A valid entity type (see entt_traits for more details).
* @tparam Args Scope of the handle to construct.
* @return A const handle referring to the same registry and the same
* entity.
*/
template<typename Other, typename... Args>
operator basic_handle<Other, Args...>() const noexcept {
static_assert(std::is_same_v<Other, Registry> || std::is_same_v<std::remove_const_t<Other>, Registry>, "Invalid conversion between different handles");
static_assert((sizeof...(Scope) == 0 || ((sizeof...(Args) != 0 && sizeof...(Args) <= sizeof...(Scope)) && ... && (type_list_contains_v<type_list<Scope...>, Args>))), "Invalid conversion between different handles");
return reg ? basic_handle<Other, Args...>{*reg, entt} : basic_handle<Other, Args...>{};
}
/**
* @brief Converts a handle to its underlying entity.
* @return The contained identifier.
*/
[[nodiscard]] operator entity_type() const noexcept {
return entity();
}
/**
* @brief Checks if a handle refers to non-null registry pointer and entity.
* @return True if the handle refers to non-null registry and entity, false otherwise.
*/
[[nodiscard]] explicit operator bool() const noexcept {
return reg && reg->valid(entt);
}
/**
* @brief Checks if a handle refers to a valid entity or not.
* @return True if the handle refers to a valid entity, false otherwise.
*/
[[nodiscard]] bool valid() const {
return reg->valid(entt);
}
/**
* @brief Returns a pointer to the underlying registry, if any.
* @return A pointer to the underlying registry, if any.
*/
[[nodiscard]] registry_type *registry() const noexcept {
return reg;
}
/**
* @brief Returns the entity associated with a handle.
* @return The entity associated with the handle.
*/
[[nodiscard]] entity_type entity() const noexcept {
return entt;
}
/**
* @brief Destroys the entity associated with a handle.
* @sa basic_registry::destroy
*/
void destroy() {
reg->destroy(entt);
}
/**
* @brief Destroys the entity associated with a handle.
* @sa basic_registry::destroy
* @param version A desired version upon destruction.
*/
void destroy(const version_type version) {
reg->destroy(entt, version);
}
/**
* @brief Assigns the given component to a handle.
* @sa basic_registry::emplace
* @tparam Component Type of component to create.
* @tparam Args Types of arguments to use to construct the component.
* @param args Parameters to use to initialize the component.
* @return A reference to the newly created component.
*/
template<typename Component, typename... Args>
decltype(auto) emplace(Args &&...args) const {
static_assert(((sizeof...(Scope) == 0) || ... || std::is_same_v<Component, Scope>), "Invalid type");
return reg->template emplace<Component>(entt, std::forward<Args>(args)...);
}
/**
* @brief Assigns or replaces the given component for a handle.
* @sa basic_registry::emplace_or_replace
* @tparam Component Type of component to assign or replace.
* @tparam Args Types of arguments to use to construct the component.
* @param args Parameters to use to initialize the component.
* @return A reference to the newly created component.
*/
template<typename Component, typename... Args>
decltype(auto) emplace_or_replace(Args &&...args) const {
static_assert(((sizeof...(Scope) == 0) || ... || std::is_same_v<Component, Scope>), "Invalid type");
return reg->template emplace_or_replace<Component>(entt, std::forward<Args>(args)...);
}
/**
* @brief Patches the given component for a handle.
* @sa basic_registry::patch
* @tparam Component Type of component to patch.
* @tparam Func Types of the function objects to invoke.
* @param func Valid function objects.
* @return A reference to the patched component.
*/
template<typename Component, typename... Func>
decltype(auto) patch(Func &&...func) const {
static_assert(((sizeof...(Scope) == 0) || ... || std::is_same_v<Component, Scope>), "Invalid type");
return reg->template patch<Component>(entt, std::forward<Func>(func)...);
}
/**
* @brief Replaces the given component for a handle.
* @sa basic_registry::replace
* @tparam Component Type of component to replace.
* @tparam Args Types of arguments to use to construct the component.
* @param args Parameters to use to initialize the component.
* @return A reference to the component being replaced.
*/
template<typename Component, typename... Args>
decltype(auto) replace(Args &&...args) const {
static_assert(((sizeof...(Scope) == 0) || ... || std::is_same_v<Component, Scope>), "Invalid type");
return reg->template replace<Component>(entt, std::forward<Args>(args)...);
}
/**
* @brief Removes the given components from a handle.
* @sa basic_registry::remove
* @tparam Component Types of components to remove.
* @return The number of components actually removed.
*/
template<typename... Component>
size_type remove() const {
static_assert(sizeof...(Scope) == 0 || (type_list_contains_v<type_list<Scope...>, Component> && ...), "Invalid type");
return reg->template remove<Component...>(entt);
}
/**
* @brief Erases the given components from a handle.
* @sa basic_registry::erase
* @tparam Component Types of components to erase.
*/
template<typename... Component>
void erase() const {
static_assert(sizeof...(Scope) == 0 || (type_list_contains_v<type_list<Scope...>, Component> && ...), "Invalid type");
reg->template erase<Component...>(entt);
}
/**
* @brief Checks if a handle has all the given components.
* @sa basic_registry::all_of
* @tparam Component Components for which to perform the check.
* @return True if the handle has all the components, false otherwise.
*/
template<typename... Component>
[[nodiscard]] decltype(auto) all_of() const {
return reg->template all_of<Component...>(entt);
}
/**
* @brief Checks if a handle has at least one of the given components.
* @sa basic_registry::any_of
* @tparam Component Components for which to perform the check.
* @return True if the handle has at least one of the given components,
* false otherwise.
*/
template<typename... Component>
[[nodiscard]] decltype(auto) any_of() const {
return reg->template any_of<Component...>(entt);
}
/**
* @brief Returns references to the given components for a handle.
* @sa basic_registry::get
* @tparam Component Types of components to get.
* @return References to the components owned by the handle.
*/
template<typename... Component>
[[nodiscard]] decltype(auto) get() const {
static_assert(sizeof...(Scope) == 0 || (type_list_contains_v<type_list<Scope...>, Component> && ...), "Invalid type");
return reg->template get<Component...>(entt);
}
/**
* @brief Returns a reference to the given component for a handle.
* @sa basic_registry::get_or_emplace
* @tparam Component Type of component to get.
* @tparam Args Types of arguments to use to construct the component.
* @param args Parameters to use to initialize the component.
* @return Reference to the component owned by the handle.
*/
template<typename Component, typename... Args>
[[nodiscard]] decltype(auto) get_or_emplace(Args &&...args) const {
static_assert(((sizeof...(Scope) == 0) || ... || std::is_same_v<Component, Scope>), "Invalid type");
return reg->template get_or_emplace<Component>(entt, std::forward<Args>(args)...);
}
/**
* @brief Returns pointers to the given components for a handle.
* @sa basic_registry::try_get
* @tparam Component Types of components to get.
* @return Pointers to the components owned by the handle.
*/
template<typename... Component>
[[nodiscard]] auto try_get() const {
static_assert(sizeof...(Scope) == 0 || (type_list_contains_v<type_list<Scope...>, Component> && ...), "Invalid type");
return reg->template try_get<Component...>(entt);
}
/**
* @brief Checks if a handle has components assigned.
* @return True if the handle has no components assigned, false otherwise.
*/
[[nodiscard]] bool orphan() const {
return reg->orphan(entt);
}
private:
registry_type *reg;
entity_type entt;
};
/**
* @brief Compares two handles.
* @tparam Args Scope of the first handle.
* @tparam Other Scope of the second handle.
* @param lhs A valid handle.
* @param rhs A valid handle.
* @return True if both handles refer to the same registry and the same
* entity, false otherwise.
*/
template<typename... Args, typename... Other>
[[nodiscard]] bool operator==(const basic_handle<Args...> &lhs, const basic_handle<Other...> &rhs) noexcept {
return lhs.registry() == rhs.registry() && lhs.entity() == rhs.entity();
}
/**
* @brief Compares two handles.
* @tparam Args Scope of the first handle.
* @tparam Other Scope of the second handle.
* @param lhs A valid handle.
* @param rhs A valid handle.
* @return False if both handles refer to the same registry and the same
* entity, true otherwise.
*/
template<typename... Args, typename... Other>
[[nodiscard]] bool operator!=(const basic_handle<Args...> &lhs, const basic_handle<Other...> &rhs) noexcept {
return !(lhs == rhs);
}
} // namespace entt
#endif
<commit_msg>doc: cleanup<commit_after>#ifndef ENTT_ENTITY_HANDLE_HPP
#define ENTT_ENTITY_HANDLE_HPP
#include <iterator>
#include <tuple>
#include <type_traits>
#include <utility>
#include "../core/iterator.hpp"
#include "../core/type_traits.hpp"
#include "entity.hpp"
#include "fwd.hpp"
namespace entt {
/**
* @cond TURN_OFF_DOXYGEN
* Internal details not to be documented.
*/
namespace internal {
template<typename It>
class handle_storage_iterator final {
template<typename Other>
friend class handle_storage_iterator;
using underlying_type = std::remove_reference_t<typename It::value_type::second_type>;
using entity_type = typename underlying_type::entity_type;
public:
using value_type = typename std::iterator_traits<It>::value_type;
using pointer = input_iterator_pointer<value_type>;
using reference = value_type;
using difference_type = std::ptrdiff_t;
using iterator_category = std::input_iterator_tag;
constexpr handle_storage_iterator() noexcept
: entt{null},
it{},
last{} {}
constexpr handle_storage_iterator(entity_type value, It from, It to) noexcept
: entt{value},
it{from},
last{to} {
while(it != last && !it->second.contains(entt)) { ++it; }
}
constexpr handle_storage_iterator &operator++() noexcept {
while(++it != last && !it->second.contains(entt)) {}
return *this;
}
constexpr handle_storage_iterator operator++(int) noexcept {
handle_storage_iterator orig = *this;
return ++(*this), orig;
}
[[nodiscard]] constexpr reference operator*() const noexcept {
return *it;
}
[[nodiscard]] constexpr pointer operator->() const noexcept {
return operator*();
}
template<typename ILhs, typename IRhs>
friend constexpr bool operator==(const handle_storage_iterator<ILhs> &, const handle_storage_iterator<IRhs> &) noexcept;
private:
entity_type entt;
It it;
It last;
};
template<typename ILhs, typename IRhs>
[[nodiscard]] constexpr bool operator==(const handle_storage_iterator<ILhs> &lhs, const handle_storage_iterator<IRhs> &rhs) noexcept {
return lhs.it == rhs.it;
}
template<typename ILhs, typename IRhs>
[[nodiscard]] constexpr bool operator!=(const handle_storage_iterator<ILhs> &lhs, const handle_storage_iterator<IRhs> &rhs) noexcept {
return !(lhs == rhs);
}
} // namespace internal
/**
* Internal details not to be documented.
* @endcond
*/
/**
* @brief Non-owning handle to an entity.
*
* Tiny wrapper around a registry and an entity.
*
* @tparam Registry Basic registry type.
* @tparam Scope Types to which to restrict the scope of a handle.
*/
template<typename Registry, typename... Scope>
struct basic_handle {
/*! @brief Type of registry accepted by the handle. */
using registry_type = Registry;
/*! @brief Underlying entity identifier. */
using entity_type = typename registry_type::entity_type;
/*! @brief Underlying version type. */
using version_type = typename registry_type::version_type;
/*! @brief Unsigned integer type. */
using size_type = typename registry_type::size_type;
/*! @brief Constructs an invalid handle. */
basic_handle() noexcept
: reg{},
entt{null} {}
/**
* @brief Constructs a handle from a given registry and entity.
* @param ref An instance of the registry class.
* @param value A valid identifier.
*/
basic_handle(registry_type &ref, entity_type value) noexcept
: reg{&ref},
entt{value} {}
/**
* @brief Returns an iterable object to use to _visit_ a handle.
*
* The iterable object returns a pair that contains the name and a reference
* to the current storage.<br/>
* Returned storage are those that contain the entity associated with the
* handle.
*
* @return An iterable object to use to _visit_ the handle.
*/
[[nodiscard]] auto storage() const noexcept {
auto iterable = reg->storage();
using iterator_type = internal::handle_storage_iterator<typename decltype(iterable)::iterator>;
return iterable_adaptor{iterator_type{entt, iterable.begin(), iterable.end()}, iterator_type{entt, iterable.end(), iterable.end()}};
}
/**
* @brief Constructs a const handle from a non-const one.
* @tparam Other A valid entity type (see entt_traits for more details).
* @tparam Args Scope of the handle to construct.
* @return A const handle referring to the same registry and the same
* entity.
*/
template<typename Other, typename... Args>
operator basic_handle<Other, Args...>() const noexcept {
static_assert(std::is_same_v<Other, Registry> || std::is_same_v<std::remove_const_t<Other>, Registry>, "Invalid conversion between different handles");
static_assert((sizeof...(Scope) == 0 || ((sizeof...(Args) != 0 && sizeof...(Args) <= sizeof...(Scope)) && ... && (type_list_contains_v<type_list<Scope...>, Args>))), "Invalid conversion between different handles");
return reg ? basic_handle<Other, Args...>{*reg, entt} : basic_handle<Other, Args...>{};
}
/**
* @brief Converts a handle to its underlying entity.
* @return The contained identifier.
*/
[[nodiscard]] operator entity_type() const noexcept {
return entity();
}
/**
* @brief Checks if a handle refers to non-null registry pointer and entity.
* @return True if the handle refers to non-null registry and entity, false otherwise.
*/
[[nodiscard]] explicit operator bool() const noexcept {
return reg && reg->valid(entt);
}
/**
* @brief Checks if a handle refers to a valid entity or not.
* @return True if the handle refers to a valid entity, false otherwise.
*/
[[nodiscard]] bool valid() const {
return reg->valid(entt);
}
/**
* @brief Returns a pointer to the underlying registry, if any.
* @return A pointer to the underlying registry, if any.
*/
[[nodiscard]] registry_type *registry() const noexcept {
return reg;
}
/**
* @brief Returns the entity associated with a handle.
* @return The entity associated with the handle.
*/
[[nodiscard]] entity_type entity() const noexcept {
return entt;
}
/*! @brief Destroys the entity associated with a handle. */
void destroy() {
reg->destroy(entt);
}
/**
* @brief Destroys the entity associated with a handle.
* @param version A desired version upon destruction.
*/
void destroy(const version_type version) {
reg->destroy(entt, version);
}
/**
* @brief Assigns the given component to a handle.
* @tparam Component Type of component to create.
* @tparam Args Types of arguments to use to construct the component.
* @param args Parameters to use to initialize the component.
* @return A reference to the newly created component.
*/
template<typename Component, typename... Args>
decltype(auto) emplace(Args &&...args) const {
static_assert(((sizeof...(Scope) == 0) || ... || std::is_same_v<Component, Scope>), "Invalid type");
return reg->template emplace<Component>(entt, std::forward<Args>(args)...);
}
/**
* @brief Assigns or replaces the given component for a handle.
* @tparam Component Type of component to assign or replace.
* @tparam Args Types of arguments to use to construct the component.
* @param args Parameters to use to initialize the component.
* @return A reference to the newly created component.
*/
template<typename Component, typename... Args>
decltype(auto) emplace_or_replace(Args &&...args) const {
static_assert(((sizeof...(Scope) == 0) || ... || std::is_same_v<Component, Scope>), "Invalid type");
return reg->template emplace_or_replace<Component>(entt, std::forward<Args>(args)...);
}
/**
* @brief Patches the given component for a handle.
* @tparam Component Type of component to patch.
* @tparam Func Types of the function objects to invoke.
* @param func Valid function objects.
* @return A reference to the patched component.
*/
template<typename Component, typename... Func>
decltype(auto) patch(Func &&...func) const {
static_assert(((sizeof...(Scope) == 0) || ... || std::is_same_v<Component, Scope>), "Invalid type");
return reg->template patch<Component>(entt, std::forward<Func>(func)...);
}
/**
* @brief Replaces the given component for a handle.
* @tparam Component Type of component to replace.
* @tparam Args Types of arguments to use to construct the component.
* @param args Parameters to use to initialize the component.
* @return A reference to the component being replaced.
*/
template<typename Component, typename... Args>
decltype(auto) replace(Args &&...args) const {
static_assert(((sizeof...(Scope) == 0) || ... || std::is_same_v<Component, Scope>), "Invalid type");
return reg->template replace<Component>(entt, std::forward<Args>(args)...);
}
/**
* @brief Removes the given components from a handle.
* @tparam Component Types of components to remove.
* @return The number of components actually removed.
*/
template<typename... Component>
size_type remove() const {
static_assert(sizeof...(Scope) == 0 || (type_list_contains_v<type_list<Scope...>, Component> && ...), "Invalid type");
return reg->template remove<Component...>(entt);
}
/**
* @brief Erases the given components from a handle.
* @tparam Component Types of components to erase.
*/
template<typename... Component>
void erase() const {
static_assert(sizeof...(Scope) == 0 || (type_list_contains_v<type_list<Scope...>, Component> && ...), "Invalid type");
reg->template erase<Component...>(entt);
}
/**
* @brief Checks if a handle has all the given components.
* @tparam Component Components for which to perform the check.
* @return True if the handle has all the components, false otherwise.
*/
template<typename... Component>
[[nodiscard]] decltype(auto) all_of() const {
return reg->template all_of<Component...>(entt);
}
/**
* @brief Checks if a handle has at least one of the given components.
* @tparam Component Components for which to perform the check.
* @return True if the handle has at least one of the given components,
* false otherwise.
*/
template<typename... Component>
[[nodiscard]] decltype(auto) any_of() const {
return reg->template any_of<Component...>(entt);
}
/**
* @brief Returns references to the given components for a handle.
* @tparam Component Types of components to get.
* @return References to the components owned by the handle.
*/
template<typename... Component>
[[nodiscard]] decltype(auto) get() const {
static_assert(sizeof...(Scope) == 0 || (type_list_contains_v<type_list<Scope...>, Component> && ...), "Invalid type");
return reg->template get<Component...>(entt);
}
/**
* @brief Returns a reference to the given component for a handle.
* @tparam Component Type of component to get.
* @tparam Args Types of arguments to use to construct the component.
* @param args Parameters to use to initialize the component.
* @return Reference to the component owned by the handle.
*/
template<typename Component, typename... Args>
[[nodiscard]] decltype(auto) get_or_emplace(Args &&...args) const {
static_assert(((sizeof...(Scope) == 0) || ... || std::is_same_v<Component, Scope>), "Invalid type");
return reg->template get_or_emplace<Component>(entt, std::forward<Args>(args)...);
}
/**
* @brief Returns pointers to the given components for a handle.
* @tparam Component Types of components to get.
* @return Pointers to the components owned by the handle.
*/
template<typename... Component>
[[nodiscard]] auto try_get() const {
static_assert(sizeof...(Scope) == 0 || (type_list_contains_v<type_list<Scope...>, Component> && ...), "Invalid type");
return reg->template try_get<Component...>(entt);
}
/**
* @brief Checks if a handle has components assigned.
* @return True if the handle has no components assigned, false otherwise.
*/
[[nodiscard]] bool orphan() const {
return reg->orphan(entt);
}
private:
registry_type *reg;
entity_type entt;
};
/**
* @brief Compares two handles.
* @tparam Args Scope of the first handle.
* @tparam Other Scope of the second handle.
* @param lhs A valid handle.
* @param rhs A valid handle.
* @return True if both handles refer to the same registry and the same
* entity, false otherwise.
*/
template<typename... Args, typename... Other>
[[nodiscard]] bool operator==(const basic_handle<Args...> &lhs, const basic_handle<Other...> &rhs) noexcept {
return lhs.registry() == rhs.registry() && lhs.entity() == rhs.entity();
}
/**
* @brief Compares two handles.
* @tparam Args Scope of the first handle.
* @tparam Other Scope of the second handle.
* @param lhs A valid handle.
* @param rhs A valid handle.
* @return False if both handles refer to the same registry and the same
* entity, true otherwise.
*/
template<typename... Args, typename... Other>
[[nodiscard]] bool operator!=(const basic_handle<Args...> &lhs, const basic_handle<Other...> &rhs) noexcept {
return !(lhs == rhs);
}
} // namespace entt
#endif
<|endoftext|> |
<commit_before>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/eval/eval/fast_value.h>
#include <vespa/eval/eval/simple_value.h>
#include <vespa/eval/eval/tensor_function.h>
#include <vespa/eval/instruction/mixed_simple_join_function.h>
#include <vespa/eval/eval/test/eval_fixture.h>
#include <vespa/eval/eval/test/gen_spec.h>
#include <vespa/vespalib/util/stringfmt.h>
using namespace vespalib;
using namespace vespalib::eval;
using namespace vespalib::eval::test;
using namespace vespalib::eval::tensor_function;
using vespalib::make_string_short::fmt;
const ValueBuilderFactory &prod_factory = FastValueBuilderFactory::get();
const ValueBuilderFactory &test_factory = SimpleValueBuilderFactory::get();
using Primary = MixedSimpleJoinFunction::Primary;
using Overlap = MixedSimpleJoinFunction::Overlap;
namespace vespalib::eval {
std::ostream &operator<<(std::ostream &os, Primary primary)
{
switch(primary) {
case Primary::LHS: return os << "LHS";
case Primary::RHS: return os << "RHS";
}
abort();
}
std::ostream &operator<<(std::ostream &os, Overlap overlap)
{
switch(overlap) {
case Overlap::FULL: return os << "FULL";
case Overlap::INNER: return os << "INNER";
case Overlap::OUTER: return os << "OUTER";
}
abort();
}
}
struct FunInfo {
using LookFor = MixedSimpleJoinFunction;
Overlap overlap;
size_t factor;
std::optional<Primary> primary;
bool l_mut;
bool r_mut;
std::optional<bool> inplace;
void verify(const EvalFixture &fixture, const LookFor &fun) const {
EXPECT_TRUE(fun.result_is_mutable());
EXPECT_EQUAL(fun.overlap(), overlap);
EXPECT_EQUAL(fun.factor(), factor);
if (primary.has_value()) {
EXPECT_EQUAL(fun.primary(), primary.value());
}
if (fun.primary_is_mutable()) {
if (fun.primary() == Primary::LHS) {
EXPECT_TRUE(l_mut);
}
if (fun.primary() == Primary::RHS) {
EXPECT_TRUE(r_mut);
}
}
if (inplace.has_value()) {
EXPECT_EQUAL(fun.inplace(), inplace.value());
}
if (fun.inplace()) {
EXPECT_TRUE(fun.primary_is_mutable());
size_t idx = (fun.primary() == Primary::LHS) ? 0 : 1;
EXPECT_EQUAL(fixture.result_value().cells().data,
fixture.param_value(idx).cells().data);
EXPECT_NOT_EQUAL(fixture.result_value().cells().data,
fixture.param_value(1-idx).cells().data);
} else {
EXPECT_NOT_EQUAL(fixture.result_value().cells().data,
fixture.param_value(0).cells().data);
EXPECT_NOT_EQUAL(fixture.result_value().cells().data,
fixture.param_value(1).cells().data);
}
}
};
void verify_simple(const vespalib::string &expr, Primary primary, Overlap overlap, size_t factor,
bool l_mut, bool r_mut, bool inplace)
{
TEST_STATE(expr.c_str());
CellTypeSpace just_double({CellType::DOUBLE}, 2);
FunInfo details{overlap, factor, primary, l_mut, r_mut, inplace};
EvalFixture::verify<FunInfo>(expr, {details}, just_double);
}
void verify_optimized(const vespalib::string &expr, Primary primary, Overlap overlap, size_t factor,
bool l_mut = false, bool r_mut = false)
{
TEST_STATE(expr.c_str());
CellTypeSpace all_types(CellTypeUtils::list_types(), 2);
FunInfo details{overlap, factor, primary, l_mut, r_mut, std::nullopt};
EvalFixture::verify<FunInfo>(expr, {details}, all_types);
}
void verify_optimized(const vespalib::string &expr, Overlap overlap, size_t factor,
bool l_mut = false, bool r_mut = false)
{
TEST_STATE(expr.c_str());
CellTypeSpace all_types(CellTypeUtils::list_types(), 2);
FunInfo details{overlap, factor, std::nullopt, l_mut, r_mut, std::nullopt};
EvalFixture::verify<FunInfo>(expr, {details}, all_types);
}
void verify_not_optimized(const vespalib::string &expr) {
TEST_STATE(expr.c_str());
CellTypeSpace just_double({CellType::DOUBLE}, 2);
EvalFixture::verify<FunInfo>(expr, {}, just_double);
}
TEST("require that basic join is optimized") {
TEST_DO(verify_optimized("y5+y5$2", Primary::RHS, Overlap::FULL, 1));
}
TEST("require that inplace is preferred") {
TEST_DO(verify_simple("y5+y5$2", Primary::RHS, Overlap::FULL, 1, false, false, false));
TEST_DO(verify_simple("y5+@y5$2", Primary::RHS, Overlap::FULL, 1, false, true, true));
TEST_DO(verify_simple("@y5+@y5$2", Primary::RHS, Overlap::FULL, 1, true, true, true));
TEST_DO(verify_simple("@y5+y5$2", Primary::LHS, Overlap::FULL, 1, true, false, true));
}
TEST("require that unit join is optimized") {
TEST_DO(verify_optimized("a1b1c1+x1y1z1", Primary::RHS, Overlap::FULL, 1));
}
TEST("require that trivial dimensions do not affect overlap calculation") {
TEST_DO(verify_optimized("c5d1+b1c5", Primary::RHS, Overlap::FULL, 1));
}
TEST("require that outer nesting is preferred to inner nesting") {
TEST_DO(verify_optimized("a1b1c1+y5", Primary::RHS, Overlap::OUTER, 5));
}
TEST("require that non-subset join is not optimized") {
TEST_DO(verify_not_optimized("y5+z3"));
}
TEST("require that subset join with complex overlap is not optimized") {
TEST_DO(verify_not_optimized("x3y5z3+y5"));
}
struct LhsRhs {
vespalib::string lhs;
vespalib::string rhs;
size_t lhs_size;
size_t rhs_size;
Overlap overlap;
size_t factor;
LhsRhs(const vespalib::string &lhs_in, const vespalib::string &rhs_in,
size_t lhs_size_in, size_t rhs_size_in, Overlap overlap_in) noexcept
: lhs(lhs_in), rhs(rhs_in), lhs_size(lhs_size_in), rhs_size(rhs_size_in), overlap(overlap_in), factor(1)
{
if (lhs_size > rhs_size) {
ASSERT_EQUAL(lhs_size % rhs_size, 0u);
factor = (lhs_size / rhs_size);
} else {
ASSERT_EQUAL(rhs_size % lhs_size, 0u);
factor = (rhs_size / lhs_size);
}
}
};
CellType join_ct(CellType lct, CellType rct) {
if (lct == CellType::DOUBLE || rct == CellType::DOUBLE) {
return CellType::DOUBLE;
} else {
return CellType::FLOAT;
}
}
TEST("require that various parameter combinations work") {
for (CellType lct : CellTypeUtils::list_types()) {
for (CellType rct : CellTypeUtils::list_types()) {
for (bool left_mut: {false, true}) {
for (bool right_mut: {false, true}) {
for (const char * expr: {"a+b", "a-b", "a*b"}) {
for (const LhsRhs ¶ms:
{ LhsRhs("y5", "y5", 5, 5, Overlap::FULL),
LhsRhs("y5", "x3y5", 5, 15, Overlap::INNER),
LhsRhs("y5", "y5z3", 5, 15, Overlap::OUTER),
LhsRhs("x3y5", "y5", 15, 5, Overlap::INNER),
LhsRhs("y5z3", "y5", 15, 5, Overlap::OUTER)})
{
EvalFixture::ParamRepo param_repo;
auto a_spec = GenSpec::from_desc(params.lhs).cells(lct).seq(AX_B(0.25, 1.125));
auto b_spec = GenSpec::from_desc(params.rhs).cells(rct).seq(AX_B(-0.25, 25.0));
if (left_mut) {
param_repo.add_mutable("a", a_spec);
} else {
param_repo.add("a", a_spec);
}
if (right_mut) {
param_repo.add_mutable("b", b_spec);
} else {
param_repo.add("b", b_spec);
}
TEST_STATE(expr);
CellType result_ct = join_ct(lct, rct);
Primary primary = Primary::RHS;
if (params.overlap == Overlap::FULL) {
bool w_lhs = (lct == result_ct) && left_mut;
bool w_rhs = (rct == result_ct) && right_mut;
if (w_lhs && !w_rhs) {
primary = Primary::LHS;
}
} else if (params.lhs_size > params.rhs_size) {
primary = Primary::LHS;
}
bool pri_mut = (primary == Primary::LHS) ? left_mut : right_mut;
bool pri_same_ct = (primary == Primary::LHS) ? (lct == result_ct) : (rct == result_ct);
bool inplace = (pri_mut && pri_same_ct);
auto expect = EvalFixture::ref(expr, param_repo);
EvalFixture slow_fixture(prod_factory, expr, param_repo, false);
EvalFixture test_fixture(test_factory, expr, param_repo, true, true);
EvalFixture fixture(prod_factory, expr, param_repo, true, true);
EXPECT_EQUAL(fixture.result(), expect);
EXPECT_EQUAL(slow_fixture.result(), expect);
EXPECT_EQUAL(test_fixture.result(), expect);
auto info = fixture.find_all<FunInfo::LookFor>();
ASSERT_EQUAL(info.size(), 1u);
FunInfo details{params.overlap, params.factor, primary, left_mut, right_mut, inplace};
details.verify(fixture, *info[0]);
}
}
}
}
}
}
}
TEST("require that scalar values are not optimized") {
TEST_DO(verify_not_optimized("reduce(v3,sum)+reduce(v4,sum)"));
TEST_DO(verify_not_optimized("reduce(v3,sum)+y5"));
TEST_DO(verify_not_optimized("y5+reduce(v3,sum)"));
TEST_DO(verify_not_optimized("reduce(v3,sum)+x3_1"));
TEST_DO(verify_not_optimized("x3_1+reduce(v3,sum)"));
TEST_DO(verify_not_optimized("reduce(v3,sum)+x3_1y5z3"));
TEST_DO(verify_not_optimized("x3_1y5z3+reduce(v3,sum)"));
}
TEST("require that sparse tensors are mostly not optimized") {
TEST_DO(verify_not_optimized("x3_1+x3_1$2"));
TEST_DO(verify_not_optimized("x3_1+y5"));
TEST_DO(verify_not_optimized("y5+x3_1"));
TEST_DO(verify_not_optimized("x3_1+x3_1y5z3"));
TEST_DO(verify_not_optimized("x3_1y5z3+x3_1"));
}
TEST("require that sparse tensor joined with trivial dense tensor is optimized") {
TEST_DO(verify_optimized("x3_1+a1b1c1", Primary::LHS, Overlap::FULL, 1));
TEST_DO(verify_optimized("a1b1c1+x3_1", Primary::RHS, Overlap::FULL, 1));
}
TEST("require that primary tensor can be empty") {
TEST_DO(verify_optimized("x0_1y5z3+y5z3", Primary::LHS, Overlap::FULL, 1));
TEST_DO(verify_optimized("y5z3+x0_1y5z3", Primary::RHS, Overlap::FULL, 1));
}
TEST("require that mixed tensors can be optimized") {
TEST_DO(verify_not_optimized("x3_1y5z3+x3_1y5z3$2"));
TEST_DO(verify_optimized("x3_1y5z3+y5z3", Primary::LHS, Overlap::FULL, 1));
TEST_DO(verify_optimized("x3_1y5z3+y5", Primary::LHS, Overlap::OUTER, 3));
TEST_DO(verify_optimized("x3_1y5z3+z3", Primary::LHS, Overlap::INNER, 5));
TEST_DO(verify_optimized("y5z3+x3_1y5z3", Primary::RHS, Overlap::FULL, 1));
TEST_DO(verify_optimized("y5+x3_1y5z3", Primary::RHS, Overlap::OUTER, 3));
TEST_DO(verify_optimized("z3+x3_1y5z3", Primary::RHS, Overlap::INNER, 5));
}
TEST("require that mixed tensors can be inplace") {
TEST_DO(verify_optimized("@x3_1y5z3+y5z3", Primary::LHS, Overlap::FULL, 1, true, false));
TEST_DO(verify_optimized("@x3_1y5z3+y5", Primary::LHS, Overlap::OUTER, 3, true, false));
TEST_DO(verify_optimized("@x3_1y5z3+z3", Primary::LHS, Overlap::INNER, 5, true, false));
TEST_DO(verify_optimized("y5z3+@x3_1y5z3", Primary::RHS, Overlap::FULL, 1, false, true));
TEST_DO(verify_optimized("y5+@x3_1y5z3", Primary::RHS, Overlap::OUTER, 3, false, true));
TEST_DO(verify_optimized("z3+@x3_1y5z3", Primary::RHS, Overlap::INNER, 5, false, true));
}
TEST_MAIN() { TEST_RUN_ALL(); }
<commit_msg>review follow-up<commit_after>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/eval/eval/fast_value.h>
#include <vespa/eval/eval/simple_value.h>
#include <vespa/eval/eval/tensor_function.h>
#include <vespa/eval/instruction/mixed_simple_join_function.h>
#include <vespa/eval/eval/test/eval_fixture.h>
#include <vespa/eval/eval/test/gen_spec.h>
#include <vespa/vespalib/util/stringfmt.h>
using namespace vespalib;
using namespace vespalib::eval;
using namespace vespalib::eval::test;
using namespace vespalib::eval::tensor_function;
using vespalib::make_string_short::fmt;
const ValueBuilderFactory &prod_factory = FastValueBuilderFactory::get();
const ValueBuilderFactory &test_factory = SimpleValueBuilderFactory::get();
using Primary = MixedSimpleJoinFunction::Primary;
using Overlap = MixedSimpleJoinFunction::Overlap;
namespace vespalib::eval {
std::ostream &operator<<(std::ostream &os, Primary primary)
{
switch(primary) {
case Primary::LHS: return os << "LHS";
case Primary::RHS: return os << "RHS";
}
abort();
}
std::ostream &operator<<(std::ostream &os, Overlap overlap)
{
switch(overlap) {
case Overlap::FULL: return os << "FULL";
case Overlap::INNER: return os << "INNER";
case Overlap::OUTER: return os << "OUTER";
}
abort();
}
}
struct FunInfo {
using LookFor = MixedSimpleJoinFunction;
Overlap overlap;
size_t factor;
Primary primary;
bool l_mut;
bool r_mut;
bool inplace;
void verify(const EvalFixture &fixture, const LookFor &fun) const {
EXPECT_TRUE(fun.result_is_mutable());
EXPECT_EQUAL(fun.overlap(), overlap);
EXPECT_EQUAL(fun.factor(), factor);
EXPECT_EQUAL(fun.primary(), primary);
if (fun.primary_is_mutable()) {
if (fun.primary() == Primary::LHS) {
EXPECT_TRUE(l_mut);
}
if (fun.primary() == Primary::RHS) {
EXPECT_TRUE(r_mut);
}
}
EXPECT_EQUAL(fun.inplace(), inplace);
if (fun.inplace()) {
EXPECT_TRUE(fun.primary_is_mutable());
size_t idx = (fun.primary() == Primary::LHS) ? 0 : 1;
EXPECT_EQUAL(fixture.result_value().cells().data,
fixture.param_value(idx).cells().data);
EXPECT_NOT_EQUAL(fixture.result_value().cells().data,
fixture.param_value(1-idx).cells().data);
} else {
EXPECT_NOT_EQUAL(fixture.result_value().cells().data,
fixture.param_value(0).cells().data);
EXPECT_NOT_EQUAL(fixture.result_value().cells().data,
fixture.param_value(1).cells().data);
}
}
};
void verify_simple(const vespalib::string &expr, Primary primary, Overlap overlap, size_t factor,
bool l_mut, bool r_mut, bool inplace)
{
TEST_STATE(expr.c_str());
CellTypeSpace just_double({CellType::DOUBLE}, 2);
FunInfo details{overlap, factor, primary, l_mut, r_mut, inplace};
EvalFixture::verify<FunInfo>(expr, {details}, just_double);
CellTypeSpace just_float({CellType::FLOAT}, 2);
EvalFixture::verify<FunInfo>(expr, {details}, just_float);
}
void verify_optimized(const vespalib::string &expr, Primary primary, Overlap overlap, size_t factor,
bool l_mut = false, bool r_mut = false, bool inplace = false)
{
TEST_STATE(expr.c_str());
CellTypeSpace all_types(CellTypeUtils::list_types(), 2);
FunInfo details{overlap, factor, primary, l_mut, r_mut, inplace};
EvalFixture::verify<FunInfo>(expr, {details}, all_types);
}
void verify_not_optimized(const vespalib::string &expr) {
TEST_STATE(expr.c_str());
CellTypeSpace just_double({CellType::DOUBLE}, 2);
EvalFixture::verify<FunInfo>(expr, {}, just_double);
}
TEST("require that basic join is optimized") {
TEST_DO(verify_optimized("y5+y5$2", Primary::RHS, Overlap::FULL, 1));
}
TEST("require that inplace is preferred") {
TEST_DO(verify_simple("y5+y5$2", Primary::RHS, Overlap::FULL, 1, false, false, false));
TEST_DO(verify_simple("y5+@y5$2", Primary::RHS, Overlap::FULL, 1, false, true, true));
TEST_DO(verify_simple("@y5+@y5$2", Primary::RHS, Overlap::FULL, 1, true, true, true));
TEST_DO(verify_simple("@y5+y5$2", Primary::LHS, Overlap::FULL, 1, true, false, true));
}
TEST("require that unit join is optimized") {
TEST_DO(verify_optimized("a1b1c1+x1y1z1", Primary::RHS, Overlap::FULL, 1));
}
TEST("require that trivial dimensions do not affect overlap calculation") {
TEST_DO(verify_optimized("c5d1+b1c5", Primary::RHS, Overlap::FULL, 1));
}
TEST("require that outer nesting is preferred to inner nesting") {
TEST_DO(verify_optimized("a1b1c1+y5", Primary::RHS, Overlap::OUTER, 5));
}
TEST("require that non-subset join is not optimized") {
TEST_DO(verify_not_optimized("y5+z3"));
}
TEST("require that subset join with complex overlap is not optimized") {
TEST_DO(verify_not_optimized("x3y5z3+y5"));
}
struct LhsRhs {
vespalib::string lhs;
vespalib::string rhs;
size_t lhs_size;
size_t rhs_size;
Overlap overlap;
size_t factor;
LhsRhs(const vespalib::string &lhs_in, const vespalib::string &rhs_in,
size_t lhs_size_in, size_t rhs_size_in, Overlap overlap_in) noexcept
: lhs(lhs_in), rhs(rhs_in), lhs_size(lhs_size_in), rhs_size(rhs_size_in), overlap(overlap_in), factor(1)
{
if (lhs_size > rhs_size) {
ASSERT_EQUAL(lhs_size % rhs_size, 0u);
factor = (lhs_size / rhs_size);
} else {
ASSERT_EQUAL(rhs_size % lhs_size, 0u);
factor = (rhs_size / lhs_size);
}
}
};
CellType join_ct(CellType lct, CellType rct) {
if (lct == CellType::DOUBLE || rct == CellType::DOUBLE) {
return CellType::DOUBLE;
} else {
return CellType::FLOAT;
}
}
TEST("require that various parameter combinations work") {
for (CellType lct : CellTypeUtils::list_types()) {
for (CellType rct : CellTypeUtils::list_types()) {
for (bool left_mut: {false, true}) {
for (bool right_mut: {false, true}) {
for (const char * expr: {"a+b", "a-b", "a*b"}) {
for (const LhsRhs ¶ms:
{ LhsRhs("y5", "y5", 5, 5, Overlap::FULL),
LhsRhs("y5", "x3y5", 5, 15, Overlap::INNER),
LhsRhs("y5", "y5z3", 5, 15, Overlap::OUTER),
LhsRhs("x3y5", "y5", 15, 5, Overlap::INNER),
LhsRhs("y5z3", "y5", 15, 5, Overlap::OUTER)})
{
EvalFixture::ParamRepo param_repo;
auto a_spec = GenSpec::from_desc(params.lhs).cells(lct).seq(AX_B(0.25, 1.125));
auto b_spec = GenSpec::from_desc(params.rhs).cells(rct).seq(AX_B(-0.25, 25.0));
if (left_mut) {
param_repo.add_mutable("a", a_spec);
} else {
param_repo.add("a", a_spec);
}
if (right_mut) {
param_repo.add_mutable("b", b_spec);
} else {
param_repo.add("b", b_spec);
}
TEST_STATE(expr);
CellType result_ct = join_ct(lct, rct);
Primary primary = Primary::RHS;
if (params.overlap == Overlap::FULL) {
bool w_lhs = (lct == result_ct) && left_mut;
bool w_rhs = (rct == result_ct) && right_mut;
if (w_lhs && !w_rhs) {
primary = Primary::LHS;
}
} else if (params.lhs_size > params.rhs_size) {
primary = Primary::LHS;
}
bool pri_mut = (primary == Primary::LHS) ? left_mut : right_mut;
bool pri_same_ct = (primary == Primary::LHS) ? (lct == result_ct) : (rct == result_ct);
bool inplace = (pri_mut && pri_same_ct);
auto expect = EvalFixture::ref(expr, param_repo);
EvalFixture slow_fixture(prod_factory, expr, param_repo, false);
EvalFixture test_fixture(test_factory, expr, param_repo, true, true);
EvalFixture fixture(prod_factory, expr, param_repo, true, true);
EXPECT_EQUAL(fixture.result(), expect);
EXPECT_EQUAL(slow_fixture.result(), expect);
EXPECT_EQUAL(test_fixture.result(), expect);
auto info = fixture.find_all<FunInfo::LookFor>();
ASSERT_EQUAL(info.size(), 1u);
FunInfo details{params.overlap, params.factor, primary, left_mut, right_mut, inplace};
details.verify(fixture, *info[0]);
}
}
}
}
}
}
}
TEST("require that scalar values are not optimized") {
TEST_DO(verify_not_optimized("reduce(v3,sum)+reduce(v4,sum)"));
TEST_DO(verify_not_optimized("reduce(v3,sum)+y5"));
TEST_DO(verify_not_optimized("y5+reduce(v3,sum)"));
TEST_DO(verify_not_optimized("reduce(v3,sum)+x3_1"));
TEST_DO(verify_not_optimized("x3_1+reduce(v3,sum)"));
TEST_DO(verify_not_optimized("reduce(v3,sum)+x3_1y5z3"));
TEST_DO(verify_not_optimized("x3_1y5z3+reduce(v3,sum)"));
}
TEST("require that sparse tensors are mostly not optimized") {
TEST_DO(verify_not_optimized("x3_1+x3_1$2"));
TEST_DO(verify_not_optimized("x3_1+y5"));
TEST_DO(verify_not_optimized("y5+x3_1"));
TEST_DO(verify_not_optimized("x3_1+x3_1y5z3"));
TEST_DO(verify_not_optimized("x3_1y5z3+x3_1"));
}
TEST("require that sparse tensor joined with trivial dense tensor is optimized") {
TEST_DO(verify_optimized("x3_1+a1b1c1", Primary::LHS, Overlap::FULL, 1));
TEST_DO(verify_optimized("a1b1c1+x3_1", Primary::RHS, Overlap::FULL, 1));
}
TEST("require that primary tensor can be empty") {
TEST_DO(verify_optimized("x0_1y5z3+y5z3", Primary::LHS, Overlap::FULL, 1));
TEST_DO(verify_optimized("y5z3+x0_1y5z3", Primary::RHS, Overlap::FULL, 1));
}
TEST("require that mixed tensors can be optimized") {
TEST_DO(verify_not_optimized("x3_1y5z3+x3_1y5z3$2"));
TEST_DO(verify_optimized("x3_1y5z3+y5z3", Primary::LHS, Overlap::FULL, 1));
TEST_DO(verify_optimized("x3_1y5z3+y5", Primary::LHS, Overlap::OUTER, 3));
TEST_DO(verify_optimized("x3_1y5z3+z3", Primary::LHS, Overlap::INNER, 5));
TEST_DO(verify_optimized("y5z3+x3_1y5z3", Primary::RHS, Overlap::FULL, 1));
TEST_DO(verify_optimized("y5+x3_1y5z3", Primary::RHS, Overlap::OUTER, 3));
TEST_DO(verify_optimized("z3+x3_1y5z3", Primary::RHS, Overlap::INNER, 5));
}
TEST("require that mixed tensors can be inplace") {
TEST_DO(verify_simple("@x3_1y5z3+y5z3", Primary::LHS, Overlap::FULL, 1, true, false, true));
TEST_DO(verify_simple("@x3_1y5z3+y5", Primary::LHS, Overlap::OUTER, 3, true, false, true));
TEST_DO(verify_simple("@x3_1y5z3+z3", Primary::LHS, Overlap::INNER, 5, true, false, true));
TEST_DO(verify_simple("@x3_1y5z3+@y5z3", Primary::LHS, Overlap::FULL, 1, true, true, true));
TEST_DO(verify_simple("@x3_1y5z3+@y5", Primary::LHS, Overlap::OUTER, 3, true, true, true));
TEST_DO(verify_simple("@x3_1y5z3+@z3", Primary::LHS, Overlap::INNER, 5, true, true, true));
TEST_DO(verify_simple("y5z3+@x3_1y5z3", Primary::RHS, Overlap::FULL, 1, false, true, true));
TEST_DO(verify_simple("y5+@x3_1y5z3", Primary::RHS, Overlap::OUTER, 3, false, true, true));
TEST_DO(verify_simple("z3+@x3_1y5z3", Primary::RHS, Overlap::INNER, 5, false, true, true));
TEST_DO(verify_simple("@y5z3+@x3_1y5z3", Primary::RHS, Overlap::FULL, 1, true, true, true));
TEST_DO(verify_simple("@y5+@x3_1y5z3", Primary::RHS, Overlap::OUTER, 3, true, true, true));
TEST_DO(verify_simple("@z3+@x3_1y5z3", Primary::RHS, Overlap::INNER, 5, true, true, true));
}
TEST_MAIN() { TEST_RUN_ALL(); }
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: VGroup.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: oj $ $Date: 2002-11-12 09:17:38 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include <stdio.h>
#ifndef _CONNECTIVITY_SDBCX_GROUP_HXX_
#include "connectivity/sdbcx/VGroup.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_PRIVILEGE_HPP_
#include <com/sun/star/sdbcx/Privilege.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_PRIVILEGEOBJECT_HPP_
#include <com/sun/star/sdbcx/PrivilegeObject.hpp>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
// -------------------------------------------------------------------------
using namespace connectivity::sdbcx;
using namespace connectivity;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
IMPLEMENT_SERVICE_INFO(OGroup,"com.sun.star.sdbcx.VGroup","com.sun.star.sdbcx.Group");
// -------------------------------------------------------------------------
OGroup::OGroup(sal_Bool _bCase) : OGroup_BASE(m_aMutex)
, ODescriptor(OGroup_BASE::rBHelper,_bCase)
, m_pUsers(NULL)
{
}
// -------------------------------------------------------------------------
OGroup::OGroup(const ::rtl::OUString& _Name,sal_Bool _bCase) : OGroup_BASE(m_aMutex)
,ODescriptor(OGroup_BASE::rBHelper,_bCase)
,m_pUsers(NULL)
{
m_Name = _Name;
}
// -------------------------------------------------------------------------
OGroup::~OGroup()
{
delete m_pUsers;
}
// -------------------------------------------------------------------------
Any SAL_CALL OGroup::queryInterface( const Type & rType ) throw(RuntimeException)
{
Any aRet = ODescriptor::queryInterface( rType);
return aRet.hasValue() ? aRet : OGroup_BASE::queryInterface( rType);
}
// -------------------------------------------------------------------------
Sequence< Type > SAL_CALL OGroup::getTypes( ) throw(RuntimeException)
{
return ::comphelper::concatSequences(ODescriptor::getTypes(),OGroup_BASE::getTypes());
}
// -------------------------------------------------------------------------
void OGroup::disposing(void)
{
OPropertySetHelper::disposing();
::osl::MutexGuard aGuard(m_aMutex);
if(m_pUsers)
m_pUsers->disposing();
}
// -------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* OGroup::createArrayHelper( ) const
{
Sequence< Property > aProps;
describeProperties(aProps);
return new ::cppu::OPropertyArrayHelper(aProps);
}
// -------------------------------------------------------------------------
::cppu::IPropertyArrayHelper & OGroup::getInfoHelper()
{
return *const_cast<OGroup*>(this)->getArrayHelper();
}
// -------------------------------------------------------------------------
Reference< XNameAccess > SAL_CALL OGroup::getUsers( ) throw(RuntimeException)
{
::osl::MutexGuard aGuard(m_aMutex);
checkDisposed(OGroup_BASE::rBHelper.bDisposed);
try
{
if ( !m_pUsers )
refreshUsers();
}
catch( const RuntimeException& )
{
// allowed to leave this method
throw;
}
catch( const Exception& )
{
// allowed
}
return const_cast<OGroup*>(this)->m_pUsers;
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OGroup::getPrivileges( const ::rtl::OUString& objName, sal_Int32 objType ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)
{
::osl::MutexGuard aGuard(m_aMutex);
checkDisposed(OGroup_BASE::rBHelper.bDisposed);
return 0;
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OGroup::getGrantablePrivileges( const ::rtl::OUString& objName, sal_Int32 objType ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)
{
::osl::MutexGuard aGuard(m_aMutex);
checkDisposed(OGroup_BASE::rBHelper.bDisposed);
return 0;
}
// -------------------------------------------------------------------------
void SAL_CALL OGroup::grantPrivileges( const ::rtl::OUString& objName, sal_Int32 objType, sal_Int32 objPrivileges ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)
{
::osl::MutexGuard aGuard(m_aMutex);
checkDisposed(OGroup_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OGroup::revokePrivileges( const ::rtl::OUString& objName, sal_Int32 objType, sal_Int32 objPrivileges ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)
{
::osl::MutexGuard aGuard(m_aMutex);
checkDisposed(OGroup_BASE::rBHelper.bDisposed);
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL OGroup::getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException)
{
return ::cppu::OPropertySetHelper::createPropertySetInfo(getInfoHelper());
}
// -----------------------------------------------------------------------------
::rtl::OUString SAL_CALL OGroup::getName( ) throw(::com::sun::star::uno::RuntimeException)
{
return m_Name;
}
// -----------------------------------------------------------------------------
void SAL_CALL OGroup::setName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException)
{
}
// -----------------------------------------------------------------------------
// XInterface
void SAL_CALL OGroup::acquire() throw()
{
OGroup_BASE::acquire();
}
// -----------------------------------------------------------------------------
void SAL_CALL OGroup::release() throw()
{
OGroup_BASE::release();
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS ooo19126 (1.10.320); FILE MERGED 2005/09/05 17:25:54 rt 1.10.320.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: VGroup.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: rt $ $Date: 2005-09-08 07:43:26 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <stdio.h>
#ifndef _CONNECTIVITY_SDBCX_GROUP_HXX_
#include "connectivity/sdbcx/VGroup.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_PRIVILEGE_HPP_
#include <com/sun/star/sdbcx/Privilege.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_PRIVILEGEOBJECT_HPP_
#include <com/sun/star/sdbcx/PrivilegeObject.hpp>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
// -------------------------------------------------------------------------
using namespace connectivity::sdbcx;
using namespace connectivity;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
IMPLEMENT_SERVICE_INFO(OGroup,"com.sun.star.sdbcx.VGroup","com.sun.star.sdbcx.Group");
// -------------------------------------------------------------------------
OGroup::OGroup(sal_Bool _bCase) : OGroup_BASE(m_aMutex)
, ODescriptor(OGroup_BASE::rBHelper,_bCase)
, m_pUsers(NULL)
{
}
// -------------------------------------------------------------------------
OGroup::OGroup(const ::rtl::OUString& _Name,sal_Bool _bCase) : OGroup_BASE(m_aMutex)
,ODescriptor(OGroup_BASE::rBHelper,_bCase)
,m_pUsers(NULL)
{
m_Name = _Name;
}
// -------------------------------------------------------------------------
OGroup::~OGroup()
{
delete m_pUsers;
}
// -------------------------------------------------------------------------
Any SAL_CALL OGroup::queryInterface( const Type & rType ) throw(RuntimeException)
{
Any aRet = ODescriptor::queryInterface( rType);
return aRet.hasValue() ? aRet : OGroup_BASE::queryInterface( rType);
}
// -------------------------------------------------------------------------
Sequence< Type > SAL_CALL OGroup::getTypes( ) throw(RuntimeException)
{
return ::comphelper::concatSequences(ODescriptor::getTypes(),OGroup_BASE::getTypes());
}
// -------------------------------------------------------------------------
void OGroup::disposing(void)
{
OPropertySetHelper::disposing();
::osl::MutexGuard aGuard(m_aMutex);
if(m_pUsers)
m_pUsers->disposing();
}
// -------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* OGroup::createArrayHelper( ) const
{
Sequence< Property > aProps;
describeProperties(aProps);
return new ::cppu::OPropertyArrayHelper(aProps);
}
// -------------------------------------------------------------------------
::cppu::IPropertyArrayHelper & OGroup::getInfoHelper()
{
return *const_cast<OGroup*>(this)->getArrayHelper();
}
// -------------------------------------------------------------------------
Reference< XNameAccess > SAL_CALL OGroup::getUsers( ) throw(RuntimeException)
{
::osl::MutexGuard aGuard(m_aMutex);
checkDisposed(OGroup_BASE::rBHelper.bDisposed);
try
{
if ( !m_pUsers )
refreshUsers();
}
catch( const RuntimeException& )
{
// allowed to leave this method
throw;
}
catch( const Exception& )
{
// allowed
}
return const_cast<OGroup*>(this)->m_pUsers;
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OGroup::getPrivileges( const ::rtl::OUString& objName, sal_Int32 objType ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)
{
::osl::MutexGuard aGuard(m_aMutex);
checkDisposed(OGroup_BASE::rBHelper.bDisposed);
return 0;
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OGroup::getGrantablePrivileges( const ::rtl::OUString& objName, sal_Int32 objType ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)
{
::osl::MutexGuard aGuard(m_aMutex);
checkDisposed(OGroup_BASE::rBHelper.bDisposed);
return 0;
}
// -------------------------------------------------------------------------
void SAL_CALL OGroup::grantPrivileges( const ::rtl::OUString& objName, sal_Int32 objType, sal_Int32 objPrivileges ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)
{
::osl::MutexGuard aGuard(m_aMutex);
checkDisposed(OGroup_BASE::rBHelper.bDisposed);
}
// -------------------------------------------------------------------------
void SAL_CALL OGroup::revokePrivileges( const ::rtl::OUString& objName, sal_Int32 objType, sal_Int32 objPrivileges ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)
{
::osl::MutexGuard aGuard(m_aMutex);
checkDisposed(OGroup_BASE::rBHelper.bDisposed);
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL OGroup::getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException)
{
return ::cppu::OPropertySetHelper::createPropertySetInfo(getInfoHelper());
}
// -----------------------------------------------------------------------------
::rtl::OUString SAL_CALL OGroup::getName( ) throw(::com::sun::star::uno::RuntimeException)
{
return m_Name;
}
// -----------------------------------------------------------------------------
void SAL_CALL OGroup::setName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException)
{
}
// -----------------------------------------------------------------------------
// XInterface
void SAL_CALL OGroup::acquire() throw()
{
OGroup_BASE::acquire();
}
// -----------------------------------------------------------------------------
void SAL_CALL OGroup::release() throw()
{
OGroup_BASE::release();
}
// -----------------------------------------------------------------------------
<|endoftext|> |
<commit_before>// C++ S&S Indentation test.
// Copy this into kate and check that it indents corrently.
// Obviously that will be different for the different indentors, but this tries
// to check cases that I might not have thought of.
// TODO: Automate testing once the indentation actually works!
namespace Test
{
enum
{
one,
two,
three,
four
};
bool function(int a, bool b,
int c, double d)
{
for (int i = 0; i < b ? a : c; ++i)
cout << "Number: " << i << endl;
switch (classType)
{
case '1':
case '/':
case ';':
break;
case ':':
colon:
break;
case Test::one:
goto colon;
}
return Test::two;
}
}
class QWidget : public QObject
{
Q_OBJECT
public:
QWidget() : parent(null)
{
}
private:
struct Car : Vehicle
{
};
private slots:
Car test();
}
Car QWidget::test()
{
// A comment.
cerr << "this"
<< "is" << "a" << "test";
/* A block
comment */
}
<commit_msg>remove old files<commit_after><|endoftext|> |
<commit_before>/*
* oldBrain.cpp
* openc2e
*
* Created by Alyssa Milburn on Mon Aug 13 2007.
* Copyright (c) 2007 Alyssa Milburn. All rights reserved.
*
* 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 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.
*
*/
#include "oldBrain.h"
#include "Creature.h"
/*
* svrule examples:
*
* * creatures 1:
* output:TRUE:input
*
* * creatures 2:
* random:0:chem 5:PLUS:state
* state:PLUS:type 0:MINUS:type 1
* input:TRUE:output:TRUE:suscept:move twrds:255:64
* suscept:TRUE:chem 0:TRUE:STW
*
* * canny:
* state:PLUS:state:PLUS:state
* type 0:TRUE:type 0:PLUS:type 1
*
*/
unsigned char processSVRule(oldNeuron *cell, oldDendrite *dend, uint8 *svrule, unsigned int len) {
unsigned char state = 0;
for (unsigned int i = 0; i < len; i++) {
switch (svrule[i]) {
/*
* these numbers are the C2 svrules
*
* TODO: remap the C1 svrule numbers at load so they match these
*/
case 0: // <end>
return state;
case 1: // 0
state = 0;
break;
case 2: // 1
state = 1;
break;
case 3: // 64
state = 64;
break;
case 4: // 255
state = 255;
break;
case 5: // chem0
break;
case 6: // chem1
break;
case 7: // chem2
break;
case 8: // chem3
break;
case 9: // state
state = cell->state;
break;
case 10: // output
break;
case 11: // thres
break;
case 12: // type0
break;
case 13: // type1
break;
case 14: // anded0
break;
case 15: // anded1
// unused?
break;
case 16: // input
// This comes from IMPT for the decision lobe.
break;
case 17: // conduct
// unused?
break;
case 18: // suscept
break;
case 19: // STW
break;
case 20: // LTW
// unused?
break;
case 21: // strength
// unused?
break;
case 22: // 32
// unused?
break;
case 23: // 128
// unused?
break;
case 24: // rnd const
// unused?
break;
case 25: // chem4
break;
case 26: // chem5
break;
case 27: // leak in
// unused: back/forward prop
break;
case 28: // leak out
// unused: back/forward prop
break;
case 29: // curr src leak in
// unused: back/forward prop
break;
case 30: // TRUE
if (!state) return 0;
break;
case 31: // PLUS
break;
case 32: // MINUS
break;
case 33: // TIMES
// unused?
break;
case 34: // INCR
// unused?
state++;
break;
case 35: // DECR
// unused?
state--;
break;
case 36: // FALSE
// unused?
break;
case 37: // multiply
// unused?
break;
case 38: // average
// unused?
break;
case 39: // move twrds
break;
case 40: // random
break;
case 41: // <error>
break;
}
}
return state;
}
oldLobe::oldLobe(oldBrain *b, oldBrainLobeGene *g) {
assert(b);
parent = b;
assert(g);
ourGene = g;
inited = false;
threshold = g->nominalthreshold;
leakagerate = g->leakagerate;
inputgain = g->inputgain;
width = g->width;
height = g->height;
// TODO: good?
if (width < 1) width = 1;
if (height < 1) height = 1;
neurons.reserve(width * height);
oldNeuron n;
for (unsigned int i = 0; i < width * height; i++) {
neurons.push_back(n);
}
// TODO
for (unsigned int i = 0; i < 6; i++) {
chems[i] = 0;
}
}
void oldLobe::init() {
inited = true;
wipe();
// TODO: is this it?
}
void oldLobe::wipe() {
for (unsigned int i = 0; i < neurons.size(); i++) {
neurons[i].state = neurons[i].output = ourGene->reststate; // TODO: good?
}
}
void oldLobe::tick() {
// TODO: do something with inputgain? presumably applied to 'input', so something to do with decision lobe..
for (unsigned int i = 0; i < neurons.size(); i++) {
unsigned char out = neurons[i].state; // TODO: svrule (ourGene->staterule)..
// apply leakage rate in order to settle at rest state
if ((parent->getTicks() & parent->getParent()->calculateTickMask(leakagerate)) == 0) {
// TODO: untested
// TODO: what happens if out < ourGene->reststate? test!
out = ourGene->reststate + ((out - ourGene->reststate) * parent->getParent()->calculateMultiplier(leakagerate)) / 65536;
}
neurons[i].state = out;
if (out < threshold)
out = 0;
else
out -= threshold;
neurons[i].output = out;
}
// TODO: dendrites (ourGene->dendrite1, ourGene->dendrite2)
// TODO: data copied to perception lobe (ourGene->perceptflag - not just true/false!)
// TODO: winner takes all (ourGene->flags)
}
oldBrain::oldBrain(oldCreature *p) {
assert(p);
parent = p;
ticks = 0;
}
void oldBrain::processGenes() {
shared_ptr<genomeFile> genome = parent->getGenome();
for (vector<gene *>::iterator i = genome->genes.begin(); i != genome->genes.end(); i++) {
if (!parent->shouldProcessGene(*i)) continue;
if (typeid(**i) == typeid(oldBrainLobeGene)) {
oldBrainLobeGene *g = (oldBrainLobeGene *)*i;
oldLobe *l = new oldLobe(this, g);
lobes[lobes.size()] = l; // TODO: muh
}
}
}
void oldBrain::init() {
for (std::map<unsigned int, oldLobe *>::iterator i = lobes.begin(); i != lobes.end(); i++) {
if (!(*i).second->wasInited()) (*i).second->init();
}
}
void oldBrain::tick() {
for (std::map<unsigned int, oldLobe *>::iterator i = lobes.begin(); i != lobes.end(); i++) {
(*i).second->tick();
}
ticks++;
}
oldLobe *oldBrain::getLobeByTissue(unsigned int id) {
if (lobes.find(id) == lobes.end())
return 0;
return lobes[id];
}
/* vim: set noet: */
<commit_msg>oldBrain: silly leakagerate bugfix<commit_after>/*
* oldBrain.cpp
* openc2e
*
* Created by Alyssa Milburn on Mon Aug 13 2007.
* Copyright (c) 2007 Alyssa Milburn. All rights reserved.
*
* 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 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.
*
*/
#include "oldBrain.h"
#include "Creature.h"
/*
* svrule examples:
*
* * creatures 1:
* output:TRUE:input
*
* * creatures 2:
* random:0:chem 5:PLUS:state
* state:PLUS:type 0:MINUS:type 1
* input:TRUE:output:TRUE:suscept:move twrds:255:64
* suscept:TRUE:chem 0:TRUE:STW
*
* * canny:
* state:PLUS:state:PLUS:state
* type 0:TRUE:type 0:PLUS:type 1
*
*/
unsigned char processSVRule(oldNeuron *cell, oldDendrite *dend, uint8 *svrule, unsigned int len) {
unsigned char state = 0;
for (unsigned int i = 0; i < len; i++) {
switch (svrule[i]) {
/*
* these numbers are the C2 svrules
*
* TODO: remap the C1 svrule numbers at load so they match these
*/
case 0: // <end>
return state;
case 1: // 0
state = 0;
break;
case 2: // 1
state = 1;
break;
case 3: // 64
state = 64;
break;
case 4: // 255
state = 255;
break;
case 5: // chem0
break;
case 6: // chem1
break;
case 7: // chem2
break;
case 8: // chem3
break;
case 9: // state
state = cell->state;
break;
case 10: // output
break;
case 11: // thres
break;
case 12: // type0
break;
case 13: // type1
break;
case 14: // anded0
break;
case 15: // anded1
// unused?
break;
case 16: // input
// This comes from IMPT for the decision lobe.
break;
case 17: // conduct
// unused?
break;
case 18: // suscept
break;
case 19: // STW
break;
case 20: // LTW
// unused?
break;
case 21: // strength
// unused?
break;
case 22: // 32
// unused?
break;
case 23: // 128
// unused?
break;
case 24: // rnd const
// unused?
break;
case 25: // chem4
break;
case 26: // chem5
break;
case 27: // leak in
// unused: back/forward prop
break;
case 28: // leak out
// unused: back/forward prop
break;
case 29: // curr src leak in
// unused: back/forward prop
break;
case 30: // TRUE
if (!state) return 0;
break;
case 31: // PLUS
break;
case 32: // MINUS
break;
case 33: // TIMES
// unused?
break;
case 34: // INCR
// unused?
state++;
break;
case 35: // DECR
// unused?
state--;
break;
case 36: // FALSE
// unused?
break;
case 37: // multiply
// unused?
break;
case 38: // average
// unused?
break;
case 39: // move twrds
break;
case 40: // random
break;
case 41: // <error>
break;
}
}
return state;
}
oldLobe::oldLobe(oldBrain *b, oldBrainLobeGene *g) {
assert(b);
parent = b;
assert(g);
ourGene = g;
inited = false;
threshold = g->nominalthreshold;
leakagerate = g->leakagerate;
inputgain = g->inputgain;
width = g->width;
height = g->height;
// TODO: good?
if (width < 1) width = 1;
if (height < 1) height = 1;
neurons.reserve(width * height);
oldNeuron n;
for (unsigned int i = 0; i < width * height; i++) {
neurons.push_back(n);
}
// TODO
for (unsigned int i = 0; i < 6; i++) {
chems[i] = 0;
}
}
void oldLobe::init() {
inited = true;
wipe();
// TODO: is this it?
}
void oldLobe::wipe() {
for (unsigned int i = 0; i < neurons.size(); i++) {
neurons[i].state = neurons[i].output = ourGene->reststate; // TODO: good?
}
}
void oldLobe::tick() {
// TODO: do something with inputgain? presumably applied to 'input', so something to do with decision lobe..
for (unsigned int i = 0; i < neurons.size(); i++) {
unsigned char out = neurons[i].state; // TODO: svrule (ourGene->staterule)..
// apply leakage rate in order to settle at rest state
if ((parent->getTicks() & parent->getParent()->calculateTickMask(leakagerate / 8)) == 0) {
// TODO: untested
// TODO: what happens if out < ourGene->reststate? test!
out = ourGene->reststate + ((out - ourGene->reststate) * parent->getParent()->calculateMultiplier(leakagerate / 8)) / 65536;
}
neurons[i].state = out;
if (out < threshold)
out = 0;
else
out -= threshold;
neurons[i].output = out;
}
// TODO: dendrites (ourGene->dendrite1, ourGene->dendrite2)
// TODO: data copied to perception lobe (ourGene->perceptflag - not just true/false!)
// TODO: winner takes all (ourGene->flags)
}
oldBrain::oldBrain(oldCreature *p) {
assert(p);
parent = p;
ticks = 0;
}
void oldBrain::processGenes() {
shared_ptr<genomeFile> genome = parent->getGenome();
for (vector<gene *>::iterator i = genome->genes.begin(); i != genome->genes.end(); i++) {
if (!parent->shouldProcessGene(*i)) continue;
if (typeid(**i) == typeid(oldBrainLobeGene)) {
oldBrainLobeGene *g = (oldBrainLobeGene *)*i;
oldLobe *l = new oldLobe(this, g);
lobes[lobes.size()] = l; // TODO: muh
}
}
}
void oldBrain::init() {
for (std::map<unsigned int, oldLobe *>::iterator i = lobes.begin(); i != lobes.end(); i++) {
if (!(*i).second->wasInited()) (*i).second->init();
}
}
void oldBrain::tick() {
for (std::map<unsigned int, oldLobe *>::iterator i = lobes.begin(); i != lobes.end(); i++) {
(*i).second->tick();
}
ticks++;
}
oldLobe *oldBrain::getLobeByTissue(unsigned int id) {
if (lobes.find(id) == lobes.end())
return 0;
return lobes[id];
}
/* vim: set noet: */
<|endoftext|> |
<commit_before>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <modules/fieldlinessequence/rendering/renderablefieldlinessequence.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/util/updatestructures.h>
#include <ghoul/opengl/programobject.h>
#include <ghoul/opengl/textureunit.h>
namespace {
std::string _loggerCat = "RenderableFieldlinesSequence";
const GLuint VaPosition = 0; // MUST CORRESPOND TO THE SHADER PROGRAM
const GLuint VaColor = 1; // MUST CORRESPOND TO THE SHADER PROGRAM
const GLuint VaMasking = 2; // MUST CORRESPOND TO THE SHADER PROGRAM
} // namespace
namespace openspace {
void RenderableFieldlinesSequence::deinitialize() {
glDeleteVertexArrays(1, &_vertexArrayObject);
_vertexArrayObject = 0;
glDeleteBuffers(1, &_vertexPositionBuffer);
_vertexPositionBuffer = 0;
glDeleteBuffers(1, &_vertexColorBuffer);
_vertexColorBuffer = 0;
glDeleteBuffers(1, &_vertexMaskingBuffer);
_vertexMaskingBuffer = 0;
RenderEngine& renderEngine = OsEng.renderEngine();
if (_shaderProgram) {
renderEngine.removeRenderProgram(_shaderProgram);
_shaderProgram = nullptr;
}
// Stall main thread until thread that's loading states is done!
while (_isLoadingStateFromDisk) {
LWARNING("TRYING TO DESTROY CLASS WHEN A THREAD USING IT IS STILL ACTIVE");
}
}
bool RenderableFieldlinesSequence::isReady() const {
return _isReady;
}
void RenderableFieldlinesSequence::render(const RenderData& data, RendererTasks&) {
if (_activeTriggerTimeIndex != -1) {
_shaderProgram->activate();
// Calculate Model View MatrixProjection
const glm::dmat4 rotMat = glm::dmat4(data.modelTransform.rotation);
const glm::dmat4 modelMat =
glm::translate(glm::dmat4(1.0), data.modelTransform.translation) *
rotMat *
glm::dmat4(glm::scale(glm::dmat4(1), glm::dvec3(data.modelTransform.scale)));
const glm::dmat4 modelViewMat = data.camera.combinedViewMatrix() * modelMat;
_shaderProgram->setUniform("modelViewProjection",
data.camera.sgctInternal.projectionMatrix() * glm::mat4(modelViewMat));
_shaderProgram->setUniform("colorMethod", _pColorMethod);
_shaderProgram->setUniform("lineColor", _pColorUniform);
_shaderProgram->setUniform("usingDomain", _pDomainEnabled);
_shaderProgram->setUniform("usingMasking", _pMaskingEnabled);
if (_pColorMethod == ColorMethod::ByQuantity) {
ghoul::opengl::TextureUnit textureUnit;
textureUnit.activate();
_transferFunction->bind(); // Calls update internally
_shaderProgram->setUniform("colorTable", textureUnit);
_shaderProgram->setUniform("colorTableRange",
_colorTableRanges[_pColorQuantity]);
}
if (_pMaskingEnabled) {
_shaderProgram->setUniform("maskingRange", _maskingRanges[_pMaskingQuantity]);
}
_shaderProgram->setUniform("domainLimR", _pDomainR.value() * _scalingFactor);
_shaderProgram->setUniform("domainLimX", _pDomainX.value() * _scalingFactor);
_shaderProgram->setUniform("domainLimY", _pDomainY.value() * _scalingFactor);
_shaderProgram->setUniform("domainLimZ", _pDomainZ.value() * _scalingFactor);
// Flow/Particles
_shaderProgram->setUniform("flowColor", _pFlowColor);
_shaderProgram->setUniform("usingParticles", _pFlowEnabled);
_shaderProgram->setUniform("particleSize", _pFlowParticleSize);
_shaderProgram->setUniform("particleSpacing", _pFlowParticleSpacing);
_shaderProgram->setUniform("particleSpeed", _pFlowSpeed);
_shaderProgram->setUniform("time", OsEng.runTime() * (_pFlowReversed ? -1 : 1));
bool additiveBlending = false;
if (_pColorABlendEnabled) {
const auto renderer = OsEng.renderEngine().rendererImplementation();
bool usingFBufferRenderer = renderer ==
RenderEngine::RendererImplementation::Framebuffer;
bool usingABufferRenderer = renderer ==
RenderEngine::RendererImplementation::ABuffer;
if (usingABufferRenderer) {
_shaderProgram->setUniform("usingAdditiveBlending", _pColorABlendEnabled);
}
additiveBlending = usingFBufferRenderer;
if (additiveBlending) {
glDepthMask(false);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
}
}
glBindVertexArray(_vertexArrayObject);
glMultiDrawArrays(
GL_LINE_STRIP, //_drawingOutputType,
_states[_activeStateIndex].lineStart().data(),
_states[_activeStateIndex].lineCount().data(),
static_cast<GLsizei>(_states[_activeStateIndex].lineStart().size())
);
glBindVertexArray(0);
_shaderProgram->deactivate();
if (additiveBlending) {
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDepthMask(true);
}
}
}
void RenderableFieldlinesSequence::update(const UpdateData& data) {
// This node shouldn't do anything if its been disabled from the gui!
if (!_enabled) {
return;
}
if (_shaderProgram->isDirty()) {
_shaderProgram->rebuildFromFile();
}
const double currentTime = data.time.j2000Seconds();
// Check if current time in OpenSpace is within sequence interval
if (isWithinSequenceInterval(currentTime)) {
const int nextIdx = _activeTriggerTimeIndex + 1;
if (_activeTriggerTimeIndex < 0 // true => Previous frame was not within the sequence interval
|| currentTime < _startTimes[_activeTriggerTimeIndex] // true => OpenSpace has stepped back to a time represented by another state
|| (nextIdx < _nStates && currentTime >= _startTimes[nextIdx])) { // true => OpenSpace has stepped forward to a time represented by another state
updateActiveTriggerTimeIndex(currentTime);
if (_loadingStatesDynamically) {
_mustLoadNewStateFromDisk = true;
} else {
_needsUpdate = true;
_activeStateIndex = _activeTriggerTimeIndex;
}
} // else {we're still in same state as previous frame (no changes needed)}
} else {
// Not in interval => set everything to false
_activeTriggerTimeIndex = -1;
_mustLoadNewStateFromDisk = false;
_needsUpdate = false;
}
if (_mustLoadNewStateFromDisk) {
if (!_isLoadingStateFromDisk && !_newStateIsReady) {
_isLoadingStateFromDisk = true;
_mustLoadNewStateFromDisk = false;
const std::string filePath = _sourceFiles[_activeTriggerTimeIndex];
std::thread readBinaryThread([this, filePath] {
this->readNewState(filePath);
});
readBinaryThread.detach();
}
}
if (_needsUpdate || _newStateIsReady) {
if (_loadingStatesDynamically) {
_states[0] = std::move(*_newState);
}
updateVertexPositionBuffer();
if (_states[_activeStateIndex].nExtraQuantities() > 0) {
_shouldUpdateColorBuffer = true;
_shouldUpdateMaskingBuffer = true;
}
// Everything is set and ready for rendering!
_needsUpdate = false;
_newStateIsReady = false;
}
if (_shouldUpdateColorBuffer) {
updateVertexColorBuffer();
_shouldUpdateColorBuffer = false;
}
if (_shouldUpdateMaskingBuffer) {
updateVertexMaskingBuffer();
_shouldUpdateMaskingBuffer = false;
}
}
inline bool RenderableFieldlinesSequence::isWithinSequenceInterval(const double currentTime) const {
return (currentTime >= _startTimes[0]) && (currentTime < _sequenceEndTime);
}
// Assumes we already know that currentTime is within the sequence interval
void RenderableFieldlinesSequence::updateActiveTriggerTimeIndex(const double currentTime) {
auto iter = std::upper_bound(_startTimes.begin(), _startTimes.end(), currentTime);
if (iter != _startTimes.end()) {
if ( iter != _startTimes.begin()) {
_activeTriggerTimeIndex =
static_cast<int>(std::distance(_startTimes.begin(), iter)) - 1;
} else {
_activeTriggerTimeIndex = 0;
}
} else {
_activeTriggerTimeIndex = static_cast<int>(_nStates) - 1;
}
}
// Reading state from disk. Must be thread safe!
void RenderableFieldlinesSequence::readNewState(const std::string& filePath) {
_newState = std::make_unique<FieldlinesState>();
if (_newState->loadStateFromOsfls(filePath)) {
_newStateIsReady = true;
}
_isLoadingStateFromDisk = false;
}
// Unbind buffers and arrays
inline void unbindGL() {
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
void RenderableFieldlinesSequence::updateVertexPositionBuffer() {
glBindVertexArray(_vertexArrayObject);
glBindBuffer(GL_ARRAY_BUFFER, _vertexPositionBuffer);
const std::vector<glm::vec3>& vertexPosVec =
_states[_activeStateIndex].vertexPositions();
glBufferData(GL_ARRAY_BUFFER, vertexPosVec.size() * sizeof(glm::vec3),
&vertexPosVec.front(), GL_STATIC_DRAW);
glEnableVertexAttribArray(VaPosition);
glVertexAttribPointer(VaPosition, 3, GL_FLOAT, GL_FALSE, 0, 0);
unbindGL();
}
void RenderableFieldlinesSequence::updateVertexColorBuffer() {
glBindVertexArray(_vertexArrayObject);
glBindBuffer(GL_ARRAY_BUFFER, _vertexColorBuffer);
bool isSuccessful;
const std::vector<float>& quantityVec =
_states[_activeStateIndex].extraQuantity(_pColorQuantity, isSuccessful);
if (isSuccessful) {
glBufferData(GL_ARRAY_BUFFER, quantityVec.size() * sizeof(float),
&quantityVec.front(), GL_STATIC_DRAW);
glEnableVertexAttribArray(VaColor);
glVertexAttribPointer(VaColor, 1, GL_FLOAT, GL_FALSE, 0, 0);
unbindGL();
}
}
void RenderableFieldlinesSequence::updateVertexMaskingBuffer() {
glBindVertexArray(_vertexArrayObject);
glBindBuffer(GL_ARRAY_BUFFER, _vertexMaskingBuffer);
bool isSuccessful;
const std::vector<float>& quantityVec =
_states[_activeStateIndex].extraQuantity(_pMaskingQuantity, isSuccessful);
if (isSuccessful) {
glBufferData(GL_ARRAY_BUFFER, quantityVec.size() * sizeof(float),
&quantityVec.front(), GL_STATIC_DRAW);
glEnableVertexAttribArray(VaMasking);
glVertexAttribPointer(VaMasking, 1, GL_FLOAT, GL_FALSE, 0, 0);
unbindGL();
}
}
} // namespace openspace
<commit_msg>Compile fix to adjust to runTime method not existing anymore<commit_after>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <modules/fieldlinessequence/rendering/renderablefieldlinessequence.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/engine/wrapper/windowwrapper.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/util/updatestructures.h>
#include <ghoul/opengl/programobject.h>
#include <ghoul/opengl/textureunit.h>
namespace {
std::string _loggerCat = "RenderableFieldlinesSequence";
const GLuint VaPosition = 0; // MUST CORRESPOND TO THE SHADER PROGRAM
const GLuint VaColor = 1; // MUST CORRESPOND TO THE SHADER PROGRAM
const GLuint VaMasking = 2; // MUST CORRESPOND TO THE SHADER PROGRAM
} // namespace
namespace openspace {
void RenderableFieldlinesSequence::deinitialize() {
glDeleteVertexArrays(1, &_vertexArrayObject);
_vertexArrayObject = 0;
glDeleteBuffers(1, &_vertexPositionBuffer);
_vertexPositionBuffer = 0;
glDeleteBuffers(1, &_vertexColorBuffer);
_vertexColorBuffer = 0;
glDeleteBuffers(1, &_vertexMaskingBuffer);
_vertexMaskingBuffer = 0;
RenderEngine& renderEngine = OsEng.renderEngine();
if (_shaderProgram) {
renderEngine.removeRenderProgram(_shaderProgram);
_shaderProgram = nullptr;
}
// Stall main thread until thread that's loading states is done!
while (_isLoadingStateFromDisk) {
LWARNING("TRYING TO DESTROY CLASS WHEN A THREAD USING IT IS STILL ACTIVE");
}
}
bool RenderableFieldlinesSequence::isReady() const {
return _isReady;
}
void RenderableFieldlinesSequence::render(const RenderData& data, RendererTasks&) {
if (_activeTriggerTimeIndex != -1) {
_shaderProgram->activate();
// Calculate Model View MatrixProjection
const glm::dmat4 rotMat = glm::dmat4(data.modelTransform.rotation);
const glm::dmat4 modelMat =
glm::translate(glm::dmat4(1.0), data.modelTransform.translation) *
rotMat *
glm::dmat4(glm::scale(glm::dmat4(1), glm::dvec3(data.modelTransform.scale)));
const glm::dmat4 modelViewMat = data.camera.combinedViewMatrix() * modelMat;
_shaderProgram->setUniform("modelViewProjection",
data.camera.sgctInternal.projectionMatrix() * glm::mat4(modelViewMat));
_shaderProgram->setUniform("colorMethod", _pColorMethod);
_shaderProgram->setUniform("lineColor", _pColorUniform);
_shaderProgram->setUniform("usingDomain", _pDomainEnabled);
_shaderProgram->setUniform("usingMasking", _pMaskingEnabled);
if (_pColorMethod == ColorMethod::ByQuantity) {
ghoul::opengl::TextureUnit textureUnit;
textureUnit.activate();
_transferFunction->bind(); // Calls update internally
_shaderProgram->setUniform("colorTable", textureUnit);
_shaderProgram->setUniform("colorTableRange",
_colorTableRanges[_pColorQuantity]);
}
if (_pMaskingEnabled) {
_shaderProgram->setUniform("maskingRange", _maskingRanges[_pMaskingQuantity]);
}
_shaderProgram->setUniform("domainLimR", _pDomainR.value() * _scalingFactor);
_shaderProgram->setUniform("domainLimX", _pDomainX.value() * _scalingFactor);
_shaderProgram->setUniform("domainLimY", _pDomainY.value() * _scalingFactor);
_shaderProgram->setUniform("domainLimZ", _pDomainZ.value() * _scalingFactor);
// Flow/Particles
_shaderProgram->setUniform("flowColor", _pFlowColor);
_shaderProgram->setUniform("usingParticles", _pFlowEnabled);
_shaderProgram->setUniform("particleSize", _pFlowParticleSize);
_shaderProgram->setUniform("particleSpacing", _pFlowParticleSpacing);
_shaderProgram->setUniform("particleSpeed", _pFlowSpeed);
_shaderProgram->setUniform(
"time",
OsEng.windowWrapper().applicationTime() * (_pFlowReversed ? -1 : 1)
);
bool additiveBlending = false;
if (_pColorABlendEnabled) {
const auto renderer = OsEng.renderEngine().rendererImplementation();
bool usingFBufferRenderer = renderer ==
RenderEngine::RendererImplementation::Framebuffer;
bool usingABufferRenderer = renderer ==
RenderEngine::RendererImplementation::ABuffer;
if (usingABufferRenderer) {
_shaderProgram->setUniform("usingAdditiveBlending", _pColorABlendEnabled);
}
additiveBlending = usingFBufferRenderer;
if (additiveBlending) {
glDepthMask(false);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
}
}
glBindVertexArray(_vertexArrayObject);
glMultiDrawArrays(
GL_LINE_STRIP, //_drawingOutputType,
_states[_activeStateIndex].lineStart().data(),
_states[_activeStateIndex].lineCount().data(),
static_cast<GLsizei>(_states[_activeStateIndex].lineStart().size())
);
glBindVertexArray(0);
_shaderProgram->deactivate();
if (additiveBlending) {
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDepthMask(true);
}
}
}
void RenderableFieldlinesSequence::update(const UpdateData& data) {
// This node shouldn't do anything if its been disabled from the gui!
if (!_enabled) {
return;
}
if (_shaderProgram->isDirty()) {
_shaderProgram->rebuildFromFile();
}
const double currentTime = data.time.j2000Seconds();
// Check if current time in OpenSpace is within sequence interval
if (isWithinSequenceInterval(currentTime)) {
const int nextIdx = _activeTriggerTimeIndex + 1;
if (_activeTriggerTimeIndex < 0 // true => Previous frame was not within the sequence interval
|| currentTime < _startTimes[_activeTriggerTimeIndex] // true => OpenSpace has stepped back to a time represented by another state
|| (nextIdx < _nStates && currentTime >= _startTimes[nextIdx])) { // true => OpenSpace has stepped forward to a time represented by another state
updateActiveTriggerTimeIndex(currentTime);
if (_loadingStatesDynamically) {
_mustLoadNewStateFromDisk = true;
} else {
_needsUpdate = true;
_activeStateIndex = _activeTriggerTimeIndex;
}
} // else {we're still in same state as previous frame (no changes needed)}
} else {
// Not in interval => set everything to false
_activeTriggerTimeIndex = -1;
_mustLoadNewStateFromDisk = false;
_needsUpdate = false;
}
if (_mustLoadNewStateFromDisk) {
if (!_isLoadingStateFromDisk && !_newStateIsReady) {
_isLoadingStateFromDisk = true;
_mustLoadNewStateFromDisk = false;
const std::string filePath = _sourceFiles[_activeTriggerTimeIndex];
std::thread readBinaryThread([this, filePath] {
this->readNewState(filePath);
});
readBinaryThread.detach();
}
}
if (_needsUpdate || _newStateIsReady) {
if (_loadingStatesDynamically) {
_states[0] = std::move(*_newState);
}
updateVertexPositionBuffer();
if (_states[_activeStateIndex].nExtraQuantities() > 0) {
_shouldUpdateColorBuffer = true;
_shouldUpdateMaskingBuffer = true;
}
// Everything is set and ready for rendering!
_needsUpdate = false;
_newStateIsReady = false;
}
if (_shouldUpdateColorBuffer) {
updateVertexColorBuffer();
_shouldUpdateColorBuffer = false;
}
if (_shouldUpdateMaskingBuffer) {
updateVertexMaskingBuffer();
_shouldUpdateMaskingBuffer = false;
}
}
inline bool RenderableFieldlinesSequence::isWithinSequenceInterval(const double currentTime) const {
return (currentTime >= _startTimes[0]) && (currentTime < _sequenceEndTime);
}
// Assumes we already know that currentTime is within the sequence interval
void RenderableFieldlinesSequence::updateActiveTriggerTimeIndex(const double currentTime) {
auto iter = std::upper_bound(_startTimes.begin(), _startTimes.end(), currentTime);
if (iter != _startTimes.end()) {
if ( iter != _startTimes.begin()) {
_activeTriggerTimeIndex =
static_cast<int>(std::distance(_startTimes.begin(), iter)) - 1;
} else {
_activeTriggerTimeIndex = 0;
}
} else {
_activeTriggerTimeIndex = static_cast<int>(_nStates) - 1;
}
}
// Reading state from disk. Must be thread safe!
void RenderableFieldlinesSequence::readNewState(const std::string& filePath) {
_newState = std::make_unique<FieldlinesState>();
if (_newState->loadStateFromOsfls(filePath)) {
_newStateIsReady = true;
}
_isLoadingStateFromDisk = false;
}
// Unbind buffers and arrays
inline void unbindGL() {
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
void RenderableFieldlinesSequence::updateVertexPositionBuffer() {
glBindVertexArray(_vertexArrayObject);
glBindBuffer(GL_ARRAY_BUFFER, _vertexPositionBuffer);
const std::vector<glm::vec3>& vertexPosVec =
_states[_activeStateIndex].vertexPositions();
glBufferData(GL_ARRAY_BUFFER, vertexPosVec.size() * sizeof(glm::vec3),
&vertexPosVec.front(), GL_STATIC_DRAW);
glEnableVertexAttribArray(VaPosition);
glVertexAttribPointer(VaPosition, 3, GL_FLOAT, GL_FALSE, 0, 0);
unbindGL();
}
void RenderableFieldlinesSequence::updateVertexColorBuffer() {
glBindVertexArray(_vertexArrayObject);
glBindBuffer(GL_ARRAY_BUFFER, _vertexColorBuffer);
bool isSuccessful;
const std::vector<float>& quantityVec =
_states[_activeStateIndex].extraQuantity(_pColorQuantity, isSuccessful);
if (isSuccessful) {
glBufferData(GL_ARRAY_BUFFER, quantityVec.size() * sizeof(float),
&quantityVec.front(), GL_STATIC_DRAW);
glEnableVertexAttribArray(VaColor);
glVertexAttribPointer(VaColor, 1, GL_FLOAT, GL_FALSE, 0, 0);
unbindGL();
}
}
void RenderableFieldlinesSequence::updateVertexMaskingBuffer() {
glBindVertexArray(_vertexArrayObject);
glBindBuffer(GL_ARRAY_BUFFER, _vertexMaskingBuffer);
bool isSuccessful;
const std::vector<float>& quantityVec =
_states[_activeStateIndex].extraQuantity(_pMaskingQuantity, isSuccessful);
if (isSuccessful) {
glBufferData(GL_ARRAY_BUFFER, quantityVec.size() * sizeof(float),
&quantityVec.front(), GL_STATIC_DRAW);
glEnableVertexAttribArray(VaMasking);
glVertexAttribPointer(VaMasking, 1, GL_FLOAT, GL_FALSE, 0, 0);
unbindGL();
}
}
} // namespace openspace
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: EncryptionData.hxx,v $
*
* $Revision: 1.1 $
*
* last change: $Author: mtg $ $Date: 2001-04-27 14:56:52 $
*
* 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): Martin Gallwey ([email protected])
*
*
************************************************************************/
#ifndef _ENCRYPTION_DATA_HXX_
#define _ENCRYPTION_DATA_HXX_
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
class EncryptionData : public cppu::OWeakObject
{
public:
com::sun::star::uno::Sequence < sal_Int8 > aKey;
com::sun::star::uno::Sequence < sal_Int8 > aSalt;
com::sun::star::uno::Sequence < sal_Int8 > aInitVector;
sal_Int64 nIterationCount;
EncryptionData(): nIterationCount ( 0 ){}
};
#endif
<commit_msg>Make IterationCount 32 bit<commit_after>/*************************************************************************
*
* $RCSfile: EncryptionData.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: mtg $ $Date: 2001-05-08 13:46:25 $
*
* 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): Martin Gallwey ([email protected])
*
*
************************************************************************/
#ifndef _ENCRYPTION_DATA_HXX_
#define _ENCRYPTION_DATA_HXX_
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
class EncryptionData : public cppu::OWeakObject
{
public:
// On export aKey holds the derived key
// On import aKey holds the hash of the user enterred key
com::sun::star::uno::Sequence < sal_Int8 > aKey;
com::sun::star::uno::Sequence < sal_uInt8 > aSalt, aInitVector;
sal_Int32 nIterationCount;
EncryptionData(): nIterationCount ( 0 ){}
};
#endif
<|endoftext|> |
<commit_before>#include "SearchManagerPostProcessor.h"
//#include <ranking-manager/RankingManager.h>
#include <mining-manager/product-ranker/ProductRankerFactory.h>
#include <mining-manager/product-ranker/ProductRanker.h>
#include <common/SFLogger.h>
#include <util/get.h>
#include <util/ClockTimer.h>
#include <fstream>
#include <algorithm>
#include <boost/scoped_ptr.hpp>
const std::string RANK_PROPERTY("_rank");
namespace sf1r {
bool isProductRanking(const KeywordSearchActionItem& actionItem)
{
if (actionItem.searchingMode_.mode_ == SearchingMode::KNN)
return false;
const KeywordSearchActionItem::SortPriorityList& sortPropertyList = actionItem.sortPriorityList_;
if (sortPropertyList.empty())
return true;
for (KeywordSearchActionItem::SortPriorityList::const_iterator it = sortPropertyList.begin();
it != sortPropertyList.end(); ++it)
{
std::string fieldNameL = it->first;
boost::to_lower(fieldNameL);
if (fieldNameL == RANK_PROPERTY)
return true;
}
return false;
}
SearchManagerPostProcessor::SearchManagerPostProcessor()
:productRankerFactory_(NULL)
{
}
SearchManagerPostProcessor::~SearchManagerPostProcessor()
{
}
bool SearchManagerPostProcessor::rerank(
const KeywordSearchActionItem& actionItem,
KeywordSearchResult& resultItem)
{
if (productRankerFactory_ &&
resultItem.topKCustomRankScoreList_.empty() &&
isProductRanking(actionItem))
{
izenelib::util::ClockTimer timer;
ProductRankingParam rankingParam(actionItem.env_.queryString_,
resultItem.topKDocs_, resultItem.topKRankScoreList_);
boost::scoped_ptr<ProductRanker> productRanker(
productRankerFactory_->createProductRanker(rankingParam));
productRanker->rank();
LOG(INFO) << "topK doc num: " << resultItem.topKDocs_.size()
<< ", product ranking costs: " << timer.elapsed() << " seconds";
return true;
}
return false;
}
}
<commit_msg>prevent rerank for SUFFIX_MATCH search mode<commit_after>#include "SearchManagerPostProcessor.h"
//#include <ranking-manager/RankingManager.h>
#include <mining-manager/product-ranker/ProductRankerFactory.h>
#include <mining-manager/product-ranker/ProductRanker.h>
#include <common/SFLogger.h>
#include <util/get.h>
#include <util/ClockTimer.h>
#include <fstream>
#include <algorithm>
#include <boost/scoped_ptr.hpp>
const std::string RANK_PROPERTY("_rank");
namespace sf1r {
bool isProductRanking(const KeywordSearchActionItem& actionItem)
{
if (actionItem.searchingMode_.mode_ == SearchingMode::KNN)
return false;
const KeywordSearchActionItem::SortPriorityList& sortPropertyList = actionItem.sortPriorityList_;
if (sortPropertyList.empty())
return true;
for (KeywordSearchActionItem::SortPriorityList::const_iterator it = sortPropertyList.begin();
it != sortPropertyList.end(); ++it)
{
std::string fieldNameL = it->first;
boost::to_lower(fieldNameL);
if (fieldNameL == RANK_PROPERTY)
return true;
}
return false;
}
SearchManagerPostProcessor::SearchManagerPostProcessor()
:productRankerFactory_(NULL)
{
}
SearchManagerPostProcessor::~SearchManagerPostProcessor()
{
}
bool SearchManagerPostProcessor::rerank(
const KeywordSearchActionItem& actionItem,
KeywordSearchResult& resultItem)
{
if (actionItem.searchingMode_.mode_ != SearchingMode::SUFFIX_MATCH
&& productRankerFactory_
&& resultItem.topKCustomRankScoreList_.empty()
&& isProductRanking(actionItem))
{
izenelib::util::ClockTimer timer;
ProductRankingParam rankingParam(actionItem.env_.queryString_,
resultItem.topKDocs_, resultItem.topKRankScoreList_);
boost::scoped_ptr<ProductRanker> productRanker(
productRankerFactory_->createProductRanker(rankingParam));
productRanker->rank();
LOG(INFO) << "topK doc num: " << resultItem.topKDocs_.size()
<< ", product ranking costs: " << timer.elapsed() << " seconds";
return true;
}
return false;
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/math/smoothing_spline/active_set_spline_2d_solver.h"
#include <algorithm>
#include "Eigen/Core"
#include "cyber/common/log.h"
#include "modules/common/math/qp_solver/qp_solver_gflags.h"
#include "modules/common/time/time.h"
#include "modules/planning/common/planning_gflags.h"
namespace apollo {
namespace planning {
namespace {
constexpr double kRoadBound = 1e10;
}
using apollo::common::time::Clock;
using Eigen::MatrixXd;
ActiveSetSpline2dSolver::ActiveSetSpline2dSolver(
const std::vector<double>& t_knots, const uint32_t order)
: Spline2dSolver(t_knots, order) {}
void ActiveSetSpline2dSolver::Reset(const std::vector<double>& t_knots,
const uint32_t order) {
spline_ = Spline2d(t_knots, order);
kernel_ = Spline2dKernel(t_knots, order);
constraint_ = Spline2dConstraint(t_knots, order);
}
// customize setup
Spline2dConstraint* ActiveSetSpline2dSolver::mutable_constraint() {
return &constraint_;
}
Spline2dKernel* ActiveSetSpline2dSolver::mutable_kernel() { return &kernel_; }
Spline2d* ActiveSetSpline2dSolver::mutable_spline() { return &spline_; }
bool ActiveSetSpline2dSolver::Solve() {
const MatrixXd& kernel_matrix = kernel_.kernel_matrix();
const MatrixXd& offset = kernel_.offset();
const MatrixXd& inequality_constraint_matrix =
constraint_.inequality_constraint().constraint_matrix();
const MatrixXd& inequality_constraint_boundary =
constraint_.inequality_constraint().constraint_boundary();
const MatrixXd& equality_constraint_matrix =
constraint_.equality_constraint().constraint_matrix();
const MatrixXd& equality_constraint_boundary =
constraint_.equality_constraint().constraint_boundary();
if (kernel_matrix.rows() != kernel_matrix.cols()) {
AERROR << "kernel_matrix.rows() [" << kernel_matrix.rows()
<< "] and kernel_matrix.cols() [" << kernel_matrix.cols()
<< "] should be identical.";
return false;
}
int num_param = kernel_matrix.rows();
int num_constraint =
equality_constraint_matrix.rows() + inequality_constraint_matrix.rows();
ADEBUG << "num_param: " << num_param
<< ", last_num_param_: " << last_num_param_;
ADEBUG << "num_constraint: " << num_constraint
<< ", last_num_constraint_: " << last_num_constraint_;
bool use_hotstart =
last_problem_success_ &&
(FLAGS_enable_sqp_solver && sqp_solver_ != nullptr &&
num_param == last_num_param_ && num_constraint == last_num_constraint_);
if (!use_hotstart) {
sqp_solver_.reset(new ::qpOASES::SQProblem(num_param, num_constraint,
::qpOASES::HST_UNKNOWN));
::qpOASES::Options my_options;
my_options.enableCholeskyRefactorisation = 10;
my_options.epsNum = FLAGS_default_qp_smoothing_eps_num;
my_options.epsDen = FLAGS_default_qp_smoothing_eps_den;
my_options.epsIterRef = FLAGS_default_qp_smoothing_eps_iter_ref;
sqp_solver_->setOptions(my_options);
if (!FLAGS_default_enable_active_set_debug_info) {
sqp_solver_->setPrintLevel(qpOASES::PL_NONE);
}
}
// definition of qpOASESproblem
const int kNumOfMatrixElements = kernel_matrix.rows() * kernel_matrix.cols();
double h_matrix[kNumOfMatrixElements]; // NOLINT
memset(h_matrix, 0, sizeof h_matrix);
const int kNumOfOffsetRows = offset.rows();
double g_matrix[kNumOfOffsetRows]; // NOLINT
memset(g_matrix, 0, sizeof g_matrix);
int index = 0;
for (int r = 0; r < kernel_matrix.rows(); ++r) {
g_matrix[r] = offset(r, 0);
for (int c = 0; c < kernel_matrix.cols(); ++c) {
h_matrix[index++] = kernel_matrix(r, c);
}
}
DCHECK_EQ(index, kernel_matrix.rows() * kernel_matrix.cols());
// search space lower bound and uppper bound
double lower_bound[num_param]; // NOLINT
double upper_bound[num_param]; // NOLINT
memset(lower_bound, 0, sizeof lower_bound);
memset(upper_bound, 0, sizeof upper_bound);
const double l_lower_bound_ = -kRoadBound;
const double l_upper_bound_ = kRoadBound;
for (int i = 0; i < num_param; ++i) {
lower_bound[i] = l_lower_bound_;
upper_bound[i] = l_upper_bound_;
}
// constraint matrix construction
double affine_constraint_matrix[num_param * num_constraint]; // NOLINT
memset(affine_constraint_matrix, 0, sizeof affine_constraint_matrix);
double constraint_lower_bound[num_constraint]; // NOLINT
double constraint_upper_bound[num_constraint]; // NOLINT
memset(constraint_lower_bound, 0, sizeof constraint_lower_bound);
memset(constraint_upper_bound, 0, sizeof constraint_upper_bound);
index = 0;
for (int r = 0; r < equality_constraint_matrix.rows(); ++r) {
constraint_lower_bound[r] = equality_constraint_boundary(r, 0);
constraint_upper_bound[r] = equality_constraint_boundary(r, 0);
for (int c = 0; c < num_param; ++c) {
affine_constraint_matrix[index++] = equality_constraint_matrix(r, c);
}
}
DCHECK_EQ(index, equality_constraint_matrix.rows() * num_param);
const double constraint_upper_bound_ = kRoadBound;
for (int r = 0; r < inequality_constraint_matrix.rows(); ++r) {
constraint_lower_bound[r + equality_constraint_boundary.rows()] =
inequality_constraint_boundary(r, 0);
constraint_upper_bound[r + equality_constraint_boundary.rows()] =
constraint_upper_bound_;
for (int c = 0; c < num_param; ++c) {
affine_constraint_matrix[index++] = inequality_constraint_matrix(r, c);
}
}
DCHECK_EQ(index, equality_constraint_matrix.rows() * num_param +
inequality_constraint_boundary.rows() * num_param);
// initialize problem
int max_iter = std::max(FLAGS_default_qp_iteration_num, num_constraint);
::qpOASES::returnValue ret;
const double start_timestamp = Clock::NowInSeconds();
if (use_hotstart) {
ADEBUG << "ActiveSetSpline2dSolver is using SQP hotstart.";
ret = sqp_solver_->hotstart(
h_matrix, g_matrix, affine_constraint_matrix, lower_bound, upper_bound,
constraint_lower_bound, constraint_upper_bound, max_iter);
if (ret != qpOASES::SUCCESSFUL_RETURN) {
AERROR << "Fail to hotstart spline 2d, will use re-init instead.";
ret = sqp_solver_->init(h_matrix, g_matrix, affine_constraint_matrix,
lower_bound, upper_bound, constraint_lower_bound,
constraint_upper_bound, max_iter);
}
} else {
AINFO << "ActiveSetSpline2dSolver is NOT using SQP hotstart.";
ret = sqp_solver_->init(h_matrix, g_matrix, affine_constraint_matrix,
lower_bound, upper_bound, constraint_lower_bound,
constraint_upper_bound, max_iter);
}
const double end_timestamp = Clock::NowInSeconds();
ADEBUG << "ActiveSetSpline2dSolver QP time: "
<< (end_timestamp - start_timestamp) * 1000 << " ms.";
ADEBUG << "return status is" << getSimpleStatus(ret);
if (ret != qpOASES::SUCCESSFUL_RETURN) {
if (ret == qpOASES::RET_MAX_NWSR_REACHED) {
AERROR << "qpOASES solver failed due to reached max iteration";
} else {
AERROR << "qpOASES solver failed due to infeasibility or other internal "
"reasons:"
<< ret;
}
last_problem_success_ = false;
return false;
}
last_problem_success_ = true;
double result[num_param]; // NOLINT
memset(result, 0, sizeof result);
sqp_solver_->getPrimalSolution(result);
MatrixXd solved_params = MatrixXd::Zero(num_param, 1);
for (int i = 0; i < num_param; ++i) {
solved_params(i, 0) = result[i];
}
last_num_param_ = num_param;
last_num_constraint_ = num_constraint;
return spline_.set_splines(solved_params, spline_.spline_order());
}
// extract
const Spline2d& ActiveSetSpline2dSolver::spline() const { return spline_; }
} // namespace planning
} // namespace apollo
<commit_msg>planning: fix active_set_spline_2d_solver compile warning.<commit_after>/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/math/smoothing_spline/active_set_spline_2d_solver.h"
#include <algorithm>
#include "Eigen/Core"
#include "cyber/common/log.h"
#include "modules/common/math/qp_solver/qp_solver_gflags.h"
#include "modules/common/time/time.h"
#include "modules/planning/common/planning_gflags.h"
namespace apollo {
namespace planning {
namespace {
constexpr double kRoadBound = 1e10;
}
using apollo::common::time::Clock;
using Eigen::MatrixXd;
ActiveSetSpline2dSolver::ActiveSetSpline2dSolver(
const std::vector<double>& t_knots, const uint32_t order)
: Spline2dSolver(t_knots, order) {}
void ActiveSetSpline2dSolver::Reset(const std::vector<double>& t_knots,
const uint32_t order) {
spline_ = Spline2d(t_knots, order);
kernel_ = Spline2dKernel(t_knots, order);
constraint_ = Spline2dConstraint(t_knots, order);
}
// customize setup
Spline2dConstraint* ActiveSetSpline2dSolver::mutable_constraint() {
return &constraint_;
}
Spline2dKernel* ActiveSetSpline2dSolver::mutable_kernel() { return &kernel_; }
Spline2d* ActiveSetSpline2dSolver::mutable_spline() { return &spline_; }
bool ActiveSetSpline2dSolver::Solve() {
const MatrixXd& kernel_matrix = kernel_.kernel_matrix();
const MatrixXd& offset = kernel_.offset();
const MatrixXd& inequality_constraint_matrix =
constraint_.inequality_constraint().constraint_matrix();
const MatrixXd& inequality_constraint_boundary =
constraint_.inequality_constraint().constraint_boundary();
const MatrixXd& equality_constraint_matrix =
constraint_.equality_constraint().constraint_matrix();
const MatrixXd& equality_constraint_boundary =
constraint_.equality_constraint().constraint_boundary();
if (kernel_matrix.rows() != kernel_matrix.cols()) {
AERROR << "kernel_matrix.rows() [" << kernel_matrix.rows()
<< "] and kernel_matrix.cols() [" << kernel_matrix.cols()
<< "] should be identical.";
return false;
}
int num_param = static_cast<int>(kernel_matrix.rows());
int num_constraint = static_cast<int>(equality_constraint_matrix.rows() +
inequality_constraint_matrix.rows());
ADEBUG << "num_param: " << num_param
<< ", last_num_param_: " << last_num_param_;
ADEBUG << "num_constraint: " << num_constraint
<< ", last_num_constraint_: " << last_num_constraint_;
bool use_hotstart =
last_problem_success_ &&
(FLAGS_enable_sqp_solver && sqp_solver_ != nullptr &&
num_param == last_num_param_ && num_constraint == last_num_constraint_);
if (!use_hotstart) {
sqp_solver_.reset(new ::qpOASES::SQProblem(num_param, num_constraint,
::qpOASES::HST_UNKNOWN));
::qpOASES::Options my_options;
my_options.enableCholeskyRefactorisation = 10;
my_options.epsNum = FLAGS_default_qp_smoothing_eps_num;
my_options.epsDen = FLAGS_default_qp_smoothing_eps_den;
my_options.epsIterRef = FLAGS_default_qp_smoothing_eps_iter_ref;
sqp_solver_->setOptions(my_options);
if (!FLAGS_default_enable_active_set_debug_info) {
sqp_solver_->setPrintLevel(qpOASES::PL_NONE);
}
}
// definition of qpOASESproblem
const auto kNumOfMatrixElements = kernel_matrix.rows() * kernel_matrix.cols();
double h_matrix[kNumOfMatrixElements]; // NOLINT
memset(h_matrix, 0, sizeof h_matrix);
const auto kNumOfOffsetRows = offset.rows();
double g_matrix[kNumOfOffsetRows]; // NOLINT
memset(g_matrix, 0, sizeof g_matrix);
int index = 0;
for (int r = 0; r < kernel_matrix.rows(); ++r) {
g_matrix[r] = offset(r, 0);
for (int c = 0; c < kernel_matrix.cols(); ++c) {
h_matrix[index++] = kernel_matrix(r, c);
}
}
DCHECK_EQ(index, kernel_matrix.rows() * kernel_matrix.cols());
// search space lower bound and uppper bound
double lower_bound[num_param]; // NOLINT
double upper_bound[num_param]; // NOLINT
memset(lower_bound, 0, sizeof lower_bound);
memset(upper_bound, 0, sizeof upper_bound);
const double l_lower_bound_ = -kRoadBound;
const double l_upper_bound_ = kRoadBound;
for (int i = 0; i < num_param; ++i) {
lower_bound[i] = l_lower_bound_;
upper_bound[i] = l_upper_bound_;
}
// constraint matrix construction
double affine_constraint_matrix[num_param * num_constraint]; // NOLINT
memset(affine_constraint_matrix, 0, sizeof affine_constraint_matrix);
double constraint_lower_bound[num_constraint]; // NOLINT
double constraint_upper_bound[num_constraint]; // NOLINT
memset(constraint_lower_bound, 0, sizeof constraint_lower_bound);
memset(constraint_upper_bound, 0, sizeof constraint_upper_bound);
index = 0;
for (int r = 0; r < equality_constraint_matrix.rows(); ++r) {
constraint_lower_bound[r] = equality_constraint_boundary(r, 0);
constraint_upper_bound[r] = equality_constraint_boundary(r, 0);
for (int c = 0; c < num_param; ++c) {
affine_constraint_matrix[index++] = equality_constraint_matrix(r, c);
}
}
DCHECK_EQ(index, equality_constraint_matrix.rows() * num_param);
const double constraint_upper_bound_ = kRoadBound;
for (int r = 0; r < inequality_constraint_matrix.rows(); ++r) {
constraint_lower_bound[r + equality_constraint_boundary.rows()] =
inequality_constraint_boundary(r, 0);
constraint_upper_bound[r + equality_constraint_boundary.rows()] =
constraint_upper_bound_;
for (int c = 0; c < num_param; ++c) {
affine_constraint_matrix[index++] = inequality_constraint_matrix(r, c);
}
}
DCHECK_EQ(index, equality_constraint_matrix.rows() * num_param +
inequality_constraint_boundary.rows() * num_param);
// initialize problem
int max_iter = std::max(FLAGS_default_qp_iteration_num, num_constraint);
::qpOASES::returnValue ret;
const double start_timestamp = Clock::NowInSeconds();
if (use_hotstart) {
ADEBUG << "ActiveSetSpline2dSolver is using SQP hotstart.";
ret = sqp_solver_->hotstart(
h_matrix, g_matrix, affine_constraint_matrix, lower_bound, upper_bound,
constraint_lower_bound, constraint_upper_bound, max_iter);
if (ret != qpOASES::SUCCESSFUL_RETURN) {
AERROR << "Fail to hotstart spline 2d, will use re-init instead.";
ret = sqp_solver_->init(h_matrix, g_matrix, affine_constraint_matrix,
lower_bound, upper_bound, constraint_lower_bound,
constraint_upper_bound, max_iter);
}
} else {
AINFO << "ActiveSetSpline2dSolver is NOT using SQP hotstart.";
ret = sqp_solver_->init(h_matrix, g_matrix, affine_constraint_matrix,
lower_bound, upper_bound, constraint_lower_bound,
constraint_upper_bound, max_iter);
}
const double end_timestamp = Clock::NowInSeconds();
ADEBUG << "ActiveSetSpline2dSolver QP time: "
<< (end_timestamp - start_timestamp) * 1000 << " ms.";
ADEBUG << "return status is" << getSimpleStatus(ret);
if (ret != qpOASES::SUCCESSFUL_RETURN) {
if (ret == qpOASES::RET_MAX_NWSR_REACHED) {
AERROR << "qpOASES solver failed due to reached max iteration";
} else {
AERROR << "qpOASES solver failed due to infeasibility or other internal "
"reasons:"
<< ret;
}
last_problem_success_ = false;
return false;
}
last_problem_success_ = true;
double result[num_param]; // NOLINT
memset(result, 0, sizeof result);
sqp_solver_->getPrimalSolution(result);
MatrixXd solved_params = MatrixXd::Zero(num_param, 1);
for (int i = 0; i < num_param; ++i) {
solved_params(i, 0) = result[i];
}
last_num_param_ = num_param;
last_num_constraint_ = num_constraint;
return spline_.set_splines(solved_params, spline_.spline_order());
}
// extract
const Spline2d& ActiveSetSpline2dSolver::spline() const { return spline_; }
} // namespace planning
} // namespace apollo
<|endoftext|> |
<commit_before>#pragma once
#include <vector>
#include <SFML/Graphics.hpp>
#include <cmath>
#include "scenenode.hpp"
template<typename T>
struct Particle
{
sf::Vector2f pos; // Position
sf::Vector2f vel; // Velocity
float lifetime;
float lifetime_max;
T node;
};
struct SmokeShape : public SceneNode
{
sf::CircleShape m_Shape;
float lifetime_max;
void draw(sf::RenderTarget& target, sf::RenderStates states) const {
states.transform *= getAbsoluteTransform();
target.draw(m_Shape);
}
};
template<typename T>
class ParticleEmitter : public SceneNode
{
public:
ParticleEmitter(T copy, SceneNode* node);
//~ParticleEmitter();
void setFrequency(float);
void setNumberOfParticles(float);
int getNumberOfParticles() { return m_particles.size(); }
void update(sf::Time);
void addParticle();
void apply(Particle<T>*);
void effect(Particle<T>*);
private:
std::vector<Particle<T>*> m_particles;
float m_Frequency;
float m_NumberOfParticles;
SceneNode* m_node;
};
template<typename T>
ParticleEmitter<T>::ParticleEmitter(T copy, SceneNode* node)
: m_Frequency()
, m_NumberOfParticles()
, m_particles()
, m_node(node)
{
}
/*ParticleSystem::~ParticleSystem()
{
for( int i = m_particles.begin(); i != m_particles.end(); i++ )
{
delete m_particles[i];
}
}
*/
template<typename T>
void ParticleEmitter<T>::setFrequency(float frequency)
{
m_Frequency = frequency;
}
template<typename T>
void ParticleEmitter<T>::setNumberOfParticles(float number)
{
m_NumberOfParticles = number;
}
template<typename T>
void ParticleEmitter<T>::update(sf::Time time)
{
float initNb(m_NumberOfParticles);
m_NumberOfParticles+=time.asSeconds()*m_Frequency;
for (int i=0; i<(static_cast<int>(m_NumberOfParticles)-static_cast<int>(initNb)); i++)
addParticle();
for (int i=0;i<m_particles.size(); i++)
{
m_particles[i]->pos+=m_particles[i]->vel*time.asSeconds();
m_particles[i]->lifetime-=time.asSeconds();
apply(m_particles[i]);
effect(m_particles[i]);
}
}
template<>
void ParticleEmitter<SmokeShape>::apply(Particle<SmokeShape>* particle)
{
sf::Vector2f gravity(0,0.3);
particle->vel-=gravity;
}
template<>
void ParticleEmitter<SmokeShape>::effect(Particle<SmokeShape>* particle)
{
sf::Color color(255,255,255,255*particle->lifetime/particle->lifetime_max);
particle->node.m_Shape.setFillColor(color);
}
template<typename T>
void ParticleEmitter<T>::effect(Particle<T>* particle)
{
}
template<typename T>
void ParticleEmitter<T>::addParticle()
{
float angle(rand());
m_particles.push_back(new Particle<T> {m_node->getPosition(), sf::Vector2f (cos(angle),sin(angle)), 2.f, 2.f, T() });
m_particles.back()->node.attachParent(m_node);
}
template<typename T>
void apply(Particle<T>* particle)
{
}
<commit_msg>new generator<commit_after>#pragma once
#include <vector>
#include <SFML/Graphics.hpp>
#include <cmath>
#include "scenenode.hpp"
template<typename T>
struct Particle
{
sf::Vector2f pos; // Position
sf::Vector2f vel; // Velocity
float lifetime;
float lifetime_max;
T node;
};
struct SmokeShape : public SceneNode
{
sf::CircleShape m_Shape;
float lifetime_max;
void draw(sf::RenderTarget& target, sf::RenderStates states) const {
states.transform *= getAbsoluteTransform();
target.draw(m_Shape);
}
};
template<typename T>
class ParticleEmitter : public SceneNode
{
public:
ParticleEmitter(T copy, SceneNode* node);
//~ParticleEmitter();
void setFrequency(float);
void setNumberOfParticles(float);
int getNumberOfParticles() { return m_particles.size(); }
void update(sf::Time);
void addParticle();
void apply(Particle<T>*);
void effect(Particle<T>*);
private:
std::vector<Particle<T>*> m_particles;
float m_Frequency;
float m_NumberOfParticles;
float m_NumberOfParticlesMax;
SceneNode* m_node;
};
template<typename T>
ParticleEmitter<T>::ParticleEmitter(T copy, SceneNode* node)
: m_Frequency()
, m_NumberOfParticles()
, m_NumberOfParticlesMax()
, m_particles()
, m_node(node)
{
}
/*ParticleSystem::~ParticleSystem()
{
for( int i = m_particles.begin(); i != m_particles.end(); i++ )
{
delete m_particles[i];
}
}
*/
template<typename T>
void ParticleEmitter<T>::setFrequency(float frequency)
{
m_Frequency = frequency;
}
template<typename T>
void ParticleEmitter<T>::setNumberOfParticles(float number)
{
m_NumberOfParticles = number;
}
template<typename T>
void ParticleEmitter<T>::update(sf::Time time)
{
m_NumberOfParticles+=time.asSeconds()*m_Frequency;
if (m_NumberOfParticles<m_NumberOfParticlesMax)
{
for (int i=0; i<(static_cast<int>(m_NumberOfParticles)-m_particles.size()); i++)
addParticle();
}
for (int i=0;i<m_particles.size(); i++)
{
if (m_particles[i] != nullptr)
{
m_particles[i]->lifetime-=time.asSeconds();
if (m_particles[i]->lifetime<0)
{
delete m_particles[i];
m_particles[i] = nullptr;
m_NumberOfParticles-=1;
}
else
{
m_particles[i]->pos+=m_particles[i]->vel*time.asSeconds();
m_particles[i]->node.setPosition(m_particles[i]->pos);
apply(m_particles[i]);
effect(m_particles[i]);
}
}
}
}
template<>
void ParticleEmitter<SmokeShape>::apply(Particle<SmokeShape>* particle)
{
sf::Vector2f gravity(0,0.3);
particle->vel-=gravity;
}
template<>
void ParticleEmitter<SmokeShape>::effect(Particle<SmokeShape>* particle)
{
sf::Color color(255,255,255,255*particle->lifetime/particle->lifetime_max);
particle->node.m_Shape.setFillColor(color);
}
template<typename T>
void ParticleEmitter<T>::effect(Particle<T>* particle)
{
}
template<typename T>
void ParticleEmitter<T>::addParticle()
{
float angle(rand());
if (m_particles.size() == m_NumberOfParticlesMax)
{
int i(0);
while (m_particles[i] != nullptr)
i++;
m_particles[i] = new Particle<T> {m_node->getPosition(), sf::Vector2f (cos(angle),sin(angle)), 2.f, 2.f, T() };
m_particles[i]->node.attachParent(m_node);
}
else
{
m_particles.push_back(new Particle<T> {m_node->getPosition(), sf::Vector2f (cos(angle),sin(angle)), 2.f, 2.f, T() });
m_particles.back()->node.attachParent(m_node);
}
}
template<typename T>
void apply(Particle<T>* particle)
{
}
<|endoftext|> |
<commit_before>//===========================================
// Lumina-DE source code
// Copyright (c) 2015, Ken Moore
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include "PlainTextEditor.h"
#include <QColor>
#include <QPainter>
#include <QTextBlock>
#include <QFileDialog>
#include <QDebug>
#include <QApplication>
#include <QMessageBox>
#include <LUtils.h>
//==============
// PUBLIC
//==============
PlainTextEditor::PlainTextEditor(QSettings *set, QWidget *parent) : QPlainTextEdit(parent){
settings = set;
LNW = new LNWidget(this);
showLNW = true;
watcher = new QFileSystemWatcher(this);
hasChanges = false;
lastSaveContents.clear();
matchleft = matchright = -1;
this->setTabStopWidth( 8 * this->fontMetrics().width(" ") ); //8 character spaces per tab (UNIX standard)
//this->setObjectName("PlainTextEditor");
//this->setStyleSheet("QPlainTextEdit#PlainTextEditor{ }");
SYNTAX = new Custom_Syntax(settings, this->document());
connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(LNW_updateWidth()) );
connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(LNW_highlightLine()) );
connect(this, SIGNAL(updateRequest(const QRect&, int)), this, SLOT(LNW_update(const QRect&, int)) );
connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(checkMatchChar()) );
connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(cursorMoved()) );
connect(this, SIGNAL(textChanged()), this, SLOT(textChanged()) );
connect(watcher, SIGNAL(fileChanged(const QString&)), this, SLOT(fileChanged()) );
LNW_updateWidth();
LNW_highlightLine();
}
PlainTextEditor::~PlainTextEditor(){
}
void PlainTextEditor::showLineNumbers(bool show){
showLNW = show;
LNW->setVisible(show);
LNW_updateWidth();
}
void PlainTextEditor::LoadSyntaxRule(QString type){
SYNTAX->loadRules(type);
SYNTAX->rehighlight();
}
void PlainTextEditor::updateSyntaxColors(){
SYNTAX->reloadRules();
SYNTAX->rehighlight();
}
//File loading/setting options
void PlainTextEditor::LoadFile(QString filepath){
if( !watcher->files().isEmpty() ){ watcher->removePaths(watcher->files()); }
bool diffFile = (filepath != this->whatsThis());
this->setWhatsThis(filepath);
this->clear();
SYNTAX->loadRules( Custom_Syntax::ruleForFile(filepath.section("/",-1)) );
lastSaveContents = LUtils::readFile(filepath).join("\n");
if(diffFile){
this->setPlainText( lastSaveContents );
}else{
//Try to keep the mouse cursor/scroll in the same position
int curpos = this->textCursor().position();;
this->setPlainText( lastSaveContents );
QApplication::processEvents();
QTextCursor cur = this->textCursor();
cur.setPosition(curpos);
this->setTextCursor( cur );
this->centerCursor(); //scroll until cursor is centered (if possible)
}
hasChanges = false;
watcher->addPath(filepath);
emit FileLoaded(this->whatsThis());
}
void PlainTextEditor::SaveFile(bool newname){
//qDebug() << "Save File:" << this->whatsThis();
if( !this->whatsThis().startsWith("/") || newname ){
//prompt for a filename/path
QString file = QFileDialog::getSaveFileName(this, tr("Save File"), this->whatsThis(), tr("Text File (*)"));
if(file.isEmpty()){ return; }
this->setWhatsThis(file);
SYNTAX->loadRules( Custom_Syntax::ruleForFile(this->whatsThis().section("/",-1)) );
SYNTAX->rehighlight();
}
if( !watcher->files().isEmpty() ){ watcher->removePaths(watcher->files()); }
bool ok = LUtils::writeFile(this->whatsThis(), this->toPlainText().split("\n"), true);
hasChanges = !ok;
if(ok){ lastSaveContents = this->toPlainText(); emit FileLoaded(this->whatsThis()); }
watcher->addPath(currentFile());
//qDebug() << " - Success:" << ok << hasChanges;
}
QString PlainTextEditor::currentFile(){
return this->whatsThis();
}
bool PlainTextEditor::hasChange(){
return hasChanges;
}
//Functions for managing the line number widget
int PlainTextEditor::LNWWidth(){
//Get the number of chars we need for line numbers
int lines = this->blockCount();
if(lines<1){ lines = 1; }
int chars = 1;
while(lines>=10){ chars++; lines/=10; }
return (this->fontMetrics().width("9")*chars); //make sure to add a tiny bit of padding
}
void PlainTextEditor::paintLNW(QPaintEvent *ev){
QPainter P(LNW);
//First set the background color
P.fillRect(ev->rect(), QColor("lightgrey"));
//Now determine which line numbers to show (based on the current viewport)
QTextBlock block = this->firstVisibleBlock();
int bTop = blockBoundingGeometry(block).translated(contentOffset()).top();
int bBottom;
//Now loop over the blocks (lines) and write in the numbers
P.setPen(Qt::black); //setup the font color
while(block.isValid() && bTop<=ev->rect().bottom()){ //ensure block below top of viewport
bBottom = bTop+blockBoundingRect(block).height();
if(block.isVisible() && bBottom >= ev->rect().top()){ //ensure block above bottom of viewport
P.drawText(0,bTop, LNW->width(), this->fontMetrics().height(), Qt::AlignRight, QString::number(block.blockNumber()+1) );
}
//Go to the next block
block = block.next();
bTop = bBottom;
}
}
//==============
// PRIVATE
//==============
void PlainTextEditor::clearMatchData(){
if(matchleft>=0 || matchright>=0){
QList<QTextEdit::ExtraSelection> sel = this->extraSelections();
for(int i=0; i<sel.length(); i++){
if(sel[i].cursor.selectedText().length()==1){ sel.takeAt(i); i--; }
}
this->setExtraSelections(sel);
matchleft = -1;
matchright = -1;
}
}
void PlainTextEditor::highlightMatch(QChar ch, bool forward, int fromPos, QChar startch){
if(forward){ matchleft = fromPos; }
else{ matchright = fromPos; }
int nested = 1; //always start within the first nest (the primary nest)
int tmpFromPos = fromPos;
//if(!forward){ tmpFromPos++; } //need to include the initial location
QString doc = this->toPlainText();
while( nested>0 && tmpFromPos<doc.length() && ( (tmpFromPos>=fromPos && forward) || ( tmpFromPos<=fromPos && !forward ) ) ){
if(forward){
QTextCursor cur = this->document()->find(ch, tmpFromPos);
if(!cur.isNull()){
nested += doc.mid(tmpFromPos+1, cur.position()-tmpFromPos).count(startch) -1;
if(nested==0){ matchright = cur.position(); }
else{ tmpFromPos = cur.position(); }
}else{ break; }
}else{
QTextCursor cur = this->document()->find(ch, tmpFromPos, QTextDocument::FindBackward);
if(!cur.isNull()){
QString mid = doc.mid(cur.position()-1, tmpFromPos-cur.position()+1);
//qDebug() << "Found backwards match:" << nested << startch << ch << mid;
//qDebug() << doc.mid(cur.position(),1) << doc.mid(tmpFromPos,1);
nested += (mid.count(startch) - mid.count(ch));
if(nested==0){ matchleft = cur.position(); }
else{ tmpFromPos = cur.position()-1; }
}else{ break; }
}
}
//Now highlight the two characters
QList<QTextEdit::ExtraSelection> sels = this->extraSelections();
if(matchleft>=0){
QTextEdit::ExtraSelection sel;
if(matchright>=0){ sel.format.setBackground( QColor(settings->value("colors/bracket-found").toString()) ); }
else{ sel.format.setBackground( QColor(settings->value("colors/bracket-missing").toString()) ); }
QTextCursor cur = this->textCursor();
cur.setPosition(matchleft);
if(forward){ cur.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor); }
else{ cur.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor); }
sel.cursor = cur;
sels << sel;
}
if(matchright>=0){
QTextEdit::ExtraSelection sel;
if(matchleft>=0){ sel.format.setBackground( QColor(settings->value("colors/bracket-found").toString()) ); }
else{ sel.format.setBackground( QColor(settings->value("colors/bracket-missing").toString()) ); }
QTextCursor cur = this->textCursor();
cur.setPosition(matchright);
if(!forward){ cur.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor); }
else{ cur.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor); }
sel.cursor = cur;
sels << sel;
}
this->setExtraSelections(sels);
}
//===================
// PRIVATE SLOTS
//===================
//Functions for managing the line number widget
void PlainTextEditor::LNW_updateWidth(){
if(showLNW){
this->setViewportMargins( LNWWidth(), 0, 0, 0); //the LNW is contained within the left margin
}else{
this->setViewportMargins( 0, 0, 0, 0); //the LNW is contained within the left margin
}
}
void PlainTextEditor::LNW_highlightLine(){
if(this->isReadOnly()){ return; }
QColor highC = QColor(0,0,0,50); //just darken the line a bit
QTextEdit::ExtraSelection sel;
sel.format.setBackground(highC);
sel.format.setProperty(QTextFormat::FullWidthSelection, true);
sel.cursor = this->textCursor();
sel.cursor.clearSelection(); //just in case it already has one
setExtraSelections( QList<QTextEdit::ExtraSelection>() << sel );
}
void PlainTextEditor::LNW_update(const QRect &rect, int dy){
if(dy!=0){ LNW->scroll(0,dy); } //make sure to scroll the line widget the same amount as the editor
else{
//Some other reason we need to repaint the widget
LNW->update(0,rect.y(), LNW->width(), rect.height()); //also repaint the LNW in the same area
}
if(rect.contains(this->viewport()->rect())){
//Something in the currently-viewed area needs updating - make sure the LNW width is still correct
LNW_updateWidth();
}
}
//Function for running the matching routine
void PlainTextEditor::checkMatchChar(){
clearMatchData();
int pos = this->textCursor().position();
QChar ch = this->document()->characterAt(pos);
bool tryback = true;
while(tryback){
tryback = false;
if(ch==QChar('(')){ highlightMatch(QChar(')'),true, pos, QChar('(') ); }
else if(ch==QChar(')')){ highlightMatch(QChar('('),false, pos, QChar(')') ); }
else if(ch==QChar('{')){ highlightMatch(QChar('}'),true, pos, QChar('{') ); }
else if(ch==QChar('}')){ highlightMatch(QChar('{'),false, pos, QChar('}') ); }
else if(ch==QChar('[')){ highlightMatch(QChar(']'),true, pos, QChar('[') ); }
else if(ch==QChar(']')){ highlightMatch(QChar('['),false, pos, QChar(']') ); }
else if(pos==this->textCursor().position()){
//Try this one more time - using the previous character instead of the current character
tryback = true;
pos--;
ch = this->document()->characterAt(pos);
}
} //end check for next/previous char
}
//Functions for notifying the parent widget of changes
void PlainTextEditor::textChanged(){
//qDebug() << " - Got Text Changed signal";
bool changed = (lastSaveContents != this->toPlainText());
if(changed == hasChanges){ return; } //no change
hasChanges = changed; //save for reading later
if(hasChanges){ emit UnsavedChanges( this->whatsThis() ); }
else{ emit FileLoaded(this->whatsThis()); }
}
void PlainTextEditor::cursorMoved(){
//Update the status tip for the editor to show the row/column number for the cursor
QTextCursor cur = this->textCursor();
QString stat = tr("Row Number: %1, Column Number: %2");
this->setStatusTip(stat.arg(QString::number(cur.blockNumber()+1) , QString::number(cur.columnNumber()) ) );
emit statusTipChanged();
}
//Function for prompting the user if the file changed externally
void PlainTextEditor::fileChanged(){
qDebug() << "File Changed:" << currentFile();
bool update = !hasChanges; //Go ahead and reload the file automatically - no custom changes in the editor
QString text = tr("The following file has been changed by some other utility. Do you want to re-load it?");
text.append("\n");
text.append( tr("(Note: You will lose all currently-unsaved changes)") );
text.append("\n\n%1");
if(!update){
update = (QMessageBox::Yes == QMessageBox::question(this, tr("File Modified"),text.arg(currentFile()) , QMessageBox::Yes | QMessageBox::No, QMessageBox::No) );
}
//Now update the text in the editor as needed
if(update){
LoadFile( currentFile() );
}
}
//==================
// PROTECTED
//==================
void PlainTextEditor::resizeEvent(QResizeEvent *ev){
QPlainTextEdit::resizeEvent(ev); //do the normal resize processing
//Now re-adjust the placement of the LNW (within the left margin area)
QRect cGeom = this->contentsRect();
LNW->setGeometry( QRect(cGeom.left(), cGeom.top(), LNWWidth(), cGeom.height()) );
}
<commit_msg>Silence a file watcher warning when opening a blank or new file.<commit_after>//===========================================
// Lumina-DE source code
// Copyright (c) 2015, Ken Moore
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include "PlainTextEditor.h"
#include <QColor>
#include <QPainter>
#include <QTextBlock>
#include <QFileDialog>
#include <QDebug>
#include <QApplication>
#include <QMessageBox>
#include <LUtils.h>
//==============
// PUBLIC
//==============
PlainTextEditor::PlainTextEditor(QSettings *set, QWidget *parent) : QPlainTextEdit(parent){
settings = set;
LNW = new LNWidget(this);
showLNW = true;
watcher = new QFileSystemWatcher(this);
hasChanges = false;
lastSaveContents.clear();
matchleft = matchright = -1;
this->setTabStopWidth( 8 * this->fontMetrics().width(" ") ); //8 character spaces per tab (UNIX standard)
//this->setObjectName("PlainTextEditor");
//this->setStyleSheet("QPlainTextEdit#PlainTextEditor{ }");
SYNTAX = new Custom_Syntax(settings, this->document());
connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(LNW_updateWidth()) );
connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(LNW_highlightLine()) );
connect(this, SIGNAL(updateRequest(const QRect&, int)), this, SLOT(LNW_update(const QRect&, int)) );
connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(checkMatchChar()) );
connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(cursorMoved()) );
connect(this, SIGNAL(textChanged()), this, SLOT(textChanged()) );
connect(watcher, SIGNAL(fileChanged(const QString&)), this, SLOT(fileChanged()) );
LNW_updateWidth();
LNW_highlightLine();
}
PlainTextEditor::~PlainTextEditor(){
}
void PlainTextEditor::showLineNumbers(bool show){
showLNW = show;
LNW->setVisible(show);
LNW_updateWidth();
}
void PlainTextEditor::LoadSyntaxRule(QString type){
SYNTAX->loadRules(type);
SYNTAX->rehighlight();
}
void PlainTextEditor::updateSyntaxColors(){
SYNTAX->reloadRules();
SYNTAX->rehighlight();
}
//File loading/setting options
void PlainTextEditor::LoadFile(QString filepath){
if( !watcher->files().isEmpty() ){ watcher->removePaths(watcher->files()); }
bool diffFile = (filepath != this->whatsThis());
this->setWhatsThis(filepath);
this->clear();
SYNTAX->loadRules( Custom_Syntax::ruleForFile(filepath.section("/",-1)) );
lastSaveContents = LUtils::readFile(filepath).join("\n");
if(diffFile){
this->setPlainText( lastSaveContents );
}else{
//Try to keep the mouse cursor/scroll in the same position
int curpos = this->textCursor().position();;
this->setPlainText( lastSaveContents );
QApplication::processEvents();
QTextCursor cur = this->textCursor();
cur.setPosition(curpos);
this->setTextCursor( cur );
this->centerCursor(); //scroll until cursor is centered (if possible)
}
hasChanges = false;
if(QFile::exists(filepath)){ watcher->addPath(filepath); }
emit FileLoaded(this->whatsThis());
}
void PlainTextEditor::SaveFile(bool newname){
//qDebug() << "Save File:" << this->whatsThis();
if( !this->whatsThis().startsWith("/") || newname ){
//prompt for a filename/path
QString file = QFileDialog::getSaveFileName(this, tr("Save File"), this->whatsThis(), tr("Text File (*)"));
if(file.isEmpty()){ return; }
this->setWhatsThis(file);
SYNTAX->loadRules( Custom_Syntax::ruleForFile(this->whatsThis().section("/",-1)) );
SYNTAX->rehighlight();
}
if( !watcher->files().isEmpty() ){ watcher->removePaths(watcher->files()); }
bool ok = LUtils::writeFile(this->whatsThis(), this->toPlainText().split("\n"), true);
hasChanges = !ok;
if(ok){ lastSaveContents = this->toPlainText(); emit FileLoaded(this->whatsThis()); }
watcher->addPath(currentFile());
//qDebug() << " - Success:" << ok << hasChanges;
}
QString PlainTextEditor::currentFile(){
return this->whatsThis();
}
bool PlainTextEditor::hasChange(){
return hasChanges;
}
//Functions for managing the line number widget
int PlainTextEditor::LNWWidth(){
//Get the number of chars we need for line numbers
int lines = this->blockCount();
if(lines<1){ lines = 1; }
int chars = 1;
while(lines>=10){ chars++; lines/=10; }
return (this->fontMetrics().width("9")*chars); //make sure to add a tiny bit of padding
}
void PlainTextEditor::paintLNW(QPaintEvent *ev){
QPainter P(LNW);
//First set the background color
P.fillRect(ev->rect(), QColor("lightgrey"));
//Now determine which line numbers to show (based on the current viewport)
QTextBlock block = this->firstVisibleBlock();
int bTop = blockBoundingGeometry(block).translated(contentOffset()).top();
int bBottom;
//Now loop over the blocks (lines) and write in the numbers
P.setPen(Qt::black); //setup the font color
while(block.isValid() && bTop<=ev->rect().bottom()){ //ensure block below top of viewport
bBottom = bTop+blockBoundingRect(block).height();
if(block.isVisible() && bBottom >= ev->rect().top()){ //ensure block above bottom of viewport
P.drawText(0,bTop, LNW->width(), this->fontMetrics().height(), Qt::AlignRight, QString::number(block.blockNumber()+1) );
}
//Go to the next block
block = block.next();
bTop = bBottom;
}
}
//==============
// PRIVATE
//==============
void PlainTextEditor::clearMatchData(){
if(matchleft>=0 || matchright>=0){
QList<QTextEdit::ExtraSelection> sel = this->extraSelections();
for(int i=0; i<sel.length(); i++){
if(sel[i].cursor.selectedText().length()==1){ sel.takeAt(i); i--; }
}
this->setExtraSelections(sel);
matchleft = -1;
matchright = -1;
}
}
void PlainTextEditor::highlightMatch(QChar ch, bool forward, int fromPos, QChar startch){
if(forward){ matchleft = fromPos; }
else{ matchright = fromPos; }
int nested = 1; //always start within the first nest (the primary nest)
int tmpFromPos = fromPos;
//if(!forward){ tmpFromPos++; } //need to include the initial location
QString doc = this->toPlainText();
while( nested>0 && tmpFromPos<doc.length() && ( (tmpFromPos>=fromPos && forward) || ( tmpFromPos<=fromPos && !forward ) ) ){
if(forward){
QTextCursor cur = this->document()->find(ch, tmpFromPos);
if(!cur.isNull()){
nested += doc.mid(tmpFromPos+1, cur.position()-tmpFromPos).count(startch) -1;
if(nested==0){ matchright = cur.position(); }
else{ tmpFromPos = cur.position(); }
}else{ break; }
}else{
QTextCursor cur = this->document()->find(ch, tmpFromPos, QTextDocument::FindBackward);
if(!cur.isNull()){
QString mid = doc.mid(cur.position()-1, tmpFromPos-cur.position()+1);
//qDebug() << "Found backwards match:" << nested << startch << ch << mid;
//qDebug() << doc.mid(cur.position(),1) << doc.mid(tmpFromPos,1);
nested += (mid.count(startch) - mid.count(ch));
if(nested==0){ matchleft = cur.position(); }
else{ tmpFromPos = cur.position()-1; }
}else{ break; }
}
}
//Now highlight the two characters
QList<QTextEdit::ExtraSelection> sels = this->extraSelections();
if(matchleft>=0){
QTextEdit::ExtraSelection sel;
if(matchright>=0){ sel.format.setBackground( QColor(settings->value("colors/bracket-found").toString()) ); }
else{ sel.format.setBackground( QColor(settings->value("colors/bracket-missing").toString()) ); }
QTextCursor cur = this->textCursor();
cur.setPosition(matchleft);
if(forward){ cur.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor); }
else{ cur.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor); }
sel.cursor = cur;
sels << sel;
}
if(matchright>=0){
QTextEdit::ExtraSelection sel;
if(matchleft>=0){ sel.format.setBackground( QColor(settings->value("colors/bracket-found").toString()) ); }
else{ sel.format.setBackground( QColor(settings->value("colors/bracket-missing").toString()) ); }
QTextCursor cur = this->textCursor();
cur.setPosition(matchright);
if(!forward){ cur.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor); }
else{ cur.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor); }
sel.cursor = cur;
sels << sel;
}
this->setExtraSelections(sels);
}
//===================
// PRIVATE SLOTS
//===================
//Functions for managing the line number widget
void PlainTextEditor::LNW_updateWidth(){
if(showLNW){
this->setViewportMargins( LNWWidth(), 0, 0, 0); //the LNW is contained within the left margin
}else{
this->setViewportMargins( 0, 0, 0, 0); //the LNW is contained within the left margin
}
}
void PlainTextEditor::LNW_highlightLine(){
if(this->isReadOnly()){ return; }
QColor highC = QColor(0,0,0,50); //just darken the line a bit
QTextEdit::ExtraSelection sel;
sel.format.setBackground(highC);
sel.format.setProperty(QTextFormat::FullWidthSelection, true);
sel.cursor = this->textCursor();
sel.cursor.clearSelection(); //just in case it already has one
setExtraSelections( QList<QTextEdit::ExtraSelection>() << sel );
}
void PlainTextEditor::LNW_update(const QRect &rect, int dy){
if(dy!=0){ LNW->scroll(0,dy); } //make sure to scroll the line widget the same amount as the editor
else{
//Some other reason we need to repaint the widget
LNW->update(0,rect.y(), LNW->width(), rect.height()); //also repaint the LNW in the same area
}
if(rect.contains(this->viewport()->rect())){
//Something in the currently-viewed area needs updating - make sure the LNW width is still correct
LNW_updateWidth();
}
}
//Function for running the matching routine
void PlainTextEditor::checkMatchChar(){
clearMatchData();
int pos = this->textCursor().position();
QChar ch = this->document()->characterAt(pos);
bool tryback = true;
while(tryback){
tryback = false;
if(ch==QChar('(')){ highlightMatch(QChar(')'),true, pos, QChar('(') ); }
else if(ch==QChar(')')){ highlightMatch(QChar('('),false, pos, QChar(')') ); }
else if(ch==QChar('{')){ highlightMatch(QChar('}'),true, pos, QChar('{') ); }
else if(ch==QChar('}')){ highlightMatch(QChar('{'),false, pos, QChar('}') ); }
else if(ch==QChar('[')){ highlightMatch(QChar(']'),true, pos, QChar('[') ); }
else if(ch==QChar(']')){ highlightMatch(QChar('['),false, pos, QChar(']') ); }
else if(pos==this->textCursor().position()){
//Try this one more time - using the previous character instead of the current character
tryback = true;
pos--;
ch = this->document()->characterAt(pos);
}
} //end check for next/previous char
}
//Functions for notifying the parent widget of changes
void PlainTextEditor::textChanged(){
//qDebug() << " - Got Text Changed signal";
bool changed = (lastSaveContents != this->toPlainText());
if(changed == hasChanges){ return; } //no change
hasChanges = changed; //save for reading later
if(hasChanges){ emit UnsavedChanges( this->whatsThis() ); }
else{ emit FileLoaded(this->whatsThis()); }
}
void PlainTextEditor::cursorMoved(){
//Update the status tip for the editor to show the row/column number for the cursor
QTextCursor cur = this->textCursor();
QString stat = tr("Row Number: %1, Column Number: %2");
this->setStatusTip(stat.arg(QString::number(cur.blockNumber()+1) , QString::number(cur.columnNumber()) ) );
emit statusTipChanged();
}
//Function for prompting the user if the file changed externally
void PlainTextEditor::fileChanged(){
qDebug() << "File Changed:" << currentFile();
bool update = !hasChanges; //Go ahead and reload the file automatically - no custom changes in the editor
QString text = tr("The following file has been changed by some other utility. Do you want to re-load it?");
text.append("\n");
text.append( tr("(Note: You will lose all currently-unsaved changes)") );
text.append("\n\n%1");
if(!update){
update = (QMessageBox::Yes == QMessageBox::question(this, tr("File Modified"),text.arg(currentFile()) , QMessageBox::Yes | QMessageBox::No, QMessageBox::No) );
}
//Now update the text in the editor as needed
if(update){
LoadFile( currentFile() );
}
}
//==================
// PROTECTED
//==================
void PlainTextEditor::resizeEvent(QResizeEvent *ev){
QPlainTextEdit::resizeEvent(ev); //do the normal resize processing
//Now re-adjust the placement of the LNW (within the left margin area)
QRect cGeom = this->contentsRect();
LNW->setGeometry( QRect(cGeom.left(), cGeom.top(), LNWWidth(), cGeom.height()) );
}
<|endoftext|> |
<commit_before>/*************** <auto-copyright.pl BEGIN do not edit this line> **************
*
* VR Juggler is (C) Copyright 1998-2003 by Iowa State University
*
* Original Authors:
* Allen Bierbaum, Christopher Just,
* Patrick Hartling, Kevin Meinert,
* Carolina Cruz-Neira, Albert Baker
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* -----------------------------------------------------------------
* File: $RCSfile$
* Date modified: $Date$
* Version: $Revision$
* -----------------------------------------------------------------
*
*************** <auto-copyright.pl END do not edit this line> ***************/
#include <cluster/PluginConfig.h>
#include <boost/concept_check.hpp>
#include <gadget/Util/Debug.h>
#include <cluster/ClusterNetwork/ClusterNode.h>
#include <plugins/RemoteInputManager/DeviceServer.h> // my header...
namespace cluster
{
DeviceServer::DeviceServer(const std::string& name, gadget::Input* device, const vpr::GUID& plugin_guid)
: deviceServerTriggerSema(0), deviceServerDoneSema(0)
{
vpr::GUID temp;
temp.generate();
do
{
mId.generate(); // Generate a unique ID for this device
vprDEBUG(vprDBG_ALL, VPR_DBG_WARNING_LVL)
<< "[DeviceServer] Invalid GUID, generating a new one."
<< std::endl << vprDEBUG_FLUSH;
}while(temp == mId);
mThreadActive = false;
mName = name;
mDevice = device;
mPluginGUID = plugin_guid;
mDeviceData = new std::vector<vpr::Uint8>;
mDataPacket = new DataPacket(plugin_guid, mId, mDeviceData);
mBufferObjectWriter = new vpr::BufferObjectWriter(mDeviceData);
start();
}
DeviceServer::~DeviceServer()
{
shutdown();
delete mDataPacket;
// mDataPacket will clean up the memory that mDeviceData points
// to since mDataPacket contains a reference to the ame memory.
mDeviceData = NULL;
}
void DeviceServer::shutdown()
{
// TODO: Make the device server actually shutdown
if ( mControlThread )
{
mThreadActive = false;
mControlThread->kill();
mControlThread = NULL;
}
}
void DeviceServer::send()
{
vpr::Guard<vpr::Mutex> guard(mClientsLock);
//vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL)
// << clrOutBOLD(clrMAGENTA,"DeviceServer::send()")
// << "Sending Device Data for: " << getName() << std::endl << vprDEBUG_FLUSH;
for (std::vector<cluster::ClusterNode*>::iterator i = mClients.begin();
i != mClients.end() ; i++)
{
//vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL) << "Sending data to: "
// << (*i)->getName() << " trying to lock socket" << std::endl << vprDEBUG_FLUSH;
try
{
(*i)->send(mDataPacket);
}
catch(cluster::ClusterException cluster_exception)
{
vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL) << "DeviceServer::send() Caught an exception!"
<< std::endl << vprDEBUG_FLUSH;
vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL) << clrSetBOLD(clrRED)
<< cluster_exception.getMessage() << clrRESET
<< std::endl << vprDEBUG_FLUSH;
vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL) <<
"DeviceServer::send() We have lost our connection to: " << (*i)->getName() << ":" << (*i)->getPort()
<< std::endl << vprDEBUG_FLUSH;
(*i)->setConnected(ClusterNode::DISCONNECTED);
debugDump(vprDBG_CONFIG_LVL);
}
}
//vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL)
// << clrOutBOLD(clrMAGENTA,"DeviceServer::send()")
// << "Done Sending Device Data for: " << getName() << std::endl << vprDEBUG_FLUSH;
}
void DeviceServer::updateLocalData()
{
// -BufferObjectWriter
mBufferObjectWriter->getData()->clear();
mBufferObjectWriter->setCurPos(0);
// This updates the mDeviceData which both mBufferedObjectReader and mDevicePacket point to
mDevice->writeObject(mBufferObjectWriter);
// We must update the size of the actual data that we are going to send
mDataPacket->getHeader()->setPacketLength(Header::RIM_PACKET_HEAD_SIZE
+ 16 /*Plugin GUID*/
+ 16 /*Plugin GUID*/
+ mDeviceData->size());
// We must serialize the header again so that we can reset the size.
mDataPacket->getHeader()->serializeHeader();
}
void DeviceServer::addClient(ClusterNode* new_client_node)
{
vprASSERT(new_client_node != NULL && "You can not add a new client that is NULL");
vpr::Guard<vpr::Mutex> guard(mClientsLock);
mClients.push_back(new_client_node);
}
void DeviceServer::removeClient(const std::string& host_name)
{
vpr::Guard<vpr::Mutex> guard(mClientsLock);
for (std::vector<cluster::ClusterNode*>::iterator i = mClients.begin() ;
i!= mClients.end() ; i++)
{
if ((*i)->getHostname() == host_name)
{
mClients.erase(i);
return;
}
}
}
void DeviceServer::debugDump(int debug_level)
{
vpr::Guard<vpr::Mutex> guard(mClientsLock);
vpr::DebugOutputGuard dbg_output(gadgetDBG_RIM,debug_level,
std::string("-------------- DeviceServer --------------\n"),
std::string("------------------------------------------\n"));
vprDEBUG(gadgetDBG_RIM,debug_level) << "Name: " << mName << std::endl << vprDEBUG_FLUSH;
{ // Used simply to make the following DebugOutputGuard go out of scope
vpr::DebugOutputGuard dbg_output2(gadgetDBG_RIM,debug_level,
std::string("------------ Clients ------------\n"),
std::string("---------------------------------\n"));
for (std::vector<cluster::ClusterNode*>::iterator i = mClients.begin() ;
i!= mClients.end() ; i++)
{
vprDEBUG(gadgetDBG_RIM,debug_level) << "-------- " << (*i)->getName() << " --------" << std::endl << vprDEBUG_FLUSH;
vprDEBUG(gadgetDBG_RIM,debug_level) << " Hostname: " << (*i)->getHostname() << std::endl << vprDEBUG_FLUSH;
vprDEBUG(gadgetDBG_RIM,debug_level) << "----------------------------------" << std::endl << vprDEBUG_FLUSH;
}
}
}
void DeviceServer::controlLoop(void* nullParam)
{
// -Block on an update call
// -Update Local Data
// -Send
// -Signal Sync
boost::ignore_unused_variable_warning(nullParam);
while(true)
{
// Wait for trigger
deviceServerTriggerSema.acquire();
//vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL) << "DeviceServer: " << getName() << " triggered\n" << vprDEBUG_FLUSH;
//vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL) << "Before Update Data\n" << vprDEBUG_FLUSH;
updateLocalData();
//vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL) << "After Update Data\n" << vprDEBUG_FLUSH;
//vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL) << "Before send Data\n" << vprDEBUG_FLUSH;
send();
//vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL) << "After Send Data\n" << vprDEBUG_FLUSH;
// Signal Done Rendering
deviceServerDoneSema.release();
//vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL) << "DeviceServer synced\n" << vprDEBUG_FLUSH;
}
}
/** Starts the control loop. */
void DeviceServer::start()
{
// --- Setup Multi-Process stuff --- //
// Create a new thread to handle the control
vpr::ThreadMemberFunctor<DeviceServer>* memberFunctor =
new vpr::ThreadMemberFunctor<DeviceServer>(this, &DeviceServer::controlLoop, NULL);
mControlThread = new vpr::Thread(memberFunctor);
if (mControlThread->valid())
{
mThreadActive = true;
}
vprDEBUG(gadgetDBG_RIM, vprDBG_CONFIG_LVL)
<< "DeviceServer " << getName() << " started. thread: "
<< mControlThread << std::endl << vprDEBUG_FLUSH;
}
void DeviceServer::go()
{
while(!mThreadActive)
{
vprDEBUG(gadgetDBG_RIM,/*vprDBG_HVERB_LVL*/1) << "Waiting in for thread to start DeviceServer::go().\n" << vprDEBUG_FLUSH;
vpr::Thread::yield();
}
deviceServerTriggerSema.release();
}
/**
* Blocks until the end of the frame.
* @post The frame has been drawn.
*/
void DeviceServer::sync()
{
vprASSERT(mThreadActive == true);
deviceServerDoneSema.acquire();
}
} // End of gadget namespace
<commit_msg>Fixed the last revision so that it actually compiles. Revision 1.13.2.1 also needs to have this change applied.<commit_after>/*************** <auto-copyright.pl BEGIN do not edit this line> **************
*
* VR Juggler is (C) Copyright 1998-2003 by Iowa State University
*
* Original Authors:
* Allen Bierbaum, Christopher Just,
* Patrick Hartling, Kevin Meinert,
* Carolina Cruz-Neira, Albert Baker
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* -----------------------------------------------------------------
* File: $RCSfile$
* Date modified: $Date$
* Version: $Revision$
* -----------------------------------------------------------------
*
*************** <auto-copyright.pl END do not edit this line> ***************/
#include <cluster/PluginConfig.h>
#include <boost/concept_check.hpp>
#include <gadget/Util/Debug.h>
#include <cluster/ClusterNetwork/ClusterNode.h>
#include <plugins/RemoteInputManager/DeviceServer.h> // my header...
namespace cluster
{
DeviceServer::DeviceServer(const std::string& name, gadget::Input* device, const vpr::GUID& plugin_guid)
: deviceServerTriggerSema(0), deviceServerDoneSema(0)
{
vpr::GUID temp;
temp.generate();
do
{
mId.generate(); // Generate a unique ID for this device
vprDEBUG(vprDBG_ALL, vprDBG_WARNING_LVL)
<< "[DeviceServer] Invalid GUID, generating a new one."
<< std::endl << vprDEBUG_FLUSH;
}while(temp == mId);
mThreadActive = false;
mName = name;
mDevice = device;
mPluginGUID = plugin_guid;
mDeviceData = new std::vector<vpr::Uint8>;
mDataPacket = new DataPacket(plugin_guid, mId, mDeviceData);
mBufferObjectWriter = new vpr::BufferObjectWriter(mDeviceData);
start();
}
DeviceServer::~DeviceServer()
{
shutdown();
delete mDataPacket;
// mDataPacket will clean up the memory that mDeviceData points
// to since mDataPacket contains a reference to the ame memory.
mDeviceData = NULL;
}
void DeviceServer::shutdown()
{
// TODO: Make the device server actually shutdown
if ( mControlThread )
{
mThreadActive = false;
mControlThread->kill();
mControlThread = NULL;
}
}
void DeviceServer::send()
{
vpr::Guard<vpr::Mutex> guard(mClientsLock);
//vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL)
// << clrOutBOLD(clrMAGENTA,"DeviceServer::send()")
// << "Sending Device Data for: " << getName() << std::endl << vprDEBUG_FLUSH;
for (std::vector<cluster::ClusterNode*>::iterator i = mClients.begin();
i != mClients.end() ; i++)
{
//vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL) << "Sending data to: "
// << (*i)->getName() << " trying to lock socket" << std::endl << vprDEBUG_FLUSH;
try
{
(*i)->send(mDataPacket);
}
catch(cluster::ClusterException cluster_exception)
{
vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL) << "DeviceServer::send() Caught an exception!"
<< std::endl << vprDEBUG_FLUSH;
vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL) << clrSetBOLD(clrRED)
<< cluster_exception.getMessage() << clrRESET
<< std::endl << vprDEBUG_FLUSH;
vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL) <<
"DeviceServer::send() We have lost our connection to: " << (*i)->getName() << ":" << (*i)->getPort()
<< std::endl << vprDEBUG_FLUSH;
(*i)->setConnected(ClusterNode::DISCONNECTED);
debugDump(vprDBG_CONFIG_LVL);
}
}
//vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL)
// << clrOutBOLD(clrMAGENTA,"DeviceServer::send()")
// << "Done Sending Device Data for: " << getName() << std::endl << vprDEBUG_FLUSH;
}
void DeviceServer::updateLocalData()
{
// -BufferObjectWriter
mBufferObjectWriter->getData()->clear();
mBufferObjectWriter->setCurPos(0);
// This updates the mDeviceData which both mBufferedObjectReader and mDevicePacket point to
mDevice->writeObject(mBufferObjectWriter);
// We must update the size of the actual data that we are going to send
mDataPacket->getHeader()->setPacketLength(Header::RIM_PACKET_HEAD_SIZE
+ 16 /*Plugin GUID*/
+ 16 /*Plugin GUID*/
+ mDeviceData->size());
// We must serialize the header again so that we can reset the size.
mDataPacket->getHeader()->serializeHeader();
}
void DeviceServer::addClient(ClusterNode* new_client_node)
{
vprASSERT(new_client_node != NULL && "You can not add a new client that is NULL");
vpr::Guard<vpr::Mutex> guard(mClientsLock);
mClients.push_back(new_client_node);
}
void DeviceServer::removeClient(const std::string& host_name)
{
vpr::Guard<vpr::Mutex> guard(mClientsLock);
for (std::vector<cluster::ClusterNode*>::iterator i = mClients.begin() ;
i!= mClients.end() ; i++)
{
if ((*i)->getHostname() == host_name)
{
mClients.erase(i);
return;
}
}
}
void DeviceServer::debugDump(int debug_level)
{
vpr::Guard<vpr::Mutex> guard(mClientsLock);
vpr::DebugOutputGuard dbg_output(gadgetDBG_RIM,debug_level,
std::string("-------------- DeviceServer --------------\n"),
std::string("------------------------------------------\n"));
vprDEBUG(gadgetDBG_RIM,debug_level) << "Name: " << mName << std::endl << vprDEBUG_FLUSH;
{ // Used simply to make the following DebugOutputGuard go out of scope
vpr::DebugOutputGuard dbg_output2(gadgetDBG_RIM,debug_level,
std::string("------------ Clients ------------\n"),
std::string("---------------------------------\n"));
for (std::vector<cluster::ClusterNode*>::iterator i = mClients.begin() ;
i!= mClients.end() ; i++)
{
vprDEBUG(gadgetDBG_RIM,debug_level) << "-------- " << (*i)->getName() << " --------" << std::endl << vprDEBUG_FLUSH;
vprDEBUG(gadgetDBG_RIM,debug_level) << " Hostname: " << (*i)->getHostname() << std::endl << vprDEBUG_FLUSH;
vprDEBUG(gadgetDBG_RIM,debug_level) << "----------------------------------" << std::endl << vprDEBUG_FLUSH;
}
}
}
void DeviceServer::controlLoop(void* nullParam)
{
// -Block on an update call
// -Update Local Data
// -Send
// -Signal Sync
boost::ignore_unused_variable_warning(nullParam);
while(true)
{
// Wait for trigger
deviceServerTriggerSema.acquire();
//vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL) << "DeviceServer: " << getName() << " triggered\n" << vprDEBUG_FLUSH;
//vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL) << "Before Update Data\n" << vprDEBUG_FLUSH;
updateLocalData();
//vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL) << "After Update Data\n" << vprDEBUG_FLUSH;
//vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL) << "Before send Data\n" << vprDEBUG_FLUSH;
send();
//vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL) << "After Send Data\n" << vprDEBUG_FLUSH;
// Signal Done Rendering
deviceServerDoneSema.release();
//vprDEBUG(gadgetDBG_RIM,vprDBG_CONFIG_LVL) << "DeviceServer synced\n" << vprDEBUG_FLUSH;
}
}
/** Starts the control loop. */
void DeviceServer::start()
{
// --- Setup Multi-Process stuff --- //
// Create a new thread to handle the control
vpr::ThreadMemberFunctor<DeviceServer>* memberFunctor =
new vpr::ThreadMemberFunctor<DeviceServer>(this, &DeviceServer::controlLoop, NULL);
mControlThread = new vpr::Thread(memberFunctor);
if (mControlThread->valid())
{
mThreadActive = true;
}
vprDEBUG(gadgetDBG_RIM, vprDBG_CONFIG_LVL)
<< "DeviceServer " << getName() << " started. thread: "
<< mControlThread << std::endl << vprDEBUG_FLUSH;
}
void DeviceServer::go()
{
while(!mThreadActive)
{
vprDEBUG(gadgetDBG_RIM,/*vprDBG_HVERB_LVL*/1) << "Waiting in for thread to start DeviceServer::go().\n" << vprDEBUG_FLUSH;
vpr::Thread::yield();
}
deviceServerTriggerSema.release();
}
/**
* Blocks until the end of the frame.
* @post The frame has been drawn.
*/
void DeviceServer::sync()
{
vprASSERT(mThreadActive == true);
deviceServerDoneSema.acquire();
}
} // End of gadget namespace
<|endoftext|> |
<commit_before>#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>
#include "exec.hh"
#include "util.hh"
#include "globals.hh"
class AutoDelete
{
string path;
bool del;
public:
AutoDelete(const string & p) : path(p)
{
del = true;
}
~AutoDelete()
{
if (del) deletePath(path);
}
void cancel()
{
del = false;
}
};
/* Run a program. */
void runProgram(const string & program,
const Strings & args, const Environment & env)
{
/* Create a log file. */
string logFileName = nixLogDir + "/run.log";
/* !!! auto-pclose on exit */
FILE * logFile = popen(("tee -a " + logFileName + " >&2").c_str(), "w"); /* !!! escaping */
if (!logFile)
throw SysError(format("creating log file `%1%'") % logFileName);
/* Create a temporary directory where the build will take
place. */
static int counter = 0;
string tmpDir = (format("/tmp/nix-%1%-%2%") % getpid() % counter++).str();
if (mkdir(tmpDir.c_str(), 0777) == -1)
throw SysError(format("creating directory `%1%'") % tmpDir);
AutoDelete delTmpDir(tmpDir);
/* Fork a child to build the package. */
pid_t pid;
switch (pid = fork()) {
case -1:
throw SysError("unable to fork");
case 0:
try { /* child */
if (chdir(tmpDir.c_str()) == -1)
throw SysError(format("changing into to `%1%'") % tmpDir);
/* Fill in the arguments. */
const char * argArr[args.size() + 2];
const char * * p = argArr;
string progName = baseNameOf(program);
*p++ = progName.c_str();
for (Strings::const_iterator i = args.begin();
i != args.end(); i++)
*p++ = i->c_str();
*p = 0;
/* Fill in the environment. */
Strings envStrs;
const char * envArr[env.size() + 1];
p = envArr;
for (Environment::const_iterator i = env.begin();
i != env.end(); i++)
*p++ = envStrs.insert(envStrs.end(),
i->first + "=" + i->second)->c_str();
*p = 0;
/* Dup the log handle into stderr. */
if (dup2(fileno(logFile), STDERR_FILENO) == -1)
throw SysError("cannot pipe standard error into log file");
/* Dup stderr to stdin. */
if (dup2(STDERR_FILENO, STDOUT_FILENO) == -1)
throw SysError("cannot dup stderr into stdout");
/* Execute the program. This should not return. */
execve(program.c_str(), (char * *) argArr, (char * *) envArr);
throw SysError(format("unable to execute %1%") % program);
} catch (exception & e) {
cerr << format("build error: %1%\n") % e.what();
}
_exit(1);
}
/* parent */
/* Close the logging pipe. Note that this should not cause
the logger to exit until builder exits (because the latter
has an open file handle to the former). */
pclose(logFile);
/* Wait for the child to finish. */
int status;
if (waitpid(pid, &status, 0) != pid)
throw Error("unable to wait for child");
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
if (keepFailed) {
msg(lvlTalkative,
format("build failed; keeping build directory `%1%'") % tmpDir);
delTmpDir.cancel();
}
throw Error("unable to build package");
}
}
<commit_msg>* Pipe /dev/null into stdin.<commit_after>#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>
#include "exec.hh"
#include "util.hh"
#include "globals.hh"
class AutoDelete
{
string path;
bool del;
public:
AutoDelete(const string & p) : path(p)
{
del = true;
}
~AutoDelete()
{
if (del) deletePath(path);
}
void cancel()
{
del = false;
}
};
static string pathNullDevice = "/dev/null";
/* Run a program. */
void runProgram(const string & program,
const Strings & args, const Environment & env)
{
/* Create a log file. */
string logFileName = nixLogDir + "/run.log";
/* !!! auto-pclose on exit */
FILE * logFile = popen(("tee -a " + logFileName + " >&2").c_str(), "w"); /* !!! escaping */
if (!logFile)
throw SysError(format("creating log file `%1%'") % logFileName);
/* Create a temporary directory where the build will take
place. */
static int counter = 0;
string tmpDir = (format("/tmp/nix-%1%-%2%") % getpid() % counter++).str();
if (mkdir(tmpDir.c_str(), 0777) == -1)
throw SysError(format("creating directory `%1%'") % tmpDir);
AutoDelete delTmpDir(tmpDir);
/* Fork a child to build the package. */
pid_t pid;
switch (pid = fork()) {
case -1:
throw SysError("unable to fork");
case 0:
try { /* child */
if (chdir(tmpDir.c_str()) == -1)
throw SysError(format("changing into to `%1%'") % tmpDir);
/* Fill in the arguments. */
const char * argArr[args.size() + 2];
const char * * p = argArr;
string progName = baseNameOf(program);
*p++ = progName.c_str();
for (Strings::const_iterator i = args.begin();
i != args.end(); i++)
*p++ = i->c_str();
*p = 0;
/* Fill in the environment. */
Strings envStrs;
const char * envArr[env.size() + 1];
p = envArr;
for (Environment::const_iterator i = env.begin();
i != env.end(); i++)
*p++ = envStrs.insert(envStrs.end(),
i->first + "=" + i->second)->c_str();
*p = 0;
/* Dup the log handle into stderr. */
if (dup2(fileno(logFile), STDERR_FILENO) == -1)
throw SysError("cannot pipe standard error into log file");
/* Dup stderr to stdin. */
if (dup2(STDERR_FILENO, STDOUT_FILENO) == -1)
throw SysError("cannot dup stderr into stdout");
/* Reroute stdin to /dev/null. */
int fdDevNull = open(pathNullDevice.c_str(), O_RDWR);
if (fdDevNull == -1)
throw SysError(format("cannot open `%1%'") % pathNullDevice);
if (dup2(fdDevNull, STDIN_FILENO) == -1)
throw SysError("cannot dup null device into stdin");
/* Execute the program. This should not return. */
execve(program.c_str(), (char * *) argArr, (char * *) envArr);
throw SysError(format("unable to execute %1%") % program);
} catch (exception & e) {
cerr << format("build error: %1%\n") % e.what();
}
_exit(1);
}
/* parent */
/* Close the logging pipe. Note that this should not cause
the logger to exit until builder exits (because the latter
has an open file handle to the former). */
pclose(logFile);
/* Wait for the child to finish. */
int status;
if (waitpid(pid, &status, 0) != pid)
throw Error("unable to wait for child");
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
if (keepFailed) {
msg(lvlTalkative,
format("build failed; keeping build directory `%1%'") % tmpDir);
delTmpDir.cancel();
}
throw Error("unable to build package");
}
}
<|endoftext|> |
<commit_before>#include "file.hh"
#include "assert.hh"
#include "buffer.hh"
#include "buffer_manager.hh"
#include "completion.hh"
#include "debug.hh"
#include "unicode.hh"
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <dirent.h>
namespace Kakoune
{
String parse_filename(StringView filename)
{
if (filename.length() >= 1 and filename[0] == '~' and
(filename.length() == 1 or filename[1] == '/'))
return parse_filename("$HOME"_str + filename.substr(1_byte));
ByteCount pos = 0;
String result;
for (ByteCount i = 0; i < filename.length(); ++i)
{
if (filename[i] == '$' and (i == 0 or filename[i-1] != '\\'))
{
result += filename.substr(pos, i - pos);
ByteCount end = i+1;
while (end != filename.length() and is_word(filename[end]))
++end;
StringView var_name = filename.substr(i+1, end - i - 1);
const char* var_value = getenv(var_name.str().c_str());
if (var_value)
result += var_value;
pos = end;
}
}
if (pos != filename.length())
result += filename.substr(pos);
return result;
}
String real_path(StringView filename)
{
StringView dirname = ".";
StringView basename = filename;
auto it = find(filename.rbegin(), filename.rend(), '/');
if (it != filename.rend())
{
dirname = StringView{filename.begin(), it.base()};
basename = StringView{it.base(), filename.end()};
}
char buffer[PATH_MAX+1];
char* res = realpath(dirname.str().c_str(), buffer);
if (not res)
throw file_not_found{dirname};
return res + "/"_str + basename;
}
String compact_path(StringView filename)
{
String real_filename = real_path(filename);
char cwd[1024];
getcwd(cwd, 1024);
String real_cwd = real_path(cwd) + '/';
if (prefix_match(real_filename, real_cwd))
return real_filename.substr(real_cwd.length());
const char* home = getenv("HOME");
if (home)
{
ByteCount home_len = (int)strlen(home);
if (real_filename.substr(0, home_len) == home)
return "~" + real_filename.substr(home_len);
}
return filename.str();
}
String read_file(StringView filename)
{
int fd = open(parse_filename(filename).c_str(), O_RDONLY);
if (fd == -1)
{
if (errno == ENOENT)
throw file_not_found(filename);
throw file_access_error(filename, strerror(errno));
}
auto close_fd = on_scope_end([fd]{ close(fd); });
String content;
char buf[256];
while (true)
{
ssize_t size = read(fd, buf, 256);
if (size == -1 or size == 0)
break;
content += String(buf, buf + size);
}
return content;
}
Buffer* create_buffer_from_file(String filename)
{
filename = real_path(parse_filename(filename));
int fd = open(filename.c_str(), O_RDONLY);
if (fd == -1)
{
if (errno == ENOENT)
return nullptr;
throw file_access_error(filename, strerror(errno));
}
struct stat st;
fstat(fd, &st);
if (S_ISDIR(st.st_mode))
{
close(fd);
throw file_access_error(filename, "is a directory");
}
const char* data = (const char*)mmap(nullptr, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
auto cleanup = on_scope_end([&]{ munmap((void*)data, st.st_size); close(fd); });
const char* pos = data;
bool crlf = false;
bool bom = false;
if (st.st_size >= 3 and
data[0] == '\xEF' and data[1] == '\xBB' and data[2] == '\xBF')
{
bom = true;
pos = data + 3;
}
std::vector<String> lines;
const char* end = data + st.st_size;
while (pos < end)
{
const char* line_end = pos;
while (line_end < end and *line_end != '\r' and *line_end != '\n')
++line_end;
// this should happen only when opening a file which has no
// end of line as last character.
if (line_end == end)
{
lines.emplace_back(pos, line_end);
lines.back() += '\n';
break;
}
lines.emplace_back(pos, line_end + 1);
lines.back().back() = '\n';
if (line_end+1 != end and *line_end == '\r' and *(line_end+1) == '\n')
{
crlf = true;
pos = line_end + 2;
}
else
pos = line_end + 1;
}
Buffer* buffer = BufferManager::instance().get_buffer_ifp(filename);
if (buffer)
buffer->reload(std::move(lines), st.st_mtime);
else
buffer = new Buffer{filename, Buffer::Flags::File,
std::move(lines), st.st_mtime};
OptionManager& options = buffer->options();
options.get_local_option("eolformat").set<String>(crlf ? "crlf" : "lf");
options.get_local_option("BOM").set<String>(bom ? "utf-8" : "no");
return buffer;
}
static void write(int fd, StringView data, StringView filename)
{
const char* ptr = data.data();
ssize_t count = (int)data.length();
while (count)
{
ssize_t written = ::write(fd, ptr, count);
ptr += written;
count -= written;
if (written == -1)
throw file_access_error(filename, strerror(errno));
}
}
void write_buffer_to_file(Buffer& buffer, StringView filename)
{
buffer.run_hook_in_own_context("BufWritePre", buffer.name());
const String& eolformat = buffer.options()["eolformat"].get<String>();
StringView eoldata;
if (eolformat == "crlf")
eoldata = "\r\n";
else
eoldata = "\n";
{
int fd = open(parse_filename(filename).c_str(),
O_CREAT | O_WRONLY | O_TRUNC, 0644);
if (fd == -1)
throw file_access_error(filename, strerror(errno));
auto close_fd = on_scope_end([fd]{ close(fd); });
if (buffer.options()["BOM"].get<String>() == "utf-8")
::write(fd, "\xEF\xBB\xBF", 3);
for (LineCount i = 0; i < buffer.line_count(); ++i)
{
// end of lines are written according to eolformat but always
// stored as \n
StringView linedata = buffer[i];
write(fd, linedata.substr(0, linedata.length()-1), filename);
write(fd, eoldata, filename);
}
}
if ((buffer.flags() & Buffer::Flags::File) and filename == buffer.name())
buffer.notify_saved();
buffer.run_hook_in_own_context("BufWritePost", buffer.name());
}
String find_file(StringView filename, memoryview<String> paths)
{
struct stat buf;
if (filename.length() > 1 and filename[0] == '/')
{
if (stat(filename.str().c_str(), &buf) == 0 and S_ISREG(buf.st_mode))
return filename.str();
return "";
}
if (filename.length() > 2 and
filename[0] == '~' and filename[1] == '/')
{
String candidate = getenv("HOME") + filename.substr(1_byte).str();
if (stat(candidate.c_str(), &buf) == 0 and S_ISREG(buf.st_mode))
return candidate;
return "";
}
for (auto candidate : paths)
{
if (not candidate.empty() and candidate.back() != '/')
candidate += '/';
candidate += filename;
if (stat(candidate.c_str(), &buf) == 0 and S_ISREG(buf.st_mode))
return candidate;
}
return "";
}
template<typename Filter>
std::vector<String> list_files(StringView prefix, StringView dirname,
Filter filter)
{
kak_assert(dirname.empty() or dirname.back() == '/');
DIR* dir = opendir(dirname.empty() ? "./" : dirname.str().c_str());
if (not dir)
return {};
auto closeDir = on_scope_end([=]{ closedir(dir); });
std::vector<String> result;
std::vector<String> subseq_result;
while (dirent* entry = readdir(dir))
{
if (not filter(*entry))
continue;
String filename = entry->d_name;
if (filename.empty())
continue;
const bool match_prefix = prefix_match(filename, prefix);
const bool match_subseq = subsequence_match(filename, prefix);
struct stat st;
if ((match_prefix or match_subseq) and
stat((dirname + filename).c_str(), &st) == 0)
{
if (S_ISDIR(st.st_mode))
filename += '/';
if (prefix.length() != 0 or filename[0] != '.')
{
if (match_prefix)
result.push_back(filename);
if (match_subseq)
subseq_result.push_back(filename);
}
}
}
return result.empty() ? subseq_result : result;
}
std::vector<String> complete_filename(StringView prefix,
const Regex& ignored_regex,
ByteCount cursor_pos)
{
String real_prefix = parse_filename(prefix.substr(0, cursor_pos));
String dirname;
String fileprefix = real_prefix;
ByteCount dir_end = -1;
for (ByteCount i = 0; i < real_prefix.length(); ++i)
{
if (real_prefix[i] == '/')
dir_end = i;
}
if (dir_end != -1)
{
dirname = real_prefix.substr(0, dir_end + 1);
fileprefix = real_prefix.substr(dir_end + 1);
}
const bool check_ignored_regex = not ignored_regex.empty() and
not boost::regex_match(fileprefix.c_str(), ignored_regex);
auto filter = [&](const dirent& entry)
{
return not check_ignored_regex or
not boost::regex_match(entry.d_name, ignored_regex);
};
std::vector<String> res = list_files(fileprefix, dirname, filter);
for (auto& file : res)
file = escape(dirname + file);
std::sort(res.begin(), res.end());
return res;
}
std::vector<String> complete_command(StringView prefix, ByteCount cursor_pos)
{
String real_prefix = parse_filename(prefix.substr(0, cursor_pos));
String dirname;
String fileprefix = real_prefix;
ByteCount dir_end = -1;
for (ByteCount i = 0; i < real_prefix.length(); ++i)
{
if (real_prefix[i] == '/')
dir_end = i;
}
std::vector<String> path;
if (dir_end != -1)
{
path.emplace_back(real_prefix.substr(0, dir_end + 1));
fileprefix = real_prefix.substr(dir_end + 1);
}
else
path = split(getenv("PATH"), ':');
std::vector<String> res;
for (auto dirname : path)
{
if (not dirname.empty() and dirname.back() != '/')
dirname += '/';
auto filter = [&](const dirent& entry) {
struct stat st;
if (stat((dirname + entry.d_name).c_str(), &st))
return false;
bool executable = (st.st_mode & S_IXUSR)
| (st.st_mode & S_IXGRP)
| (st.st_mode & S_IXOTH);
return S_ISREG(st.st_mode) and executable;
};
auto completion = list_files(prefix, dirname, filter);
std::move(completion.begin(), completion.end(), std::back_inserter(res));
}
std::sort(res.begin(), res.end());
auto it = std::unique(res.begin(), res.end());
res.erase(it, res.end());
return res;
}
time_t get_fs_timestamp(StringView filename)
{
struct stat st;
if (stat(filename.str().c_str(), &st) != 0)
return InvalidTime;
return st.st_mtime;
}
}
<commit_msg>use StringView::zstr() in place of StringView::str().c_str()<commit_after>#include "file.hh"
#include "assert.hh"
#include "buffer.hh"
#include "buffer_manager.hh"
#include "completion.hh"
#include "debug.hh"
#include "unicode.hh"
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <dirent.h>
namespace Kakoune
{
String parse_filename(StringView filename)
{
if (filename.length() >= 1 and filename[0] == '~' and
(filename.length() == 1 or filename[1] == '/'))
return parse_filename("$HOME"_str + filename.substr(1_byte));
ByteCount pos = 0;
String result;
for (ByteCount i = 0; i < filename.length(); ++i)
{
if (filename[i] == '$' and (i == 0 or filename[i-1] != '\\'))
{
result += filename.substr(pos, i - pos);
ByteCount end = i+1;
while (end != filename.length() and is_word(filename[end]))
++end;
StringView var_name = filename.substr(i+1, end - i - 1);
const char* var_value = getenv(var_name.zstr());
if (var_value)
result += var_value;
pos = end;
}
}
if (pos != filename.length())
result += filename.substr(pos);
return result;
}
String real_path(StringView filename)
{
StringView dirname = ".";
StringView basename = filename;
auto it = find(filename.rbegin(), filename.rend(), '/');
if (it != filename.rend())
{
dirname = StringView{filename.begin(), it.base()};
basename = StringView{it.base(), filename.end()};
}
char buffer[PATH_MAX+1];
char* res = realpath(dirname.zstr(), buffer);
if (not res)
throw file_not_found{dirname};
return res + "/"_str + basename;
}
String compact_path(StringView filename)
{
String real_filename = real_path(filename);
char cwd[1024];
getcwd(cwd, 1024);
String real_cwd = real_path(cwd) + '/';
if (prefix_match(real_filename, real_cwd))
return real_filename.substr(real_cwd.length());
const char* home = getenv("HOME");
if (home)
{
ByteCount home_len = (int)strlen(home);
if (real_filename.substr(0, home_len) == home)
return "~" + real_filename.substr(home_len);
}
return filename.str();
}
String read_file(StringView filename)
{
int fd = open(parse_filename(filename).c_str(), O_RDONLY);
if (fd == -1)
{
if (errno == ENOENT)
throw file_not_found(filename);
throw file_access_error(filename, strerror(errno));
}
auto close_fd = on_scope_end([fd]{ close(fd); });
String content;
char buf[256];
while (true)
{
ssize_t size = read(fd, buf, 256);
if (size == -1 or size == 0)
break;
content += String(buf, buf + size);
}
return content;
}
Buffer* create_buffer_from_file(String filename)
{
filename = real_path(parse_filename(filename));
int fd = open(filename.c_str(), O_RDONLY);
if (fd == -1)
{
if (errno == ENOENT)
return nullptr;
throw file_access_error(filename, strerror(errno));
}
struct stat st;
fstat(fd, &st);
if (S_ISDIR(st.st_mode))
{
close(fd);
throw file_access_error(filename, "is a directory");
}
const char* data = (const char*)mmap(nullptr, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
auto cleanup = on_scope_end([&]{ munmap((void*)data, st.st_size); close(fd); });
const char* pos = data;
bool crlf = false;
bool bom = false;
if (st.st_size >= 3 and
data[0] == '\xEF' and data[1] == '\xBB' and data[2] == '\xBF')
{
bom = true;
pos = data + 3;
}
std::vector<String> lines;
const char* end = data + st.st_size;
while (pos < end)
{
const char* line_end = pos;
while (line_end < end and *line_end != '\r' and *line_end != '\n')
++line_end;
// this should happen only when opening a file which has no
// end of line as last character.
if (line_end == end)
{
lines.emplace_back(pos, line_end);
lines.back() += '\n';
break;
}
lines.emplace_back(pos, line_end + 1);
lines.back().back() = '\n';
if (line_end+1 != end and *line_end == '\r' and *(line_end+1) == '\n')
{
crlf = true;
pos = line_end + 2;
}
else
pos = line_end + 1;
}
Buffer* buffer = BufferManager::instance().get_buffer_ifp(filename);
if (buffer)
buffer->reload(std::move(lines), st.st_mtime);
else
buffer = new Buffer{filename, Buffer::Flags::File,
std::move(lines), st.st_mtime};
OptionManager& options = buffer->options();
options.get_local_option("eolformat").set<String>(crlf ? "crlf" : "lf");
options.get_local_option("BOM").set<String>(bom ? "utf-8" : "no");
return buffer;
}
static void write(int fd, StringView data, StringView filename)
{
const char* ptr = data.data();
ssize_t count = (int)data.length();
while (count)
{
ssize_t written = ::write(fd, ptr, count);
ptr += written;
count -= written;
if (written == -1)
throw file_access_error(filename, strerror(errno));
}
}
void write_buffer_to_file(Buffer& buffer, StringView filename)
{
buffer.run_hook_in_own_context("BufWritePre", buffer.name());
const String& eolformat = buffer.options()["eolformat"].get<String>();
StringView eoldata;
if (eolformat == "crlf")
eoldata = "\r\n";
else
eoldata = "\n";
{
int fd = open(parse_filename(filename).c_str(),
O_CREAT | O_WRONLY | O_TRUNC, 0644);
if (fd == -1)
throw file_access_error(filename, strerror(errno));
auto close_fd = on_scope_end([fd]{ close(fd); });
if (buffer.options()["BOM"].get<String>() == "utf-8")
::write(fd, "\xEF\xBB\xBF", 3);
for (LineCount i = 0; i < buffer.line_count(); ++i)
{
// end of lines are written according to eolformat but always
// stored as \n
StringView linedata = buffer[i];
write(fd, linedata.substr(0, linedata.length()-1), filename);
write(fd, eoldata, filename);
}
}
if ((buffer.flags() & Buffer::Flags::File) and filename == buffer.name())
buffer.notify_saved();
buffer.run_hook_in_own_context("BufWritePost", buffer.name());
}
String find_file(StringView filename, memoryview<String> paths)
{
struct stat buf;
if (filename.length() > 1 and filename[0] == '/')
{
if (stat(filename.zstr(), &buf) == 0 and S_ISREG(buf.st_mode))
return filename.str();
return "";
}
if (filename.length() > 2 and
filename[0] == '~' and filename[1] == '/')
{
String candidate = getenv("HOME") + filename.substr(1_byte).str();
if (stat(candidate.c_str(), &buf) == 0 and S_ISREG(buf.st_mode))
return candidate;
return "";
}
for (auto candidate : paths)
{
if (not candidate.empty() and candidate.back() != '/')
candidate += '/';
candidate += filename;
if (stat(candidate.c_str(), &buf) == 0 and S_ISREG(buf.st_mode))
return candidate;
}
return "";
}
template<typename Filter>
std::vector<String> list_files(StringView prefix, StringView dirname,
Filter filter)
{
kak_assert(dirname.empty() or dirname.back() == '/');
DIR* dir = opendir(dirname.empty() ? "./" : dirname.zstr());
if (not dir)
return {};
auto closeDir = on_scope_end([=]{ closedir(dir); });
std::vector<String> result;
std::vector<String> subseq_result;
while (dirent* entry = readdir(dir))
{
if (not filter(*entry))
continue;
String filename = entry->d_name;
if (filename.empty())
continue;
const bool match_prefix = prefix_match(filename, prefix);
const bool match_subseq = subsequence_match(filename, prefix);
struct stat st;
if ((match_prefix or match_subseq) and
stat((dirname + filename).c_str(), &st) == 0)
{
if (S_ISDIR(st.st_mode))
filename += '/';
if (prefix.length() != 0 or filename[0] != '.')
{
if (match_prefix)
result.push_back(filename);
if (match_subseq)
subseq_result.push_back(filename);
}
}
}
return result.empty() ? subseq_result : result;
}
std::vector<String> complete_filename(StringView prefix,
const Regex& ignored_regex,
ByteCount cursor_pos)
{
String real_prefix = parse_filename(prefix.substr(0, cursor_pos));
String dirname;
String fileprefix = real_prefix;
ByteCount dir_end = -1;
for (ByteCount i = 0; i < real_prefix.length(); ++i)
{
if (real_prefix[i] == '/')
dir_end = i;
}
if (dir_end != -1)
{
dirname = real_prefix.substr(0, dir_end + 1);
fileprefix = real_prefix.substr(dir_end + 1);
}
const bool check_ignored_regex = not ignored_regex.empty() and
not boost::regex_match(fileprefix.c_str(), ignored_regex);
auto filter = [&](const dirent& entry)
{
return not check_ignored_regex or
not boost::regex_match(entry.d_name, ignored_regex);
};
std::vector<String> res = list_files(fileprefix, dirname, filter);
for (auto& file : res)
file = escape(dirname + file);
std::sort(res.begin(), res.end());
return res;
}
std::vector<String> complete_command(StringView prefix, ByteCount cursor_pos)
{
String real_prefix = parse_filename(prefix.substr(0, cursor_pos));
String dirname;
String fileprefix = real_prefix;
ByteCount dir_end = -1;
for (ByteCount i = 0; i < real_prefix.length(); ++i)
{
if (real_prefix[i] == '/')
dir_end = i;
}
std::vector<String> path;
if (dir_end != -1)
{
path.emplace_back(real_prefix.substr(0, dir_end + 1));
fileprefix = real_prefix.substr(dir_end + 1);
}
else
path = split(getenv("PATH"), ':');
std::vector<String> res;
for (auto dirname : path)
{
if (not dirname.empty() and dirname.back() != '/')
dirname += '/';
auto filter = [&](const dirent& entry) {
struct stat st;
if (stat((dirname + entry.d_name).c_str(), &st))
return false;
bool executable = (st.st_mode & S_IXUSR)
| (st.st_mode & S_IXGRP)
| (st.st_mode & S_IXOTH);
return S_ISREG(st.st_mode) and executable;
};
auto completion = list_files(prefix, dirname, filter);
std::move(completion.begin(), completion.end(), std::back_inserter(res));
}
std::sort(res.begin(), res.end());
auto it = std::unique(res.begin(), res.end());
res.erase(it, res.end());
return res;
}
time_t get_fs_timestamp(StringView filename)
{
struct stat st;
if (stat(filename.zstr(), &st) != 0)
return InvalidTime;
return st.st_mtime;
}
}
<|endoftext|> |
<commit_before>// Filename: test_audio.cxx
// Created by: cary (24Sep00)
//
////////////////////////////////////////////////////////////////////
#include <pandabase.h>
#include "audio.h"
#include "config_audio.h"
#include <ipc_traits.h>
int
main(int argc, char* argv[]) {
if (! AudioPool::verify_sample("test.wav")) {
audio_cat->fatal() << "could not locate 'test.wav'" << endl;
exit(-1);
}
AudioSample* sample = AudioPool::load_sample("test.wav");
audio_cat->info() << "test.wav is " << sample->length() << "sec long"
<< endl;
audio_cat->info() << "Playing test.wav" << endl;
AudioManager::play(sample);
while (sample->status() == AudioSample::PLAYING) {
AudioManager::update();
ipc_traits::sleep(0, 1000000);
}
// AudioMidi foo("test.midi");
if (! AudioPool::verify_music("test.midi")) {
audio_cat->fatal() << "could not locate 'test.midi'" << endl;
exit(-1);
}
AudioMusic* music = AudioPool::load_music("test.midi");
audio_cat->info() << "Playing test.midi" << endl;
AudioManager::play(music);
while (music->status() == AudioMusic::PLAYING) {
AudioManager::update();
ipc_traits::sleep(0, 1000000);
}
return 0;
}
<commit_msg>screwing around with mp3<commit_after>// Filename: test_audio.cxx
// Created by: cary (24Sep00)
//
////////////////////////////////////////////////////////////////////
#include <pandabase.h>
#include "audio.h"
#include "config_audio.h"
#include <ipc_traits.h>
int
main(int argc, char* argv[]) {
// if (! AudioPool::verify_sample("test.wav")) {
// audio_cat->fatal() << "could not locate 'test.wav'" << endl;
// exit(-1);
// }
if (! AudioPool::verify_sample("test.mp3")) {
audio_cat->fatal() << "could not locate 'test.mp3'" << endl;
exit(-1);
}
// AudioSample* sample = AudioPool::load_sample("test.wav");
AudioSample* sample = AudioPool::load_sample("test.mp3");
audio_cat->info() << "test.wav is " << sample->length() << "sec long"
<< endl;
audio_cat->info() << "Playing test.wav" << endl;
AudioManager::play(sample);
while (sample->status() == AudioSample::PLAYING) {
AudioManager::update();
ipc_traits::sleep(0, 1000000);
}
// AudioMidi foo("test.midi");
if (! AudioPool::verify_music("test.midi")) {
audio_cat->fatal() << "could not locate 'test.midi'" << endl;
exit(-1);
}
AudioMusic* music = AudioPool::load_music("test.midi");
audio_cat->info() << "Playing test.midi" << endl;
AudioManager::play(music);
while (music->status() == AudioMusic::PLAYING) {
AudioManager::update();
ipc_traits::sleep(0, 1000000);
}
return 0;
}
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <iostream>
#include <boost/thread.hpp>
#include <boost/foreach.hpp>
#include <Dataflow/Engine/Controller/NetworkEditorController.h>
#include <Dataflow/Network/Connection.h>
#include <Dataflow/Network/Network.h>
#include <Dataflow/Network/ModuleDescription.h>
#include <Dataflow/Network/Module.h>
#include <Dataflow/Network/ModuleFactory.h>
#include <Dataflow/Serialization/Network/NetworkXMLSerializer.h>
#include <Dataflow/Serialization/Network/NetworkDescriptionSerialization.h>
#include <Dataflow/Engine/Controller/DynamicPortManager.h>
#include <Core/Logging/Log.h>
#ifdef BUILD_WITH_PYTHON
#include <Dataflow/Engine/Python/NetworkEditorPythonAPI.h>
#include <Dataflow/Engine/Controller/PythonImpl.h>
#endif
using namespace SCIRun;
using namespace SCIRun::Dataflow::Engine;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core::Logging;
using namespace SCIRun::Core;
NetworkEditorController::NetworkEditorController(ModuleFactoryHandle mf, ModuleStateFactoryHandle sf, ExecutionStrategyFactoryHandle executorFactory, AlgorithmFactoryHandle af, ModulePositionEditor* mpg) :
theNetwork_(new Network(mf, sf, af)),
moduleFactory_(mf),
stateFactory_(sf),
algoFactory_(af),
executorFactory_(executorFactory),
modulePositionEditor_(mpg)
{
dynamicPortManager_.reset(new DynamicPortManager(connectionAdded_, connectionRemoved_, this));
//TODO should this class own the network or just keep a reference?
#ifdef BUILD_WITH_PYTHON
NetworkEditorPythonAPI::setImpl(boost::make_shared<PythonImpl>(*this));
#endif
}
NetworkEditorController::NetworkEditorController(SCIRun::Dataflow::Networks::NetworkHandle network, ExecutionStrategyFactoryHandle executorFactory, ModulePositionEditor* mpg)
: theNetwork_(network), executorFactory_(executorFactory), modulePositionEditor_(mpg)
{
}
ModuleHandle NetworkEditorController::addModule(const std::string& moduleName)
{
auto realModule = addModuleImpl(moduleName);
/*emit*/ moduleAdded_(moduleName, realModule);
printNetwork();
return realModule;
}
ModuleHandle NetworkEditorController::addModuleImpl(const std::string& moduleName)
{
//TODO: should pass in entire info struct
ModuleLookupInfo info;
info.module_name_ = moduleName;
ModuleHandle realModule = theNetwork_->add_module(info);
return realModule;
}
void NetworkEditorController::removeModule(const ModuleId& id)
{
//auto disableDynamicPortManager(createDynamicPortSwitch());
theNetwork_->remove_module(id);
//before or after?
// deciding on after: ProvenanceWindow/Manager wants the state *after* removal.
/*emit*/ moduleRemoved_(id);
printNetwork();
}
ModuleHandle NetworkEditorController::duplicateModule(const ModuleHandle& module)
{
//auto disableDynamicPortManager(createDynamicPortSwitch());
ENSURE_NOT_NULL(module, "Cannot duplicate null module");
ModuleId id(module->get_id());
auto newModule = addModuleImpl(id.name_);
newModule->set_state(module->get_state()->clone());
moduleAdded_(id.name_, newModule);
//TODO: probably a pretty poor way to deal with what I think is a race condition with signaling the GUI to place the module widget.
boost::this_thread::sleep(boost::posix_time::milliseconds(1));
BOOST_FOREACH(InputPortHandle input, module->inputPorts())
{
if (input->nconnections() == 1)
{
auto conn = input->connection(0);
auto source = conn->oport_;
//TODO: this will work if we define PortId.id# to be 0..n, unique for each module. But what about gaps?
requestConnection(source.get(), newModule->getInputPort(input->id()).get());
}
}
return newModule;
}
void NetworkEditorController::connectNewModule(const SCIRun::Dataflow::Networks::ModuleHandle& moduleToConnectTo, const SCIRun::Dataflow::Networks::PortDescriptionInterface* portToConnect, const std::string& newModuleName)
{
auto newMod = addModule(newModuleName);
//TODO: see above
boost::this_thread::sleep(boost::posix_time::milliseconds(1));
//TODO duplication
if (portToConnect->isInput())
{
BOOST_FOREACH(OutputPortHandle p, newMod->outputPorts())
{
if (p->get_typename() == portToConnect->get_typename())
{
requestConnection(p.get(), portToConnect);
return;
}
}
}
else
{
BOOST_FOREACH(InputPortHandle p, newMod->inputPorts())
{
if (p->get_typename() == portToConnect->get_typename())
{
requestConnection(p.get(), portToConnect);
return;
}
}
}
}
void NetworkEditorController::printNetwork() const
{
//TODO: and make this switchable
if (false)
{
if (theNetwork_)
LOG_DEBUG(theNetwork_->toString() << std::endl);
}
}
void NetworkEditorController::requestConnection(const SCIRun::Dataflow::Networks::PortDescriptionInterface* from, const SCIRun::Dataflow::Networks::PortDescriptionInterface* to)
{
ENSURE_NOT_NULL(from, "from port");
ENSURE_NOT_NULL(to, "to port");
auto out = from->isInput() ? to : from;
auto in = from->isInput() ? from : to;
ConnectionDescription desc(
OutgoingConnectionDescription(out->getUnderlyingModuleId(), out->id()),
IncomingConnectionDescription(in->getUnderlyingModuleId(), in->id()));
PortConnectionDeterminer q;
if (q.canBeConnected(*from, *to))
{
ConnectionId id = theNetwork_->connect(ConnectionOutputPort(theNetwork_->lookupModule(desc.out_.moduleId_), desc.out_.portId_),
ConnectionInputPort(theNetwork_->lookupModule(desc.in_.moduleId_), desc.in_.portId_));
if (!id.id_.empty())
connectionAdded_(desc);
printNetwork();
}
else
{
Log::get() << NOTICE << "Invalid Connection request: input port is full, or ports are different datatype or same i/o type, or on the same module." << std::endl;
invalidConnection_(desc);
}
}
void NetworkEditorController::removeConnection(const ConnectionId& id)
{
if (theNetwork_->disconnect(id))
connectionRemoved_(id);
printNetwork();
}
boost::signals2::connection NetworkEditorController::connectModuleAdded(const ModuleAddedSignalType::slot_type& subscriber)
{
return moduleAdded_.connect(subscriber);
}
boost::signals2::connection NetworkEditorController::connectModuleRemoved(const ModuleRemovedSignalType::slot_type& subscriber)
{
return moduleRemoved_.connect(subscriber);
}
boost::signals2::connection NetworkEditorController::connectConnectionAdded(const ConnectionAddedSignalType::slot_type& subscriber)
{
return connectionAdded_.connect(subscriber);
}
boost::signals2::connection NetworkEditorController::connectConnectionRemoved(const ConnectionRemovedSignalType::slot_type& subscriber)
{
return connectionRemoved_.connect(subscriber);
}
boost::signals2::connection NetworkEditorController::connectInvalidConnection(const InvalidConnectionSignalType::slot_type& subscriber)
{
return invalidConnection_.connect(subscriber);
}
boost::signals2::connection NetworkEditorController::connectNetworkExecutionStarts(const ExecuteAllStartsSignalType::slot_type& subscriber)
{
return ExecutionStrategy::connectNetworkExecutionStarts(subscriber);
}
boost::signals2::connection NetworkEditorController::connectNetworkExecutionFinished(const ExecuteAllFinishesSignalType::slot_type& subscriber)
{
return ExecutionStrategy::connectNetworkExecutionFinished(subscriber);
}
boost::signals2::connection NetworkEditorController::connectPortAdded(const PortAddedSignalType::slot_type& subscriber)
{
return dynamicPortManager_->connectPortAdded(subscriber);
}
boost::signals2::connection NetworkEditorController::connectPortRemoved(const PortRemovedSignalType::slot_type& subscriber)
{
return dynamicPortManager_->connectPortRemoved(subscriber);
}
NetworkFileHandle NetworkEditorController::saveNetwork() const
{
NetworkToXML conv(modulePositionEditor_);
return conv.to_xml_data(theNetwork_);
}
void NetworkEditorController::loadNetwork(const NetworkFileHandle& xml)
{
if (xml)
{
try
{
NetworkXMLConverter conv(moduleFactory_, stateFactory_, algoFactory_, this);
theNetwork_ = conv.from_xml_data(xml->network);
for (size_t i = 0; i < theNetwork_->nmodules(); ++i)
{
ModuleHandle module = theNetwork_->module(i);
moduleAdded_(module->get_module_name(), module);
}
{
auto disable(createDynamicPortSwitch());
//this is handled by NetworkXMLConverter now--but now the logic is convoluted.
//They need to be signaled again after the modules are signaled to alert the GUI. Hence the disabling of DPM
BOOST_FOREACH(const ConnectionDescription& cd, theNetwork_->connections())
{
ConnectionId id = ConnectionId::create(cd);
connectionAdded_(cd);
}
}
if (modulePositionEditor_)
modulePositionEditor_->moveModules(xml->modulePositions);
else
std::cout << "module position editor is null" << std::endl;
}
catch (ExceptionBase& e)
{
Log::get() << ERROR << "File load failed: exception while processing xml network data: " << e.what() << std::endl;
theNetwork_->clear();
throw;
}
}
}
void NetworkEditorController::clear()
{
//std::cout << "NetworkEditorController::clear()" << std::endl;
}
void NetworkEditorController::executeAll(const ExecutableLookup* lookup)
{
if (!currentExecutor_)
currentExecutor_ = executorFactory_->create(ExecutionStrategy::DYNAMIC_PARALLEL); //TODO: read some setting for default executor type
currentExecutor_->executeAll(*theNetwork_, lookup ? *lookup : *theNetwork_);
theNetwork_->setModuleExecutionState(ModuleInterface::Waiting);
}
NetworkHandle NetworkEditorController::getNetwork() const
{
return theNetwork_;
}
void NetworkEditorController::setNetwork(NetworkHandle nh)
{
ENSURE_NOT_NULL(nh, "Null network.");
theNetwork_ = nh;
}
NetworkGlobalSettings& NetworkEditorController::getSettings()
{
return theNetwork_->settings();
}
void NetworkEditorController::setExecutorType(int type)
{
currentExecutor_ = executorFactory_->create((ExecutionStrategy::Type)type);
}
const ModuleDescriptionMap& NetworkEditorController::getAllAvailableModuleDescriptions() const
{
return moduleFactory_->getAllAvailableModuleDescriptions();
}
boost::shared_ptr<DisableDynamicPortSwitch> NetworkEditorController::createDynamicPortSwitch()
{
return boost::make_shared<DisableDynamicPortSwitch>(dynamicPortManager_);
}
DisableDynamicPortSwitch::DisableDynamicPortSwitch(boost::shared_ptr<DynamicPortManager> dpm) : first_(true), dpm_(dpm)
{
if (dpm_)
{
first_ = !dpm_->isDisabled();
if (first_)
dpm_->disable();
}
}
DisableDynamicPortSwitch::~DisableDynamicPortSwitch()
{
if (dpm_ && first_)
dpm_->enable();
}<commit_msg>Switch back to working version<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <iostream>
#include <boost/thread.hpp>
#include <boost/foreach.hpp>
#include <Dataflow/Engine/Controller/NetworkEditorController.h>
#include <Dataflow/Network/Connection.h>
#include <Dataflow/Network/Network.h>
#include <Dataflow/Network/ModuleDescription.h>
#include <Dataflow/Network/Module.h>
#include <Dataflow/Network/ModuleFactory.h>
#include <Dataflow/Serialization/Network/NetworkXMLSerializer.h>
#include <Dataflow/Serialization/Network/NetworkDescriptionSerialization.h>
#include <Dataflow/Engine/Controller/DynamicPortManager.h>
#include <Core/Logging/Log.h>
#ifdef BUILD_WITH_PYTHON
#include <Dataflow/Engine/Python/NetworkEditorPythonAPI.h>
#include <Dataflow/Engine/Controller/PythonImpl.h>
#endif
using namespace SCIRun;
using namespace SCIRun::Dataflow::Engine;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core::Logging;
using namespace SCIRun::Core;
NetworkEditorController::NetworkEditorController(ModuleFactoryHandle mf, ModuleStateFactoryHandle sf, ExecutionStrategyFactoryHandle executorFactory, AlgorithmFactoryHandle af, ModulePositionEditor* mpg) :
theNetwork_(new Network(mf, sf, af)),
moduleFactory_(mf),
stateFactory_(sf),
algoFactory_(af),
executorFactory_(executorFactory),
modulePositionEditor_(mpg)
{
dynamicPortManager_.reset(new DynamicPortManager(connectionAdded_, connectionRemoved_, this));
//TODO should this class own the network or just keep a reference?
#ifdef BUILD_WITH_PYTHON
NetworkEditorPythonAPI::setImpl(boost::make_shared<PythonImpl>(*this));
#endif
}
NetworkEditorController::NetworkEditorController(SCIRun::Dataflow::Networks::NetworkHandle network, ExecutionStrategyFactoryHandle executorFactory, ModulePositionEditor* mpg)
: theNetwork_(network), executorFactory_(executorFactory), modulePositionEditor_(mpg)
{
}
ModuleHandle NetworkEditorController::addModule(const std::string& moduleName)
{
auto realModule = addModuleImpl(moduleName);
/*emit*/ moduleAdded_(moduleName, realModule);
printNetwork();
return realModule;
}
ModuleHandle NetworkEditorController::addModuleImpl(const std::string& moduleName)
{
//TODO: should pass in entire info struct
ModuleLookupInfo info;
info.module_name_ = moduleName;
ModuleHandle realModule = theNetwork_->add_module(info);
return realModule;
}
void NetworkEditorController::removeModule(const ModuleId& id)
{
//auto disableDynamicPortManager(createDynamicPortSwitch());
theNetwork_->remove_module(id);
//before or after?
// deciding on after: ProvenanceWindow/Manager wants the state *after* removal.
/*emit*/ moduleRemoved_(id);
printNetwork();
}
ModuleHandle NetworkEditorController::duplicateModule(const ModuleHandle& module)
{
//auto disableDynamicPortManager(createDynamicPortSwitch());
ENSURE_NOT_NULL(module, "Cannot duplicate null module");
ModuleId id(module->get_id());
auto newModule = addModuleImpl(id.name_);
newModule->set_state(module->get_state()->clone());
moduleAdded_(id.name_, newModule);
//TODO: probably a pretty poor way to deal with what I think is a race condition with signaling the GUI to place the module widget.
boost::this_thread::sleep(boost::posix_time::milliseconds(1));
BOOST_FOREACH(InputPortHandle input, module->inputPorts())
{
if (input->nconnections() == 1)
{
auto conn = input->connection(0);
auto source = conn->oport_;
//TODO: this will work if we define PortId.id# to be 0..n, unique for each module. But what about gaps?
requestConnection(source.get(), newModule->getInputPort(input->id()).get());
}
}
return newModule;
}
void NetworkEditorController::connectNewModule(const SCIRun::Dataflow::Networks::ModuleHandle& moduleToConnectTo, const SCIRun::Dataflow::Networks::PortDescriptionInterface* portToConnect, const std::string& newModuleName)
{
auto newMod = addModule(newModuleName);
//TODO: see above
boost::this_thread::sleep(boost::posix_time::milliseconds(1));
//TODO duplication
if (portToConnect->isInput())
{
BOOST_FOREACH(OutputPortHandle p, newMod->outputPorts())
{
if (p->get_typename() == portToConnect->get_typename())
{
requestConnection(p.get(), portToConnect);
return;
}
}
}
else
{
BOOST_FOREACH(InputPortHandle p, newMod->inputPorts())
{
if (p->get_typename() == portToConnect->get_typename())
{
requestConnection(p.get(), portToConnect);
return;
}
}
}
}
void NetworkEditorController::printNetwork() const
{
//TODO: and make this switchable
if (false)
{
if (theNetwork_)
LOG_DEBUG(theNetwork_->toString() << std::endl);
}
}
void NetworkEditorController::requestConnection(const SCIRun::Dataflow::Networks::PortDescriptionInterface* from, const SCIRun::Dataflow::Networks::PortDescriptionInterface* to)
{
ENSURE_NOT_NULL(from, "from port");
ENSURE_NOT_NULL(to, "to port");
auto out = from->isInput() ? to : from;
auto in = from->isInput() ? from : to;
ConnectionDescription desc(
OutgoingConnectionDescription(out->getUnderlyingModuleId(), out->id()),
IncomingConnectionDescription(in->getUnderlyingModuleId(), in->id()));
PortConnectionDeterminer q;
if (q.canBeConnected(*from, *to))
{
ConnectionId id = theNetwork_->connect(ConnectionOutputPort(theNetwork_->lookupModule(desc.out_.moduleId_), desc.out_.portId_),
ConnectionInputPort(theNetwork_->lookupModule(desc.in_.moduleId_), desc.in_.portId_));
if (!id.id_.empty())
connectionAdded_(desc);
printNetwork();
}
else
{
Log::get() << NOTICE << "Invalid Connection request: input port is full, or ports are different datatype or same i/o type, or on the same module." << std::endl;
invalidConnection_(desc);
}
}
void NetworkEditorController::removeConnection(const ConnectionId& id)
{
if (theNetwork_->disconnect(id))
connectionRemoved_(id);
printNetwork();
}
boost::signals2::connection NetworkEditorController::connectModuleAdded(const ModuleAddedSignalType::slot_type& subscriber)
{
return moduleAdded_.connect(subscriber);
}
boost::signals2::connection NetworkEditorController::connectModuleRemoved(const ModuleRemovedSignalType::slot_type& subscriber)
{
return moduleRemoved_.connect(subscriber);
}
boost::signals2::connection NetworkEditorController::connectConnectionAdded(const ConnectionAddedSignalType::slot_type& subscriber)
{
return connectionAdded_.connect(subscriber);
}
boost::signals2::connection NetworkEditorController::connectConnectionRemoved(const ConnectionRemovedSignalType::slot_type& subscriber)
{
return connectionRemoved_.connect(subscriber);
}
boost::signals2::connection NetworkEditorController::connectInvalidConnection(const InvalidConnectionSignalType::slot_type& subscriber)
{
return invalidConnection_.connect(subscriber);
}
boost::signals2::connection NetworkEditorController::connectNetworkExecutionStarts(const ExecuteAllStartsSignalType::slot_type& subscriber)
{
return ExecutionStrategy::connectNetworkExecutionStarts(subscriber);
}
boost::signals2::connection NetworkEditorController::connectNetworkExecutionFinished(const ExecuteAllFinishesSignalType::slot_type& subscriber)
{
return ExecutionStrategy::connectNetworkExecutionFinished(subscriber);
}
boost::signals2::connection NetworkEditorController::connectPortAdded(const PortAddedSignalType::slot_type& subscriber)
{
return dynamicPortManager_->connectPortAdded(subscriber);
}
boost::signals2::connection NetworkEditorController::connectPortRemoved(const PortRemovedSignalType::slot_type& subscriber)
{
return dynamicPortManager_->connectPortRemoved(subscriber);
}
NetworkFileHandle NetworkEditorController::saveNetwork() const
{
NetworkToXML conv(modulePositionEditor_);
return conv.to_xml_data(theNetwork_);
}
void NetworkEditorController::loadNetwork(const NetworkFileHandle& xml)
{
if (xml)
{
try
{
NetworkXMLConverter conv(moduleFactory_, stateFactory_, algoFactory_, this);
theNetwork_ = conv.from_xml_data(xml->network);
for (size_t i = 0; i < theNetwork_->nmodules(); ++i)
{
ModuleHandle module = theNetwork_->module(i);
moduleAdded_(module->get_module_name(), module);
}
{
auto disable(createDynamicPortSwitch());
//this is handled by NetworkXMLConverter now--but now the logic is convoluted.
//They need to be signaled again after the modules are signaled to alert the GUI. Hence the disabling of DPM
BOOST_FOREACH(const ConnectionDescription& cd, theNetwork_->connections())
{
ConnectionId id = ConnectionId::create(cd);
connectionAdded_(cd);
}
}
if (modulePositionEditor_)
modulePositionEditor_->moveModules(xml->modulePositions);
else
std::cout << "module position editor is null" << std::endl;
}
catch (ExceptionBase& e)
{
Log::get() << ERROR << "File load failed: exception while processing xml network data: " << e.what() << std::endl;
theNetwork_->clear();
throw;
}
}
}
void NetworkEditorController::clear()
{
//std::cout << "NetworkEditorController::clear()" << std::endl;
}
void NetworkEditorController::executeAll(const ExecutableLookup* lookup)
{
if (!currentExecutor_)
currentExecutor_ = executorFactory_->create(ExecutionStrategy::BASIC_PARALLEL); //TODO: read some setting for default executor type
currentExecutor_->executeAll(*theNetwork_, lookup ? *lookup : *theNetwork_);
theNetwork_->setModuleExecutionState(ModuleInterface::Waiting);
}
NetworkHandle NetworkEditorController::getNetwork() const
{
return theNetwork_;
}
void NetworkEditorController::setNetwork(NetworkHandle nh)
{
ENSURE_NOT_NULL(nh, "Null network.");
theNetwork_ = nh;
}
NetworkGlobalSettings& NetworkEditorController::getSettings()
{
return theNetwork_->settings();
}
void NetworkEditorController::setExecutorType(int type)
{
currentExecutor_ = executorFactory_->create((ExecutionStrategy::Type)type);
}
const ModuleDescriptionMap& NetworkEditorController::getAllAvailableModuleDescriptions() const
{
return moduleFactory_->getAllAvailableModuleDescriptions();
}
boost::shared_ptr<DisableDynamicPortSwitch> NetworkEditorController::createDynamicPortSwitch()
{
return boost::make_shared<DisableDynamicPortSwitch>(dynamicPortManager_);
}
DisableDynamicPortSwitch::DisableDynamicPortSwitch(boost::shared_ptr<DynamicPortManager> dpm) : first_(true), dpm_(dpm)
{
if (dpm_)
{
first_ = !dpm_->isDisabled();
if (first_)
dpm_->disable();
}
}
DisableDynamicPortSwitch::~DisableDynamicPortSwitch()
{
if (dpm_ && first_)
dpm_->enable();
}<|endoftext|> |
<commit_before>/****************************************************************************
* stermcom.cc
*
* Copyright (c) 2015 Yoshinori Sugino
* This software is released under the MIT License.
****************************************************************************/
#include <fcntl.h>
#include <libgen.h>
#include <sys/select.h>
#include <unistd.h>
#include <cassert>
#include <cerrno>
#include <csignal>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <list>
#include "common_type.h"
#include "debug.h"
#include "file_descriptor.h"
#include "signal_settings.h"
#include "terminal_interface.h"
namespace {
using status_t = common::status_t;
volatile sig_atomic_t g_should_continue = 1;
struct Arguments {
uint32_t baud_rate;
};
status_t mainLoop(const int32_t &tty_fd, const Arguments &args) {
fd_set fds_r, fds_w;
uint8_t one_char;
std::list<uint8_t> string_buffer{};
ssize_t rw_size;
util::TerminalInterface stdin_term(STDIN_FILENO), tty_term(tty_fd);
if (stdin_term.SetRawMode() == status_t::kFailure)
return status_t::kFailure;
if (tty_term.SetRawMode() == status_t::kFailure)
return status_t::kFailure;
if (tty_term.SetBaudRate(args.baud_rate, util::direction_t::kOut) ==
status_t::kFailure)
return status_t::kFailure;
if (tty_term.SetBaudRate(0, util::direction_t::kIn) == status_t::kFailure)
return status_t::kFailure;
assert(tty_fd > STDIN_FILENO && "Assertion for select()");
while (g_should_continue) {
FD_ZERO(&fds_r);
FD_ZERO(&fds_r);
FD_SET(STDIN_FILENO, &fds_r);
FD_SET(tty_fd, &fds_r);
FD_SET(tty_fd, &fds_w);
errno = 0;
auto ret = select(tty_fd + 1, &fds_r, &fds_w, nullptr, nullptr);
if (ret == -1) {
if (errno == EINTR) {
DEBUG_PRINTF("Signal was caught when select() is waiting");
} else {
printf("Error\n");
return status_t::kFailure;
}
break;
}
if (FD_ISSET(STDIN_FILENO, &fds_r)) {
rw_size = read(STDIN_FILENO, &one_char, 1);
if (one_char == 0x18) break; // 0x18: Ctrl-x
if (rw_size > 0) string_buffer.push_back(one_char);
}
if (FD_ISSET(tty_fd, &fds_w)) {
if (!string_buffer.empty()) {
rw_size = write(tty_fd, &string_buffer.front(), 1);
if (rw_size > 0) string_buffer.pop_front();
}
}
if (FD_ISSET(tty_fd, &fds_r)) {
uint8_t tty_read_buffer;
rw_size = read(tty_fd, &tty_read_buffer, 1);
if (rw_size > 0) write(STDOUT_FILENO, &tty_read_buffer, 1);
}
}
return status_t::kSuccess;
}
} // namespace
int main(int argc, char *argv[]) {
if (argc != 3) {
auto path_name = argv[0];
printf("USAGE: ./%s baud_rate device_node\n", basename(path_name));
return EXIT_FAILURE;
}
Arguments args;
args.baud_rate = strtol(argv[1], nullptr, 10);
util::FileDescriptor fd(argv[2], O_RDWR | O_NOCTTY | O_NONBLOCK);
if (fd.IsSuccess() == false) {
return EXIT_FAILURE;
}
if (!isatty(fd)) {
return EXIT_FAILURE;
}
// +: decay operator
if (util::InitializeSignalAction(
#ifdef PRIVATE_DEBUG
+[](int32_t) -> void {
// write(): Async-Signal-Safe
(void)write(STDOUT_FILENO, "Ignore signal\n", 14);
},
#else
SIG_IGN,
#endif // PRIVATE_DEBUG
+[](int32_t) -> void {
// write(), kill(): Async-Signal-Safe
#ifdef PRIVATE_DEBUG
(void)write(STDOUT_FILENO, "Disconnect\n", 11);
#endif // PRIVATE_DEBUG
// When signal is caught, select() is not always waiting.
g_should_continue = 0;
}) == status_t::kFailure) return EXIT_FAILURE;
auto ret = mainLoop(fd, args);
if (ret == status_t::kFailure) return EXIT_FAILURE;
return EXIT_SUCCESS;
}
<commit_msg>Remove an unnecessary comment<commit_after>/****************************************************************************
* stermcom.cc
*
* Copyright (c) 2015 Yoshinori Sugino
* This software is released under the MIT License.
****************************************************************************/
#include <fcntl.h>
#include <libgen.h>
#include <sys/select.h>
#include <unistd.h>
#include <cassert>
#include <cerrno>
#include <csignal>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <list>
#include "common_type.h"
#include "debug.h"
#include "file_descriptor.h"
#include "signal_settings.h"
#include "terminal_interface.h"
namespace {
using status_t = common::status_t;
volatile sig_atomic_t g_should_continue = 1;
struct Arguments {
uint32_t baud_rate;
};
status_t mainLoop(const int32_t &tty_fd, const Arguments &args) {
fd_set fds_r, fds_w;
uint8_t one_char;
std::list<uint8_t> string_buffer{};
ssize_t rw_size;
util::TerminalInterface stdin_term(STDIN_FILENO), tty_term(tty_fd);
if (stdin_term.SetRawMode() == status_t::kFailure)
return status_t::kFailure;
if (tty_term.SetRawMode() == status_t::kFailure)
return status_t::kFailure;
if (tty_term.SetBaudRate(args.baud_rate, util::direction_t::kOut) ==
status_t::kFailure)
return status_t::kFailure;
if (tty_term.SetBaudRate(0, util::direction_t::kIn) == status_t::kFailure)
return status_t::kFailure;
assert(tty_fd > STDIN_FILENO && "Assertion for select()");
while (g_should_continue) {
FD_ZERO(&fds_r);
FD_ZERO(&fds_r);
FD_SET(STDIN_FILENO, &fds_r);
FD_SET(tty_fd, &fds_r);
FD_SET(tty_fd, &fds_w);
errno = 0;
auto ret = select(tty_fd + 1, &fds_r, &fds_w, nullptr, nullptr);
if (ret == -1) {
if (errno == EINTR) {
DEBUG_PRINTF("Signal was caught when select() is waiting");
} else {
printf("Error\n");
return status_t::kFailure;
}
break;
}
if (FD_ISSET(STDIN_FILENO, &fds_r)) {
rw_size = read(STDIN_FILENO, &one_char, 1);
if (one_char == 0x18) break; // 0x18: Ctrl-x
if (rw_size > 0) string_buffer.push_back(one_char);
}
if (FD_ISSET(tty_fd, &fds_w)) {
if (!string_buffer.empty()) {
rw_size = write(tty_fd, &string_buffer.front(), 1);
if (rw_size > 0) string_buffer.pop_front();
}
}
if (FD_ISSET(tty_fd, &fds_r)) {
uint8_t tty_read_buffer;
rw_size = read(tty_fd, &tty_read_buffer, 1);
if (rw_size > 0) write(STDOUT_FILENO, &tty_read_buffer, 1);
}
}
return status_t::kSuccess;
}
} // namespace
int main(int argc, char *argv[]) {
if (argc != 3) {
auto path_name = argv[0];
printf("USAGE: ./%s baud_rate device_node\n", basename(path_name));
return EXIT_FAILURE;
}
Arguments args;
args.baud_rate = strtol(argv[1], nullptr, 10);
util::FileDescriptor fd(argv[2], O_RDWR | O_NOCTTY | O_NONBLOCK);
if (fd.IsSuccess() == false) {
return EXIT_FAILURE;
}
if (!isatty(fd)) {
return EXIT_FAILURE;
}
// +: decay operator
if (util::InitializeSignalAction(
#ifdef PRIVATE_DEBUG
+[](int32_t) -> void {
// write(): Async-Signal-Safe
(void)write(STDOUT_FILENO, "Ignore signal\n", 14);
},
#else
SIG_IGN,
#endif // PRIVATE_DEBUG
+[](int32_t) -> void {
#ifdef PRIVATE_DEBUG
(void)write(STDOUT_FILENO, "Disconnect\n", 11);
#endif // PRIVATE_DEBUG
// When signal is caught, select() is not always waiting.
g_should_continue = 0;
}) == status_t::kFailure) return EXIT_FAILURE;
auto ret = mainLoop(fd, args);
if (ret == status_t::kFailure) return EXIT_FAILURE;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/***************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Qt Software Information ([email protected])
**
**
** Non-Open Source Usage
**
** Licensees may use this file in accordance with the Qt Beta Version
** License Agreement, Agreement version 2.2 provided with the Software or,
** alternatively, in accordance with the terms contained in a written
** agreement between you and Nokia.
**
** GNU General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the packaging
** of this file. Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
**
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt GPL Exception
** version 1.3, included in the file GPL_EXCEPTION.txt in this package.
**
***************************************************************************/
#include "gdbmacrosbuildstep.h"
#include "makestep.h"
#include "qmakestep.h"
#include "qt4project.h"
#include "qt4projectmanagerconstants.h"
#include <coreplugin/icore.h>
#include <utils/qtcassert.h>
using namespace Qt4ProjectManager;
using namespace Qt4ProjectManager::Internal;
GdbMacrosBuildStep::GdbMacrosBuildStep(Qt4Project *project)
: BuildStep(project), m_project(project)
{
}
GdbMacrosBuildStep::~GdbMacrosBuildStep()
{
}
bool GdbMacrosBuildStep::init(const QString &buildConfiguration)
{
m_buildDirectory = m_project->buildDirectory(buildConfiguration);
m_qmake = m_project->qtVersion(buildConfiguration)->qmakeCommand();
m_buildConfiguration = buildConfiguration;
return true;
}
void GdbMacrosBuildStep::run(QFutureInterface<bool> & fi)
{
QVariant v = value("clean");
if (v.isNull() || v.toBool() == false) {
// Normal run
QString dumperPath = Core::ICore::instance()->resourcePath() + "/gdbmacros/";
QStringList files;
files << "gdbmacros.cpp"
<< "gdbmacros.pro";
QString destDir = m_buildDirectory + "/qtc-gdbmacros/";
QDir dir;
dir.mkpath(destDir);
foreach (const QString &file, files) {
QFile destination(destDir + file);
if (destination.exists())
destination.remove();
QFile::copy(dumperPath + file, destDir + file);
}
Qt4Project *qt4Project = static_cast<Qt4Project *>(project());
QProcess qmake;
qmake.setEnvironment(qt4Project->environment(m_buildConfiguration).toStringList());
qmake.setWorkingDirectory(destDir);
QStringList configarguments;
QStringList makeArguments;
// Find qmake step...
QMakeStep *qmakeStep = qt4Project->qmakeStep();
// Find out which configuration is used in this build configuration
// and what kind of CONFIG we need to pass to qmake for that
if (qmakeStep->value(m_buildConfiguration, "buildConfiguration").isValid()) {
QtVersion::QmakeBuildConfig defaultBuildConfiguration = qt4Project->qtVersion(m_buildConfiguration)->defaultBuildConfig();
QtVersion::QmakeBuildConfig projectBuildConfiguration = QtVersion::QmakeBuildConfig(qmakeStep->value(m_buildConfiguration, "buildConfiguration").toInt());
if ((defaultBuildConfiguration & QtVersion::BuildAll) && !(projectBuildConfiguration & QtVersion::BuildAll))
configarguments << "CONFIG-=debug_and_release";
if (!(defaultBuildConfiguration & QtVersion::BuildAll) && (projectBuildConfiguration & QtVersion::BuildAll))
configarguments << "CONFIG+=debug_and_release";
if ((defaultBuildConfiguration & QtVersion::DebugBuild) && !(projectBuildConfiguration & QtVersion::DebugBuild))
configarguments << "CONFIG+=release";
if (!(defaultBuildConfiguration & QtVersion::DebugBuild) && (projectBuildConfiguration & QtVersion::DebugBuild))
configarguments << "CONFIG+=debug";
if (projectBuildConfiguration & QtVersion::BuildAll)
makeArguments << (projectBuildConfiguration & QtVersion::DebugBuild ? "debug" : "release");
} else {
// Old style with CONFIG+=debug_and_release
configarguments << "CONFIG+=debug_and_release";
const MakeStep *ms = qt4Project->makeStep();
QStringList makeargs = ms->value(m_buildConfiguration, "makeargs").toStringList();
if (makeargs.contains("debug")) {
makeArguments << "debug";
} else if (makeargs.contains("release")) {
makeArguments << "release";
}
}
QString mkspec = qt4Project->qtVersion(m_buildConfiguration)->mkspec();
qmake.start(m_qmake, QStringList()<<"-spec"<<mkspec<<configarguments<<"gdbmacros.pro");
qmake.waitForFinished();
qmake.start(qt4Project->qtVersion(m_buildConfiguration)->makeCommand(), makeArguments);
qmake.waitForFinished();
fi.reportResult(true);
} else {
// Clean step, we want to remove the directory
QString destDir = m_buildDirectory + "/qtc-gdbmacros/";
Qt4Project *qt4Project = static_cast<Qt4Project *>(project());
QProcess make;
make.setEnvironment(qt4Project->environment(m_buildConfiguration).toStringList());
make.setWorkingDirectory(destDir);
make.start(qt4Project->qtVersion(m_buildConfiguration)->makeCommand(), QStringList()<<"distclean");
make.waitForFinished();
QStringList files;
files << "gdbmacros.cpp"
<< "gdbmacros.pro";
QStringList directories;
directories << "debug"
<< "release";
foreach(const QString &file, files) {
QFile destination(destDir + file);
destination.remove();
}
foreach(const QString &dir, directories) {
QDir destination(destDir + dir);
destination.rmdir(destDir + dir);
}
QDir(destDir).rmdir(destDir);
fi.reportResult(true);
}
}
QString GdbMacrosBuildStep::name()
{
return Constants::GDBMACROSBUILDSTEP;
}
QString GdbMacrosBuildStep::displayName()
{
return "Gdb Macros Build";
}
ProjectExplorer::BuildStepConfigWidget *GdbMacrosBuildStep::createConfigWidget()
{
return new GdbMacrosBuildStepConfigWidget;
}
bool GdbMacrosBuildStep::immutable() const
{
return false;
}
bool GdbMacrosBuildStepFactory::canCreate(const QString &name) const
{
return name == Constants::GDBMACROSBUILDSTEP;
}
ProjectExplorer::BuildStep *GdbMacrosBuildStepFactory::create(ProjectExplorer::Project *pro, const QString &name) const
{
Q_ASSERT(name == Constants::GDBMACROSBUILDSTEP);
Qt4Project *qt4project = qobject_cast<Qt4Project *>(pro);
Q_ASSERT(qt4project);
return new GdbMacrosBuildStep(qt4project);
}
QStringList GdbMacrosBuildStepFactory::canCreateForProject(ProjectExplorer::Project *pro) const
{
QStringList results;
if (qobject_cast<Qt4Project *>(pro))
results << Constants::GDBMACROSBUILDSTEP;
return results;
}
QString GdbMacrosBuildStepFactory::displayNameForName(const QString &name) const
{
if (name == Constants::GDBMACROSBUILDSTEP)
return "Gdb Macros Build";
else
return QString::null;
}
QString GdbMacrosBuildStepConfigWidget::displayName() const
{
return "Gdb Macros Build";
}
void GdbMacrosBuildStepConfigWidget::init(const QString & /*buildConfiguration*/)
{
// TODO
}
<commit_msg>Some feedback about 2-3 second delay before running qmake<commit_after>/***************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Qt Software Information ([email protected])
**
**
** Non-Open Source Usage
**
** Licensees may use this file in accordance with the Qt Beta Version
** License Agreement, Agreement version 2.2 provided with the Software or,
** alternatively, in accordance with the terms contained in a written
** agreement between you and Nokia.
**
** GNU General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the packaging
** of this file. Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
**
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt GPL Exception
** version 1.3, included in the file GPL_EXCEPTION.txt in this package.
**
***************************************************************************/
#include "gdbmacrosbuildstep.h"
#include "makestep.h"
#include "qmakestep.h"
#include "qt4project.h"
#include "qt4projectmanagerconstants.h"
#include <coreplugin/icore.h>
#include <utils/qtcassert.h>
using namespace Qt4ProjectManager;
using namespace Qt4ProjectManager::Internal;
GdbMacrosBuildStep::GdbMacrosBuildStep(Qt4Project *project)
: BuildStep(project), m_project(project)
{
}
GdbMacrosBuildStep::~GdbMacrosBuildStep()
{
}
bool GdbMacrosBuildStep::init(const QString &buildConfiguration)
{
m_buildDirectory = m_project->buildDirectory(buildConfiguration);
m_qmake = m_project->qtVersion(buildConfiguration)->qmakeCommand();
m_buildConfiguration = buildConfiguration;
return true;
}
void GdbMacrosBuildStep::run(QFutureInterface<bool> & fi)
{
QVariant v = value("clean");
if (v.isNull() || v.toBool() == false) {
addToOutputWindow("<b>Creating gdb macros library...</b>");
// Normal run
QString dumperPath = Core::ICore::instance()->resourcePath() + "/gdbmacros/";
QStringList files;
files << "gdbmacros.cpp"
<< "gdbmacros.pro";
QString destDir = m_buildDirectory + "/qtc-gdbmacros/";
QDir dir;
dir.mkpath(destDir);
foreach (const QString &file, files) {
QFile destination(destDir + file);
if (destination.exists())
destination.remove();
QFile::copy(dumperPath + file, destDir + file);
}
Qt4Project *qt4Project = static_cast<Qt4Project *>(project());
QProcess qmake;
qmake.setEnvironment(qt4Project->environment(m_buildConfiguration).toStringList());
qmake.setWorkingDirectory(destDir);
QStringList configarguments;
QStringList makeArguments;
// Find qmake step...
QMakeStep *qmakeStep = qt4Project->qmakeStep();
// Find out which configuration is used in this build configuration
// and what kind of CONFIG we need to pass to qmake for that
if (qmakeStep->value(m_buildConfiguration, "buildConfiguration").isValid()) {
QtVersion::QmakeBuildConfig defaultBuildConfiguration = qt4Project->qtVersion(m_buildConfiguration)->defaultBuildConfig();
QtVersion::QmakeBuildConfig projectBuildConfiguration = QtVersion::QmakeBuildConfig(qmakeStep->value(m_buildConfiguration, "buildConfiguration").toInt());
if ((defaultBuildConfiguration & QtVersion::BuildAll) && !(projectBuildConfiguration & QtVersion::BuildAll))
configarguments << "CONFIG-=debug_and_release";
if (!(defaultBuildConfiguration & QtVersion::BuildAll) && (projectBuildConfiguration & QtVersion::BuildAll))
configarguments << "CONFIG+=debug_and_release";
if ((defaultBuildConfiguration & QtVersion::DebugBuild) && !(projectBuildConfiguration & QtVersion::DebugBuild))
configarguments << "CONFIG+=release";
if (!(defaultBuildConfiguration & QtVersion::DebugBuild) && (projectBuildConfiguration & QtVersion::DebugBuild))
configarguments << "CONFIG+=debug";
if (projectBuildConfiguration & QtVersion::BuildAll)
makeArguments << (projectBuildConfiguration & QtVersion::DebugBuild ? "debug" : "release");
} else {
// Old style with CONFIG+=debug_and_release
configarguments << "CONFIG+=debug_and_release";
const MakeStep *ms = qt4Project->makeStep();
QStringList makeargs = ms->value(m_buildConfiguration, "makeargs").toStringList();
if (makeargs.contains("debug")) {
makeArguments << "debug";
} else if (makeargs.contains("release")) {
makeArguments << "release";
}
}
QString mkspec = qt4Project->qtVersion(m_buildConfiguration)->mkspec();
qmake.start(m_qmake, QStringList()<<"-spec"<<mkspec<<configarguments<<"gdbmacros.pro");
qmake.waitForFinished();
qmake.start(qt4Project->qtVersion(m_buildConfiguration)->makeCommand(), makeArguments);
qmake.waitForFinished();
fi.reportResult(true);
} else {
// Clean step, we want to remove the directory
QString destDir = m_buildDirectory + "/qtc-gdbmacros/";
Qt4Project *qt4Project = static_cast<Qt4Project *>(project());
QProcess make;
make.setEnvironment(qt4Project->environment(m_buildConfiguration).toStringList());
make.setWorkingDirectory(destDir);
make.start(qt4Project->qtVersion(m_buildConfiguration)->makeCommand(), QStringList()<<"distclean");
make.waitForFinished();
QStringList files;
files << "gdbmacros.cpp"
<< "gdbmacros.pro";
QStringList directories;
directories << "debug"
<< "release";
foreach(const QString &file, files) {
QFile destination(destDir + file);
destination.remove();
}
foreach(const QString &dir, directories) {
QDir destination(destDir + dir);
destination.rmdir(destDir + dir);
}
QDir(destDir).rmdir(destDir);
fi.reportResult(true);
}
}
QString GdbMacrosBuildStep::name()
{
return Constants::GDBMACROSBUILDSTEP;
}
QString GdbMacrosBuildStep::displayName()
{
return "Gdb Macros Build";
}
ProjectExplorer::BuildStepConfigWidget *GdbMacrosBuildStep::createConfigWidget()
{
return new GdbMacrosBuildStepConfigWidget;
}
bool GdbMacrosBuildStep::immutable() const
{
return false;
}
bool GdbMacrosBuildStepFactory::canCreate(const QString &name) const
{
return name == Constants::GDBMACROSBUILDSTEP;
}
ProjectExplorer::BuildStep *GdbMacrosBuildStepFactory::create(ProjectExplorer::Project *pro, const QString &name) const
{
Q_ASSERT(name == Constants::GDBMACROSBUILDSTEP);
Qt4Project *qt4project = qobject_cast<Qt4Project *>(pro);
Q_ASSERT(qt4project);
return new GdbMacrosBuildStep(qt4project);
}
QStringList GdbMacrosBuildStepFactory::canCreateForProject(ProjectExplorer::Project *pro) const
{
QStringList results;
if (qobject_cast<Qt4Project *>(pro))
results << Constants::GDBMACROSBUILDSTEP;
return results;
}
QString GdbMacrosBuildStepFactory::displayNameForName(const QString &name) const
{
if (name == Constants::GDBMACROSBUILDSTEP)
return "Gdb Macros Build";
else
return QString::null;
}
QString GdbMacrosBuildStepConfigWidget::displayName() const
{
return "Gdb Macros Build";
}
void GdbMacrosBuildStepConfigWidget::init(const QString & /*buildConfiguration*/)
{
// TODO
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
**
**************************************************************************/
#include "profilehighlighter.h"
#include <QtCore/QRegExp>
#include <QtGui/QColor>
#include <QtGui/QTextDocument>
#include <QtGui/QTextEdit>
using namespace Qt4ProjectManager::Internal;
#define MAX_VARIABLES 49
const char *const variables[MAX_VARIABLES] = {
"CONFIG",
"DEFINES",
"DEF_FILE",
"DEPENDPATH",
"DESTDIR",
"DESTDIR_TARGET",
"DISTFILES",
"DLLDESTDIR",
"FORMS",
"HEADERS",
"INCLUDEPATH",
"LEXSOURCES",
"LIBS",
"MAKEFILE",
"MOC_DIR",
"OBJECTS",
"OBJECTS_DIR",
"OBJMOC",
"PKGCONFIG",
"POST_TARGETDEPS",
"PRECOMPILED_HEADER",
"PRE_TARGETDEPS",
"QMAKE",
"QMAKESPEC",
"QT",
"RCC_DIR",
"RC_FILE",
"REQUIRES",
"RESOURCES",
"RES_FILE",
"SOURCES",
"SRCMOC",
"SUBDIRS",
"TARGET",
"TARGET_EXT",
"TARGET_x",
"TARGET_x.y.z",
"TEMPLATE",
"TRANSLATIONS",
"UI_DIR",
"UI_HEADERS_DIR",
"UI_SOURCES_DIR",
"VER_MAJ",
"VER_MIN",
"VER_PAT",
"VERSION",
"VPATH",
"YACCSOURCES",
0
};
#define MAX_FUNCTIONS 22
const char *const functions[MAX_FUNCTIONS] = {
"basename",
"CONFIG",
"contains",
"count",
"dirname",
"error",
"exists",
"find",
"for",
"include",
"infile",
"isEmpty",
"join",
"member",
"message",
"prompt",
"quote",
"sprintf",
"system",
"unique",
"warning",
0
};
struct KeywordHelper
{
inline KeywordHelper(const QString &word) : needle(word) {}
const QString needle;
};
static bool operator<(const KeywordHelper &helper, const char *kw)
{
return helper.needle < QLatin1String(kw);
}
static bool operator<(const char *kw, const KeywordHelper &helper)
{
return QLatin1String(kw) < helper.needle;
}
static bool isVariable(const QString &word)
{
const char *const *start = &variables[0];
const char *const *end = &variables[MAX_VARIABLES - 1];
const char *const *kw = qBinaryFind(start, end, KeywordHelper(word));
return *kw != 0;
}
static bool isFunction(const QString &word)
{
const char *const *start = &functions[0];
const char *const *end = &functions[MAX_FUNCTIONS - 1];
const char *const *kw = qBinaryFind(start, end, KeywordHelper(word));
return *kw != 0;
}
ProFileHighlighter::ProFileHighlighter(QTextDocument *document) :
QSyntaxHighlighter(document)
{
}
void ProFileHighlighter::highlightBlock(const QString &text)
{
if (text.isEmpty())
return;
QString buf;
bool inCommentMode = false;
QTextCharFormat emptyFormat;
int i = 0;
for (;;) {
const QChar c = text.at(i);
if (inCommentMode) {
setFormat(i, 1, m_formats[ProfileCommentFormat]);
} else {
if (c.isLetter() || c == '_' || c == '.') {
buf += c;
setFormat(i - buf.length()+1, buf.length(), emptyFormat);
if (!buf.isEmpty() && isFunction(buf))
setFormat(i - buf.length()+1, buf.length(), m_formats[ProfileFunctionFormat]);
else if (!buf.isEmpty() && isVariable(buf))
setFormat(i - buf.length()+1, buf.length(), m_formats[ProfileVariableFormat]);
} else if (c == '(') {
if (!buf.isEmpty() && isFunction(buf))
setFormat(i - buf.length(), buf.length(), m_formats[ProfileFunctionFormat]);
buf.clear();
} else if (c == '#') {
inCommentMode = true;
setFormat(i, 1, m_formats[ProfileCommentFormat]);
buf.clear();
} else {
if (!buf.isEmpty() && isVariable(buf))
setFormat(i - buf.length(), buf.length(), m_formats[ProfileVariableFormat]);
buf.clear();
}
}
i++;
if (i >= text.length())
break;
}
}
<commit_msg>Highlight OTHER_FILES in pro editor.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
**
**************************************************************************/
#include "profilehighlighter.h"
#include <QtCore/QRegExp>
#include <QtGui/QColor>
#include <QtGui/QTextDocument>
#include <QtGui/QTextEdit>
using namespace Qt4ProjectManager::Internal;
#define MAX_VARIABLES 50
const char *const variables[MAX_VARIABLES] = {
"CONFIG",
"DEFINES",
"DEF_FILE",
"DEPENDPATH",
"DESTDIR",
"DESTDIR_TARGET",
"DISTFILES",
"DLLDESTDIR",
"FORMS",
"HEADERS",
"INCLUDEPATH",
"LEXSOURCES",
"LIBS",
"MAKEFILE",
"MOC_DIR",
"OBJECTS",
"OBJECTS_DIR",
"OBJMOC",
"OTHER_FILES",
"PKGCONFIG",
"POST_TARGETDEPS",
"PRECOMPILED_HEADER",
"PRE_TARGETDEPS",
"QMAKE",
"QMAKESPEC",
"QT",
"RCC_DIR",
"RC_FILE",
"REQUIRES",
"RESOURCES",
"RES_FILE",
"SOURCES",
"SRCMOC",
"SUBDIRS",
"TARGET",
"TARGET_EXT",
"TARGET_x",
"TARGET_x.y.z",
"TEMPLATE",
"TRANSLATIONS",
"UI_DIR",
"UI_HEADERS_DIR",
"UI_SOURCES_DIR",
"VER_MAJ",
"VER_MIN",
"VER_PAT",
"VERSION",
"VPATH",
"YACCSOURCES",
0
};
#define MAX_FUNCTIONS 22
const char *const functions[MAX_FUNCTIONS] = {
"basename",
"CONFIG",
"contains",
"count",
"dirname",
"error",
"exists",
"find",
"for",
"include",
"infile",
"isEmpty",
"join",
"member",
"message",
"prompt",
"quote",
"sprintf",
"system",
"unique",
"warning",
0
};
struct KeywordHelper
{
inline KeywordHelper(const QString &word) : needle(word) {}
const QString needle;
};
static bool operator<(const KeywordHelper &helper, const char *kw)
{
return helper.needle < QLatin1String(kw);
}
static bool operator<(const char *kw, const KeywordHelper &helper)
{
return QLatin1String(kw) < helper.needle;
}
static bool isVariable(const QString &word)
{
const char *const *start = &variables[0];
const char *const *end = &variables[MAX_VARIABLES - 1];
const char *const *kw = qBinaryFind(start, end, KeywordHelper(word));
return *kw != 0;
}
static bool isFunction(const QString &word)
{
const char *const *start = &functions[0];
const char *const *end = &functions[MAX_FUNCTIONS - 1];
const char *const *kw = qBinaryFind(start, end, KeywordHelper(word));
return *kw != 0;
}
ProFileHighlighter::ProFileHighlighter(QTextDocument *document) :
QSyntaxHighlighter(document)
{
}
void ProFileHighlighter::highlightBlock(const QString &text)
{
if (text.isEmpty())
return;
QString buf;
bool inCommentMode = false;
QTextCharFormat emptyFormat;
int i = 0;
for (;;) {
const QChar c = text.at(i);
if (inCommentMode) {
setFormat(i, 1, m_formats[ProfileCommentFormat]);
} else {
if (c.isLetter() || c == '_' || c == '.') {
buf += c;
setFormat(i - buf.length()+1, buf.length(), emptyFormat);
if (!buf.isEmpty() && isFunction(buf))
setFormat(i - buf.length()+1, buf.length(), m_formats[ProfileFunctionFormat]);
else if (!buf.isEmpty() && isVariable(buf))
setFormat(i - buf.length()+1, buf.length(), m_formats[ProfileVariableFormat]);
} else if (c == '(') {
if (!buf.isEmpty() && isFunction(buf))
setFormat(i - buf.length(), buf.length(), m_formats[ProfileFunctionFormat]);
buf.clear();
} else if (c == '#') {
inCommentMode = true;
setFormat(i, 1, m_formats[ProfileCommentFormat]);
buf.clear();
} else {
if (!buf.isEmpty() && isVariable(buf))
setFormat(i - buf.length(), buf.length(), m_formats[ProfileVariableFormat]);
buf.clear();
}
}
i++;
if (i >= text.length())
break;
}
}
<|endoftext|> |
<commit_before>#include <glm/glm.hpp>
#include <gl-platform/GLPlatform.hpp>
#include <entity-system/GenericSystem.hpp>
#include <es-systems/SystemCore.hpp>
#include <es-acorn/Acorn.hpp>
#include <es-general/comp/Transform.hpp>
#include <es-general/comp/StaticGlobalTime.hpp>
#include <es-general/comp/StaticCamera.hpp>
#include <es-general/comp/StaticOrthoCamera.hpp>
#include <es-general/comp/CameraSelect.hpp>
#include <es-render/comp/VBO.hpp>
#include <es-render/comp/IBO.hpp>
#include <es-render/comp/CommonUniforms.hpp>
#include <es-render/comp/Shader.hpp>
#include <es-render/comp/Texture.hpp>
#include <es-render/comp/GLState.hpp>
#include <es-render/comp/VecUniform.hpp>
#include <es-render/comp/MatUniform.hpp>
#include <es-render/comp/StaticGLState.hpp>
#include <es-render/comp/StaticVBOMan.hpp>
#include <bserialize/BSerialize.hpp>
#include "../comp/RenderBasicGeom.h"
#include "../comp/SRRenderState.h"
#include "../comp/RenderList.h"
namespace es = CPM_ES_NS;
namespace shaders = CPM_GL_SHADERS_NS;
// Every component is self contained. It only accesses the systems and
// components that it specifies in it's component list.
namespace SCIRun {
namespace Render {
class RenderBasicSys :
public es::GenericSystem<true,
RenderBasicGeom, // TAG class
SRRenderState,
RenderList,
gen::Transform,
gen::StaticGlobalTime,
ren::VBO,
ren::IBO,
ren::CommonUniforms,
ren::VecUniform,
ren::MatUniform,
ren::Shader,
ren::GLState,
gen::StaticCamera,
ren::StaticGLState,
ren::StaticVBOMan>
{
public:
static const char* getName() {return "RenderBasicSys";}
bool isComponentOptional(uint64_t type) override
{
return es::OptionalComponents<RenderList,
ren::GLState,
ren::StaticGLState,
ren::CommonUniforms,
ren::VecUniform,
ren::MatUniform>(type);
}
void groupExecute(
es::ESCoreBase&, uint64_t /* entityID */,
const es::ComponentGroup<RenderBasicGeom>& geom,
const es::ComponentGroup<SRRenderState>& srstate,
const es::ComponentGroup<RenderList>& rlist,
const es::ComponentGroup<gen::Transform>& trafo,
const es::ComponentGroup<gen::StaticGlobalTime>& time,
const es::ComponentGroup<ren::VBO>& vbo,
const es::ComponentGroup<ren::IBO>& ibo,
const es::ComponentGroup<ren::CommonUniforms>& commonUniforms,
const es::ComponentGroup<ren::VecUniform>& vecUniforms,
const es::ComponentGroup<ren::MatUniform>& matUniforms,
const es::ComponentGroup<ren::Shader>& shader,
const es::ComponentGroup<ren::GLState>& state,
const es::ComponentGroup<gen::StaticCamera>& camera,
const es::ComponentGroup<ren::StaticGLState>& defaultGLState,
const es::ComponentGroup<ren::StaticVBOMan>& vboMan) override
{
/// \todo This needs to be moved to pre-execute.
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{
return;
}
// Setup *everything*. We don't want to enter multiple conditional
// statements if we can avoid it. So we assume everything has not been
// setup (including uniforms) if the simple geom hasn't been setup.
if (geom.front().attribs.isSetup() == false)
{
// We use const cast to get around a 'modify' call for 2 reasons:
// 1) This is populating system specific GL data. It has no bearing on the
// actual simulation state.
// 2) It is more correct than issuing a modify call. The data is used
// directly below to render geometry.
const_cast<RenderBasicGeom&>(geom.front()).attribs.setup(
vbo.front().glid, shader.front().glid, vboMan.front());
/// \todo Optimize by pulling uniforms only once.
if (commonUniforms.size() > 0)
{
const_cast<ren::CommonUniforms&>(commonUniforms.front()).checkUniformArray(
shader.front().glid);
}
if (vecUniforms.size() > 0)
{
for (const ren::VecUniform& unif : vecUniforms)
{
const_cast<ren::VecUniform&>(unif).checkUniform(shader.front().glid);
}
}
if (matUniforms.size() > 0)
{
for (const ren::MatUniform& unif : matUniforms)
{
const_cast<ren::MatUniform&>(unif).checkUniform(shader.front().glid);
}
}
}
// Check to see if we have GLState. If so, apply it relative to the
// current state (I'm actually thinking GLState is a bad idea, and we
// should just program what we need manually in the system -- depending
// on type). State can be set in a pre-walk phase.
if (state.size() > 0 && defaultGLState.size() > 0)
{
// Apply GLState based on current GLState (the static state), if it is
// present. Otherwise, fully apply it (performance issue).
state.front().state.applyRelative(defaultGLState.front().state);
}
// Bind shader.
GL(glUseProgram(shader.front().glid));
// Bind VBO and IBO
GL(glBindBuffer(GL_ARRAY_BUFFER, vbo.front().glid));
GL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo.front().glid));
// Bind any common uniforms.
if (commonUniforms.size() > 0)
{
commonUniforms.front().applyCommonUniforms(
trafo.front().transform, camera.front().data, time.front().globalTime);
}
// Apply vector uniforms (if any).
for (const ren::VecUniform& unif : vecUniforms) {unif.applyUniform();}
// Apply matrix uniforms (if any).
for (const ren::MatUniform& unif : matUniforms) {unif.applyUniform();}
geom.front().attribs.bind();
// Disable zwrite if we are rendering a transparent object.
if (srstate.front().state.get(RenderState::USE_TRANSPARENCY))
{
GL(glDepthMask(GL_FALSE));
GL(glDisable(GL_CULL_FACE));
}
if (rlist.size() > 0)
{
// Lookup transform uniform and uniform color uniform (we may not
// use the uniform color uniform).
// Note: Some of this work can be done beforehand. But we elect not to
// since it is feasible that the data contained in the VBO can change
// fairly dramatically.
// Build BSerialize object.
CPM_BSERIALIZE_NS::BSerialize posDeserialize(
rlist.front().data->getBuffer(), rlist.front().data->getBufferSize());
CPM_BSERIALIZE_NS::BSerialize colorDeserialize(
rlist.front().data->getBuffer(), rlist.front().data->getBufferSize());
int64_t posSize = 0;
int64_t colorSize = 0;
int64_t stride = 0; // Stride of entire attributes buffer.
// Determine stride for our buffer. Also determine appropriate position
// and color information offsets, and set the offsets. Also determine
// attribute size in bytes.
for (const auto& attrib : rlist.front().attributes)
{
if (attrib.name == "aPos")
{
if (stride != 0) {posDeserialize.readBytes(stride);}
posSize = attrib.sizeInBytes;
}
else if (attrib.name == "aColor")
{
if (stride != 0) {colorDeserialize.readBytes(stride);}
colorSize = attrib.sizeInBytes;
}
stride += attrib.sizeInBytes;
}
int64_t posStride = stride - posSize;
int64_t colorStride = stride - colorSize;
// Render using a draw list. We will be using the VBO and IBO attached
// to this object as the basic rendering primitive.
for (int i = 0; i < rlist.front().numElements; ++i)
{
// Read position.
float x = posDeserialize.read<float>();
float y = posDeserialize.read<float>();
float z = posDeserialize.read<float>();
posDeserialize.readBytes(posStride);
// Read color if available.
if (colorSize > 0)
{
float r = static_cast<float>(colorDeserialize.read<uint8_t>()) / 255.0f;
float g = static_cast<float>(colorDeserialize.read<uint8_t>()) / 255.0f;
float b = static_cast<float>(colorDeserialize.read<uint8_t>()) / 255.0f;
float a = static_cast<float>(colorDeserialize.read<uint8_t>()) / 255.0f;
/// \todo Set the uniform color uniform. We need to lookup the
/// color uniform in our shader.
}
// Update transform.
GL(glDrawElements(ibo.front().primMode, ibo.front().numPrims,
ibo.front().primType, 0));
}
}
else
{
if (!srstate.front().state.get(RenderState::IS_DOUBLE_SIDED))
{
GL(glDrawElements(ibo.front().primMode, ibo.front().numPrims,
ibo.front().primType, 0));
}
else
{
GL(glEnable(GL_CULL_FACE));
// Double sided rendering. Mimic SCIRun4 and use GL_FRONT and GL_BACK
// to mimic forward facing and back facing polygons.
// Draw front facing polygons.
GLint fdToggleLoc = glGetUniformLocation(shader.front().glid, "uFDToggle");
GL(glUniform1f(fdToggleLoc, 1.0f));
glCullFace(GL_BACK);
GL(glDrawElements(ibo.front().primMode, ibo.front().numPrims,
ibo.front().primType, 0));
GL(glUniform1f(fdToggleLoc, 0.0f));
glCullFace(GL_FRONT);
GL(glDrawElements(ibo.front().primMode, ibo.front().numPrims,
ibo.front().primType, 0));
}
}
if (srstate.front().state.get(RenderState::USE_TRANSPARENCY))
{
GL(glDepthMask(GL_TRUE));
GL(glEnable(GL_CULL_FACE));
}
geom.front().attribs.unbind();
// Reapply the default state here -- only do this if static state is
// present.
if (state.size() > 0 && defaultGLState.size() > 0)
{
defaultGLState.front().state.applyRelative(state.front().state);
}
}
};
void registerSystem_RenderBasicGeom(CPM_ES_ACORN_NS::Acorn& core)
{
core.registerSystem<RenderBasicSys>();
}
const char* getSystemName_RenderBasicGeom()
{
return RenderBasicSys::getName();
}
} // namespace Render
} // namespace SCIRun
<commit_msg>Finalize implementation of uniform color render lists.<commit_after>#include <glm/glm.hpp>
#include <gl-platform/GLPlatform.hpp>
#include <entity-system/GenericSystem.hpp>
#include <es-systems/SystemCore.hpp>
#include <es-acorn/Acorn.hpp>
#include <es-general/comp/Transform.hpp>
#include <es-general/comp/StaticGlobalTime.hpp>
#include <es-general/comp/StaticCamera.hpp>
#include <es-general/comp/StaticOrthoCamera.hpp>
#include <es-general/comp/CameraSelect.hpp>
#include <es-render/comp/VBO.hpp>
#include <es-render/comp/IBO.hpp>
#include <es-render/comp/CommonUniforms.hpp>
#include <es-render/comp/Shader.hpp>
#include <es-render/comp/Texture.hpp>
#include <es-render/comp/GLState.hpp>
#include <es-render/comp/VecUniform.hpp>
#include <es-render/comp/MatUniform.hpp>
#include <es-render/comp/StaticGLState.hpp>
#include <es-render/comp/StaticVBOMan.hpp>
#include <bserialize/BSerialize.hpp>
#include "../comp/RenderBasicGeom.h"
#include "../comp/SRRenderState.h"
#include "../comp/RenderList.h"
namespace es = CPM_ES_NS;
namespace shaders = CPM_GL_SHADERS_NS;
// Every component is self contained. It only accesses the systems and
// components that it specifies in it's component list.
namespace SCIRun {
namespace Render {
class RenderBasicSys :
public es::GenericSystem<true,
RenderBasicGeom, // TAG class
SRRenderState,
RenderList,
gen::Transform,
gen::StaticGlobalTime,
ren::VBO,
ren::IBO,
ren::CommonUniforms,
ren::VecUniform,
ren::MatUniform,
ren::Shader,
ren::GLState,
gen::StaticCamera,
ren::StaticGLState,
ren::StaticVBOMan>
{
public:
static const char* getName() {return "RenderBasicSys";}
bool isComponentOptional(uint64_t type) override
{
return es::OptionalComponents<RenderList,
ren::GLState,
ren::StaticGLState,
ren::CommonUniforms,
ren::VecUniform,
ren::MatUniform>(type);
}
void groupExecute(
es::ESCoreBase&, uint64_t /* entityID */,
const es::ComponentGroup<RenderBasicGeom>& geom,
const es::ComponentGroup<SRRenderState>& srstate,
const es::ComponentGroup<RenderList>& rlist,
const es::ComponentGroup<gen::Transform>& trafo,
const es::ComponentGroup<gen::StaticGlobalTime>& time,
const es::ComponentGroup<ren::VBO>& vbo,
const es::ComponentGroup<ren::IBO>& ibo,
const es::ComponentGroup<ren::CommonUniforms>& commonUniforms,
const es::ComponentGroup<ren::VecUniform>& vecUniforms,
const es::ComponentGroup<ren::MatUniform>& matUniforms,
const es::ComponentGroup<ren::Shader>& shader,
const es::ComponentGroup<ren::GLState>& state,
const es::ComponentGroup<gen::StaticCamera>& camera,
const es::ComponentGroup<ren::StaticGLState>& defaultGLState,
const es::ComponentGroup<ren::StaticVBOMan>& vboMan) override
{
/// \todo This needs to be moved to pre-execute.
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{
return;
}
// Setup *everything*. We don't want to enter multiple conditional
// statements if we can avoid it. So we assume everything has not been
// setup (including uniforms) if the simple geom hasn't been setup.
if (geom.front().attribs.isSetup() == false)
{
// We use const cast to get around a 'modify' call for 2 reasons:
// 1) This is populating system specific GL data. It has no bearing on the
// actual simulation state.
// 2) It is more correct than issuing a modify call. The data is used
// directly below to render geometry.
const_cast<RenderBasicGeom&>(geom.front()).attribs.setup(
vbo.front().glid, shader.front().glid, vboMan.front());
/// \todo Optimize by pulling uniforms only once.
if (commonUniforms.size() > 0)
{
const_cast<ren::CommonUniforms&>(commonUniforms.front()).checkUniformArray(
shader.front().glid);
}
if (vecUniforms.size() > 0)
{
for (const ren::VecUniform& unif : vecUniforms)
{
const_cast<ren::VecUniform&>(unif).checkUniform(shader.front().glid);
}
}
if (matUniforms.size() > 0)
{
for (const ren::MatUniform& unif : matUniforms)
{
const_cast<ren::MatUniform&>(unif).checkUniform(shader.front().glid);
}
}
}
// Check to see if we have GLState. If so, apply it relative to the
// current state (I'm actually thinking GLState is a bad idea, and we
// should just program what we need manually in the system -- depending
// on type). State can be set in a pre-walk phase.
if (state.size() > 0 && defaultGLState.size() > 0)
{
// Apply GLState based on current GLState (the static state), if it is
// present. Otherwise, fully apply it (performance issue).
state.front().state.applyRelative(defaultGLState.front().state);
}
// Bind shader.
GL(glUseProgram(shader.front().glid));
// Bind VBO and IBO
GL(glBindBuffer(GL_ARRAY_BUFFER, vbo.front().glid));
GL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo.front().glid));
// Bind any common uniforms.
if (commonUniforms.size() > 0)
{
commonUniforms.front().applyCommonUniforms(
trafo.front().transform, camera.front().data, time.front().globalTime);
}
// Apply vector uniforms (if any).
for (const ren::VecUniform& unif : vecUniforms) {unif.applyUniform();}
// Apply matrix uniforms (if any).
for (const ren::MatUniform& unif : matUniforms) {unif.applyUniform();}
geom.front().attribs.bind();
// Disable zwrite if we are rendering a transparent object.
if (srstate.front().state.get(RenderState::USE_TRANSPARENCY))
{
GL(glDepthMask(GL_FALSE));
GL(glDisable(GL_CULL_FACE));
}
if (rlist.size() > 0)
{
glm::mat4 rlistTrafo = trafo.front().transform;
GLint uniformColorLoc = 0;
for (const ren::VecUniform& unif : vecUniforms)
{
if (std::string(unif.getName()) == "uColor")
{
uniformColorLoc = unif.uniformLocation;
}
}
// Note: Some of this work can be done beforehand. But we elect not to
// since it is feasible that the data contained in the VBO can change
// fairly dramatically.
// Build BSerialize object.
CPM_BSERIALIZE_NS::BSerialize posDeserialize(
rlist.front().data->getBuffer(), rlist.front().data->getBufferSize());
CPM_BSERIALIZE_NS::BSerialize colorDeserialize(
rlist.front().data->getBuffer(), rlist.front().data->getBufferSize());
int64_t posSize = 0;
int64_t colorSize = 0;
int64_t stride = 0; // Stride of entire attributes buffer.
// Determine stride for our buffer. Also determine appropriate position
// and color information offsets, and set the offsets. Also determine
// attribute size in bytes.
for (const auto& attrib : rlist.front().attributes)
{
if (attrib.name == "aPos")
{
if (stride != 0) {posDeserialize.readBytes(stride);}
posSize = attrib.sizeInBytes;
}
else if (attrib.name == "aColor")
{
if (stride != 0) {colorDeserialize.readBytes(stride);}
colorSize = attrib.sizeInBytes;
}
stride += attrib.sizeInBytes;
}
int64_t posStride = stride - posSize;
int64_t colorStride = stride - colorSize;
// Render using a draw list. We will be using the VBO and IBO attached
// to this object as the basic rendering primitive.
for (int i = 0; i < rlist.front().numElements; ++i)
{
// Read position.
float x = posDeserialize.read<float>();
float y = posDeserialize.read<float>();
float z = posDeserialize.read<float>();
posDeserialize.readBytes(posStride);
// Read color if available.
if (colorSize > 0)
{
float r = static_cast<float>(colorDeserialize.read<uint8_t>()) / 255.0f;
float g = static_cast<float>(colorDeserialize.read<uint8_t>()) / 255.0f;
float b = static_cast<float>(colorDeserialize.read<uint8_t>()) / 255.0f;
float a = static_cast<float>(colorDeserialize.read<uint8_t>()) / 255.0f;
colorDeserialize.readBytes(posStride);
/// \todo Set the uniform color uniform. We need to lookup the
/// color uniform in our shader.
GL(glUniform4f(uniformColorLoc, r, g, b, a));
}
// Update transform.
rlistTrafo[3].x = x;
rlistTrafo[3].y = y;
rlistTrafo[3].z = z;
commonUniforms.front().applyCommonUniforms(
rlistTrafo, camera.front().data, time.front().globalTime);
GL(glDrawElements(ibo.front().primMode, ibo.front().numPrims,
ibo.front().primType, 0));
}
}
else
{
if (!srstate.front().state.get(RenderState::IS_DOUBLE_SIDED))
{
GL(glDrawElements(ibo.front().primMode, ibo.front().numPrims,
ibo.front().primType, 0));
}
else
{
GL(glEnable(GL_CULL_FACE));
// Double sided rendering. Mimic SCIRun4 and use GL_FRONT and GL_BACK
// to mimic forward facing and back facing polygons.
// Draw front facing polygons.
GLint fdToggleLoc = glGetUniformLocation(shader.front().glid, "uFDToggle");
GL(glUniform1f(fdToggleLoc, 1.0f));
glCullFace(GL_BACK);
GL(glDrawElements(ibo.front().primMode, ibo.front().numPrims,
ibo.front().primType, 0));
GL(glUniform1f(fdToggleLoc, 0.0f));
glCullFace(GL_FRONT);
GL(glDrawElements(ibo.front().primMode, ibo.front().numPrims,
ibo.front().primType, 0));
}
}
if (srstate.front().state.get(RenderState::USE_TRANSPARENCY))
{
GL(glDepthMask(GL_TRUE));
GL(glEnable(GL_CULL_FACE));
}
geom.front().attribs.unbind();
// Reapply the default state here -- only do this if static state is
// present.
if (state.size() > 0 && defaultGLState.size() > 0)
{
defaultGLState.front().state.applyRelative(state.front().state);
}
}
};
void registerSystem_RenderBasicGeom(CPM_ES_ACORN_NS::Acorn& core)
{
core.registerSystem<RenderBasicSys>();
}
const char* getSystemName_RenderBasicGeom()
{
return RenderBasicSys::getName();
}
} // namespace Render
} // namespace SCIRun
<|endoftext|> |
<commit_before>// Copyright (c) 2018 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/renderer/printing/print_render_frame_helper_delegate.h"
#include "content/public/renderer/render_frame.h"
#include "extensions/buildflags/buildflags.h"
#include "third_party/blink/public/web/web_element.h"
#include "third_party/blink/public/web/web_local_frame.h"
#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "extensions/common/constants.h"
#include "extensions/renderer/guest_view/mime_handler_view/post_message_support.h"
#endif // BUILDFLAG(ENABLE_EXTENSIONS)
namespace electron {
PrintRenderFrameHelperDelegate::PrintRenderFrameHelperDelegate() = default;
PrintRenderFrameHelperDelegate::~PrintRenderFrameHelperDelegate() = default;
// Return the PDF object element if |frame| is the out of process PDF extension.
blink::WebElement PrintRenderFrameHelperDelegate::GetPdfElement(
blink::WebLocalFrame* frame) {
#if BUILDFLAG(ENABLE_EXTENSIONS)
GURL url = frame->GetDocument().Url();
bool inside_pdf_extension =
url.SchemeIs(extensions::kExtensionScheme) &&
url.host_piece() == extension_misc::kPdfExtensionId;
if (inside_pdf_extension) {
// <object> with id="plugin" is created in
// chrome/browser/resources/pdf/pdf_viewer_base.js.
auto viewer_element = frame->GetDocument().GetElementById("viewer");
if (!viewer_element.IsNull() && !viewer_element.ShadowRoot().IsNull()) {
auto plugin_element =
viewer_element.ShadowRoot().QuerySelector("#plugin");
if (!plugin_element.IsNull()) {
return plugin_element;
}
}
NOTREACHED();
}
#endif // BUILDFLAG(ENABLE_EXTENSIONS)
return blink::WebElement();
}
bool PrintRenderFrameHelperDelegate::IsPrintPreviewEnabled() {
return false;
}
bool PrintRenderFrameHelperDelegate::OverridePrint(
blink::WebLocalFrame* frame) {
#if BUILDFLAG(ENABLE_EXTENSIONS)
auto* post_message_support =
extensions::PostMessageSupport::FromWebLocalFrame(frame);
if (post_message_support) {
// This message is handled in chrome/browser/resources/pdf/pdf_viewer.js and
// instructs the PDF plugin to print. This is to make window.print() on a
// PDF plugin document correctly print the PDF. See
// https://crbug.com/448720.
base::DictionaryValue message;
message.SetString("type", "print");
post_message_support->PostMessageFromValue(message);
return true;
}
#endif // BUILDFLAG(ENABLE_EXTENSIONS)
return false;
}
} // namespace electron
<commit_msg>fix: fetching PDF element from `WebLocalFrame` (#34176)<commit_after>// Copyright (c) 2018 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/renderer/printing/print_render_frame_helper_delegate.h"
#include "content/public/renderer/render_frame.h"
#include "extensions/buildflags/buildflags.h"
#include "third_party/blink/public/web/web_element.h"
#include "third_party/blink/public/web/web_local_frame.h"
#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "chrome/common/pdf_util.h"
#include "extensions/common/constants.h"
#include "extensions/renderer/guest_view/mime_handler_view/post_message_support.h"
#endif // BUILDFLAG(ENABLE_EXTENSIONS)
namespace electron {
PrintRenderFrameHelperDelegate::PrintRenderFrameHelperDelegate() = default;
PrintRenderFrameHelperDelegate::~PrintRenderFrameHelperDelegate() = default;
// Return the PDF object element if |frame| is the out of process PDF extension.
blink::WebElement PrintRenderFrameHelperDelegate::GetPdfElement(
blink::WebLocalFrame* frame) {
#if BUILDFLAG(ENABLE_EXTENSIONS)
if (frame->Parent() &&
IsPdfInternalPluginAllowedOrigin(frame->Parent()->GetSecurityOrigin())) {
auto plugin_element = frame->GetDocument().QuerySelector("embed");
DCHECK(!plugin_element.IsNull());
return plugin_element;
}
#endif // BUILDFLAG(ENABLE_EXTENSIONS)
return blink::WebElement();
}
bool PrintRenderFrameHelperDelegate::IsPrintPreviewEnabled() {
return false;
}
bool PrintRenderFrameHelperDelegate::OverridePrint(
blink::WebLocalFrame* frame) {
#if BUILDFLAG(ENABLE_EXTENSIONS)
auto* post_message_support =
extensions::PostMessageSupport::FromWebLocalFrame(frame);
if (post_message_support) {
// This message is handled in chrome/browser/resources/pdf/pdf_viewer.js and
// instructs the PDF plugin to print. This is to make window.print() on a
// PDF plugin document correctly print the PDF. See
// https://crbug.com/448720.
base::DictionaryValue message;
message.SetString("type", "print");
post_message_support->PostMessageFromValue(message);
return true;
}
#endif // BUILDFLAG(ENABLE_EXTENSIONS)
return false;
}
} // namespace electron
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: animationaudionode.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-03-30 08:05:02 $
*
* 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): _______________________________________
*
*
************************************************************************/
// must be first
#include <canvas/debug.hxx>
#include <canvas/verbosetrace.hxx>
#include <animationaudionode.hxx>
#include <delayevent.hxx>
#include <tools.hxx>
#include <nodetools.hxx>
#include <generateevent.hxx>
using namespace ::com::sun::star;
namespace presentation
{
namespace internal
{
AnimationAudioNode::AnimationAudioNode( const uno::Reference< animations::XAnimationNode >& xNode,
const BaseContainerNodeSharedPtr& rParent,
const NodeContext& rContext ) :
BaseNode( xNode, rParent, rContext ),
mxAudioNode( xNode, uno::UNO_QUERY_THROW ),
maSoundURL(),
mpPlayer()
{
mxAudioNode->getSource() >>= maSoundURL;
OSL_ENSURE( maSoundURL.getLength(),
"AnimationAudioNode::AnimationAudioNode(): could not extract sound source URL/empty URL string" );
ENSURE_AND_THROW( getContext().mxComponentContext.is(),
"AnimationAudioNode::AnimationAudioNode(): Invalid component context" );
}
void AnimationAudioNode::dispose()
{
resetPlayer();
mxAudioNode.clear();
BaseNode::dispose();
}
bool AnimationAudioNode::activate()
{
if( !BaseNode::activate() )
return false;
createPlayer();
// not having a player is not a hard error here
// (remainder of the animations should still
// work). Below, we assume a duration of 0.0 if no
// player is available
if( !mpPlayer.get() )
return false;
AnimationEventHandlerSharedPtr aHandler( ::boost::dynamic_pointer_cast<AnimationEventHandler>( getSelf() ) );
OSL_ENSURE( aHandler.get(), "AnimationAudioNode::activate(): could not cas self to AnimationEventHandler?" );
getContext().mrEventMultiplexer.addCommandStopAudioHandler( aHandler );
return mpPlayer->startPlayback();
}
// TODO(F2): generate deactivation event, when sound
// is over
void AnimationAudioNode::deactivate()
{
AnimationEventHandlerSharedPtr aHandler( ::boost::dynamic_pointer_cast<AnimationEventHandler>( getSelf() ) );
OSL_ENSURE( aHandler.get(), "AnimationAudioNode::deactivate(): could not cas self to AnimationEventHandler?" );
getContext().mrEventMultiplexer.removeCommandStopAudioHandler( aHandler );
// force-end sound
if( mpPlayer.get() )
mpPlayer->stopPlayback();
resetPlayer();
// notify state change
getContext().mrEventMultiplexer.notifyAudioStopped( getSelf() );
BaseNode::deactivate();
}
/** Overridden, because the sound duration normally
determines effect duration.
*/
void AnimationAudioNode::scheduleDeactivationEvent() const
{
// TODO(F2): Handle end time attribute, too
if( getXNode()->getDuration().hasValue() )
{
BaseNode::scheduleDeactivationEvent();
}
else
{
createPlayer();
if( !mpPlayer.get() )
{
// no duration and no inherent media time
// - assume duration '0'
getContext().mrEventQueue.addEvent(
makeEvent( boost::bind( &BaseNode::deactivate,
getSelf() ) ) );
}
else
{
// no node duration. Take inherent media
// time, then
getContext().mrEventQueue.addEvent(
makeDelay( boost::bind( &BaseNode::deactivate,
getSelf() ),
mpPlayer->getDuration() ) );
}
}
}
void AnimationAudioNode::notifyDeactivating( const AnimationNodeSharedPtr& rNotifier )
{
// NO-OP for all leaf nodes (which typically don't register nowhere)
// TODO(F1): for end sync functionality, this might indeed be used some day
}
bool AnimationAudioNode::hasPendingAnimation() const
{
// force slide to use the animation framework
// (otherwise, a single sound on the slide would
// not be played).
return true;
}
void AnimationAudioNode::createPlayer() const
{
if( mpPlayer.get() )
return;
try
{
mpPlayer = SoundPlayer::create( getContext().mrEventMultiplexer,
maSoundURL,
getContext().mxComponentContext );
}
catch( lang::NoSupportException& )
{
// catch possible exceptions from SoundPlayer,
// since being not able to playback the sound
// is not a hard error here (remainder of the
// animations should still work).
}
}
void AnimationAudioNode::resetPlayer() const
{
if( mpPlayer.get() )
{
mpPlayer->stopPlayback();
mpPlayer->dispose();
mpPlayer.reset();
}
}
bool AnimationAudioNode::handleAnimationEvent( const AnimationNodeSharedPtr& rNode )
{
// TODO: for now we support only STOPAUDIO events.
deactivate();
return true;
}
}
}
<commit_msg>INTEGRATION: CWS presfixes04 (1.6.8); FILE MERGED 2005/04/20 18:02:22 thb 1.6.8.1: #i47657# Changed Event interface, to better express the meaning of the isCharged() (former wasFired()) method; changed EventQueue and UserEventQueue to ignore events which are discharged; changed Impl_Presentation::notifySlideAnimationEnded to generate an interruptable delay, i.e. one that can be fired prematurely by user intervention; improved/clarified docs<commit_after>/*************************************************************************
*
* $RCSfile: animationaudionode.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: obo $ $Date: 2005-04-22 13:29:38 $
*
* 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): _______________________________________
*
*
************************************************************************/
// must be first
#include <canvas/debug.hxx>
#include <canvas/verbosetrace.hxx>
#include <animationaudionode.hxx>
#include <delayevent.hxx>
#include <tools.hxx>
#include <nodetools.hxx>
using namespace ::com::sun::star;
namespace presentation
{
namespace internal
{
AnimationAudioNode::AnimationAudioNode( const uno::Reference< animations::XAnimationNode >& xNode,
const BaseContainerNodeSharedPtr& rParent,
const NodeContext& rContext ) :
BaseNode( xNode, rParent, rContext ),
mxAudioNode( xNode, uno::UNO_QUERY_THROW ),
maSoundURL(),
mpPlayer()
{
mxAudioNode->getSource() >>= maSoundURL;
OSL_ENSURE( maSoundURL.getLength(),
"AnimationAudioNode::AnimationAudioNode(): could not extract sound source URL/empty URL string" );
ENSURE_AND_THROW( getContext().mxComponentContext.is(),
"AnimationAudioNode::AnimationAudioNode(): Invalid component context" );
}
void AnimationAudioNode::dispose()
{
resetPlayer();
mxAudioNode.clear();
BaseNode::dispose();
}
bool AnimationAudioNode::activate()
{
if( !BaseNode::activate() )
return false;
createPlayer();
// not having a player is not a hard error here
// (remainder of the animations should still
// work). Below, we assume a duration of 0.0 if no
// player is available
if( !mpPlayer.get() )
return false;
AnimationEventHandlerSharedPtr aHandler( ::boost::dynamic_pointer_cast<AnimationEventHandler>( getSelf() ) );
OSL_ENSURE( aHandler.get(), "AnimationAudioNode::activate(): could not cas self to AnimationEventHandler?" );
getContext().mrEventMultiplexer.addCommandStopAudioHandler( aHandler );
return mpPlayer->startPlayback();
}
// TODO(F2): generate deactivation event, when sound
// is over
void AnimationAudioNode::deactivate()
{
AnimationEventHandlerSharedPtr aHandler( ::boost::dynamic_pointer_cast<AnimationEventHandler>( getSelf() ) );
OSL_ENSURE( aHandler.get(), "AnimationAudioNode::deactivate(): could not cas self to AnimationEventHandler?" );
getContext().mrEventMultiplexer.removeCommandStopAudioHandler( aHandler );
// force-end sound
if( mpPlayer.get() )
mpPlayer->stopPlayback();
resetPlayer();
// notify state change
getContext().mrEventMultiplexer.notifyAudioStopped( getSelf() );
BaseNode::deactivate();
}
/** Overridden, because the sound duration normally
determines effect duration.
*/
void AnimationAudioNode::scheduleDeactivationEvent() const
{
// TODO(F2): Handle end time attribute, too
if( getXNode()->getDuration().hasValue() )
{
BaseNode::scheduleDeactivationEvent();
}
else
{
createPlayer();
if( !mpPlayer.get() )
{
// no duration and no inherent media time
// - assume duration '0'
getContext().mrEventQueue.addEvent(
makeEvent( boost::bind( &BaseNode::deactivate,
getSelf() ) ) );
}
else
{
// no node duration. Take inherent media
// time, then
getContext().mrEventQueue.addEvent(
makeDelay( boost::bind( &BaseNode::deactivate,
getSelf() ),
mpPlayer->getDuration() ) );
}
}
}
void AnimationAudioNode::notifyDeactivating( const AnimationNodeSharedPtr& rNotifier )
{
// NO-OP for all leaf nodes (which typically don't register nowhere)
// TODO(F1): for end sync functionality, this might indeed be used some day
}
bool AnimationAudioNode::hasPendingAnimation() const
{
// force slide to use the animation framework
// (otherwise, a single sound on the slide would
// not be played).
return true;
}
void AnimationAudioNode::createPlayer() const
{
if( mpPlayer.get() )
return;
try
{
mpPlayer = SoundPlayer::create( getContext().mrEventMultiplexer,
maSoundURL,
getContext().mxComponentContext );
}
catch( lang::NoSupportException& )
{
// catch possible exceptions from SoundPlayer,
// since being not able to playback the sound
// is not a hard error here (remainder of the
// animations should still work).
}
}
void AnimationAudioNode::resetPlayer() const
{
if( mpPlayer.get() )
{
mpPlayer->stopPlayback();
mpPlayer->dispose();
mpPlayer.reset();
}
}
bool AnimationAudioNode::handleAnimationEvent( const AnimationNodeSharedPtr& rNode )
{
// TODO(F2): for now we support only STOPAUDIO events.
deactivate();
return true;
}
}
}
<|endoftext|> |
<commit_before>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2011 Sergey Lisitsyn
* Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
*/
#include <shogun/evaluation/ContingencyTableEvaluation.h>
#include <shogun/labels/BinaryLabels.h>
using namespace shogun;
float64_t CContingencyTableEvaluation::evaluate(CLabels* predicted, CLabels* ground_truth)
{
ASSERT(predicted->get_label_type()==LT_BINARY);
ASSERT(ground_truth->get_label_type()==LT_BINARY);
predicted->ensure_valid();
ground_truth->ensure_valid();
compute_scores((CBinaryLabels*)predicted,(CBinaryLabels*)ground_truth);
switch (m_type)
{
case ACCURACY:
return get_accuracy();
case ERROR_RATE:
return get_error_rate();
case BAL:
return get_BAL();
case WRACC:
return get_WRACC();
case F1:
return get_F1();
case CROSS_CORRELATION:
return get_cross_correlation();
case RECALL:
return get_recall();
case PRECISION:
return get_precision();
case SPECIFICITY:
return get_specificity();
}
SG_NOTIMPLEMENTED;
return 42;
}
inline EEvaluationDirection CContingencyTableEvaluation::get_evaluation_direction()
{
switch (m_type)
{
case ACCURACY:
return ED_MAXIMIZE;
case ERROR_RATE:
return ED_MINIMIZE;
case BAL:
return ED_MINIMIZE;
case WRACC:
return ED_MAXIMIZE;
case F1:
return ED_MAXIMIZE;
case CROSS_CORRELATION:
return ED_MAXIMIZE;
case RECALL:
return ED_MAXIMIZE;
case PRECISION:
return ED_MAXIMIZE;
case SPECIFICITY:
return ED_MAXIMIZE;
default:
SG_NOTIMPLEMENTED;
}
return ED_MINIMIZE;
}
void CContingencyTableEvaluation::compute_scores(CBinaryLabels* predicted, CBinaryLabels* ground_truth)
{
ASSERT(ground_truth->get_label_type() == LT_BINARY);
ASSERT(predicted->get_label_type() == LT_BINARY);
ASSERT(predicted->get_num_labels()==ground_truth->get_num_labels());
m_TP = 0.0;
m_FP = 0.0;
m_TN = 0.0;
m_FN = 0.0;
m_N = predicted->get_num_labels();
for (int i=0; i<predicted->get_num_labels(); i++)
{
if (ground_truth->get_label(i)==1)
{
if (predicted->get_label(i)==1)
m_TP += 1.0;
else
m_FN += 1.0;
}
else
{
if (predicted->get_label(i)==1)
m_FP += 1.0;
else
m_TN += 1.0;
}
}
m_computed = true;
}
<commit_msg>bugfix: removed valid check since this case has to be allowed<commit_after>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2011 Sergey Lisitsyn
* Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
*/
#include <shogun/evaluation/ContingencyTableEvaluation.h>
#include <shogun/labels/BinaryLabels.h>
using namespace shogun;
float64_t CContingencyTableEvaluation::evaluate(CLabels* predicted, CLabels* ground_truth)
{
ASSERT(predicted->get_label_type()==LT_BINARY);
ASSERT(ground_truth->get_label_type()==LT_BINARY);
/* commented out: what if a machine only returns +1 in apply() ??
* Heiko Strathamn */
// predicted->ensure_valid();
ground_truth->ensure_valid();
compute_scores((CBinaryLabels*)predicted,(CBinaryLabels*)ground_truth);
switch (m_type)
{
case ACCURACY:
return get_accuracy();
case ERROR_RATE:
return get_error_rate();
case BAL:
return get_BAL();
case WRACC:
return get_WRACC();
case F1:
return get_F1();
case CROSS_CORRELATION:
return get_cross_correlation();
case RECALL:
return get_recall();
case PRECISION:
return get_precision();
case SPECIFICITY:
return get_specificity();
}
SG_NOTIMPLEMENTED;
return 42;
}
inline EEvaluationDirection CContingencyTableEvaluation::get_evaluation_direction()
{
switch (m_type)
{
case ACCURACY:
return ED_MAXIMIZE;
case ERROR_RATE:
return ED_MINIMIZE;
case BAL:
return ED_MINIMIZE;
case WRACC:
return ED_MAXIMIZE;
case F1:
return ED_MAXIMIZE;
case CROSS_CORRELATION:
return ED_MAXIMIZE;
case RECALL:
return ED_MAXIMIZE;
case PRECISION:
return ED_MAXIMIZE;
case SPECIFICITY:
return ED_MAXIMIZE;
default:
SG_NOTIMPLEMENTED;
}
return ED_MINIMIZE;
}
void CContingencyTableEvaluation::compute_scores(CBinaryLabels* predicted, CBinaryLabels* ground_truth)
{
ASSERT(ground_truth->get_label_type() == LT_BINARY);
ASSERT(predicted->get_label_type() == LT_BINARY);
ASSERT(predicted->get_num_labels()==ground_truth->get_num_labels());
m_TP = 0.0;
m_FP = 0.0;
m_TN = 0.0;
m_FN = 0.0;
m_N = predicted->get_num_labels();
for (int i=0; i<predicted->get_num_labels(); i++)
{
if (ground_truth->get_label(i)==1)
{
if (predicted->get_label(i)==1)
m_TP += 1.0;
else
m_FN += 1.0;
}
else
{
if (predicted->get_label(i)==1)
m_FP += 1.0;
else
m_TN += 1.0;
}
}
m_computed = true;
}
<|endoftext|> |
<commit_before>#include "ZambeziManager.h"
#include "ZambeziMiningTask.h"
#include "../group-manager/PropValueTable.h" // pvid_t
#include "../group-manager/GroupManager.h"
#include "../attr-manager/AttrManager.h"
#include "../attr-manager/AttrTable.h"
#include <common/PropSharedLock.h>
#include <configuration-manager/ZambeziConfig.h>
#include <util/ClockTimer.h>
#include <glog/logging.h>
#include <fstream>
#include <math.h>
#include <algorithm>
using namespace sf1r;
namespace
{
const izenelib::ir::Zambezi::Algorithm kAlgorithm =
izenelib::ir::Zambezi::SVS;
}
ZambeziManager::ZambeziManager(
const ZambeziConfig& config,
faceted::AttrManager* attrManager,
NumericPropertyTableBuilder* numericTableBuilder)
: config_(config)
, attrManager_(attrManager)
, indexer_(config_.poolSize, config_.poolCount, config_.reverse)
, numericTableBuilder_(numericTableBuilder)
{
}
bool ZambeziManager::open()
{
const std::string& path = config_.indexFilePath;
std::ifstream ifs(path.c_str(), std::ios_base::binary);
if (! ifs)
return true;
LOG(INFO) << "loading zambezi index path: " << path;
try
{
indexer_.load(ifs);
}
catch (const std::exception& e)
{
LOG(ERROR) << "exception in read file: " << e.what()
<< ", path: " << path;
return false;
}
LOG(INFO) << "finished loading zambezi index, total doc num: "
<< indexer_.totalDocNum();
return true;
}
MiningTask* ZambeziManager::createMiningTask(DocumentManager& documentManager)
{
return new ZambeziMiningTask(config_, documentManager, indexer_);
}
void ZambeziManager::search(
const std::vector<std::string>& tokens,
const boost::function<bool(uint32_t)>& filter,
uint32_t limit,
std::vector<docid_t>& docids,
std::vector<uint32_t>& scores)
{
izenelib::util::ClockTimer timer;
indexer_.retrievalAndFiltering(kAlgorithm, tokens, filter, limit, docids, scores);
LOG(INFO) << "zambezi returns docid num: " << docids.size()
<< ", costs :" << timer.elapsed() << " seconds";
}
void ZambeziManager::NormalizeScore(
std::vector<docid_t>& docids,
std::vector<float>& scores,
std::vector<float>& productScores,
PropSharedLockSet &sharedLockSet)
{
faceted::AttrTable* attTable = NULL;
if (attrManager_)
{
attTable = &(attrManager_->getAttrTable());
sharedLockSet.insertSharedLock(attTable);
}
float maxScore = 1;
std::string propName = "itemcount";
boost::shared_ptr<NumericPropertyTableBase> numericTable =
numericTableBuilder_->createPropertyTable(propName);
if (numericTable)
sharedLockSet.insertSharedLock(numericTable.get());
for (uint32_t i = 0; i < docids.size(); ++i)
{
uint32_t attr_size = 1;
if (attTable)
{
faceted::AttrTable::ValueIdList attrvids;
attTable->getValueIdList(docids[i], attrvids);
attr_size = std::min(attrvids.size(), size_t(10));
}
if (numericTable)
{
int32_t itemcount = 1;
numericTable->getInt32Value(docids[i], itemcount, false);
attr_size += std::min(itemcount, 50);
}
scores[i] = scores[i] * pow(attr_size, 0.3);
if (scores[i] > maxScore)
maxScore = scores[i];
}
for (unsigned int i = 0; i < scores.size(); ++i)
{
scores[i] = int(scores[i] / maxScore * 10) + productScores[i];
}
}
<commit_msg>add commetcount factor into relevance score, and if use this, the b5mp.xm Category weight need to change from 10 to 100;<commit_after>#include "ZambeziManager.h"
#include "ZambeziMiningTask.h"
#include "../group-manager/PropValueTable.h" // pvid_t
#include "../group-manager/GroupManager.h"
#include "../attr-manager/AttrManager.h"
#include "../attr-manager/AttrTable.h"
#include <common/PropSharedLock.h>
#include <configuration-manager/ZambeziConfig.h>
#include <util/ClockTimer.h>
#include <glog/logging.h>
#include <fstream>
#include <math.h>
#include <algorithm>
using namespace sf1r;
namespace
{
const izenelib::ir::Zambezi::Algorithm kAlgorithm =
izenelib::ir::Zambezi::SVS;
}
ZambeziManager::ZambeziManager(
const ZambeziConfig& config,
faceted::AttrManager* attrManager,
NumericPropertyTableBuilder* numericTableBuilder)
: config_(config)
, attrManager_(attrManager)
, indexer_(config_.poolSize, config_.poolCount, config_.reverse)
, numericTableBuilder_(numericTableBuilder)
{
}
bool ZambeziManager::open()
{
const std::string& path = config_.indexFilePath;
std::ifstream ifs(path.c_str(), std::ios_base::binary);
if (! ifs)
return true;
LOG(INFO) << "loading zambezi index path: " << path;
try
{
indexer_.load(ifs);
}
catch (const std::exception& e)
{
LOG(ERROR) << "exception in read file: " << e.what()
<< ", path: " << path;
return false;
}
LOG(INFO) << "finished loading zambezi index, total doc num: "
<< indexer_.totalDocNum();
return true;
}
MiningTask* ZambeziManager::createMiningTask(DocumentManager& documentManager)
{
return new ZambeziMiningTask(config_, documentManager, indexer_);
}
void ZambeziManager::search(
const std::vector<std::string>& tokens,
const boost::function<bool(uint32_t)>& filter,
uint32_t limit,
std::vector<docid_t>& docids,
std::vector<uint32_t>& scores)
{
izenelib::util::ClockTimer timer;
indexer_.retrievalAndFiltering(kAlgorithm, tokens, filter, limit, docids, scores);
LOG(INFO) << "zambezi returns docid num: " << docids.size()
<< ", costs :" << timer.elapsed() << " seconds";
}
void ZambeziManager::NormalizeScore(
std::vector<docid_t>& docids,
std::vector<float>& scores,
std::vector<float>& productScores,
PropSharedLockSet &sharedLockSet)
{
faceted::AttrTable* attTable = NULL;
if (attrManager_)
{
attTable = &(attrManager_->getAttrTable());
sharedLockSet.insertSharedLock(attTable);
}
float maxScore = 1;
std::string propName = "itemcount";
std::string propName_comment = "CommentCount";
boost::shared_ptr<NumericPropertyTableBase> numericTable =
numericTableBuilder_->createPropertyTable(propName);
boost::shared_ptr<NumericPropertyTableBase> numericTable_comment =
numericTableBuilder_->createPropertyTable(propName_comment);
if (numericTable)
sharedLockSet.insertSharedLock(numericTable.get());
if (numericTable_comment)
sharedLockSet.insertSharedLock(numericTable_comment.get());
for (uint32_t i = 0; i < docids.size(); ++i)
{
uint32_t attr_size = 1;
if (attTable)
{
faceted::AttrTable::ValueIdList attrvids;
attTable->getValueIdList(docids[i], attrvids);
attr_size = std::min(attrvids.size(), size_t(10));
}
if (numericTable)
{
int32_t itemcount = 1;
numericTable->getInt32Value(docids[i], itemcount, false);
attr_size += std::min(itemcount, 50);
}
if (numericTable_comment)
{
int32_t commentcount = 1;
numericTable_comment->getInt32Value(docids[i], commentcount, false);
attr_size += std::min(commentcount, 100);
}
scores[i] = scores[i] * pow(attr_size, 0.3);
if (scores[i] > maxScore)
maxScore = scores[i];
}
for (unsigned int i = 0; i < scores.size(); ++i)
{
scores[i] = int(scores[i] / maxScore * 100) + productScores[i];
}
}
<|endoftext|> |
<commit_before>//
// Created by pkanev on 5/11/2017.
//
#include <NativeScriptAssert.h>
#include "v8-css-agent-impl.h"
namespace v8_inspector {
namespace CSSAgentState {
static const char cssEnabled[] = "cssEnabled";
}
V8CSSAgentImpl::V8CSSAgentImpl(V8InspectorSessionImpl *session,
protocol::FrontendChannel *frontendChannel,
protocol::DictionaryValue *state)
: m_session(session),
m_frontend(frontendChannel),
m_state(state),
m_enabled(false) {
Instance = this;
}
V8CSSAgentImpl::~V8CSSAgentImpl() { }
void V8CSSAgentImpl::enable(std::unique_ptr<protocol::CSS::Backend::EnableCallback> callback) {
if (m_enabled) {
callback->sendFailure("CSS Agent already enabled!");
return;
}
m_state->setBoolean(CSSAgentState::cssEnabled, true);
m_enabled = true;
callback->sendSuccess();
}
void V8CSSAgentImpl::disable(ErrorString *) {
if (!m_enabled) {
return;
}
m_state->setBoolean(CSSAgentState::cssEnabled, false);
m_enabled = false;
}
// TODO: Pete: implement
void V8CSSAgentImpl::getMatchedStylesForNode(ErrorString *errorString, int in_nodeId,
Maybe<protocol::CSS::CSSStyle> *out_inlineStyle,
Maybe<protocol::CSS::CSSStyle> *out_attributesStyle,
Maybe<protocol::Array<protocol::CSS::RuleMatch>> *out_matchedCSSRules,
Maybe<protocol::Array<protocol::CSS::PseudoElementMatches>> *out_pseudoElements,
Maybe<protocol::Array<protocol::CSS::InheritedStyleEntry>> *out_inherited,
Maybe<protocol::Array<protocol::CSS::CSSKeyframesRule>> *out_cssKeyframesRules) {
//// out_inlineStyle
auto cssPropsArr = protocol::Array<protocol::CSS::CSSProperty>::create();
auto shorthandPropArr = protocol::Array<protocol::CSS::ShorthandEntry>::create();
auto inlineStyle = protocol::CSS::CSSStyle::create()
.setCssProperties(std::move(cssPropsArr))
.setShorthandEntries(std::move(shorthandPropArr))
.build();
//// out_attributesStyle
auto attrArr = protocol::Array<protocol::CSS::CSSProperty>::create();
auto attributeStyle = protocol::CSS::CSSStyle::create()
.setCssProperties(std::move(attrArr))
.setShorthandEntries(std::move(protocol::Array<protocol::CSS::ShorthandEntry>::create()))
.build();
//// out_matchedCSSRules
auto cssSelectorsArr = protocol::Array<protocol::CSS::Value>::create();
auto cssSelectorList = protocol::CSS::SelectorList::create()
.setSelectors(std::move(cssSelectorsArr))
.setText("")
.build();
auto cssRule = protocol::CSS::CSSRule::create()
.setSelectorList(std::move(cssSelectorList))
.setOrigin(protocol::CSS::StyleSheetOriginEnum::Regular)
.setStyle(std::move(protocol::CSS::CSSStyle::create()
.setCssProperties(std::move(protocol::Array<protocol::CSS::CSSProperty>::create()))
.setShorthandEntries(std::move(protocol::Array<protocol::CSS::ShorthandEntry>::create()))
.build()))
.build();
auto rulesMatchedArr = protocol::Array<protocol::CSS::RuleMatch>::create();
//// out_pseudoElements
auto pseudoElementsArr = protocol::Array<protocol::CSS::PseudoElementMatches>::create();
//// out_inherited
auto inheritedElementsArr = protocol::Array<protocol::CSS::InheritedStyleEntry>::create();
auto inheritedelem = protocol::CSS::InheritedStyleEntry::create()
.setInlineStyle(std::move(protocol::CSS::CSSStyle::create()
.setCssProperties(std::move(protocol::Array<protocol::CSS::CSSProperty>::create()))
.setShorthandEntries(std::move(protocol::Array<protocol::CSS::ShorthandEntry>::create()))
.build()))
.setMatchedCSSRules(std::move(protocol::Array<protocol::CSS::RuleMatch>::create()))
.build();
inheritedElementsArr->addItem(std::move(inheritedelem));
//// out_cssKeyframesRules
auto cssKeyFramesRulesArr = protocol::Array<protocol::CSS::CSSKeyframesRule>::create();
*out_inlineStyle = Maybe<protocol::CSS::CSSStyle>(std::move(inlineStyle));
*out_attributesStyle = Maybe<protocol::CSS::CSSStyle>(std::move(attributeStyle));
*out_matchedCSSRules = Maybe<protocol::Array<protocol::CSS::RuleMatch>>(std::move(rulesMatchedArr));
*out_cssKeyframesRules = Maybe<protocol::Array<protocol::CSS::CSSKeyframesRule>>(std::move(cssKeyFramesRulesArr));
*out_inherited = Maybe<protocol::Array<protocol::CSS::InheritedStyleEntry>>(std::move(inheritedElementsArr));
*out_pseudoElements = Maybe<protocol::Array<protocol::CSS::PseudoElementMatches>>(std::move(pseudoElementsArr));
}
// TODO: Pete: implement
void V8CSSAgentImpl::getInlineStylesForNode(ErrorString *, int in_nodeId,
Maybe<protocol::CSS::CSSStyle> *out_inlineStyle,
Maybe<protocol::CSS::CSSStyle> *out_attributesStyle) {
//// out_inlineStyle
auto cssPropsArr = protocol::Array<protocol::CSS::CSSProperty>::create();
auto shorthandPropArr = protocol::Array<protocol::CSS::ShorthandEntry>::create();
auto inlineStyle = protocol::CSS::CSSStyle::create()
.setCssProperties(std::move(cssPropsArr))
.setShorthandEntries(std::move(shorthandPropArr))
.build();
//// out_attributesStyle
auto attrArr = protocol::Array<protocol::CSS::CSSProperty>::create();
auto attributeStyle = protocol::CSS::CSSStyle::create()
.setCssProperties(std::move(attrArr))
.setShorthandEntries(std::move(protocol::Array<protocol::CSS::ShorthandEntry>::create()))
.build();
*out_inlineStyle = Maybe<protocol::CSS::CSSStyle>(std::move(inlineStyle));
*out_attributesStyle = Maybe<protocol::CSS::CSSStyle>(std::move(attributeStyle));
}
void V8CSSAgentImpl::getComputedStyleForNode(ErrorString *, int in_nodeId,
std::unique_ptr<protocol::Array<protocol::CSS::CSSComputedStyleProperty>> *out_computedStyle) {
auto computedStylePropertyArr = protocol::Array<protocol::CSS::CSSComputedStyleProperty>::create();
*out_computedStyle = std::move(computedStylePropertyArr);
}
void V8CSSAgentImpl::getPlatformFontsForNode(ErrorString *, int in_nodeId,
std::unique_ptr<protocol::Array<protocol::CSS::PlatformFontUsage>> *out_fonts) {
auto fontsArr = protocol::Array<protocol::CSS::PlatformFontUsage>::create();
fontsArr->addItem(std::move(protocol::CSS::PlatformFontUsage::create().setFamilyName("System Font").setGlyphCount(1).setIsCustomFont(false).build()));
*out_fonts = std::move(fontsArr);
}
// TODO: Pete: implement
void V8CSSAgentImpl::getStyleSheetText(ErrorString *, const String &in_styleSheetId,
String *out_text) {
*out_text = "";
}
V8CSSAgentImpl* V8CSSAgentImpl::Instance = 0;
}<commit_msg>get computed styles for a node based on modules implementation<commit_after>//
// Created by pkanev on 5/11/2017.
//
#include <NativeScriptAssert.h>
#include <ArgConverter.h>
#include "v8-css-agent-impl.h"
namespace v8_inspector {
using tns::ArgConverter;
namespace CSSAgentState {
static const char cssEnabled[] = "cssEnabled";
}
V8CSSAgentImpl::V8CSSAgentImpl(V8InspectorSessionImpl *session,
protocol::FrontendChannel *frontendChannel,
protocol::DictionaryValue *state)
: m_session(session),
m_frontend(frontendChannel),
m_state(state),
m_enabled(false) {
Instance = this;
}
V8CSSAgentImpl::~V8CSSAgentImpl() { }
void V8CSSAgentImpl::enable(std::unique_ptr<protocol::CSS::Backend::EnableCallback> callback) {
if (m_enabled) {
callback->sendFailure("CSS Agent already enabled!");
return;
}
m_state->setBoolean(CSSAgentState::cssEnabled, true);
m_enabled = true;
callback->sendSuccess();
}
void V8CSSAgentImpl::disable(ErrorString *) {
if (!m_enabled) {
return;
}
m_state->setBoolean(CSSAgentState::cssEnabled, false);
m_enabled = false;
}
// TODO: Pete: implement
void V8CSSAgentImpl::getMatchedStylesForNode(ErrorString *errorString, int in_nodeId,
Maybe<protocol::CSS::CSSStyle> *out_inlineStyle,
Maybe<protocol::CSS::CSSStyle> *out_attributesStyle,
Maybe<protocol::Array<protocol::CSS::RuleMatch>> *out_matchedCSSRules,
Maybe<protocol::Array<protocol::CSS::PseudoElementMatches>> *out_pseudoElements,
Maybe<protocol::Array<protocol::CSS::InheritedStyleEntry>> *out_inherited,
Maybe<protocol::Array<protocol::CSS::CSSKeyframesRule>> *out_cssKeyframesRules) {
//// out_inlineStyle
auto cssPropsArr = protocol::Array<protocol::CSS::CSSProperty>::create();
auto shorthandPropArr = protocol::Array<protocol::CSS::ShorthandEntry>::create();
auto inlineStyle = protocol::CSS::CSSStyle::create()
.setCssProperties(std::move(cssPropsArr))
.setShorthandEntries(std::move(shorthandPropArr))
.build();
//// out_attributesStyle
auto attrArr = protocol::Array<protocol::CSS::CSSProperty>::create();
auto attributeStyle = protocol::CSS::CSSStyle::create()
.setCssProperties(std::move(attrArr))
.setShorthandEntries(std::move(protocol::Array<protocol::CSS::ShorthandEntry>::create()))
.build();
//// out_matchedCSSRules
auto cssSelectorsArr = protocol::Array<protocol::CSS::Value>::create();
auto cssSelectorList = protocol::CSS::SelectorList::create()
.setSelectors(std::move(cssSelectorsArr))
.setText("")
.build();
auto cssRule = protocol::CSS::CSSRule::create()
.setSelectorList(std::move(cssSelectorList))
.setOrigin(protocol::CSS::StyleSheetOriginEnum::Regular)
.setStyle(std::move(protocol::CSS::CSSStyle::create()
.setCssProperties(std::move(protocol::Array<protocol::CSS::CSSProperty>::create()))
.setShorthandEntries(std::move(protocol::Array<protocol::CSS::ShorthandEntry>::create()))
.build()))
.build();
auto rulesMatchedArr = protocol::Array<protocol::CSS::RuleMatch>::create();
//// out_pseudoElements
auto pseudoElementsArr = protocol::Array<protocol::CSS::PseudoElementMatches>::create();
//// out_inherited
auto inheritedElementsArr = protocol::Array<protocol::CSS::InheritedStyleEntry>::create();
auto inheritedelem = protocol::CSS::InheritedStyleEntry::create()
.setInlineStyle(std::move(protocol::CSS::CSSStyle::create()
.setCssProperties(std::move(protocol::Array<protocol::CSS::CSSProperty>::create()))
.setShorthandEntries(std::move(protocol::Array<protocol::CSS::ShorthandEntry>::create()))
.build()))
.setMatchedCSSRules(std::move(protocol::Array<protocol::CSS::RuleMatch>::create()))
.build();
inheritedElementsArr->addItem(std::move(inheritedelem));
//// out_cssKeyframesRules
auto cssKeyFramesRulesArr = protocol::Array<protocol::CSS::CSSKeyframesRule>::create();
*out_inlineStyle = Maybe<protocol::CSS::CSSStyle>(std::move(inlineStyle));
*out_attributesStyle = Maybe<protocol::CSS::CSSStyle>(std::move(attributeStyle));
*out_matchedCSSRules = Maybe<protocol::Array<protocol::CSS::RuleMatch>>(std::move(rulesMatchedArr));
*out_cssKeyframesRules = Maybe<protocol::Array<protocol::CSS::CSSKeyframesRule>>(std::move(cssKeyFramesRulesArr));
*out_inherited = Maybe<protocol::Array<protocol::CSS::InheritedStyleEntry>>(std::move(inheritedElementsArr));
*out_pseudoElements = Maybe<protocol::Array<protocol::CSS::PseudoElementMatches>>(std::move(pseudoElementsArr));
}
// TODO: Pete: implement
void V8CSSAgentImpl::getInlineStylesForNode(ErrorString *, int in_nodeId,
Maybe<protocol::CSS::CSSStyle> *out_inlineStyle,
Maybe<protocol::CSS::CSSStyle> *out_attributesStyle) {
//// out_inlineStyle
auto cssPropsArr = protocol::Array<protocol::CSS::CSSProperty>::create();
auto shorthandPropArr = protocol::Array<protocol::CSS::ShorthandEntry>::create();
auto inlineStyle = protocol::CSS::CSSStyle::create()
.setCssProperties(std::move(cssPropsArr))
.setShorthandEntries(std::move(shorthandPropArr))
.build();
//// out_attributesStyle
auto attrArr = protocol::Array<protocol::CSS::CSSProperty>::create();
auto attributeStyle = protocol::CSS::CSSStyle::create()
.setCssProperties(std::move(attrArr))
.setShorthandEntries(std::move(protocol::Array<protocol::CSS::ShorthandEntry>::create()))
.build();
*out_inlineStyle = Maybe<protocol::CSS::CSSStyle>(std::move(inlineStyle));
*out_attributesStyle = Maybe<protocol::CSS::CSSStyle>(std::move(attributeStyle));
}
void V8CSSAgentImpl::getComputedStyleForNode(ErrorString *, int in_nodeId,
std::unique_ptr<protocol::Array<protocol::CSS::CSSComputedStyleProperty>> *out_computedStyle) {
auto computedStylePropertyArr = protocol::Array<protocol::CSS::CSSComputedStyleProperty>::create();
auto getComputedStylesForNodeString = "__getComputedStylesForNode";
// TODO: Pete: Find a better way to get a hold of the isolate
auto isolate = v8::Isolate::GetCurrent();
auto context = isolate->GetCurrentContext();
auto global = context->Global();
auto getComputedStylesForNode = global->Get(ArgConverter::ConvertToV8String(isolate, getComputedStylesForNodeString));
if (!getComputedStylesForNode.IsEmpty() && getComputedStylesForNode->IsFunction()) {
auto getComputedStylesForNodeFunc = getComputedStylesForNode.As<v8::Function>();
v8::Local<v8::Value> args[] = { v8::Number::New(isolate, in_nodeId) };
auto maybeResult = getComputedStylesForNodeFunc->Call(context, global, 1, args);
v8::Local<v8::Value> outResult;
maybeResult.ToLocal(&outResult);
if (!outResult.IsEmpty()) {
auto resultString = ArgConverter::ConvertToString(outResult->ToString());
auto resultCStr = resultString.c_str();
auto resultJson = protocol::parseJSON(resultCStr);
protocol::ErrorSupport errorSupport;
auto computedStyles = protocol::Array<protocol::CSS::CSSComputedStyleProperty>::parse(resultJson.get(), &errorSupport);
auto errorSupportString = errorSupport.errors().utf8();
if (!errorSupportString.empty()) {
auto errorMessage = "Error while parsing CSSComputedStyleProperty object. ";
DEBUG_WRITE_FORCE("%s Error: %s", errorMessage, errorSupportString.c_str());
} else {
*out_computedStyle = std::move(computedStyles);
return;
}
}
}
*out_computedStyle = std::move(computedStylePropertyArr);
}
void V8CSSAgentImpl::getPlatformFontsForNode(ErrorString *, int in_nodeId,
std::unique_ptr<protocol::Array<protocol::CSS::PlatformFontUsage>> *out_fonts) {
auto fontsArr = protocol::Array<protocol::CSS::PlatformFontUsage>::create();
fontsArr->addItem(std::move(protocol::CSS::PlatformFontUsage::create().setFamilyName("System Font").setGlyphCount(1).setIsCustomFont(false).build()));
*out_fonts = std::move(fontsArr);
}
// TODO: Pete: implement
void V8CSSAgentImpl::getStyleSheetText(ErrorString *, const String &in_styleSheetId,
String *out_text) {
*out_text = "";
}
V8CSSAgentImpl* V8CSSAgentImpl::Instance = 0;
}<|endoftext|> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.