text string | size int64 | token_count int64 |
|---|---|---|
#include <vector>
#include <algorithm>
#include <iostream>
#include "TicTacToePlayer.h"
TicTacToeMove TicTacToePlayer::generateMove(const TicTacToeBoardDescriptor& board, char next_sym, std::vector<int>& generated){
auto last = generated.size() > 0 ? generated.back() : -1;
for (auto i = ++last; i < BOARD_SIZE; ++i){
if (board[i] == '.'){
generated.push_back(i);
return TicTacToeMove(i, next_sym);
}
}
throw 2; // Finished moves
}
TicTacToeMove treeSearch(Tree & t, char symbol, bool is_max=true){
auto max_val = alphabeta(t, is_max);
auto pos = findMoveInTree(t);
std::cout << "Move: " << pos << std::endl;
TicTacToeMove move(pos, symbol);
return move;
}
int alphabeta(Tree& t, bool is_max, int alpha, int beta){
if (!t.hasChildren()) { //if is leave
return t.getValue();
}
std::vector<int> children_values;
for (auto i = 0; i < t.numChildren(); ++i){
auto val = alphabeta(t.getChildren(i), !is_max, alpha, beta);
if (is_max)
alpha = std::max(alpha, val);
else
beta = std::min(beta, val);
if (alpha >= beta) {
t.setValue(val);
return val;
}
children_values.push_back(val);
}
auto thisVal = 0;
if (is_max)
thisVal = *(std::max_element(children_values.begin(), children_values.end()));
else
thisVal = *(std::min_element(children_values.begin(), children_values.end()));
t.setValue(thisVal);
return thisVal;
}
int findMoveInTree(Tree& t) {
auto val = t.getValue();
for (auto i = 0; i < t.numChildren(); ++i) {
if (t.getChildren(i).getValue() == val)
return t.getLabel(i);
}
}
TicTacToeMove TicTacToePlayer::play(const TicTacToeBoard & board) {
Tree playTree(board.getDescriptor());
makeTree(playTree, assigned_simbol == 'x');
bool is_first = board.numOccupied() == 0;
auto move = treeSearch(playTree, assigned_simbol, is_first);
return move;
}
Tree& TicTacToePlayer::makeTree(Tree & t, bool x) {
std::vector<int> generatedMoves;
auto d = t.getDescriptor();
auto b = TicTacToeBoard (d);
auto state = b.getGameState();
switch (state){
case Win1:
t.setValue(10);
return t;
case Win2:
t.setValue(-10);
return t;
case Draw:
t.setValue(0);
return t;
}
while(1){
try {
auto move = generateMove(b.getDescriptor(), x ? 'x' : 'o', generatedMoves);
t.addChildren(new Tree(d.editDescription(move.i, move.s)));
} catch (int e){ // Moves are finished
break;
}
}
t.setLabels(generatedMoves);
for (auto i = 0; i < t.numChildren(); ++i){
makeTree(t.getChildren(i), !x);
}
return t;
} | 2,872 | 1,000 |
/**
* @author ${kekkaishivn} - dattl@ifi.uio.no
*
* ${tags}
*/
#include <grp.h>
#include "MyEnclave_u.h"
struct group *ocall_getgrgid(gid_t gid)
{
return getgrgid(gid);
}
int ocall_initgroups(const char *user, gid_t group)
{
return initgroups(user, group);
}
| 268 | 126 |
#ifndef OPENPOSE_PRODUCER_DATUM_PRODUCER_HPP
#define OPENPOSE_PRODUCER_DATUM_PRODUCER_HPP
#include <atomic>
#include <limits> // std::numeric_limits
#include <tuple>
#include <openpose/core/common.hpp>
#include <openpose/core/datum.hpp>
#include <openpose/utilities/fastMath.hpp>
#include <openpose/producer/producer.hpp>
#include <iostream>
#include <string>
namespace op
{
template<typename TDatum>
class DatumProducer
{
public:
explicit DatumProducer(
const std::shared_ptr<Producer>& producerSharedPtr,
const unsigned long long frameFirst = 0, const unsigned long long frameStep = 1,
const unsigned long long frameLast = std::numeric_limits<unsigned long long>::max(),
const std::shared_ptr<std::pair<std::atomic<bool>, std::atomic<int>>>& videoSeekSharedPtr = nullptr);
virtual ~DatumProducer();
std::pair<bool, std::shared_ptr<std::vector<std::shared_ptr<TDatum>>>> checkIfRunningAndGetDatum();
private:
const unsigned long long mNumberFramesToProcess;
std::shared_ptr<Producer> spProducer;
unsigned long long mGlobalCounter;
unsigned long long mFrameStep;
unsigned int mNumberConsecutiveEmptyFrames;
std::shared_ptr<std::pair<std::atomic<bool>, std::atomic<int>>> spVideoSeek;
void checkIfTooManyConsecutiveEmptyFrames(
unsigned int& numberConsecutiveEmptyFrames, const bool emptyFrame) const;
DELETE_COPY(DatumProducer);
};
}
// Implementation
#include <opencv2/imgproc/imgproc.hpp> // cv::cvtColor
#include <openpose/producer/datumProducer.hpp>
namespace op
{
template<typename TDatum>
DatumProducer<TDatum>::DatumProducer(
const std::shared_ptr<Producer>& producerSharedPtr,
const unsigned long long frameFirst, const unsigned long long frameStep,
const unsigned long long frameLast,
const std::shared_ptr<std::pair<std::atomic<bool>, std::atomic<int>>>& videoSeekSharedPtr) :
mNumberFramesToProcess{(frameLast != std::numeric_limits<unsigned long long>::max()
? frameLast - frameFirst : frameLast)},
spProducer{producerSharedPtr},
mGlobalCounter{0ll},
mFrameStep{frameStep},
mNumberConsecutiveEmptyFrames{0u},
spVideoSeek{videoSeekSharedPtr}
{
try
{
// Sanity check
if (frameLast < frameFirst)
error("The desired initial frame must be lower than the last one (flags `--frame_first` vs."
" `--frame_last`). Current: " + std::to_string(frameFirst) + " vs. " + std::to_string(frameLast)
+ ".", __LINE__, __FUNCTION__, __FILE__);
if (frameLast != std::numeric_limits<unsigned long long>::max()
&& frameLast > spProducer->get(CV_CAP_PROP_FRAME_COUNT)-1)
error("The desired last frame must be lower than the length of the video or the number of images."
" Current: " + std::to_string(frameLast) + " vs. "
+ std::to_string(positiveIntRound(spProducer->get(CV_CAP_PROP_FRAME_COUNT))-1) + ".",
__LINE__, __FUNCTION__, __FILE__);
// Set frame first and step
if (spProducer->getType() != ProducerType::FlirCamera && spProducer->getType() != ProducerType::IPCamera
&& spProducer->getType() != ProducerType::Webcam)
{
// Frame first
spProducer->set(CV_CAP_PROP_POS_FRAMES, (double)frameFirst);
// Frame step
spProducer->set(ProducerProperty::FrameStep, (double)frameStep);
}
}
catch (const std::exception& e)
{
error(e.what(), __LINE__, __FUNCTION__, __FILE__);
}
}
template<typename TDatum>
DatumProducer<TDatum>::~DatumProducer()
{
}
template<typename TDatum>
std::pair<bool, std::shared_ptr<std::vector<std::shared_ptr<TDatum>>>> DatumProducer<TDatum>::checkIfRunningAndGetDatum()
{
try
{
auto datums = std::make_shared<std::vector<std::shared_ptr<TDatum>>>();
// Check last desired frame has not been reached
if (mNumberFramesToProcess != std::numeric_limits<unsigned long long>::max()
&& mGlobalCounter > mNumberFramesToProcess)
{
spProducer->release();
}
// If producer released -> it sends an empty cv::Mat + a datumProducerRunning signal
const bool datumProducerRunning = spProducer->isOpened();
// If device is open
if (datumProducerRunning)
{
// Fast forward/backward - Seek to specific frame index desired
if (spVideoSeek != nullptr)
{
// Fake pause vs. normal mode
const auto increment = spVideoSeek->second - (spVideoSeek->first ? 1 : 0);
// Normal mode
if (increment != 0)
spProducer->set(CV_CAP_PROP_POS_FRAMES, spProducer->get(CV_CAP_PROP_POS_FRAMES) + increment);
// It must be always reset or bug in fake pause
spVideoSeek->second = 0;
}
auto nextFrameName = spProducer->getNextFrameName();
const auto nextFrameNumber = (unsigned long long)spProducer->get(CV_CAP_PROP_POS_FRAMES);
const auto cvMats = spProducer->getFrames();
const auto cameraMatrices = spProducer->getCameraMatrices();
auto cameraExtrinsics = spProducer->getCameraExtrinsics();
auto cameraIntrinsics = spProducer->getCameraIntrinsics();
// Check frames are not empty
checkIfTooManyConsecutiveEmptyFrames(mNumberConsecutiveEmptyFrames, cvMats.empty() || cvMats[0].empty());
if (!cvMats.empty())
{
datums->resize(cvMats.size());
// Datum cannot be assigned before resize()
auto& datumPtr = (*datums)[0];
datumPtr = std::make_shared<TDatum>();
// Filling first element
std::swap(datumPtr->name, nextFrameName);
datumPtr->frameNumber = nextFrameNumber;
datumPtr->cvInputData = cvMats[0];
if (!cameraMatrices.empty())
{
datumPtr->cameraMatrix = cameraMatrices[0];
datumPtr->cameraExtrinsics = cameraExtrinsics[0];
datumPtr->cameraIntrinsics = cameraIntrinsics[0];
}
// Image integrity
if (datumPtr->cvInputData.channels() != 3)
{
const std::string commonMessage{"Input images must be 3-channel BGR."};
// Grey to RGB if required
if (datumPtr->cvInputData.channels() == 1)
{
log(commonMessage + " Converting grey image into BGR.", Priority::High);
cv::cvtColor(datumPtr->cvInputData, datumPtr->cvInputData, CV_GRAY2BGR);
}
else
error(commonMessage, __LINE__, __FUNCTION__, __FILE__);
}
// std::cout << "DatumProducer:: datumPtr->cvOutputData is empty? " << datumPtr->cvOutputData.empty() << "\n";
datumPtr->cvOutputData = datumPtr->cvInputData;
// Resize if it's stereo-system
if (datums->size() > 1)
{
// Stereo-system: Assign all cv::Mat
for (auto i = 1u ; i < datums->size() ; i++)
{
auto& datumIPtr = (*datums)[i];
datumIPtr = std::make_shared<TDatum>();
datumIPtr->name = datumPtr->name;
datumIPtr->frameNumber = datumPtr->frameNumber;
datumIPtr->cvInputData = cvMats[i];
datumIPtr->cvOutputData = datumIPtr->cvInputData;
if (cameraMatrices.size() > i)
{
datumIPtr->cameraMatrix = cameraMatrices[i];
datumIPtr->cameraExtrinsics = cameraExtrinsics[i];
datumIPtr->cameraIntrinsics = cameraIntrinsics[i];
}
}
}
// Check producer is running
if (!datumProducerRunning || (*datums)[0]->cvInputData.empty())
datums = nullptr;
// Increase counter if successful image
if (datums != nullptr)
mGlobalCounter += mFrameStep;
}
}
// Return result
return std::make_pair(datumProducerRunning, datums);
}
catch (const std::exception& e)
{
error(e.what(), __LINE__, __FUNCTION__, __FILE__);
return std::make_pair(false, std::make_shared<std::vector<std::shared_ptr<TDatum>>>());
}
}
template<typename TDatum>
void DatumProducer<TDatum>::checkIfTooManyConsecutiveEmptyFrames(
unsigned int& numberConsecutiveEmptyFrames, const bool emptyFrame) const
{
numberConsecutiveEmptyFrames = (emptyFrame ? numberConsecutiveEmptyFrames+1 : 0);
const auto threshold = 500u;
if (numberConsecutiveEmptyFrames >= threshold)
error("Detected too many (" + std::to_string(numberConsecutiveEmptyFrames) + ") empty frames in a row.",
__LINE__, __FUNCTION__, __FILE__);
}
extern template class DatumProducer<BASE_DATUM>;
}
#endif // OPENPOSE_PRODUCER_DATUM_PRODUCER_HPP
| 10,164 | 2,822 |
#include "manager.h"
namespace Blocks {
Manager manager;
Manager::~Manager() {
// So the 0x1 placeholders are not accidentally deleted.
blocks_[0] = nullptr;
groups_[0] = nullptr;
deleteallslotvector(connections_);
deleteallslotvector(blocks_);
deleteallslotvector(groups_);
}
// TODO: Multiple windows/screens on desktop.
void Manager::Init(ExpandingInteractive& main_canvas_or_scene, const ScreenProperties& props) {
if (!graphics.Init()) {
log::Fatal("Blocks Manager", "Graphics failed to initialize!");
}
main_cs_ = &main_canvas_or_scene;
screen_props_ = props;
screen_props_.hidden = true;
input.RegisterDefaultEventHandler(Event);
input.RegisterInterruptEventHandler(InterruptEvent);
// Create the screen but hidden for now. (So everything can be loaded.)
Screen& screen = graphics.CreateCustomScreen(screen_props_);
main_screen_ = &screen;
render.SetScreenContext(screen);
input.RegisterFrameDrawHandler(screen, Draw);
// Set based on interpreted values in case of fullscreen, mobile, etc.
main_cs_->setDrawableArea(main_screen_->width(), main_screen_->height());
active_.store(true);
}
// Run the event loop, draw frames, and pass events to the component blocks.
int Manager::Exec() {
// Set based on interpreted values in case of fullscreen, mobile, etc.
main_cs_->setDrawableArea(main_screen_->width(), main_screen_->height());
main_screen_->show();
return input.ExecEventHandlerLoop();
}
void Manager::Event(InputModule::Event e) {
manager.EventInternal(e);
}
// Thread Safe
void Manager::InterruptEvent(InputModule::Event e) {
manager.InterruptEventInternal(e);
}
// Thread Safe
void Manager::InterruptEventInternal(InputModule::Event e) {
switch (e.type) {
case InputModule::AppToBackground:
active_.store(false);
if (onbackground_ != nullptr) onbackground_();
break;
case InputModule::AppToForeground:
active_.store(true);
if (onforeground_ != nullptr) onforeground_();
break;
// TODO: LowMemory, Termination events
}
}
// This handles events directly from the input module.
void Manager::EventInternal(InputModule::Event e) {
BlockEvent be;
switch (e.type) {
case InputModule::ScreenResize:
// If resize, then resize the main_canvas
main_cs_->setDrawableArea(e.screen.width, e.screen.height);
break;
// If mouse/touch, pass down.
case InputModule::MouseMove:
be.screen.x = e.mouse.x;
be.screen.y = e.mouse.y;
be.screen.dx = e.mouse.dx;
be.screen.dy = e.mouse.dy;
if (e.mouse.button_state & SDL_BUTTON_LMASK) {
be.type = BlockEvent::PressDrag;
// Drag events start at x/y and travel by dx/dy
be.screen.x -= e.mouse.dx;
be.screen.y -= e.mouse.dy;
} else {
be.type = BlockEvent::Hover;
}
break;
case InputModule::MouseDown:
if (e.mouse.button != SDL_BUTTON_LEFT) {
break;
}
be.type = BlockEvent::PressDown;
be.screen.x = e.mouse.x;
be.screen.y = e.mouse.y;
break;
case InputModule::MouseUp:
if (e.mouse.button != SDL_BUTTON_LEFT) {
break;
}
be.type = BlockEvent::PressUp;
be.screen.x = e.mouse.x;
be.screen.y = e.mouse.y;
break;
// TODO: Right-click/menu button (and 3D touch on iOS too?) //
case InputModule::MouseWheel:
// TODO! //
break;
// TODO: These two may have no coordinates? //
case InputModule::MouseEnter:
be.type = BlockEvent::HoverEnter;
break;
case InputModule::MouseExit:
be.type = BlockEvent::HoverExit;
break;
case InputModule::TouchMove:
be.type = BlockEvent::PressDrag;
be.screen.x = e.touch.x - e.touch.dx;
be.screen.y = e.touch.y - e.touch.dy;
be.screen.dx = e.touch.dx;
be.screen.dy = e.touch.dy;
break;
case InputModule::TouchDown:
be.type = BlockEvent::PressDown;
be.screen.x = e.touch.x;
be.screen.y = e.touch.y;
break;
case InputModule::TouchUp:
be.type = BlockEvent::PressUp;
be.screen.x = e.touch.x;
be.screen.y = e.touch.y;
break;
case InputModule::MultiTouch:
// TODO! //
break;
default:
// Ignore other events.
return;
}
if (be.is_screen()) {
// Send to the Main Canvas (or through the Scene)
main_cs_->event(be);
}
// Process Inter-Block Events Here:
ProcessAllBlockEvents();
}
void Manager::ProcessAllBlockEvents() {
BlockEvent e;
const size_t total_group_count = groups_.size();
while (event_queue_.recvEvent(&e)) { // More events to process
const size_t o_id = e.origin_id;
if (o_id == 0) {
// Manager itself, which is impossible.
log::Error("Blocks Manager", "Event sent to queue with invalid zero id!"); continue;
} else if (o_id >= blocks_.size()) {
// Since events are never sent from a group id.
log::Error("Blocks Manager", "Invalid inter-block event source id: " + string::itoa(o_id)); continue;
}
BlockConn* bc = blocks_[o_id];
if (bc == nullptr) {
log::Error("Blocks Manager", "Event sent to queue from removed/deleted block!"); continue;
}
std::vector<Connection*>* conns_ = &(bc->conn_from); // All connections from this block ID.
size_t group_j = -1;
const size_t group_len = bc->groups.size();
while (true) {
for (size_t i = 0; i < conns_->size(); i++) {
Connection* c = (*conns_)[i];
if (c == nullptr || (c->event != BlockEvent::Any && c->event != e.type)) {
continue; // Check next connection, not a match.
}
// Possible match, check other connection conditions.
if (c->type == Connection::Always) {
// OK!
} else if (c->type == Connection::IfFunc) {
if (c->test_func == nullptr || !(c->test_func(e))) {
continue; // Not active, otherwise OK.
}
} else if (c->type == Connection::IfVar) {
if (c->test_var == nullptr || !(c->test_var)) {
continue; // Not active, otherwise OK.
}
} else {
log::Error("Blocks Manager", "Unsupported connection type!"); continue;
}
// Send Action
size_t d_id = c->destination;
if (d_id == 0) {
// Manager itself
if (c->action == BlockAction::Quit) {
input.Quit(); // Doesn't actually quit immediately, in case of a save dialog, etc.
continue;
} else if (c->action == BlockAction::RunFunc) {
if (c->action_func != nullptr) {
c->action_func(e);
} else {
log::Error("Blocks Manager", "Custom action function missing!");
}
continue;
} else {
log::Error("Blocks Manager",
"Invalid action passed to manager: " + string::itoa(c->action)); continue;
}
} else if (d_id == Connection::ID_SELF) {
// Send the action to the origin block
SendActionToBlock(o_id, c, e);
} else if (d_id >= Connection::ID_GROUP_OFFSET) {
// Group destination
d_id -= Connection::ID_GROUP_OFFSET;
if (d_id >= groups_.size() || d_id == 0) { // Group zero is also reserved.
log::Error("Blocks Manager",
"Invalid inter-block action destination group id: " + string::itoa(d_id)); continue;
}
BlockGroup* group = groups_[d_id];
if (group == nullptr) {
log::Error("Blocks Manager", "Action sent to removed/deleted group!"); return;
}
const size_t g_len = group->blocks.size();
for (size_t g = 0; g < g_len; g++) {
Eventable* block = group->blocks[g];
if (block != nullptr) {
SendActionToBlock(block, c, e);
}
}
} else {
// Send the action to the (single) block
SendActionToBlock(d_id, c, e);
}
}
group_j++;
while (group_j < group_len &&
(bc->groups[group_j] == 0 ||
bc->groups[group_j] >= total_group_count ||
groups_[bc->groups[group_j]] == nullptr)) {
// Skip invalid groups
group_j++;
}
if (group_j < group_len) {
conns_ = &(groups_[bc->groups[group_j]]->conn_from);
} else {
// Done with groups
break;
}
}
}
}
void Manager::SendActionToBlock(const size_t destination_id, Connection* c, const BlockEvent& e) {
if (destination_id >= blocks_.size() || destination_id == 0) {
log::Error("Blocks Manager",
"Invalid inter-block action destination id: " + string::itoa(destination_id)); return;
}
BlockConn* dest_bc = blocks_[destination_id];
if (dest_bc == nullptr || dest_bc->block == nullptr) {
log::Error("Blocks Manager", "Action sent to removed/deleted block!"); return;
}
SendActionToBlock(dest_bc->block, c, e);
}
void Manager::SendActionToBlock(Eventable* block, Connection* c, const BlockEvent& e) {
BlockAction a(c->action);
if (c->default_data.type != BlockAction::Invalid) {
a = c->default_data;
a.type = c->action;
}
if (a.is_movement()) {
if (a.type == BlockAction::SetPos) {
a.position.x = e.screen.x;
a.position.y = e.screen.y;
} else if (a.type == BlockAction::MoveBy) {
a.delta.dx = e.screen.dx;
a.delta.dy = e.screen.dy;
}
} else if (a.is_block()) {
Drawable* d = nullptr;
switch (a.type) {
case BlockAction::BlockEnable:
block->enable();
break;
case BlockAction::BlockDisable:
block->disable();
break;
case BlockAction::BlockToggleEnabled:
block->toggle_enabled();
break;
case BlockAction::BlockShow:
case BlockAction::BlockHide:
case BlockAction::BlockToggleVisible:
case BlockAction::BlockShowEnable:
case BlockAction::BlockHideDisable:
case BlockAction::BlockToggleVisibleEnabled:
d = dynamic_cast<Drawable*>(block);
if (d == nullptr) {
log::Fatal("Blocks Manager", "Attempted to show/hide a non-drawable block!");
}
switch (a.type) {
case BlockAction::BlockShow:
d->show();
break;
case BlockAction::BlockHide:
d->hide();
break;
case BlockAction::BlockToggleVisible:
d->toggle_visible();
break;
case BlockAction::BlockShowEnable:
d->show();
block->enable();
break;
case BlockAction::BlockHideDisable:
d->hide();
block->disable();
break;
case BlockAction::BlockToggleVisibleEnabled:
d->toggle_visible();
block->toggle_enabled();
break;
default:
log::Error("Blocks Manager", "Unknown block-specific action!");
break;
}
break;
default:
log::Error("Blocks Manager", "Unknown block-specific action!");
break;
}
return; // These actions are done directly without passing to the block.
} else if (a.is_generate()) {
if (a.type == BlockAction::GenerateRemoveSender || a.type == BlockAction::GenerateReplaceSender) {
a.sender.id = e.origin_id;
}
}
block->action(a);
}
void Manager::Draw(const double frame_delta_time_msec) {
manager.DrawInternal(frame_delta_time_msec);
}
// This handles the frame_draw from the input module's event loop.
void Manager::DrawInternal(const double frame_delta_time_msec) {
if (!active_.load(std::memory_order_relaxed)) return;
frame_delta_time_msec_ = frame_delta_time_msec;
frame_count_++;
// Process any physics/etc. before drawing.
const size_t len = frame_processors_.size();
for (size_t i = 0; i < len; i++) {
FrameProcessor* fp = frame_processors_[i];
if (fp != nullptr) {
fp->frame(frame_delta_time_msec);
}
}
if (!active_.load(std::memory_order_relaxed)) return;
render.ClearDrawOffset(); // As the main canvas fills the entire screen.
render.Clear(white);
main_cs_->draw();
if (!active_.load(std::memory_order_relaxed)) return;
render.RenderFrameDone();
}
void Manager::AddFrameProcessor(FrameProcessor& proc) {
addtoslotvectorindex(frame_processors_, &proc);
}
void Manager::RemoveFrameProcessor(FrameProcessor& proc) {
// Don't delete as the frame processor object is not owned here, and may be re-used or re-added later on.
deletefromslotvector(frame_processors_, &proc, false);
}
// To allow this block to participate in the event connection system.
// If the block only draws or handles screen events from the canvas, then this is unneccessary.
size_t Manager::RegisterEventable(Eventable& block) {
const size_t id = addtoslotvectorindex(blocks_, new BlockConn(block));
block.registerEventSendQueue(id, event_queue_); // So this block can send events to the manager and other blocks.
return id;
}
void Manager::DeregisterEventable(const size_t block_id) {
if (block_id >= blocks_.size()) {
// TODO: Print error here?
return;
}
BlockConn* bc = blocks_[block_id];
if (bc == nullptr) {
return; // OK if already deleted.
}
Eventable* e = blocks_[block_id]->block;
if (e != nullptr) {
e->deregisterEventSendQueue();
}/* else {
// TODO: Print error here?
}*/
for (size_t i = 0; i < bc->groups.size(); i++) {
RemoveEventableFromGroup(block_id, bc->groups[i]);
}
delete blocks_[block_id];
blocks_[block_id] = nullptr;
}
size_t Manager::RegisterGroup() { // Returns the next available group ID
return addtoslotvectorindex(groups_, new BlockGroup()) + Connection::ID_GROUP_OFFSET;
}
// TODO: Remove the groups each block in this group is a part of from their BlockConn(s)
// OR: Make sure all blocks are removed from this group first, before it can be deleted?
void Manager::DeregisterGroup(size_t group_id) {
if (group_id >= Connection::ID_GROUP_OFFSET) {
group_id -= Connection::ID_GROUP_OFFSET;
}
if (group_id >= groups_.size() || group_id == 0) {
// TODO: Print error here?
return;
}
BlockGroup* group = groups_[group_id];
if (group == nullptr) {
return; // OK if already deleted.
}
delete groups_[group_id];
groups_[group_id] = nullptr;
}
size_t Manager::RegisterEventableInGroup(Eventable& block, const size_t group_id) { // Returns the index/id of the block added.
const size_t id = RegisterEventable(block);
AddEventableToGroup(id, group_id);
return id;
}
void Manager::AddEventableToGroup(const size_t block_id, size_t group_id) {
if (group_id >= Connection::ID_GROUP_OFFSET) {
group_id -= Connection::ID_GROUP_OFFSET;
}
if (group_id >= groups_.size() || group_id == 0 || block_id >= blocks_.size()) {
// TODO: Print error here?
return;
}
BlockGroup* group = groups_[group_id];
BlockConn* bc = blocks_[block_id];
if (group == nullptr || bc == nullptr) {
// TODO: Print error here?
return;
}
addtoslotvectorindex(group->blocks, bc->block);
addtozerovector(bc->groups, group_id);
}
void Manager::RemoveEventableFromGroup(const size_t block_id, size_t group_id) {
if (group_id >= Connection::ID_GROUP_OFFSET) {
group_id -= Connection::ID_GROUP_OFFSET;
}
if (group_id >= groups_.size() || group_id == 0 || block_id >= blocks_.size()) {
// TODO: Print error here?
return;
}
BlockGroup* group = groups_[group_id];
BlockConn* bc = blocks_[block_id];
if (group == nullptr || bc == nullptr) {
// TODO: Print error here?
return;
}
Eventable* e = bc->block;
if (e == nullptr) {
// TODO: Print error here?
return;
}
deletefromslotvector(group->blocks, e, false); // Don't actually delete as the Eventable is not owned.
removefromzerovector(bc->groups, group_id);
}
size_t Manager::AddEventActionConnection(const Connection& conn) {
const size_t o = conn.origin;
const size_t d = conn.destination;
const size_t bc_len = blocks_.size();
// Destination can be the manager (0), and both can be a group.
if (o == 0 ||
(o >= bc_len && !(o >= Connection::ID_GROUP_OFFSET && (o - Connection::ID_GROUP_OFFSET) < groups_.size())) ||
(d >= bc_len && !(d >= Connection::ID_GROUP_OFFSET && (d - Connection::ID_GROUP_OFFSET) < groups_.size())
&& d != Connection::ID_SELF)) {
log::Error("Invalid connection added to manager (invalid origin/destination)!");
return -1; // TODO: Should connection zero be returned/reserved instead?
}
if (conn.type == Connection::IfFunc && conn.test_func == nullptr) {
log::Error("Blocks Manager", "Invalid IfFunc connection - no test function!"); return -1;
}
if (conn.type == Connection::IfVar && conn.test_var == nullptr) {
log::Error("Blocks Manager", "Invalid IfFunc connection - no test function!"); return -1;
}
Connection* c = new Connection(conn);
const size_t conn_id = addtoslotvectorindex(connections_, c); // Copy data.
if (o >= Connection::ID_GROUP_OFFSET) { // Is a group-based connection.
groups_[o - Connection::ID_GROUP_OFFSET]->conn_from.push_back(c);
} else {
blocks_[o]->conn_from.push_back(c);
}
return conn_id;
}
} // namespace Blocks
| 16,637 | 6,304 |
#include "nativeparticipantimpl.h"
#include "nativesubscriberimpl.h"
#include <iostream>
#include <chrono>
#include <thread>
using namespace us::ihmc::rtps::impl::fastRTPS;
class ExampleParticipantListener : public NativeParticipantListener
{
void onParticipantDiscovery(int64_t infoPtr, int64_t guidHigh, int64_t guidLow, DISCOVERY_STATUS status)
{
std::cout << "Discovered participant " << getName(infoPtr) << std::endl;
}
};
class ExampleSubscriberListener : public NativeSubscriberListener
{
virtual void onSubscriptionMatched(MatchingStatus status, int64_t guidHigh, int64_t guidLow)
{
std::cout << "Found publisher" << std::endl;
}
virtual void onNewDataMessage()
{
std::cout << "Got callback" << std::endl;
}
};
int main()
{
RTPSParticipantAttributes rtps;
rtps.setName("Participant");
rtps.builtin.domainId = 1;
ExampleParticipantListener participantListener;
NativeParticipantImpl participant(rtps, &participantListener);
participant.registerType("chat::ChatMessage", 64000, false);
SubscriberAttributes attr;
attr.topic.topicName = "ChatBox1";
attr.topic.topicDataType = "chat::ChatMessage";
attr.qos.m_reliability.kind = BEST_EFFORT_RELIABILITY_QOS;
attr.qos.m_partition.push_back("us/ihmc");
ExampleSubscriberListener subscriberListener;
NativeSubscriberImpl subscriber(-1, -1, 528, PREALLOCATED_MEMORY_MODE,
&attr.topic, &attr.qos, &attr.times, &attr.unicastLocatorList, &attr.multicastLocatorList, &attr.outLocatorList,
false, &participant, &subscriberListener);
subscriber.createSubscriber();
std::vector<unsigned char> data(64000);
SampleInfoMarshaller marshaller;
while(true)
{
subscriber.waitForUnreadMessage();
if(subscriber.takeNextData(64000, data.data(), &marshaller, NO_KEY, SHARED_OWNERSHIP_QOS))
{
std::cout << "Got message of length " << marshaller.dataLength << std::endl;
}
}
}
| 2,076 | 713 |
#include "common.h"
#include "Window.h"
#include "TaskSystem.h"
#include "Timer.h"
#include "Graphics.h"
#include "Renderer.h"
#include "State.h"
#include "DefaultLoadState.h"
#include "StateManager.h"
#include "GuiSystem.h"
using namespace jsh;
using namespace jsh::_internal;
namespace jshEngine {
void BeginUpdate(float dt);
void EndUpdate(float dt);
uint32 g_FPS = 0u;
Time g_DeltaTime = 0.f;
uint32 g_FixedUpdateFrameRate;
float g_FixedUpdateDeltaTime;
StateManager g_State;
GuiSystem g_GuiSystem;
enum JSH_ENGINE_STATE : uint8 {
JSH_ENGINE_STATE_NONE,
JSH_ENGINE_STATE_INITIALIZING,
JSH_ENGINE_STATE_INITIALIZED,
JSH_ENGINE_STATE_RUNNING,
JSH_ENGINE_STATE_CLOSING,
JSH_ENGINE_STATE_CLOSED
};
JSH_ENGINE_STATE g_EngineState = JSH_ENGINE_STATE_NONE;
bool Initialize(jsh::State* state, jsh::State* loadState)
{
jshTimer::Initialize();
jshDebug::_internal::Initialize();
if (g_EngineState != JSH_ENGINE_STATE_NONE) {
jshDebug::LogW("jshEngine is already initialized");
return false;
}
g_EngineState = JSH_ENGINE_STATE_INITIALIZING;
try {
if (!jshTask::Initialize()) {
jshDebug::LogE("Can't initialize jshTaskSystem");
return false;
}
SetFixedUpdateFrameRate(60u);
if (!jshWindow::Initialize()) {
jshDebug::LogE("Can't initialize jshWindow");
return false;
}
if (!jshRenderer::_internal::Initialize()) {
jshDebug::LogE("Can't initialize jshRenderer");
return false;
}
//im gui initialize
jshImGui(if (!jshGraphics::_internal::InitializeImGui()) {
jshDebug::LogE("Cant't initialize ImGui");
return false;
});
jshScene::Initialize();
g_GuiSystem.Initialize();
LoadState(state, loadState);
jshDebug::LogI("jshEngine initialized");
jshDebug::LogSeparator();
g_EngineState = JSH_ENGINE_STATE_INITIALIZED;
}
catch (std::exception e) {
jshFatalError("STD Exception: '%s'", e.what());
return false;
}
catch (...) {
jshFatalError("Unknown error");
return false;
}
return true;
}
void Run()
{
if (g_EngineState != JSH_ENGINE_STATE_INITIALIZED) {
jshFatalError("You must initialize jshEngine");
}
g_EngineState = JSH_ENGINE_STATE_RUNNING;
try {
Time lastTime = jshTimer::Now();
g_DeltaTime = lastTime;
Time actualTime = 0.f;
const float SHOW_FPS_RATE = 1.0f;
float dtCount = 0.f;
float fpsCount = 0u;
float fixedUpdateCount = 0.f;
while (jshWindow::UpdateInput()) {
actualTime = jshTimer::Now();
g_DeltaTime = actualTime - lastTime;
lastTime = actualTime;
fixedUpdateCount += g_DeltaTime;
if (g_DeltaTime > 0.2f) g_DeltaTime = 0.2f;
g_State.Prepare();
// update
BeginUpdate(g_DeltaTime);
g_State.Update(g_DeltaTime);
if (fixedUpdateCount >= 0.01666666f) {
fixedUpdateCount -= 0.01666666f;
g_State.FixedUpdate();
}
EndUpdate(g_DeltaTime);
// render
jshRenderer::_internal::Begin();
g_State.Render();
jshRenderer::_internal::Render();
jshRenderer::_internal::End();
// FPS count
dtCount += g_DeltaTime;
fpsCount++;
if (dtCount >= SHOW_FPS_RATE) {
g_FPS = uint32(fpsCount / SHOW_FPS_RATE);
//jshDebug::Log("%u", g_FPS);
fpsCount = 0.f;
dtCount -= SHOW_FPS_RATE;
}
}
}
catch (std::exception e) {
jshFatalError("STD Exception: '%s'", e.what());
}
catch (...) {
jshFatalError("Unknown error");
}
}
bool Close()
{
jshDebug::LogSeparator();
if (g_EngineState == JSH_ENGINE_STATE_CLOSING || g_EngineState == JSH_ENGINE_STATE_CLOSED) {
jshDebug::LogW("jshEngine is already closed");
}
g_EngineState = JSH_ENGINE_STATE_CLOSING;
try {
g_State.ClearState();
jshScene::Close();
if (!jshTask::Close()) return false;
if (!jshWindow::Close()) return false;
if (!jshRenderer::_internal::Close()) return false;
jshDebug::LogI("jshEngine closed");
jshDebug::_internal::Close();
g_EngineState = JSH_ENGINE_STATE_CLOSED;
}
catch (std::exception e) {
jshFatalError("STD Exception: '%s'", e.what());
return false;
}
catch (...) {
jshFatalError("Unknown error");
return false;
}
return true;
}
void Exit(int code)
{
if (g_EngineState != JSH_ENGINE_STATE_CLOSED) {
if (!Close()) jshDebug::LogE("Can't close jshEngine properly");
}
exit(code);
}
///////////////////////////////////////UPDATE/////////////////////////////////////
void BeginUpdate(float dt)
{
if (jshInput::IsKey(JSH_KEY_CONTROL) && jshInput::IsKeyPressed(JSH_KEY_F11)) jshEngine::Exit(0);
// Update Camera matrices
{
auto& cameras = jshScene::_internal::GetComponentsList()[CameraComponent::ID];
for (uint32 i = 0; i < cameras.size(); i += uint32(CameraComponent::SIZE)) {
CameraComponent* camera = reinterpret_cast<CameraComponent*>(&cameras[i]);
camera->UpdateMatrices();
}
}
// Update Gui
g_GuiSystem.Update(dt);
}
void EndUpdate(float dt)
{
}
////////////////////////////////////////STATE MANAGEMENT////////////////////////////
void LoadState(jsh::State* state, jsh::State* loadState)
{
g_State.LoadState(state, loadState);
}
State* GetCurrentState()
{
return g_State.GetCurrentState();
}
uint32 GetFPS()
{
return g_FPS;
}
float GetDeltaTime()
{
return g_DeltaTime;
}
bool IsInitialized()
{
return g_EngineState != JSH_ENGINE_STATE_NONE && g_EngineState != JSH_ENGINE_STATE_INITIALIZING;
}
// FIXED UPDATE METHODS
void SetFixedUpdateFrameRate(uint32 frameRate)
{
g_FixedUpdateFrameRate = frameRate;
g_FixedUpdateDeltaTime = 1.f / (float)frameRate;
}
float GetFixedUpdateDeltaTime()
{
return g_FixedUpdateDeltaTime;
}
// VERSION
constexpr uint64 g_MajorVersion = 0u;
constexpr uint64 g_MinorVersion = 1u;
constexpr uint64 g_RevisionVersion = 2u;
uint64 GetMajorVersion()
{
return g_MajorVersion;
}
uint64 GetMinorVersion()
{
return g_MinorVersion;
}
uint64 GetRevisionVersion()
{
return g_RevisionVersion;
}
uint64 GetVersion()
{
return g_MajorVersion * 1000000u + g_MinorVersion * 1000u + g_RevisionVersion;
}
const char* GetVersionStr()
{
const static std::string str = std::string(std::to_string(g_MajorVersion) + '.' + std::to_string(g_MinorVersion) + '.' + std::to_string(g_RevisionVersion));
return str.c_str();
}
const wchar* GetVersionStrW()
{
const static std::wstring str = std::wstring(std::to_wstring(g_MajorVersion) + L'.' + std::to_wstring(g_MinorVersion) + L'.' + std::to_wstring(g_RevisionVersion));
return str.c_str();
}
// PROPERTIES
const char* GetName()
{
const static std::string str = std::string("jshEngine " + std::string(GetVersionStr()));
return str.c_str();
}
const wchar* GetNameW()
{
const static std::wstring str = std::wstring(L"jshEngine " + std::wstring(GetVersionStrW()));
return str.c_str();
}
} | 6,860 | 2,989 |
/**
* @file
* @copyright This code is licensed under the 3-clause BSD license.\n
* Copyright ETH Zurich, Laboratory for Physical Chemistry, Reiher Group.\n
* See LICENSE.txt for details.
*/
#include "LevenbergMarquardt.h"
#include <Eigen/Dense>
#include <unsupported/Eigen/NonLinearOptimization>
namespace Scine {
namespace Utils {
void LevenbergMarquardt::optimize(Eigen::VectorXd& parameters, UpdateFunctionManagerBase& updateFunctionManager) {
LMFunctor functor(updateFunctionManager);
functor.n = static_cast<int>(parameters.size());
functor.m = functor.updateFunctionManager_.getNumberOfDataPoints(parameters);
Eigen::LevenbergMarquardt<LMFunctor, double> lm(functor);
// Set maximum number of function evaluations if it was set to a sensible value
if (maxFuncEval > 0)
lm.parameters.maxfev = maxFuncEval;
lm.minimize(parameters);
// Calculate and update covariance matrix if desired
if (calculateCovarianceMatrix) {
auto hessian = lm.fjac.transpose() * lm.fjac;
auto inverseHessian = hessian.inverse();
auto variance = (1.0 / (functor.m - functor.n + 1.0)) * lm.fvec.squaredNorm();
covarianceMatrix_ = variance * inverseHessian;
}
}
LevenbergMarquardt::LMFunctor::LMFunctor(UpdateFunctionManagerBase& updateFunctionManager)
: updateFunctionManager_(updateFunctionManager) {
}
// Compute 'm' errors, one for each data point, for the given parameter values in 'x'
int LevenbergMarquardt::LMFunctor::operator()(const Eigen::VectorXd& parameters, Eigen::VectorXd& fvec) const {
updateFunctionManager_.updateErrors(parameters, fvec);
return 0;
}
// Compute the Jacobian of the errors
int LevenbergMarquardt::LMFunctor::df(const Eigen::VectorXd& parameters, Eigen::MatrixXd& fjac) const {
updateFunctionManager_.updateJacobian(parameters, fjac);
return 0;
}
// Returns 'm', the number of values.
int LevenbergMarquardt::LMFunctor::values() const {
return m;
}
// Returns 'n', the number of inputs.
int LevenbergMarquardt::LMFunctor::inputs() const {
return n;
}
const Eigen::MatrixXd& LevenbergMarquardt::getCovarianceMatrix() {
return covarianceMatrix_;
}
} // namespace Utils
} // namespace Scine | 2,191 | 736 |
#include<bits/stdc++.h>
using namespace std;
using vi = vector<int>; using vvi = vector<vi>;
using ii = pair<int,int>; using vii = vector<ii>;
using l = long long; using vl = vector<l>; using vvl = vector<vl>;
using ll = pair<l,l>; using vll = vector<ll>; using vvll = vector<vll>;
using lu = unsigned long long;
using vb = vector<bool>; using vvb = vector<vb>;
using vd = vector<double>; using vvd = vector<vd>;
const int INF = numeric_limits<int>::max();
const double EPS = 1e-10;
const l e5 = 100000, e6 = 1000000, e7 = 10000000, e9 = 1000000000;
vvl masks(10);
const l MAX = 30;
bool solve(vl& chars, vl& solution, int number) {
if (number == 10) {
for (auto c : chars) if (c) return false;
return true;
}
l min_count = INF;
for (l i = 0; i < MAX; i++) {
if (masks[number][i]) min_count = min(min_count, chars[i] / masks[number][i]);
}
// cerr << number << " min " << min_count << endl;
for (l i = min_count; i >= 0; i--) {
for (l j = 0; j < MAX; j++) {
chars[j] -= i * masks[number][j];
}
solution[number] = i;
if (solve(chars, solution, number+1)) return true;
for (l j = 0; j < MAX; j++) {
chars[j] += i * masks[number][j];
}
}
return false;
}
vl get_mask(string s) {
vl result(MAX);
for (auto c : s) result[c - 'A']++;
return result;
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(0);
l tcc;
cin >> tcc;
struct {
string value;
char mark;
int digit;
} traits[] = {
{"ZERO", 'Z', 0},
{"TWO", 'W', 2},
{"FOUR", 'U', 4},
{"SIX", 'X', 6},
{"FIVE", 'F', 5},
{"SEVEN", 'V', 7},
{"EIGHT", 'G', 8},
{"NINE", 'I', 9},
{"THREE", 'R', 3},
{"ONE", 'N', 1},
};
for (l tc = 0; tc < tcc; tc++) {
cout << "Case #" << (tc + 1) << ": ";
string s; cin >> s;
auto ms = get_mask(s);
vl counts(10);
for (auto t : traits) {
l c = ms[t.mark - 'A'];
auto m = get_mask(t.value);
for (l j = 0; j < MAX; j++) {
ms[j] -= m[j] * c;
}
counts[t.digit] = c;
}
for (l i = 0; i < 10; i++) {
for (l j = 0; j < counts[i]; j++) {
cout << i;
}
}
cout << endl;
}
}
| 2,182 | 955 |
/*
* Copyright 2004-2017 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include "clangUtil.h"
#include <inttypes.h>
#include <cctype>
#include <cstring>
#include <cstdio>
#include <sstream>
#include "astutil.h"
#include "driver.h"
#include "expr.h"
#include "files.h"
#include "mysystem.h"
#include "passes.h"
#include "stmt.h"
#include "stringutil.h"
#include "symbol.h"
#include "type.h"
#include "codegen.h"
#include "clangSupport.h"
#include "build.h"
#include "llvmDebug.h"
typedef Type ChapelType;
#ifndef HAVE_LLVM
void readExternC(void) {
// Do nothing if we don't have LLVM support.
}
void cleanupExternC(void) {
// Do nothing if we don't have LLVM support.
}
#else
using namespace clang;
using namespace llvm;
#define GLOBAL_PTR_SPACE 100
#define WIDE_PTR_SPACE 101
#define GLOBAL_PTR_SIZE 64
#define GLOBAL_PTR_ABI_ALIGN 64
#define GLOBAL_PTR_PREF_ALIGN 64
#include "llvmGlobalToWide.h"
#include "llvmAggregateGlobalOps.h"
// TODO - add functionality to clang so that we don't
// have to have what are basically copies of
// ModuleBuilder.cpp
// ( and BackendUtil.cpp but we used PassManagerBuilder::addGlobalExtension)
//
// This one is not normally included by clang clients
// and not normally installed in the include directory.
//
// Q. Could we instead call methods on clang::CodeGenerator subclass of
// ASTConsumer such as HandleTopLevelDecl to achieve what we want?
// We would have a different AST visitor for populating the LVT.
//
// It is likely that we can leave the C parser "open" somehow and then
// add statements to it at the end.
// BUT we couldn't call EmitDeferredDecl.
//
//
#include "CodeGenModule.h"
#include "CGRecordLayout.h"
#include "CGDebugInfo.h"
#include "clang/CodeGen/BackendUtil.h"
static void setupForGlobalToWide();
fileinfo gAllExternCode;
fileinfo gChplCompilationConfig;
static
VarSymbol *minMaxConstant(int nbits, bool isSigned, bool isMin)
{
if( nbits == 8 && isSigned && isMin )
return new_IntSymbol(INT8_MIN, INT_SIZE_8);
else if( nbits == 8 && isSigned && !isMin )
return new_IntSymbol(INT8_MAX, INT_SIZE_8);
else if( nbits == 8 && !isSigned && isMin )
return new_IntSymbol(0, INT_SIZE_8);
else if( nbits == 8 && !isSigned && !isMin )
return new_IntSymbol(UINT8_MAX, INT_SIZE_8);
else if( nbits == 16 && isSigned && isMin )
return new_IntSymbol(INT16_MIN, INT_SIZE_16);
else if( nbits == 16 && isSigned && !isMin )
return new_IntSymbol(INT16_MAX, INT_SIZE_16);
else if( nbits == 16 && !isSigned && isMin )
return new_IntSymbol(0, INT_SIZE_16);
else if( nbits == 16 && !isSigned && !isMin )
return new_IntSymbol(UINT16_MAX, INT_SIZE_16);
else if( nbits == 32 && isSigned && isMin )
return new_IntSymbol(INT32_MIN, INT_SIZE_32);
else if( nbits == 32 && isSigned && !isMin )
return new_IntSymbol(INT32_MAX, INT_SIZE_32);
else if( nbits == 32 && !isSigned && isMin )
return new_IntSymbol(0, INT_SIZE_32);
else if( nbits == 32 && !isSigned && !isMin )
return new_IntSymbol(UINT32_MAX, INT_SIZE_32);
else if( nbits == 64 && isSigned && isMin )
return new_IntSymbol(INT64_MIN, INT_SIZE_64);
else if( nbits == 64 && isSigned && !isMin )
return new_IntSymbol(INT64_MAX, INT_SIZE_64);
else if( nbits == 64 && !isSigned && isMin )
return new_IntSymbol(0, INT_SIZE_64);
else if( nbits == 64 && !isSigned && !isMin )
return new_IntSymbol(UINT64_MAX, INT_SIZE_64);
else INT_ASSERT(0 && "Bad options for minMaxConstant");
return NULL;
}
static
void addMinMax(const char* prefix, int nbits, bool isSigned)
{
GenInfo* info = gGenInfo;
LayeredValueTable *lvt = info->lvt;
astlocT prevloc = currentAstLoc;
currentAstLoc.lineno = 0;
currentAstLoc.filename = astr("<internal>");
const char* min_name = astr(prefix, "_MIN");
const char* max_name = astr(prefix, "_MAX");
if( isSigned ) {
// only signed versions have a meaningful min.
lvt->addGlobalVarSymbol(min_name, minMaxConstant(nbits, isSigned, true));
}
// but signed and unsigned both have a max
lvt->addGlobalVarSymbol(max_name, minMaxConstant(nbits, isSigned, false));
currentAstLoc = prevloc;
}
static
void addMinMax(ASTContext* Ctx, const char* prefix, clang::CanQualType qt)
{
const clang::Type* ct = qt.getTypePtr();
int nbits = Ctx->getTypeSize(ct);
bool isSigned = ct->isSignedIntegerType();
addMinMax(prefix, nbits, isSigned);
}
static
void setupClangContext(GenInfo* info, ASTContext* Ctx)
{
std::string layout;
info->Ctx = Ctx;
if( ! info->parseOnly ) {
info->module->setTargetTriple(
info->Ctx->getTargetInfo().getTriple().getTriple());
// Also setup some basic TBAA metadata nodes.
llvm::LLVMContext& cx = info->module->getContext();
// Create the TBAA root node
{
LLVM_METADATA_OPERAND_TYPE* Ops[1];
Ops[0] = llvm::MDString::get(cx, "Chapel types");
info->tbaaRootNode = llvm::MDNode::get(cx, Ops);
}
// Create type for ftable
{
LLVM_METADATA_OPERAND_TYPE* Ops[3];
Ops[0] = llvm::MDString::get(cx, "Chapel ftable");
Ops[1] = info->tbaaRootNode;
// and mark it as constant
Ops[2] = llvm_constant_as_metadata(
ConstantInt::get(llvm::Type::getInt64Ty(cx), 1));
info->tbaaFtableNode = llvm::MDNode::get(cx, Ops);
}
{
LLVM_METADATA_OPERAND_TYPE* Ops[3];
Ops[0] = llvm::MDString::get(cx, "Chapel vmtable");
Ops[1] = info->tbaaRootNode;
// and mark it as constant
Ops[2] = llvm_constant_as_metadata(
ConstantInt::get(llvm::Type::getInt64Ty(cx), 1));
info->tbaaVmtableNode = llvm::MDNode::get(cx, Ops);
}
}
info->targetLayout = info->Ctx->getTargetInfo().getTargetDescription();
layout = info->targetLayout;
if( fLLVMWideOpt && ! info->parseOnly ) {
char buf[200]; //needs to store up to 8 32-bit numbers in decimal
assert(GLOBAL_PTR_SIZE == GLOBAL_PTR_BITS);
// Add global pointer info to layout.
snprintf(buf, sizeof(buf), "-p%u:%u:%u:%u-p%u:%u:%u:%u", GLOBAL_PTR_SPACE, GLOBAL_PTR_SIZE, GLOBAL_PTR_ABI_ALIGN, GLOBAL_PTR_PREF_ALIGN, WIDE_PTR_SPACE, GLOBAL_PTR_SIZE, GLOBAL_PTR_ABI_ALIGN, GLOBAL_PTR_PREF_ALIGN);
layout += buf;
// Save the global address space we are using in info.
info->globalToWideInfo.globalSpace = GLOBAL_PTR_SPACE;
info->globalToWideInfo.wideSpace = WIDE_PTR_SPACE;
}
// Always set the module layout. This works around an apparent bug in
// clang or LLVM (trivial/deitz/test_array_low.chpl would print out the
// wrong answer because some i64s were stored at the wrong alignment).
if( info->module ) info->module->setDataLayout(layout);
info->targetData =
new LLVM_TARGET_DATA(info->Ctx->getTargetInfo().getTargetDescription());
if( ! info->parseOnly ) {
info->cgBuilder = new CodeGen::CodeGenModule(*Ctx,
#if HAVE_LLVM_VER >= 37
info->Clang->getHeaderSearchOpts(),
info->Clang->getPreprocessorOpts(),
#endif
info->codegenOptions,
*info->module,
*info->targetData, *info->Diags);
}
// Set up some constants that depend on the Clang context.
{
addMinMax(Ctx, "CHAR", Ctx->CharTy);
addMinMax(Ctx, "SCHAR", Ctx->SignedCharTy);
addMinMax(Ctx, "UCHAR", Ctx->UnsignedCharTy);
addMinMax(Ctx, "SHRT", Ctx->ShortTy);
addMinMax(Ctx, "USHRT", Ctx->UnsignedShortTy);
addMinMax(Ctx, "INT", Ctx->IntTy);
addMinMax(Ctx, "UINT", Ctx->UnsignedIntTy);
addMinMax(Ctx, "LONG", Ctx->LongTy);
addMinMax(Ctx, "ULONG", Ctx->UnsignedLongTy);
addMinMax(Ctx, "LLONG", Ctx->LongLongTy);
addMinMax(Ctx, "ULLONG", Ctx->UnsignedLongLongTy);
}
}
// Adds a mapping from id->getName() to a variable or CDecl to info->lvt
static
void handleMacro(const IdentifierInfo* id, const MacroInfo* macro)
{
GenInfo* info = gGenInfo;
Preprocessor &preproc = info->Clang->getPreprocessor();
VarSymbol* varRet = NULL;
TypeDecl* cTypeRet = NULL;
ValueDecl* cValueRet = NULL;
const bool debugPrint = false;
if( debugPrint) printf("Adding macro %s\n", id->getName().str().c_str());
//Handling only simple string or integer defines
if(macro->getNumArgs() > 0) {
if( debugPrint) {
printf("the macro takes arguments\n");
}
return; // TODO -- handle macro functions.
}
// Check that we have a single token surrounded by any
// number of parens. ie 1, (1), ((1))
Token tok; // the main token.
size_t left_parens = 0;
size_t right_parens = 0;
ssize_t ntokens = macro->getNumTokens();
ssize_t t_idx;
bool negate = false;
if( ntokens > 0 ) {
MacroInfo::tokens_iterator ti = macro->tokens_end() - 1;
for( t_idx = ntokens - 1; t_idx >= 0; t_idx-- ) {
tok = *ti;
if(tok.getKind() == tok::r_paren) right_parens++;
else break;
--ti;
}
}
{
MacroInfo::tokens_iterator ti = macro->tokens_begin();
for( t_idx = 0; t_idx < ntokens; t_idx++ ) {
tok = *ti;
if(tok.getKind() == tok::l_paren) left_parens++;
else if(tok.getKind() == tok::minus) {
negate = true;
ntokens--;
} else break;
++ti;
}
}
if( left_parens == right_parens &&
ntokens - left_parens - right_parens == 1 ) {
// OK!
} else {
if( debugPrint) {
printf("the following macro is too complicated or empty:\n");
}
return; // we don't handle complicated expressions like A+B
}
switch(tok.getKind()) {
case tok::numeric_constant: {
std::string numString;
int hex;
int isfloat;
if( negate ) numString.append("-");
if (tok.getLiteralData() && tok.getLength()) {
numString.append(tok.getLiteralData(), tok.getLength());
}
if( debugPrint) printf("num = %s\n", numString.c_str());
hex = 0;
if( numString[0] == '0' && (numString[1] == 'x' || numString[1] == 'X'))
{
hex = 1;
}
isfloat = 0;
if(numString.find('.') != std::string::npos) {
isfloat = 1;
}
// also check for exponent since e.g. 1e10 is a float.
if( hex ) {
// C99 hex floats use p for exponent
if(numString.find('p') != std::string::npos ||
numString.find('P') != std::string::npos) {
isfloat = 1;
}
} else {
if(numString.find('e') != std::string::npos ||
numString.find('E') != std::string::npos) {
isfloat = 1;
}
}
if( !isfloat ) {
IF1_int_type size = INT_SIZE_32;
if(tolower(numString[numString.length() - 1]) == 'l') {
numString[numString.length() - 1] = '\0';
size = INT_SIZE_64;
}
if(tolower(numString[numString.length() - 1]) == 'u') {
numString[numString.length() - 1] = '\0';
varRet = new_UIntSymbol(strtoul(numString.c_str(), NULL, 0), size);
}
else {
varRet = new_IntSymbol(strtol(numString.c_str(), NULL, 0), size);
}
}
else {
IF1_float_type size = FLOAT_SIZE_64;
if(tolower(numString[numString.length() - 1]) == 'l') {
numString[numString.length() - 1] = '\0';
}
varRet = new_RealSymbol(numString.c_str(), size);
}
break;
}
case tok::string_literal: {
std::string body = std::string(tok.getLiteralData(), tok.getLength());
if( debugPrint) printf("str = %s\n", body.c_str());
varRet = new_CStringSymbol(body.c_str());
break;
}
case tok::identifier: {
IdentifierInfo* tokId = tok.getIdentifierInfo();
std::string idName = tokId->getName();
if( debugPrint) {
printf("id = %s\n", idName.c_str());
}
// Handle the case where the macro refers to something we've
// already parsed in C
varRet = info->lvt->getVarSymbol(idName);
if( !varRet ) {
info->lvt->getCDecl(idName, &cTypeRet, &cValueRet);
}
if( !varRet && !cTypeRet && !cValueRet ) {
// Check to see if it's another macro.
MacroInfo* otherMacro = preproc.getMacroInfo(tokId);
if( otherMacro && otherMacro != macro ) {
// Handle the other macro to add it to the LVT under the new name
// The recursive call will add it to the LVT
if( debugPrint) printf("other macro\n");
handleMacro(tokId, otherMacro);
// Get whatever was added in the recursive call
// so that we can add it under the new name.
varRet = info->lvt->getVarSymbol(idName);
info->lvt->getCDecl(idName, &cTypeRet, &cValueRet);
}
}
if( debugPrint ) {
if( varRet ) printf("found var %s\n", varRet->cname);
if( cTypeRet ) {
std::string s = cTypeRet->getName();
printf("found cdecl type %s\n", s.c_str());
}
if( cValueRet ) {
std::string s = cValueRet->getName();
printf("found cdecl value %s\n", s.c_str());
}
}
break;
}
default:
break;
}
if( debugPrint ) {
std::string s = id->getName();
const char* kind = NULL;
if( varRet ) kind = "var";
if( cTypeRet ) kind = "cdecl type";
if( cValueRet ) kind = "cdecl value";
if( kind ) printf("%s: adding an %s to the lvt\n", s.c_str(), kind);
}
if( varRet ) {
info->lvt->addGlobalVarSymbol(id->getName(), varRet);
}
if( cTypeRet ) {
info->lvt->addGlobalCDecl(id->getName(), cTypeRet);
}
if( cValueRet ) {
info->lvt->addGlobalCDecl(id->getName(), cValueRet);
}
}
static
void readMacrosClang(void) {
GenInfo* info = gGenInfo;
LayeredValueTable *lvt = info->lvt;
SET_LINENO(rootModule);
// Pre-populate with important INTxx_MIN/MAX from stdint.h
// because we have trouble reading these because they have
// special stuff to get the right constant width, but they
// are all known integer values.
lvt->addGlobalVarSymbol("NULL", new_IntSymbol(0, INT_SIZE_64));
// Add INT{8,16,32,64}_{MIN,MAX} and INT_MAX and friends.
addMinMax("INT8", 8, true);
addMinMax("UINT8", 8, false);
addMinMax("INT16", 16, true);
addMinMax("UINT16", 16, false);
addMinMax("INT32", 32, true);
addMinMax("UINT32", 32, false);
addMinMax("INT64", 64, true);
addMinMax("UINT64", 64, false);
//printf("Running ReadMacrosAction\n");
Preprocessor &preproc = info->Clang->getPreprocessor();
// Identify macro-functions and macro-values.
// Later, if we see a use of a macro-function, we can
// compile it to a static/inline function with args types based an use
// how will we know the return type?
// expr->getType() stmt->getRetValue()->getType....
// ... add function wrapping macro with wrong type
// parse/analyze squelching errors; get the macro expression type;
// correct the type and recompile to LLVM
// See ClangExpressionParser.cpp in lldb which parses
// a C expression from a command line... we need to
// do something similar.
for(Preprocessor::macro_iterator i = preproc.macro_begin();
i != preproc.macro_end();
i++) {
#if HAVE_LLVM_VER >= 37
handleMacro(i->first, i->second.getLatest()->getMacroInfo());
#elif HAVE_LLVM_VER >= 33
handleMacro(i->first, i->second->getMacroInfo());
#else
handleMacro(i->first, i->second);
#endif
}
};
// We need a way to:
// 1: parse code only
// 2: keep the code generator open until we finish generating Chapel code,
// since we might need to code generate called functions.
// 3: append to the target description
// 4: get LLVM values for code generated C things (e.g. types, function ptrs)
//
// This code is boiler-plate code mostly copied from ModuleBuilder.cpp - see
// http://clang.llvm.org/doxygen/ModuleBuilder_8cpp_source.html
// Note that ModuleBuilder.cpp is from the clang project and distributed
// under a BSD-like license.
//
// As far as we know, there is no public API for clang that
// would allow us the level of control we need over code generation.
// The portions that are not copied are delineated by
// comments indicating that they are custom to Chapel.
class CCodeGenConsumer : public ASTConsumer {
private:
GenInfo* info;
unsigned HandlingTopLevelDecls;
SmallVector<CXXMethodDecl *, 8> DeferredInlineMethodDefinitions;
struct HandlingTopLevelDeclRAII {
CCodeGenConsumer &Self;
HandlingTopLevelDeclRAII(CCodeGenConsumer &Self) : Self(Self) {
++Self.HandlingTopLevelDecls;
}
~HandlingTopLevelDeclRAII() {
if (--Self.HandlingTopLevelDecls == 0)
Self.EmitDeferredDecls();
}
};
public:
CCodeGenConsumer()
: ASTConsumer(), info(gGenInfo), HandlingTopLevelDecls(0) {
}
virtual ~CCodeGenConsumer() { }
// these macros help us to copy and paste the code from ModuleBuilder.
#define Ctx (info->Ctx)
#define Diags (* info->Diags)
#define Builder (info->cgBuilder)
#define CodeGenOpts (info->codegenOptions)
// mostly taken from ModuleBuilder.cpp
/// ASTConsumer override:
// Initialize - This is called to initialize the consumer, providing
// the ASTContext.
virtual void Initialize(ASTContext &Context) LLVM_CXX_OVERRIDE {
// This does setTargetTriple, setDataLayout, initialize targetData
// and cgBuilder.
setupClangContext(info, &Context);
for (size_t i = 0, e = CodeGenOpts.DependentLibraries.size(); i < e; ++i)
HandleDependentLibrary(CodeGenOpts.DependentLibraries[i]);
}
// ASTConsumer override:
// HandleCXXStaticMemberVarInstantiation - Tell the consumer that
// this variable has been instantiated.
virtual void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) LLVM_CXX_OVERRIDE {
// Custom to Chapel
if( info->parseOnly ) return;
// End custom to Chapel
if (Diags.hasErrorOccurred())
return;
Builder->HandleCXXStaticMemberVarInstantiation(VD);
}
// ASTConsumer override:
//
// HandleTopLevelDecl - Handle the specified top-level declaration.
// This is called by the parser to process every top-level Decl*.
//
// \returns true to continue parsing, or false to abort parsing.
virtual bool HandleTopLevelDecl(DeclGroupRef DG) LLVM_CXX_OVERRIDE {
if (Diags.hasErrorOccurred())
return true;
HandlingTopLevelDeclRAII HandlingDecl(*this);
// Make sure to emit all elements of a Decl.
for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) {
// Custom to Chapel
if(TypedefDecl *td = dyn_cast<TypedefDecl>(*I)) {
const clang::Type *ctype= td->getUnderlyingType().getTypePtrOrNull();
//printf("Adding typedef %s\n", td->getNameAsString().c_str());
if(ctype != NULL) {
info->lvt->addGlobalCDecl(td);
}
} else if(FunctionDecl *fd = dyn_cast<FunctionDecl>(*I)) {
info->lvt->addGlobalCDecl(fd);
} else if(VarDecl *vd = dyn_cast<VarDecl>(*I)) {
info->lvt->addGlobalCDecl(vd);
} else if(clang::RecordDecl *rd = dyn_cast<RecordDecl>(*I)) {
if( rd->getName().size() > 0 ) {
// Handle forward declaration for structs
info->lvt->addGlobalCDecl(rd);
}
}
if( info->parseOnly ) continue;
// End custom to Chapel
Builder->EmitTopLevelDecl(*I);
}
return true;
}
// ModuleBuilder.cpp has EmitDeferredDecls but that's not in ASTConsumer.
void EmitDeferredDecls() {
if (DeferredInlineMethodDefinitions.empty())
return;
// Emit any deferred inline method definitions. Note that more deferred
// methods may be added during this loop, since ASTConsumer callbacks
// can be invoked if AST inspection results in declarations being added.
HandlingTopLevelDeclRAII HandlingDecl(*this);
for (unsigned I = 0; I != DeferredInlineMethodDefinitions.size(); ++I)
Builder->EmitTopLevelDecl(DeferredInlineMethodDefinitions[I]);
DeferredInlineMethodDefinitions.clear();
}
// ASTConsumer override:
// \brief This callback is invoked each time an inline method
// definition is completed.
virtual void HandleInlineMethodDefinition(CXXMethodDecl *D) LLVM_CXX_OVERRIDE {
if (Diags.hasErrorOccurred())
return;
assert(D->doesThisDeclarationHaveABody());
// We may want to emit this definition. However, that decision might be
// based on computing the linkage, and we have to defer that in case we
// are inside of something that will change the method's final linkage,
// e.g.
// typedef struct {
// void bar();
// void foo() { bar(); }
// } A;
DeferredInlineMethodDefinitions.push_back(D);
// Provide some coverage mapping even for methods that aren't emitted.
// Don't do this for templated classes though, as they may not be
// instantiable.
if (!D->getParent()->getDescribedClassTemplate())
Builder->AddDeferredUnusedCoverageMapping(D);
}
// skipped ASTConsumer HandleInterestingDecl
// HandleTagDeclRequiredDefinition
// HandleCXXImplicitFunctionInstantiation
// HandleTopLevelDeclInObjCContainer
// HandleImplicitImportDecl
// GetASTMutationListener
// GetASTDeserializationListener
// PrintStats
// shouldSkipFunctionBody
// ASTConsumer override:
// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
// to (e.g. struct, union, enum, class) is completed. This allows the
// client hack on the type, which can occur at any point in the file
// (because these can be defined in declspecs).
virtual void HandleTagDeclDefinition(TagDecl *D) LLVM_CXX_OVERRIDE {
if (Diags.hasErrorOccurred())
return;
// Custom to Chapel - make a note of C globals
if(EnumDecl *ed = dyn_cast<EnumDecl>(D)) {
// Add the enum type
info->lvt->addGlobalCDecl(ed);
// Add the enum values
for(EnumDecl::enumerator_iterator e = ed->enumerator_begin();
e != ed->enumerator_end();
e++) {
info->lvt->addGlobalCDecl(*e); // & goes away with newer clang
}
} else if(RecordDecl *rd = dyn_cast<RecordDecl>(D)) {
const clang::Type *ctype = rd->getTypeForDecl();
if(ctype != NULL && rd->getDefinition() != NULL) {
info->lvt->addGlobalCDecl(rd);
}
}
if( info->parseOnly ) return;
// End Custom to Chapel
Builder->UpdateCompletedType(D);
// For MSVC compatibility, treat declarations of static data members with
// inline initializers as definitions.
if (Ctx->getLangOpts().MSVCCompat) {
for (Decl *Member : D->decls()) {
if (VarDecl *VD = dyn_cast<VarDecl>(Member)) {
if (Ctx->isMSStaticDataMemberInlineDefinition(VD) &&
Ctx->DeclMustBeEmitted(VD)) {
Builder->EmitGlobal(VD);
}
}
}
}
}
// ASTConsumer override:
// \brief This callback is invoked the first time each TagDecl is required
// to be complete.
virtual void HandleTagDeclRequiredDefinition(const TagDecl *D) LLVM_CXX_OVERRIDE {
if (Diags.hasErrorOccurred())
return;
if( info->parseOnly ) return;
if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
DI->completeRequiredType(RD);
}
// ASTConsumer override:
// HandleTranslationUnit - This method is called when the ASTs for
// entire translation unit have been parsed.
virtual void HandleTranslationUnit(ASTContext &Context) LLVM_CXX_OVERRIDE {
if (Diags.hasErrorOccurred()) {
if(Builder)
Builder->clear();
return;
}
/* custom to Chapel -
we don't release the builder now, because
we want to add a bunch of uses of functions
that may not have been codegened yet.
Instead, we call this in cleanupClang.
if (Builder)
Builder->Release();
*/
}
// ASTConsumer override:
//
// CompleteTentativeDefinition - Callback invoked at the end of a
// translation unit to notify the consumer that the given tentative
// definition should be completed.
//
// The variable declaration
// itself will be a tentative definition. If it had an incomplete
// array type, its type will have already been changed to an array
// of size 1. However, the declaration remains a tentative
// definition and has not been modified by the introduction of an
// implicit zero initializer.
virtual void CompleteTentativeDefinition(VarDecl *D) LLVM_CXX_OVERRIDE {
if (Diags.hasErrorOccurred())
return;
// Custom to Chapel
if( info->parseOnly ) return;
// End Custom to Chapel
Builder->EmitTentativeDefinition(D);
}
// ASTConsumer override:
// \brief Callback involved at the end of a translation unit to
// notify the consumer that a vtable for the given C++ class is
// required.
//
// \param RD The class whose vtable was used.
virtual void HandleVTable(CXXRecordDecl *RD
#if HAVE_LLVM_VER < 37
, bool DefinitionRequired
#endif
) LLVM_CXX_OVERRIDE {
if (Diags.hasErrorOccurred())
return;
// Custom to Chapel
if( info->parseOnly ) return;
// End Custom to Chapel
Builder->EmitVTable(RD
#if HAVE_LLVM_VER < 37
, DefinitionRequired
#endif
);
}
// ASTConsumer override:
//
// \brief Handle a pragma that appends to Linker Options. Currently
// this only exists to support Microsoft's #pragma comment(linker,
// "/foo").
void HandleLinkerOptionPragma(llvm::StringRef Opts) override {
Builder->AppendLinkerOptions(Opts);
}
// HandleLinkerOptionPragma
// ASTConsumer override:
// \brief Handle a pragma that emits a mismatch identifier and value to
// the object file for the linker to work with. Currently, this only
// exists to support Microsoft's #pragma detect_mismatch.
virtual void HandleDetectMismatch(llvm::StringRef Name,
llvm::StringRef Value) LLVM_CXX_OVERRIDE {
Builder->AddDetectMismatch(Name, Value);
}
// ASTConsumer override:
// \brief Handle a dependent library created by a pragma in the source.
/// Currently this only exists to support Microsoft's
/// #pragma comment(lib, "/foo").
virtual void HandleDependentLibrary(llvm::StringRef Lib) LLVM_CXX_OVERRIDE {
Builder->AddDependentLib(Lib);
}
// undefine macros we created to help with ModuleBuilder
#undef Ctx
#undef Diags
#undef Builder
#undef CodeGenOpts
};
#if HAVE_LLVM_VER >= 36
#define CREATE_AST_CONSUMER_RETURN_TYPE std::unique_ptr<ASTConsumer>
#else
#define CREATE_AST_CONSUMER_RETURN_TYPE ASTConsumer*
#endif
class CCodeGenAction : public ASTFrontendAction {
public:
CCodeGenAction() { }
protected:
virtual CREATE_AST_CONSUMER_RETURN_TYPE CreateASTConsumer(
CompilerInstance &CI, StringRef InFile);
};
CREATE_AST_CONSUMER_RETURN_TYPE CCodeGenAction::CreateASTConsumer(
CompilerInstance &CI, StringRef InFile) {
#if HAVE_LLVM_VER >= 36
return std::unique_ptr<ASTConsumer>(new CCodeGenConsumer());
#else
return new CCodeGenConsumer();
#endif
};
static void finishClang(GenInfo* info){
if( info->cgBuilder ) {
info->cgBuilder->Release();
}
info->Diags.reset();
info->DiagID.reset();
}
static void deleteClang(GenInfo* info){
if( info->cgBuilder ) {
delete info->cgBuilder;
info->cgBuilder = NULL;
}
delete info->targetData;
delete info->Clang;
info->Clang = NULL;
delete info->cgAction;
info->cgAction = NULL;
}
static void cleanupClang(GenInfo* info)
{
finishClang(info);
deleteClang(info);
}
void setupClang(GenInfo* info, std::string mainFile)
{
std::string clangexe = info->clangCC;
std::vector<const char*> clangArgs;
for( size_t i = 0; i < info->clangCCArgs.size(); ++i ) {
clangArgs.push_back(info->clangCCArgs[i].c_str());
}
for( size_t i = 0; i < info->clangLDArgs.size(); ++i ) {
clangArgs.push_back(info->clangLDArgs[i].c_str());
}
for( size_t i = 0; i < info->clangOtherArgs.size(); ++i ) {
clangArgs.push_back(info->clangOtherArgs[i].c_str());
}
if (llvmCodegen) {
clangArgs.push_back("-emit-llvm");
}
//clangArgs.push_back("-c");
clangArgs.push_back(mainFile.c_str()); // chpl - always compile rt file
info->diagOptions = new DiagnosticOptions();
info->DiagClient= new TextDiagnosticPrinter(errs(),&*info->diagOptions);
info->DiagID = new DiagnosticIDs();
#if HAVE_LLVM_VER >= 32
info->Diags = new DiagnosticsEngine(
info->DiagID, &*info->diagOptions, info->DiagClient);
#else
info->Diags = new DiagnosticsEngine(info->DiagID, info->DiagClient);
#endif
CompilerInvocation* CI =
createInvocationFromCommandLine(clangArgs, info->Diags);
// Get the codegen options from the clang command line.
info->codegenOptions = CI->getCodeGenOpts();
// if --fast is given, we should be at least at -O3.
if(fFastFlag && info->codegenOptions.OptimizationLevel < 3) {
info->codegenOptions.OptimizationLevel = 3;
}
{
// Make sure we include clang's internal header dir
#if HAVE_LLVM_VER >= 34
SmallString<128> P;
SmallString<128> P2; // avoids a valgrind overlapping memcpy
P = clangexe;
// Remove /clang from foo/bin/clang
P2 = sys::path::parent_path(P);
// Remove /bin from foo/bin
P = sys::path::parent_path(P2);
if( ! P.equals("") ) {
// Get foo/lib/clang/<version>/
sys::path::append(P, "lib");
sys::path::append(P, "clang");
sys::path::append(P, CLANG_VERSION_STRING);
}
CI->getHeaderSearchOpts().ResourceDir = P.str();
sys::path::append(P, "include");
#else
sys::Path P(clangexe);
if (!P.isEmpty()) {
P.eraseComponent(); // Remove /clang from foo/bin/clang
P.eraseComponent(); // Remove /bin from foo/bin
// Get foo/lib/clang/<version>/
P.appendComponent("lib");
P.appendComponent("clang");
P.appendComponent(CLANG_VERSION_STRING);
}
CI->getHeaderSearchOpts().ResourceDir = P.str();
sys::Path P2(P);
P.appendComponent("include");
#endif
#if HAVE_LLVM_VER >= 33
CI->getHeaderSearchOpts().AddPath(
P.str(), frontend::System,false, false);
#else
CI->getHeaderSearchOpts().AddPath(
P.str(), frontend::System,false, false, false, true, false);
#endif
}
// Create a compiler instance to handle the actual work.
info->Clang = new CompilerInstance();
info->Clang->setInvocation(CI);
// Save the TargetOptions and LangOptions since these
// are used during machine code generation.
info->clangTargetOptions = info->Clang->getTargetOpts();
info->clangLangOptions = info->Clang->getLangOpts();
// Create the compilers actual diagnostics engine.
// Create the compilers actual diagnostics engine.
#if HAVE_LLVM_VER >= 33
info->Clang->createDiagnostics();
#else
info->Clang->createDiagnostics(int(clangArgs.size()),&clangArgs[0]);
#endif
if (!info->Clang->hasDiagnostics())
INT_FATAL("Bad diagnostics from clang");
}
void finishCodegenLLVM() {
GenInfo* info = gGenInfo;
// Codegen extra stuff for global-to-wide optimization.
setupForGlobalToWide();
// Finish up our cleanup optimizers...
info->FPM_postgen->doFinalization();
// We don't need our postgen function pass manager anymore.
delete info->FPM_postgen;
info->FPM_postgen = NULL;
// Now finish any Clang code generation.
finishClang(info);
if(debug_info)debug_info->finalize();
// Verify the LLVM module.
if( developer ) {
bool problems;
#if HAVE_LLVM_VER >= 35
problems = verifyModule(*info->module, &errs());
//problems = false;
#else
problems = verifyModule(*info->module, PrintMessageAction);
#endif
if(problems) {
INT_FATAL("LLVM module verification failed");
}
}
}
void prepareCodegenLLVM()
{
GenInfo *info = gGenInfo;
LEGACY_FUNCTION_PASS_MANAGER *fpm = new LEGACY_FUNCTION_PASS_MANAGER(info->module);
PassManagerBuilder PMBuilder;
// Set up the optimizer pipeline.
// Start with registering info about how the
// target lays out data structures.
#if HAVE_LLVM_VER >= 37
// We already set the data layout in setupClangContext
// don't need to do anything else.
#elif HAVE_LLVM_VER >= 36
// We already set the data layout in setupClangContext
fpm->add(new DataLayoutPass());
#elif HAVE_LLVM_VER >= 35
fpm->add(new DataLayoutPass(info->module));
#else
fpm->add(new DataLayout(info->module));
#endif
if( fFastFlag ) {
PMBuilder.OptLevel = 2;
PMBuilder.populateFunctionPassManager(*fpm);
}
info->FPM_postgen = fpm;
info->FPM_postgen->doInitialization();
}
#if HAVE_LLVM_VER >= 33
static void handleErrorLLVM(void* user_data, const std::string& reason,
bool gen_crash_diag)
#else
static void handleErrorLLVM(void* user_data, const std::string& reason)
#endif
{
INT_FATAL("llvm fatal error: %s", reason.c_str());
}
struct ExternBlockInfo {
GenInfo* gen_info;
fileinfo file;
ExternBlockInfo() : gen_info(NULL), file() { }
~ExternBlockInfo() { }
};
typedef std::set<ModuleSymbol*> module_set_t;
typedef module_set_t::iterator module_set_iterator_t;
module_set_t gModulesWithExternBlocks;
bool lookupInExternBlock(ModuleSymbol* module, const char* name,
clang::TypeDecl** cTypeOut,
clang::ValueDecl** cValueOut,
ChapelType** chplTypeOut)
{
if( ! module->extern_info ) return false;
module->extern_info->gen_info->lvt->getCDecl(name, cTypeOut, cValueOut);
VarSymbol* var = module->extern_info->gen_info->lvt->getVarSymbol(name);
if( var ) *chplTypeOut = var->typeInfo();
return ( (*cTypeOut) || (*cValueOut) || (*chplTypeOut) );
}
bool alreadyConvertedExtern(ModuleSymbol* module, const char* name)
{
return module->extern_info->gen_info->lvt->isAlreadyInChapelAST(name);
}
bool setAlreadyConvertedExtern(ModuleSymbol* module, const char* name)
{
return module->extern_info->gen_info->lvt->markAddedToChapelAST(name);
}
void runClang(const char* just_parse_filename) {
static bool is_installed_fatal_error_handler = false;
/* TODO -- note that clang/examples/clang-interpreter/main.cpp
includes an example for getting the executable path,
so that we could automatically set CHPL_HOME. */
std::string home(CHPL_HOME);
std::string compileline = home + "/util/config/compileline";
compileline += " COMP_GEN_WARN="; compileline += istr(ccwarnings);
compileline += " COMP_GEN_DEBUG="; compileline += istr(debugCCode);
compileline += " COMP_GEN_OPT="; compileline += istr(optimizeCCode);
compileline += " COMP_GEN_SPECIALIZE="; compileline += istr(specializeCCode);
compileline += " COMP_GEN_FLOAT_OPT="; compileline += istr(ffloatOpt);
std::string readargsfrom;
if( !llvmCodegen && just_parse_filename ) {
// We're handling an extern block and not using the LLVM backend.
// Don't ask for any compiler-specific C flags.
readargsfrom = compileline + " --llvm"
" --clang"
" --clang-sysroot-arguments"
" --includes-and-defines";
} else {
// We're parsing extern blocks AND any parts of the runtime
// in order to prepare for an --llvm compilation.
// Use compiler-specific flags for clang-included.
readargsfrom = compileline + " --llvm"
" --clang"
" --clang-sysroot-arguments"
" --cflags"
" --includes-and-defines";
}
std::vector<std::string> args;
std::vector<std::string> clangCCArgs;
std::vector<std::string> clangLDArgs;
std::vector<std::string> clangOtherArgs;
std::string clangCC, clangCXX;
// Gather information from readargsfrom into clangArgs.
readArgsFromCommand(readargsfrom.c_str(), args);
if( args.size() < 2 ) USR_FATAL("Could not find runtime dependencies for --llvm build");
clangCC = args[0];
clangCXX = args[1];
// Note that these CC arguments will be saved in info->clangCCArgs
// and will be used when compiling C files as well.
for( size_t i = 2; i < args.size(); ++i ) {
clangCCArgs.push_back(args[i]);
}
forv_Vec(const char*, dirName, incDirs) {
clangCCArgs.push_back(std::string("-I") + dirName);
}
clangCCArgs.push_back(std::string("-I") + getIntermediateDirName());
//split ccflags by spaces
std::stringstream ccArgsStream(ccflags);
std::string ccArg;
while(ccArgsStream >> ccArg)
clangCCArgs.push_back(ccArg);
clangCCArgs.push_back("-pthread");
// libFlag and ldflags are handled during linking later.
clangCCArgs.push_back("-DCHPL_GEN_CODE");
// Always include sys_basic because it might change the
// behaviour of macros!
clangOtherArgs.push_back("-include");
clangOtherArgs.push_back("sys_basic.h");
if (!just_parse_filename) {
// Running clang to compile all runtime and extern blocks
// Include header files from the command line.
{
int filenum = 0;
while (const char* inputFilename = nthFilename(filenum++)) {
if (isCHeader(inputFilename)) {
clangOtherArgs.push_back("-include");
clangOtherArgs.push_back(inputFilename);
}
}
}
// Include extern C blocks
if( externC && gAllExternCode.filename ) {
clangOtherArgs.push_back("-include");
clangOtherArgs.push_back(gAllExternCode.filename);
}
} else {
// Just running clang to parse the extern blocks for this module.
clangOtherArgs.push_back("-include");
clangOtherArgs.push_back(just_parse_filename);
}
if( printSystemCommands ) {
printf("<internal clang> ");
for( size_t i = 0; i < clangCCArgs.size(); i++ ) {
printf("%s ", clangCCArgs[i].c_str());
}
for( size_t i = 0; i < clangOtherArgs.size(); i++ ) {
printf("%s ", clangOtherArgs[i].c_str());
}
printf("\n");
}
// Initialize gGenInfo
// Toggle LLVM code generation in our clang run;
// turn it off if we just wanted to parse some C.
gGenInfo = new GenInfo(clangCC, clangCXX,
compileline, clangCCArgs, clangLDArgs, clangOtherArgs,
just_parse_filename != NULL);
if( llvmCodegen || externC )
{
GenInfo *info = gGenInfo;
// Install an LLVM Fatal Error Handler.
if (!is_installed_fatal_error_handler) {
is_installed_fatal_error_handler = true;
install_fatal_error_handler(handleErrorLLVM);
}
// Run the Start Generation action
// Now initialize a code generator...
// this will enable us to ask for addresses of static (inline) functions
// and cause them to be emitted eventually.
// CCodeGenAction is defined above. It traverses the C AST
// and does the code generation.
info->cgAction = new CCodeGenAction();
if (!info->Clang->ExecuteAction(*info->cgAction)) {
if (just_parse_filename) {
USR_FATAL("error running clang on extern block");
} else {
USR_FATAL("error running clang during code generation");
}
}
if( ! info->parseOnly ) {
// This seems to be needed, even though it is strange.
// (otherwise we segfault in info->builder->CreateGlobalString)
// Some IRBuilder methods, codegenning a string,
// need a basic block in order to get to the module
// so we create a dummy function to code generate into
llvm::Type * voidTy = llvm::Type::getVoidTy(info->module->getContext());
std::vector<llvm::Type*> args;
llvm::FunctionType * FT = llvm::FunctionType::get(voidTy, args, false);
Function * F =
Function::Create(FT, Function::InternalLinkage,
"chplDummyFunction", info->module);
llvm::BasicBlock *block =
llvm::BasicBlock::Create(info->module->getContext(), "entry", F);
info->builder->SetInsertPoint(block);
}
// read macros. May call IRBuilder methods to codegen a string,
// so needs to happen after we set the insert point.
readMacrosClang();
if( ! info->parseOnly ) {
info->builder->CreateRetVoid();
}
}
}
static
void saveExternBlock(ModuleSymbol* module, const char* extern_code)
{
if( ! gAllExternCode.filename ) {
openCFile(&gAllExternCode, "extern-code", "c");
INT_ASSERT(gAllExternCode.fptr);
// Allow code in extern block to use malloc/calloc/realloc/free
// Note though that e.g. strdup or other library routines that
// allocate memory might still be an issue...
fprintf(gAllExternCode.fptr, "#include \"chpl-mem-no-warning-macros.h\"\n");
}
if( ! module->extern_info ) {
// Figure out what file to place the C code into.
module->extern_info = new ExternBlockInfo();
const char* name = astr("extern_block_", module->cname);
openCFile(&module->extern_info->file, name, "c");
// Could put #ifndef/define/endif wrapper start here.
}
FILE* f = module->extern_info->file.fptr;
INT_ASSERT(f);
// Append the C code to that file.
fputs(extern_code, f);
// Always make sure it ends in a close semi (solves errors)
fputs("\n;\n", f);
// Add this module to the set of modules needing extern compilation.
std::pair<module_set_iterator_t,bool> already_there;
already_there = gModulesWithExternBlocks.insert(module);
if( already_there.second ) {
// A new element was added to the map ->
// first time we have worked with this module.
// Add a #include of this module's extern block code to the
// global extern code file.
fprintf(gAllExternCode.fptr,
"#include \"%s\"\n", module->extern_info->file.filename);
}
}
void readExternC(void) {
// Handle extern C blocks.
forv_Vec(ExternBlockStmt, eb, gExternBlockStmts) {
// Figure out the parent module symbol.
ModuleSymbol* module = eb->getModule();
saveExternBlock(module, eb->c_code);
}
// Close extern_c_file.
if( gAllExternCode.fptr ) closefile(&gAllExternCode);
// Close any extern files for any modules we had generated code for.
module_set_iterator_t it;
for( it = gModulesWithExternBlocks.begin();
it != gModulesWithExternBlocks.end();
++it ) {
ModuleSymbol* module = *it;
INT_ASSERT(module->extern_info);
// Could put #ifndef/define/endif wrapper end here.
closefile(&module->extern_info->file);
// Now parse the extern C code for that module.
runClang(module->extern_info->file.filename);
// Now swap what went into the global layered value table
// into the module's own layered value table.
module->extern_info->gen_info = gGenInfo;
gGenInfo = NULL;
}
}
void cleanupExternC(void) {
module_set_iterator_t it;
for( it = gModulesWithExternBlocks.begin();
it != gModulesWithExternBlocks.end();
++it ) {
ModuleSymbol* module = *it;
INT_ASSERT(module->extern_info);
cleanupClang(module->extern_info->gen_info);
delete module->extern_info->gen_info;
delete module->extern_info;
// Remove all ExternBlockStmts from this module.
forv_Vec(ExternBlockStmt, eb, gExternBlockStmts) {
eb->remove();
}
gExternBlockStmts.clear();
}
}
llvm::Function* getFunctionLLVM(const char* name)
{
GenInfo* info = gGenInfo;
Function* fn = info->module->getFunction(name);
if( fn ) return fn;
GenRet got = info->lvt->getValue(name);
if( got.val ) {
fn = cast<Function>(got.val);
return fn;
}
return NULL;
}
llvm::Type* getTypeLLVM(const char* name)
{
GenInfo* info = gGenInfo;
llvm::Type* t = info->module->getTypeByName(name);
if( t ) return t;
t = info->lvt->getType(name);
if( t ) return t;
return NULL;
}
// should support TypedefDecl,EnumDecl,RecordDecl
llvm::Type* codegenCType(const TypeDecl* td)
{
GenInfo* info = gGenInfo;
CodeGen::CodeGenTypes & cdt = info->cgBuilder->getTypes();
QualType qType;
// handle TypedefDecl
if( const TypedefNameDecl* tnd = dyn_cast<TypedefNameDecl>(td) ) {
qType = tnd->getCanonicalDecl()->getUnderlyingType();
// had const Type *ctype = td->getUnderlyingType().getTypePtrOrNull();
//could also do:
// qType =
// tnd->getCanonicalDecl()->getTypeForDecl()->getCanonicalTypeInternal();
} else if( const EnumDecl* ed = dyn_cast<EnumDecl>(td) ) {
qType = ed->getCanonicalDecl()->getIntegerType();
// could also use getPromotionType()
//could also do:
// qType =
// tnd->getCanonicalDecl()->getTypeForDecl()->getCanonicalTypeInternal();
} else if( const RecordDecl* rd = dyn_cast<RecordDecl>(td) ) {
RecordDecl *def = rd->getDefinition();
INT_ASSERT(def);
qType=def->getCanonicalDecl()->getTypeForDecl()->getCanonicalTypeInternal();
} else {
INT_FATAL("Unknown clang type declaration");
}
return cdt.ConvertTypeForMem(qType);
}
// should support FunctionDecl,VarDecl,EnumConstantDecl
GenRet codegenCValue(const ValueDecl *vd)
{
GenInfo* info = gGenInfo;
GenRet ret;
if( info->cfile ) {
ret.c = vd->getName();
return ret;
}
if(const FunctionDecl *fd = dyn_cast<FunctionDecl>(vd)) {
// It's a function decl.
ret.val = info->cgBuilder->GetAddrOfFunction(fd);
ret.isLVPtr = GEN_VAL;
} else if(const VarDecl *vard = dyn_cast<VarDecl>(vd)) {
// It's a (global) variable decl
ret.val = info->cgBuilder->GetAddrOfGlobalVar(vard);
ret.isLVPtr = GEN_PTR;
} else if(const EnumConstantDecl *ed = dyn_cast<EnumConstantDecl>(vd)) {
// It's a constant enum value
APInt v = ed->getInitVal();
ret.isUnsigned = ! ed->getType()->hasSignedIntegerRepresentation();
CodeGen::CodeGenTypes & cdt = info->cgBuilder->getTypes();
llvm::Type* type = cdt.ConvertTypeForMem(ed->getType());
ret.val = ConstantInt::get(type, v);
ret.isLVPtr = GEN_VAL;
} else {
INT_FATAL("Unknown clang value declaration");
}
return ret;
}
LayeredValueTable::LayeredValueTable(){
layers.push_front(map_type());
}
void LayeredValueTable::addLayer(){
layers.push_front(map_type());
}
void LayeredValueTable::removeLayer(){
if(layers.size() != 1) {
layers.pop_front();
}
}
void LayeredValueTable::addValue(
StringRef name, Value *value, uint8_t isLVPtr, bool isUnsigned) {
Storage store;
store.u.value = value;
store.isLVPtr = isLVPtr;
store.isUnsigned = isUnsigned;
(layers.front())[name] = store;
}
void LayeredValueTable::addGlobalValue(
StringRef name, Value *value, uint8_t isLVPtr, bool isUnsigned) {
Storage store;
store.u.value = value;
store.isLVPtr = isLVPtr;
store.isUnsigned = isUnsigned;
(layers.back())[name] = store;
}
void LayeredValueTable::addGlobalValue(StringRef name, GenRet gend) {
addGlobalValue(name, gend.val, gend.isLVPtr, gend.isUnsigned);
}
void LayeredValueTable::addGlobalType(StringRef name, llvm::Type *type) {
Storage store;
store.u.type = type;
/*fprintf(stderr, "Adding global type %s ", name.str().c_str());
type->dump();
fprintf(stderr, "\n");
*/
(layers.back())[name] = store;
}
void LayeredValueTable::addGlobalCDecl(NamedDecl* cdecl) {
addGlobalCDecl(cdecl->getName(), cdecl);
// Also file structs under 'struct struct_name'
if(isa<RecordDecl>(cdecl)) {
std::string sname = "struct ";
sname += cdecl->getName();
addGlobalCDecl(sname, cdecl);
}
}
void LayeredValueTable::addGlobalCDecl(StringRef name, NamedDecl* cdecl) {
if(RecordDecl *rd = dyn_cast<RecordDecl>(cdecl)) {
// For record decls, always use the completed definition
// if it is available.
// E.g., we might visit decls in this order:
// struct stat { ... }
// struct stat;
RecordDecl* completed = rd->getDefinition();
if (completed) {
// Use the completed version below.
cdecl = completed;
}
}
// Add to an existing Storage record, so that it can store
// both a type and a value (e.g. struct stat and function stat).
Storage & store = (layers.back())[name];
if (isa<TypeDecl>(cdecl)) store.u.cTypeDecl = cast<TypeDecl>(cdecl);
if (isa<ValueDecl>(cdecl)) store.u.cValueDecl = cast<ValueDecl>(cdecl);
}
void LayeredValueTable::addGlobalVarSymbol(llvm::StringRef name, VarSymbol* var)
{
Storage store;
store.u.chplVar = var;
(layers.back())[name] = store;
}
void LayeredValueTable::addBlock(StringRef name, llvm::BasicBlock *block) {
Storage store;
store.u.block = block;
layer_iterator blockLayer = --layers.end();
if(layers.size() > 1) {
blockLayer = --blockLayer;
}
(*blockLayer)[name] = store;
}
GenRet LayeredValueTable::getValue(StringRef name) {
if(Storage *store = get(name)) {
if( store->u.value ) {
INT_ASSERT(isa<Value>(store->u.value));
GenRet ret;
ret.val = store->u.value;
ret.isLVPtr = store->isLVPtr;
ret.isUnsigned = store->isUnsigned;
return ret;
}
if( store->u.cValueDecl ) {
INT_ASSERT(isa<ValueDecl>(store->u.cValueDecl));
// we have a clang value decl.
// maybe FunctionDecl,VarDecl,EnumConstantDecl
// Convert it to an LLVM value
// should support FunctionDecl,VarDecl,EnumConstantDecl
return codegenCValue(store->u.cValueDecl);
}
if( store->u.chplVar && isVarSymbol(store->u.chplVar) ) {
VarSymbol* var = store->u.chplVar;
GenRet ret = var; // code generate it!
return ret;
}
}
GenRet ret;
return ret;
}
llvm::BasicBlock *LayeredValueTable::getBlock(StringRef name) {
if(Storage *store = get(name)) {
if( store->u.block && isa<llvm::BasicBlock>(store->u.block) )
return store->u.block;
}
return NULL;
}
llvm::Type *LayeredValueTable::getType(StringRef name) {
if(Storage *store = get(name)) {
if( store->u.type ) {
INT_ASSERT(isa<llvm::Type>(store->u.type));
return store->u.type;
}
if( store->u.cTypeDecl ) {
INT_ASSERT(isa<TypeDecl>(store->u.cTypeDecl));
// we have a clang type decl.
// maybe TypedefDecl,EnumDecl,RecordDecl
// Convert it to an LLVM type.
return codegenCType(store->u.cTypeDecl);
}
}
return NULL;
}
// Returns a type or a name decl for a given name
// Note that C can have a function and a type sharing the same name
// (e.g. stat/struct stat).
// Sets the output arguments to NULL if a type/value was not found.
// Either output argument can be NULL.
void LayeredValueTable::getCDecl(StringRef name, TypeDecl** cTypeOut,
ValueDecl** cValueOut) {
if (cValueOut) *cValueOut = NULL;
if (cTypeOut) *cTypeOut = NULL;
if(Storage *store = get(name)) {
if( store->u.cValueDecl ) {
INT_ASSERT(isa<ValueDecl>(store->u.cValueDecl));
// we have a clang value decl.
// maybe FunctionDecl,VarDecl,EnumConstantDecl
if (cValueOut) *cValueOut = store->u.cValueDecl;
}
if( store->u.cTypeDecl ) {
INT_ASSERT(isa<TypeDecl>(store->u.cTypeDecl));
// we have a clang type decl.
// maybe TypedefDecl,EnumDecl,RecordDecl
if (cTypeOut) *cTypeOut = store->u.cTypeDecl;
}
}
}
VarSymbol* LayeredValueTable::getVarSymbol(StringRef name) {
if(Storage *store = get(name)) {
if( store->u.chplVar && isVarSymbol(store->u.chplVar) ) {
// we have a Chapel Var Symbol.
// maybe immediate number or string, possibly variable reference.
// These come from macros.
return store->u.chplVar;
}
}
return NULL;
}
LayeredValueTable::Storage* LayeredValueTable::get(StringRef name) {
for(layer_iterator i = layers.begin(); i != layers.end(); ++i) {
value_iterator j = i->find(name);
if(j != i->end())
{
return &j->second;
}
}
return NULL;
}
bool LayeredValueTable::isAlreadyInChapelAST(llvm::StringRef name)
{
if(Storage *store = get(name)) {
return store->addedToChapelAST;
}
return false;
}
bool LayeredValueTable::markAddedToChapelAST(llvm::StringRef name)
{
if(Storage *store = get(name)) {
if( store->addedToChapelAST ) return false;
store->addedToChapelAST = true;
return true;
} else {
// Otherwise, make a new entry.
Storage toStore;
toStore.addedToChapelAST = true;
(layers.back())[name] = toStore;
return true;
}
}
void LayeredValueTable::swap(LayeredValueTable* other)
{
this->layers.swap(other->layers);
}
int getCRecordMemberGEP(const char* typeName, const char* fieldName)
{
GenInfo* info = gGenInfo;
TypeDecl* d = NULL;
int ret;
info->lvt->getCDecl(typeName, &d, NULL);
INT_ASSERT(d);
if( isa<TypedefDecl>(d) ) {
TypedefDecl* td = cast<TypedefDecl>(d);
const clang::Type* t = td->getUnderlyingType().getTypePtr();
while( t->isPointerType() ) {
t = t->getPointeeType().getTypePtr();
}
const RecordType* rt = t->getAsStructureType();
INT_ASSERT(rt);
d = rt->getDecl();
// getAsUnionType also available, but we don't support extern unions
}
INT_ASSERT(isa<RecordDecl>(d));
RecordDecl* rec = cast<RecordDecl>(d);
// Find the field decl.
RecordDecl::field_iterator it;
FieldDecl* field = NULL;
for( it = rec->field_begin(); it != rec->field_end(); ++it ) {
if( fieldName == it->getName() ) {
field = *it;
break;
}
}
INT_ASSERT(field);
ret=info->cgBuilder->getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
return ret;
}
bool isBuiltinExternCFunction(const char* cname)
{
if( 0 == strcmp(cname, "sizeof") ) return true;
else return false;
}
static
void addAggregateGlobalOps(const PassManagerBuilder &Builder,
LEGACY_PASS_MANAGER &PM) {
GenInfo* info = gGenInfo;
if( fLLVMWideOpt ) {
PM.add(createAggregateGlobalOpsOptPass(info->globalToWideInfo.globalSpace));
}
}
static
void addGlobalToWide(const PassManagerBuilder &Builder,
LEGACY_PASS_MANAGER &PM) {
GenInfo* info = gGenInfo;
if( fLLVMWideOpt ) {
PM.add(createGlobalToWide(&info->globalToWideInfo, info->targetLayout));
}
}
// If we're using the LLVM wide optimizations, we have to add
// some functions to call put/get into the Chapel runtime layers
// (the optimization is meant to be portable to other languages)
static
void setupForGlobalToWide(void) {
if( ! fLLVMWideOpt ) return;
GenInfo* ginfo = gGenInfo;
GlobalToWideInfo* info = &ginfo->globalToWideInfo;
info->localeIdType = ginfo->lvt->getType("chpl_localeID_t");
assert(info->localeIdType);
info->nodeIdType = ginfo->lvt->getType("c_nodeid_t");
assert(info->nodeIdType);
info->addrFn = getFunctionLLVM("chpl_wide_ptr_get_address");
INT_ASSERT(info->addrFn);
info->locFn = getFunctionLLVM("chpl_wide_ptr_read_localeID");
INT_ASSERT(info->locFn);
info->nodeFn = getFunctionLLVM("chpl_wide_ptr_get_node");
INT_ASSERT(info->nodeFn);
info->makeFn = getFunctionLLVM("chpl_return_wide_ptr_loc_ptr");
INT_ASSERT(info->makeFn);
info->getFn = getFunctionLLVM("chpl_gen_comm_get_ctl");
INT_ASSERT(info->getFn);
info->putFn = getFunctionLLVM("chpl_gen_comm_put_ctl");
INT_ASSERT(info->putFn);
info->getPutFn = getFunctionLLVM("chpl_gen_comm_getput");
INT_ASSERT(info->getPutFn);
info->memsetFn = getFunctionLLVM("chpl_gen_comm_memset");
INT_ASSERT(info->memsetFn);
// Call these functions in a dummy externally visible
// function which GlobalToWide should remove. We need to do that
// in order to prevent the functions from being removed for
// not having references when they are inline/internal linkage.
// Our function here just returns a pointer to the i'th (i is the argument)
// such function - and since it is marked externally visible, there
// is no way that the compiler can completely remove the needed
// runtime functions.
const char* dummy = "chpl_wide_opt_dummy";
if( getFunctionLLVM(dummy) ) INT_FATAL("dummy function already exists");
llvm::Type* retType = llvm::Type::getInt8PtrTy(ginfo->module->getContext());
llvm::Type* argType = llvm::Type::getInt64Ty(ginfo->module->getContext());
llvm::Value* fval = ginfo->module->getOrInsertFunction(
dummy, retType, argType, NULL);
llvm::Function* fn = llvm::dyn_cast<llvm::Function>(fval);
// Mark the function as external so that it will not be removed
fn->setLinkage(llvm::GlobalValue::ExternalLinkage);
llvm::BasicBlock* block =
llvm::BasicBlock::Create(ginfo->module->getContext(), "entry", fn);
ginfo->builder->SetInsertPoint(block);
llvm::Constant* fns[] = {info->addrFn, info->locFn, info->nodeFn,
info->makeFn, info->getFn, info->putFn,
info->getPutFn, info->memsetFn, NULL};
llvm::Value* ret = llvm::Constant::getNullValue(retType);
llvm::Function::arg_iterator args = fn->arg_begin();
llvm::Value* arg = args++;
for( int i = 0; fns[i]; i++ ) {
llvm::Constant* f = fns[i];
llvm::Value* ptr = ginfo->builder->CreatePointerCast(f, retType);
llvm::Value* id = llvm::ConstantInt::get(argType, i);
llvm::Value* eq = ginfo->builder->CreateICmpEQ(arg, id);
ret = ginfo->builder->CreateSelect(eq, ptr, ret);
}
ginfo->builder->CreateRet(ret);
#if HAVE_LLVM_VER >= 35
llvm::verifyFunction(*fn, &errs());
#endif
info->preservingFn = fn;
}
void makeBinaryLLVM(void) {
#if HAVE_LLVM_VER >= 36
std::error_code errorInfo;
#else
std::string errorInfo;
#endif
GenInfo* info = gGenInfo;
std::string moduleFilename = genIntermediateFilename("chpl__module.bc");
std::string preOptFilename = genIntermediateFilename("chpl__module-nopt.bc");
if( saveCDir[0] != '\0' ) {
// Save the generated LLVM before optimization.
tool_output_file output (preOptFilename.c_str(),
errorInfo,
#if HAVE_LLVM_VER >= 34
sys::fs::F_None
#else
raw_fd_ostream::F_Binary
#endif
);
WriteBitcodeToFile(info->module, output.os());
output.keep();
output.os().flush();
}
tool_output_file output (moduleFilename.c_str(),
errorInfo,
#if HAVE_LLVM_VER >= 34
sys::fs::F_None
#else
raw_fd_ostream::F_Binary
#endif
);
static bool addedGlobalExts = false;
if( ! addedGlobalExts ) {
// Add the Global to Wide optimization if necessary.
PassManagerBuilder::addGlobalExtension(PassManagerBuilder::EP_ScalarOptimizerLate, addAggregateGlobalOps);
PassManagerBuilder::addGlobalExtension(PassManagerBuilder::EP_ScalarOptimizerLate, addGlobalToWide);
PassManagerBuilder::addGlobalExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, addGlobalToWide);
addedGlobalExts = true;
}
EmitBackendOutput(*info->Diags, info->codegenOptions,
info->clangTargetOptions, info->clangLangOptions,
#if HAVE_LLVM_VER >= 35
info->Ctx->getTargetInfo().getTargetDescription(),
#endif
info->module, Backend_EmitBC, &output.os());
output.keep();
output.os().flush();
//finishClang is before the call to the debug finalize
deleteClang(info);
std::string options = "";
std::string home(CHPL_HOME);
std::string compileline = info->compileline;
compileline += " --llvm"
" --clang"
" --main.o"
" --clang-sysroot-arguments"
" --libraries";
std::vector<std::string> args;
readArgsFromCommand(compileline.c_str(), args);
INT_ASSERT(args.size() >= 1);
std::string clangCC = args[0];
std::string clangCXX = args[1];
std::string maino = args[2];
std::vector<std::string> dotOFiles;
// Gather C flags for compiling C files.
std::string cargs;
for( size_t i = 0; i < info->clangCCArgs.size(); ++i ) {
cargs += " ";
cargs += info->clangCCArgs[i];
}
// Compile any C files.
{
// Start with configuration settings
const char* inputFilename = gChplCompilationConfig.pathname;
const char* objFilename = objectFileForCFile(inputFilename);
mysystem(astr(clangCC.c_str(),
" -c -o ",
objFilename,
" ",
inputFilename,
cargs.c_str()),
"Compile C File");
dotOFiles.push_back(objFilename);
}
int filenum = 0;
while (const char* inputFilename = nthFilename(filenum++)) {
if (isCSource(inputFilename)) {
const char* objFilename = objectFileForCFile(inputFilename);
mysystem(astr(clangCC.c_str(),
" -c -o ", objFilename,
" ", inputFilename, cargs.c_str()),
"Compile C File");
dotOFiles.push_back(objFilename);
} else if( isObjFile(inputFilename) ) {
dotOFiles.push_back(inputFilename);
}
}
// Start linker options with C args
// This is important to get e.g. -O3 -march=native
// since with LLVM we are doing link-time optimization.
// We know it's OK to include -I (e.g.) since we're calling
// clang++ to link so that it can optimize the .bc files.
options = cargs;
if(debugCCode) {
options += " -g";
}
options += " ";
options += ldflags;
options += " -pthread";
// Now, if we're doing a multilocale build, we have to make a launcher.
// For this reason, we create a makefile. codegen_makefile
// also gives us the name of the temporary place to save
// the generated program.
fileinfo mainfile;
mainfile.filename = "chpl__module.bc";
mainfile.pathname = moduleFilename.c_str();
const char* tmpbinname = NULL;
codegen_makefile(&mainfile, &tmpbinname, true);
INT_ASSERT(tmpbinname);
// Run the linker. We always use clang++ because some third-party
// libraries are written in C++. With the C backend, this switcheroo
// is accomplished in the Makefiles somewhere
std::string command = clangCXX + " " + options + " " +
moduleFilename + " " + maino +
" -o " + tmpbinname;
for( size_t i = 0; i < dotOFiles.size(); i++ ) {
command += " ";
command += dotOFiles[i];
}
// 0 is clang, 1 is clang++, 2 is main.o
for(size_t i = 3; i < args.size(); ++i) {
command += " ";
command += args[i];
}
// Put user-requested libraries at the end of the compile line,
// they should at least be after the .o files and should be in
// order where libraries depend on libraries to their right.
for (int i=0; i<numLibFlags; i++) {
command += " ";
command += libFlag[i];
}
if( printSystemCommands ) {
printf("%s\n", command.c_str());
}
mysystem(command.c_str(), "Make Binary - Linking");
// Now run the makefile to move from tmpbinname to the proper program
// name and to build a launcher (if necessary).
const char* makeflags = printSystemCommands ? "-f " : "-s -f ";
const char* makecmd = astr(astr(CHPL_MAKE, " "),
makeflags,
getIntermediateDirName(), "/Makefile");
if( printSystemCommands ) {
printf("%s\n", makecmd);
}
mysystem(makecmd, "Make Binary - Building Launcher and Copying");
}
#endif
| 64,295 | 21,914 |
// Copyright 2021 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/ui/ash/projector/projector_client_impl.h"
#include "ash/constants/ash_features.h"
#include "ash/public/cpp/projector/projector_controller.h"
#include "ash/webui/projector_app/annotator_message_handler.h"
#include "ash/webui/projector_app/projector_app_client.h"
#include "ash/webui/projector_app/public/cpp/projector_app_constants.h"
#include "chrome/browser/ash/drive/drive_integration_service.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/download/download_prefs.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/speech/on_device_speech_recognizer.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/web_applications/system_web_app_ui_utils.h"
#include "chrome/browser/web_applications/system_web_apps/system_web_app_types.h"
#include "chromeos/login/login_state/login_state.h"
#include "components/soda/soda_installer.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "media/base/media_switches.h"
#include "projector_client_impl.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/views/controls/webview/webview.h"
#include "url/gurl.h"
namespace {
inline const std::string& GetLocale() {
return g_browser_process->GetApplicationLocale();
}
} // namespace
// static
void ProjectorClientImpl::InitForProjectorAnnotator(views::WebView* web_view) {
web_view->LoadInitialURL(GURL(ash::kChromeUITrustedAnnotatorUrl));
content::WebContents* web_contents = web_view->GetWebContents();
content::WebUI* web_ui = web_contents->GetWebUI();
web_ui->AddMessageHandler(std::make_unique<ash::AnnotatorMessageHandler>());
}
ProjectorClientImpl::ProjectorClientImpl(ash::ProjectorController* controller)
: controller_(controller) {
controller_->SetClient(this);
}
ProjectorClientImpl::ProjectorClientImpl()
: ProjectorClientImpl(ash::ProjectorController::Get()) {}
ProjectorClientImpl::~ProjectorClientImpl() = default;
void ProjectorClientImpl::StartSpeechRecognition() {
// ProjectorController should only request for speech recognition after it
// has been informed that recognition is available.
// TODO(crbug.com/1165437): Dynamically determine language code.
DCHECK(OnDeviceSpeechRecognizer::IsOnDeviceSpeechRecognizerAvailable(
GetLocale()));
DCHECK_EQ(speech_recognizer_.get(), nullptr);
recognizer_status_ = SPEECH_RECOGNIZER_OFF;
speech_recognizer_ = std::make_unique<OnDeviceSpeechRecognizer>(
weak_ptr_factory_.GetWeakPtr(), ProfileManager::GetActiveUserProfile(),
GetLocale(), /*recognition_mode_ime=*/false,
/*enable_formatting=*/true);
}
void ProjectorClientImpl::StopSpeechRecognition() {
speech_recognizer_.reset();
recognizer_status_ = SPEECH_RECOGNIZER_OFF;
}
void ProjectorClientImpl::ShowSelfieCam() {
selfie_cam_bubble_manager_.Show(
ProfileManager::GetActiveUserProfile(),
display::Screen::GetScreen()->GetPrimaryDisplay().work_area());
}
void ProjectorClientImpl::CloseSelfieCam() {
selfie_cam_bubble_manager_.Close();
}
bool ProjectorClientImpl::IsSelfieCamVisible() const {
return selfie_cam_bubble_manager_.IsVisible();
}
void ProjectorClientImpl::OnSpeechResult(
const std::u16string& text,
bool is_final,
const absl::optional<media::SpeechRecognitionResult>& full_result) {
DCHECK(full_result.has_value());
controller_->OnTranscription(full_result.value());
}
void ProjectorClientImpl::OnSpeechRecognitionStateChanged(
SpeechRecognizerStatus new_state) {
if (new_state == SPEECH_RECOGNIZER_ERROR) {
speech_recognizer_.reset();
recognizer_status_ = SPEECH_RECOGNIZER_OFF;
controller_->OnTranscriptionError();
} else if (new_state == SPEECH_RECOGNIZER_READY) {
if (recognizer_status_ == SPEECH_RECOGNIZER_OFF && speech_recognizer_) {
// The SpeechRecognizer was initialized after being created, and
// is ready to start recognizing speech.
speech_recognizer_->Start();
}
}
recognizer_status_ = new_state;
}
bool ProjectorClientImpl::GetDriveFsMountPointPath(
base::FilePath* result) const {
if (!IsDriveFsMounted())
return false;
if (ash::ProjectorController::AreExtendedProjectorFeaturesDisabled()) {
auto* profile = ProfileManager::GetActiveUserProfile();
DCHECK(profile);
DownloadPrefs* download_prefs = DownloadPrefs::FromBrowserContext(
ProfileManager::GetActiveUserProfile());
*result = download_prefs->GetDefaultDownloadDirectoryForProfile();
return true;
}
drive::DriveIntegrationService* integration_service =
drive::DriveIntegrationServiceFactory::FindForProfile(
ProfileManager::GetActiveUserProfile());
*result = integration_service->GetMountPointPath();
return true;
}
bool ProjectorClientImpl::IsDriveFsMounted() const {
if (!chromeos::LoginState::Get()->IsUserLoggedIn())
return false;
if (ash::ProjectorController::AreExtendedProjectorFeaturesDisabled()) {
// Return true when extended projector features are disabled. Use download
// folder for Projector storage.
return true;
}
auto* profile = ProfileManager::GetActiveUserProfile();
drive::DriveIntegrationService* integration_service =
drive::DriveIntegrationServiceFactory::FindForProfile(profile);
return integration_service && integration_service->IsMounted();
}
void ProjectorClientImpl::OpenProjectorApp() const {
auto* profile = ProfileManager::GetActiveUserProfile();
web_app::LaunchSystemWebAppAsync(profile, web_app::SystemAppType::PROJECTOR);
}
void ProjectorClientImpl::MinimizeProjectorApp() const {
auto* profile = ProfileManager::GetActiveUserProfile();
auto* browser =
FindSystemWebAppBrowser(profile, web_app::SystemAppType::PROJECTOR);
if (browser)
browser->window()->Minimize();
}
void ProjectorClientImpl::OnNewScreencastPreconditionChanged(
const ash::NewScreencastPrecondition& precondition) const {
ash::ProjectorAppClient::Get()->OnNewScreencastPreconditionChanged(
precondition);
}
| 6,403 | 2,019 |
#include "output.h"//use file code that I created
#include<iostream>//use standard library
using std::cout;
int main()
{
cout<<"Hello World!";
return 0;
} | 160 | 58 |
/*Ideas22222222222
⭐ -1. Still giving INVALID MOVE(wrong in game.py).
0. Doesn,t know townhall dead
1. GAME: Improve Endgame Heuristics (If less stealth attack)
2. GAME: Similar to above, Try adding heuristics for stealth attack
0. Work on 10x10 rather than samller
XXX 3. TIME: Instead of calling Function directly see value of 'score'
XXX 4. TIME: Introduce sort at lower levels then instead of calling utility(after introduction of (3) TOO EXPENSIVE slower
5. GAME: Stangnant Game?
6. TEST: Match with TA Bots
7. TIME: MutliThreading calculate best move for every next opponent move then play
8. GAME: Better huristic and evaluation functions
9. LEARN: Update weights after computation of utility form lower depths
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#include <string>
#include <climits>
#include"player2.cpp"
using namespace std;
//--Manual Options and Developer Options
int RED =1; //Developer Option: check by reducing number of branches
bool LEARN = false; //learn mode
bool DYNAMIC_DEPTH = true; //Depth static or Dynamic
bool SORT = true; //sort for better pruning
bool CLEAN = true; //clean for utility calculation?
int DEPTH=2;
int ENDGAME = 4; //4 bansal 5 sondhi ?
//vector<vector<int> > RealBoard;
//const int m=8,n=8;
int PLAYER_ID; //1 ->black and 2 -> white : Fixed for a game
//int RATE = 1; //Learning rate
int DOWN = 0; //opponent townhall down?
bool LESS = false;
/*Weights*/
int w_townhall_w =200; //200~300
int w_townhall_b =-200; //-200~300
int w_soldier_w =90; //90
int w_soldier_b =-90; //-90
int w_cannon_w =1; //1
int w_cannon_b =-1; //-1
int w_TcountW =-20; //-10
int w_TcountB =20; //10
int w_ScountW =-10; //-10
int w_ScountB =10; //10
int w_vicinityW =1; //weight
int w_vicinityB =-1; // weight
//Learned Values
//int l_townhall_w =923; //200
//int l_townhall_b =-923; //-200
//int l_soldier_w =713; //90
//int l_soldier_b =-713; //-90
//int l_cannon_w =1; //1
//int l_cannon_b =-1; //-1
//int l_TcountW =-613; //-10
//int l_TcountB =613; //10
//int l_ScountW =-613; //-10
//int l_ScountB =613; //10
/*
-------(m)------>
| 🔳🔲🔳🔲🔳🔲🔳🔲
| 🔳🔲🔳🔲🔳🔲🔳🔲
| 🔳🔲🔳🔲🔳🔲🔳🔲
(n)🔳🔲🔳🔲🔳🔲🔳🔲
| 🔳🔲🔳🔲🔳🔲🔳🔲
| 🔳🔲🔳🔲🔳🔲🔳🔲
| 🔳🔲🔳🔲🔳🔲🔳🔲
V 🔳🔲🔳🔲🔳🔲🔳🔲
*/
/*----------------------CLASS BEGIN----------------------*/
class State{
int m=8,n=8; // 2-Black-Negative // 1-White-Positive
vector<vector<int> > board;
vector <tuple <char,pair <lld,lld>,pair <lld,lld > > > Moves;
int moveToPlay =0;
public: int moveIndex = 0;
int score=0; // score of board /if no search done then equal to utility
// int whosMoves = 1; // 1 get white move and 2 to get black move
/*
PLAYER_ID == whosMoves Opponent
PLAYER_ID !- whosMoves your moves
*/
/*Statistics for evaluation function*/
//Basic count
int townhall_w = 4;
int soldier_w = 16;
int cannon_w = 4;
int townhall_b = 4;
int soldier_b = 16;
int cannon_b = 4;
//Attack count
int TcountB =0;
int TcountW =0;
int ScountB =0;
int ScountW =0;
//Vicinity Count
int vicinityB =0;
int vicinityW =0;
/*--END Statistics for evaluation function*/
//Constructor
public: State(vector<vector<int> > bored){
m=getM();
n=getN();
board.resize(n);
for(int i=0;i<n;i++) board[i].resize(m);
board = bored;
//getBoardS();
}
//copy constructor
public: void copy(State* st){
m=getM();
n=getN();
board.resize(n);
for(int i=0;i<n;i++) board[i].resize(m);
board = st->board;
// whosMoves = 3-st->whosMoves; //invert whose move
}
/*--Utility calculating functions--*/
//Think how to layout the board and different sides in numbers##
//writing code based on enemy -ve and black mostly
//townhall and soldier count and vicinity count
void setBasicCount(){
//set to zero
townhall_w =0;
townhall_b =0;
soldier_w = 0;
soldier_b =0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(board[i][j]==1){
soldier_w++;
vicinityW+=i;
}
else if(board[i][j]==-1){
soldier_b++;
vicinityB+=(n-i);
}
else if(board[i][j]==2) townhall_w++;
else if(board[i][j]==-2) townhall_b++;
}
}
}
/*
DevOpt:Printing visual functions
*/
string representation(int i, int x, int y){
switch (i){
case 1 : return "⚪";
case -1: return "⚫";
case 2 : return "🔲";
case -2 : return "🔳";
default: if(x%2==y%2) return " "; else return " ";
// default: if(x%2==y%2) return "⬛"; else return "⬜";
}
return "X";
}
void printBoard(){
for(int i=0;i<n;i++){
for(int j=0;j<m;j++)
cerr<<representation(board[i][j],i,j)<<" ";
cerr<<endl<<endl;
}
}
//To print outside board
void printBoard(vector<vector<int> > board){
for(int i=0;i<n;i++){
for(int j=0;j<m;j++)
cerr<<representation(board[i][j],i,j)<<" ";
cerr<<endl<<endl;
}
}
void printMove(int index){
tuple<char,pair <int,int> ,pair <int,int> > move = Moves[index];
cerr<<get<0>(move)<<" "<<get<1>(move).first<<" "<<get<1>(move).second<<" => "<<get<2>(move).first<<" "<<get<2>(move).second<<endl;
}
/*END Printing and Visualizatin Functions*/
//cannon count
int getCannonCount(){
cannon_b=0;
cannon_w=0;
//Horizontal cannons
for(int i=0;i<n;i++){
for(int j=0;j<m-2;j++){
if(board[i][j]==1&&board[i][j+1]==1&&board[i][j+2]==1) //horizontal cannon found
cannon_w++;
else if(board[i][j]==-1&&board[i][j+1]==-1&&board[i][j+2]==-1)
cannon_b++;
}
}
//vertical cannons
for(int j=0;j<m;j++){
for(int i=0;i<m-2;i++){
if(board[i][j]==1&&board[i+1][j]==1&&board[i+2][j]==1)
cannon_w++;
else if(board[i][j]==-1&&board[i+1][j]==-1&&board[i+2][j]==-1)
cannon_b++;
}
}
//bottom right diagonal cannons
for(int i=0;i<n-2;i++){
for(int j=0;j<m-2;j++){
if(board[i][j]==1&&board[i+1][j+1]==1&&board[i+2][j+2]==1)
cannon_w++;
else if(board[i][j]==-1&&board[i+1][j+1]==-1&&board[i+2][j+2]==-1)
cannon_b++;
}
}
//bottom left diagonal cannons
for(int i=0;i<n-2;i++){
for(int j=2;j<m;j++){
if(board[i][j]==1&&board[i+1][j-1]==1&&board[i+2][j-2]==1)
cannon_w++;
else if(board[i][j]==-1&&board[i+1][j-1]==-1&&board[i+2][j-2]==-1)
cannon_b++;
}
}
}
//no of black soliders in attacking range
void blackUnderAttack(){
//###Might Over write !!!!
vector <tuple <char,pair <lld,lld>,pair <lld,lld > > > Moves;
Moves =validMovesR(2); //moves of white
TcountB=0;
ScountB=0;
for(int i=0;i<Moves.size();i++){
if(board[get<2>(Moves[i]).first][get<2>(Moves[i]).second]==-1) //black soldier present
ScountB++;
if(board[get<2>(Moves[i]).first][get<2>(Moves[i]).second]==-2) //black soldier present
TcountB++;
}
}
//no of white soliders in attacking range
void whiteUnderAttack(){
vector <tuple <char,pair <lld,lld>,pair <lld,lld > > > Moves;
Moves =validMovesR(1); //moves of black
TcountW=0;
ScountW=0;
for(int i=0;i<Moves.size();i++){
if(board[get<2>(Moves[i]).first][get<2>(Moves[i]).second]==1) //white soldier present
ScountW++;
if(board[get<2>(Moves[i]).first][get<2>(Moves[i]).second]==2) //white soldier present
TcountW++;
}
}
//soldiers under attacki
//number of cannons
//enemy cannons
//attacking cannos
//under attack form cannons
//townhalls under attack
//townhall in attacking range
public: int utility(){ //high desired for US
int util=0;
setBasicCount();
getCannonCount();
blackUnderAttack();
whiteUnderAttack();
//setVicinity();
//⭐END GAME Heuristics⭐//
if(soldier_w < ENDGAME &&PLAYER_ID==2){
// cerr<<"We are in the ENDGAME now!\n";
//when less soldiers then save your soldiers
w_soldier_w=130; //120
//stay out of attacking zones
w_ScountW = -70; //-60
//Don't Try to attack soldiers
w_ScountB = 5; //-5
}
else if(soldier_b < ENDGAME &&PLAYER_ID==1){
// cerr<<"We are in the ENDGAME now!\n";
//when less soldiers then save your soldiers
w_soldier_b=-130; //-120
//stay out of attacking zones
w_ScountB = 70; //60
//Don't Try to attack soldiers
w_ScountW = -5; //-5
}
//END ENDGAME Heuristics//
util += (w_townhall_w*townhall_w + w_townhall_b*townhall_b);
// cerr<<"Util TC: "<<util<<endl;
util += (w_soldier_w*soldier_w + w_soldier_b*soldier_b);
// cerr<<"Util BC: "<<util<<endl;
util += (w_cannon_w*cannon_w + w_cannon_b*cannon_b);
// cerr<<"Util CC: "<<util<<endl;
util += (w_TcountW*TcountW + w_TcountB*TcountB);
util += (w_ScountW*ScountW + w_ScountB*ScountB);
// cerr<<"TcountW: "<<TcountW<<" TcountB: "<<TcountB<<endl;
// cerr<<"ScountW: "<<ScountW<<" ScountB: "<<ScountB<<endl;
// cerr<<"Util AC: "<<util<<endl;
//closeness to other townhalls
util += (w_vicinityW*vicinityW + w_vicinityB*vicinityB)/10;
if(PLAYER_ID==1)
util = -util;
score = util;
return util;
}
/*----END Utility Calculating functions*/
/*---Functions to communicate with player module---*/
//Just gives board position if current move played
void move(tuple<char,pair <int,int> ,pair <int,int> > move,int turn){
//printBoard();
//cerr<<"PLAYER_ID fiven: "<<turn<<endl;
board = update(board,move,3-turn); //in player.cpp
}
//Primary method to get validMoves
void validMoves(int turn){
Moves= getValidMoves(board,3-turn); //in player.cpp
//removeBlank(); //remove blank cannon shots
clean(Moves); //remove repetitive bomb shots/
}
//Secondary method to get validMoves for utility calculation
vector <tuple <char,pair <lld,lld>,pair <lld,lld > > > validMovesR(int turn){
vector <tuple <char,pair <lld,lld>,pair <lld,lld > > > Moves= getValidMoves(board,3-turn); //in player.cpp
//removeBlank(); //remove blank cannon shots
if(CLEAN)
clean(Moves); //remove repetitive bomb shots/
return Moves;
}
//removes duplicate cannon shot moves and ARRANGES bomb shots before
void clean(vector <tuple <char,pair <lld,lld>,pair <lld,lld > > > &Moves){
for(int i=0;i<Moves.size();i++){
if(get<0>(Moves[i])=='M')
continue;
for(int j=i+1;j<Moves.size();j++){
if(get<0>(Moves[j])=='M')
continue;
if(get<2>(Moves[i])==get<2>(Moves[j])){ //same target
swap(Moves[j],Moves[Moves.size()-1]);
Moves.pop_back();
j--;
}
}
}
}
//Removes duplicate bomb shots of same cannon
void removeBlank(){
for(int i=0;i<Moves.size();i++){
if(get<0>(Moves[i])=='M')
continue;
if(board[get<2>(Moves[i]).first][get<2>(Moves[i]).second]==0)
swap(Moves[i],Moves[Moves.size()-1]);
Moves.pop_back();
i--;
}
}
void getBoardS(){
board=getBoard(); //in player.cpp
}
//Play function: Actually plays the move and updates board
tuple <char,pair <lld,lld>,pair <lld,lld > > play(int i){
moveToPlay=i;
return Moves[moveToPlay]; //update in player.cpp
}
//return all the board positions after one ply
vector<State*> Successors(int turn){
validMoves(turn);
vector<State*> children(Moves.size());
for(int i=0;i<Moves.size();i++){
children[i] = new State(board); //#check once: copy constructor working?
children[i]->copy(this);//problem in copy
//printBoard();
children[i]->move(Moves[i],turn);
children[i]->moveIndex=i;
// children[i]->printBoard();
//Move and Utility
// cerr<<"Utility of "<<i<<"th move is "<<children[i]->utility()<<endl;
// printMove(i);
//printBoard();
// cerr<<"-------------------------------------------"<<endl;
}
return children;
}
};
/*--------------------------------------------------END Class Def; BEGIN MINIMAX--------------------------------------------------*/
//Learning
//void learn(int o , int n){
// int loss = n-o;
// int delta = RATE*loss;
// delta/=8;
// if(PLAYER_ID==1)
// delta=-delta;
//
// l_townhall_w+=delta;
// l_townhall_b-=delta;
// l_soldier_w +=delta;
// l_soldier_b -=delta;
//
// l_ScountW +=delta;
// l_ScountB -=delta;
// l_TcountW +=delta;
// l_TcountB -=delta;
//
// cerr<<"int l_townhall_w = "<<l_townhall_w<<";"<<endl;
// cerr<<"int l_townhall_b = "<<l_townhall_b<<";"<<endl;
// cerr<<"int l_soldier_w = "<<l_soldier_w<<";"<<endl;
// cerr<<"int l_soldier_b = "<<l_soldier_b<<";"<<endl;
// cerr<<"int l_ScountW: "<<l_ScountW<<";"<<endl;
// cerr<<"int l_ScountB: "<<l_ScountB<<";"<<endl;
// cerr<<"int l_TcountW: "<<l_TcountW<<";"<<endl;
// cerr<<"int l_TcountB: "<<l_TcountB<<";"<<endl;
//}
/*---------------Helper Functions---------------*/
// Put higher utility state prior
bool compareStates(State* left, State* right){
int l = left->score;
int r = right->score;
return l > r;
}
/*--------------END-Helper Functions-END--------*/
/*--Function Prototypes--*/
int MiniMax(State *state, int depth);
int MinVal(State *state,int alpha,int beta,int depth);
int MaxVal(State *state,int alpha,int beta,int depth);
/*--Function Prototypes*/
//returns an index for best action // depth =0 means random player
int MiniMax(State *state, int depth){
int max_value=0;
int max_index=0;
int v;
int alpha = INT_MIN;
int beta = INT_MAX;
vector<State*> children = state->Successors(PLAYER_ID); //own moves
int BranchF = children.size();
if(BranchF<=0){
cerr<<"No Moves to Play!\n";
return 0;
}
//Compute and store utilities of all children for sorting
for(int i=0;i<BranchF;i++)
int temp=children[i]->utility();
//Sort according to utility for better pruning
if(SORT)
sort(children.begin(),children.end(),compareStates);
//set depth based on number of moves
if(DYNAMIC_DEPTH& (!LESS)){
if(children.size()>30) depth = 3;
else if(children.size()>20) depth = 4;
else if(children.size()>10) depth = 5;
if(children.size()<=10) depth = 6;
if(children.size()<3) depth = 7; //8 is too much
}
// cerr<<"\nBranch Factor: "<<children.size()<<endl;
// cerr<<"Depth: "<<depth<<endl;
if(depth <=0){ //Random Player
srand(time(NULL));
return rand()%(children.size());
}
max_value = MinVal(children[0],alpha,beta,depth-1); //put first value in max_value
// cerr<<"Max Initial"<<max_value<<" Index: "<<max_index<<"Utility: "<<children[0]->utility()<<endl;
// children[0]->printBoard();
for(int i=0;i<children.size();i++){
v=MinVal(children[i],alpha,beta,depth-1);
// v=MinVal(children[i],alpha,beta,depth-1);
// alpha = max(alpha,v);
// if (alpha<v){
// alpha = v;
// max_index=i;
// }
// cerr<<"Trying value "<<v<<" Index: "<<i<<"\n "<<endl;
// state->printMove(children[i]->moveIndex);
// cerr<<"Uitlity: "<<children[i]->utility()<<endl;
// children[i]->printBoard();
// cerr<<"v: "<<v<<endl;
//
if(v>max_value){
max_value=v;
max_index=i;
// cerr<<"Max value "<<max_value<<" Index: "<<max_index<<"Utility: "<<children[i]->utility()<<endl;
// children[i]->printBoard();
}
}
//## Can Update weights here
// cerr<<"Max update "<<max_value<<" Index: "<<max_index<<"Utility: "<<children[max]->utility()<<endl;
// cerr<<"Uitlity: "<<children[max_index]->utility()<<endl;
// children[max_index]->printBoard();
// cerr<<"Utility: "<<max_value<<endl;
// state->printMove(children[max_index]->moveIndex);
// cerr<<"(Index, Pre): ("<<max_index<<", "<<children[max_index]->moveIndex<<")\n\n";
return children[max_index]->moveIndex;
}
/*
returns minimum utility value
*/
int MinVal(State *state,int alpha,int beta,int depth){
int child;
// cerr<<"Utility of this state: "<<state->utility()<<endl;
if (/*state->terminal()*/depth <=0) //## can we so with cutoff or need to have different checks for terminal and cutoff nodes??
return state->utility();
vector<State*> children = state->Successors(3-PLAYER_ID); //3 minus; to get other persons move
if(children.size()<=0) //NO Moves left for opponent
return state->utility();
for (int i=0;i<children.size();i++){
child = MaxVal(children[i],alpha,beta,depth-1);
beta = min(beta,child);
if(alpha>=beta)
return child;
}
return beta; //beta
}
/*END MinVal*/
//alpha = the highest value for MAX along the path
//beta = the lowest value for MIN along the path
/*
returns maximum utility value
*/
int MaxVal(State *state, int alpha, int beta,int depth){
int child;
// cerr<<"Utility of this state: "<<state->utility()<<endl;
if (/*state->terminal()*/depth <=0)
return state->utility();
vector<State*> children = state->Successors(PLAYER_ID);
if(children.size()<=0) //NO Moves left
return state->utility();
for (int i=0;i<children.size();i++){
child = MinVal(children[i],alpha,beta,depth-1);
alpha = max(alpha,child);
if (alpha>=beta)
return child;
}
return alpha;
}
| 16,538 | 7,809 |
// Copyright 2022 Trevogin Kirill
#include <tbb/tbb.h>
#include <algorithm>
#include <cmath>
#include <ctime>
#include <iostream>
#include <random>
#include <utility>
#include <vector>
#include "../../../modules/task_3/trevogin_k_hoar_tbb/hoar.h"
#include "gtest/gtest.h"
#define N 100000
TEST(Hoare_Quick_Sort_TBB, Can_Sort_Correctly) {
double* arr = new double[N];
Get_Random_Array(arr, N);
qHoareSortTbb(arr, N);
ASSERT_EQ(1, IsSorted(arr, N));
}
TEST(Hoare_Quick_Sort_TBB, Can_Sort_Empty_Array) {
double* arr = new double[N];
for (int i = 0; i < N; i++) {
arr[i] = 0;
}
qHoareSortTbb(arr, N);
double sum_element = 0.0;
for (int i = 0; i < N; i++) {
sum_element += arr[i];
}
ASSERT_EQ(sum_element, 0);
}
TEST(Hoare_Quick_Sort_TBB, Can_Sort_Opposite_Elements) {
double* arr = new double[N];
Get_Random_Array(arr, N);
for (int i = 0; i < N; i += 2) {
arr[i] = arr[i + 1] * (-1);
}
double* arr2 = new double[N];
Copy_elements(arr, arr2, N);
qHoareSortTbb(arr, N);
qHoareSort(arr2, 0, N - 1);
ASSERT_EQ((int)std::equal(&arr[0], &arr[N], &arr2[0]), 1);
}
TEST(Hoare_Quick_Sort_TBB, Can_Sort_Already_Sorted_Elements) {
double* arr = new double[N];
Get_Random_Array(arr, N);
qHoareSort(arr, 0, N - 1);
double* arr2 = new double[N];
Copy_elements(arr, arr2, N);
qHoareSortTbb(arr, N);
ASSERT_EQ((int)std::equal(&arr[0], &arr[N], &arr2[0]), 1);
}
TEST(Hoare_Quick_Sort_TBB, Can_Sort_Mixed_Array) {
double* arr = new double[N];
Get_Random_Array(arr, N);
qHoareSort(arr, 0, N - 1);
double* arr2 = new double[N];
Copy_elements(arr, arr2, N);
for (int i = 2; i < N; i += 3) {
double temp = arr[i - 2];
arr[i - 2] = arr[i];
arr[i] = temp;
}
qHoareSortTbb(arr, N);
ASSERT_EQ((int)std::equal(&arr[0], &arr[N], &arr2[0]), 1);
}
TEST(Hoare_Quick_Sort_TBB, DISABLED_Compare_Seq_and_Tbb_Average_Time) {
double* arr = new double[N];
double* arr2 = new double[N];
std::vector<bool> sorted;
Get_Random_Array(arr, N);
Copy_elements(arr, arr2, N);
tbb::tick_count t1 = tbb::tick_count::now();
qHoareSort(arr2, 0, N - 1);
double seq_time = (tbb::tick_count::now() - t1).seconds();
std::cout << "Sequential time: " << seq_time << " s" << '\n';
sorted.push_back(IsSorted(arr2, N));
tbb::tick_count t2 = tbb::tick_count::now();
qHoareSortTbb(arr, N);
double parallel_time = (tbb::tick_count::now() - t2).seconds();
std::cout << "Parallel tbb time: " << parallel_time << " s" << '\n';
std::cout << "Acceleration = seqtime/partime = " << seq_time / parallel_time << " " << '\n';
sorted.push_back(IsSorted(arr, N));
bool x = true;
for (auto i : sorted)
x = x && i;
ASSERT_EQ(1, x);
}
int main(int argc, char** argv) {
tbb::task_scheduler_init init(tbb::task_scheduler_init::automatic);
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 3,023 | 1,308 |
/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/audio_processing/audio_processing_impl.h"
#include <assert.h>
#include "webrtc/base/checks.h"
#include "webrtc/base/platform_file.h"
#include "webrtc/common_audio/include/audio_util.h"
#include "webrtc/common_audio/channel_buffer.h"
#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
extern "C" {
#include "webrtc/modules/audio_processing/aec/aec_core.h"
}
#include "webrtc/modules/audio_processing/agc/agc_manager_direct.h"
#include "webrtc/modules/audio_processing/audio_buffer.h"
#include "webrtc/modules/audio_processing/beamformer/nonlinear_beamformer.h"
#include "webrtc/modules/audio_processing/common.h"
#include "webrtc/modules/audio_processing/echo_cancellation_impl.h"
#include "webrtc/modules/audio_processing/echo_control_mobile_impl.h"
#include "webrtc/modules/audio_processing/gain_control_impl.h"
#include "webrtc/modules/audio_processing/high_pass_filter_impl.h"
#include "webrtc/modules/audio_processing/level_estimator_impl.h"
#include "webrtc/modules/audio_processing/noise_suppression_impl.h"
#include "webrtc/modules/audio_processing/processing_component.h"
#include "webrtc/modules/audio_processing/transient/transient_suppressor.h"
#include "webrtc/modules/audio_processing/voice_detection_impl.h"
#include "webrtc/modules/interface/module_common_types.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/file_wrapper.h"
#include "webrtc/system_wrappers/interface/logging.h"
#include "webrtc/system_wrappers/interface/metrics.h"
#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
// Files generated at build-time by the protobuf compiler.
#ifdef WEBRTC_ANDROID_PLATFORM_BUILD
#include "external/webrtc/webrtc/modules/audio_processing/debug.pb.h"
#else
#include "webrtc/audio_processing/debug.pb.h"
#endif
#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
#define RETURN_ON_ERR(expr) \
do { \
int err = (expr); \
if (err != kNoError) { \
return err; \
} \
} while (0)
namespace webrtc {
// Throughout webrtc, it's assumed that success is represented by zero.
static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero");
// This class has two main functionalities:
//
// 1) It is returned instead of the real GainControl after the new AGC has been
// enabled in order to prevent an outside user from overriding compression
// settings. It doesn't do anything in its implementation, except for
// delegating the const methods and Enable calls to the real GainControl, so
// AGC can still be disabled.
//
// 2) It is injected into AgcManagerDirect and implements volume callbacks for
// getting and setting the volume level. It just caches this value to be used
// in VoiceEngine later.
class GainControlForNewAgc : public GainControl, public VolumeCallbacks {
public:
explicit GainControlForNewAgc(GainControlImpl* gain_control)
: real_gain_control_(gain_control),
volume_(0) {
}
// GainControl implementation.
int Enable(bool enable) override {
return real_gain_control_->Enable(enable);
}
bool is_enabled() const override { return real_gain_control_->is_enabled(); }
int set_stream_analog_level(int level) override {
volume_ = level;
return AudioProcessing::kNoError;
}
int stream_analog_level() override { return volume_; }
int set_mode(Mode mode) override { return AudioProcessing::kNoError; }
Mode mode() const override { return GainControl::kAdaptiveAnalog; }
int set_target_level_dbfs(int level) override {
return AudioProcessing::kNoError;
}
int target_level_dbfs() const override {
return real_gain_control_->target_level_dbfs();
}
int set_compression_gain_db(int gain) override {
return AudioProcessing::kNoError;
}
int compression_gain_db() const override {
return real_gain_control_->compression_gain_db();
}
int enable_limiter(bool enable) override { return AudioProcessing::kNoError; }
bool is_limiter_enabled() const override {
return real_gain_control_->is_limiter_enabled();
}
int set_analog_level_limits(int minimum, int maximum) override {
return AudioProcessing::kNoError;
}
int analog_level_minimum() const override {
return real_gain_control_->analog_level_minimum();
}
int analog_level_maximum() const override {
return real_gain_control_->analog_level_maximum();
}
bool stream_is_saturated() const override {
return real_gain_control_->stream_is_saturated();
}
// VolumeCallbacks implementation.
void SetMicVolume(int volume) override { volume_ = volume; }
int GetMicVolume() override { return volume_; }
private:
GainControl* real_gain_control_;
int volume_;
};
AudioProcessing* AudioProcessing::Create() {
Config config;
return Create(config, nullptr);
}
AudioProcessing* AudioProcessing::Create(const Config& config) {
return Create(config, nullptr);
}
AudioProcessing* AudioProcessing::Create(const Config& config,
Beamformer<float>* beamformer) {
AudioProcessingImpl* apm = new AudioProcessingImpl(config, beamformer);
if (apm->Initialize() != kNoError) {
delete apm;
apm = NULL;
}
return apm;
}
AudioProcessingImpl::AudioProcessingImpl(const Config& config)
: AudioProcessingImpl(config, nullptr) {}
AudioProcessingImpl::AudioProcessingImpl(const Config& config,
Beamformer<float>* beamformer)
: echo_cancellation_(NULL),
echo_control_mobile_(NULL),
gain_control_(NULL),
high_pass_filter_(NULL),
level_estimator_(NULL),
noise_suppression_(NULL),
voice_detection_(NULL),
crit_(CriticalSectionWrapper::CreateCriticalSection()),
#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
debug_file_(FileWrapper::Create()),
event_msg_(new audioproc::Event()),
#endif
fwd_in_format_(kSampleRate16kHz, 1),
fwd_proc_format_(kSampleRate16kHz),
fwd_out_format_(kSampleRate16kHz, 1),
rev_in_format_(kSampleRate16kHz, 1),
rev_proc_format_(kSampleRate16kHz, 1),
split_rate_(kSampleRate16kHz),
stream_delay_ms_(0),
delay_offset_ms_(0),
was_stream_delay_set_(false),
last_stream_delay_ms_(0),
last_aec_system_delay_ms_(0),
output_will_be_muted_(false),
key_pressed_(false),
#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
use_new_agc_(false),
#else
use_new_agc_(config.Get<ExperimentalAgc>().enabled),
#endif
agc_startup_min_volume_(config.Get<ExperimentalAgc>().startup_min_volume),
#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)
transient_suppressor_enabled_(false),
#else
transient_suppressor_enabled_(config.Get<ExperimentalNs>().enabled),
#endif
beamformer_enabled_(config.Get<Beamforming>().enabled),
beamformer_(beamformer),
array_geometry_(config.Get<Beamforming>().array_geometry),
supports_48kHz_(config.Get<AudioProcessing48kHzSupport>().enabled) {
echo_cancellation_ = new EchoCancellationImpl(this, crit_);
component_list_.push_back(echo_cancellation_);
echo_control_mobile_ = new EchoControlMobileImpl(this, crit_);
component_list_.push_back(echo_control_mobile_);
gain_control_ = new GainControlImpl(this, crit_);
component_list_.push_back(gain_control_);
high_pass_filter_ = new HighPassFilterImpl(this, crit_);
component_list_.push_back(high_pass_filter_);
level_estimator_ = new LevelEstimatorImpl(this, crit_);
component_list_.push_back(level_estimator_);
noise_suppression_ = new NoiseSuppressionImpl(this, crit_);
component_list_.push_back(noise_suppression_);
voice_detection_ = new VoiceDetectionImpl(this, crit_);
component_list_.push_back(voice_detection_);
gain_control_for_new_agc_.reset(new GainControlForNewAgc(gain_control_));
SetExtraOptions(config);
}
AudioProcessingImpl::~AudioProcessingImpl() {
{
CriticalSectionScoped crit_scoped(crit_);
// Depends on gain_control_ and gain_control_for_new_agc_.
agc_manager_.reset();
// Depends on gain_control_.
gain_control_for_new_agc_.reset();
while (!component_list_.empty()) {
ProcessingComponent* component = component_list_.front();
component->Destroy();
delete component;
component_list_.pop_front();
}
#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
if (debug_file_->Open()) {
debug_file_->CloseFile();
}
#endif
}
delete crit_;
crit_ = NULL;
}
int AudioProcessingImpl::Initialize() {
CriticalSectionScoped crit_scoped(crit_);
return InitializeLocked();
}
int AudioProcessingImpl::set_sample_rate_hz(int rate) {
CriticalSectionScoped crit_scoped(crit_);
return InitializeLocked(rate,
rate,
rev_in_format_.rate(),
fwd_in_format_.num_channels(),
fwd_out_format_.num_channels(),
rev_in_format_.num_channels());
}
int AudioProcessingImpl::Initialize(int input_sample_rate_hz,
int output_sample_rate_hz,
int reverse_sample_rate_hz,
ChannelLayout input_layout,
ChannelLayout output_layout,
ChannelLayout reverse_layout) {
CriticalSectionScoped crit_scoped(crit_);
return InitializeLocked(input_sample_rate_hz,
output_sample_rate_hz,
reverse_sample_rate_hz,
ChannelsFromLayout(input_layout),
ChannelsFromLayout(output_layout),
ChannelsFromLayout(reverse_layout));
}
int AudioProcessingImpl::InitializeLocked() {
const int fwd_audio_buffer_channels = beamformer_enabled_ ?
fwd_in_format_.num_channels() :
fwd_out_format_.num_channels();
render_audio_.reset(new AudioBuffer(rev_in_format_.samples_per_channel(),
rev_in_format_.num_channels(),
rev_proc_format_.samples_per_channel(),
rev_proc_format_.num_channels(),
rev_proc_format_.samples_per_channel()));
capture_audio_.reset(new AudioBuffer(fwd_in_format_.samples_per_channel(),
fwd_in_format_.num_channels(),
fwd_proc_format_.samples_per_channel(),
fwd_audio_buffer_channels,
fwd_out_format_.samples_per_channel()));
// Initialize all components.
for (auto item : component_list_) {
int err = item->Initialize();
if (err != kNoError) {
return err;
}
}
InitializeExperimentalAgc();
InitializeTransient();
InitializeBeamformer();
#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
if (debug_file_->Open()) {
int err = WriteInitMessage();
if (err != kNoError) {
return err;
}
}
#endif
return kNoError;
}
int AudioProcessingImpl::InitializeLocked(int input_sample_rate_hz,
int output_sample_rate_hz,
int reverse_sample_rate_hz,
int num_input_channels,
int num_output_channels,
int num_reverse_channels) {
if (input_sample_rate_hz <= 0 ||
output_sample_rate_hz <= 0 ||
reverse_sample_rate_hz <= 0) {
return kBadSampleRateError;
}
if (num_output_channels > num_input_channels) {
return kBadNumberChannelsError;
}
// Only mono and stereo supported currently.
if (num_input_channels > 2 || num_input_channels < 1 ||
num_output_channels > 2 || num_output_channels < 1 ||
num_reverse_channels > 2 || num_reverse_channels < 1) {
return kBadNumberChannelsError;
}
if (beamformer_enabled_ &&
(static_cast<size_t>(num_input_channels) != array_geometry_.size() ||
num_output_channels > 1)) {
return kBadNumberChannelsError;
}
fwd_in_format_.set(input_sample_rate_hz, num_input_channels);
fwd_out_format_.set(output_sample_rate_hz, num_output_channels);
rev_in_format_.set(reverse_sample_rate_hz, num_reverse_channels);
// We process at the closest native rate >= min(input rate, output rate)...
int min_proc_rate = std::min(fwd_in_format_.rate(), fwd_out_format_.rate());
int fwd_proc_rate;
if (supports_48kHz_ && min_proc_rate > kSampleRate32kHz) {
fwd_proc_rate = kSampleRate48kHz;
} else if (min_proc_rate > kSampleRate16kHz) {
fwd_proc_rate = kSampleRate32kHz;
} else if (min_proc_rate > kSampleRate8kHz) {
fwd_proc_rate = kSampleRate16kHz;
} else {
fwd_proc_rate = kSampleRate8kHz;
}
// ...with one exception.
if (echo_control_mobile_->is_enabled() && min_proc_rate > kSampleRate16kHz) {
fwd_proc_rate = kSampleRate16kHz;
}
fwd_proc_format_.set(fwd_proc_rate);
// We normally process the reverse stream at 16 kHz. Unless...
int rev_proc_rate = kSampleRate16kHz;
if (fwd_proc_format_.rate() == kSampleRate8kHz) {
// ...the forward stream is at 8 kHz.
rev_proc_rate = kSampleRate8kHz;
} else {
if (rev_in_format_.rate() == kSampleRate32kHz) {
// ...or the input is at 32 kHz, in which case we use the splitting
// filter rather than the resampler.
rev_proc_rate = kSampleRate32kHz;
}
}
// Always downmix the reverse stream to mono for analysis. This has been
// demonstrated to work well for AEC in most practical scenarios.
rev_proc_format_.set(rev_proc_rate, 1);
if (fwd_proc_format_.rate() == kSampleRate32kHz ||
fwd_proc_format_.rate() == kSampleRate48kHz) {
split_rate_ = kSampleRate16kHz;
} else {
split_rate_ = fwd_proc_format_.rate();
}
return InitializeLocked();
}
// Calls InitializeLocked() if any of the audio parameters have changed from
// their current values.
int AudioProcessingImpl::MaybeInitializeLocked(int input_sample_rate_hz,
int output_sample_rate_hz,
int reverse_sample_rate_hz,
int num_input_channels,
int num_output_channels,
int num_reverse_channels) {
if (input_sample_rate_hz == fwd_in_format_.rate() &&
output_sample_rate_hz == fwd_out_format_.rate() &&
reverse_sample_rate_hz == rev_in_format_.rate() &&
num_input_channels == fwd_in_format_.num_channels() &&
num_output_channels == fwd_out_format_.num_channels() &&
num_reverse_channels == rev_in_format_.num_channels()) {
return kNoError;
}
return InitializeLocked(input_sample_rate_hz,
output_sample_rate_hz,
reverse_sample_rate_hz,
num_input_channels,
num_output_channels,
num_reverse_channels);
}
void AudioProcessingImpl::SetExtraOptions(const Config& config) {
CriticalSectionScoped crit_scoped(crit_);
for (auto item : component_list_) {
item->SetExtraOptions(config);
}
if (transient_suppressor_enabled_ != config.Get<ExperimentalNs>().enabled) {
transient_suppressor_enabled_ = config.Get<ExperimentalNs>().enabled;
InitializeTransient();
}
}
int AudioProcessingImpl::input_sample_rate_hz() const {
CriticalSectionScoped crit_scoped(crit_);
return fwd_in_format_.rate();
}
int AudioProcessingImpl::sample_rate_hz() const {
CriticalSectionScoped crit_scoped(crit_);
return fwd_in_format_.rate();
}
int AudioProcessingImpl::proc_sample_rate_hz() const {
return fwd_proc_format_.rate();
}
int AudioProcessingImpl::proc_split_sample_rate_hz() const {
return split_rate_;
}
int AudioProcessingImpl::num_reverse_channels() const {
return rev_proc_format_.num_channels();
}
int AudioProcessingImpl::num_input_channels() const {
return fwd_in_format_.num_channels();
}
int AudioProcessingImpl::num_output_channels() const {
return fwd_out_format_.num_channels();
}
void AudioProcessingImpl::set_output_will_be_muted(bool muted) {
CriticalSectionScoped lock(crit_);
output_will_be_muted_ = muted;
if (agc_manager_.get()) {
agc_manager_->SetCaptureMuted(output_will_be_muted_);
}
}
bool AudioProcessingImpl::output_will_be_muted() const {
CriticalSectionScoped lock(crit_);
return output_will_be_muted_;
}
int AudioProcessingImpl::ProcessStream(const float* const* src,
int samples_per_channel,
int input_sample_rate_hz,
ChannelLayout input_layout,
int output_sample_rate_hz,
ChannelLayout output_layout,
float* const* dest) {
CriticalSectionScoped crit_scoped(crit_);
if (!src || !dest) {
return kNullPointerError;
}
RETURN_ON_ERR(MaybeInitializeLocked(input_sample_rate_hz,
output_sample_rate_hz,
rev_in_format_.rate(),
ChannelsFromLayout(input_layout),
ChannelsFromLayout(output_layout),
rev_in_format_.num_channels()));
if (samples_per_channel != fwd_in_format_.samples_per_channel()) {
return kBadDataLengthError;
}
#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
if (debug_file_->Open()) {
event_msg_->set_type(audioproc::Event::STREAM);
audioproc::Stream* msg = event_msg_->mutable_stream();
const size_t channel_size =
sizeof(float) * fwd_in_format_.samples_per_channel();
for (int i = 0; i < fwd_in_format_.num_channels(); ++i)
msg->add_input_channel(src[i], channel_size);
}
#endif
capture_audio_->CopyFrom(src, samples_per_channel, input_layout);
RETURN_ON_ERR(ProcessStreamLocked());
capture_audio_->CopyTo(fwd_out_format_.samples_per_channel(),
output_layout,
dest);
#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
if (debug_file_->Open()) {
audioproc::Stream* msg = event_msg_->mutable_stream();
const size_t channel_size =
sizeof(float) * fwd_out_format_.samples_per_channel();
for (int i = 0; i < fwd_out_format_.num_channels(); ++i)
msg->add_output_channel(dest[i], channel_size);
RETURN_ON_ERR(WriteMessageToDebugFile());
}
#endif
return kNoError;
}
int AudioProcessingImpl::ProcessStream(AudioFrame* frame) {
CriticalSectionScoped crit_scoped(crit_);
if (!frame) {
return kNullPointerError;
}
// Must be a native rate.
if (frame->sample_rate_hz_ != kSampleRate8kHz &&
frame->sample_rate_hz_ != kSampleRate16kHz &&
frame->sample_rate_hz_ != kSampleRate32kHz &&
frame->sample_rate_hz_ != kSampleRate48kHz) {
return kBadSampleRateError;
}
if (echo_control_mobile_->is_enabled() &&
frame->sample_rate_hz_ > kSampleRate16kHz) {
LOG(LS_ERROR) << "AECM only supports 16 or 8 kHz sample rates";
return kUnsupportedComponentError;
}
// TODO(ajm): The input and output rates and channels are currently
// constrained to be identical in the int16 interface.
RETURN_ON_ERR(MaybeInitializeLocked(frame->sample_rate_hz_,
frame->sample_rate_hz_,
rev_in_format_.rate(),
frame->num_channels_,
frame->num_channels_,
rev_in_format_.num_channels()));
if (frame->samples_per_channel_ != fwd_in_format_.samples_per_channel()) {
return kBadDataLengthError;
}
#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
if (debug_file_->Open()) {
event_msg_->set_type(audioproc::Event::STREAM);
audioproc::Stream* msg = event_msg_->mutable_stream();
const size_t data_size = sizeof(int16_t) *
frame->samples_per_channel_ *
frame->num_channels_;
msg->set_input_data(frame->data_, data_size);
}
#endif
capture_audio_->DeinterleaveFrom(frame);
RETURN_ON_ERR(ProcessStreamLocked());
capture_audio_->InterleaveTo(frame, output_copy_needed(is_data_processed()));
#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
if (debug_file_->Open()) {
audioproc::Stream* msg = event_msg_->mutable_stream();
const size_t data_size = sizeof(int16_t) *
frame->samples_per_channel_ *
frame->num_channels_;
msg->set_output_data(frame->data_, data_size);
RETURN_ON_ERR(WriteMessageToDebugFile());
}
#endif
return kNoError;
}
int AudioProcessingImpl::ProcessStreamLocked() {
#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
if (debug_file_->Open()) {
audioproc::Stream* msg = event_msg_->mutable_stream();
msg->set_delay(stream_delay_ms_);
msg->set_drift(echo_cancellation_->stream_drift_samples());
msg->set_level(gain_control()->stream_analog_level());
msg->set_keypress(key_pressed_);
}
#endif
MaybeUpdateHistograms();
AudioBuffer* ca = capture_audio_.get(); // For brevity.
if (use_new_agc_ && gain_control_->is_enabled()) {
agc_manager_->AnalyzePreProcess(ca->channels()[0],
ca->num_channels(),
fwd_proc_format_.samples_per_channel());
}
bool data_processed = is_data_processed();
if (analysis_needed(data_processed)) {
ca->SplitIntoFrequencyBands();
}
if (beamformer_enabled_) {
beamformer_->ProcessChunk(*ca->split_data_f(), ca->split_data_f());
ca->set_num_channels(1);
}
RETURN_ON_ERR(high_pass_filter_->ProcessCaptureAudio(ca));
RETURN_ON_ERR(gain_control_->AnalyzeCaptureAudio(ca));
RETURN_ON_ERR(noise_suppression_->AnalyzeCaptureAudio(ca));
RETURN_ON_ERR(echo_cancellation_->ProcessCaptureAudio(ca));
if (echo_control_mobile_->is_enabled() && noise_suppression_->is_enabled()) {
ca->CopyLowPassToReference();
}
RETURN_ON_ERR(noise_suppression_->ProcessCaptureAudio(ca));
RETURN_ON_ERR(echo_control_mobile_->ProcessCaptureAudio(ca));
RETURN_ON_ERR(voice_detection_->ProcessCaptureAudio(ca));
if (use_new_agc_ &&
gain_control_->is_enabled() &&
(!beamformer_enabled_ || beamformer_->is_target_present())) {
agc_manager_->Process(ca->split_bands_const(0)[kBand0To8kHz],
ca->num_frames_per_band(),
split_rate_);
}
RETURN_ON_ERR(gain_control_->ProcessCaptureAudio(ca));
if (synthesis_needed(data_processed)) {
ca->MergeFrequencyBands();
}
// TODO(aluebs): Investigate if the transient suppression placement should be
// before or after the AGC.
if (transient_suppressor_enabled_) {
float voice_probability =
agc_manager_.get() ? agc_manager_->voice_probability() : 1.f;
transient_suppressor_->Suppress(ca->channels_f()[0],
ca->num_frames(),
ca->num_channels(),
ca->split_bands_const_f(0)[kBand0To8kHz],
ca->num_frames_per_band(),
ca->keyboard_data(),
ca->num_keyboard_frames(),
voice_probability,
key_pressed_);
}
// The level estimator operates on the recombined data.
RETURN_ON_ERR(level_estimator_->ProcessStream(ca));
was_stream_delay_set_ = false;
return kNoError;
}
int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data,
int samples_per_channel,
int sample_rate_hz,
ChannelLayout layout) {
CriticalSectionScoped crit_scoped(crit_);
if (data == NULL) {
return kNullPointerError;
}
const int num_channels = ChannelsFromLayout(layout);
RETURN_ON_ERR(MaybeInitializeLocked(fwd_in_format_.rate(),
fwd_out_format_.rate(),
sample_rate_hz,
fwd_in_format_.num_channels(),
fwd_out_format_.num_channels(),
num_channels));
if (samples_per_channel != rev_in_format_.samples_per_channel()) {
return kBadDataLengthError;
}
#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
if (debug_file_->Open()) {
event_msg_->set_type(audioproc::Event::REVERSE_STREAM);
audioproc::ReverseStream* msg = event_msg_->mutable_reverse_stream();
const size_t channel_size =
sizeof(float) * rev_in_format_.samples_per_channel();
for (int i = 0; i < num_channels; ++i)
msg->add_channel(data[i], channel_size);
RETURN_ON_ERR(WriteMessageToDebugFile());
}
#endif
render_audio_->CopyFrom(data, samples_per_channel, layout);
return AnalyzeReverseStreamLocked();
}
int AudioProcessingImpl::AnalyzeReverseStream(AudioFrame* frame) {
CriticalSectionScoped crit_scoped(crit_);
if (frame == NULL) {
return kNullPointerError;
}
// Must be a native rate.
if (frame->sample_rate_hz_ != kSampleRate8kHz &&
frame->sample_rate_hz_ != kSampleRate16kHz &&
frame->sample_rate_hz_ != kSampleRate32kHz &&
frame->sample_rate_hz_ != kSampleRate48kHz) {
return kBadSampleRateError;
}
// This interface does not tolerate different forward and reverse rates.
if (frame->sample_rate_hz_ != fwd_in_format_.rate()) {
return kBadSampleRateError;
}
RETURN_ON_ERR(MaybeInitializeLocked(fwd_in_format_.rate(),
fwd_out_format_.rate(),
frame->sample_rate_hz_,
fwd_in_format_.num_channels(),
fwd_in_format_.num_channels(),
frame->num_channels_));
if (frame->samples_per_channel_ != rev_in_format_.samples_per_channel()) {
return kBadDataLengthError;
}
#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
if (debug_file_->Open()) {
event_msg_->set_type(audioproc::Event::REVERSE_STREAM);
audioproc::ReverseStream* msg = event_msg_->mutable_reverse_stream();
const size_t data_size = sizeof(int16_t) *
frame->samples_per_channel_ *
frame->num_channels_;
msg->set_data(frame->data_, data_size);
RETURN_ON_ERR(WriteMessageToDebugFile());
}
#endif
render_audio_->DeinterleaveFrom(frame);
return AnalyzeReverseStreamLocked();
}
int AudioProcessingImpl::AnalyzeReverseStreamLocked() {
AudioBuffer* ra = render_audio_.get(); // For brevity.
if (rev_proc_format_.rate() == kSampleRate32kHz) {
ra->SplitIntoFrequencyBands();
}
RETURN_ON_ERR(echo_cancellation_->ProcessRenderAudio(ra));
RETURN_ON_ERR(echo_control_mobile_->ProcessRenderAudio(ra));
if (!use_new_agc_) {
RETURN_ON_ERR(gain_control_->ProcessRenderAudio(ra));
}
return kNoError;
}
int AudioProcessingImpl::set_stream_delay_ms(int delay) {
Error retval = kNoError;
was_stream_delay_set_ = true;
delay += delay_offset_ms_;
if (delay < 0) {
delay = 0;
retval = kBadStreamParameterWarning;
}
// TODO(ajm): the max is rather arbitrarily chosen; investigate.
if (delay > 500) {
delay = 500;
retval = kBadStreamParameterWarning;
}
stream_delay_ms_ = delay;
return retval;
}
int AudioProcessingImpl::stream_delay_ms() const {
return stream_delay_ms_;
}
bool AudioProcessingImpl::was_stream_delay_set() const {
return was_stream_delay_set_;
}
void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) {
key_pressed_ = key_pressed;
}
bool AudioProcessingImpl::stream_key_pressed() const {
return key_pressed_;
}
void AudioProcessingImpl::set_delay_offset_ms(int offset) {
CriticalSectionScoped crit_scoped(crit_);
delay_offset_ms_ = offset;
}
int AudioProcessingImpl::delay_offset_ms() const {
return delay_offset_ms_;
}
int AudioProcessingImpl::StartDebugRecording(
const char filename[AudioProcessing::kMaxFilenameSize]) {
CriticalSectionScoped crit_scoped(crit_);
static_assert(kMaxFilenameSize == FileWrapper::kMaxFileNameSize, "");
if (filename == NULL) {
return kNullPointerError;
}
#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
// Stop any ongoing recording.
if (debug_file_->Open()) {
if (debug_file_->CloseFile() == -1) {
return kFileError;
}
}
if (debug_file_->OpenFile(filename, false) == -1) {
debug_file_->CloseFile();
return kFileError;
}
int err = WriteInitMessage();
if (err != kNoError) {
return err;
}
return kNoError;
#else
return kUnsupportedFunctionError;
#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
}
int AudioProcessingImpl::StartDebugRecording(FILE* handle) {
CriticalSectionScoped crit_scoped(crit_);
if (handle == NULL) {
return kNullPointerError;
}
#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
// Stop any ongoing recording.
if (debug_file_->Open()) {
if (debug_file_->CloseFile() == -1) {
return kFileError;
}
}
if (debug_file_->OpenFromFileHandle(handle, true, false) == -1) {
return kFileError;
}
int err = WriteInitMessage();
if (err != kNoError) {
return err;
}
return kNoError;
#else
return kUnsupportedFunctionError;
#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
}
int AudioProcessingImpl::StartDebugRecordingForPlatformFile(
rtc::PlatformFile handle) {
FILE* stream = rtc::FdopenPlatformFileForWriting(handle);
return StartDebugRecording(stream);
}
int AudioProcessingImpl::StopDebugRecording() {
CriticalSectionScoped crit_scoped(crit_);
#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
// We just return if recording hasn't started.
if (debug_file_->Open()) {
if (debug_file_->CloseFile() == -1) {
return kFileError;
}
}
return kNoError;
#else
return kUnsupportedFunctionError;
#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
}
EchoCancellation* AudioProcessingImpl::echo_cancellation() const {
return echo_cancellation_;
}
EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const {
return echo_control_mobile_;
}
GainControl* AudioProcessingImpl::gain_control() const {
if (use_new_agc_) {
return gain_control_for_new_agc_.get();
}
return gain_control_;
}
HighPassFilter* AudioProcessingImpl::high_pass_filter() const {
return high_pass_filter_;
}
LevelEstimator* AudioProcessingImpl::level_estimator() const {
return level_estimator_;
}
NoiseSuppression* AudioProcessingImpl::noise_suppression() const {
return noise_suppression_;
}
VoiceDetection* AudioProcessingImpl::voice_detection() const {
return voice_detection_;
}
bool AudioProcessingImpl::is_data_processed() const {
if (beamformer_enabled_) {
return true;
}
int enabled_count = 0;
for (auto item : component_list_) {
if (item->is_component_enabled()) {
enabled_count++;
}
}
// Data is unchanged if no components are enabled, or if only level_estimator_
// or voice_detection_ is enabled.
if (enabled_count == 0) {
return false;
} else if (enabled_count == 1) {
if (level_estimator_->is_enabled() || voice_detection_->is_enabled()) {
return false;
}
} else if (enabled_count == 2) {
if (level_estimator_->is_enabled() && voice_detection_->is_enabled()) {
return false;
}
}
return true;
}
bool AudioProcessingImpl::output_copy_needed(bool is_data_processed) const {
// Check if we've upmixed or downmixed the audio.
return ((fwd_out_format_.num_channels() != fwd_in_format_.num_channels()) ||
is_data_processed || transient_suppressor_enabled_);
}
bool AudioProcessingImpl::synthesis_needed(bool is_data_processed) const {
return (is_data_processed && (fwd_proc_format_.rate() == kSampleRate32kHz ||
fwd_proc_format_.rate() == kSampleRate48kHz));
}
bool AudioProcessingImpl::analysis_needed(bool is_data_processed) const {
if (!is_data_processed && !voice_detection_->is_enabled() &&
!transient_suppressor_enabled_) {
// Only level_estimator_ is enabled.
return false;
} else if (fwd_proc_format_.rate() == kSampleRate32kHz ||
fwd_proc_format_.rate() == kSampleRate48kHz) {
// Something besides level_estimator_ is enabled, and we have super-wb.
return true;
}
return false;
}
void AudioProcessingImpl::InitializeExperimentalAgc() {
if (use_new_agc_) {
if (!agc_manager_.get()) {
agc_manager_.reset(new AgcManagerDirect(gain_control_,
gain_control_for_new_agc_.get(),
agc_startup_min_volume_));
}
agc_manager_->Initialize();
agc_manager_->SetCaptureMuted(output_will_be_muted_);
}
}
void AudioProcessingImpl::InitializeTransient() {
if (transient_suppressor_enabled_) {
if (!transient_suppressor_.get()) {
transient_suppressor_.reset(new TransientSuppressor());
}
transient_suppressor_->Initialize(fwd_proc_format_.rate(),
split_rate_,
fwd_out_format_.num_channels());
}
}
void AudioProcessingImpl::InitializeBeamformer() {
if (beamformer_enabled_) {
if (!beamformer_) {
beamformer_.reset(new NonlinearBeamformer(array_geometry_));
}
beamformer_->Initialize(kChunkSizeMs, split_rate_);
}
}
void AudioProcessingImpl::MaybeUpdateHistograms() {
static const int kMinDiffDelayMs = 60;
if (echo_cancellation()->is_enabled()) {
// Detect a jump in platform reported system delay and log the difference.
const int diff_stream_delay_ms = stream_delay_ms_ - last_stream_delay_ms_;
if (diff_stream_delay_ms > kMinDiffDelayMs && last_stream_delay_ms_ != 0) {
RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump",
diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100);
}
last_stream_delay_ms_ = stream_delay_ms_;
// Detect a jump in AEC system delay and log the difference.
const int frames_per_ms = rtc::CheckedDivExact(split_rate_, 1000);
const int aec_system_delay_ms =
WebRtcAec_system_delay(echo_cancellation()->aec_core()) / frames_per_ms;
const int diff_aec_system_delay_ms = aec_system_delay_ms -
last_aec_system_delay_ms_;
if (diff_aec_system_delay_ms > kMinDiffDelayMs &&
last_aec_system_delay_ms_ != 0) {
RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump",
diff_aec_system_delay_ms, kMinDiffDelayMs, 1000,
100);
}
last_aec_system_delay_ms_ = aec_system_delay_ms;
// TODO(bjornv): Consider also logging amount of jumps. This gives a better
// indication of how frequent jumps are.
}
}
#ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP
int AudioProcessingImpl::WriteMessageToDebugFile() {
int32_t size = event_msg_->ByteSize();
if (size <= 0) {
return kUnspecifiedError;
}
#if defined(WEBRTC_ARCH_BIG_ENDIAN)
// TODO(ajm): Use little-endian "on the wire". For the moment, we can be
// pretty safe in assuming little-endian.
#endif
if (!event_msg_->SerializeToString(&event_str_)) {
return kUnspecifiedError;
}
// Write message preceded by its size.
if (!debug_file_->Write(&size, sizeof(int32_t))) {
return kFileError;
}
if (!debug_file_->Write(event_str_.data(), event_str_.length())) {
return kFileError;
}
event_msg_->Clear();
return kNoError;
}
int AudioProcessingImpl::WriteInitMessage() {
event_msg_->set_type(audioproc::Event::INIT);
audioproc::Init* msg = event_msg_->mutable_init();
msg->set_sample_rate(fwd_in_format_.rate());
msg->set_num_input_channels(fwd_in_format_.num_channels());
msg->set_num_output_channels(fwd_out_format_.num_channels());
msg->set_num_reverse_channels(rev_in_format_.num_channels());
msg->set_reverse_sample_rate(rev_in_format_.rate());
msg->set_output_sample_rate(fwd_out_format_.rate());
int err = WriteMessageToDebugFile();
if (err != kNoError) {
return err;
}
return kNoError;
}
#endif // WEBRTC_AUDIOPROC_DEBUG_DUMP
} // namespace webrtc
| 37,123 | 12,227 |
//===--- SarifDiagnostics.cpp - Sarif Diagnostics for Paths -----*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines the SarifDiagnostics object.
//
//===----------------------------------------------------------------------===//
#include "clang/Basic/Version.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
#include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/Support/JSON.h"
#include "llvm/Support/Path.h"
using namespace llvm;
using namespace clang;
using namespace ento;
namespace {
class SarifDiagnostics : public PathDiagnosticConsumer {
std::string OutputFile;
public:
SarifDiagnostics(AnalyzerOptions &, const std::string &Output)
: OutputFile(Output) {}
~SarifDiagnostics() override = default;
void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
FilesMade *FM) override;
StringRef getName() const override { return "SarifDiagnostics"; }
PathGenerationScheme getGenerationScheme() const override { return Minimal; }
bool supportsLogicalOpControlFlow() const override { return true; }
bool supportsCrossFileDiagnostics() const override { return true; }
};
} // end anonymous namespace
void ento::createSarifDiagnosticConsumer(
AnalyzerOptions &AnalyzerOpts, PathDiagnosticConsumers &C,
const std::string &Output, const Preprocessor &,
const cross_tu::CrossTranslationUnitContext &) {
C.push_back(new SarifDiagnostics(AnalyzerOpts, Output));
}
static StringRef getFileName(const FileEntry &FE) {
StringRef Filename = FE.tryGetRealPathName();
if (Filename.empty())
Filename = FE.getName();
return Filename;
}
static std::string percentEncodeURICharacter(char C) {
// RFC 3986 claims alpha, numeric, and this handful of
// characters are not reserved for the path component and
// should be written out directly. Otherwise, percent
// encode the character and write that out instead of the
// reserved character.
if (llvm::isAlnum(C) ||
StringRef::npos != StringRef("-._~:@!$&'()*+,;=").find(C))
return std::string(&C, 1);
return "%" + llvm::toHex(StringRef(&C, 1));
}
static std::string fileNameToURI(StringRef Filename) {
llvm::SmallString<32> Ret = StringRef("file://");
// Get the root name to see if it has a URI authority.
StringRef Root = sys::path::root_name(Filename);
if (Root.startswith("//")) {
// There is an authority, so add it to the URI.
Ret += Root.drop_front(2).str();
} else if (!Root.empty()) {
// There is no authority, so end the component and add the root to the URI.
Ret += Twine("/" + Root).str();
}
auto Iter = sys::path::begin(Filename), End = sys::path::end(Filename);
assert(Iter != End && "Expected there to be a non-root path component.");
// Add the rest of the path components, encoding any reserved characters;
// we skip past the first path component, as it was handled it above.
std::for_each(++Iter, End, [&Ret](StringRef Component) {
// For reasons unknown to me, we may get a backslash with Windows native
// paths for the initial backslash following the drive component, which
// we need to ignore as a URI path part.
if (Component == "\\")
return;
// Add the separator between the previous path part and the one being
// currently processed.
Ret += "/";
// URI encode the part.
for (char C : Component) {
Ret += percentEncodeURICharacter(C);
}
});
return Ret.str().str();
}
static json::Object createFileLocation(const FileEntry &FE) {
return json::Object{{"uri", fileNameToURI(getFileName(FE))}};
}
static json::Object createFile(const FileEntry &FE) {
return json::Object{{"fileLocation", createFileLocation(FE)},
{"roles", json::Array{"resultFile"}},
{"length", FE.getSize()},
{"mimeType", "text/plain"}};
}
static json::Object createFileLocation(const FileEntry &FE,
json::Array &Files) {
std::string FileURI = fileNameToURI(getFileName(FE));
// See if the Files array contains this URI already. If it does not, create
// a new file object to add to the array.
auto I = llvm::find_if(Files, [&](const json::Value &File) {
if (const json::Object *Obj = File.getAsObject()) {
if (const json::Object *FileLoc = Obj->getObject("fileLocation")) {
Optional<StringRef> URI = FileLoc->getString("uri");
return URI && URI->equals(FileURI);
}
}
return false;
});
// Calculate the index within the file location array so it can be stored in
// the JSON object.
auto Index = static_cast<unsigned>(std::distance(Files.begin(), I));
if (I == Files.end())
Files.push_back(createFile(FE));
return json::Object{{"uri", FileURI}, {"fileIndex", Index}};
}
static json::Object createTextRegion(SourceRange R, const SourceManager &SM) {
return json::Object{
{"startLine", SM.getExpansionLineNumber(R.getBegin())},
{"endLine", SM.getExpansionLineNumber(R.getEnd())},
{"startColumn", SM.getExpansionColumnNumber(R.getBegin())},
{"endColumn", SM.getExpansionColumnNumber(R.getEnd())}};
}
static json::Object createPhysicalLocation(SourceRange R, const FileEntry &FE,
const SourceManager &SMgr,
json::Array &Files) {
return json::Object{{{"fileLocation", createFileLocation(FE, Files)},
{"region", createTextRegion(R, SMgr)}}};
}
enum class Importance { Important, Essential, Unimportant };
static StringRef importanceToStr(Importance I) {
switch (I) {
case Importance::Important:
return "important";
case Importance::Essential:
return "essential";
case Importance::Unimportant:
return "unimportant";
}
llvm_unreachable("Fully covered switch is not so fully covered");
}
static json::Object createThreadFlowLocation(json::Object &&Location,
Importance I) {
return json::Object{{"location", std::move(Location)},
{"importance", importanceToStr(I)}};
}
static json::Object createMessage(StringRef Text) {
return json::Object{{"text", Text.str()}};
}
static json::Object createLocation(json::Object &&PhysicalLocation,
StringRef Message = "") {
json::Object Ret{{"physicalLocation", std::move(PhysicalLocation)}};
if (!Message.empty())
Ret.insert({"message", createMessage(Message)});
return Ret;
}
static Importance calculateImportance(const PathDiagnosticPiece &Piece) {
switch (Piece.getKind()) {
case PathDiagnosticPiece::Call:
case PathDiagnosticPiece::Macro:
case PathDiagnosticPiece::Note:
case PathDiagnosticPiece::PopUp:
// FIXME: What should be reported here?
break;
case PathDiagnosticPiece::Event:
return Piece.getTagStr() == "ConditionBRVisitor" ? Importance::Important
: Importance::Essential;
case PathDiagnosticPiece::ControlFlow:
return Importance::Unimportant;
}
return Importance::Unimportant;
}
static json::Object createThreadFlow(const PathPieces &Pieces,
json::Array &Files) {
const SourceManager &SMgr = Pieces.front()->getLocation().getManager();
json::Array Locations;
for (const auto &Piece : Pieces) {
const PathDiagnosticLocation &P = Piece->getLocation();
Locations.push_back(createThreadFlowLocation(
createLocation(createPhysicalLocation(P.asRange(),
*P.asLocation().getFileEntry(),
SMgr, Files),
Piece->getString()),
calculateImportance(*Piece)));
}
return json::Object{{"locations", std::move(Locations)}};
}
static json::Object createCodeFlow(const PathPieces &Pieces,
json::Array &Files) {
return json::Object{
{"threadFlows", json::Array{createThreadFlow(Pieces, Files)}}};
}
static json::Object createTool() {
return json::Object{{"name", "clang"},
{"fullName", "clang static analyzer"},
{"language", "en-US"},
{"version", getClangFullVersion()}};
}
static json::Object createResult(const PathDiagnostic &Diag, json::Array &Files,
const StringMap<unsigned> &RuleMapping) {
const PathPieces &Path = Diag.path.flatten(false);
const SourceManager &SMgr = Path.front()->getLocation().getManager();
auto Iter = RuleMapping.find(Diag.getCheckName());
assert(Iter != RuleMapping.end() && "Rule ID is not in the array index map?");
return json::Object{
{"message", createMessage(Diag.getVerboseDescription())},
{"codeFlows", json::Array{createCodeFlow(Path, Files)}},
{"locations",
json::Array{createLocation(createPhysicalLocation(
Diag.getLocation().asRange(),
*Diag.getLocation().asLocation().getFileEntry(), SMgr, Files))}},
{"ruleIndex", Iter->getValue()},
{"ruleId", Diag.getCheckName()}};
}
static StringRef getRuleDescription(StringRef CheckName) {
return llvm::StringSwitch<StringRef>(CheckName)
#define GET_CHECKERS
#define CHECKER(FULLNAME, CLASS, HELPTEXT, DOC_URI, IS_HIDDEN) \
.Case(FULLNAME, HELPTEXT)
#include "clang/StaticAnalyzer/Checkers/Checkers.inc"
#undef CHECKER
#undef GET_CHECKERS
;
}
static StringRef getRuleHelpURIStr(StringRef CheckName) {
return llvm::StringSwitch<StringRef>(CheckName)
#define GET_CHECKERS
#define CHECKER(FULLNAME, CLASS, HELPTEXT, DOC_URI, IS_HIDDEN) \
.Case(FULLNAME, DOC_URI)
#include "clang/StaticAnalyzer/Checkers/Checkers.inc"
#undef CHECKER
#undef GET_CHECKERS
;
}
static json::Object createRule(const PathDiagnostic &Diag) {
StringRef CheckName = Diag.getCheckName();
json::Object Ret{
{"fullDescription", createMessage(getRuleDescription(CheckName))},
{"name", createMessage(CheckName)},
{"id", CheckName}};
std::string RuleURI = getRuleHelpURIStr(CheckName);
if (!RuleURI.empty())
Ret["helpUri"] = RuleURI;
return Ret;
}
static json::Array createRules(std::vector<const PathDiagnostic *> &Diags,
StringMap<unsigned> &RuleMapping) {
json::Array Rules;
llvm::StringSet<> Seen;
llvm::for_each(Diags, [&](const PathDiagnostic *D) {
StringRef RuleID = D->getCheckName();
std::pair<llvm::StringSet<>::iterator, bool> P = Seen.insert(RuleID);
if (P.second) {
RuleMapping[RuleID] = Rules.size(); // Maps RuleID to an Array Index.
Rules.push_back(createRule(*D));
}
});
return Rules;
}
static json::Object createResources(std::vector<const PathDiagnostic *> &Diags,
StringMap<unsigned> &RuleMapping) {
return json::Object{{"rules", createRules(Diags, RuleMapping)}};
}
static json::Object createRun(std::vector<const PathDiagnostic *> &Diags) {
json::Array Results, Files;
StringMap<unsigned> RuleMapping;
json::Object Resources = createResources(Diags, RuleMapping);
llvm::for_each(Diags, [&](const PathDiagnostic *D) {
Results.push_back(createResult(*D, Files, RuleMapping));
});
return json::Object{{"tool", createTool()},
{"resources", std::move(Resources)},
{"results", std::move(Results)},
{"files", std::move(Files)}};
}
void SarifDiagnostics::FlushDiagnosticsImpl(
std::vector<const PathDiagnostic *> &Diags, FilesMade *) {
// We currently overwrite the file if it already exists. However, it may be
// useful to add a feature someday that allows the user to append a run to an
// existing SARIF file. One danger from that approach is that the size of the
// file can become large very quickly, so decoding into JSON to append a run
// may be an expensive operation.
std::error_code EC;
llvm::raw_fd_ostream OS(OutputFile, EC, llvm::sys::fs::F_Text);
if (EC) {
llvm::errs() << "warning: could not create file: " << EC.message() << '\n';
return;
}
json::Object Sarif{
{"$schema",
"http://json.schemastore.org/sarif-2.0.0-csd.2.beta.2018-11-28"},
{"version", "2.0.0-csd.2.beta.2018-11-28"},
{"runs", json::Array{createRun(Diags)}}};
OS << llvm::formatv("{0:2}\n", json::Value(std::move(Sarif)));
}
| 12,911 | 3,919 |
#include "opt-methods/util/Charting.hpp"
using namespace Charting;
void Charting::addToChart(QtCharts::QChart *chart, QtCharts::QAbstractSeries *s)
{
s->setUseOpenGL();
chart->addSeries(s);
s->attachAxis(axisX(chart));
s->attachAxis(axisY(chart));
}
qreal Charting::getAxisRange(QtCharts::QValueAxis *axis) { return axis->max() - axis->min(); }
void Charting::growAxisRange(QtCharts::QValueAxis *axis, double coef)
{
qreal r = getAxisRange(axis);
axis->setRange(axis->min() - r * coef, axis->max() + r * coef);
}
void Charting::createNaturalSequenceAxes(QtCharts::QChart* chart, [[maybe_unused]] int n)
{
using namespace QtCharts;
chart->createDefaultAxes();
auto* x = axisX<QtCharts::QValueAxis>(chart);
auto* y = axisY<QtCharts::QValueAxis>(chart);
growAxisRange(x, 0.01);
x->setLabelFormat("%i");
growAxisRange(y, 0.01);
}
| 846 | 331 |
// -*- C++ -*-
//
// $Id: EC_ProxySupplier.inl 77001 2007-02-12 07:54:49Z johnnyw $
TAO_BEGIN_VERSIONED_NAMESPACE_DECL
ACE_INLINE void
TAO_EC_ProxyPushSupplier::suspend_connection_i (void)
{
this->suspended_ = 1;
}
ACE_INLINE void
TAO_EC_ProxyPushSupplier::suspend_connection_locked (void)
{
ACE_GUARD_THROW_EX (
ACE_Lock, ace_mon, *this->lock_,
CORBA::INTERNAL ());
// @@ RtecEventChannelAdmin::EventChannel::SYNCHRONIZATION_ERROR ());
this->suspend_connection_i ();
}
ACE_INLINE void
TAO_EC_ProxyPushSupplier::resume_connection_i (void)
{
this->suspended_ = 0;
}
ACE_INLINE void
TAO_EC_ProxyPushSupplier::resume_connection_locked (void)
{
ACE_GUARD_THROW_EX (
ACE_Lock, ace_mon, *this->lock_,
CORBA::INTERNAL ());
// @@ RtecEventChannelAdmin::EventChannel::SYNCHRONIZATION_ERROR ());
this->resume_connection_i ();
}
ACE_INLINE CORBA::Boolean
TAO_EC_ProxyPushSupplier::is_connected_i (void) const
{
return !CORBA::is_nil (this->consumer_.in ());
}
ACE_INLINE CORBA::Boolean
TAO_EC_ProxyPushSupplier::is_connected (void) const
{
ACE_GUARD_RETURN (ACE_Lock, ace_mon, *this->lock_, 0);
return this->is_connected_i ();
}
ACE_INLINE CORBA::Boolean
TAO_EC_ProxyPushSupplier::is_suspended (void) const
{
ACE_GUARD_RETURN (ACE_Lock, ace_mon, *this->lock_, 0);
return this->suspended_;
}
ACE_INLINE RtecEventComm::PushConsumer_ptr
TAO_EC_ProxyPushSupplier::consumer (void) const
{
ACE_GUARD_RETURN (ACE_Lock, ace_mon, *this->lock_, 0);
return RtecEventComm::PushConsumer::_duplicate (this->consumer_.in ());
}
ACE_INLINE void
TAO_EC_ProxyPushSupplier::consumer_i (RtecEventComm::PushConsumer_ptr consumer)
{
this->consumer_ = consumer;
}
ACE_INLINE void
TAO_EC_ProxyPushSupplier::consumer (RtecEventComm::PushConsumer_ptr consumer)
{
ACE_GUARD (ACE_Lock, ace_mon, *this->lock_);
this->consumer_i (consumer);
}
ACE_INLINE const RtecEventChannelAdmin::ConsumerQOS&
TAO_EC_ProxyPushSupplier::subscriptions (void) const
{
// @@ TODO There should be a better way to signal errors here.
ACE_GUARD_RETURN (ACE_Lock, ace_mon, *this->lock_, this->qos_);
return this->qos_;
}
TAO_END_VERSIONED_NAMESPACE_DECL
| 2,200 | 922 |
#include <assert.h>
#include "DO.h"
#include "Iterator.h"
#include <exception>
using namespace std;
bool relatie1(TCheie cheie1, TCheie cheie2) {
if (cheie1 <= cheie2) {
return true;
}
else {
return false;
}
}
void testAll() {
DO dictOrd = DO(relatie1);
assert(dictOrd.dim() == 0);
assert(dictOrd.vid());
dictOrd.adauga(1, 2);
assert(dictOrd.dim() == 1);
assert(!dictOrd.vid());
assert(dictOrd.cauta(1) != NULL_TVALOARE);
TValoare v = dictOrd.adauga(1, 3);
assert(v == 2);
assert(dictOrd.cauta(1) == 3);
Iterator it = dictOrd.iterator();
it.prim();
while (it.valid()) {
TElem e = it.element();
assert(e.second != NULL_TVALOARE);
it.urmator();
}
assert(dictOrd.sterge(1) == 3);
assert(dictOrd.vid());
}
| 827 | 328 |
#include "game_loop.h"
#include <chrono>
#include <thread>
#include <iostream>
using namespace std::chrono_literals;
// we use a fixed timestep of 1 / (60 fps) = 16 milliseconds
constexpr std::chrono::nanoseconds timestep(16666666ns);
void GameLoop::run(std::function<void(float)> update) {
using clock = std::chrono::high_resolution_clock;
std::chrono::nanoseconds total_frame_time = timestep;
std::chrono::nanoseconds sleepy_time = timestep;
int num = 0;
std::chrono::nanoseconds sum = 0ns;
while(running) {
auto start = clock::now();
update(total_frame_time.count() / 1000000.f);
auto update_duration = std::chrono::duration_cast<std::chrono::nanoseconds> (clock::now() - start);
sleepy_time = timestep - update_duration - (total_frame_time - sleepy_time - update_duration);
std::this_thread::sleep_for(sleepy_time);
total_frame_time = std::chrono::duration_cast<std::chrono::nanoseconds> (clock::now() - start);
num++;
sum += total_frame_time;
if (num >= 120) {
std::cout << 1000000000.f / (sum.count()/num) << " fps" << std::endl;
num = 0;
sum = 0ns;
}
}
}
void GameLoop::setQuitting() {
running = false;
}
| 1,315 | 480 |
/*******************************************************************************************
* @file MergeTwoSortedListsSolution.cpp 2015\12\7 18:00:31 $
* @author Wang Xiaotao<wangxiaotao1980@gmail.com> (中文编码测试)
* @note LeetCode No.21 Merge Two Sorted Lists
*******************************************************************************************/
#include "MergeTwoSortedListsSolution.hpp"
#include "Struct.hpp"
// ------------------------------------------------------------------------------------------
// LeetCode No.21 Merge Two Sorted Lists
ListNode* MergeTwoSortedListsSolution::mergeTwoLists(ListNode* l1, ListNode* l2)
{
ListNode* pRealHead = new ListNode(0);
ListNode* pCurrent = pRealHead;
while (l1 && l2)
{
if ((l1->val) > (l2->val))
{
pCurrent->next = l2;
pCurrent = pCurrent->next;
l2 = l2->next;
}
else
{
pCurrent->next = l1;
pCurrent = pCurrent->next;
l1 = l1->next;
}
}
if (l1)
{
pCurrent->next = l1;
}
if (l2)
{
pCurrent->next = l2;
}
ListNode* pResult = pRealHead->next;
delete pRealHead;
return pResult;
}
//
// ------------------------------------------------------------------------------------------ | 1,348 | 421 |
/*
*
* Copyright 2018 Asylo authors
*
* 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 "asylo/platform/common/debug_strings.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
namespace asylo {
namespace {
using ::testing::Eq;
using ::testing::StrEq;
TEST(DebugStringsTest, Null) {
EXPECT_THAT(buffer_to_hex_string(nullptr, 0), StrEq("null"));
}
TEST(DebugStringsTest, ZeroLength) {
char buffer[] = "abc";
EXPECT_THAT(buffer_to_hex_string(static_cast<const void *>(buffer), 0),
StrEq("[]"));
}
TEST(DebugStringsTest, NegativeLength) {
char buffer[] = "abc";
EXPECT_THAT(buffer_to_hex_string(static_cast<const void *>(buffer), -4),
StrEq("[ERROR: negative length -4]"));
}
TEST(DebugStringsTest, SingletonNullBuffer) {
uint8_t buffer[] = {0};
ASSERT_THAT(sizeof(buffer), Eq(1));
EXPECT_THAT(buffer_to_hex_string(static_cast<const void *>(buffer), 1),
StrEq("[0x00]"));
}
TEST(DebugStringsTest, NonemptyBufferDecimalDigits) {
char buffer[] = "ABC";
ASSERT_THAT(sizeof(buffer), Eq(4));
EXPECT_THAT(buffer_to_hex_string(static_cast<const void *>(buffer), 4),
StrEq("[0x41424300]"));
}
TEST(DebugStringsTest, NonemptyBufferHighDigits) {
char buffer[] = "[-]";
ASSERT_THAT(sizeof(buffer), Eq(4));
EXPECT_THAT(buffer_to_hex_string(static_cast<const void *>(buffer), 4),
StrEq("[0x5B2D5D00]"));
}
TEST(DebugStringsTest, NonemptyNullBuffer) {
uint8_t buffer[] = {0, 0, 0, 0};
ASSERT_THAT(sizeof(buffer), Eq(4));
EXPECT_THAT(buffer_to_hex_string(static_cast<const void *>(buffer), 4),
StrEq("[0x00000000]"));
}
} // namespace
} // namespace asylo
| 2,194 | 802 |
#include "LFO.hpp"
#include "lookup_tables.hpp"
#include "PRNG.hpp"
#include "wave_scanner.hpp"
LFO::LFO(uint32_t sample_rate) : sample_rate(sample_rate) {}
void LFO::tick(void)
{
phase_accumulator += tuning_word;
updateWaveshapes();
}
void LFO::setInput(Input_t input_type, int value)
{
input[input_type] = value;
if (input_type == FREQ_mHz)
{
updateTuningWord();
}
}
int LFO::getOutput(Shape_t output_type)
{
return output[output_type];
}
void LFO::updateTuningWord(void)
{
/*
* In DDS, the tuning word M = (2^N * f_out)/(f_c), where N is the number of
* bits in the accumulator, f_out is the desired output frequency, and f_c
* is the sample rate.
*
* Since the LFO frequency is measured in milli Hertz, this becomes
* M = (2^N * f_out_mHz)/(f_c * 1000)
*
* Note that the MAX_ACCUMULATOR value is actually equal to 2^N - 1, but this
* off-by-one does not meaningfully impact the calculation.
*/
const uint32_t two_to_the_N = ACCUMULATOR_FULL_SCALE;
const uint32_t f_c = sample_rate;
const uint32_t f_out_mHz = input[FREQ_mHz];
const uint32_t mSec_per_sec = 1000u;
const uint32_t M = (two_to_the_N / (f_c * mSec_per_sec)) * f_out_mHz;
tuning_word = M;
}
void LFO::updateWaveshapes(void)
{
updateTriangle();
updateSine();
updateSquare();
updateRandom();
updateCrossfade();
}
void LFO::updateSine(void)
{
const uint32_t lut_idx = phase_accumulator >> NUM_FRACTIONAL_BITS_IN_ACCUMULATOR;
const uint32_t next_idx = (lut_idx + 1u) % SINE_LOOKUP_TABLE_SIZE;
const uint32_t fraction = phase_accumulator & ACCUMULATOR_FRACTION_MASK;
output[SINE] = linearInterpolation(Lookup_Tables::SINE_LUT[lut_idx], Lookup_Tables::SINE_LUT[next_idx], fraction);
}
void LFO::updateTriangle(void)
{
// keep the tri in phase with the sine
const uint32_t phase_shifted_accum = phase_accumulator + ACCUMULATOR_QUARTER_SCALE;
// derive the triangle directly from the phase accumulator
if (phase_shifted_accum <= ACCUMULATOR_HALF_SCALE)
{
output[TRIANGLE] = (phase_shifted_accum >> (ACCUMULATOR_BIT_WIDTH - OUTPUT_NUM_BITS - 1u)) - OUTPUT_MAX_VAL;
}
else
{
output[TRIANGLE] = ((ACCUMULATOR_FULL_SCALE - phase_shifted_accum) >> (ACCUMULATOR_BIT_WIDTH - OUTPUT_NUM_BITS - 1u)) - OUTPUT_MAX_VAL;
}
}
void LFO::updateSquare(void)
{
output[SQUARE] = phase_accumulator < ACCUMULATOR_HALF_SCALE ? OUTPUT_MAX_VAL : OUTPUT_MIN_VAL;
}
void LFO::updateRandom(void)
{
// the LFO "feels" better if the random signal updates at twice the base frequency
const uint32_t double_time_accum = phase_accumulator << 1u;
static uint32_t last_double_time_accum;
const bool accum_rolled_over = double_time_accum < last_double_time_accum;
if (accum_rolled_over)
{
// get a random sample in the bounds of the LFO range, centered around zero
const int random_sample = (PRNG::nextRand() & ((1 << OUTPUT_NUM_BITS) - 1)) - OUTPUT_MAX_VAL;
output[RANDOM] = random_sample;
}
last_double_time_accum = double_time_accum;
}
void LFO::updateCrossfade(void)
{
output[CROSSFADED] = Wave_Scanner::crossfade(output, NUM_LFO_SHAPES - 1, input[WAVE_SCAN]);
}
int LFO::linearInterpolation(int y1, int y2, uint32_t fraction)
{
return y1 + (fraction * (y2 - y1)) / ACCUMULATOR_FRACTION_MASK;
}
| 3,411 | 1,367 |
// 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 "util/memory-metrics.h"
#include <boost/algorithm/string.hpp>
#include <gutil/strings/substitute.h>
#include "runtime/bufferpool/buffer-pool.h"
#include "runtime/bufferpool/reservation-tracker.h"
#include "util/jni-util.h"
#include "util/mem-info.h"
#include "util/time.h"
using boost::algorithm::to_lower;
using namespace impala;
using namespace strings;
DECLARE_bool(mmap_buffers);
SumGauge* AggregateMemoryMetrics::TOTAL_USED = nullptr;
IntGauge* AggregateMemoryMetrics::NUM_MAPS = nullptr;
IntGauge* AggregateMemoryMetrics::MAPPED_BYTES = nullptr;
IntGauge* AggregateMemoryMetrics::RSS = nullptr;
IntGauge* AggregateMemoryMetrics::ANON_HUGE_PAGE_BYTES = nullptr;
StringProperty* AggregateMemoryMetrics::THP_ENABLED = nullptr;
StringProperty* AggregateMemoryMetrics::THP_DEFRAG = nullptr;
StringProperty* AggregateMemoryMetrics::THP_KHUGEPAGED_DEFRAG = nullptr;
TcmallocMetric* TcmallocMetric::BYTES_IN_USE = nullptr;
TcmallocMetric* TcmallocMetric::PAGEHEAP_FREE_BYTES = nullptr;
TcmallocMetric* TcmallocMetric::TOTAL_BYTES_RESERVED = nullptr;
TcmallocMetric* TcmallocMetric::PAGEHEAP_UNMAPPED_BYTES = nullptr;
TcmallocMetric::PhysicalBytesMetric* TcmallocMetric::PHYSICAL_BYTES_RESERVED = nullptr;
SanitizerMallocMetric* SanitizerMallocMetric::BYTES_ALLOCATED = nullptr;
BufferPoolMetric* BufferPoolMetric::LIMIT = nullptr;
BufferPoolMetric* BufferPoolMetric::SYSTEM_ALLOCATED = nullptr;
BufferPoolMetric* BufferPoolMetric::RESERVED = nullptr;
BufferPoolMetric* BufferPoolMetric::UNUSED_RESERVATION_BYTES = nullptr;
BufferPoolMetric* BufferPoolMetric::NUM_FREE_BUFFERS = nullptr;
BufferPoolMetric* BufferPoolMetric::FREE_BUFFER_BYTES = nullptr;
BufferPoolMetric* BufferPoolMetric::CLEAN_PAGES_LIMIT = nullptr;
BufferPoolMetric* BufferPoolMetric::NUM_CLEAN_PAGES = nullptr;
BufferPoolMetric* BufferPoolMetric::CLEAN_PAGE_BYTES = nullptr;
TcmallocMetric* TcmallocMetric::CreateAndRegister(
MetricGroup* metrics, const string& key, const string& tcmalloc_var) {
return metrics->RegisterMetric(new TcmallocMetric(MetricDefs::Get(key), tcmalloc_var));
}
Status impala::RegisterMemoryMetrics(MetricGroup* metrics, bool register_jvm_metrics,
ReservationTracker* global_reservations, BufferPool* buffer_pool) {
if (global_reservations != nullptr) {
DCHECK(buffer_pool != nullptr);
RETURN_IF_ERROR(BufferPoolMetric::InitMetrics(
metrics->GetOrCreateChildGroup("buffer-pool"), global_reservations, buffer_pool));
}
// Add compound metrics that track totals across malloc and the buffer pool.
// total-used should track the total physical memory in use.
vector<IntGauge*> used_metrics;
if (FLAGS_mmap_buffers && global_reservations != nullptr) {
// If we mmap() buffers, the buffers are not allocated via malloc. Ensure they are
// properly tracked.
used_metrics.push_back(BufferPoolMetric::SYSTEM_ALLOCATED);
}
#if defined(ADDRESS_SANITIZER) || defined(THREAD_SANITIZER)
SanitizerMallocMetric::BYTES_ALLOCATED = metrics->RegisterMetric(
new SanitizerMallocMetric(MetricDefs::Get("sanitizer-total-bytes-allocated")));
used_metrics.push_back(SanitizerMallocMetric::BYTES_ALLOCATED);
#else
MetricGroup* tcmalloc_metrics = metrics->GetOrCreateChildGroup("tcmalloc");
// We rely on TCMalloc for our global memory metrics, so skip setting them up
// if we're not using TCMalloc.
TcmallocMetric::BYTES_IN_USE = TcmallocMetric::CreateAndRegister(
tcmalloc_metrics, "tcmalloc.bytes-in-use", "generic.current_allocated_bytes");
TcmallocMetric::TOTAL_BYTES_RESERVED = TcmallocMetric::CreateAndRegister(
tcmalloc_metrics, "tcmalloc.total-bytes-reserved", "generic.heap_size");
TcmallocMetric::PAGEHEAP_FREE_BYTES = TcmallocMetric::CreateAndRegister(
tcmalloc_metrics, "tcmalloc.pageheap-free-bytes", "tcmalloc.pageheap_free_bytes");
TcmallocMetric::PAGEHEAP_UNMAPPED_BYTES =
TcmallocMetric::CreateAndRegister(tcmalloc_metrics,
"tcmalloc.pageheap-unmapped-bytes", "tcmalloc.pageheap_unmapped_bytes");
TcmallocMetric::PHYSICAL_BYTES_RESERVED =
tcmalloc_metrics->RegisterMetric(new TcmallocMetric::PhysicalBytesMetric(
MetricDefs::Get("tcmalloc.physical-bytes-reserved")));
used_metrics.push_back(TcmallocMetric::PHYSICAL_BYTES_RESERVED);
#endif
MetricGroup* aggregate_metrics = metrics->GetOrCreateChildGroup("memory");
AggregateMemoryMetrics::TOTAL_USED = aggregate_metrics->RegisterMetric(
new SumGauge(MetricDefs::Get("memory.total-used"), used_metrics));
if (register_jvm_metrics) {
RETURN_IF_ERROR(JvmMetric::InitMetrics(metrics->GetOrCreateChildGroup("jvm")));
}
if (MemInfo::HaveSmaps()) {
AggregateMemoryMetrics::NUM_MAPS =
aggregate_metrics->AddGauge("memory.num-maps", 0U);
AggregateMemoryMetrics::MAPPED_BYTES =
aggregate_metrics->AddGauge("memory.mapped-bytes", 0U);
AggregateMemoryMetrics::RSS = aggregate_metrics->AddGauge("memory.rss", 0U);
AggregateMemoryMetrics::ANON_HUGE_PAGE_BYTES =
aggregate_metrics->AddGauge("memory.anon-huge-page-bytes", 0U);
}
ThpConfig thp_config = MemInfo::ParseThpConfig();
AggregateMemoryMetrics::THP_ENABLED =
aggregate_metrics->AddProperty("memory.thp.enabled", thp_config.enabled);
AggregateMemoryMetrics::THP_DEFRAG =
aggregate_metrics->AddProperty("memory.thp.defrag", thp_config.defrag);
AggregateMemoryMetrics::THP_KHUGEPAGED_DEFRAG = aggregate_metrics->AddProperty(
"memory.thp.khugepaged-defrag", thp_config.khugepaged_defrag);
AggregateMemoryMetrics::Refresh();
return Status::OK();
}
void AggregateMemoryMetrics::Refresh() {
if (NUM_MAPS != nullptr) {
// Only call ParseSmaps() if the metrics were created.
MappedMemInfo map_info = MemInfo::ParseSmaps();
NUM_MAPS->SetValue(map_info.num_maps);
MAPPED_BYTES->SetValue(map_info.size_kb * 1024);
RSS->SetValue(map_info.rss_kb * 1024);
ANON_HUGE_PAGE_BYTES->SetValue(map_info.anon_huge_pages_kb * 1024);
}
ThpConfig thp_config = MemInfo::ParseThpConfig();
THP_ENABLED->SetValue(thp_config.enabled);
THP_DEFRAG->SetValue(thp_config.defrag);
THP_KHUGEPAGED_DEFRAG->SetValue(thp_config.khugepaged_defrag);
}
JvmMetric* JvmMetric::CreateAndRegister(MetricGroup* metrics, const string& key,
const string& pool_name, JvmMetric::JvmMetricType type) {
string pool_name_for_key = pool_name;
to_lower(pool_name_for_key);
replace(pool_name_for_key.begin(), pool_name_for_key.end(), ' ', '-');
return metrics->RegisterMetric(new JvmMetric(MetricDefs::Get(key, pool_name_for_key),
pool_name, type));
}
JvmMetric::JvmMetric(const TMetricDef& def, const string& mempool_name,
JvmMetricType type) : IntGauge(def, 0) {
mempool_name_ = mempool_name;
metric_type_ = type;
}
Status JvmMetric::InitMetrics(MetricGroup* metrics) {
DCHECK(metrics != nullptr);
TGetJvmMetricsRequest request;
request.get_all = true;
TGetJvmMetricsResponse response;
RETURN_IF_ERROR(JniUtil::GetJvmMetrics(request, &response));
for (const TJvmMemoryPool& usage: response.memory_pools) {
JvmMetric::CreateAndRegister(metrics, "jvm.$0.max-usage-bytes", usage.name, MAX);
JvmMetric::CreateAndRegister(metrics, "jvm.$0.current-usage-bytes", usage.name,
CURRENT);
JvmMetric::CreateAndRegister(metrics, "jvm.$0.committed-usage-bytes", usage.name,
COMMITTED);
JvmMetric::CreateAndRegister(metrics, "jvm.$0.init-usage-bytes", usage.name, INIT);
JvmMetric::CreateAndRegister(metrics, "jvm.$0.peak-max-usage-bytes", usage.name,
PEAK_MAX);
JvmMetric::CreateAndRegister(metrics, "jvm.$0.peak-current-usage-bytes", usage.name,
PEAK_CURRENT);
JvmMetric::CreateAndRegister(metrics, "jvm.$0.peak-committed-usage-bytes", usage.name,
PEAK_COMMITTED);
JvmMetric::CreateAndRegister(metrics, "jvm.$0.peak-init-usage-bytes", usage.name,
PEAK_INIT);
}
return Status::OK();
}
int64_t JvmMetric::GetValue() {
TGetJvmMetricsRequest request;
request.get_all = false;
request.__set_memory_pool(mempool_name_);
TGetJvmMetricsResponse response;
if (!JniUtil::GetJvmMetrics(request, &response).ok()) return 0;
if (response.memory_pools.size() != 1) return 0;
TJvmMemoryPool& pool = response.memory_pools[0];
DCHECK(pool.name == mempool_name_);
switch (metric_type_) {
case MAX:
return pool.max;
case INIT:
return pool.init;
case CURRENT:
return pool.used;
case COMMITTED:
return pool.committed;
case PEAK_MAX:
return pool.peak_max;
case PEAK_INIT:
return pool.peak_init;
case PEAK_CURRENT:
return pool.peak_used;
case PEAK_COMMITTED:
return pool.peak_committed;
default:
DCHECK(false) << "Unknown JvmMetricType: " << metric_type_;
}
return 0;
}
Status BufferPoolMetric::InitMetrics(MetricGroup* metrics,
ReservationTracker* global_reservations, BufferPool* buffer_pool) {
LIMIT = metrics->RegisterMetric(
new BufferPoolMetric(MetricDefs::Get("buffer-pool.limit"),
BufferPoolMetricType::LIMIT, global_reservations, buffer_pool));
SYSTEM_ALLOCATED = metrics->RegisterMetric(
new BufferPoolMetric(MetricDefs::Get("buffer-pool.system-allocated"),
BufferPoolMetricType::SYSTEM_ALLOCATED, global_reservations, buffer_pool));
RESERVED = metrics->RegisterMetric(
new BufferPoolMetric(MetricDefs::Get("buffer-pool.reserved"),
BufferPoolMetricType::RESERVED, global_reservations, buffer_pool));
UNUSED_RESERVATION_BYTES = metrics->RegisterMetric(
new BufferPoolMetric(MetricDefs::Get("buffer-pool.unused-reservation-bytes"),
BufferPoolMetricType::UNUSED_RESERVATION_BYTES, global_reservations,
buffer_pool));
NUM_FREE_BUFFERS = metrics->RegisterMetric(
new BufferPoolMetric(MetricDefs::Get("buffer-pool.free-buffers"),
BufferPoolMetricType::NUM_FREE_BUFFERS, global_reservations, buffer_pool));
FREE_BUFFER_BYTES = metrics->RegisterMetric(
new BufferPoolMetric(MetricDefs::Get("buffer-pool.free-buffer-bytes"),
BufferPoolMetricType::FREE_BUFFER_BYTES, global_reservations, buffer_pool));
CLEAN_PAGES_LIMIT = metrics->RegisterMetric(
new BufferPoolMetric(MetricDefs::Get("buffer-pool.clean-pages-limit"),
BufferPoolMetricType::CLEAN_PAGES_LIMIT, global_reservations, buffer_pool));
NUM_CLEAN_PAGES = metrics->RegisterMetric(
new BufferPoolMetric(MetricDefs::Get("buffer-pool.clean-pages"),
BufferPoolMetricType::NUM_CLEAN_PAGES, global_reservations, buffer_pool));
CLEAN_PAGE_BYTES = metrics->RegisterMetric(
new BufferPoolMetric(MetricDefs::Get("buffer-pool.clean-page-bytes"),
BufferPoolMetricType::CLEAN_PAGE_BYTES, global_reservations, buffer_pool));
return Status::OK();
}
BufferPoolMetric::BufferPoolMetric(const TMetricDef& def, BufferPoolMetricType type,
ReservationTracker* global_reservations, BufferPool* buffer_pool)
: IntGauge(def, 0),
type_(type),
global_reservations_(global_reservations),
buffer_pool_(buffer_pool) {}
int64_t BufferPoolMetric::GetValue() {
// IMPALA-6362: we have to be careful that none of the below calls to ReservationTracker
// methods acquire ReservationTracker::lock_ to avoid a potential circular dependency
// with MemTracker::child_trackers_lock_, which may be held when refreshing MemTracker
// consumption.
switch (type_) {
case BufferPoolMetricType::LIMIT:
return buffer_pool_->GetSystemBytesLimit();
case BufferPoolMetricType::SYSTEM_ALLOCATED:
return buffer_pool_->GetSystemBytesAllocated();
case BufferPoolMetricType::RESERVED:
return global_reservations_->GetReservation();
case BufferPoolMetricType::UNUSED_RESERVATION_BYTES: {
// Estimate the unused reservation based on other aggregate values, defined as
// the total bytes of reservation where there is no corresponding buffer in use
// by a client. Buffers are either in-use, free buffers, or attached to clean pages.
int64_t total_used_reservation = buffer_pool_->GetSystemBytesAllocated()
- buffer_pool_->GetFreeBufferBytes()
- buffer_pool_->GetCleanPageBytes();
return global_reservations_->GetReservation() - total_used_reservation;
}
case BufferPoolMetricType::NUM_FREE_BUFFERS:
return buffer_pool_->GetNumFreeBuffers();
case BufferPoolMetricType::FREE_BUFFER_BYTES:
return buffer_pool_->GetFreeBufferBytes();
case BufferPoolMetricType::CLEAN_PAGES_LIMIT:
return buffer_pool_->GetCleanPageBytesLimit();
case BufferPoolMetricType::NUM_CLEAN_PAGES:
return buffer_pool_->GetNumCleanPages();
case BufferPoolMetricType::CLEAN_PAGE_BYTES:
return buffer_pool_->GetCleanPageBytes();
default:
DCHECK(false) << "Unknown BufferPoolMetricType: " << static_cast<int>(type_);
}
return 0;
}
| 13,674 | 4,815 |
#include "../../headers/renderpasses/Renderpass.hpp"
#include "../../headers/RTFilterDemo.hpp"
namespace rtf
{
void Renderpass::setRtFilterDemo(RTFilterDemo* rtFilterDemo)
{
m_rtFilterDemo = rtFilterDemo;
m_vulkanDevice = rtFilterDemo->vulkanDevice;
m_attachmentManager = rtFilterDemo->m_attachmentManager;
m_rtFilterDemo = rtFilterDemo;
}
} | 353 | 133 |
/*****************************************************************************
* Copyright (C) 2008-2011 Massachusetts Institute of Technology *
* *
* 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 *
* *
* This source code is part of the PetaBricks project: *
* http://projects.csail.mit.edu/petabricks/ *
* *
*****************************************************************************/
#include "trainingdeps.h"
std::map<std::string, std::vector<std::string> > petabricks::TrainingDeps::_callgraph;
namespace petabricks {
void TrainingDeps::emitRules(std::string& choicename,
const std::vector<RulePtr>& sortedRules) {
_os << " <rules choicename=\"" << choicename << "\">\n";
int index = 0;
for (std::vector<RulePtr>::const_iterator i = sortedRules.begin(),
e = sortedRules.end(); i != e; ++i) {
_os << " <rule index=\"" << index << "\" label=\"" << (*i)->getLabel()
<< "\" />\n";
++index;
}
_os << " </rules>\n";
}
}
| 2,664 | 729 |
#include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
char s[100];
long long int a=138902663,k,l,i=8;
while(1)
{
k=(a*a)/100,i=8;
while(k!=0)
{
if(k%10!=i--) break;
k/=100;
}
if(k==0) break;
i=8;
a-=6;
k=(a*a)/100;
while(k!=0)
{
if((k%10)!=i) break;
i--;
k/=100;
}
if(k==0) break;
a-=4;
}
cout<<"a="<<a<<"0\na*a="<<a*a;
return 0;
}
| 458 | 252 |
/*
pbrt source code Copyright(c) 1998-2012 Matt Pharr and Greg Humphreys.
This file is part of pbrt.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// renderers/samplerrenderer.cpp*
#include "stdafx.h"
#include "renderers/samplerrenderer.h"
#include "scene.h"
#include "film.h"
#include "volume.h"
#include "sampler.h"
#include "integrator.h"
#include "progressreporter.h"
#include "camera.h"
#include "intersection.h"
static uint32_t hash(char *key, uint32_t len)
{
uint32_t hash = 0, i;
for (hash=0, i=0; i<len; ++i) {
hash += key[i];
hash += (hash << 10);
hash ^= (hash >> 6);
}
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
return hash;
}
// SamplerRendererTask Definitions
void SamplerRendererTask::Run() {
PBRT_STARTED_RENDERTASK(taskNum);
// Get sub-_Sampler_ for _SamplerRendererTask_
Sampler *sampler = mainSampler->GetSubSampler(taskNum, taskCount);
if (!sampler)
{
reporter.Update();
PBRT_FINISHED_RENDERTASK(taskNum);
return;
}
// Declare local variables used for rendering loop
MemoryArena arena;
RNG rng(taskNum);
// Allocate space for samples and intersections
int maxSamples = sampler->MaximumSampleCount();
Sample *samples = origSample->Duplicate(maxSamples);
RayDifferential *rays = new RayDifferential[maxSamples];
Spectrum *Ls = new Spectrum[maxSamples];
Spectrum *Ts = new Spectrum[maxSamples];
Intersection *isects = new Intersection[maxSamples];
// Get samples from _Sampler_ and update image
int sampleCount;
while ((sampleCount = sampler->GetMoreSamples(samples, rng)) > 0) {
// Generate camera rays and compute radiance along rays
for (int i = 0; i < sampleCount; ++i) {
// Find camera ray for _sample[i]_
PBRT_STARTED_GENERATING_CAMERA_RAY(&samples[i]);
float rayWeight = camera->GenerateRayDifferential(samples[i], &rays[i]);
rays[i].ScaleDifferentials(1.f / sqrtf(sampler->samplesPerPixel));
PBRT_FINISHED_GENERATING_CAMERA_RAY(&samples[i], &rays[i], rayWeight);
// Evaluate radiance along camera ray
PBRT_STARTED_CAMERA_RAY_INTEGRATION(&rays[i], &samples[i]);
if (visualizeObjectIds) {
if (rayWeight > 0.f && scene->Intersect(rays[i], &isects[i])) {
// random shading based on shape id...
uint32_t ids[2] = { isects[i].shapeId, isects[i].primitiveId };
uint32_t h = hash((char *)ids, sizeof(ids));
float rgb[3] = { float(h & 0xff), float((h >> 8) & 0xff),
float((h >> 16) & 0xff) };
Ls[i] = Spectrum::FromRGB(rgb);
Ls[i] /= 255.f;
}
else
Ls[i] = 0.f;
}
else {
if (rayWeight > 0.f)
Ls[i] = rayWeight * renderer->Li(scene, rays[i], &samples[i], rng,
arena, &isects[i], &Ts[i]);
else {
Ls[i] = 0.f;
Ts[i] = 1.f;
}
// Issue warning if unexpected radiance value returned
if (Ls[i].HasNaNs()) {
Error("Not-a-number radiance value returned "
"for image sample. Setting to black.");
Ls[i] = Spectrum(0.f);
}
else if (Ls[i].y() < -1e-5) {
Error("Negative luminance value, %f, returned "
"for image sample. Setting to black.", Ls[i].y());
Ls[i] = Spectrum(0.f);
}
else if (isinf(Ls[i].y())) {
Error("Infinite luminance value returned "
"for image sample. Setting to black.");
Ls[i] = Spectrum(0.f);
}
}
PBRT_FINISHED_CAMERA_RAY_INTEGRATION(&rays[i], &samples[i], &Ls[i]);
}
// Report sample results to _Sampler_, add contributions to image
if (sampler->ReportResults(samples, rays, Ls, isects, sampleCount))
{
for (int i = 0; i < sampleCount; ++i)
{
PBRT_STARTED_ADDING_IMAGE_SAMPLE(&samples[i], &rays[i], &Ls[i], &Ts[i]);
camera->film->AddSample(samples[i], Ls[i]);
PBRT_FINISHED_ADDING_IMAGE_SAMPLE();
}
}
// Free _MemoryArena_ memory from computing image sample values
arena.FreeAll();
}
// Clean up after _SamplerRendererTask_ is done with its image region
camera->film->UpdateDisplay(sampler->xPixelStart,
sampler->yPixelStart, sampler->xPixelEnd+1, sampler->yPixelEnd+1);
delete sampler;
delete[] samples;
delete[] rays;
delete[] Ls;
delete[] Ts;
delete[] isects;
reporter.Update();
PBRT_FINISHED_RENDERTASK(taskNum);
}
// SamplerRenderer Method Definitions
SamplerRenderer::SamplerRenderer(Sampler *s, Camera *c,
SurfaceIntegrator *si, VolumeIntegrator *vi,
bool visIds) {
sampler = s;
camera = c;
surfaceIntegrator = si;
volumeIntegrator = vi;
visualizeObjectIds = visIds;
}
SamplerRenderer::~SamplerRenderer() {
delete sampler;
delete camera;
delete surfaceIntegrator;
delete volumeIntegrator;
}
void SamplerRenderer::Render(const Scene *scene) {
PBRT_FINISHED_PARSING();
// Allow integrators to do preprocessing for the scene
PBRT_STARTED_PREPROCESSING();
surfaceIntegrator->Preprocess(scene, camera, this);
volumeIntegrator->Preprocess(scene, camera, this);
PBRT_FINISHED_PREPROCESSING();
PBRT_STARTED_RENDERING();
// Allocate and initialize _sample_
Sample *sample = new Sample(sampler, surfaceIntegrator,
volumeIntegrator, scene);
// Create and launch _SamplerRendererTask_s for rendering image
// Compute number of _SamplerRendererTask_s to create for rendering
int nPixels = camera->film->xResolution * camera->film->yResolution;
int nTasks = max(32 * NumSystemCores(), nPixels / (16*16));
nTasks = RoundUpPow2(nTasks);
ProgressReporter reporter(nTasks, "Rendering");
vector<Task *> renderTasks;
for (int i = 0; i < nTasks; ++i)
renderTasks.push_back(new SamplerRendererTask(scene, this, camera,
reporter, sampler, sample,
visualizeObjectIds,
nTasks-1-i, nTasks));
EnqueueTasks(renderTasks);
WaitForAllTasks();
for (uint32_t i = 0; i < renderTasks.size(); ++i)
delete renderTasks[i];
reporter.Done();
PBRT_FINISHED_RENDERING();
// Clean up after rendering and store final image
delete sample;
camera->film->WriteImage();
}
Spectrum SamplerRenderer::Li(const Scene *scene,
const RayDifferential &ray, const Sample *sample, RNG &rng,
MemoryArena &arena, Intersection *isect, Spectrum *T) const {
Assert(ray.time == sample->time);
Assert(!ray.HasNaNs());
// Allocate local variables for _isect_ and _T_ if needed
Spectrum localT;
if (!T) T = &localT;
Intersection localIsect;
if (!isect) isect = &localIsect;
Spectrum Li = 0.f;
if (scene->Intersect(ray, isect))
Li = surfaceIntegrator->Li(scene, this, ray, *isect, sample,
rng, arena);
else {
// Handle ray that doesn't intersect any geometry
for (uint32_t i = 0; i < scene->lights.size(); ++i)
Li += scene->lights[i]->Le(ray);
}
Spectrum Lvi = volumeIntegrator->Li(scene, this, ray, sample, rng,
T, arena);
return *T * Li + Lvi;
}
Spectrum SamplerRenderer::Transmittance(const Scene *scene,
const RayDifferential &ray, const Sample *sample, RNG &rng,
MemoryArena &arena) const {
return volumeIntegrator->Transmittance(scene, this, ray, sample,
rng, arena);
}
| 9,537 | 3,132 |
#include "i4pch.h"
#include "WinShipLinker.h" | 46 | 24 |
//===-- NativeRegisterContextWindows.cpp ------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "lldb/Host/HostThread.h"
#include "lldb/Host/windows/HostThreadWindows.h"
#include "lldb/Host/windows/windows.h"
#include "lldb/Utility/Log.h"
#include "NativeRegisterContextWindows.h"
#include "NativeThreadWindows.h"
#include "ProcessWindowsLog.h"
using namespace lldb;
using namespace lldb_private;
NativeRegisterContextWindows::NativeRegisterContextWindows(
NativeThreadProtocol &thread, RegisterInfoInterface *reg_info_interface_p)
: NativeRegisterContextRegisterInfo(thread, reg_info_interface_p) {}
lldb::thread_t NativeRegisterContextWindows::GetThreadHandle() const {
auto wthread = static_cast<NativeThreadWindows *>(&m_thread);
return wthread->GetHostThread().GetNativeThread().GetSystemHandle();
}
| 1,104 | 327 |
/*
Copyright (C) 2005-2007 Feeling Software Inc.
Portions of the code are:
Copyright (C) 2005-2007 Sony Computer Entertainment America
MIT License: http://www.opensource.org/licenses/mit-license.php
*/
#include "StdAfx.h"
#include "FUtils/FUParameter.h"
#include "FCDocument/FCDocument.h"
#include "FCDocument/FCDAnimated.h"
#include "FCDocument/FCDAnimation.h"
#include "FCDocument/FCDAnimationChannel.h"
#include "FCDocument/FCDAnimationCurve.h"
#include "FCDocument/FCDEntity.h"
#include "FCDocument/FCDLibrary.h"
#include "FCDocument/FCDParameterAnimatable.h"
class FCTestOutsideParameter : public FCDObject
{
public:
DeclareParameter(float, FUParameterQualifiers::SIMPLE, test1, FC("A large parameter name!"));
DeclareParameterAnimatable(FMVector3, FUParameterQualifiers::VECTOR, test2, FC("An animatable parameter"));
DeclareParameterAnimatable(FMVector3, FUParameterQualifiers::COLOR, test3, FC("A complex animatable parameter"));
DeclareParameterPtr(FCDObject, test4, FC("A simple object pointer"));
DeclareParameterRef(FCDObject, test5, FC("An object reference!"));
DeclareParameterList(Float, test6, FC("A float list parameter."));
DeclareParameterTrackList(FCDObject, test7, FC("An object tracker list."));
DeclareParameterContainer(FCDObject, test8, FC("An object container."));
DeclareParameterListAnimatable(FMVector3, FUParameterQualifiers::COLOR, test9, FC("An animatable color list."));
FCTestOutsideParameter(FCDocument* document)
: FCDObject(document)
, InitializeParameter(test1, 0.0f)
, InitializeParameterAnimatableNoArg(test2)
, InitializeParameterAnimatable(test3, FMVector3::XAxis)
, InitializeParameter(test4, NULL)
, InitializeParameterNoArg(test5)
, InitializeParameterNoArg(test6)
, InitializeParameterNoArg(test7)
, InitializeParameterNoArg(test8)
, InitializeParameterAnimatableNoArg(test9)
{
}
virtual ~FCTestOutsideParameter()
{
}
};
ImplementParameterObject(FCTestOutsideParameter, FCDObject, test4, new FCDObject(parent->GetDocument()));
ImplementParameterObject(FCTestOutsideParameter, FCDObject, test5, new FCDObject(parent->GetDocument()));
ImplementParameterObject(FCTestOutsideParameter, FCDObject, test7, new FCDObject(parent->GetDocument()));
ImplementParameterObject(FCTestOutsideParameter, FCDObject, test8, new FCDObject(parent->GetDocument()));
TESTSUITE_START(FCDParameter)
TESTSUITE_TEST(0, Simple)
FUObjectRef<FCDocument> document = FCollada::NewTopDocument();
FUObjectRef<FCDEntity> entity = new FCDEntity(document);
entity->SetNote(FC("Noting down."));
PassIf(IsEquivalent(entity->GetNote(), FC("Noting down.")));
TESTSUITE_TEST(1, Functionality)
FUObjectRef<FCDocument> document = FCollada::NewTopDocument();
FUObjectRef<FCTestOutsideParameter> parameter = new FCTestOutsideParameter(document);
// Simple float parameter
PassIf(parameter->test1 == 0.0f);
parameter->test1 = 2.1f;
PassIf(parameter->test1 == 2.1f);
// Animatable 3D vector parameter.
parameter->test2 = FMVector3::One;
PassIf(parameter->test2 == FMVector3::One);
PassIf(parameter->test2 - FMVector3::One == FMVector3::Zero);
PassIf(parameter->test2.GetAnimated() != NULL);
PassIf(parameter->test2.GetAnimated()->GetValueCount() == 3);
// Object parameters
parameter->test4 = parameter->test5;
PassIf(parameter->test4 == parameter->test5);
parameter->test5 = NULL;
PassIf(parameter->test5 == NULL);
parameter->test4 = new FCDObject(document);
PassIf(parameter->test4 != NULL);
PassIf(parameter->test4->GetTrackerCount() == 1);
parameter->test5 = parameter->test4;
PassIf(parameter->test5 != NULL);
PassIf(parameter->test5->GetTrackerCount() == 1);
parameter->test5 = NULL;
PassIf(parameter->test4 == NULL);
// Primitive list parameter
size_t count = parameter->test6.size();
PassIf(count == 0 && parameter->test6.empty());
parameter->test6.push_back(0.52f);
PassIf(parameter->test6.size() == 1);
parameter->test6.clear();
PassIf(parameter->test6.size() == 0);
parameter->test6.push_back(0.45f);
PassIf(parameter->test6.size() == 1);
parameter->test6.erase(0, 1);
PassIf(parameter->test6.size() == 0);
// Tracked object list parameter
FUTrackedPtr<FCDObject> testObject = new FCDObject(document);
count = parameter->test7.size();
PassIf(count == 0 && parameter->test7.empty());
parameter->test7.push_back(testObject);
PassIf(parameter->test7.size() == 1);
parameter->test7.clear();
PassIf(testObject != NULL);
PassIf(parameter->test7.size() == 0);
parameter->test7.push_back(testObject);
PassIf(parameter->test7.size() == 1);
parameter->test7.erase(0, 1);
PassIf(parameter->test7.size() == 0);
testObject->Release();
PassIf(testObject == NULL);
// Object container parameter
testObject = new FCDObject(document);
count = parameter->test8.size();
PassIf(count == 0 && parameter->test8.empty());
parameter->test8.push_back(testObject);
PassIf(parameter->test8.size() == 1);
parameter->test8.clear();
PassIf(testObject == NULL); // this is a container, so testObject should have been released!
PassIf(parameter->test8.size() == 0);
parameter->test8.push_back(new FCDObject(document));
PassIf(parameter->test8.size() == 1);
parameter->test8.erase(0, 1);
PassIf(parameter->test8.size() == 0);
TESTSUITE_TEST(2, AnimatedListParameter)
FUObjectRef<FCDocument> document = FCollada::NewTopDocument();
FUObjectRef<FCTestOutsideParameter> parameter = new FCTestOutsideParameter(document);
FCDAnimation* animation = document->GetAnimationLibrary()->AddEntity();
FCDAnimationChannel* channel = animation->AddChannel();
// Animated list parameter.
// Simple operations
#define TESTP parameter->test9
PassIf(TESTP.size() == 0);
TESTP.push_back(FMVector3::XAxis);
TESTP.push_back(FMVector3::YAxis);
TESTP.push_back(FMVector3::ZAxis);
PassIf(TESTP.size() == 3);
FailIf(TESTP.IsAnimated());
FailIf(TESTP.IsAnimated(0));
PassIf(TESTP.GetAnimatedValues().empty());
PassIf(TESTP.GetAnimated(2) != NULL);
FailIf(TESTP.GetAnimatedValues().empty());
FailIf(TESTP.IsAnimated(2));
TESTP.push_front(FMVector3::XAxis);
TESTP.push_front(FMVector3::YAxis);
TESTP.push_front(FMVector3::ZAxis);
PassIf(TESTP.GetAnimated(2) != NULL);
PassIf(TESTP.at(1) == FMVector3::YAxis);
PassIf(TESTP.at(4) == FMVector3::YAxis);
PassIf(!TESTP.IsAnimated(5));
PassIf(!TESTP.IsAnimated(4));
PassIf(TESTP.GetAnimated(2)->GetArrayElement() == 2);
// List insertion tests.
TESTP.GetAnimated(2)->AddCurve(0, channel->AddCurve());
PassIf(TESTP.IsAnimated());
PassIf(TESTP.IsAnimated(2));
PassIf(!TESTP.IsAnimated(1));
PassIf(!TESTP.IsAnimated(3));
TESTP.insert(2, FMVector3::XAxis); // should move the curve up to index 3!
PassIf(TESTP.IsAnimated(3));
PassIf(!TESTP.IsAnimated(2));
PassIf(!TESTP.IsAnimated(4));
PassIf(TESTP.GetAnimated(3)->GetArrayElement() == 3);
TESTP.insert(5, FMVector3::YAxis); // no movement of the curve.
PassIf(TESTP.IsAnimated(3));
PassIf(!TESTP.IsAnimated(2));
PassIf(!TESTP.IsAnimated(4));
PassIf(TESTP.GetAnimated(4)->GetArrayElement() == 4);
// List removal tests.
TESTP.erase(0); // should move the curve back to index 2.
PassIf(TESTP.IsAnimated(2));
PassIf(!TESTP.IsAnimated(1));
PassIf(!TESTP.IsAnimated(3));
PassIf(TESTP.GetAnimated(2)->GetArrayElement() == 2);
TESTP.erase(0, 4); // nothing should be animated anymore.
FailIf(TESTP.IsAnimated());
// List resizing tests.
TESTP.clear();
FailIf(TESTP.IsAnimated());
TESTP.resize(4);
FailIf(TESTP.IsAnimated());
TESTP.GetAnimated(1)->AddCurve(0, channel->AddCurve());
PassIf(TESTP.IsAnimated());
PassIf(TESTP.IsAnimated(1));
TESTP.resize(6);
PassIf(TESTP.IsAnimated());
PassIf(TESTP.IsAnimated(1));
TESTP.resize(1);
FailIf(TESTP.IsAnimated());
TESTSUITE_END
| 7,876 | 2,730 |
// This file has been generated by Py++.
#ifndef SingletonWindowFactoryManager_hpp__pyplusplus_wrapper
#define SingletonWindowFactoryManager_hpp__pyplusplus_wrapper
void register_SingletonWindowFactoryManager_class();
#endif//SingletonWindowFactoryManager_hpp__pyplusplus_wrapper
| 283 | 78 |
#ifndef STAN_MATH_PRIM_FUN_INVERSE_HPP
#define STAN_MATH_PRIM_FUN_INVERSE_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
namespace stan {
namespace math {
/**
* Returns the inverse of the specified matrix.
*
* @tparam T type of elements in the matrix
* @tparam R number of rows, can be Eigen::Dynamic
* @tparam C number of columns, can be Eigen::Dynamic
*
* @param m specified matrix
* @return Inverse of the matrix (an empty matrix if the specified matrix has
* size zero).
* @throw std::invalid_argument if the matrix is not square.
*/
template <typename EigMat,
require_eigen_vt<std::is_arithmetic, EigMat>* = nullptr>
inline Eigen::Matrix<value_type_t<EigMat>, EigMat::RowsAtCompileTime,
EigMat::ColsAtCompileTime>
inverse(const EigMat& m) {
check_square("inverse", "m", m);
if (m.size() == 0) {
return {};
}
return m.inverse();
}
} // namespace math
} // namespace stan
#endif
| 1,009 | 356 |
#include "../Shared.h"
namespace UnitTests
{
namespace Arrays
{
TEST(ArrayCat, One)
{
const std::string innerCode = "@ = (((3 * 1).arrayCreate * 1 * 2).arraySet * 2 * 3).arraySet.(id * arrayCat).(print * ([-1] * 0 * 0).arraySet.print * print);";
const std::string expected = "[1, 2, 3]";
GeneralizedTest(standardInput, expected, MakeTestProgram(innerCode));
}
TEST(ArrayCat, Three)
{
const std::string innerCode = R"(
@ = ( (1 * 1).arrayCreate *
((2 * 2).arrayCreate * 1 * 3).arraySet *
(((3 * 4).arrayCreate * 1 * 5).arraySet * 2 * 6).arraySet
).arrayCat.print;)";
const std::string expected = "[1, 2, 3, 4, 5, 6]";
GeneralizedTest(standardInput, expected, MakeTestProgram(innerCode));
}
}
} | 750 | 330 |
/*
* Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
* All rights reserved.
*
* This library/application is free software; you can redistribute and/or modify it under the terms of
* the license that is included with this library/application in the file license.txt.
*/
#include "CeilingRenderer.h"
#include "Tracer.h"
//---- CeilingRenderer ---------------------------------------------------------------
RegisterRenderer(CeilingRenderer);
CeilingRenderer::CeilingRenderer(const char *name) : ComparingRenderer(name) { }
CeilingRenderer::~CeilingRenderer() { }
long CeilingRenderer::FindSlot(String &key, const ROAnything &list)
{
StartTrace(CeilingRenderer.FindSlot);
long i = 0;
long sz = list.GetSize();
while ((i < sz) && (key.Compare(list.SlotName(i)) > 0) ) {
++i;
}
return i < sz ? i : -1;
}
| 870 | 283 |
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#include <vgui/ILocalize.h>
#include "vgui_controls/TextEntry.h"
#include "select_player_dialog.h"
#include "tf_controls.h"
#include "c_playerresource.h"
#include "ienginevgui.h"
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
int CSelectPlayerDialog::SortPartnerInfoFunc( const partner_info_t *pA, const partner_info_t *pB )
{
return Q_stricmp( pA->m_name.Get(), pB->m_name.Get() );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CSelectPlayerDialog::CSelectPlayerDialog( vgui::Panel *parent )
: vgui::EditablePanel( parent, "SelectPlayerDialog" )
, m_bAllowSameTeam( true )
, m_bAllowOutsideServer( true )
{
if ( parent == NULL )
{
vgui::HScheme scheme = vgui::scheme()->LoadSchemeFromFileEx( enginevgui->GetPanel( PANEL_CLIENTDLL ), "resource/ClientScheme.res", "ClientScheme");
SetScheme(scheme);
SetProportional( true );
}
m_pSelectFromServerButton = NULL;
m_pCancelButton = NULL;
m_pButtonKV = NULL;
m_bReapplyButtonKVs = false;
for ( int i = 0; i < SPDS_NUM_STATES; i++ )
{
m_pStatePanels[i] = new vgui::EditablePanel( this, VarArgs("StatePanel%d",i) );
}
m_pPlayerList = new vgui::EditablePanel( this, "PlayerList" );
m_pPlayerListScroller = new vgui::ScrollableEditablePanel( this, m_pPlayerList, "PlayerListScroller" );
m_iCurrentState = SPDS_SELECTING_PLAYER;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CSelectPlayerDialog::~CSelectPlayerDialog( void )
{
if ( m_pButtonKV )
{
m_pButtonKV->deleteThis();
m_pButtonKV = NULL;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSelectPlayerDialog::Reset( void )
{
m_iCurrentState = SPDS_SELECTING_PLAYER;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSelectPlayerDialog::ApplySettings( KeyValues *inResourceData )
{
BaseClass::ApplySettings( inResourceData );
KeyValues *pItemKV = inResourceData->FindKey( "button_kv" );
if ( pItemKV )
{
if ( m_pButtonKV )
{
m_pButtonKV->deleteThis();
}
m_pButtonKV = new KeyValues("button_kv");
pItemKV->CopySubkeys( m_pButtonKV );
m_bReapplyButtonKVs = true;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSelectPlayerDialog::ApplySchemeSettings( vgui::IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
LoadControlSettings( GetResFile() );
m_pCancelButton = dynamic_cast<CExButton*>( FindChildByName( "CancelButton" ) );
// Find all the sub buttons, and set their action signals to point to this panel
for ( int i = 0; i < SPDS_NUM_STATES; i++ )
{
int iButton = 0;
CExButton *pButton = NULL;
do
{
pButton = dynamic_cast<CExButton*>( m_pStatePanels[i]->FindChildByName( VarArgs("subbutton%d",iButton)) );
if ( pButton )
{
pButton->AddActionSignalTarget( this );
// The second button on the first state is the server button
if ( iButton == 1 )
{
m_pSelectFromServerButton = pButton;
}
iButton++;
}
} while (pButton);
}
UpdateState();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSelectPlayerDialog::PerformLayout( void )
{
BaseClass::PerformLayout();
// Layout the player list buttons
if ( m_pPlayerPanels.Count() )
{
int iButtonH = m_pPlayerPanels[0]->GetTall() + YRES(2);
m_pPlayerList->SetSize( m_pPlayerList->GetWide(), YRES(2) + (iButtonH * m_pPlayerPanels.Count()) );
// These need to all be layout-complete before we can position the player panels,
// because the scrollbar will cause the playerlist entries to move when it lays out.
m_pPlayerList->InvalidateLayout( true );
m_pPlayerListScroller->InvalidateLayout( true );
m_pPlayerListScroller->GetScrollbar()->InvalidateLayout( true );
for ( int i = 0; i < m_pPlayerPanels.Count(); i++ )
{
m_pPlayerPanels[i]->SetPos( 0, YRES(2) + (iButtonH * i) );
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSelectPlayerDialog::OnCommand( const char *command )
{
if ( !Q_stricmp( command, "cancel" ) )
{
if ( m_iCurrentState != SPDS_SELECTING_PLAYER )
{
m_iCurrentState = SPDS_SELECTING_PLAYER;
UpdateState();
return;
}
TFModalStack()->PopModal( this );
SetVisible( false );
MarkForDeletion();
if ( GetParent() )
{
PostMessage( GetParent(), new KeyValues("CancelSelection") );
}
return;
}
else if ( !Q_stricmp( command, "friends" ) )
{
m_iCurrentState = SPDS_SELECTING_FROM_FRIENDS;
UpdateState();
return;
}
else if ( !Q_stricmp( command, "server" ) )
{
m_iCurrentState = SPDS_SELECTING_FROM_SERVER;
UpdateState();
return;
}
else if ( !Q_strnicmp( command, "select_player", 13 ) )
{
int iPlayer = atoi( command + 13 ) - 1;
if ( iPlayer >= 0 && iPlayer < m_PlayerInfoList.Count() )
{
m_iCurrentState = SPDS_SELECTING_PLAYER;
OnCommand( "cancel" );
OnSelectPlayer( m_PlayerInfoList[iPlayer].m_steamID );
}
return;
}
BaseClass::OnCommand( command );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSelectPlayerDialog::UpdateState( void )
{
for ( int i = 0; i < SPDS_NUM_STATES; i++ )
{
if ( !m_pStatePanels[i] )
continue;
m_pStatePanels[i]->SetVisible( m_iCurrentState == i );
}
if ( m_pSelectFromServerButton )
{
m_pSelectFromServerButton->SetEnabled( engine->IsInGame() );
}
if ( m_iCurrentState == SPDS_SELECTING_PLAYER )
{
m_pCancelButton->SetText( g_pVGuiLocalize->Find( "#Cancel" ) );
}
else
{
m_pCancelButton->SetText( g_pVGuiLocalize->Find( "#TF_Back" ) );
}
switch ( m_iCurrentState )
{
case SPDS_SELECTING_FROM_FRIENDS:
SetupSelectFriends();
break;
case SPDS_SELECTING_FROM_SERVER:
SetupSelectServer( false );
break;
case SPDS_SELECTING_PLAYER:
default:
m_pPlayerListScroller->SetVisible( false );
break;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSelectPlayerDialog::SetupSelectFriends( void )
{
// @todo optional check to see if friend is on my server
if ( m_bAllowOutsideServer == false )
{
SetupSelectServer( true );
return;
}
m_PlayerInfoList.Purge();
if ( steamapicontext && steamapicontext->SteamFriends() )
{
// Get our game info so we can use that to test if our friends are connected to the same game as us
FriendGameInfo_t myGameInfo;
CSteamID mySteamID = steamapicontext->SteamUser()->GetSteamID();
steamapicontext->SteamFriends()->GetFriendGamePlayed( mySteamID, &myGameInfo );
int iFriends = steamapicontext->SteamFriends()->GetFriendCount( k_EFriendFlagImmediate );
for ( int i = 0; i < iFriends; i++ )
{
CSteamID friendSteamID = steamapicontext->SteamFriends()->GetFriendByIndex( i, k_EFriendFlagImmediate );
FriendGameInfo_t gameInfo;
if ( !AllowOutOfGameFriends() && !steamapicontext->SteamFriends()->GetFriendGamePlayed( friendSteamID, &gameInfo ) )
continue;
// Friends is in-game. Make sure it's TF2.
if ( AllowOutOfGameFriends() || (gameInfo.m_gameID.IsValid() && gameInfo.m_gameID == myGameInfo.m_gameID) )
{
const char *pszName = steamapicontext->SteamFriends()->GetFriendPersonaName( friendSteamID );
int idx = m_PlayerInfoList.AddToTail();
partner_info_t &info = m_PlayerInfoList[idx];
info.m_steamID = friendSteamID;
info.m_name = pszName;
}
}
}
UpdatePlayerList();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSelectPlayerDialog::SetupSelectServer( bool bFriendsOnly )
{
m_PlayerInfoList.Purge();
if ( steamapicontext && steamapicontext->SteamUtils() )
{
for( int iPlayerIndex = 1 ; iPlayerIndex <= MAX_PLAYERS; iPlayerIndex++ )
{
// find all players who are on the local player's team
int iLocalPlayerIndex = GetLocalPlayerIndex();
if( ( iPlayerIndex != iLocalPlayerIndex ) && ( g_PR->IsConnected( iPlayerIndex ) ) )
{
player_info_t pi;
if ( !engine->GetPlayerInfo( iPlayerIndex, &pi ) )
continue;
if ( !pi.friendsID )
continue;
CSteamID steamID( pi.friendsID, 1, GetUniverse(), k_EAccountTypeIndividual );
if ( bFriendsOnly )
{
EFriendRelationship eRelationship = steamapicontext->SteamFriends()->GetFriendRelationship( steamID );
if ( eRelationship != k_EFriendRelationshipFriend )
{
continue;
}
}
if ( g_PR->GetTeam( iPlayerIndex ) != TF_TEAM_RED && g_PR->GetTeam( iPlayerIndex ) != TF_TEAM_BLUE )
continue;
if ( m_bAllowSameTeam == false )
{
if ( GetLocalPlayerTeam() == g_PR->GetTeam( iPlayerIndex ) )
{
continue;
}
}
int idx = m_PlayerInfoList.AddToTail();
partner_info_t &info = m_PlayerInfoList[idx];
info.m_steamID = steamID;
info.m_name = pi.name;
}
}
}
UpdatePlayerList();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSelectPlayerDialog::UpdatePlayerList( void )
{
vgui::Label *pLabelEmpty = dynamic_cast<vgui::Label*>( m_pStatePanels[m_iCurrentState]->FindChildByName("EmptyPlayerListLabel") );
vgui::Label *pLabelQuery = dynamic_cast<vgui::Label*>( m_pStatePanels[m_iCurrentState]->FindChildByName("QueryLabel") );
// If we have no players in our list, show the no-player label.
if ( m_PlayerInfoList.Count() == 0 )
{
if ( pLabelEmpty )
{
pLabelEmpty->SetVisible( true );
}
if ( pLabelQuery )
{
pLabelQuery->SetVisible( false );
}
return;
}
// First, reapply any KVs we have to reapply
if ( m_bReapplyButtonKVs )
{
m_bReapplyButtonKVs = false;
if ( m_pButtonKV )
{
FOR_EACH_VEC( m_pPlayerPanels, i )
{
m_pPlayerPanels[i]->ApplySettings( m_pButtonKV );
}
}
}
// sort by name
m_PlayerInfoList.Sort( &SortPartnerInfoFunc );
// Otherwise, build the player panels from the list of steam IDs
for ( int i = 0; i < m_PlayerInfoList.Count(); i++ )
{
if ( m_pPlayerPanels.Count() <= i )
{
m_pPlayerPanels.AddToTail();
m_pPlayerPanels[i] = new CSelectPlayerTargetPanel( m_pPlayerList, VarArgs("player%d",i) );
m_pPlayerPanels[i]->GetButton()->SetCommand( VarArgs("select_player%d",i+1) );
m_pPlayerPanels[i]->GetButton()->AddActionSignalTarget( this );
m_pPlayerPanels[i]->GetAvatar()->SetShouldDrawFriendIcon( false );
m_pPlayerPanels[i]->GetAvatar()->SetMouseInputEnabled( false );
if ( m_pButtonKV )
{
m_pPlayerPanels[i]->ApplySettings( m_pButtonKV );
m_pPlayerPanels[i]->InvalidateLayout( true );
}
}
m_pPlayerPanels[i]->SetInfo( m_PlayerInfoList[i].m_steamID, m_PlayerInfoList[i].m_name );
}
m_pPlayerListScroller->GetScrollbar()->SetAutohideButtons( true );
m_pPlayerListScroller->GetScrollbar()->SetValue( 0 );
// Remove any extra player panels
for ( int i = m_pPlayerPanels.Count()-1; i >= m_PlayerInfoList.Count(); i-- )
{
m_pPlayerPanels[i]->MarkForDeletion();
m_pPlayerPanels.Remove(i);
}
if ( pLabelEmpty )
{
pLabelEmpty->SetVisible( false );
}
if ( pLabelQuery )
{
pLabelQuery->SetVisible( true );
}
m_pPlayerListScroller->SetVisible( true );
InvalidateLayout();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSelectPlayerTargetPanel::SetInfo( const CSteamID &steamID, const char *pszName )
{
if ( !steamapicontext || !steamapicontext->SteamFriends() )
return;
m_pAvatar->SetPlayer( steamID, k_EAvatarSize64x64 );
m_pButton->SetText( pszName );
}
| 12,784 | 4,654 |
#include <cstdio>
#include "AMReX_LevelBld.H"
#include <AMReX_ParmParse.H>
#include "Castro.H"
#include "Castro_F.H"
#ifdef AMREX_DIMENSION_AGNOSTIC
#include "Castro_bc_fill_nd_F.H"
#include "Castro_bc_fill_nd.H"
#else
#include "Castro_bc_fill_F.H"
#include "Castro_bc_fill.H"
#endif
#include "Castro_generic_fill_F.H"
#include "Castro_generic_fill.H"
#include <Derive_F.H>
#include "Derive.H"
#ifdef RADIATION
# include "Radiation.H"
# include "RAD_F.H"
#endif
#include "AMReX_buildInfo.H"
using std::string;
using namespace amrex;
static Box the_same_box (const Box& b) { return b; }
static Box grow_box_by_one (const Box& b) { return amrex::grow(b,1); }
typedef StateDescriptor::BndryFunc BndryFunc;
//
// Components are:
// Interior, Inflow, Outflow, Symmetry, SlipWall, NoSlipWall
//
static int scalar_bc[] =
{
INT_DIR, EXT_DIR, FOEXTRAP, REFLECT_EVEN, REFLECT_EVEN, REFLECT_EVEN
};
static int norm_vel_bc[] =
{
INT_DIR, EXT_DIR, FOEXTRAP, REFLECT_ODD, REFLECT_ODD, REFLECT_ODD
};
static int tang_vel_bc[] =
{
INT_DIR, EXT_DIR, FOEXTRAP, REFLECT_EVEN, REFLECT_EVEN, REFLECT_EVEN
};
static
void
set_scalar_bc (BCRec& bc, const BCRec& phys_bc)
{
const int* lo_bc = phys_bc.lo();
const int* hi_bc = phys_bc.hi();
for (int i = 0; i < BL_SPACEDIM; i++)
{
bc.setLo(i,scalar_bc[lo_bc[i]]);
bc.setHi(i,scalar_bc[hi_bc[i]]);
}
}
static
void
set_x_vel_bc(BCRec& bc, const BCRec& phys_bc)
{
const int* lo_bc = phys_bc.lo();
const int* hi_bc = phys_bc.hi();
bc.setLo(0,norm_vel_bc[lo_bc[0]]);
bc.setHi(0,norm_vel_bc[hi_bc[0]]);
#if (BL_SPACEDIM >= 2)
bc.setLo(1,tang_vel_bc[lo_bc[1]]);
bc.setHi(1,tang_vel_bc[hi_bc[1]]);
#endif
#if (BL_SPACEDIM == 3)
bc.setLo(2,tang_vel_bc[lo_bc[2]]);
bc.setHi(2,tang_vel_bc[hi_bc[2]]);
#endif
}
static
void
set_y_vel_bc(BCRec& bc, const BCRec& phys_bc)
{
const int* lo_bc = phys_bc.lo();
const int* hi_bc = phys_bc.hi();
bc.setLo(0,tang_vel_bc[lo_bc[0]]);
bc.setHi(0,tang_vel_bc[hi_bc[0]]);
#if (BL_SPACEDIM >= 2)
bc.setLo(1,norm_vel_bc[lo_bc[1]]);
bc.setHi(1,norm_vel_bc[hi_bc[1]]);
#endif
#if (BL_SPACEDIM == 3)
bc.setLo(2,tang_vel_bc[lo_bc[2]]);
bc.setHi(2,tang_vel_bc[hi_bc[2]]);
#endif
}
static
void
set_z_vel_bc(BCRec& bc, const BCRec& phys_bc)
{
const int* lo_bc = phys_bc.lo();
const int* hi_bc = phys_bc.hi();
bc.setLo(0,tang_vel_bc[lo_bc[0]]);
bc.setHi(0,tang_vel_bc[hi_bc[0]]);
#if (BL_SPACEDIM >= 2)
bc.setLo(1,tang_vel_bc[lo_bc[1]]);
bc.setHi(1,tang_vel_bc[hi_bc[1]]);
#endif
#if (BL_SPACEDIM == 3)
bc.setLo(2,norm_vel_bc[lo_bc[2]]);
bc.setHi(2,norm_vel_bc[hi_bc[2]]);
#endif
}
void
Castro::variableSetUp ()
{
// Castro::variableSetUp is called in the constructor of Amr.cpp, so
// it should get called every time we start or restart a job
// initialize the start time for our CPU-time tracker
startCPUTime = ParallelDescriptor::second();
// Output the git commit hashes used to build the executable.
if (ParallelDescriptor::IOProcessor()) {
const char* castro_hash = buildInfoGetGitHash(1);
const char* amrex_hash = buildInfoGetGitHash(2);
const char* microphysics_hash = buildInfoGetGitHash(3);
const char* buildgithash = buildInfoGetBuildGitHash();
const char* buildgitname = buildInfoGetBuildGitName();
if (strlen(castro_hash) > 0) {
std::cout << "\n" << "Castro git describe: " << castro_hash << "\n";
}
if (strlen(amrex_hash) > 0) {
std::cout << "AMReX git describe: " << amrex_hash << "\n";
}
if (strlen(microphysics_hash) > 0) {
std::cout << "Microphysics git describe: " << microphysics_hash << "\n";
}
if (strlen(buildgithash) > 0){
std::cout << buildgitname << " git describe: " << buildgithash << "\n";
}
std::cout << "\n";
}
BL_ASSERT(desc_lst.size() == 0);
// Get options, set phys_bc
read_params();
// Initialize the runtime parameters for any of the external
// microphysics
extern_init();
// Initialize the network
network_init();
#ifdef REACTIONS
// Initialize the burner
burner_init();
#endif
#ifdef SPONGE
// Initialize the sponge
sponge_init();
#endif
// Initialize the amr info
amrinfo_init();
const int dm = BL_SPACEDIM;
//
// Set number of state variables and pointers to components
//
// Get the number of species from the network model.
ca_get_num_spec(&NumSpec);
// Get the number of auxiliary quantities from the network model.
ca_get_num_aux(&NumAux);
// Get the number of advected quantities -- set at compile time
ca_get_num_adv(&NumAdv);
#include "set_conserved.H"
NUM_STATE = cnt;
#include "set_primitive.H"
#include "set_godunov.H"
// Define NUM_GROW from the f90 module.
ca_get_method_params(&NUM_GROW);
const Real run_strt = ParallelDescriptor::second() ;
// Read in the input values to Fortran.
ca_set_castro_method_params();
// set the conserved, primitive, aux, and godunov indices in Fortran
ca_set_method_params(dm, Density, Xmom,
#ifdef HYBRID_MOMENTUM
Rmom,
#endif
Eden, Eint, Temp, FirstAdv, FirstSpec, FirstAux,
#ifdef SHOCK_VAR
Shock,
#endif
#ifdef MHD
QMAGX, QMAGY, QMAGZ,
#endif
#ifdef RADIATION
QPTOT, QREITOT, QRAD,
#endif
QRHO,
QU, QV, QW,
QGAME, QGC, QPRES, QREINT,
QTEMP,
QFA, QFS, QFX,
#ifdef RADIATION
GDLAMS, GDERADS,
#endif
GDRHO, GDU, GDV, GDW,
GDPRES, GDGAME);
// Get the number of primitive variables from Fortran.
ca_get_nqsrc(&NQSRC);
// and the auxiliary variables
ca_get_nqaux(&NQAUX);
// and the number of primitive variable source terms
ca_get_nqsrc(&NQSRC);
// initialize the Godunov state array used in hydro
ca_get_ngdnv(&NGDNV);
// NQ will be used to dimension the primitive variable state
// vector it will include the "pure" hydrodynamical variables +
// any radiation variables
ca_get_nq(&NQ);
Real run_stop = ParallelDescriptor::second() - run_strt;
ParallelDescriptor::ReduceRealMax(run_stop,ParallelDescriptor::IOProcessorNumber());
if (ParallelDescriptor::IOProcessor())
std::cout << "\nTime in ca_set_method_params: " << run_stop << '\n' ;
const Geometry& dgeom = DefaultGeometry();
const int coord_type = dgeom.Coord();
// Get the center variable from the inputs and pass it directly to Fortran.
Vector<Real> center(BL_SPACEDIM, 0.0);
ParmParse ppc("castro");
ppc.queryarr("center",center,0,BL_SPACEDIM);
ca_set_problem_params(dm,phys_bc.lo(),phys_bc.hi(),
Interior,Inflow,Outflow,Symmetry,SlipWall,NoSlipWall,coord_type,
dgeom.ProbLo(),dgeom.ProbHi(),center.dataPtr());
// Read in the parameters for the tagging criteria
// and store them in the Fortran module.
const int probin_file_length = probin_file.length();
Vector<int> probin_file_name(probin_file_length);
for (int i = 0; i < probin_file_length; i++)
probin_file_name[i] = probin_file[i];
ca_get_tagging_params(probin_file_name.dataPtr(),&probin_file_length);
#ifdef SPONGE
// Read in the parameters for the sponge
// and store them in the Fortran module.
ca_get_sponge_params(probin_file_name.dataPtr(),&probin_file_length);
#endif
Interpolater* interp;
if (state_interp_order == 0) {
interp = &pc_interp;
}
else {
if (lin_limit_state_interp == 1)
interp = &lincc_interp;
else
interp = &cell_cons_interp;
}
#ifdef RADIATION
// cell_cons_interp is not conservative in spherical coordinates.
// We could do this for other cases too, but I'll confine it to
// neutrino problems for now so as not to change the results of
// other people's tests. Better to fix cell_cons_interp!
if (dgeom.IsSPHERICAL() && Radiation::nNeutrinoSpecies > 0) {
interp = &pc_interp;
}
#endif
// Note that the default is state_data_extrap = false,
// store_in_checkpoint = true. We only need to put these in
// explicitly if we want to do something different,
// like not store the state data in a checkpoint directory
bool state_data_extrap = false;
bool store_in_checkpoint;
#ifdef RADIATION
// Radiation should always have at least one ghost zone.
int ngrow_state = std::max(1, state_nghost);
#else
int ngrow_state = state_nghost;
#endif
BL_ASSERT(ngrow_state >= 0);
store_in_checkpoint = true;
desc_lst.addDescriptor(State_Type,IndexType::TheCellType(),
StateDescriptor::Point,ngrow_state,NUM_STATE,
interp,state_data_extrap,store_in_checkpoint);
#ifdef SELF_GRAVITY
store_in_checkpoint = true;
desc_lst.addDescriptor(PhiGrav_Type, IndexType::TheCellType(),
StateDescriptor::Point, 1, 1,
&cell_cons_interp, state_data_extrap,
store_in_checkpoint);
store_in_checkpoint = false;
desc_lst.addDescriptor(Gravity_Type,IndexType::TheCellType(),
StateDescriptor::Point,NUM_GROW,3,
&cell_cons_interp,state_data_extrap,store_in_checkpoint);
#endif
// Source terms -- for the CTU method, because we do characteristic
// tracing on the source terms, we need NUM_GROW ghost cells to do
// the reconstruction. For MOL and SDC, on the other hand, we only
// need 1 (for the fourth-order stuff). Simplified SDC uses the CTU
// advance, so it behaves the same way as CTU here.
store_in_checkpoint = true;
int source_ng;
if (time_integration_method == CornerTransportUpwind || time_integration_method == SimplifiedSpectralDeferredCorrections) {
source_ng = NUM_GROW;
}
else if (time_integration_method == MethodOfLines || time_integration_method == SpectralDeferredCorrections) {
source_ng = 1;
}
else {
amrex::Error("Unknown time_integration_method");
}
desc_lst.addDescriptor(Source_Type, IndexType::TheCellType(),
StateDescriptor::Point, source_ng, NUM_STATE,
&cell_cons_interp, state_data_extrap, store_in_checkpoint);
#ifdef ROTATION
store_in_checkpoint = false;
desc_lst.addDescriptor(PhiRot_Type, IndexType::TheCellType(),
StateDescriptor::Point, 1, 1,
&cell_cons_interp, state_data_extrap,
store_in_checkpoint);
store_in_checkpoint = false;
desc_lst.addDescriptor(Rotation_Type,IndexType::TheCellType(),
StateDescriptor::Point,NUM_GROW,3,
&cell_cons_interp,state_data_extrap,store_in_checkpoint);
#endif
#ifdef REACTIONS
// Components 0:Numspec-1 are omegadot_i
// Component NumSpec is enuc = (eout-ein)
// Component NumSpec+1 is rho_enuc= rho * (eout-ein)
store_in_checkpoint = true;
desc_lst.addDescriptor(Reactions_Type,IndexType::TheCellType(),
StateDescriptor::Point,0,NumSpec+2,
&cell_cons_interp,state_data_extrap,store_in_checkpoint);
#endif
#ifdef REACTIONS
// For simplified SDC, we want to store the reactions source.
if (time_integration_method == SimplifiedSpectralDeferredCorrections) {
store_in_checkpoint = true;
desc_lst.addDescriptor(Simplified_SDC_React_Type, IndexType::TheCellType(),
StateDescriptor::Point, NUM_GROW, NQSRC,
&cell_cons_interp, state_data_extrap, store_in_checkpoint);
}
#endif
Vector<BCRec> bcs(NUM_STATE);
Vector<std::string> name(NUM_STATE);
BCRec bc;
set_scalar_bc(bc, phys_bc);
bcs[Density] = bc;
name[Density] = "density";
set_x_vel_bc(bc, phys_bc);
bcs[Xmom] = bc;
name[Xmom] = "xmom";
set_y_vel_bc(bc, phys_bc);
bcs[Ymom] = bc;
name[Ymom] = "ymom";
set_z_vel_bc(bc, phys_bc);
bcs[Zmom] = bc;
name[Zmom] = "zmom";
#ifdef HYBRID_MOMENTUM
set_scalar_bc(bc, phys_bc);
bcs[Rmom] = bc;
name[Rmom] = "rmom";
set_scalar_bc(bc, phys_bc);
bcs[Lmom] = bc;
name[Lmom] = "lmom";
set_scalar_bc(bc, phys_bc);
bcs[Pmom] = bc;
name[Pmom] = "pmom";
#endif
set_scalar_bc(bc, phys_bc);
bcs[Eden] = bc;
name[Eden] = "rho_E";
set_scalar_bc(bc, phys_bc);
bcs[Eint] = bc;
name[Eint] = "rho_e";
set_scalar_bc(bc, phys_bc);
bcs[Temp] = bc;
name[Temp] = "Temp";
for (int i=0; i<NumAdv; ++i)
{
char buf[64];
sprintf(buf, "adv_%d", i);
set_scalar_bc(bc, phys_bc);
bcs[FirstAdv+i] = bc;
name[FirstAdv+i] = string(buf);
}
// Get the species names from the network model.
std::vector<std::string> spec_names;
for (int i = 0; i < NumSpec; i++) {
int len = 20;
Vector<int> int_spec_names(len);
// This call return the actual length of each string in "len"
ca_get_spec_names(int_spec_names.dataPtr(),&i,&len);
char char_spec_names[len+1];
for (int j = 0; j < len; j++)
char_spec_names[j] = int_spec_names[j];
char_spec_names[len] = '\0';
spec_names.push_back(std::string(char_spec_names));
}
if ( ParallelDescriptor::IOProcessor())
{
std::cout << NumSpec << " Species: " << std::endl;
for (int i = 0; i < NumSpec; i++)
std::cout << spec_names[i] << ' ' << ' ';
std::cout << std::endl;
}
for (int i=0; i<NumSpec; ++i)
{
set_scalar_bc(bc, phys_bc);
bcs[FirstSpec+i] = bc;
name[FirstSpec+i] = "rho_" + spec_names[i];
}
// Get the auxiliary names from the network model.
std::vector<std::string> aux_names;
for (int i = 0; i < NumAux; i++) {
int len = 20;
Vector<int> int_aux_names(len);
// This call return the actual length of each string in "len"
ca_get_aux_names(int_aux_names.dataPtr(),&i,&len);
char char_aux_names[len+1];
for (int j = 0; j < len; j++)
char_aux_names[j] = int_aux_names[j];
char_aux_names[len] = '\0';
aux_names.push_back(std::string(char_aux_names));
}
if ( ParallelDescriptor::IOProcessor())
{
std::cout << NumAux << " Auxiliary Variables: " << std::endl;
for (int i = 0; i < NumAux; i++)
std::cout << aux_names[i] << ' ' << ' ';
std::cout << std::endl;
}
for (int i=0; i<NumAux; ++i)
{
set_scalar_bc(bc, phys_bc);
bcs[FirstAux+i] = bc;
name[FirstAux+i] = "rho_" + aux_names[i];
}
#ifdef SHOCK_VAR
set_scalar_bc(bc, phys_bc);
bcs[Shock] = bc;
name[Shock] = "Shock";
#endif
desc_lst.setComponent(State_Type,
Density,
name,
bcs,
BndryFunc(ca_denfill,ca_hypfill));
#ifdef SELF_GRAVITY
set_scalar_bc(bc,phys_bc);
desc_lst.setComponent(PhiGrav_Type,0,"phiGrav",bc,BndryFunc(ca_phigravfill));
set_x_vel_bc(bc,phys_bc);
desc_lst.setComponent(Gravity_Type,0,"grav_x",bc,BndryFunc(ca_gravxfill));
set_y_vel_bc(bc,phys_bc);
desc_lst.setComponent(Gravity_Type,1,"grav_y",bc,BndryFunc(ca_gravyfill));
set_z_vel_bc(bc,phys_bc);
desc_lst.setComponent(Gravity_Type,2,"grav_z",bc,BndryFunc(ca_gravzfill));
#endif
#ifdef ROTATION
set_scalar_bc(bc,phys_bc);
desc_lst.setComponent(PhiRot_Type,0,"phiRot",bc,BndryFunc(ca_phirotfill));
set_x_vel_bc(bc,phys_bc);
desc_lst.setComponent(Rotation_Type,0,"rot_x",bc,BndryFunc(ca_rotxfill));
set_y_vel_bc(bc,phys_bc);
desc_lst.setComponent(Rotation_Type,1,"rot_y",bc,BndryFunc(ca_rotyfill));
set_z_vel_bc(bc,phys_bc);
desc_lst.setComponent(Rotation_Type,2,"rot_z",bc,BndryFunc(ca_rotzfill));
#endif
// Source term array will use standard hyperbolic fill.
Vector<BCRec> source_bcs(NUM_STATE);
Vector<std::string> state_type_source_names(NUM_STATE);
for (int i = 0; i < NUM_STATE; ++i) {
state_type_source_names[i] = name[i] + "_source";
source_bcs[i] = bcs[i];
// Replace inflow BCs with FOEXTRAP.
for (int j = 0; j < AMREX_SPACEDIM; ++j) {
if (source_bcs[i].lo(j) == EXT_DIR)
source_bcs[i].setLo(j, FOEXTRAP);
if (source_bcs[i].hi(j) == EXT_DIR)
source_bcs[i].setHi(j, FOEXTRAP);
}
}
desc_lst.setComponent(Source_Type,Density,state_type_source_names,source_bcs,
BndryFunc(ca_generic_single_fill,ca_generic_multi_fill));
#ifdef REACTIONS
std::string name_react;
for (int i=0; i<NumSpec; ++i)
{
set_scalar_bc(bc,phys_bc);
name_react = "omegadot_" + spec_names[i];
desc_lst.setComponent(Reactions_Type, i, name_react, bc,BndryFunc(ca_reactfill));
}
desc_lst.setComponent(Reactions_Type, NumSpec , "enuc", bc, BndryFunc(ca_reactfill));
desc_lst.setComponent(Reactions_Type, NumSpec+1, "rho_enuc", bc, BndryFunc(ca_reactfill));
#endif
#ifdef REACTIONS
if (time_integration_method == SimplifiedSpectralDeferredCorrections) {
for (int i = 0; i < NQSRC; ++i) {
char buf[64];
sprintf(buf, "sdc_react_source_%d", i);
set_scalar_bc(bc,phys_bc);
// Replace inflow BCs with FOEXTRAP.
for (int j = 0; j < AMREX_SPACEDIM; ++j) {
if (bc.lo(j) == EXT_DIR)
bc.setLo(j, FOEXTRAP);
if (bc.hi(j) == EXT_DIR)
bc.setHi(j, FOEXTRAP);
}
desc_lst.setComponent(Simplified_SDC_React_Type,i,std::string(buf),bc,BndryFunc(ca_generic_single_fill));
}
}
#endif
#ifdef RADIATION
int ngrow = 1;
int ncomp = Radiation::nGroups;
desc_lst.addDescriptor(Rad_Type, IndexType::TheCellType(),
StateDescriptor::Point, ngrow, ncomp,
interp);
set_scalar_bc(bc,phys_bc);
if (ParallelDescriptor::IOProcessor()) {
std::cout << "Radiation::nGroups = " << Radiation::nGroups << std::endl;
std::cout << "Radiation::nNeutrinoSpecies = "
<< Radiation::nNeutrinoSpecies << std::endl;
if (Radiation::nNeutrinoSpecies > 0) {
std::cout << "Radiation::nNeutrinoGroups = ";
for (int n = 0; n < Radiation::nNeutrinoSpecies; n++) {
std::cout << " " << Radiation::nNeutrinoGroups[n];
}
std::cout << std::endl;
if (Radiation::nNeutrinoGroups[0] > 0 &&
NumAdv != 0) {
amrex::Error("Neutrino solver assumes NumAdv == 0");
}
if (Radiation::nNeutrinoGroups[0] > 0 &&
(NumSpec != 1 || NumAux != 1)) {
amrex::Error("Neutrino solver assumes NumSpec == NumAux == 1");
}
}
}
char rad_name[10];
if (!Radiation::do_multigroup) {
desc_lst
.setComponent(Rad_Type, Rad, "rad", bc,
BndryFunc(ca_radfill));
}
else {
if (Radiation::nNeutrinoSpecies == 0 ||
Radiation::nNeutrinoGroups[0] == 0) {
for (int i = 0; i < Radiation::nGroups; i++) {
sprintf(rad_name, "rad%d", i);
desc_lst
.setComponent(Rad_Type, i, rad_name, bc,
BndryFunc(ca_radfill));
}
}
else {
int indx = 0;
for (int j = 0; j < Radiation::nNeutrinoSpecies; j++) {
for (int i = 0; i < Radiation::nNeutrinoGroups[j]; i++) {
sprintf(rad_name, "rads%dg%d", j, i);
desc_lst.setComponent(Rad_Type, indx, rad_name, bc, BndryFunc(ca_radfill));
indx++;
}
}
}
}
#endif
// some optional State_Type's -- since these depend on the value of
// runtime parameters, we don't add these to the enum, but instead
// add them to the count of State_Type's if we will use them
if (use_custom_knapsack_weights) {
Knapsack_Weight_Type = desc_lst.size();
desc_lst.addDescriptor(Knapsack_Weight_Type, IndexType::TheCellType(),
StateDescriptor::Point,
0, 1, &pc_interp);
// Because we use piecewise constant interpolation, we do not use bc and BndryFunc.
desc_lst.setComponent(Knapsack_Weight_Type, 0, "KnapsackWeight",
bc, BndryFunc(ca_nullfill));
}
#ifdef REACTIONS
if (time_integration_method == SpectralDeferredCorrections && (mol_order == 4 || sdc_order == 4)) {
// we are doing 4th order reactive SDC. We need 2 ghost cells here
SDC_Source_Type = desc_lst.size();
store_in_checkpoint = false;
desc_lst.addDescriptor(SDC_Source_Type, IndexType::TheCellType(),
StateDescriptor::Point, 2, NUM_STATE,
interp, state_data_extrap, store_in_checkpoint);
// this is the same thing we do for the sources
desc_lst.setComponent(SDC_Source_Type, Density, state_type_source_names, source_bcs,
BndryFunc(ca_generic_single_fill, ca_generic_multi_fill));
}
#endif
num_state_type = desc_lst.size();
//
// DEFINE DERIVED QUANTITIES
//
// Pressure
//
derive_lst.add("pressure",IndexType::TheCellType(),1,ca_derpres,the_same_box);
derive_lst.addComponent("pressure",desc_lst,State_Type,Density,NUM_STATE);
//
// Kinetic energy
//
derive_lst.add("kineng",IndexType::TheCellType(),1,ca_derkineng,the_same_box);
derive_lst.addComponent("kineng",desc_lst,State_Type,Density,1);
derive_lst.addComponent("kineng",desc_lst,State_Type,Xmom,3);
//
// Sound speed (c)
//
derive_lst.add("soundspeed",IndexType::TheCellType(),1,ca_dersoundspeed,the_same_box);
derive_lst.addComponent("soundspeed",desc_lst,State_Type,Density,NUM_STATE);
//
// Gamma_1
//
derive_lst.add("Gamma_1",IndexType::TheCellType(),1,ca_dergamma1,the_same_box);
derive_lst.addComponent("Gamma_1",desc_lst,State_Type,Density,NUM_STATE);
//
// Mach number(M)
//
derive_lst.add("MachNumber",IndexType::TheCellType(),1,ca_dermachnumber,the_same_box);
derive_lst.addComponent("MachNumber",desc_lst,State_Type,Density,NUM_STATE);
#if (BL_SPACEDIM == 1)
//
// Wave speed u+c
//
derive_lst.add("uplusc",IndexType::TheCellType(),1,ca_deruplusc,the_same_box);
derive_lst.addComponent("uplusc",desc_lst,State_Type,Density,NUM_STATE);
//
// Wave speed u-c
//
derive_lst.add("uminusc",IndexType::TheCellType(),1,ca_deruminusc,the_same_box);
derive_lst.addComponent("uminusc",desc_lst,State_Type,Density,NUM_STATE);
#endif
//
// Gravitational forcing
//
#ifdef SELF_GRAVITY
// derive_lst.add("rhog",IndexType::TheCellType(),1,
// BL_FORT_PROC_CALL(CA_RHOG,ca_rhog),the_same_box);
// derive_lst.addComponent("rhog",desc_lst,State_Type,Density,1);
// derive_lst.addComponent("rhog",desc_lst,Gravity_Type,0,BL_SPACEDIM);
#endif
//
// Entropy (S)
//
derive_lst.add("entropy",IndexType::TheCellType(),1,ca_derentropy,the_same_box);
derive_lst.addComponent("entropy",desc_lst,State_Type,Density,NUM_STATE);
#ifdef DIFFUSION
if (diffuse_temp) {
//
// thermal conductivity (k_th)
//
derive_lst.add("thermal_cond",IndexType::TheCellType(),1,ca_dercond,the_same_box);
derive_lst.addComponent("thermal_cond",desc_lst,State_Type,Density,NUM_STATE);
//
// thermal diffusivity (k_th/(rho c_v))
//
derive_lst.add("diff_coeff",IndexType::TheCellType(),1,ca_derdiffcoeff,the_same_box);
derive_lst.addComponent("diff_coeff",desc_lst,State_Type,Density,NUM_STATE);
//
// diffusion term (the divergence of thermal flux)
//
derive_lst.add("diff_term",IndexType::TheCellType(),1,ca_derdiffterm,grow_box_by_one);
derive_lst.addComponent("diff_term",desc_lst,State_Type,Density,NUM_STATE);
}
#endif
//
// Vorticity
//
derive_lst.add("magvort",IndexType::TheCellType(),1,ca_dermagvort,grow_box_by_one);
// Here we exploit the fact that Xmom = Density + 1
// in order to use the correct interpolation.
if (Xmom != Density+1)
amrex::Error("We are assuming Xmom = Density + 1 in Castro_setup.cpp");
derive_lst.addComponent("magvort",desc_lst,State_Type,Density,4);
//
// Div(u)
//
derive_lst.add("divu",IndexType::TheCellType(),1,ca_derdivu,grow_box_by_one);
derive_lst.addComponent("divu",desc_lst,State_Type,Density,1);
derive_lst.addComponent("divu",desc_lst,State_Type,Xmom,3);
//
// Internal energy as derived from rho*E, part of the state
//
derive_lst.add("eint_E",IndexType::TheCellType(),1,ca_dereint1,the_same_box);
derive_lst.addComponent("eint_E",desc_lst,State_Type,Density,NUM_STATE);
//
// Internal energy as derived from rho*e, part of the state
//
derive_lst.add("eint_e",IndexType::TheCellType(),1,ca_dereint2,the_same_box);
derive_lst.addComponent("eint_e",desc_lst,State_Type,Density,NUM_STATE);
//
// Log(density)
//
derive_lst.add("logden",IndexType::TheCellType(),1,ca_derlogden,the_same_box);
derive_lst.addComponent("logden",desc_lst,State_Type,Density,NUM_STATE);
derive_lst.add("StateErr",IndexType::TheCellType(),3,ca_derstate,grow_box_by_one);
derive_lst.addComponent("StateErr",desc_lst,State_Type,Density,1);
derive_lst.addComponent("StateErr",desc_lst,State_Type,Temp,1);
derive_lst.addComponent("StateErr",desc_lst,State_Type,FirstSpec,1);
//
// X from rhoX
//
for (int i = 0; i < NumSpec; i++){
std::string spec_string = "X("+spec_names[i]+")";
derive_lst.add(spec_string,IndexType::TheCellType(),1,ca_derspec,the_same_box);
derive_lst.addComponent(spec_string,desc_lst,State_Type,Density,1);
derive_lst.addComponent(spec_string,desc_lst,State_Type,FirstSpec+i,1);
}
//
// Abar
//
derive_lst.add("abar",IndexType::TheCellType(),1,ca_derabar,the_same_box);
derive_lst.addComponent("abar",desc_lst,State_Type,Density,1);
derive_lst.addComponent("abar",desc_lst,State_Type,FirstSpec,NumSpec);
//
// Velocities
//
derive_lst.add("x_velocity",IndexType::TheCellType(),1,ca_dervel,the_same_box);
derive_lst.addComponent("x_velocity",desc_lst,State_Type,Density,1);
derive_lst.addComponent("x_velocity",desc_lst,State_Type,Xmom,1);
derive_lst.add("y_velocity",IndexType::TheCellType(),1,ca_dervel,the_same_box);
derive_lst.addComponent("y_velocity",desc_lst,State_Type,Density,1);
derive_lst.addComponent("y_velocity",desc_lst,State_Type,Ymom,1);
derive_lst.add("z_velocity",IndexType::TheCellType(),1,ca_dervel,the_same_box);
derive_lst.addComponent("z_velocity",desc_lst,State_Type,Density,1);
derive_lst.addComponent("z_velocity",desc_lst,State_Type,Zmom,1);
#ifdef REACTIONS
//
// Nuclear energy generation timescale t_e == e / edot
// Sound-crossing time t_s == dx / c_s
// Ratio of these is t_s_t_e == t_s / t_e
//
derive_lst.add("t_sound_t_enuc",IndexType::TheCellType(),1,ca_derenuctimescale,the_same_box);
derive_lst.addComponent("t_sound_t_enuc",desc_lst,State_Type,Density,NUM_STATE);
derive_lst.addComponent("t_sound_t_enuc",desc_lst,Reactions_Type,NumSpec,1);
#endif
derive_lst.add("magvel",IndexType::TheCellType(),1,ca_dermagvel,the_same_box);
derive_lst.addComponent("magvel",desc_lst,State_Type,Density,1);
derive_lst.addComponent("magvel",desc_lst,State_Type,Xmom,3);
derive_lst.add("radvel",IndexType::TheCellType(),1,ca_derradialvel,the_same_box);
derive_lst.addComponent("radvel",desc_lst,State_Type,Density,1);
derive_lst.addComponent("radvel",desc_lst,State_Type,Xmom,3);
derive_lst.add("magmom",IndexType::TheCellType(),1,ca_dermagmom,the_same_box);
derive_lst.addComponent("magmom",desc_lst,State_Type,Xmom,3);
derive_lst.add("angular_momentum_x",IndexType::TheCellType(),1,ca_derangmomx,the_same_box);
derive_lst.addComponent("angular_momentum_x",desc_lst,State_Type,Density,1);
derive_lst.addComponent("angular_momentum_x",desc_lst,State_Type,Xmom,3);
derive_lst.add("angular_momentum_y",IndexType::TheCellType(),1,ca_derangmomy,the_same_box);
derive_lst.addComponent("angular_momentum_y",desc_lst,State_Type,Density,1);
derive_lst.addComponent("angular_momentum_y",desc_lst,State_Type,Xmom,3);
derive_lst.add("angular_momentum_z",IndexType::TheCellType(),1,ca_derangmomz,the_same_box);
derive_lst.addComponent("angular_momentum_z",desc_lst,State_Type,Density,1);
derive_lst.addComponent("angular_momentum_z",desc_lst,State_Type,Xmom,3);
#ifdef SELF_GRAVITY
derive_lst.add("maggrav",IndexType::TheCellType(),1,ca_dermaggrav,the_same_box);
derive_lst.addComponent("maggrav",desc_lst,Gravity_Type,0,3);
#endif
#ifdef AMREX_PARTICLES
//
// We want a derived type that corresponds to the number of particles
// in each cell. We only intend to use it in plotfiles for debugging
// purposes. We'll just use the DERNULL since don't do anything in
// fortran for now. We'll actually set the values in writePlotFile().
//
derive_lst.add("particle_count",IndexType::TheCellType(),1,ca_dernull,the_same_box);
derive_lst.addComponent("particle_count",desc_lst,State_Type,Density,1);
derive_lst.add("total_particle_count",IndexType::TheCellType(),1,ca_dernull,the_same_box);
derive_lst.addComponent("total_particle_count",desc_lst,State_Type,Density,1);
#endif
#ifdef RADIATION
if (Radiation::do_multigroup) {
derive_lst.add("Ertot", IndexType::TheCellType(),1,ca_derertot,the_same_box);
derive_lst.addComponent("Ertot",desc_lst,Rad_Type,0,Radiation::nGroups);
}
#endif
#ifdef NEUTRINO
if (Radiation::nNeutrinoSpecies > 0 &&
Radiation::plot_neutrino_group_energies_per_MeV) {
char rad_name[10];
int indx = 0;
for (int j = 0; j < Radiation::nNeutrinoSpecies; j++) {
for (int i = 0; i < Radiation::nNeutrinoGroups[j]; i++) {
sprintf(rad_name, "Neuts%dg%d", j, i);
derive_lst.add(rad_name,IndexType::TheCellType(),1,ca_derneut,the_same_box);
derive_lst.addComponent(rad_name,desc_lst,Rad_Type,indx,1);
indx++;
}
}
}
if (Radiation::nNeutrinoSpecies > 0 &&
Radiation::nNeutrinoGroups[0] > 0) {
derive_lst.add("Enue", IndexType::TheCellType(),1,ca_derenue,the_same_box);
derive_lst.addComponent("Enue",desc_lst,Rad_Type,0,Radiation::nGroups);
derive_lst.add("Enuae", IndexType::TheCellType(),1,ca_derenuae,the_same_box);
derive_lst.addComponent("Enuae",desc_lst,Rad_Type,0,Radiation::nGroups);
//
// rho_Yl = rho(Ye + Ynue - Ynuebar)
//
derive_lst.add("rho_Yl",IndexType::TheCellType(),1,ca_derrhoyl,the_same_box);
// Don't actually need density for rho * Yl
derive_lst.addComponent("rho_Yl",desc_lst,State_Type,Density,1);
// FirstAux is (rho * Ye)
derive_lst.addComponent("rho_Yl",desc_lst,State_Type,FirstAux,1);
derive_lst.addComponent("rho_Yl",desc_lst,Rad_Type,0,Radiation::nGroups);
//
// Yl = (Ye + Ynue - Ynuebar)
//
derive_lst.add("Yl",IndexType::TheCellType(),1,ca_deryl,the_same_box);
derive_lst.addComponent("Yl",desc_lst,State_Type,Density,1);
// FirstAux is (rho * Ye)
derive_lst.addComponent("Yl",desc_lst,State_Type,FirstAux,1);
derive_lst.addComponent("Yl",desc_lst,Rad_Type,0,Radiation::nGroups);
//
// Ynue
//
derive_lst.add("Ynue",IndexType::TheCellType(),1,ca_derynue,the_same_box);
derive_lst.addComponent("Ynue",desc_lst,State_Type,Density,1);
// FirstAux is (rho * Ye)
derive_lst.addComponent("Ynue",desc_lst,State_Type,FirstAux,1);
derive_lst.addComponent("Ynue",desc_lst,Rad_Type,0,Radiation::nGroups);
//
// Ynuebar
//
derive_lst.add("Ynuae",IndexType::TheCellType(),1,ca_derynuae,the_same_box);
derive_lst.addComponent("Ynuae",desc_lst,State_Type,Density,1);
// FirstAux is (rho * Ye)
derive_lst.addComponent("Ynuae",desc_lst,State_Type,FirstAux,1);
derive_lst.addComponent("Ynuae",desc_lst,Rad_Type,0,Radiation::nGroups);
}
#endif
for (int i = 0; i < NumAux; i++) {
derive_lst.add(aux_names[i],IndexType::TheCellType(),1,ca_derspec,the_same_box);
derive_lst.addComponent(aux_names[i],desc_lst,State_Type,Density,1);
derive_lst.addComponent(aux_names[i],desc_lst,State_Type,FirstAux+i,1);
}
#if 0
//
// A derived quantity equal to all the state variables.
//
derive_lst.add("FULLSTATE",IndexType::TheCellType(),NUM_STATE,FORT_DERCOPY,the_same_box);
derive_lst.addComponent("FULLSTATE",desc_lst,State_Type,Density,NUM_STATE);
#endif
//
// Problem-specific adds
#include <Problem_Derives.H>
//
// DEFINE ERROR ESTIMATION QUANTITIES
//
ErrorSetUp();
//
// Construct an array holding the names of the source terms.
//
source_names.resize(num_src);
// Fill with an empty string to initialize.
for (int n = 0; n < num_src; ++n)
source_names[n] = "";
source_names[ext_src] = "user-defined external";
source_names[thermo_src] = "pdivU source";
#ifdef SPONGE
source_names[sponge_src] = "sponge";
#endif
#ifdef DIFFUSION
source_names[diff_src] = "diffusion";
#endif
#ifdef HYBRID_MOMENTUM
source_names[hybrid_src] = "hybrid";
#endif
#ifdef GRAVITY
source_names[grav_src] = "gravity";
#endif
#ifdef ROTATION
source_names[rot_src] = "rotation";
#endif
#ifdef AMREX_USE_CUDA
// Set the minimum number of threads needed per
// threadblock to do BC fills with CUDA. We will
// force this to be 8. The reason is that it is
// not otherwise guaranteed for our thread blocks
// to be aligned with the grid in such a way that
// the synchronization logic in amrex_filccn works
// out. We need at least NUM_GROW + 1 threads in a
// block for CTU. If we used this minimum of 5, we
// would hit cases where this doesn't work since
// our blocking_factor is usually a power of 2, and
// the thread blocks would not be aligned to guarantee
// that the threadblocks containing the ghost zones
// contained all of the ghost zones, as well as the
// required interior zone. And for reflecting BCs,
// we need NUM_GROW * 2 == 8 threads anyway. This logic
// then requires that blocking_factor be a multiple
// of 8. It is a little wasteful for MOL/SDC and for
// problems that only have outflow BCs, but the BC
// fill is not the expensive part of the algorithm
// for our production science problems anyway, so
// we ignore this extra cost in favor of safety.
for (int dim = 0; dim < AMREX_SPACEDIM; ++dim) {
numBCThreadsMin[dim] = 8;
}
#endif
// method of lines Butcher tableau
if (mol_order == 1) {
// first order Euler
MOL_STAGES = 1;
a_mol.resize(MOL_STAGES);
for (int n = 0; n < MOL_STAGES; ++n)
a_mol[n].resize(MOL_STAGES);
a_mol[0] = {1};
b_mol = {1.0};
c_mol = {0.0};
} else if (mol_order == 2) {
// second order TVD
MOL_STAGES = 2;
a_mol.resize(MOL_STAGES);
for (int n = 0; n < MOL_STAGES; ++n)
a_mol[n].resize(MOL_STAGES);
a_mol[0] = {0, 0,};
a_mol[1] = {1.0, 0,};
b_mol = {0.5, 0.5};
c_mol = {0.0, 1.0};
} else if (mol_order == 3) {
// third order TVD
MOL_STAGES = 3;
a_mol.resize(MOL_STAGES);
for (int n = 0; n < MOL_STAGES; ++n)
a_mol[n].resize(MOL_STAGES);
a_mol[0] = {0.0, 0.0, 0.0};
a_mol[1] = {1.0, 0.0, 0.0};
a_mol[2] = {0.25, 0.25, 0.0};
b_mol = {1./6., 1./6., 2./3.};
c_mol = {0.0, 1.0, 0.5};
} else if (mol_order == 4) {
// fourth order TVD
MOL_STAGES = 4;
a_mol.resize(MOL_STAGES);
for (int n = 0; n < MOL_STAGES; ++n)
a_mol[n].resize(MOL_STAGES);
a_mol[0] = {0.0, 0.0, 0.0, 0.0};
a_mol[1] = {0.5, 0.0, 0.0, 0.0};
a_mol[2] = {0.0, 0.5, 0.0, 0.0};
a_mol[3] = {0.0, 0.0, 1.0, 0.0};
b_mol = {1./6., 1./3., 1./3., 1./6.};
c_mol = {0.0, 0.5, 0.5, 1.0};
} else {
amrex::Error("invalid value of mol_order\n");
}
if (sdc_order == 2) {
SDC_NODES = 2;
dt_sdc.resize(SDC_NODES);
dt_sdc = {0.0, 1.0};
} else if (sdc_order == 4) {
SDC_NODES = 3;
dt_sdc.resize(SDC_NODES);
dt_sdc = {0.0, 0.5, 1.0};
} else {
amrex::Error("invalid value of sdc_order");
}
}
| 35,174 | 14,348 |
#include <windows.h>
#define MAX_SPRITES 500
static char * sprites[MAX_SPRITES];
void add_sprite (int id, const char * sprite)
{
if ( id >= 0 && id < MAX_SPRITES )
sprites[id] = _strdup(sprite);
}
const char * sprite_lookup (int id)
{
if ( id >= 0 && id < MAX_SPRITES && sprites[id] )
return sprites[id];
else
return "unknown";
}
| 347 | 155 |
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, k;
cin >> n >> k;
vector<int> p(n);
for (int i = 0; i < n; i++)
{
cin >> p.at(i);
}
sort(p.begin(), p.end());
int ans = 0;
for (int i = 0; i < k; i++)
{
ans += p.at(i);
}
cout << ans << endl;
}
| 324 | 143 |
/*
File: osx_clipboard.cpp
Author: Taylor Robbins
Date: 10\07\2017
Description:
** Holds the functions that handle interfacing with the OSX clipboard
#included from osx_main.cpp
*/
// +==============================+
// | OSX_CopyToClipboard |
// +==============================+
// void OSX_CopyToClipboard(const void* dataPntr, u32 dataSize)
CopyToClipboard_DEFINITION(OSX_CopyToClipboard)
{
char* tempSpace = (char*)malloc(dataSize+1);
memcpy(tempSpace, dataPntr, dataSize);
tempSpace[dataSize] = '\0';
glfwSetClipboardString(PlatformInfo.window, tempSpace);
free(tempSpace);
}
// +==============================+
// | OSX_CopyFromClipboard |
// +==============================+
// void* OSX_CopyFromClipboard(MemoryArena_t* arenaPntr, u32* dataLengthOut)
CopyFromClipboard_DEFINITION(OSX_CopyFromClipboard)
{
*dataLengthOut = 0;
const char* contents = glfwGetClipboardString(PlatformInfo.window);
if (contents == nullptr) { return nullptr; }
*dataLengthOut = (u32)strlen(contents);
return (void*)contents;
}
| 1,057 | 391 |
void m() { fora (i = 0; 1; i++); }
| 35 | 21 |
#include "./utility/rt.h"
int DIM_SIZE;
int TILE_SIZE;
void stencil_trace(int *a, int *b, unsigned int dim_size, unsigned int tile_size) {
vector<int> idx;
for (int i = 1; i < dim_size+1 ; i += tile_size) {
for (int j = 1; j < dim_size+1; j += tile_size) {
for (int i_tiled = i; i_tiled < min(i+tile_size, dim_size+1); i_tiled++) {
for (int j_tiled = j; j_tiled < min(j+tile_size, dim_size+1); j_tiled++) {
idx.clear(); idx.push_back(i); idx.push_back(j); idx.push_back(i_tiled), idx.push_back(j_tiled);
b[i_tiled* (DIM_SIZE + 2) +j_tiled] = a[i_tiled* (DIM_SIZE + 2)+j_tiled] + a[i_tiled* (DIM_SIZE + 2)+j_tiled + 1] + a[i_tiled* (DIM_SIZE + 2)+j_tiled - 1] + a[(i_tiled-1)* (DIM_SIZE + 2) +j_tiled] + a[(i_tiled+1)* (DIM_SIZE + 2) +j_tiled];
rtTmpAccess(i_tiled * (DIM_SIZE + 2) + j_tiled, 0, 0, idx);
rtTmpAccess(i_tiled * (DIM_SIZE + 2) + j_tiled + 1, 1, 0, idx);
rtTmpAccess(i_tiled * (DIM_SIZE + 2) + j_tiled - 1, 2, 0, idx);
rtTmpAccess( (i_tiled-1) * (DIM_SIZE + 2) + j_tiled, 3, 0, idx);
rtTmpAccess( (i_tiled+1) * (DIM_SIZE + 2) + j_tiled, 4, 0, idx);
rtTmpAccess(i_tiled * (DIM_SIZE + 2) + j_tiled + (DIM_SIZE + 2)* (DIM_SIZE + 2), 5, 0, idx);
}
}
}
}
return;
}
int main(int argc, char* argv[]) {
if (argc != 3) {
cout << "This benchmark needs 1 loop bounds" << endl;
return 0;
}
for (int i = 1; i < argc; i++) {
if (!isdigit(argv[i][0])) {
cout << "arguments must be integer" << endl;
return 0;
}
}
DIM_SIZE = stoi(argv[1]);
TILE_SIZE = stoi(argv[2]);
int* a = (int*)malloc( (DIM_SIZE+2)* (DIM_SIZE+2)*sizeof(int));
int* b = (int*)malloc( (DIM_SIZE+2)* (DIM_SIZE+2)*sizeof(int));
for (int i = 0; i < (DIM_SIZE+2) * (DIM_SIZE+2); i++) {
a[i] = i % 256;
}
stencil_trace(a, b, DIM_SIZE, TILE_SIZE);
dumpRIHistogram();
return 0;
}
| 2,182 | 970 |
//
// Copyright (c) 2015-2020 Microsoft Corporation and Contributors.
// SPDX-License-Identifier: Apache-2.0
//
#include "OfflineStorageHandler.hpp"
#include "OfflineStorageFactory.hpp"
#include "offline/MemoryStorage.hpp"
#include "ILogManager.hpp"
#include <algorithm>
#include <numeric>
#include <set>
namespace MAT_NS_BEGIN {
MATSDK_LOG_INST_COMPONENT_CLASS(OfflineStorageHandler, "EventsSDK.StorageHandler", "Events telemetry client - OfflineStorageHandler class");
OfflineStorageHandler::OfflineStorageHandler(ILogManager& logManager, IRuntimeConfig& runtimeConfig, ITaskDispatcher& taskDispatcher) :
m_observer(nullptr),
m_logManager(logManager),
m_config(runtimeConfig),
m_taskDispatcher(taskDispatcher),
m_killSwitchManager(),
m_clockSkewManager(),
m_flushPending(false),
m_offlineStorageMemory(nullptr),
m_offlineStorageDisk(nullptr),
m_readFromMemory(false),
m_lastReadCount(0),
m_shutdownStarted(false),
m_memoryDbSize(0),
m_queryDbSize(0),
m_isStorageFullNotificationSend(false)
{
// TODO: [MG] - OfflineStorage_SQLite.cpp is performing similar checks
uint32_t percentage = m_config[CFG_INT_RAMCACHE_FULL_PCT];
uint32_t cacheMemorySizeLimitInBytes = m_config[CFG_INT_RAM_QUEUE_SIZE];
if (percentage > 0 && percentage <= 100)
{
m_memoryDbSizeNotificationLimit = (percentage * cacheMemorySizeLimitInBytes) / 100;
}
else
{
// In case if user has specified bad percentage, we stick to 75%
m_memoryDbSizeNotificationLimit = (DB_FULL_NOTIFICATION_DEFAULT_PERCENTAGE * cacheMemorySizeLimitInBytes) / 100;
}
}
bool OfflineStorageHandler::isKilled(StorageRecord const& record)
{
return (
/* fast */ m_killSwitchManager.isActive() &&
/* slower */ m_killSwitchManager.isTokenBlocked(record.tenantToken));
}
void OfflineStorageHandler::WaitForFlush()
{
{
LOCKGUARD(m_flushLock);
if (!m_flushPending)
return;
}
LOG_INFO("Waiting for pending Flush (%p) to complete...", m_flushHandle.m_task);
m_flushComplete.wait();
}
OfflineStorageHandler::~OfflineStorageHandler()
{
WaitForFlush();
if (nullptr != m_offlineStorageMemory)
{
m_offlineStorageMemory.reset();
}
if (nullptr != m_offlineStorageDisk)
{
m_offlineStorageDisk.reset();
}
}
void OfflineStorageHandler::Initialize(IOfflineStorageObserver& observer)
{
m_observer = &observer;
uint32_t cacheMemorySizeLimitInBytes = m_config[CFG_INT_RAM_QUEUE_SIZE];
m_offlineStorageDisk = OfflineStorageFactory::Create(m_logManager, m_config);
m_offlineStorageDisk->Initialize(*this);
// TODO: [MG] - consider passing m_offlineStorageDisk to m_offlineStorageMemory,
// so that the Flush() op on memory storage leads to saving unflushed events to
// disk.
if (cacheMemorySizeLimitInBytes > 0)
{
m_offlineStorageMemory.reset(new MemoryStorage(m_logManager, m_config));
m_offlineStorageMemory->Initialize(*this);
}
m_shutdownStarted = false;
LOG_TRACE("Initializing offline storage handler");
}
void OfflineStorageHandler::Shutdown()
{
LOG_TRACE("Shutting down offline storage handler");
m_shutdownStarted = true;
WaitForFlush();
if (nullptr != m_offlineStorageMemory)
{
m_offlineStorageMemory->ReleaseAllRecords();
Flush();
m_offlineStorageMemory->Shutdown();
}
if (nullptr != m_offlineStorageDisk)
{
m_offlineStorageDisk->Shutdown();
}
}
/// <summary>
/// Get estimated DB size
/// </summary>
/// <returns>
/// Size of memory + disk storage
/// </returns>
/// <remarks>
/// Value may change at runtime, so it's only approximate value.
/// </remarks>
size_t OfflineStorageHandler::GetSize()
{
size_t size = 0;
if (m_offlineStorageMemory != nullptr)
size += m_offlineStorageMemory->GetSize();
if (m_offlineStorageDisk != nullptr)
size += m_offlineStorageDisk->GetSize();
return size;
}
size_t OfflineStorageHandler::GetRecordCount(EventLatency latency) const
{
size_t count = 0;
if (m_offlineStorageMemory != nullptr)
count += m_offlineStorageMemory->GetRecordCount(latency);
if (m_offlineStorageDisk != nullptr)
count += m_offlineStorageDisk->GetRecordCount(latency);
return count;
}
void OfflineStorageHandler::Flush()
{
// Flush could be executed from context of worker thread, as well as from TPM and
// after HTTP callback. Make sure it is atomic / thread-safe.
LOCKGUARD(m_flushLock);
// If item isn't scheduled yet, it gets canceled, so that we don't do two flushes.
// If we are running that item right now (our thread), then nothing happens other
// than the handle gets replaced by nullptr in this DeferredCallbackHandle obj.
m_flushHandle.Cancel();
size_t dbSizeBeforeFlush = m_offlineStorageMemory->GetSize();
if ((m_offlineStorageMemory) && (dbSizeBeforeFlush > 0) && (m_offlineStorageDisk))
{
// This will block on and then take a lock for the duration of this move, and
// StoreRecord() will then block until the move completes.
auto records = m_offlineStorageMemory->GetRecords(false, EventLatency_Unspecified);
std::vector<StorageRecordId> ids;
// TODO: [MG] - consider running the batch in transaction
// if (sqlite)
// sqlite->Execute("BEGIN");
size_t totalSaved = m_offlineStorageDisk->StoreRecords(records);
// TODO: [MG] - consider running the batch in transaction
// if (sqlite)
// sqlite->Execute("END");
// Delete records from reserved on flush
HttpHeaders dummy;
bool fromMemory = true;
m_offlineStorageMemory->DeleteRecords(ids, dummy, fromMemory);
// Notify event listener about the records cached
OnStorageRecordsSaved(totalSaved);
if (m_offlineStorageMemory->GetSize() > dbSizeBeforeFlush)
{
// We managed to accumulate as much data as we had before the flush,
// means we cannot keep up flushing at the same speed as incoming
// obviously because the disk is slower than ram.
LOG_WARN("Data is arriving too fast!");
}
}
m_isStorageFullNotificationSend = false;
// Flush is done, notify the waiters
m_flushComplete.post();
m_flushPending = false;
}
bool OfflineStorageHandler::StoreRecord(StorageRecord const& record)
{
// Don't discard on shutdown because the kill-switch may be temporary.
// Attempt to upload after restart.
if ((!m_shutdownStarted) && isKilled(record))
{
// Discard unwanted records associated with killed tenant, reporting events as dropped
return false;
}
// Check cache size only once at start
static uint32_t cacheMemorySizeLimitInBytes = m_config[CFG_INT_RAM_QUEUE_SIZE];
if (nullptr != m_offlineStorageMemory && !m_shutdownStarted)
{
auto memDbSize = m_offlineStorageMemory->GetSize();
{
// During flush, this will block on a mutex while records
// are selected and removed from the cache (but will
// not block for the subsequent handoff to persistent
// storage)
m_offlineStorageMemory->StoreRecord(record);
}
// Perform periodic flush to disk
if (memDbSize > cacheMemorySizeLimitInBytes)
{
if (m_flushLock.try_lock())
{
if (!m_flushPending)
{
m_flushPending = true;
m_flushComplete.Reset();
m_flushHandle = PAL::scheduleTask(&m_taskDispatcher, 0, this, &OfflineStorageHandler::Flush);
LOG_INFO("Requested Flush (%p)", m_flushHandle.m_task);
}
m_flushLock.unlock();
}
}
}
else
{
if (m_offlineStorageDisk != nullptr)
{
if (record.persistence != EventPersistence::EventPersistence_DoNotStoreOnDisk)
{
m_offlineStorageDisk->StoreRecord(record);
}
}
}
return true;
}
size_t OfflineStorageHandler::StoreRecords(std::vector<StorageRecord>& records)
{
size_t stored = 0;
for (auto& i : records)
{
if (StoreRecord(i))
{
++stored;
}
}
return stored;
}
bool OfflineStorageHandler::ResizeDb()
{
if (nullptr != m_offlineStorageMemory)
{
m_offlineStorageMemory->ResizeDb();
}
if (nullptr != m_offlineStorageDisk)
{
m_offlineStorageDisk->ResizeDb();
}
return true;
}
bool OfflineStorageHandler::IsLastReadFromMemory()
{
return m_readFromMemory;
}
unsigned OfflineStorageHandler::LastReadRecordCount()
{
return m_lastReadCount;
}
bool OfflineStorageHandler::GetAndReserveRecords(std::function<bool(StorageRecord&&)> const& consumer, unsigned leaseTimeMs, EventLatency minLatency, unsigned maxCount)
{
bool returnValue = false;
m_lastReadCount = 0;
m_readFromMemory = false;
if (m_offlineStorageMemory)
{
returnValue |= m_offlineStorageMemory->GetAndReserveRecords(consumer, leaseTimeMs, minLatency, maxCount);
m_lastReadCount += m_offlineStorageMemory->LastReadRecordCount();
if (m_lastReadCount <= maxCount)
maxCount -= m_lastReadCount;
m_readFromMemory = true;
// Prefer to send all of in-memory first before going to disk. This also helps in case if in-ram queue
// is larger than request size (2MB), we'd exit the function because the consumer no longer wants more
// records.
if (m_lastReadCount)
return returnValue;
}
if (m_offlineStorageDisk)
{
returnValue |= m_offlineStorageDisk->GetAndReserveRecords(consumer, leaseTimeMs, minLatency, maxCount);
auto lastOfflineReadCount = m_offlineStorageDisk->LastReadRecordCount();
if (lastOfflineReadCount)
{
m_lastReadCount += lastOfflineReadCount;
m_readFromMemory = false;
}
}
if (m_config.IsClockSkewEnabled() && !m_clockSkewManager.GetResumeTransmissionAfterClockSkew()
/* && !consumedIds.empty() */
)
{
m_clockSkewManager.GetDelta();
}
return returnValue;
}
std::vector<StorageRecord> OfflineStorageHandler::GetRecords(bool shutdown, EventLatency minLatency, unsigned maxCount)
{
// This method should not be called directly because it's a no-op
assert(false);
UNREFERENCED_PARAMETER(shutdown);
UNREFERENCED_PARAMETER(minLatency);
UNREFERENCED_PARAMETER(maxCount);
return std::vector<StorageRecord>{};
}
/**
* Delete records by API ingestion key aka "Tenant Token".
* Internal method used by DeleteRecords and ReleaseRecords
* invoked by HTTP callback thread. The scrubbing is done
* async in context where the HTTP callback is running.
*/
void OfflineStorageHandler::DeleteRecordsByKeys(const std::list<std::string>& keys)
{
for (const auto& key : keys)
{
/* DELETE * FROM events WHERE tenant_token=${key} */
DeleteRecords({{"tenant_token", key}});
}
}
/**
* Delete all records locally".
*/
void OfflineStorageHandler::DeleteAllRecords()
{
for (const auto storagePtr : { m_offlineStorageMemory.get() , m_offlineStorageDisk.get() })
{
if (storagePtr != nullptr)
{
storagePtr->DeleteAllRecords();
}
}
}
/**
* Perform scrub of both memory queue and offline storage.
*/
/// <summary>
/// Perform scrub of underlying storage systems using 'where' clause
/// </summary>
/// <param name="whereFilter">The where filter.</param>
/// <remarks>
/// whereFilter contains the key-value pairs for the
/// WHERE [key0==value0 .. keyN==valueN] clause.
/// </remarks>
void OfflineStorageHandler::DeleteRecords(const std::map<std::string, std::string>& whereFilter)
{
for (const auto storagePtr : {m_offlineStorageMemory.get(), m_offlineStorageDisk.get()})
{
if (storagePtr != nullptr)
{
storagePtr->DeleteRecords(whereFilter);
}
}
}
/// <summary>
/// Delete records that would match the set of ids or based on kill-switch header
/// </summary>
/// <param name="ids">Identifiers of records to delete</param>
/// <param name="headers">Headers may indicate "Kill-Token" several times</param>
/// <param name="fromMemory">Flag that indicates where to delete from by IDs</param>
/// <remarks>
/// IDs of records that are no longer found in the storage are silently ignored.
/// Called from the internal worker thread.
/// Killed tokens deleted from both - memory storage and offline storage if available.
/// </remarks>
void OfflineStorageHandler::DeleteRecords(std::vector<StorageRecordId> const& ids, HttpHeaders headers, bool& fromMemory)
{
if (m_clockSkewManager.isWaitingForClockSkew())
{
m_clockSkewManager.handleResponse(headers);
}
/* Handle delete of killed tokens on 200 OK or non-retryable status code */
if ((!headers.empty()) && m_killSwitchManager.handleResponse(headers))
{
/* Since we got the ask for a new token kill, means we sent something we should now stop sending */
LOG_TRACE("Scrub all pending events associated with killed token(s)");
DeleteRecordsByKeys(m_killSwitchManager.getTokensList());
}
LOG_TRACE(" OfflineStorageHandler Deleting %u sent event(s) {%s%s}...",
static_cast<unsigned>(ids.size()), ids.front().c_str(), (ids.size() > 1) ? ", ..." : "");
if (fromMemory && nullptr != m_offlineStorageMemory)
{
m_offlineStorageMemory->DeleteRecords(ids, headers, fromMemory);
}
else
{
if (nullptr != m_offlineStorageDisk)
{
m_offlineStorageDisk->DeleteRecords(ids, headers, fromMemory);
}
}
}
void OfflineStorageHandler::ReleaseRecords(std::vector<StorageRecordId> const& ids, bool incrementRetryCount, HttpHeaders headers, bool& fromMemory)
{
if (m_clockSkewManager.isWaitingForClockSkew())
{
m_clockSkewManager.handleResponse(headers);
}
/* Handle delete of kills tokens on 503 or other retryable status code */
if ((!headers.empty()) && m_killSwitchManager.handleResponse(headers))
{
/* Since we got the ask for a new token kill, means we sent something we should now stop sending */
LOG_TRACE("Scrub all pending events associated with killed token(s)");
DeleteRecordsByKeys(m_killSwitchManager.getTokensList());
}
if (fromMemory && nullptr != m_offlineStorageMemory)
{
m_offlineStorageMemory->ReleaseRecords(ids, incrementRetryCount, headers, fromMemory);
}
else
{
if (nullptr != m_offlineStorageDisk)
{
m_offlineStorageDisk->ReleaseRecords(ids, incrementRetryCount, headers, fromMemory);
}
}
}
bool OfflineStorageHandler::StoreSetting(std::string const& name, std::string const& value)
{
if (nullptr != m_offlineStorageDisk)
{
m_offlineStorageDisk->StoreSetting(name, value);
return true;
}
return false;
}
std::string OfflineStorageHandler::GetSetting(std::string const& name)
{
if (nullptr != m_offlineStorageDisk)
{
return m_offlineStorageDisk->GetSetting(name);
}
return "";
}
bool OfflineStorageHandler::DeleteSetting(std::string const& name)
{
if (nullptr != m_offlineStorageDisk)
{
return m_offlineStorageDisk->DeleteSetting(name);
}
return false;
}
void OfflineStorageHandler::OnStorageOpened(std::string const& type)
{
m_observer->OnStorageOpened(type);
}
void OfflineStorageHandler::OnStorageFailed(std::string const& reason)
{
m_observer->OnStorageOpenFailed(reason);
}
void OfflineStorageHandler::OnStorageOpenFailed(std::string const& reason)
{
m_observer->OnStorageOpenFailed(reason);
}
void OfflineStorageHandler::OnStorageTrimmed(std::map<std::string, size_t> const& numRecords)
{
m_observer->OnStorageTrimmed(numRecords);
}
void OfflineStorageHandler::OnStorageRecordsDropped(std::map<std::string, size_t> const& numRecords)
{
m_observer->OnStorageRecordsDropped(numRecords);
}
void OfflineStorageHandler::OnStorageRecordsRejected(std::map<std::string, size_t> const& numRecords)
{
m_observer->OnStorageRecordsRejected(numRecords);
}
void OfflineStorageHandler::OnStorageRecordsSaved(size_t numRecords)
{
m_observer->OnStorageRecordsSaved(numRecords);
}
} MAT_NS_END
| 18,463 | 5,232 |
// OutputMaster example
// By Andrés Cabrera mantaraya36@gmail.com
// July 2018
#include <iostream>
#include "al/app/al_App.hpp"
#include "al/graphics/al_Shapes.hpp"
// This example shows a simple input level meter
using namespace al;
struct MyApp : public App {
float *meterValues;
void onCreate() override { meterValues = new float(audioIO().channelsIn()); }
void onSound(AudioIOData &io) override {
while (io()) {
for (auto i = 0; i < io.channelsOut(); i++) {
// Write meter values. This is only safe because float is atomic on
// desktops.
if (meterValues[i] < fabs(io.in(0))) {
meterValues[i] = io.in(0);
}
}
}
}
void onDraw(Graphics &g) override {
g.clear(0);
// Copies the current values to the array passed
Mesh m;
addQuad(m, 0.2f, 0.2f);
g.color(1.0);
for (auto i = 0; i < audioIO().channelsOut(); i++) {
g.pushMatrix();
g.color(HSV(0.5f + 0.5f * meterValues[i]));
g.translate(-1.0f + (2.0f * i / (audioIO().channelsOut() - 1.0f)),
-0.5f + meterValues[i], -4);
meterValues[i] = 0;
g.draw(m);
g.popMatrix();
}
}
};
int main(int argc, char *argv[]) {
MyApp app;
app.title("Stereo Audio Scene");
app.fps(30);
app.configureAudio(44100, 256, 2, 2);
app.start();
return 0;
}
| 1,357 | 526 |
#pragma once
#ifndef BE_BLT_LUA_BLT_DEBUG_HPP_
#define BE_BLT_LUA_BLT_DEBUG_HPP_
#include <lua/lua.h>
#include <lua/lauxlib.h>
namespace be::belua {
///////////////////////////////////////////////////////////////////////////////
int open_blt_debug(lua_State* L);
extern const luaL_Reg blt_debug_module;
} // be::belua
#endif
| 331 | 131 |
/*
THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
SOFTWARE CORPORATION ("PARALLAX"). PARALLAX, IN DISTRIBUTING THE CODE TO
END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
IN USING, DISPLAYING, AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
FREE PURPOSES. IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES. THE END-USER UNDERSTANDS
AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
COPYRIGHT 1993-1998 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED.
*/
#ifdef EDITOR
#include <string.h>
#include "main_d1/inferno.h"
#include "editor.h"
#include "kdefs.h"
static fix r1scale, r4scale;
static int curve;
int InitCurve()
{
curve = 0;
return 1;
}
int GenerateCurve()
{
if ( (Markedsegp != 0) && !IS_CHILD(Markedsegp->children[Markedside])) {
r1scale = r4scale = F1_0*20;
autosave_mine( mine_filename );
diagnostic_message("Curve Generated.");
Update_flags |= UF_WORLD_CHANGED;
curve = generate_curve(r1scale, r4scale);
mine_changed = 1;
if (curve == 1) {
strcpy(undo_status[Autosave_count], "Curve Generation UNDONE.\n");
}
if (curve == 0) diagnostic_message("Cannot generate curve -- check Current segment.");
}
else diagnostic_message("Cannot generate curve -- check Marked segment.");
warn_if_concave_segments();
return 1;
}
int DecreaseR4()
{
if (curve) {
Update_flags |= UF_WORLD_CHANGED;
delete_curve();
r4scale -= F1_0;
generate_curve(r1scale, r4scale);
diagnostic_message("R4 vector decreased.");
mine_changed = 1;
warn_if_concave_segments();
}
return 1;
}
int IncreaseR4()
{
if (curve) {
Update_flags |= UF_WORLD_CHANGED;
delete_curve();
r4scale += F1_0;
generate_curve(r1scale, r4scale);
diagnostic_message("R4 vector increased.");
mine_changed = 1;
warn_if_concave_segments();
}
return 1;
}
int DecreaseR1()
{
if (curve) {
Update_flags |= UF_WORLD_CHANGED;
delete_curve();
r1scale -= F1_0;
generate_curve(r1scale, r4scale);
diagnostic_message("R1 vector decreased.");
mine_changed = 1;
warn_if_concave_segments();
}
return 1;
}
int IncreaseR1()
{
if (curve) {
Update_flags |= UF_WORLD_CHANGED;
delete_curve();
r1scale += F1_0;
generate_curve(r1scale, r4scale);
diagnostic_message("R1 vector increased.");
mine_changed = 1;
warn_if_concave_segments();
}
return 1;
}
int DeleteCurve()
{
// fix_bogus_uvs_all();
set_average_light_on_curside();
if (curve) {
Update_flags |= UF_WORLD_CHANGED;
delete_curve();
curve = 0;
mine_changed = 1;
diagnostic_message("Curve Deleted.");
warn_if_concave_segments();
}
return 1;
}
int SetCurve()
{
if (curve) curve = 0;
//autosave_mine( mine_filename );
//strcpy(undo_status[Autosave_count], "Curve Generation UNDONE.\n");
return 1;
}
#endif
| 3,133 | 1,341 |
/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2011 Torus Knot Software Ltd
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 "OgrePageContentCollection.h"
#include "OgrePageContentCollectionFactory.h"
#include "OgreStreamSerialiser.h"
#include "OgrePageContent.h"
#include "OgrePage.h"
namespace Ogre
{
//---------------------------------------------------------------------
const uint32 PageContentCollection::CHUNK_ID = StreamSerialiser::makeIdentifier("PGCC");
const uint16 PageContentCollection::CHUNK_VERSION = 1;
//---------------------------------------------------------------------
PageContentCollection::PageContentCollection(PageContentCollectionFactory* creator)
: mCreator(creator), mParent(0)
{
}
//---------------------------------------------------------------------
PageContentCollection::~PageContentCollection()
{
// don't call destroy(), we're not the final subclass
}
//---------------------------------------------------------------------
PageManager* PageContentCollection::getManager() const
{
return mParent->getManager();
}
//---------------------------------------------------------------------
const String& PageContentCollection::getType() const
{
return mCreator->getName();
}
//---------------------------------------------------------------------
void PageContentCollection::_notifyAttached(Page* parent)
{
mParent = parent;
}
//---------------------------------------------------------------------
SceneManager* PageContentCollection::getSceneManager() const
{
return mParent->getSceneManager();
}
}
| 2,822 | 770 |
#include "image_clip.h"
#include <QGraphicsSceneMouseEvent>
#include <QtWidgets/QGraphicsPixmapItem>
#include <QtWidgets/QGraphicsRectItem>
#include <iostream>
ImageClip::ImageClip(QObject* parent)
{
cap = new cv::VideoCapture;
bins = 64;
lut = cv::Mat(1, bins*bins*bins, CV_8UC1, cv::Scalar(0));
std::cout <<lut.size()<< std::endl;
type = GREEN;
selection = true;
lut_view = false;
logging_model_ = new QStringListModel;
}
/**
* Qt mouse press event.
*
* Set the first rectangle point and draw the rectangle color
*/
void ImageClip::mousePressEvent(QGraphicsSceneMouseEvent* event)
{
if (event->button() & Qt::LeftButton)
{
m_leftMouseButtonPressed = true;
setPreviousPosition(event->scenePos());
m_selection = new QGraphicsRectItem();
m_selection->setBrush(QBrush(QColor(158,182,255,96)));
m_selection->setPen(QPen(QColor(158,182,255,200),1));
addItem(m_selection);
}
QGraphicsScene::mousePressEvent(event);
}
/**
* Qt mouse move event.
*
* Draw the rectangle by following mouse movement.
*/
void ImageClip::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
{
if (m_leftMouseButtonPressed)
{
auto dx = event->scenePos().x() - m_previousPosition.x();
auto dy = event->scenePos().y() - m_previousPosition.y();
auto left = qMin(m_previousPosition.x(), event->scenePos().x());
auto top = qMin(m_previousPosition.y(), event->scenePos().y());
m_selection->setRect(left, top, qAbs(dx),qAbs(dy));
}
QGraphicsScene::mouseMoveEvent(event);
}
/**
* Qt mouse release event.
*
* Get the second rectangle coordinate and create ROI
*/
void ImageClip::mouseReleaseEvent(QGraphicsSceneMouseEvent* event)
{
if (event->button() & Qt::LeftButton)
{
m_leftMouseButtonPressed = false;
QRect selectionRect = m_selection->boundingRect().toRect();
cv::Rect roi(selectionRect.x(), selectionRect.y(), selectionRect.width(), selectionRect.height() );
getData(roi);
delete m_selection;
}
QGraphicsScene::mouseReleaseEvent(event);
}
void ImageClip::setPreviousPosition(const QPointF previousPosition)
{
if (m_previousPosition == previousPosition)
return;
m_previousPosition = previousPosition;
emit previousPositionChanged(m_previousPosition);
}
QPointF ImageClip::previousPosition() const
{
return m_previousPosition;
}
/**
* Assign selected labels to all values in ROI.
*/
void ImageClip::getData(cv::Rect &roi)
{
cv::Mat img_roi;
if (roi.x > origin.cols) roi.x = origin.cols;
if (roi.y > origin.rows) roi.y = origin.rows;
if ((roi.x + roi.width) > origin.cols) roi.width = roi.x + roi.width - origin.cols;
if ((roi.y + roi.height) > origin.rows) roi.height = roi.y + roi.height - origin.rows;
img_roi = origin(roi);
for(int i = 0; i < img_roi.rows; i++)
for(int j = 0; j < img_roi.cols; j++)
{
// Reduce the color value 256 -> 64
cv::Vec3b intensity = img_roi.at<cv::Vec3b>(i, j);
uchar h = intensity.val[0] /4;
uchar s = intensity.val[1] /4;
uchar v = intensity.val[2] /4;
if(selection)
switch(type)
{
case GREEN : lut.at<uchar>(0, h+s*bins+v*bins*bins)=GREEN; break;
case WHITE : lut.at<uchar>(0, h+s*bins+v*bins*bins)=WHITE; break;
case BLACK : lut.at<uchar>(0, h+s*bins+v*bins*bins)=BLACK; break;
case OTHER : lut.at<uchar>(0, h+s*bins+v*bins*bins)=OTHER; break;
}
else
lut.at<uchar>(0, h+s*bins+v*bins*bins)=OTHER;
}
// std::stringstream text;
// text << "Data Saved " << " x : " << std::to_string(roi.x) << " y : " << std::to_string(roi.y);
// log(text.str());
}
void ImageClip::loadFile(QString path)
{
if(cap->isOpened())
{
cap->release();
cap->open(path.toStdString());
}
else
cap->open(path.toStdString());
}
void ImageClip::updateImage()
{
updateImage(true);
}
void ImageClip::updateImage(bool status)
{
QImage vid_frame;
if(cap->isOpened())
{
if (status)
{
cap->read(frame);
cv::resize(frame, frame, cv::Size(480, 360));
frame.copyTo(origin);
cv::cvtColor(frame, frame, cv::COLOR_BGR2RGB);
vid_frame = QImage(frame.data, frame.cols, frame.rows, frame.step, QImage::Format_RGB888);
}
if(lut_view)
updateLUT();
else
emit sendImage(vid_frame);
}
}
void ImageClip::updateLUT()
{
cv::Mat imageLut;
origin.copyTo(imageLut);
cv::Vec3b colors;
for(int i = 0; i < imageLut.rows; i++)
for(int j = 0; j < imageLut.cols; j++)
{
cv::Vec3b val = imageLut.at<cv::Vec3b>(i,j);
int h = val.val[0] / 4;
int s = val.val[1] / 4;
int v = val.val[2] / 4;
uchar space = lut.at<uchar>(0,h+s*bins+v*bins*bins);
if(space == OTHER)
{
colors.val[0]=255;
colors.val[1]=0;
colors.val[2]=0;
imageLut.at<cv::Vec3b>(i,j) = colors;
}
else if(space == GREEN)
{
colors.val[0]=0;
colors.val[1]=255;
colors.val[2]=0;
imageLut.at<cv::Vec3b>(i,j) = colors;
}
else if(space == WHITE)
{
colors.val[0]=255;
colors.val[1]=255;
colors.val[2]=255;
imageLut.at<cv::Vec3b>(i,j) = colors;
}
else if(space == BLACK)
{
colors.val[0]=0;
colors.val[1]=0;
colors.val[2]=0;
imageLut.at<cv::Vec3b>(i,j) = colors;
}
}
cv::cvtColor(imageLut, imageLut, cv::COLOR_BGR2RGB);
QImage vid_frame(imageLut.data, imageLut.cols, imageLut.rows, imageLut.step, QImage::Format_RGB888);
emit sendImage(vid_frame);
}
void ImageClip::loadLUT(QString path)
{
cv::FileStorage storage(path.toStdString(), cv::FileStorage::READ);
storage["lut"] >> lut;
storage.release();
std::stringstream text;
text << "Data Imported from " << path.toStdString();
log(text.str());
}
void ImageClip::saveLUT(bool status)
{
std::string filename = "lut.xml";
cv::FileStorage storage(filename, cv::FileStorage::WRITE);
storage << "lut" << lut;
storage.release();
std::stringstream text;
text << "Data Exported to " << filename;
log(text.str());
}
void ImageClip::log(std::string msg)
{
logging_model_->insertRows(logging_model_->rowCount(), 1);
std::stringstream logging_model_msg;
logging_model_msg << "[DEBUG] " << msg;
QVariant new_row(QString(logging_model_msg.str().c_str()));
logging_model_->setData(logging_model_->index(logging_model_->rowCount() - 1), new_row);
emit loggingUpdated(); // used to readjust the scrollbar
}
void ImageClip::clearLog()
{
if (logging_model_->rowCount() == 0)
return;
logging_model_->removeRows(0, logging_model_->rowCount());
}
| 6,677 | 2,576 |
/* joystick_node.cpp
* Copyright (C) 2021 SS47816
* ROS Node for controlling the vehicle using joysticks
**/
#include <math.h>
#include <ros/ros.h>
#include <ros/console.h>
#include <std_msgs/String.h>
#include <sensor_msgs/Joy.h>
#include <lgsvl_msgs/VehicleControlData.h>
#include <lgsvl_msgs/VehicleStateData.h>
#include <autoware_msgs/VehicleCmd.h>
class JoystickTeleop
{
public:
JoystickTeleop();
private:
bool is_healthy_ = true;
int curr_mode_;
int curr_gear_;
float deadzone_;
float steering_limit_; // [deg]
std::string joy_type_;
std::string control_setting_;
std::string steering_mapping_;
std_msgs::String curr_mode_name_;
std_msgs::String curr_gear_name_;
ros::NodeHandle nh;
ros::Subscriber joystick_sub;
ros::Subscriber autonomous_cmd_sub;
ros::Subscriber health_monitor_sub;
ros::Publisher vehicle_cmd_pub;
ros::Publisher vehicle_state_pub;
ros::Publisher pub_curr_mode;
ros::Publisher pub_curr_gear;
void joystickCallback(const sensor_msgs::Joy::ConstPtr& joy_msg);
void autonomousCmdCallback(const autoware_msgs::VehicleCmd::ConstPtr& auto_cmd_msg);
// void healthMonitorCallback(const agv::HealthMonitor::ConstPtr& health_msg);
};
JoystickTeleop::JoystickTeleop()
{
ros::NodeHandle private_nh("~");
std::string joy_topic;
std::string autonomous_cmd_topic;
std::string vehicle_cmd_topic;
std::string vehicle_state_topic;
std::string curr_mode_topic;
std::string curr_gear_topic;
// std::string health_monitor_topic;
ROS_ASSERT(private_nh.getParam("joy_topic", joy_topic));
ROS_ASSERT(private_nh.getParam("joy_type", joy_type_));
ROS_ASSERT(private_nh.getParam("control_setting", control_setting_));
ROS_ASSERT(private_nh.getParam("steering_mapping", steering_mapping_));
ROS_ASSERT(private_nh.getParam("autonomous_cmd_topic", autonomous_cmd_topic));
ROS_ASSERT(private_nh.getParam("vehicle_cmd_topic", vehicle_cmd_topic));
ROS_ASSERT(private_nh.getParam("vehicle_state_topic", vehicle_state_topic));
ROS_ASSERT(private_nh.getParam("curr_mode_topic", curr_mode_topic));
ROS_ASSERT(private_nh.getParam("curr_gear_topic", curr_gear_topic));
// ROS_ASSERT(private_nh.getParam("health_monitor_topic", health_monitor_topic));
ROS_ASSERT(private_nh.getParam("steering_limit", steering_limit_));
ROS_ASSERT(private_nh.getParam("deadzone", deadzone_));
joystick_sub = nh.subscribe(joy_topic, 1, &JoystickTeleop::joystickCallback, this);
autonomous_cmd_sub = nh.subscribe(autonomous_cmd_topic, 1, &JoystickTeleop::autonomousCmdCallback, this);
// health_monitor_sub = nh.subscribe(health_monitor_topic, 1, &JoystickTeleop::healthMonitorCallback, this);
vehicle_cmd_pub = nh.advertise<lgsvl_msgs::VehicleControlData>(vehicle_cmd_topic, 1);
vehicle_state_pub = nh.advertise<lgsvl_msgs::VehicleStateData>(vehicle_state_topic, 1);
pub_curr_mode = nh.advertise<std_msgs::String>(curr_mode_topic, 1);
pub_curr_gear = nh.advertise<std_msgs::String>(curr_gear_topic, 1);
curr_mode_name_.data = "MANUAL";
curr_gear_name_.data = "PARKING";
curr_mode_ = lgsvl_msgs::VehicleStateData::VEHICLE_MODE_COMPLETE_MANUAL;
curr_gear_ == lgsvl_msgs::VehicleControlData::GEAR_PARKING;
ROS_INFO("joy_type: using %s\n", joy_type_.c_str());
}
void JoystickTeleop::joystickCallback(const sensor_msgs::Joy::ConstPtr& joy_msg)
{
bool A, B, X, Y, LB, RB, button_stick_left, button_stick_right;
float LT, RT, LR_axis_stick_L, UD_axis_stick_L, LR_axis_stick_R, UD_axis_stick_R, cross_key_LR, cross_key_UD;
float accel_axes, brake_axes, steer_axes;
lgsvl_msgs::VehicleControlData vehicle_cmd;
vehicle_cmd.header = joy_msg->header;
vehicle_cmd.header.frame_id = "base_link";
vehicle_cmd.target_wheel_angular_rate = 0.0;
vehicle_cmd.acceleration_pct = 0.0;
vehicle_cmd.braking_pct = 1.0;
lgsvl_msgs::VehicleStateData vehicle_state;
vehicle_state.header = joy_msg->header;
vehicle_state.header.frame_id = "base_link";
vehicle_state.blinker_state = lgsvl_msgs::VehicleStateData::BLINKERS_OFF;
vehicle_state.headlight_state = lgsvl_msgs::VehicleStateData::HEADLIGHTS_OFF;
vehicle_state.wiper_state = lgsvl_msgs::VehicleStateData::WIPERS_OFF;
vehicle_state.autonomous_mode_active = 0;
vehicle_state.hand_brake_active = 0;
vehicle_state.horn_active = 0;
// Select the joystick type used
if (joy_type_.compare("F710") == 0) // Logitech F710 XInput Mode
{
A = joy_msg->buttons[0];
B = joy_msg->buttons[1];
X = joy_msg->buttons[2];
Y = joy_msg->buttons[3];
// LB = joy_msg->buttons[4]; // doing nothing
// RB = joy_msg->buttons[5]; // doing nothing
// button_stick_left = joy_msg->buttons[10]; // doing nothing
// button_stick_right = joy_msg->buttons[11]; // doing nothing
cross_key_LR = joy_msg->axes[0];
cross_key_UD = joy_msg->axes[1];
LT = joy_msg->axes[2]; // [0, 1], doing nothing
LR_axis_stick_R = joy_msg->axes[3];
UD_axis_stick_R = joy_msg->axes[4];
RT = joy_msg->axes[5]; // [0, 1], release the full power
// LR_axis_stick_L = joy_msg->axes[6]; // doing nothing
// UD_axis_stick_L = joy_msg->axes[7]; // doing nothing
}
else if (joy_type_.compare("Xbox") == 0) // default using xbox wired controller
{
A = joy_msg->buttons[0];
B = joy_msg->buttons[1];
X = joy_msg->buttons[2];
Y = joy_msg->buttons[3];
// LB = joy_msg->buttons[4]; // doing nothing
// RB = joy_msg->buttons[5]; // doing nothing
// button_stick_left = joy_msg->buttons[9]; // doing nothing
// button_stick_right = joy_msg->buttons[10]; // doing nothing
LR_axis_stick_L = joy_msg->axes[0];
UD_axis_stick_L = joy_msg->axes[1];
LT = joy_msg->axes[2]; // [1.0, -1.0], doing nothing
LR_axis_stick_R = joy_msg->axes[3];
UD_axis_stick_R = joy_msg->axes[4];
RT = joy_msg->axes[5]; // [1.0, -1.0], release the full power
// cross_key_LR = joy_msg->axes[6]; // doing nothing
// cross_key_UD = joy_msg->axes[7]; // doing nothing
}
else
{
ROS_ERROR("[joystick_node]: Invalid joystick type (%s) used, 'Xbox' or 'F710' expected", joy_type_.c_str());
return;
}
// Select the joystick control setting used
if (control_setting_.compare("ForzaHorizon") == 0)
{
accel_axes = (-RT + 1.0)/2.0;
brake_axes = (-LT + 1.0)/2.0;
steer_axes = LR_axis_stick_L;
}
else if (control_setting_.compare("JapanHand") == 0)
{
accel_axes = UD_axis_stick_R;
brake_axes = -accel_axes;
steer_axes = LR_axis_stick_L;
}
else if (control_setting_.compare("USAHand") == 0)
{
accel_axes = UD_axis_stick_L;
brake_axes = -accel_axes;
steer_axes = LR_axis_stick_R;
}
else
{
ROS_ERROR("[joystick_node]: Invalid control setting (%s) used, 'ForzaHorizon', 'JapanHand' or 'USAHand' expected", control_setting_.c_str());
return;
}
// Switch Vehicle Mode and Gear
if (B)
{
// Manual Mode, Parking Gear
curr_mode_name_.data = "MANUAL";
curr_mode_ = lgsvl_msgs::VehicleStateData::VEHICLE_MODE_COMPLETE_MANUAL;
curr_gear_name_.data = "PARKING";
curr_gear_ = lgsvl_msgs::VehicleControlData::GEAR_PARKING;
}
else if (X)
{
// Manual Mode, Forward Gear
curr_mode_name_.data = "MANUAL";
curr_mode_ = lgsvl_msgs::VehicleStateData::VEHICLE_MODE_COMPLETE_MANUAL;
curr_gear_name_.data = "DRIVE";
curr_gear_ = lgsvl_msgs::VehicleControlData::GEAR_DRIVE;
}
else if (Y)
{
// Manual Mode, Reverse Gear
curr_mode_name_.data = "MANUAL";
curr_mode_ = lgsvl_msgs::VehicleStateData::VEHICLE_MODE_COMPLETE_MANUAL;
curr_gear_name_.data = "REVERSE";
curr_gear_ = lgsvl_msgs::VehicleControlData::GEAR_REVERSE;
}
else if (A)
{
// Autonomous Mode, Auto Gear
if (!is_healthy_)
{
// Emergency Mode, Neutral Gear
curr_mode_name_.data = "EMERGENCY";
curr_mode_ = lgsvl_msgs::VehicleStateData::VEHICLE_MODE_EMERGENCY_MODE;
curr_gear_name_.data = "NEUTRAL";
curr_gear_ = lgsvl_msgs::VehicleControlData::GEAR_NEUTRAL;
vehicle_state.hand_brake_active = 1;
ROS_ERROR("[Emergency Mode]: Unhealthy vehicle!");
return;
}
else if (curr_mode_ == lgsvl_msgs::VehicleStateData::VEHICLE_MODE_COMPLETE_MANUAL
&& curr_gear_ == lgsvl_msgs::VehicleControlData::GEAR_PARKING)
{
// Autonomous Mode, Drive TBD
curr_mode_name_.data = "AUTONOMOUS";
curr_mode_ = lgsvl_msgs::VehicleStateData::VEHICLE_MODE_COMPLETE_AUTO_DRIVE;
}
else if (curr_mode_ == lgsvl_msgs::VehicleStateData::VEHICLE_MODE_COMPLETE_AUTO_DRIVE)
{
ROS_DEBUG("[ Auto Mode ]: Vehicle Already in Autonomous Mode");
return;
}
else
{
ROS_DEBUG("[joystick_node]: Can only enter Autonomous Mode from Brake Mode!");
return;
}
}
// Publish vehicle control messages based on vehicle mode
if (curr_mode_ == lgsvl_msgs::VehicleStateData::VEHICLE_MODE_COMPLETE_AUTO_DRIVE)
{
// Empty Action, Let autonomousCmdCallback() function handle publishing autonomous mode messages
pub_curr_mode.publish(curr_mode_name_);
pub_curr_gear.publish(curr_gear_name_);
return;
}
else if (curr_mode_ == lgsvl_msgs::VehicleStateData::VEHICLE_MODE_COMPLETE_MANUAL)
{
// Map Accel & Brake axes output
if (curr_gear_ == lgsvl_msgs::VehicleControlData::GEAR_DRIVE)
{
vehicle_cmd.acceleration_pct = accel_axes;
vehicle_cmd.braking_pct = brake_axes;
}
else if (curr_gear_ == lgsvl_msgs::VehicleControlData::GEAR_REVERSE)
{
vehicle_cmd.acceleration_pct = brake_axes;
vehicle_cmd.braking_pct = accel_axes;
}
// Map Steering axes output
if (control_setting_.compare("Quadratic") == 0)
{
vehicle_cmd.target_wheel_angle = -(steer_axes*steer_axes)*steering_limit_/180.0*M_PI;
}
else
{
vehicle_cmd.target_wheel_angle = -steer_axes*steering_limit_/180.0*M_PI;
}
// ROS_DEBUG("[Manual Mode]: Steering Goal Angle: %.1f [deg] Throttle Value: %.2f",
// joy_type_.c_str(), vehicle_cmd.target_wheel_angle*180.0/M_PI, vehicle_cmd.acceleration_pct);
}
else
{
// Emergency Mode, Neutral Gear
curr_mode_name_.data = "EMERGENCY";
curr_mode_ = lgsvl_msgs::VehicleStateData::VEHICLE_MODE_EMERGENCY_MODE;
curr_gear_name_.data = "NEUTRAL";
curr_gear_ = lgsvl_msgs::VehicleControlData::GEAR_NEUTRAL;
vehicle_state.hand_brake_active = 1;
ROS_ERROR("[Emergency Mode]: Unhealthy vehicle!");
}
// Publish final vehicle command, state, mode, and gear messages
vehicle_cmd.target_gear = curr_gear_;
vehicle_cmd_pub.publish(std::move(vehicle_cmd));
vehicle_state.vehicle_mode = curr_mode_;
vehicle_state.current_gear = curr_gear_;
vehicle_state_pub.publish(std::move(vehicle_state));
pub_curr_mode.publish(curr_mode_name_);
pub_curr_gear.publish(curr_gear_name_);
return;
}
void JoystickTeleop::autonomousCmdCallback(const autoware_msgs::VehicleCmd::ConstPtr& auto_cmd_msg)
{
if (curr_mode_ != lgsvl_msgs::VehicleStateData::VEHICLE_MODE_COMPLETE_AUTO_DRIVE)
{
return;
}
lgsvl_msgs::VehicleControlData vehicle_cmd;
vehicle_cmd.header = auto_cmd_msg->header;
vehicle_cmd.header.frame_id = "base_link";
lgsvl_msgs::VehicleStateData vehicle_state;
vehicle_state.header = auto_cmd_msg->header;
vehicle_state.header.frame_id = "base_link";
vehicle_state.blinker_state = lgsvl_msgs::VehicleStateData::BLINKERS_OFF;
vehicle_state.headlight_state = lgsvl_msgs::VehicleStateData::HEADLIGHTS_OFF;
vehicle_state.wiper_state = lgsvl_msgs::VehicleStateData::WIPERS_OFF;
vehicle_state.vehicle_mode = lgsvl_msgs::VehicleStateData::VEHICLE_MODE_COMPLETE_AUTO_DRIVE;
vehicle_state.autonomous_mode_active = 1;
vehicle_state.hand_brake_active = 0;
vehicle_state.horn_active = 0;
if (!is_healthy_)
{
// Emergency Mode, Neutral Gear
curr_mode_name_.data = "EMERGENCY";
curr_mode_ = lgsvl_msgs::VehicleStateData::VEHICLE_MODE_EMERGENCY_MODE;
curr_gear_name_.data = "NEUTRAL";
curr_gear_ = lgsvl_msgs::VehicleControlData::GEAR_NEUTRAL;
vehicle_state.hand_brake_active = 1;
ROS_ERROR("[Emergency Mode]: Unhealthy vehicle!");
}
else if (auto_cmd_msg->gear_cmd.gear == autoware_msgs::Gear::PARK)
{
curr_gear_ = lgsvl_msgs::VehicleControlData::GEAR_PARKING;
curr_gear_name_.data = "PARKING";
}
else if (auto_cmd_msg->gear_cmd.gear == autoware_msgs::Gear::DRIVE)
{
curr_gear_ = lgsvl_msgs::VehicleControlData::GEAR_DRIVE;
curr_gear_name_.data = "DRIVE";
vehicle_cmd.acceleration_pct = std::fabs(std::max(0.0, auto_cmd_msg->twist_cmd.twist.linear.x));
vehicle_cmd.braking_pct = std::fabs(std::min(0.0, auto_cmd_msg->twist_cmd.twist.linear.x));
vehicle_cmd.target_wheel_angle = -(auto_cmd_msg->twist_cmd.twist.angular.z);
}
else if (auto_cmd_msg->gear_cmd.gear == autoware_msgs::Gear::REVERSE)
{
curr_gear_ = lgsvl_msgs::VehicleControlData::GEAR_REVERSE;
curr_gear_name_.data = "REVERSE";
}
else if (auto_cmd_msg->gear_cmd.gear == autoware_msgs::Gear::LOW)
{
curr_gear_ = lgsvl_msgs::VehicleControlData::GEAR_LOW;
curr_gear_name_.data = "LOW";
}
else
{
curr_gear_ = lgsvl_msgs::VehicleControlData::GEAR_NEUTRAL;
curr_gear_name_.data = "NEUTRAL";
}
// ROS_DEBUG("[ Auto Mode ]: Steering Goal Angle: %.1f [deg] Throttle Value: %.2f",
// joy_type_.c_str(), vehicle_cmd.target_wheel_angle*180.0/M_PI, vehicle_cmd.acceleration_pct);
vehicle_cmd.target_gear = curr_gear_;
vehicle_cmd_pub.publish(std::move(vehicle_cmd));
vehicle_state.current_gear = curr_gear_;
vehicle_state_pub.publish(std::move(vehicle_state));
pub_curr_mode.publish(curr_mode_name_);
pub_curr_gear.publish(curr_gear_name_);
return;
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "joystick_node");
JoystickTeleop joystick_teleop_obj;
ros::spin();
return 0;
}
| 14,122 | 5,791 |
#pragma once
#include "matrix.hpp"
#include "max-or-inf.hpp"
#include "global-greedy.hpp"
#include "edge.hpp"
#include "print-info.hpp"
#include "k-opt.hpp"
#include <unordered_set>
#include <random>
#include <iostream>
#include <cmath>
template<typename T>
class Sigma_Male {
public:
Sigma_Male(uint32_t seed, double recency = 1.0 / 1024.0);
void grind(const Matrix<T>& mat, size_t start, size_t num_iterations, bool run_kopt = true);
const Matrix<double>& get_freq_mat();
T get_min_path_length() const;
const std::vector<size_t>& get_shortest_path_found();
private:
Matrix<double> frequency;
std::vector<size_t> shortest_path_found;
T min_path_length;
std::mt19937 rng;
double recency;
};
template<typename T>
Sigma_Male<T>::Sigma_Male(uint32_t s, double r) : min_path_length{get_max_val_or_inf<T>()}, rng{s}, recency(r) {}
template<typename T>
void Sigma_Male<T>::grind(const Matrix<T>& mat, size_t start, size_t num_iterations, bool run_kopt) {
frequency = Matrix<double>(mat.get_num_rows(), mat.get_num_cols(), [](){ return 0; });
Global_Greedy<T> gg;
Matrix<T> cur_mat = mat;
K_Opt<T> kopt(137, 5);
double cur_path_length = 1.0;
double thing_to_add = 0.0;
for (size_t i = 0; i < num_iterations; i++) {
gg.run(cur_mat, start);
std::vector<size_t> path = gg.get_path();
if (run_kopt) {
//print_path(path);
//std::cout << "Path Length: " << get_path_length(path, mat) << "\n";
kopt.run(mat, start, path);
//print_path(path);
//std::cout << "Path Length: " << get_path_length(path, mat) << "\n";
//std::cout << "--------------------------------------------------------------------------------\n";
}
cur_path_length = get_path_length(path, mat);
if (cur_path_length < min_path_length) {
min_path_length = get_path_length(path, mat);
shortest_path_found = path;
}
std::vector<Edge> edges;
edges.reserve(path.size());
T path_length{};
for (size_t j = 0; j < path.size() - 1; j++) {
const size_t& cur = path[j];
const size_t& next = path[j + 1];
if (cur_path_length <= min_path_length) {
thing_to_add = 1.0;
} else {
thing_to_add = 1.0 / (1.0 + cur_path_length - min_path_length);
thing_to_add *= thing_to_add;
}
frequency.at(cur, next) *= (1.0 - recency);
frequency.at(cur, next) += thing_to_add * recency;
edges.push_back({cur, next});
path_length += mat.at(cur, next);
}
// std::cout << "Path Length: " << path_length << "\n";
cur_mat = mat;
std::vector<double> edge_weights;
edge_weights.reserve(edges.size());
for (const Edge& edge : edges) {
T cur_edge_length = mat.at(edge.start, edge.end);
edge_weights.push_back(mat.at(edge.start, edge.end));
}
std::discrete_distribution<size_t> dist{edge_weights.begin(), edge_weights.end()};
for (size_t j = 0; j < 2 * sqrt(edges.size()); j++) {
const Edge& cur_edge = edges[dist(rng)];
cur_mat.at(cur_edge.start, cur_edge.end) = get_max_val_or_inf<T>() / mat.get_num_cols();
}
}
}
template<typename T>
const Matrix<double>& Sigma_Male<T>::get_freq_mat() {
return frequency;
}
template<typename T>
T Sigma_Male<T>::get_min_path_length() const {
return min_path_length;
}
| 3,156 | 1,349 |
/*******************************************************************************
* Copyright (c) 2014, 2015 IBM Corporation and others
*
* 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 StatusInitializerStub_hpp
#define StatusInitializerStub_hpp
#include <stdio.h>
#include "StatusInitializer.hpp"
namespace loc{
class StatusInitializerStub : public StatusInitializer{
public:
Locations initializeLocations(int n){
Locations locs;
//int n= 100;
for(int i=0; i<n; i++){
Location loc(0,0,0,0);
locs.push_back(loc);
}
return locs;
}
Poses initializePoses(int n){
Locations locs = initializeLocations(n);
//int n = (int) locs.size();
Poses poses(n);
for(int i=0; i<n; i++){
Location loc = locs.at(i);
Pose pose;
pose.x(loc.x()).y(loc.y()).floor(loc.floor()).z(loc.z());
pose.orientation(0.0).velocity(1.0).normalVelocity(1.0);
poses[i]=pose;
}
return poses;
}
States initializeStates(int n){
Poses poses = initializePoses(n);
//int n = (int) poses.size();
States states(n);
for(int i=0; i<n; i++){
Pose pose = poses.at(i);
State state;
state.x(pose.x()).y(pose.y()).floor(pose.floor()).z(pose.z());
state.orientation(0.0).velocity(1.0).normalVelocity(1.0);
state.orientationBias(0.0).rssiBias(0.0);
states[i]=state;
}
return states;
}
};
}
#endif /* StatusInitializerStub_hpp */
| 2,920 | 883 |
// c:/Users/user/Documents/Programming/Music/Chou/OnKai/a.cpp
#include "../../Header.hpp"
#include "a_Body.hpp"
#include "../../../Error/FaultInCoding/a.hpp"
const PitchClass& OnKai::PitchClassTable( const KaiMei& num ) const noexcept
{
const PitchClass* p_Table[7] =
{
&m_I ,
&m_II ,
&m_III ,
&m_IV ,
&m_V ,
&m_VI ,
&m_VII
};
return *p_Table[ num.Represent() ];
}
DEFINITION_OF_GLOBAL_CONST_ON_KAI( ChouOnKai , 0 , 2 , 4 , 5 , 7 , 9 , 11 );
DEFINITION_OF_GLOBAL_CONST_ON_KAI( WaSeiTekiTanOnKai , 0 , 2 , 3 , 5 , 7 , 8 , 11 );
DEFINITION_OF_GLOBAL_CONST_ON_KAI( ShiZenTanOnKai , 0 , 2 , 3 , 5 , 7 , 8 , 10 );
| 706 | 362 |
#include <string>
#include <string.h>
#include <memory>
#include <cstdlib>
#include "timer-test.hpp"
/*
TODO: This example is really dry, how can we make it awesome?
Without making it so complicated that it fails to elucidate its point.
*/
using namespace blit;
const uint16_t screen_width = 320;
const uint16_t screen_height = 240;
blit::timer timer_count;
uint32_t count;
void timer_count_update(blit::timer &t){
count++;
// Instead of using loops we're going to stop the timer in our callback
// In this case it will count to ten and then stop.
// But you could depend upon any condition to stop the timer.
if(count == 10) {
t.stop();
}
}
void init() {
blit::set_screen_mode(blit::screen_mode::hires);
// Timers must be initialized
// In this case we want our timer to call the `timer_count_update` function
// very 1000ms, or 1 second. We also want it to loop indefinitely.
// We can pass -1 to loop indefinitely, or just nothing at all since -1
// is the default.
timer_count.init(timer_count_update, 1000, -1);
// Next we probably want to start our timer!
timer_count.start();
}
int tick_count = 0;
void render(uint32_t time_ms) {
char text_buffer[60];
fb.pen(rgba(20, 30, 40));
fb.clear();
// Fancy title bar, nothing to see here.
fb.pen(rgba(255, 255, 255));
fb.rectangle(rect(0, 0, 320, 14));
fb.pen(rgba(0, 0, 0));
fb.text("Timer Test", &minimal_font[0][0], point(5, 4));
// Since our timer callback is updating our `count` variable
// we can just display it on the screen and watch it tick up!
fb.pen(rgba(255, 255, 255));
sprintf(text_buffer, "Count: %d", count);
fb.text(text_buffer, &minimal_font[0][0], point(120, 100));
// `is_running()` is a handy shorthand for checking the timer state
if(timer_count.is_running()) {
fb.text("Timer running...", &minimal_font[0][0], point(120, 110));
} else {
fb.text("Timer stopped!", &minimal_font[0][0], point(120, 110));
fb.text("Press A to restart.", &minimal_font[0][0], point(120, 120));
}
}
void update(uint32_t time_ms) {
// `is_stopped()` works too!
if (blit::buttons & blit::button::A && timer_count.is_stopped()) {
count = 0;
timer_count.start();
}
} | 2,320 | 914 |
// Time: O(nlogn)
// Space: O(n)
class Solution {
public:
int minAbsoluteSumDiff(vector<int>& nums1, vector<int>& nums2) {
static const int MOD = 1e9 + 7;
vector<int> sorted_nums1(cbegin(nums1), cend(nums1));
sort(begin(sorted_nums1), end(sorted_nums1));
int result = 0, max_change = 0;
for (int i = 0; i < size(nums2); ++i) {
int diff = abs(nums1[i] - nums2[i]);
result = (result + diff) % MOD;
if (diff < max_change) {
continue;
}
const auto cit = lower_bound(cbegin(sorted_nums1), cend(sorted_nums1), nums2[i]);
if (cit != cend(sorted_nums1)) {
max_change = max(max_change, diff - abs(*cit - nums2[i]));
}
if (cit != cbegin(sorted_nums1)) {
max_change = max(max_change, diff - abs(*prev(cit) - nums2[i]));
}
}
return (result - max_change + MOD) % MOD;
}
};
| 983 | 355 |
#include <Core/Types.hpp>
#include <Core/Utils/Attribs.hpp>
#include <Core/Utils/Log.hpp>
namespace Ra {
namespace Core {
namespace Utils {
AttribBase::~AttribBase() {
notify();
}
template <>
size_t Attrib<float>::getElementSize() const {
return 1;
}
template <>
size_t Attrib<double>::getElementSize() const {
return 1;
}
AttribManager::~AttribManager() {
clear();
}
void AttribManager::clear() {
m_attribs.clear();
m_attribsIndex.clear();
}
void AttribManager::copyAllAttributes( const AttribManager& m ) {
for ( const auto& attr : m.m_attribs )
{
if ( attr == nullptr ) continue;
if ( attr->isFloat() )
{
auto h = addAttrib<Scalar>( attr->getName() );
getAttrib( h ).setData( static_cast<Attrib<Scalar>*>( attr.get() )->data() );
}
else if ( attr->isVector2() )
{
auto h = addAttrib<Vector2>( attr->getName() );
getAttrib( h ).setData( static_cast<Attrib<Vector2>*>( attr.get() )->data() );
}
else if ( attr->isVector3() )
{
auto h = addAttrib<Vector3>( attr->getName() );
getAttrib( h ).setData( static_cast<Attrib<Vector3>*>( attr.get() )->data() );
}
else if ( attr->isVector4() )
{
auto h = addAttrib<Vector4>( attr->getName() );
getAttrib( h ).setData( static_cast<Attrib<Vector4>*>( attr.get() )->data() );
}
else
LOG( logWARNING ) << "Warning, copy of mesh attribute " << attr->getName()
<< " type is not supported (only float, vec2, vec3 nor vec4 are "
"supported) [from AttribManager::copyAllAttribute()]";
}
}
bool AttribManager::hasSameAttribs( const AttribManager& other ) {
// one way
for ( const auto& attr : m_attribsIndex )
{
if ( other.m_attribsIndex.find( attr.first ) == other.m_attribsIndex.cend() )
{ return false; }
}
// the other way
for ( const auto& attr : other.m_attribsIndex )
{
if ( m_attribsIndex.find( attr.first ) == m_attribsIndex.cend() ) { return false; }
}
return true;
}
} // namespace Utils
} // namespace Core
} // namespace Ra
| 2,258 | 736 |
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include <memory>
#include <string>
#include <cassert>
int main(int, char**)
{
auto up2 = std::make_unique<int[]>(10, 20, 30, 40);
return 0;
}
| 521 | 160 |
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2015 - ROLI Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE 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.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
const bool deleteSourceWhenDeleted)
: source (source_, deleteSourceWhenDeleted),
requiredNumberOfChannels (2)
{
remappedInfo.buffer = &buffer;
remappedInfo.startSample = 0;
}
ChannelRemappingAudioSource::~ChannelRemappingAudioSource() {}
//==============================================================================
void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_)
{
const ScopedLock sl (lock);
requiredNumberOfChannels = requiredNumberOfChannels_;
}
void ChannelRemappingAudioSource::clearAllMappings()
{
const ScopedLock sl (lock);
remappedInputs.clear();
remappedOutputs.clear();
}
void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex)
{
const ScopedLock sl (lock);
while (remappedInputs.size() < destIndex)
remappedInputs.add (-1);
remappedInputs.set (destIndex, sourceIndex);
}
void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex)
{
const ScopedLock sl (lock);
while (remappedOutputs.size() < sourceIndex)
remappedOutputs.add (-1);
remappedOutputs.set (sourceIndex, destIndex);
}
int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const
{
const ScopedLock sl (lock);
if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
return remappedInputs.getUnchecked (inputChannelIndex);
return -1;
}
int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const
{
const ScopedLock sl (lock);
if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
return remappedOutputs .getUnchecked (outputChannelIndex);
return -1;
}
//==============================================================================
void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
{
source->prepareToPlay (samplesPerBlockExpected, sampleRate);
}
void ChannelRemappingAudioSource::releaseResources()
{
source->releaseResources();
}
void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
{
const ScopedLock sl (lock);
buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
const int numChans = bufferToFill.buffer->getNumChannels();
for (int i = 0; i < buffer.getNumChannels(); ++i)
{
const int remappedChan = getRemappedInputChannel (i);
if (remappedChan >= 0 && remappedChan < numChans)
{
buffer.copyFrom (i, 0, *bufferToFill.buffer,
remappedChan,
bufferToFill.startSample,
bufferToFill.numSamples);
}
else
{
buffer.clear (i, 0, bufferToFill.numSamples);
}
}
remappedInfo.numSamples = bufferToFill.numSamples;
source->getNextAudioBlock (remappedInfo);
bufferToFill.clearActiveBufferRegion();
for (int i = 0; i < requiredNumberOfChannels; ++i)
{
const int remappedChan = getRemappedOutputChannel (i);
if (remappedChan >= 0 && remappedChan < numChans)
{
bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
buffer, i, 0, bufferToFill.numSamples);
}
}
}
//==============================================================================
XmlElement* ChannelRemappingAudioSource::createXml() const
{
XmlElement* e = new XmlElement ("MAPPINGS");
String ins, outs;
const ScopedLock sl (lock);
for (int i = 0; i < remappedInputs.size(); ++i)
ins << remappedInputs.getUnchecked(i) << ' ';
for (int i = 0; i < remappedOutputs.size(); ++i)
outs << remappedOutputs.getUnchecked(i) << ' ';
e->setAttribute ("inputs", ins.trimEnd());
e->setAttribute ("outputs", outs.trimEnd());
return e;
}
void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e)
{
if (e.hasTagName ("MAPPINGS"))
{
const ScopedLock sl (lock);
clearAllMappings();
StringArray ins, outs;
ins.addTokens (e.getStringAttribute ("inputs"), false);
outs.addTokens (e.getStringAttribute ("outputs"), false);
for (int i = 0; i < ins.size(); ++i)
remappedInputs.add (ins[i].getIntValue());
for (int i = 0; i < outs.size(); ++i)
remappedOutputs.add (outs[i].getIntValue());
}
}
| 5,654 | 1,650 |
/*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/polardb/model/DescribeDatabasesResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Polardb;
using namespace AlibabaCloud::Polardb::Model;
DescribeDatabasesResult::DescribeDatabasesResult() :
ServiceResult()
{}
DescribeDatabasesResult::DescribeDatabasesResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
DescribeDatabasesResult::~DescribeDatabasesResult()
{}
void DescribeDatabasesResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allDatabasesNode = value["Databases"]["Database"];
for (auto valueDatabasesDatabase : allDatabasesNode)
{
Database databasesObject;
if(!valueDatabasesDatabase["DBName"].isNull())
databasesObject.dBName = valueDatabasesDatabase["DBName"].asString();
if(!valueDatabasesDatabase["DBStatus"].isNull())
databasesObject.dBStatus = valueDatabasesDatabase["DBStatus"].asString();
if(!valueDatabasesDatabase["DBDescription"].isNull())
databasesObject.dBDescription = valueDatabasesDatabase["DBDescription"].asString();
if(!valueDatabasesDatabase["CharacterSetName"].isNull())
databasesObject.characterSetName = valueDatabasesDatabase["CharacterSetName"].asString();
if(!valueDatabasesDatabase["Engine"].isNull())
databasesObject.engine = valueDatabasesDatabase["Engine"].asString();
auto allAccountsNode = valueDatabasesDatabase["Accounts"]["Account"];
for (auto valueDatabasesDatabaseAccountsAccount : allAccountsNode)
{
Database::Account accountsObject;
if(!valueDatabasesDatabaseAccountsAccount["AccountName"].isNull())
accountsObject.accountName = valueDatabasesDatabaseAccountsAccount["AccountName"].asString();
if(!valueDatabasesDatabaseAccountsAccount["AccountStatus"].isNull())
accountsObject.accountStatus = valueDatabasesDatabaseAccountsAccount["AccountStatus"].asString();
if(!valueDatabasesDatabaseAccountsAccount["AccountPrivilege"].isNull())
accountsObject.accountPrivilege = valueDatabasesDatabaseAccountsAccount["AccountPrivilege"].asString();
if(!valueDatabasesDatabaseAccountsAccount["PrivilegeStatus"].isNull())
accountsObject.privilegeStatus = valueDatabasesDatabaseAccountsAccount["PrivilegeStatus"].asString();
databasesObject.accounts.push_back(accountsObject);
}
databases_.push_back(databasesObject);
}
}
std::vector<DescribeDatabasesResult::Database> DescribeDatabasesResult::getDatabases()const
{
return databases_;
}
| 3,155 | 983 |
#include <chrono>
#include <regex>
#include <fstream>
#include <thread>
#include <sstream>
#include <iosfwd>
#include <unistd.h>
#include <rapidjson/document.h>
#include <openssl/md5.h>
#include "misc.h"
#ifdef _WIN32
//#include <io.h>
#include <windows.h>
#include <winreg.h>
#else
#ifndef __hpux
#include <sys/select.h>
#endif /* __hpux */
#ifndef _access
#define _access access
#endif // _access
#include <sys/socket.h>
#endif // _WIN32
void sleep(int interval)
{
/*
#ifdef _WIN32
Sleep(interval);
#else
// Portable sleep for platforms other than Windows.
struct timeval wait = { 0, interval * 1000 };
select(0, NULL, NULL, NULL, &wait);
#endif
*/
//upgrade to c++11 standard
this_thread::sleep_for(chrono::milliseconds(interval));
}
string GBKToUTF8(string str_src)
{
#ifdef _WIN32
const char* strGBK = str_src.c_str();
int len = MultiByteToWideChar(CP_ACP, 0, strGBK, -1, NULL, 0);
wchar_t* wstr = new wchar_t[len + 1];
memset(wstr, 0, len + 1);
MultiByteToWideChar(CP_ACP, 0, strGBK, -1, wstr, len);
len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
char* str = new char[len + 1];
memset(str, 0, len + 1);
WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, len, NULL, NULL);
string strTemp = str;
if(wstr)
delete[] wstr;
if(str)
delete[] str;
return strTemp;
#else
return str_src;
#endif // _WIN32
}
string UTF8ToGBK(string str_src)
{
#ifdef _WIN32
const char* strUTF8 = str_src.data();
int len = MultiByteToWideChar(CP_UTF8, 0, strUTF8, -1, NULL, 0);
wchar_t* wszGBK = new wchar_t[len + 1];
memset(wszGBK, 0, len * 2 + 2);
MultiByteToWideChar(CP_UTF8, 0, strUTF8, -1, wszGBK, len);
len = WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, NULL, 0, NULL, NULL);
char* szGBK = new char[len + 1];
memset(szGBK, 0, len + 1);
WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, szGBK, len, NULL, NULL);
string strTemp(szGBK);
if (wszGBK)
delete[] wszGBK;
if (szGBK)
delete[] szGBK;
return strTemp;
#else
return str_src;
#endif
}
#ifdef _WIN32
// string to wstring
void StringToWstring(wstring& szDst, string str)
{
string temp = str;
int len = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)temp.c_str(), -1, NULL,0);
wchar_t* wszUtf8 = new wchar_t[len + 1];
memset(wszUtf8, 0, len * 2 + 2);
MultiByteToWideChar(CP_ACP, 0, (LPCSTR)temp.c_str(), -1, (LPWSTR)wszUtf8, len);
szDst = wszUtf8;
wstring r = wszUtf8;
delete[] wszUtf8;
}
#endif // _WIN32
unsigned char FromHex(unsigned char x)
{
unsigned char y = '\0';
if (x >= 'A' && x <= 'Z')
y = x - 'A' + 10;
else if (x >= 'a' && x <= 'z')
y = x - 'a' + 10;
else if (x >= '0' && x <= '9')
y = x - '0';
else
assert(0);
return y;
}
string UrlDecode(const string& str)
{
string strTemp = "";
size_t length = str.length();
for (size_t i = 0; i < length; i++)
{
if (str[i] == '+')
strTemp += ' ';
else if (str[i] == '%')
{
assert(i + 2 < length);
unsigned char high = FromHex((unsigned char)str[++i]);
unsigned char low = FromHex((unsigned char)str[++i]);
strTemp += high * 16 + low;
}
else
strTemp += str[i];
}
return strTemp;
}
static inline bool is_base64(unsigned char c)
{
return (isalnum(c) || (c == '+') || (c == '/'));
}
string base64_encode(string string_to_encode)
{
char const* bytes_to_encode = string_to_encode.data();
unsigned int in_len = string_to_encode.size();
string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (in_len--)
{
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3)
{
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for(i = 0; (i <4) ; i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for(j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
while((i++ < 3))
ret += '=';
}
return ret;
}
string base64_decode(string encoded_string)
{
int in_len = encoded_string.size();
int i = 0;
int j = 0;
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
string ret;
while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_]))
{
char_array_4[i++] = encoded_string[in_];
in_++;
if (i ==4)
{
for (i = 0; i <4; i++)
char_array_4[i] = base64_chars.find(char_array_4[i]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (i = 0; (i < 3); i++)
ret += char_array_3[i];
i = 0;
}
}
if (i)
{
for (j = i; j <4; j++)
char_array_4[j] = 0;
for (j = 0; j <4; j++)
char_array_4[j] = base64_chars.find(char_array_4[j]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (j = 0; (j < i - 1); j++)
ret += char_array_3[j];
}
return ret;
}
vector<string> split(const string &s, const string &seperator)
{
vector<string> result;
typedef string::size_type string_size;
string_size i = 0;
while(i != s.size())
{
int flag = 0;
while(i != s.size() && flag == 0)
{
flag = 1;
for(string_size x = 0; x < seperator.size(); ++x)
if(s[i] == seperator[x])
{
++i;
flag = 0;
break;
}
}
flag = 0;
string_size j = i;
while(j != s.size() && flag == 0)
{
for(string_size x = 0; x < seperator.size(); ++x)
if(s[j] == seperator[x])
{
flag = 1;
break;
}
if(flag == 0)
++j;
}
if(i != j)
{
result.push_back(s.substr(i, j-i));
i = j;
}
}
return result;
}
string getSystemProxy()
{
#ifdef _WIN32
HKEY key;
auto ret = RegOpenKeyEx(HKEY_CURRENT_USER, R"(Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings)", 0, KEY_ALL_ACCESS, &key);
if(ret != ERROR_SUCCESS){
//std::cout << "open failed: " << ret << std::endl;
return string();
}
DWORD values_count, max_value_name_len, max_value_len;
ret = RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL,
&values_count, &max_value_name_len, &max_value_len, NULL, NULL);
if(ret != ERROR_SUCCESS){
//std::cout << "query failed" << std::endl;
return string();
}
std::vector<std::tuple<std::shared_ptr<char>, DWORD, std::shared_ptr<BYTE>>> values;
for(DWORD i = 0; i < values_count; i++){
std::shared_ptr<char> value_name(new char[max_value_name_len + 1],
std::default_delete<char[]>());
DWORD value_name_len = max_value_name_len + 1;
DWORD value_type, value_len;
RegEnumValue(key, i, value_name.get(), &value_name_len, NULL, &value_type, NULL, &value_len);
std::shared_ptr<BYTE> value(new BYTE[value_len],
std::default_delete<BYTE[]>());
value_name_len = max_value_name_len + 1;
RegEnumValue(key, i, value_name.get(), &value_name_len, NULL, &value_type, value.get(), &value_len);
values.push_back(std::make_tuple(value_name, value_type, value));
}
DWORD ProxyEnable = 0;
for (auto x : values) {
if (strcmp(std::get<0>(x).get(), "ProxyEnable") == 0) {
ProxyEnable = *(DWORD*)(std::get<2>(x).get());
}
}
if (ProxyEnable) {
for (auto x : values) {
if (strcmp(std::get<0>(x).get(), "ProxyServer") == 0) {
//std::cout << "ProxyServer: " << (char*)(std::get<2>(x).get()) << std::endl;
return string((char*)(std::get<2>(x).get()));
}
}
}
/*
else {
//std::cout << "Proxy not Enabled" << std::endl;
}
*/
//return 0;
return string();
#else
char* proxy = getenv("ALL_PROXY");
if(proxy != NULL)
return string(proxy);
else
return string();
#endif // _WIN32
}
string trim(const string& str)
{
string::size_type pos = str.find_first_not_of(' ');
if (pos == string::npos)
{
return str;
}
string::size_type pos2 = str.find_last_not_of(' ');
if (pos2 != string::npos)
{
return str.substr(pos, pos2 - pos + 1);
}
return str.substr(pos);
}
string getUrlArg(string url, string request)
{
smatch result;
if (regex_search(url.cbegin(), url.cend(), result, regex(request + "=(.*?)&")))
{
return result[1];
}
else if (regex_search(url.cbegin(), url.cend(), result, regex(request + "=(.*)")))
{
return result[1];
}
else
{
return string();
}
}
string replace_all_distinct(string str, string old_value, string new_value)
{
for(string::size_type pos(0); pos != string::npos; pos += new_value.length())
{
if((pos = str.find(old_value, pos)) != string::npos)
str.replace(pos, old_value.length(), new_value);
else
break;
}
return str;
}
bool regFind(string src, string target)
{
regex reg(target);
return regex_search(src, reg);
}
string regReplace(string src, string match, string rep)
{
string result = "";
regex reg(match);
regex_replace(back_inserter(result), src.begin(), src.end(), reg, rep);
return result;
}
bool regMatch(string src, string match)
{
regex reg(match);
return regex_match(src, reg);
}
string speedCalc(double speed)
{
if(speed == 0.0)
return string("0.00B");
char str[10];
string retstr;
if(speed >= 1073741824.0)
sprintf(str, "%.2fGB", speed / 1073741824.0);
else if(speed >= 1048576.0)
sprintf(str, "%.2fMB", speed / 1048576.0);
else if(speed >= 1024.0)
sprintf(str, "%.2fKB", speed / 1024.0);
else
sprintf(str, "%.2fB", speed);
retstr = str;
return retstr;
}
string urlsafe_base64_reverse(string encoded_string)
{
return replace_all_distinct(replace_all_distinct(encoded_string, "-", "+"), "_", "/");
}
string urlsafe_base64_decode(string encoded_string)
{
return base64_decode(urlsafe_base64_reverse(encoded_string));
}
string grabContent(string raw)
{
/*
string strTmp="";
vector<string> content;
content=split(raw,"\r\n\r\n");
for(unsigned int i=1;i<content.size();i++) strTmp+=content[i];
*/
return regReplace(raw.substr(raw.find("\r\n\r\n") + 4), "^\\d*?\\r\\n(.*)\\r\\n\\d", "$1");
//return raw;
}
string getMD5(string data)
{
MD5_CTX ctx;
string result;
unsigned int i = 0;
unsigned char digest[16] = {};
MD5_Init(&ctx);
MD5_Update(&ctx, data.data(), data.size());
MD5_Final((unsigned char *)&digest, &ctx);
char tmp[3] = {};
for(i = 0; i < 16; i++)
{
snprintf(tmp, 3, "%02x", digest[i]);
result += tmp;
}
return result;
}
string fileGet(string path)
{
ifstream infile;
stringstream strstrm;
infile.open(path, ios::binary);
if(infile)
{
strstrm<<infile.rdbuf();
infile.close();
return strstrm.str();
}
return string();
}
bool fileExist(string path)
{
return _access(path.data(), 4) != -1;
}
bool fileCopy(string source, string dest)
{
ifstream infile;
ofstream outfile;
infile.open(source, ios::binary);
if(!infile)
return false;
outfile.open(dest, ios::binary);
if(!outfile)
return false;
try
{
outfile<<infile.rdbuf();
}
catch (exception &e)
{
return false;
}
infile.close();
outfile.close();
return true;
}
string fileToBase64(string filepath)
{
return base64_encode(fileGet(filepath));
}
string fileGetMD5(string filepath)
{
return getMD5(fileGet(filepath));
}
int fileWrite(string path, string content, bool overwrite)
{
fstream outfile;
ios::openmode mode = overwrite ? ios::out : ios::app;
outfile.open(path, mode);
outfile<<content<<endl;
outfile.close();
return 0;
}
bool isIPv4(string address)
{
return regMatch(address, "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$");
}
bool isIPv6(string address)
{
int ret;
vector<string> regLists = {"^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$", "^((?:[0-9A-Fa-f]{1,4}(:[0-9A-Fa-f]{1,4})*)?)::((?:([0-9A-Fa-f]{1,4}:)*[0-9A-Fa-f]{1,4})?)$", "^(::(?:[0-9A-Fa-f]{1,4})(?::[0-9A-Fa-f]{1,4}){5})|((?:[0-9A-Fa-f]{1,4})(?::[0-9A-Fa-f]{1,4}){5}::)$"};
for(unsigned int i = 0; i < regLists.size(); i++)
{
ret = regMatch(address, regLists[i]);
if(ret)
return true;
}
return false;
}
string rand_str(const int len)
{
string retData;
srand(time(NULL));
int cnt = 0;
while(cnt < len)
{
switch((rand() % 3))
{
case 1:
retData += ('A' + rand() % 26);
break;
case 2:
retData += ('a' + rand() % 26);
break;
default:
retData += ('0' + rand() % 10);
break;
}
cnt++;
}
return retData;
}
void urlParse(string url, string &host, string &path, int &port, bool &isTLS)
{
vector<string> args;
if(regMatch(url, "^https://(.*)"))
isTLS = true;
url = regReplace(url, "^(http|https)://", "");
if(url.find("/") == url.npos)
{
host = url;
path = "/";
}
else
{
host = url.substr(0, url.find("/"));
path = url.substr(url.find("/"));
}
if(regFind(host, "\\[(.*)\\]")) //IPv6
{
args = split(regReplace(host, "\\[(.*)\\](.*)", "$1,$2"), ",");
if(args.size() == 2) //with port
port = stoi(args[1].substr(1));
host = args[0];
}
else if(strFind(host, ":"))
{
port = stoi(host.substr(host.rfind(":") + 1));
host = host.substr(0, host.rfind(":"));
}
if(port == 0)
{
if(isTLS)
port = 443;
else
port = 80;
}
}
| 15,877 | 6,356 |
#include <netwidgets.h>
N::TldEditor:: TldEditor ( QWidget * parent , Plan * p )
: TreeWidget ( parent , p )
, NetworkManager ( p )
{
WidgetClass ;
Configure ( ) ;
}
N::TldEditor::~TldEditor(void)
{
}
void N::TldEditor::Configure(void)
{
setWindowTitle ( tr("Top level domains") ) ;
setDragDropMode ( DragOnly ) ;
setRootIsDecorated ( false ) ;
setAlternatingRowColors ( true ) ;
setHorizontalScrollBarPolicy ( Qt::ScrollBarAsNeeded ) ;
setVerticalScrollBarPolicy ( Qt::ScrollBarAsNeeded ) ;
setColumnCount ( 6 ) ;
NewTreeWidgetItem ( header ) ;
header->setText ( 0,tr("Top level domain")) ;
header->setText ( 1,tr("Country" )) ;
header->setText ( 2,tr("NIC" )) ;
header->setText ( 3,tr("SLDs" )) ;
header->setText ( 4,tr("Sites" )) ;
header->setText ( 5,tr("Comment" )) ;
setHeaderItem ( header ) ;
plan -> setFont ( this ) ;
}
bool N::TldEditor::FocusIn(void)
{
LinkAction ( Refresh , List () ) ;
LinkAction ( Copy , CopyToClipboard() ) ;
return true ;
}
void N::TldEditor::List(void)
{
SqlConnection SC ( plan->sql ) ;
QString CN = QtUUID::createUuidString ( ) ;
if (SC.open("TldEditor",CN)) {
if (LoadDomainIndex(SC)) {
QString tld ;
foreach (tld,TLDs) {
NewTreeWidgetItem ( IT ) ;
SUID uuid = TldUuids [ tld ] ;
int country = TldNations [ uuid ] ;
SUID cuid = Countries [ country ] ;
QString nic = NICs [ uuid ] ;
int slds = TldCounts ( SC,uuid ) ;
int tlds = TldTotal ( SC,uuid ) ;
QString comment = Comments [ uuid ] ;
IT -> setData (0,Qt::UserRole,uuid ) ;
IT -> setTextAlignment(3,Qt::AlignRight) ;
IT -> setTextAlignment(4,Qt::AlignRight) ;
IT -> setText (0,tld ) ;
IT -> setText (1,Nations[cuid] ) ;
IT -> setText (2,nic ) ;
IT -> setText (3,QString::number(slds) ) ;
IT -> setText (4,QString::number(tlds) ) ;
IT -> setText (5,comment ) ;
addTopLevelItem ( IT ) ;
} ;
} ;
SC . close ( ) ;
} ;
SC.remove() ;
SuitableColumns ( ) ;
Alert ( Done ) ;
}
| 3,129 | 897 |
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
string operation;
getline(cin, operation);
int pseudo_random_number;
cin >> pseudo_random_number; cin.ignore();
string rotor[3];
for (int i = 0; i < 3; i++) {
getline(cin, rotor[i]);
}
string message;
getline(cin, message);
if (operation[0] == 'E') {
for (int i = 0; i < message.size(); i++) {
message[i] = ((message[i] - 'A' + pseudo_random_number + i) % 26) + 'A';
}
for (int i = 0; i < 3; i++)
for (int j = 0; j < message.size(); j++)
message[j] = rotor[i][message[j] - 'A'];
}
else {
for (int i = 2; i > -1; i--)
for (int j = 0; j < message.size(); j++)
message[j] = rotor[i].find(message[j]) + 'A';
for (int i = 0; i < message.size(); i++) {
int idx = (message[i] - 'A' - pseudo_random_number - i);
while (idx < 0)
idx += 26;
message[i] = (idx % 26) + 'A';
}
}
// Write an answer using cout. DON'T FORGET THE "<< endl"
// To debug: cerr << "Debug messages..." << endl;
cout << message << endl;
}
| 1,264 | 482 |
/*
Copyright (c) 2009-present Maximus5
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 name of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR 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.
*/
#undef VALIDATE_AND_DELAY_ON_TERMINATE
#ifdef _DEBUG
// Раскомментировать, чтобы сразу после запуска процесса (conemuc.exe) показать MessageBox, чтобы прицепиться дебаггером
// #define SHOW_STARTED_MSGBOX
// #define SHOW_ADMIN_STARTED_MSGBOX
// #define SHOW_MAIN_MSGBOX
// #define SHOW_ALTERNATIVE_MSGBOX
// #define SHOW_DEBUG_STARTED_MSGBOX
// #define SHOW_COMSPEC_STARTED_MSGBOX
// #define SHOW_SERVER_STARTED_MSGBOX
// #define SHOW_STARTED_ASSERT
// #define SHOW_STARTED_PRINT
// #define SHOW_STARTED_PRINT_LITE
#define SHOW_EXITWAITKEY_MSGBOX
// #define SHOW_INJECT_MSGBOX
// #define SHOW_INJECTREM_MSGBOX
// #define SHOW_ATTACH_MSGBOX
// #define SHOW_ROOT_STARTED
// #define SHOW_ASYNC_STARTED
#define WINE_PRINT_PROC_INFO
// #define USE_PIPE_DEBUG_BOXES
// #define SHOW_SETCONTITLE_MSGBOX
#define SHOW_LOADCFGFILE_MSGBOX
// #define DEBUG_ISSUE_623
// #define VALIDATE_AND_DELAY_ON_TERMINATE
#elif defined(__GNUC__)
// Раскомментировать, чтобы сразу после запуска процесса (conemuc.exe) показать MessageBox, чтобы прицепиться дебаггером
// #define SHOW_STARTED_MSGBOX
#else
//
#endif
#define SHOWDEBUGSTR
#define DEBUGSTRCMD(x) DEBUGSTR(x)
#define DEBUGSTARTSTOPBOX(x) //MessageBox(NULL, x, WIN3264TEST(L"ConEmuC",L"ConEmuC64"), MB_ICONINFORMATION|MB_SYSTEMMODAL)
#define DEBUGSTRFIN(x) DEBUGSTR(x)
#define DEBUGSTRCP(x) DEBUGSTR(x)
#define DEBUGSTRSIZE(x) DEBUGSTR(x)
//#define SHOW_INJECT_MSGBOX
#include "ConEmuSrv.h"
#include "../common/CmdLine.h"
#include "../common/ConsoleAnnotation.h"
#include "../common/ConsoleMixAttr.h"
#include "../common/ConsoleRead.h"
#include "../common/EmergencyShow.h"
#include "../common/execute.h"
#include "../common/HkFunc.h"
#include "../common/MArray.h"
#include "../common/MPerfCounter.h"
#include "../common/MProcess.h"
#include "../common/MMap.h"
#include "../common/MModule.h"
#include "../common/MRect.h"
#include "../common/MSectionSimple.h"
#include "../common/MWow64Disable.h"
#include "../common/ProcessSetEnv.h"
#include "../common/ProcessData.h"
#include "../common/RConStartArgs.h"
#include "../common/SetEnvVar.h"
#include "../common/StartupEnvEx.h"
#include "../common/wcwidth.h"
#include "../common/WCodePage.h"
#include "../common/WConsole.h"
#include "../common/WFiles.h"
#include "../common/WThreads.h"
#include "../common/WUser.h"
#include "../ConEmu/version.h"
#include "../ConEmuHk/Injects.h"
#include "Actions.h"
#include "ConProcess.h"
#include "ConsoleHelp.h"
#include "GuiMacro.h"
#include "Debugger.h"
#include "StartEnv.h"
#include "UnicodeTest.h"
#ifndef __GNUC__
#pragma comment(lib, "shlwapi.lib")
#endif
WARNING("Обязательно после запуска сделать apiSetForegroundWindow на GUI окно, если в фокусе консоль");
WARNING("Обязательно получить код и имя родительского процесса");
#ifdef USEPIPELOG
namespace PipeServerLogger
{
Event g_events[BUFFER_SIZE];
LONG g_pos = -1;
}
#endif
WARNING("!!!! Пока можно при появлении события запоминать текущий тик");
// и проверять его в RefreshThread. Если он не 0 - и дельта больше (100мс?)
// то принудительно перечитать консоль и сбросить тик в 0.
WARNING("Наверное все-же стоит производить периодические чтения содержимого консоли, а не только по событию");
WARNING("Стоит именно здесь осуществлять проверку живости GUI окна (если оно было). Ведь может быть запущен не far, а CMD.exe");
WARNING("Если GUI умер, или не подцепился по таймауту - показать консольное окно и наверное установить шрифт поболе");
WARNING("В некоторых случаях не срабатывает ни EVENT_CONSOLE_UPDATE_SIMPLE ни EVENT_CONSOLE_UPDATE_REGION");
// Пример. Запускаем cmd.exe. печатаем какую-то муйню в командной строке и нажимаем 'Esc'
// При Esc никаких событий ВООБЩЕ не дергается, а экран в консоли изменился!
FGetConsoleKeyboardLayoutName pfnGetConsoleKeyboardLayoutName = NULL;
FGetConsoleProcessList pfnGetConsoleProcessList = NULL;
FDebugActiveProcessStop pfnDebugActiveProcessStop = NULL;
FDebugSetProcessKillOnExit pfnDebugSetProcessKillOnExit = NULL;
FGetConsoleDisplayMode pfnGetConsoleDisplayMode = NULL;
/* Console Handles */
//MConHandle ghConIn ( L"CONIN$" );
MConHandle ghConOut(L"CONOUT$");
// Время ожидания завершения консольных процессов, когда юзер нажал крестик в КОНСОЛЬНОМ окне
// The system also displays this dialog box if the process does not respond within a certain time-out period
// (5 seconds for CTRL_CLOSE_EVENT, and 20 seconds for CTRL_LOGOFF_EVENT or CTRL_SHUTDOWN_EVENT).
// Поэтому ждать пытаемся - не больше 4 сек
#define CLOSE_CONSOLE_TIMEOUT 4000
/* Global */
CEStartupEnv* gpStartEnv = NULL;
HMODULE ghOurModule = NULL; // ConEmuCD.dll
DWORD gnSelfPID = 0;
wchar_t gsModuleName[32] = L"";
wchar_t gsVersion[20] = L"";
wchar_t gsSelfExe[MAX_PATH] = L""; // Full path+exe to our executable
wchar_t gsSelfPath[MAX_PATH] = L""; // Directory of our executable
BOOL gbTerminateOnExit = FALSE;
//HANDLE ghConIn = NULL, ghConOut = NULL;
HWND ghConWnd = NULL;
DWORD gnConEmuPID = 0; // PID of ConEmu[64].exe (ghConEmuWnd)
HWND ghConEmuWnd = NULL; // Root! window
HWND ghConEmuWndDC = NULL; // ConEmu DC window
HWND ghConEmuWndBack = NULL; // ConEmu Back window
DWORD gnMainServerPID = 0;
DWORD gnAltServerPID = 0;
BOOL gbLogProcess = FALSE;
BOOL gbWasBufferHeight = FALSE;
BOOL gbNonGuiMode = FALSE;
DWORD gnExitCode = 0;
HANDLE ghRootProcessFlag = NULL;
HANDLE ghExitQueryEvent = NULL; int nExitQueryPlace = 0, nExitPlaceStep = 0;
#define EPS_WAITING4PROCESS 550
#define EPS_ROOTPROCFINISHED 560
SetTerminateEventPlace gTerminateEventPlace = ste_None;
HANDLE ghQuitEvent = NULL;
bool gbQuit = false;
BOOL gbInShutdown = FALSE;
BOOL gbInExitWaitForKey = FALSE;
BOOL gbStopExitWaitForKey = FALSE;
BOOL gbCtrlBreakStopWaitingShown = FALSE;
BOOL gbTerminateOnCtrlBreak = FALSE;
BOOL gbPrintRetErrLevel = FALSE; // Вывести в StdOut код завершения процесса (RM_COMSPEC в основном)
bool gbSkipHookersCheck = false;
RConStartArgs::CloseConfirm gnConfirmExitParm = RConStartArgs::eConfDefault; // | eConfAlways | eConfNever | eConfEmpty | eConfHalt
BOOL gbAlwaysConfirmExit = FALSE;
BOOL gbAutoDisableConfirmExit = FALSE; // если корневой процесс проработал достаточно (10 сек) - будет сброшен gbAlwaysConfirmExit
BOOL gbRootAliveLess10sec = FALSE; // корневой процесс проработал менее CHECK_ROOTOK_TIMEOUT
int gbRootWasFoundInCon = 0;
BOOL gbComspecInitCalled = FALSE;
AttachModeEnum gbAttachMode = am_None; // сервер запущен НЕ из conemu.exe (а из плагина, из CmdAutoAttach, или -new_console, или /GUIATTACH, или /ADMIN)
BOOL gbAlienMode = FALSE; // сервер НЕ является владельцем консоли (корневым процессом этого консольного окна)
BOOL gbDefTermCall = FALSE; // сервер запущен из DefTerm приложения (*.vshost.exe), конcоль может быть скрыта
BOOL gbCreatingHiddenConsole = FALSE; // Используется для "тихого" открытия окна RealConsole из *.vshost.exe
BOOL gbForceHideConWnd = FALSE;
DWORD gdwMainThreadId = 0;
wchar_t* gpszRunCmd = NULL;
wchar_t* gpszRootExe = NULL; // may be set with '/ROOTEXE' switch if used with '/TRMPID'. full path to root exe
wchar_t* gpszTaskCmd = NULL;
CProcessEnvCmd* gpSetEnv = NULL;
LPCWSTR gpszCheck4NeedCmd = NULL; // Для отладки
wchar_t gszComSpec[MAX_PATH+1] = {0};
bool gbRunInBackgroundTab = false;
BOOL gbRunViaCmdExe = FALSE;
DWORD gnImageSubsystem = 0, gnImageBits = 32;
//HANDLE ghCtrlCEvent = NULL, ghCtrlBreakEvent = NULL;
//HANDLE ghHeap = NULL; //HeapCreate(HEAP_GENERATE_EXCEPTIONS, nMinHeapSize, 0);
#ifdef _DEBUG
size_t gnHeapUsed = 0, gnHeapMax = 0;
HANDLE ghFarInExecuteEvent;
#endif
RunMode gnRunMode = RM_UNDEFINED;
BOOL gbDumpServerInitStatus = FALSE;
BOOL gbNoCreateProcess = FALSE;
BOOL gbDontInjectConEmuHk = FALSE;
BOOL gbAsyncRun = FALSE;
UINT gnPTYmode = 0; // 1 enable PTY, 2 - disable PTY (work as plain console), 0 - don't change
BOOL gbRootIsCmdExe = TRUE;
BOOL gbAttachFromFar = FALSE;
BOOL gbAlternativeAttach = FALSE; // Подцепиться к существующей консоли, без внедрения в процесс ConEmuHk.dll
BOOL gbSkipWowChange = FALSE;
BOOL gbConsoleModeFlags = TRUE;
DWORD gnConsoleModeFlags = 0; //(ENABLE_QUICK_EDIT_MODE|ENABLE_INSERT_MODE);
WORD gnDefTextColors = 0, gnDefPopupColors = 0; // Передаются через "/TA=..."
BOOL gbVisibleOnStartup = FALSE;
OSVERSIONINFO gOSVer;
WORD gnOsVer = 0x500;
bool gbIsWine = false;
bool gbIsDBCS = false;
SrvInfo* gpSrv = NULL;
//#pragma pack(push, 1)
//CESERVER_CONSAVE* gpStoredOutput = NULL;
//#pragma pack(pop)
//MSection* gpcsStoredOutput = NULL;
//CmdInfo* gpSrv = NULL;
COORD gcrVisibleSize = {80,25}; // gcrBufferSize переименован в gcrVisibleSize
BOOL gbParmVisibleSize = FALSE;
BOOL gbParmBufSize = FALSE;
SHORT gnBufferHeight = 0;
SHORT gnBufferWidth = 0; // Определяется в MyGetConsoleScreenBufferInfo
#ifdef _DEBUG
wchar_t* gpszPrevConTitle = NULL;
#endif
MFileLogEx* gpLogSize = NULL;
BOOL gbInRecreateRoot = FALSE;
namespace InputLogger
{
Event g_evt[BUFFER_INFO_SIZE];
LONG g_evtidx = -1;
LONG g_overflow = 0;
};
void ShutdownSrvStep(LPCWSTR asInfo, int nParm1 /*= 0*/, int nParm2 /*= 0*/, int nParm3 /*= 0*/, int nParm4 /*= 0*/)
{
#ifdef SHOW_SHUTDOWNSRV_STEPS
static int nDbg = 0;
if (!nDbg)
nDbg = IsDebuggerPresent() ? 1 : 2;
if (nDbg != 1)
return;
wchar_t szFull[512];
msprintf(szFull, countof(szFull), L"%u:ConEmuC:PID=%u:TID=%u: ",
GetTickCount(), GetCurrentProcessId(), GetCurrentThreadId());
if (asInfo)
{
int nLen = lstrlen(szFull);
msprintf(szFull+nLen, countof(szFull)-nLen, asInfo, nParm1, nParm2, nParm3, nParm4);
}
lstrcat(szFull, L"\n");
OutputDebugString(szFull);
#endif
}
void InitVersion()
{
wchar_t szMinor[8] = L""; lstrcpyn(szMinor, _T(MVV_4a), countof(szMinor));
//msprintf не умеет "%02u"
swprintf_c(gsVersion, L"%02u%02u%02u%s", MVV_1, MVV_2, MVV_3, szMinor);
}
#ifdef _DEBUG
int ShowInjectRemoteMsg(int nRemotePID, LPCWSTR asCmdArg)
{
int iBtn = IDOK;
#ifdef SHOW_INJECTREM_MSGBOX
wchar_t szDbgMsg[512], szTitle[128];
PROCESSENTRY32 pinf;
GetProcessInfo(nRemotePID, &pinf);
swprintf_c(szTitle, L"ConEmuCD PID=%u", GetCurrentProcessId());
swprintf_c(szDbgMsg, L"Hooking PID=%s {%s}\nConEmuCD PID=%u. Continue with injects?", asCmdArg ? asCmdArg : L"", pinf.szExeFile, GetCurrentProcessId());
iBtn = MessageBoxW(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL|MB_OKCANCEL);
#endif
return iBtn;
}
#endif
//UINT gnMsgActivateCon = 0;
UINT gnMsgSwitchCon = 0;
UINT gnMsgHookedKey = 0;
//UINT gnMsgConsoleHookedKey = 0;
void LoadSrvInfoMap(LPCWSTR pszExeName = NULL, LPCWSTR pszDllName = NULL)
{
if (ghConWnd)
{
MFileMapping<CESERVER_CONSOLE_MAPPING_HDR> ConInfo;
ConInfo.InitName(CECONMAPNAME, LODWORD(ghConWnd)); //-V205
CESERVER_CONSOLE_MAPPING_HDR *pInfo = ConInfo.Open();
if (pInfo)
{
if (pInfo->cbSize >= sizeof(CESERVER_CONSOLE_MAPPING_HDR))
{
if (pInfo->hConEmuRoot && IsWindow(pInfo->hConEmuRoot))
{
SetConEmuWindows(pInfo->hConEmuRoot, pInfo->hConEmuWndDc, pInfo->hConEmuWndBack);
}
if (pInfo->nServerPID && pInfo->nServerPID != gnSelfPID)
{
gnMainServerPID = pInfo->nServerPID;
gnAltServerPID = pInfo->nAltServerPID;
}
gbLogProcess = (pInfo->nLoggingType == glt_Processes);
if (pszExeName && gbLogProcess)
{
CEStr lsDir;
int ImageBits = 0, ImageSystem = 0;
#ifdef _WIN64
ImageBits = 64;
#else
ImageBits = 32;
#endif
CESERVER_REQ* pIn = ExecuteNewCmdOnCreate(pInfo, ghConWnd, eSrvLoaded,
L"", pszExeName, pszDllName, GetDirectory(lsDir), NULL, NULL, NULL, NULL,
ImageBits, ImageSystem,
GetStdHandle(STD_INPUT_HANDLE), GetStdHandle(STD_OUTPUT_HANDLE), GetStdHandle(STD_ERROR_HANDLE));
if (pIn)
{
CESERVER_REQ* pOut = ExecuteGuiCmd(ghConWnd, pIn, ghConWnd);
ExecuteFreeResult(pIn);
if (pOut) ExecuteFreeResult(pOut);
}
}
ConInfo.CloseMap();
}
else
{
_ASSERTE(pInfo->cbSize == sizeof(CESERVER_CONSOLE_MAPPING_HDR));
}
}
}
}
#if defined(__GNUC__)
extern "C"
#endif
BOOL WINAPI DllMain(HINSTANCE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
{
ghOurModule = (HMODULE)hModule;
ghWorkingModule = hModule;
hkFunc.Init(WIN3264TEST(L"ConEmuCD.dll",L"ConEmuCD64.dll"), ghOurModule);
DWORD nImageBits = WIN3264TEST(32,64), nImageSubsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI;
GetImageSubsystem(nImageSubsystem,nImageBits);
if (nImageSubsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
ghConWnd = NULL;
else
ghConWnd = GetConEmuHWND(2);
gnSelfPID = GetCurrentProcessId();
gfnSearchAppPaths = SearchAppPaths;
wchar_t szExeName[MAX_PATH] = L"", szDllName[MAX_PATH] = L"";
GetModuleFileName(NULL, szExeName, countof(szExeName));
GetModuleFileName((HMODULE)hModule, szDllName, countof(szDllName));
if (IsConsoleServer(PointToName(szExeName)))
wcscpy_c(gsModuleName, WIN3264TEST(L"ConEmuC",L"ConEmuC64"));
else
wcscpy_c(gsModuleName, WIN3264TEST(L"ConEmuCD",L"ConEmuCD64"));
InitVersion();
#ifdef _DEBUG
HANDLE hProcHeap = GetProcessHeap();
gAllowAssertThread = am_Pipe;
#endif
#ifdef SHOW_STARTED_MSGBOX
if (!IsDebuggerPresent())
{
char szMsg[128] = ""; msprintf(szMsg, countof(szMsg), WIN3264TEST("ConEmuCD.dll","ConEmuCD64.dll") " loaded, PID=%u, TID=%u", GetCurrentProcessId(), GetCurrentThreadId());
char szFile[MAX_PATH] = ""; GetModuleFileNameA(NULL, szFile, countof(szFile));
MessageBoxA(NULL, szMsg, PointToName(szFile), 0);
}
#endif
#ifdef _DEBUG
DWORD dwConMode = -1;
GetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), &dwConMode);
#endif
//_ASSERTE(ghHeap == NULL);
//ghHeap = HeapCreate(HEAP_GENERATE_EXCEPTIONS, 200000, 0);
HeapInitialize();
/* *** DEBUG PURPOSES */
gpStartEnv = LoadStartupEnvEx::Create();
/* *** DEBUG PURPOSES */
// Preload some function pointers to get proper addresses,
// before some other hooking dlls may replace them
GetLoadLibraryAddress(); // gfLoadLibrary
if (IsWin7()) // and gfLdrGetDllHandleByName
GetLdrGetDllHandleByNameAddress();
//#ifndef TESTLINK
gpLocalSecurity = LocalSecurity();
//gnMsgActivateCon = RegisterWindowMessage(CONEMUMSG_ACTIVATECON);
gnMsgSwitchCon = RegisterWindowMessage(CONEMUMSG_SWITCHCON);
gnMsgHookedKey = RegisterWindowMessage(CONEMUMSG_HOOKEDKEY);
//gnMsgConsoleHookedKey = RegisterWindowMessage(CONEMUMSG_CONSOLEHOOKEDKEY);
//#endif
//wchar_t szSkipEventName[128];
//swprintf_c(szSkipEventName, CEHOOKDISABLEEVENT, GetCurrentProcessId());
//HANDLE hSkipEvent = OpenEvent(EVENT_ALL_ACCESS , FALSE, szSkipEventName);
////BOOL lbSkipInjects = FALSE;
//if (hSkipEvent)
//{
// gbSkipInjects = (WaitForSingleObject(hSkipEvent, 0) == WAIT_OBJECT_0);
// CloseHandle(hSkipEvent);
//}
//else
//{
// gbSkipInjects = FALSE;
//}
// Открыть мэппинг консоли и попытаться получить HWND GUI, PID сервера, и пр...
if (ghConWnd)
LoadSrvInfoMap(szExeName, szDllName);
//if (!gbSkipInjects && ghConWnd)
//{
// InitializeConsoleInputSemaphore();
//}
//#ifdef _WIN64
//DWORD nImageBits = 64, nImageSubsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI;
//#else
//DWORD nImageBits = 32, nImageSubsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI;
//#endif
//GetImageSubsystem(nImageSubsystem,nImageBits);
//CShellProc sp;
//if (sp.LoadGuiMapping())
//{
// wchar_t szExeName[MAX_PATH+1]; //, szBaseDir[MAX_PATH+2];
// //BOOL lbDosBoxAllowed = FALSE;
// if (!GetModuleFileName(NULL, szExeName, countof(szExeName))) szExeName[0] = 0;
// CESERVER_REQ* pIn = sp.NewCmdOnCreate(
// gbSkipInjects ? eHooksLoaded : eInjectingHooks,
// L"", szExeName, GetCommandLineW(),
// NULL, NULL, NULL, NULL, // flags
// nImageBits, nImageSubsystem,
// GetStdHandle(STD_INPUT_HANDLE), GetStdHandle(STD_OUTPUT_HANDLE), GetStdHandle(STD_ERROR_HANDLE));
// if (pIn)
// {
// //HWND hConWnd = GetConEmuHWND(2);
// CESERVER_REQ* pOut = ExecuteGuiCmd(ghConWnd, pIn, ghConWnd);
// ExecuteFreeResult(pIn);
// if (pOut) ExecuteFreeResult(pOut);
// }
//}
//if (!gbSkipInjects)
//{
// #ifdef _DEBUG
// wchar_t szModule[MAX_PATH+1]; szModule[0] = 0;
// #endif
// #ifdef SHOW_INJECT_MSGBOX
// wchar_t szDbgMsg[1024], szTitle[128];//, szModule[MAX_PATH];
// if (!GetModuleFileName(NULL, szModule, countof(szModule)))
// wcscpy_c(szModule, L"GetModuleFileName failed");
// swprintf_c(szTitle, L"ConEmuHk, PID=%u", GetCurrentProcessId());
// swprintf_c(szDbgMsg, L"SetAllHooks, ConEmuHk, PID=%u\n%s", GetCurrentProcessId(), szModule);
// MessageBoxW(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL);
// #endif
// gnRunMode = RM_APPLICATION;
// #ifdef _DEBUG
// //wchar_t szModule[MAX_PATH+1]; szModule[0] = 0;
// GetModuleFileName(NULL, szModule, countof(szModule));
// const wchar_t* pszName = PointToName(szModule);
// _ASSERTE((nImageSubsystem==IMAGE_SUBSYSTEM_WINDOWS_CUI) || (lstrcmpi(pszName, L"DosBox.exe")==0));
// //if (!lstrcmpi(pszName, L"far.exe") || !lstrcmpi(pszName, L"mingw32-make.exe"))
// //if (!lstrcmpi(pszName, L"as.exe"))
// // MessageBoxW(NULL, L"as.exe loaded!", L"ConEmuHk", MB_SYSTEMMODAL);
// //else if (!lstrcmpi(pszName, L"cc1plus.exe"))
// // MessageBoxW(NULL, L"cc1plus.exe loaded!", L"ConEmuHk", MB_SYSTEMMODAL);
// //else if (!lstrcmpi(pszName, L"mingw32-make.exe"))
// // MessageBoxW(NULL, L"mingw32-make.exe loaded!", L"ConEmuHk", MB_SYSTEMMODAL);
// //if (!lstrcmpi(pszName, L"g++.exe"))
// // MessageBoxW(NULL, L"g++.exe loaded!", L"ConEmuHk", MB_SYSTEMMODAL);
// //{
// #endif
// gbHooksWasSet = StartupHooks(ghOurModule);
// #ifdef _DEBUG
// //}
// #endif
// // Если NULL - значит это "Detached" консольный процесс, посылать "Started" в сервер смысла нет
// if (ghConWnd != NULL)
// {
// SendStarted();
// //#ifdef _DEBUG
// //// Здесь это приводит к обвалу _chkstk,
// //// похоже из-за того, что dll-ка загружена НЕ из известных модулей,
// //// а из специально сформированного блока памяти
// // -- в одной из функций, под локальные переменные выделялось слишком много памяти
// // -- переделал в malloc/free, все заработало
// //TestShellProcessor();
// //#endif
// }
//}
//else
//{
// gbHooksWasSet = FALSE;
//}
}
break;
case DLL_PROCESS_DETACH:
{
ShutdownSrvStep(L"DLL_PROCESS_DETACH");
//if (!gbSkipInjects && gbHooksWasSet)
//{
// gbHooksWasSet = FALSE;
// ShutdownHooks();
//}
#ifdef _DEBUG
if ((gnRunMode == RM_SERVER) && (nExitPlaceStep == EPS_WAITING4PROCESS/*550*/))
{
// Это происходило после Ctrl+C если не был установлен HandlerRoutine
// Ни _ASSERT ни DebugBreak здесь позвать уже не получится - все закрывается и игнорируется
OutputDebugString(L"!!! Server was abnormally terminated !!!\n");
LogString("!!! Server was abnormally terminated !!!\n");
}
#endif
if ((gnRunMode == RM_APPLICATION) || (gnRunMode == RM_ALTSERVER))
{
SendStopped();
}
//else if (gnRunMode == RM_ALTSERVER)
//{
// WARNING("RM_ALTSERVER тоже должен посылать уведомление в главный сервер о своем завершении");
// // Но пока - оставим, для отладки ситуации, когда процесс завершается аварийно (Kill).
// _ASSERTE(gnRunMode != RM_ALTSERVER && "AltServer must inform MainServer about self-termination");
//}
//#ifndef TESTLINK
CommonShutdown();
//ReleaseConsoleInputSemaphore();
//#endif
//if (ghHeap)
//{
// HeapDestroy(ghHeap);
// ghHeap = NULL;
//}
HeapDeinitialize();
ShutdownSrvStep(L"DLL_PROCESS_DETACH done");
}
break;
}
return TRUE;
}
//#if defined(GNUCRTSTARTUP)
//extern "C" {
// BOOL WINAPI _DllMainCRTStartup(HANDLE hDll,DWORD dwReason,LPVOID lpReserved);
//};
//
//BOOL WINAPI _DllMainCRTStartup(HANDLE hDll,DWORD dwReason,LPVOID lpReserved)
//{
// DllMain(hDll, dwReason, lpReserved);
// return TRUE;
//}
//#endif
#ifdef _DEBUG
void OnProcessCreatedDbg(BOOL bRc, DWORD dwErr, LPPROCESS_INFORMATION pProcessInformation, LPSHELLEXECUTEINFO pSEI)
{
int iDbg = 0;
#ifdef SHOW_ASYNC_STARTED
if (gbAsyncRun)
{
_ASSERTE(FALSE && "Async startup requested");
}
#endif
#ifdef SHOW_ROOT_STARTED
if (bRc)
{
wchar_t szTitle[64], szMsg[128];
swprintf_c(szTitle, L"ConEmuSrv, PID=%u", GetCurrentProcessId());
swprintf_c(szMsg, L"Root process started, PID=%u", pProcessInformation->dwProcessId);
MessageBox(NULL,szMsg,szTitle,0);
}
#endif
}
#endif
BOOL createProcess(BOOL abSkipWowChange, LPCWSTR lpApplicationName, LPWSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation)
{
CEStr fnDescr(lstrmerge(L"createProcess App={", lpApplicationName, L"} Cmd={", lpCommandLine, L"}"));
LogFunction(fnDescr);
MWow64Disable wow;
if (!abSkipWowChange)
wow.Disable();
// %PATHS% from [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths]
// must be already processed in IsNeedCmd >> FileExistsSearch >> SearchAppPaths
DWORD nStartTick = GetTickCount();
#if defined(SHOW_STARTED_PRINT_LITE)
if (gnRunMode == RM_SERVER)
{
_printf("Starting root: ");
_wprintf(lpCommandLine ? lpCommandLine : lpApplicationName ? lpApplicationName : L"<NULL>");
}
#endif
SetLastError(0);
BOOL lbRc = CreateProcess(lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation);
DWORD dwErr = GetLastError();
DWORD nStartDuration = GetTickCount() - nStartTick;
wchar_t szRunRc[80];
if (lbRc)
swprintf_c(szRunRc, L"Succeeded (%u ms) PID=%u", nStartDuration, lpProcessInformation->dwProcessId);
else
swprintf_c(szRunRc, L"Failed (%u ms) Code=%u(x%04X)", nStartDuration, dwErr, dwErr);
LogFunction(szRunRc);
#if defined(SHOW_STARTED_PRINT_LITE)
if (gnRunMode == RM_SERVER)
{
if (lbRc)
_printf("\nSuccess (%u ms), PID=%u\n\n", nStartDuration, lpProcessInformation->dwProcessId);
else
_printf("\nFailed (%u ms), Error code=%u(x%04X)\n", nStartDuration, dwErr, dwErr);
}
#endif
#ifdef _DEBUG
OnProcessCreatedDbg(lbRc, dwErr, lpProcessInformation, NULL);
#endif
if (!abSkipWowChange)
{
wow.Restore();
}
SetLastError(dwErr);
return lbRc;
}
// Возвращает текст с информацией о пути к сохраненному дампу
// DWORD CreateDumpForReport(LPEXCEPTION_POINTERS ExceptionInfo, wchar_t (&szFullInfo)[1024], LPWSTR pszComment = NULL);
#include "../common/Dump.h"
bool CopyToClipboard(LPCWSTR asText)
{
if (!asText)
return false;
bool bCopied = false;
if (OpenClipboard(NULL))
{
DWORD cch = lstrlen(asText);
HGLOBAL hglbCopy = GlobalAlloc(GMEM_MOVEABLE, (cch + 1) * sizeof(*asText));
if (hglbCopy)
{
wchar_t* lptstrCopy = (wchar_t*)GlobalLock(hglbCopy);
if (lptstrCopy)
{
_wcscpy_c(lptstrCopy, cch+1, asText);
GlobalUnlock(hglbCopy);
EmptyClipboard();
bCopied = (SetClipboardData(CF_UNICODETEXT, hglbCopy) != NULL);
}
}
CloseClipboard();
}
return bCopied;
}
LPTOP_LEVEL_EXCEPTION_FILTER gpfnPrevExFilter = NULL;
bool gbCreateDumpOnExceptionInstalled = false;
LONG WINAPI CreateDumpOnException(LPEXCEPTION_POINTERS ExceptionInfo)
{
bool bKernelTrap = (gnInReadConsoleOutput > 0);
wchar_t szExcptInfo[1024] = L"";
wchar_t szDmpFile[MAX_PATH+64] = L"";
wchar_t szAdd[2000];
DWORD dwErr = CreateDumpForReport(ExceptionInfo, szExcptInfo, szDmpFile);
szAdd[0] = 0;
if (bKernelTrap)
{
wcscat_c(szAdd, L"Due to Microsoft kernel bug the crash was occurred\r\n");
wcscat_c(szAdd, CEMSBUGWIKI /* http://conemu.github.io/en/MicrosoftBugs.html */);
wcscat_c(szAdd, L"\r\n\r\n" L"The only possible workaround: enabling ‘Inject ConEmuHk’\r\n");
wcscat_c(szAdd, CEHOOKSWIKI /* http://conemu.github.io/en/ConEmuHk.html */);
wcscat_c(szAdd, L"\r\n\r\n");
}
wcscat_c(szAdd, szExcptInfo);
if (szDmpFile[0])
{
wcscat_c(szAdd, L"\r\n\r\n" L"Memory dump was saved to\r\n");
wcscat_c(szAdd, szDmpFile);
if (!bKernelTrap)
{
wcscat_c(szAdd, L"\r\n\r\n" L"Please Zip it and send to developer (via DropBox etc.)\r\n");
wcscat_c(szAdd, CEREPORTCRASH /* http://conemu.github.io/en/Issues.html... */);
}
}
wcscat_c(szAdd, L"\r\n\r\nPress <Yes> to copy this text to clipboard");
if (!bKernelTrap)
{
wcscat_c(szAdd, L"\r\nand open project web page");
}
// Message title
wchar_t szTitle[100], szExe[MAX_PATH] = L"", *pszExeName;
GetModuleFileName(NULL, szExe, countof(szExe));
pszExeName = (wchar_t*)PointToName(szExe);
if (pszExeName && lstrlen(pszExeName) > 63) pszExeName[63] = 0;
swprintf_c(szTitle, L"%s crashed, PID=%u", pszExeName ? pszExeName : L"<process>", GetCurrentProcessId());
DWORD nMsgFlags = MB_YESNO|MB_ICONSTOP|MB_SYSTEMMODAL
| (bKernelTrap ? MB_DEFBUTTON2 : 0);
int nBtn = MessageBox(NULL, szAdd, szTitle, nMsgFlags);
if (nBtn == IDYES)
{
CopyToClipboard(szAdd);
if (!bKernelTrap)
{
ShellExecute(NULL, L"open", CEREPORTCRASH, NULL, NULL, SW_SHOWNORMAL);
}
}
LONG lExRc = EXCEPTION_EXECUTE_HANDLER;
if (gpfnPrevExFilter)
{
// если фильтр уже был установлен перед нашим - будем звать его
// все-равно уже свалились, на валидность адреса можно не проверяться
lExRc = gpfnPrevExFilter(ExceptionInfo);
}
return lExRc;
}
void SetupCreateDumpOnException()
{
if (gnRunMode == RM_GUIMACRO)
{
// Must not be called in GuiMacro mode!
_ASSERTE(gnRunMode!=RM_GUIMACRO);
return;
}
// По умолчанию - фильтр в AltServer не включается, но в настройках ConEmu есть опция
// gpSet->isConsoleExceptionHandler --> CECF_ConExcHandler
_ASSERTE((gnRunMode == RM_ALTSERVER) && (gpSrv->pConsole && (gpSrv->pConsole->hdr.Flags & CECF_ConExcHandler)));
// Far 3.x, telnet, Vim, etc.
// В этих программах ConEmuCD.dll может загружаться для работы с альтернативными буферами и TrueColor
if (!gpfnPrevExFilter && !IsDebuggerPresent())
{
// Сохраним, если фильтр уже был установлен - будем звать его из нашей функции
gpfnPrevExFilter = SetUnhandledExceptionFilter(CreateDumpOnException);
gbCreateDumpOnExceptionInstalled = true;
}
}
#ifdef SHOW_SERVER_STARTED_MSGBOX
void ShowServerStartedMsgBox(LPCWSTR asCmdLine)
{
wchar_t szTitle[100]; swprintf_c(szTitle, L"ConEmuC [Server] started (PID=%i)", gnSelfPID);
const wchar_t* pszCmdLine = asCmdLine;
MessageBox(NULL,pszCmdLine,szTitle,0);
}
#endif
void LoadExePath()
{
// Already loaded?
if (gsSelfExe[0] && gsSelfPath[0])
return;
DWORD nSelfLen = GetModuleFileNameW(NULL, gsSelfExe, countof(gsSelfExe));
if (!nSelfLen || (nSelfLen >= countof(gsSelfExe)))
{
_ASSERTE(FALSE && "GetModuleFileNameW(NULL) failed");
gsSelfExe[0] = 0;
}
else
{
lstrcpyn(gsSelfPath, gsSelfExe, countof(gsSelfPath));
wchar_t* pszSlash = (wchar_t*)PointToName(gsSelfPath);
if (pszSlash && (pszSlash > gsSelfPath))
*pszSlash = 0;
else
gsSelfPath[0] = 0;
}
}
void UnlockCurrentDirectory()
{
if ((gnRunMode == RM_SERVER) && gsSelfPath[0])
{
SetCurrentDirectory(gsSelfPath);
}
}
bool CheckAndWarnHookers()
{
if (gbSkipHookersCheck)
{
if (gpLogSize) gpLogSize->LogString(L"CheckAndWarnHookers skipped due to /OMITHOOKSWARN switch");
return false;
}
bool bHooked = false;
struct CheckModules {
LPCWSTR Title, File;
} modules [] = {
{L"MacType", WIN3264TEST(L"MacType.dll", L"MacType64.dll")},
{L"AnsiCon", WIN3264TEST(L"ANSI32.dll", L"ANSI64.dll")},
{NULL}
};
CEStr szMessage;
wchar_t szPath[MAX_PATH+16] = L"", szAddress[32] = L"";
LPCWSTR pszTitle = NULL, pszName = NULL;
HMODULE hModule = NULL;
bool bConOutChecked = false, bRedirected = false;
//BOOL bColorChanged = FALSE;
CONSOLE_SCREEN_BUFFER_INFO sbi = {};
HANDLE hOut = NULL;
for (INT_PTR i = 0; modules[i].Title; i++)
{
pszTitle = modules[i].Title;
pszName = modules[i].File;
hModule = GetModuleHandle(pszName);
if (hModule)
{
bHooked = true;
if (!GetModuleFileName(hModule, szPath, countof(szPath)))
{
wcscpy_c(szPath, pszName); // Must not get here, but show a name at least on errors
}
if (!bConOutChecked)
{
bConOutChecked = true;
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hOut, &sbi);
bRedirected = IsOutputRedirected();
#if 0
// Useless in most cases, most of users are running cmd.exe
// but it clears all existing text attributes on start
if (!bRedirected)
bColorChanged = SetConsoleTextAttribute(hOut, 12); // LightRed on Black
#endif
}
swprintf_c(szAddress, WIN3264TEST(L"0x%08X",L"0x%08X%08X"), WIN3264WSPRINT((DWORD_PTR)hModule));
szMessage = lstrmerge(
L"WARNING! The ", pszTitle, L"'s hooks are detected at ", szAddress, L"\r\n"
L" ");
LPCWSTR pszTail = L"\r\n"
L" Please add ConEmuC.exe and ConEmuC64.exe\r\n"
L" to the exclusion list to avoid crashes!\r\n"
L" " CEMACTYPEWARN L"\r\n\r\n";
_wprintf(szMessage);
_wprintf(szPath);
_wprintf(pszTail);
}
}
#if 0
// If we've set warning colors - return original ones
if (bColorChanged)
SetConsoleTextAttribute(hOut, sbi.wAttributes);
#endif
return bHooked;
}
// Main entry point for ConEmuC.exe
#if defined(__GNUC__)
extern "C"
#endif
int __stdcall ConsoleMain3(int anWorkMode/*0-Server&ComSpec,1-AltServer,2-Reserved,3-GuiMacro*/, LPCWSTR asCmdLine)
{
#if defined(SHOW_MAIN_MSGBOX) || defined(SHOW_ADMIN_STARTED_MSGBOX)
bool bShowWarn = false;
#if defined(SHOW_MAIN_MSGBOX)
if (!IsDebuggerPresent()) bShowWarn = true;
#endif
#if defined(SHOW_ADMIN_STARTED_MSGBOX)
if (IsUserAdmin()) bShowWarn = true;
#endif
if (bShowWarn)
{
char szMsg[MAX_PATH+128]; msprintf(szMsg, countof(szMsg), WIN3264TEST("ConEmuCD.dll","ConEmuCD64.dll") " loaded, PID=%u, TID=%u\r\n", GetCurrentProcessId(), GetCurrentThreadId());
int nMsgLen = lstrlenA(szMsg);
GetModuleFileNameA(NULL, szMsg+nMsgLen, countof(szMsg)-nMsgLen);
MessageBoxA(NULL, szMsg, "ConEmu server" WIN3264TEST(""," x64"), 0);
}
#endif
if (!anWorkMode)
{
if (!IsDebuggerPresent())
{
// Наш exe-шник, gpfnPrevExFilter не нужен
SetUnhandledExceptionFilter(CreateDumpOnException);
gbCreateDumpOnExceptionInstalled = true;
}
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleMode(hOut, ENABLE_PROCESSED_OUTPUT|ENABLE_WRAP_AT_EOL_OUTPUT);
WARNING("Этот атрибут нужно задавать в настройках GUI!");
#if 0
SetConsoleTextAttribute(hOut, 7);
#endif
}
switch (anWorkMode)
{
case 0:
gnRunMode = RM_SERVER; break;
case 1:
gnRunMode = RM_ALTSERVER; break;
case 3:
gnRunMode = RM_GUIMACRO; break;
default:
gnRunMode = RM_UNDEFINED;
}
// Check linker fails!
if (ghOurModule == NULL)
{
wchar_t szTitle[128]; swprintf_c(szTitle, WIN3264TEST(L"ConEmuCD",L"ConEmuCD64") L", PID=%u", GetCurrentProcessId());
MessageBox(NULL, L"ConsoleMain2: ghOurModule is NULL\nDllMain was not executed", szTitle, MB_ICONSTOP|MB_SYSTEMMODAL);
return CERR_DLLMAIN_SKIPPED;
}
if (!gpSrv && (gnRunMode != RM_GUIMACRO))
gpSrv = (SrvInfo*)calloc(sizeof(SrvInfo),1);
if (gpSrv)
{
gpSrv->InitFields();
if (ghConEmuWnd)
{
GetWindowThreadProcessId(ghConEmuWnd, &gnConEmuPID);
}
}
#if defined(SHOW_STARTED_PRINT)
BOOL lbDbgWrite; DWORD nDbgWrite; HANDLE hDbg; char szDbgString[255], szHandles[128];
wchar_t szTitle[255];
swprintf_c(szTitle, L"ConEmuCD[%u]: PID=%u", WIN3264TEST(32,64), GetCurrentProcessId());
MessageBox(0, asCmdLine, szTitle, MB_SYSTEMMODAL);
hDbg = CreateFile(L"CONOUT$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
sprintf_c(szHandles, "STD_OUTPUT_HANDLE(0x%08X) STD_ERROR_HANDLE(0x%08X) CONOUT$(0x%08X)",
(DWORD)GetStdHandle(STD_OUTPUT_HANDLE), (DWORD)GetStdHandle(STD_ERROR_HANDLE), (DWORD)hDbg);
printf("ConEmuC: Printf: %s\n", szHandles);
sprintf_c(szDbgString, "ConEmuC: STD_OUTPUT_HANDLE: %s\n", szHandles);
lbDbgWrite = WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), szDbgString, lstrlenA(szDbgString), &nDbgWrite, NULL);
sprintf_c(szDbgString, "ConEmuC: STD_ERROR_HANDLE: %s\n", szHandles);
lbDbgWrite = WriteFile(GetStdHandle(STD_ERROR_HANDLE), szDbgString, lstrlenA(szDbgString), &nDbgWrite, NULL);
sprintf_c(szDbgString, "ConEmuC: CONOUT$: %s", szHandles);
lbDbgWrite = WriteFile(hDbg, szDbgString, lstrlenA(szDbgString), &nDbgWrite, NULL);
CloseHandle(hDbg);
//sprintf_c(szDbgString, "ConEmuC: PID=%u", GetCurrentProcessId());
//MessageBoxA(0, "Press Ok to continue", szDbgString, MB_SYSTEMMODAL);
#elif defined(SHOW_STARTED_PRINT_LITE)
{
wchar_t szPath[MAX_PATH]; GetModuleFileNameW(NULL, szPath, countof(szPath));
wchar_t szDbgMsg[MAX_PATH*2];
swprintf_c(szDbgMsg, L"%s started, PID=%u\n", PointToName(szPath), GetCurrentProcessId());
_wprintf(szDbgMsg);
gbDumpServerInitStatus = TRUE;
}
#endif
int iRc = 100;
PROCESS_INFORMATION pi; memset(&pi, 0, sizeof(pi));
STARTUPINFOW si = {sizeof(STARTUPINFOW)};
// ConEmuC должен быть максимально прозрачен для конечного процесса
GetStartupInfo(&si);
DWORD dwErr = 0, nWait = 0, nWaitExitEvent = -1, nWaitDebugExit = -1, nWaitComspecExit = -1;
DWORD dwWaitGui = -1, dwWaitRoot = -1;
BOOL lbRc = FALSE;
//DWORD mode = 0;
//BOOL lb = FALSE;
//ghHeap = HeapCreate(HEAP_GENERATE_EXCEPTIONS, 200000, 0);
memset(&gOSVer, 0, sizeof(gOSVer));
gOSVer.dwOSVersionInfoSize = sizeof(gOSVer);
GetOsVersionInformational(&gOSVer);
gnOsVer = ((gOSVer.dwMajorVersion & 0xFF) << 8) | (gOSVer.dwMinorVersion & 0xFF);
gbIsWine = IsWine(); // В общем случае, на флажок ориентироваться нельзя. Это для информации.
gbIsDBCS = IsWinDBCS();
gpLocalSecurity = LocalSecurity();
HMODULE hKernel = GetModuleHandleW(L"kernel32.dll");
// Хэндл консольного окна
ghConWnd = GetConEmuHWND(2);
gbVisibleOnStartup = IsWindowVisible(ghConWnd);
// здесь действительно может быть NULL при запуска как detached comspec
//_ASSERTE(ghConWnd!=NULL);
//if (!ghConWnd)
//{
// dwErr = GetLastError();
// _printf("ghConWnd==NULL, ErrCode=0x%08X\n", dwErr);
// iRc = CERR_GETCONSOLEWINDOW; goto wrap;
//}
// PID
gnSelfPID = GetCurrentProcessId();
gdwMainThreadId = GetCurrentThreadId();
DWORD nCurrentPIDCount = 0, nCurrentPIDs[64] = {};
if (hKernel)
{
pfnGetConsoleKeyboardLayoutName = (FGetConsoleKeyboardLayoutName)GetProcAddress(hKernel, "GetConsoleKeyboardLayoutNameW");
pfnGetConsoleProcessList = (FGetConsoleProcessList)GetProcAddress(hKernel, "GetConsoleProcessList");
pfnGetConsoleDisplayMode = (FGetConsoleDisplayMode)GetProcAddress(hKernel, "GetConsoleDisplayMode");
}
#ifdef _DEBUG
if (ghConWnd)
{
// Это событие дергается в отладочной (мной поправленной) версии фара
// Suppress warning C4311 'type cast': pointer truncation from 'HWND' to 'DWORD'
wchar_t szEvtName[64]; swprintf_c(szEvtName, L"FARconEXEC:%08X", LODWORD(ghConWnd));
ghFarInExecuteEvent = CreateEvent(0, TRUE, FALSE, szEvtName);
}
#endif
#if defined(SHOW_STARTED_MSGBOX) || defined(SHOW_COMSPEC_STARTED_MSGBOX)
if (!IsDebuggerPresent())
{
wchar_t szTitle[100]; swprintf_c(szTitle, L"ConEmuCD[%u]: PID=%u", WIN3264TEST(32,64), GetCurrentProcessId());
MessageBox(NULL, asCmdLine, szTitle, MB_SYSTEMMODAL);
}
#endif
#ifdef SHOW_STARTED_ASSERT
if (!IsDebuggerPresent())
{
_ASSERT(FALSE);
}
#endif
LoadExePath();
PRINT_COMSPEC(L"ConEmuC started: %s\n", asCmdLine);
nExitPlaceStep = 50;
xf_check();
#ifdef _DEBUG
{
wchar_t szCpInfo[128];
DWORD nCP = GetConsoleOutputCP();
swprintf_c(szCpInfo, L"Current Output CP = %u\n", nCP);
DEBUGSTRCP(szCpInfo);
}
#endif
// Event is used in almost all modes, even in "debugger"
if (!ghExitQueryEvent
&& (gnRunMode != RM_GUIMACRO)
)
{
ghExitQueryEvent = CreateEvent(NULL, TRUE/*используется в нескольких нитях, manual*/, FALSE, NULL);
}
LPCWSTR pszFullCmdLine = asCmdLine;
wchar_t szDebugCmdLine[MAX_PATH];
lstrcpyn(szDebugCmdLine, pszFullCmdLine ? pszFullCmdLine : L"", countof(szDebugCmdLine));
if (gnRunMode == RM_GUIMACRO)
{
// Separate parser function
iRc = GuiMacroCommandLine(pszFullCmdLine);
_ASSERTE(iRc == CERR_GUIMACRO_SUCCEEDED || iRc == CERR_GUIMACRO_FAILED);
goto wrap;
}
else if (anWorkMode)
{
// Alternative mode
_ASSERTE(anWorkMode==1); // может еще и 2 появится - для StandAloneGui
_ASSERTE(gnRunMode == RM_UNDEFINED || gnRunMode == RM_ALTSERVER);
gnRunMode = RM_ALTSERVER;
_ASSERTE(!gbCreateDumpOnExceptionInstalled);
_ASSERTE(gbAttachMode==am_None);
if (!(gbAttachMode & am_Modes))
gbAttachMode |= am_Simple;
gnConfirmExitParm = RConStartArgs::eConfNever;
gbAlwaysConfirmExit = FALSE; gbAutoDisableConfirmExit = FALSE;
gbNoCreateProcess = TRUE;
gbAlienMode = TRUE;
gpSrv->dwRootProcess = GetCurrentProcessId();
gpSrv->hRootProcess = GetCurrentProcess();
//gnConEmuPID = ...;
gpszRunCmd = (wchar_t*)calloc(1,2);
CreateColorerHeader();
}
else if ((iRc = ParseCommandLine(pszFullCmdLine)) != 0)
{
wchar_t szLog[80];
swprintf_c(szLog, L"ParseCommandLine returns %i, exiting", iRc);
LogFunction(szLog);
// Especially if our process was started under non-interactive account,
// than ExitWaitForKey causes the infinitely running process, which user can't kill easily
gbInShutdown = true;
goto wrap;
}
if (gbInShutdown)
goto wrap;
// По идее, при вызове дебаггера ParseCommandLine сразу должна послать на выход.
_ASSERTE(!(gpSrv->DbgInfo.bDebuggerActive || gpSrv->DbgInfo.bDebugProcess || gpSrv->DbgInfo.bDebugProcessTree))
if (gnRunMode == RM_SERVER)
{
// Until the root process is not terminated - set to STILL_ACTIVE
gnExitCode = STILL_ACTIVE;
#ifdef _DEBUG
// отладка для Wine
#ifdef USE_PIPE_DEBUG_BOXES
gbPipeDebugBoxes = true;
#endif
if (gbIsWine)
{
wchar_t szMsg[128];
msprintf(szMsg, countof(szMsg), L"ConEmuC Started, Wine detected\r\nConHWND=x%08X(%u), PID=%u\r\nCmdLine: ",
LODWORD(ghConWnd), LODWORD(ghConWnd), gnSelfPID);
_wprintf(szMsg);
_wprintf(asCmdLine);
_wprintf(L"\r\n");
}
#endif
// Warn about external hookers
CheckAndWarnHookers();
}
_ASSERTE(!gpSrv->hRootProcessGui || ((LODWORD(gpSrv->hRootProcessGui))!=0xCCCCCCCC && IsWindow(gpSrv->hRootProcessGui)));
//#ifdef _DEBUG
//CreateLogSizeFile();
//#endif
nExitPlaceStep = 100;
xf_check();
#ifdef SHOW_SERVER_STARTED_MSGBOX
if ((gnRunMode == RM_SERVER || gnRunMode == RM_ALTSERVER) && !IsDebuggerPresent() && gbNoCreateProcess)
{
ShowServerStartedMsgBox(asCmdLine);
}
#endif
/* ***************************** */
/* *** "Общая" инициализация *** */
/* ***************************** */
nExitPlaceStep = 150;
if (!ghExitQueryEvent)
{
dwErr = GetLastError();
_printf("CreateEvent() failed, ErrCode=0x%08X\n", dwErr);
iRc = CERR_EXITEVENT; goto wrap;
}
ResetEvent(ghExitQueryEvent);
if (!ghQuitEvent)
ghQuitEvent = CreateEvent(NULL, TRUE/*used in several threads, manual!*/, FALSE, NULL);
if (!ghQuitEvent)
{
dwErr = GetLastError();
_printf("CreateEvent() failed, ErrCode=0x%08X\n", dwErr);
iRc = CERR_EXITEVENT; goto wrap;
}
ResetEvent(ghQuitEvent);
xf_check();
if (gnRunMode == RM_SERVER || gnRunMode == RM_ALTSERVER || gnRunMode == RM_AUTOATTACH)
{
if ((HANDLE)ghConOut == INVALID_HANDLE_VALUE)
{
dwErr = GetLastError();
_printf("CreateFile(CONOUT$) failed, ErrCode=0x%08X\n", dwErr);
iRc = CERR_CONOUTFAILED; goto wrap;
}
if (pfnGetConsoleProcessList)
{
SetLastError(0);
nCurrentPIDCount = pfnGetConsoleProcessList(nCurrentPIDs, countof(nCurrentPIDs));
// Wine bug
if (!nCurrentPIDCount)
{
DWORD nErr = GetLastError();
_ASSERTE(nCurrentPIDCount || gbIsWine);
wchar_t szDbgMsg[512], szFile[MAX_PATH] = {};
GetModuleFileName(NULL, szFile, countof(szFile));
msprintf(szDbgMsg, countof(szDbgMsg), L"%s: PID=%u: GetConsoleProcessList failed, code=%u\r\n", PointToName(szFile), gnSelfPID, nErr);
_wprintf(szDbgMsg);
pfnGetConsoleProcessList = NULL;
}
}
}
nExitPlaceStep = 200;
/* ******************************** */
/* ****** "Server-mode" init ****** */
/* ******************************** */
if (gnRunMode == RM_SERVER || gnRunMode == RM_ALTSERVER || gnRunMode == RM_AUTOATTACH)
{
_ASSERTE(anWorkMode == (gnRunMode == RM_ALTSERVER));
if ((iRc = ServerInit()) != 0)
{
nExitPlaceStep = 250;
goto wrap;
}
}
else
{
xf_check();
if ((iRc = ComspecInit()) != 0)
{
nExitPlaceStep = 300;
goto wrap;
}
}
/* ********************************* */
/* ****** Start child process ****** */
/* ********************************* */
#ifdef SHOW_STARTED_PRINT
sprintf_c(szDbgString, "ConEmuC: PID=%u", GetCurrentProcessId());
MessageBoxA(0, "Press Ok to continue", szDbgString, MB_SYSTEMMODAL);
#endif
// Don't use CREATE_NEW_PROCESS_GROUP, or Ctrl-C stops working
// We need to set `0` before CreateProcess, otherwise we may get timeout,
// due to misc antivirus software, BEFORE CreateProcess finishes
if (!(gbAttachMode & am_Modes))
gpSrv->processes->nProcessStartTick = 0;
if (gbNoCreateProcess)
{
// Process already started, just attach RealConsole to ConEmu (VirtualConsole)
lbRc = TRUE;
pi.hProcess = gpSrv->hRootProcess;
pi.dwProcessId = gpSrv->dwRootProcess;
}
else
{
_ASSERTE(gnRunMode != RM_ALTSERVER);
nExitPlaceStep = 350;
// Process environment variables
wchar_t* pszExpandedCmd = ParseConEmuSubst(gpszRunCmd);
if (pszExpandedCmd)
{
free(gpszRunCmd);
gpszRunCmd = pszExpandedCmd;
}
#ifdef _DEBUG
if (ghFarInExecuteEvent && wcsstr(gpszRunCmd,L"far.exe"))
ResetEvent(ghFarInExecuteEvent);
#endif
LPCWSTR pszCurDir = NULL;
WARNING("The process handle must have the PROCESS_VM_OPERATION access right!");
if (gbUseDosBox)
{
DosBoxHelp();
}
else if (gnRunMode == RM_SERVER && !gbRunViaCmdExe)
{
// Проверить, может пытаются запустить GUI приложение как вкладку в ConEmu?
if (((si.dwFlags & STARTF_USESHOWWINDOW) && (si.wShowWindow == SW_HIDE))
|| !(si.dwFlags & STARTF_USESHOWWINDOW) || (si.wShowWindow != SW_SHOWNORMAL))
{
//_ASSERTEX(si.wShowWindow != SW_HIDE); -- да, окно сервера (консоль) спрятана
// Имеет смысл, только если окно хотят изначально спрятать
const wchar_t *psz = gpszRunCmd, *pszStart;
CEStr szExe;
if (NextArg(&psz, szExe, &pszStart) == 0)
{
MWow64Disable wow;
if (!gbSkipWowChange) wow.Disable();
DWORD RunImageSubsystem = 0, RunImageBits = 0, RunFileAttrs = 0;
bool bSubSystem = GetImageSubsystem(szExe, RunImageSubsystem, RunImageBits, RunFileAttrs);
if (!bSubSystem)
{
// szExe may be simple "notepad", we must seek for executable...
CEStr szFound;
// We are interesting only on ".exe" files,
// supposing that other executable extensions can't be GUI applications
if (apiSearchPath(NULL, szExe, L".exe", szFound))
bSubSystem = GetImageSubsystem(szFound, RunImageSubsystem, RunImageBits, RunFileAttrs);
}
if (bSubSystem)
{
if (RunImageSubsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
{
si.dwFlags |= STARTF_USESHOWWINDOW;
si.wShowWindow = SW_SHOWNORMAL;
}
}
}
}
}
// ConEmuC должен быть максимально прозрачен для конечного процесса
WARNING("При компиляции gcc все равно прозрачно не получается");
BOOL lbInheritHandle = (gnRunMode!=RM_SERVER);
// Если не делать вставку ConEmuC.exe в промежуток между g++.exe и (as.exe или cc1plus.exe)
// то все хорошо, если вставлять - то лезет куча ошибок вида
// c:/gcc/mingw/bin/../libexec/gcc/mingw32/4.3.2/cc1plus.exe:1: error: stray '\220' in program
// c:/gcc/mingw/bin/../libexec/gcc/mingw32/4.3.2/cc1plus.exe:1:4: warning: null character(s) ignored
// c:/gcc/mingw/bin/../libexec/gcc/mingw32/4.3.2/cc1plus.exe:1: error: stray '\3' in program
// c:/gcc/mingw/bin/../libexec/gcc/mingw32/4.3.2/cc1plus.exe:1:6: warning: null character(s) ignored
// Возможно, проблема в наследовании pipe-ов, проверить бы... или в другом SecurityDescriptor.
//MWow64Disable wow;
////#ifndef _DEBUG
//if (!gbSkipWowChange) wow.Disable();
////#endif
#ifdef _DEBUG
LPCWSTR pszRunCmpApp = NULL;
#endif
CEStr szExeName;
{
LPCWSTR pszStart = gpszRunCmd;
if (NextArg(&pszStart, szExeName) == 0)
{
#ifdef _DEBUG
if (FileExists(szExeName))
{
pszRunCmpApp = szExeName;
pszRunCmpApp = NULL;
}
#endif
}
}
LPSECURITY_ATTRIBUTES lpSec = LocalSecurity();
//#ifdef _DEBUG
// lpSec = NULL;
//#endif
// Не будем разрешать наследование, если нужно - сделаем DuplicateHandle
lbRc = createProcess(!gbSkipWowChange, NULL, gpszRunCmd, lpSec,lpSec, lbInheritHandle,
NORMAL_PRIORITY_CLASS/*|CREATE_NEW_PROCESS_GROUP*/
|CREATE_SUSPENDED/*((gnRunMode == RM_SERVER) ? CREATE_SUSPENDED : 0)*/,
NULL, pszCurDir, &si, &pi);
dwErr = GetLastError();
if (!lbRc && (gnRunMode == RM_SERVER) && dwErr == ERROR_FILE_NOT_FOUND)
{
// Фикс для перемещения ConEmu.exe в подпапку фара. т.е. far.exe находится на одну папку выше
if (gsSelfExe[0] != 0)
{
wchar_t szSelf[MAX_PATH*2];
wcscpy_c(szSelf, gsSelfExe);
wchar_t* pszSlash = wcsrchr(szSelf, L'\\');
if (pszSlash)
{
*pszSlash = 0; // получили папку с exe-шником
pszSlash = wcsrchr(szSelf, L'\\');
if (pszSlash)
{
*pszSlash = 0; // получили родительскую папку
pszCurDir = szSelf;
SetCurrentDirectory(pszCurDir);
// Пробуем еще раз, в родительской директории
// Не будем разрешать наследование, если нужно - сделаем DuplicateHandle
lbRc = createProcess(!gbSkipWowChange, NULL, gpszRunCmd, NULL,NULL, FALSE/*TRUE*/,
NORMAL_PRIORITY_CLASS/*|CREATE_NEW_PROCESS_GROUP*/
|CREATE_SUSPENDED/*((gnRunMode == RM_SERVER) ? CREATE_SUSPENDED : 0)*/,
NULL, pszCurDir, &si, &pi);
dwErr = GetLastError();
}
}
}
}
//wow.Restore();
if (lbRc) // && (gnRunMode == RM_SERVER))
{
nExitPlaceStep = 400;
#ifdef SHOW_INJECT_MSGBOX
wchar_t szDbgMsg[128], szTitle[128];
swprintf_c(szTitle, L"%s PID=%u", gsModuleName, GetCurrentProcessId());
szDbgMsg[0] = 0;
#endif
if (gbDontInjectConEmuHk
|| (!szExeName.IsEmpty() && IsConsoleServer(szExeName)))
{
#ifdef SHOW_INJECT_MSGBOX
swprintf_c(szDbgMsg, L"%s PID=%u\nConEmuHk injects skipped, PID=%u", gsModuleName, GetCurrentProcessId(), pi.dwProcessId);
#endif
}
else
{
TODO("Не только в сервере, но и в ComSpec, чтобы дочерние КОНСОЛЬНЫЕ процессы могли пользоваться редиректами");
//""F:\VCProject\FarPlugin\ConEmu\Bugs\DOS\TURBO.EXE ""
TODO("При выполнении DOS приложений - VirtualAllocEx(hProcess, обламывается!");
TODO("В принципе - завелось, но в сочетании с Anamorphosis получается странное зацикливание far->conemu->anamorph->conemu");
#ifdef SHOW_INJECT_MSGBOX
swprintf_c(szDbgMsg, L"%s PID=%u\nInjecting hooks into PID=%u", gsModuleName, GetCurrentProcessId(), pi.dwProcessId);
MessageBoxW(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL);
#endif
//BOOL gbLogProcess = FALSE;
//TODO("Получить из мэппинга glt_Process");
//#ifdef _DEBUG
//gbLogProcess = TRUE;
//#endif
CINJECTHK_EXIT_CODES iHookRc = CIH_GeneralError/*-1*/;
if (((gnImageSubsystem == IMAGE_SUBSYSTEM_DOS_EXECUTABLE) || (gnImageBits == 16))
&& !gbUseDosBox)
{
// Если запускается ntvdm.exe - все-равно хук поставить не даст
iHookRc = CIH_OK/*0*/;
}
else
{
// Чтобы модуль хуков в корневом процессе знал, что оно корневое
_ASSERTE(ghRootProcessFlag==NULL);
wchar_t szEvtName[64];
msprintf(szEvtName, countof(szEvtName), CECONEMUROOTPROCESS, pi.dwProcessId);
ghRootProcessFlag = CreateEvent(LocalSecurity(), TRUE, TRUE, szEvtName);
if (ghRootProcessFlag)
{
SetEvent(ghRootProcessFlag);
}
else
{
_ASSERTE(ghRootProcessFlag!=NULL);
}
// Теперь ставим хуки
iHookRc = InjectHooks(pi, gbLogProcess);
}
if (iHookRc != CIH_OK/*0*/)
{
DWORD nErrCode = GetLastError();
//_ASSERTE(iHookRc == 0); -- ассерт не нужен, есть MsgBox
wchar_t szDbgMsg[255], szTitle[128];
swprintf_c(szTitle, L"ConEmuC[%u], PID=%u", WIN3264TEST(32,64), GetCurrentProcessId());
swprintf_c(szDbgMsg, L"ConEmuC.M, PID=%u\nInjecting hooks into PID=%u\nFAILED, code=%i:0x%08X", GetCurrentProcessId(), pi.dwProcessId, iHookRc, nErrCode);
MessageBoxW(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL);
}
if (gbUseDosBox)
{
// Если запустился - то сразу добавим в список процессов (хотя он и не консольный)
ghDosBoxProcess = pi.hProcess; gnDosBoxPID = pi.dwProcessId;
//ProcessAdd(pi.dwProcessId);
}
}
#ifdef SHOW_INJECT_MSGBOX
wcscat_c(szDbgMsg, L"\nPress OK to resume started process");
MessageBoxW(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL);
#endif
// Отпустить процесс (это корневой процесс консоли, например far.exe)
ResumeThread(pi.hThread);
}
if (!lbRc && dwErr == 0x000002E4)
{
nExitPlaceStep = 450;
// Допустимо только в режиме comspec - тогда запустится новая консоль
_ASSERTE(gnRunMode != RM_SERVER);
PRINT_COMSPEC(L"Vista+: The requested operation requires elevation (ErrCode=0x%08X).\n", dwErr);
// Vista: The requested operation requires elevation.
LPCWSTR pszCmd = gpszRunCmd;
wchar_t szVerb[10];
CEStr szExec;
if (NextArg(&pszCmd, szExec) == 0)
{
SHELLEXECUTEINFO sei = {sizeof(SHELLEXECUTEINFO)};
sei.hwnd = ghConEmuWnd;
sei.fMask = SEE_MASK_NO_CONSOLE; //SEE_MASK_NOCLOSEPROCESS; -- смысла ждать завершения нет - процесс запускается в новой консоли
wcscpy_c(szVerb, L"open"); sei.lpVerb = szVerb;
sei.lpFile = szExec.ms_Val;
sei.lpParameters = pszCmd;
sei.lpDirectory = pszCurDir;
sei.nShow = SW_SHOWNORMAL;
MWow64Disable wow; wow.Disable();
lbRc = ShellExecuteEx(&sei);
dwErr = GetLastError();
#ifdef _DEBUG
OnProcessCreatedDbg(lbRc, dwErr, NULL, &sei);
#endif
wow.Restore();
if (lbRc)
{
// OK
pi.hProcess = NULL; pi.dwProcessId = 0;
pi.hThread = NULL; pi.dwThreadId = 0;
// т.к. запустилась новая консоль - подтверждение на закрытие этой точно не нужно
DisableAutoConfirmExit();
iRc = 0; goto wrap;
}
}
}
}
if (!lbRc)
{
nExitPlaceStep = 900;
PrintExecuteError(gpszRunCmd, dwErr);
iRc = CERR_CREATEPROCESS; goto wrap;
}
if ((gbAttachMode & am_Modes))
{
// мы цепляемся к уже существующему процессу:
// аттач из фар плагина или запуск dos-команды в новой консоли через -new_console
// в последнем случае отключение подтверждения закрытия однозначно некорректно
// -- DisableAutoConfirmExit(); - низя
}
else
{
if (!gpSrv->processes->nProcessStartTick) // Уже мог быть проинициализирован из cmd_CmdStartStop
gpSrv->processes->nProcessStartTick = GetTickCount();
}
if (pi.dwProcessId)
AllowSetForegroundWindow(pi.dwProcessId);
#ifdef _DEBUG
xf_validate(NULL);
#endif
/* *************************** */
/* *** Waiting for startup *** */
/* *************************** */
// Don't "lock" startup folder
UnlockCurrentDirectory();
if (gnRunMode == RM_SERVER)
{
//DWORD dwWaitGui = -1;
nExitPlaceStep = 500;
gpSrv->hRootProcess = pi.hProcess; pi.hProcess = NULL; // Required for Win2k
gpSrv->hRootThread = pi.hThread; pi.hThread = NULL;
gpSrv->dwRootProcess = pi.dwProcessId;
gpSrv->dwRootThread = pi.dwThreadId;
gpSrv->dwRootStartTime = GetTickCount();
// Скорее всего процесс в консольном списке уже будет
gpSrv->processes->CheckProcessCount(TRUE);
#ifdef _DEBUG
if (gpSrv->processes->nProcessCount && !gpSrv->DbgInfo.bDebuggerActive)
{
_ASSERTE(gpSrv->processes->pnProcesses[gpSrv->processes->nProcessCount-1]!=0);
}
#endif
//if (pi.hProcess) SafeCloseHandle(pi.hProcess);
//if (pi.hThread) SafeCloseHandle(pi.hThread);
if (gpSrv->hConEmuGuiAttached)
{
DEBUGTEST(DWORD t1 = timeGetTime());
dwWaitGui = WaitForSingleObject(gpSrv->hConEmuGuiAttached, 1000);
#ifdef _DEBUG
DWORD t2 = timeGetTime(), tDur = t2-t1;
if (tDur > GUIATTACHEVENT_TIMEOUT)
{
_ASSERTE(tDur <= GUIATTACHEVENT_TIMEOUT);
}
#endif
if (dwWaitGui == WAIT_OBJECT_0)
{
// GUI пайп готов
swprintf_c(gpSrv->szGuiPipeName, CEGUIPIPENAME, L".", LODWORD(ghConWnd)); // был gnSelfPID //-V205
}
}
// Ждем, пока в консоли не останется процессов (кроме нашего)
TODO("Проверить, может ли так получиться, что CreateProcess прошел, а к консоли он не прицепился? Может, если процесс GUI");
// "Подцепление" процесса к консоли наверное может задержать антивирус
nWait = nWaitExitEvent = WaitForSingleObject(ghExitQueryEvent, CHECK_ANTIVIRUS_TIMEOUT);
if (nWait != WAIT_OBJECT_0) // Если таймаут
{
iRc = gpSrv->processes->nProcessCount
+ (((gpSrv->processes->nProcessCount==1) && gbUseDosBox && (WaitForSingleObject(ghDosBoxProcess,0)==WAIT_TIMEOUT)) ? 1 : 0);
// И процессов в консоли все еще нет
if (iRc == 1 && !gpSrv->DbgInfo.bDebuggerActive)
{
if (!gbInShutdown)
{
gbTerminateOnCtrlBreak = TRUE;
gbCtrlBreakStopWaitingShown = TRUE;
//_printf("Process was not attached to console. Is it GUI?\nCommand to be executed:\n");
//_wprintf(gpszRunCmd);
PrintExecuteError(gpszRunCmd, 0, L"Process was not attached to console. Is it GUI?\n");
_printf("\n\nPress Ctrl+Break to stop waiting\n");
while (!gbInShutdown && (nWait != WAIT_OBJECT_0))
{
nWait = nWaitExitEvent = WaitForSingleObject(ghExitQueryEvent, 250);
if (nWaitExitEvent == WAIT_OBJECT_0)
{
dwWaitRoot = WaitForSingleObject(gpSrv->hRootProcess, 0);
if (dwWaitRoot == WAIT_OBJECT_0)
{
gbTerminateOnCtrlBreak = FALSE;
gbCtrlBreakStopWaitingShown = FALSE; // сбросим, чтобы ассерты не лезли
}
else
{
// Root process must be terminated at this point (can't start/initialize)
_ASSERTE(dwWaitRoot == WAIT_OBJECT_0);
}
}
if ((nWait != WAIT_OBJECT_0) && (gpSrv->processes->nProcessCount > 1))
{
gbTerminateOnCtrlBreak = FALSE;
gbCtrlBreakStopWaitingShown = FALSE; // сбросим, чтобы ассерты не лезли
goto wait; // OK, переходим в основной цикл ожидания завершения
}
}
}
// Что-то при загрузке компа иногда все-таки не дожидается, когда процесс в консоли появится
_ASSERTE(FALSE && gbTerminateOnCtrlBreak && gbInShutdown);
iRc = CERR_PROCESSTIMEOUT; goto wrap;
}
}
}
else if (gnRunMode == RM_COMSPEC)
{
// В режиме ComSpec нас интересует завершение ТОЛЬКО дочернего процесса
_ASSERTE(pi.dwProcessId!=0);
gpSrv->dwRootProcess = pi.dwProcessId;
gpSrv->dwRootThread = pi.dwThreadId;
}
/* *************************** */
/* *** Ожидание завершения *** */
/* *************************** */
wait:
#ifdef _DEBUG
xf_validate(NULL);
#endif
#ifdef _DEBUG
if (gnRunMode == RM_SERVER)
{
gbPipeDebugBoxes = false;
}
#endif
// JIC, if there was "goto"
UnlockCurrentDirectory();
if (gnRunMode == RM_ALTSERVER)
{
// Alternative server, we can't wait for "self" termination
iRc = 0;
goto AltServerDone;
} // (gnRunMode == RM_ALTSERVER)
else if (gnRunMode == RM_SERVER)
{
nExitPlaceStep = EPS_WAITING4PROCESS/*550*/;
// There is at least one process in console. Wait until there would be nobody except us.
nWait = WAIT_TIMEOUT; nWaitExitEvent = -2;
_ASSERTE(!gpSrv->DbgInfo.bDebuggerActive);
#ifdef _DEBUG
while (nWait == WAIT_TIMEOUT)
{
nWait = nWaitExitEvent = WaitForSingleObject(ghExitQueryEvent, 100);
// Not actual? Что-то при загрузке компа иногда все-таки не дожидается, когда процесс в консоли появится
_ASSERTE(!(gbCtrlBreakStopWaitingShown && (nWait != WAIT_TIMEOUT)));
}
#else
nWait = nWaitExitEvent = WaitForSingleObject(ghExitQueryEvent, INFINITE);
_ASSERTE(!(gbCtrlBreakStopWaitingShown && (nWait != WAIT_TIMEOUT)));
#endif
ShutdownSrvStep(L"ghExitQueryEvent was set");
#ifdef _DEBUG
xf_validate(NULL);
#endif
// Root ExitCode
GetExitCodeProcess(gpSrv->hRootProcess, &gnExitCode);
nExitPlaceStep = EPS_ROOTPROCFINISHED/*560*/;
#ifdef _DEBUG
if (nWait == WAIT_OBJECT_0)
{
DEBUGSTRFIN(L"*** FinalizeEvent was set!\n");
}
#endif
} // (gnRunMode == RM_SERVER)
else
{
nExitPlaceStep = 600;
//HANDLE hEvents[3];
//hEvents[0] = pi.hProcess;
//hEvents[1] = ghCtrlCEvent;
//hEvents[2] = ghCtrlBreakEvent;
//WaitForSingleObject(pi.hProcess, INFINITE);
#ifdef _DEBUG
xf_validate(NULL);
#endif
DWORD nWaitMS = gbAsyncRun ? 0 : INFINITE;
nWaitComspecExit = WaitForSingleObject(pi.hProcess, nWaitMS);
#ifdef _DEBUG
xf_validate(NULL);
#endif
// Получить ExitCode
GetExitCodeProcess(pi.hProcess, &gnExitCode);
#ifdef _DEBUG
xf_validate(NULL);
#endif
// Close all handles now
if (pi.hProcess)
SafeCloseHandle(pi.hProcess);
if (pi.hThread)
SafeCloseHandle(pi.hThread);
#ifdef _DEBUG
xf_validate(NULL);
#endif
} // (gnRunMode == RM_COMSPEC)
/* *********************** */
/* *** Finalizing work *** */
/* *********************** */
iRc = 0;
wrap:
ShutdownSrvStep(L"Finalizing.1");
#if defined(SHOW_STARTED_PRINT_LITE)
if (gnRunMode == RM_SERVER)
{
_printf("\n" WIN3264TEST("ConEmuC.exe","ConEmuC64.exe") " finalizing, PID=%u\n", GetCurrentProcessId());
}
#endif
#ifdef VALIDATE_AND_DELAY_ON_TERMINATE
// Проверка кучи
xf_validate(NULL);
// Отлов изменения высоты буфера
if (gnRunMode == RM_SERVER)
Sleep(1000);
#endif
// К сожалению, HandlerRoutine может быть еще не вызван, поэтому
// в самой процедуре ExitWaitForKey вставлена проверка флага gbInShutdown
PRINT_COMSPEC(L"Finalizing. gbInShutdown=%i\n", gbInShutdown);
#ifdef SHOW_STARTED_MSGBOX
MessageBox(GetConEmuHWND(2), L"Finalizing", (gnRunMode == RM_SERVER) ? L"ConEmuC.Server" : L"ConEmuC.ComSpec", 0);
#endif
#ifdef VALIDATE_AND_DELAY_ON_TERMINATE
xf_validate(NULL);
#endif
if (iRc == CERR_GUIMACRO_SUCCEEDED)
{
iRc = 0;
}
if (gnRunMode == RM_SERVER && gpSrv->hRootProcess)
GetExitCodeProcess(gpSrv->hRootProcess, &gnExitCode);
else if (pi.hProcess)
GetExitCodeProcess(pi.hProcess, &gnExitCode);
// Ассерт может быть если был запрос на аттач, который не удался
_ASSERTE(gnExitCode!=STILL_ACTIVE || (iRc==CERR_ATTACHFAILED) || (iRc==CERR_RUNNEWCONSOLE) || gbAsyncRun);
// Log exit code
if (((gnRunMode == RM_SERVER && gpSrv->hRootProcess) ? gpSrv->dwRootProcess : pi.dwProcessId) != 0)
{
wchar_t szInfo[80];
LPCWSTR pszName = (gnRunMode == RM_SERVER && gpSrv->hRootProcess) ? L"Shell" : L"Process";
DWORD nPID = (gnRunMode == RM_SERVER && gpSrv->hRootProcess) ? gpSrv->dwRootProcess : pi.dwProcessId;
if (gnExitCode >= 0x80000000)
swprintf_c(szInfo, L"\n%s PID=%u ExitCode=%u (%i) {x%08X}", pszName, nPID, gnExitCode, (int)gnExitCode, gnExitCode);
else
swprintf_c(szInfo, L"\n%s PID=%u ExitCode=%u {x%08X}", pszName, nPID, gnExitCode, gnExitCode);
LogFunction(szInfo+1);
if (gbPrintRetErrLevel)
{
wcscat_c(szInfo, L"\n");
_wprintf(szInfo);
}
// Post information to GUI
if (gnMainServerPID && !gpSrv->bWasDetached)
{
CESERVER_REQ* pIn = ExecuteNewCmd(CECMD_GETROOTINFO, sizeof(CESERVER_REQ_HDR)+sizeof(CESERVER_ROOT_INFO));
if (pIn && gpSrv->processes->GetRootInfo(pIn))
{
CESERVER_REQ *pSrvOut = ExecuteGuiCmd(ghConWnd, pIn, ghConWnd, TRUE/*async*/);
ExecuteFreeResult(pSrvOut);
}
ExecuteFreeResult(pIn);
}
}
if (iRc && (gbAttachMode & am_Auto))
{
// Issue 1003: Non zero exit codes leads to problems in some applications...
iRc = 0;
}
ShutdownSrvStep(L"Finalizing.2");
if (!gbInShutdown // только если юзер не нажал крестик в заголовке окна, или не удался /ATTACH (чтобы в консоль не гадить)
&& ((iRc!=0 && iRc!=CERR_RUNNEWCONSOLE && iRc!=CERR_EMPTY_COMSPEC_CMDLINE
&& iRc!=CERR_UNICODE_CHK_FAILED && iRc!=CERR_UNICODE_CHK_OKAY
&& iRc!=CERR_GUIMACRO_SUCCEEDED && iRc!=CERR_GUIMACRO_FAILED
&& iRc!=CERR_AUTOATTACH_NOT_ALLOWED && iRc!=CERR_ATTACHFAILED
&& iRc!=CERR_WRONG_GUI_VERSION
&& !(gnRunMode!=RM_SERVER && iRc==CERR_CREATEPROCESS))
|| gbAlwaysConfirmExit)
)
{
UnlockCurrentDirectory();
//#ifdef _DEBUG
//if (!gbInShutdown)
// MessageBox(0, L"ExitWaitForKey", L"ConEmuC", MB_SYSTEMMODAL);
//#endif
BOOL lbProcessesLeft = FALSE, lbDontShowConsole = FALSE;
BOOL lbLineFeedAfter = TRUE;
DWORD nProcesses[10] = {};
DWORD nProcCount = -1;
if (pfnGetConsoleProcessList)
{
// консоль может не успеть среагировать на "закрытие" корневого процесса
nProcCount = pfnGetConsoleProcessList(nProcesses, 10);
if (nProcCount > 1)
{
DWORD nValid = 0;
for (DWORD i = 0; i < nProcCount; i++)
{
if ((nProcesses[i] != gpSrv->dwRootProcess)
#ifndef WIN64
&& (nProcesses[i] != gpSrv->processes->nNtvdmPID)
#endif
)
{
nValid++;
}
}
lbProcessesLeft = (nValid > 1);
}
}
LPCWSTR pszMsg = NULL;
if (lbProcessesLeft)
{
pszMsg = L"\n\nPress Enter or Esc to exit...";
lbDontShowConsole = gnRunMode != RM_SERVER;
}
else if ((gnConfirmExitParm == RConStartArgs::eConfEmpty)
|| (gnConfirmExitParm == RConStartArgs::eConfHalt))
{
lbLineFeedAfter = FALSE; // Don't print anything to console
}
else
{
if (gbRootWasFoundInCon == 1)
{
// If root process has been working less than CHECK_ROOTOK_TIMEOUT
if (gbRootAliveLess10sec && (gnConfirmExitParm != RConStartArgs::eConfAlways))
{
static wchar_t szMsg[255];
if (gnExitCode)
{
PrintExecuteError(gpszRunCmd, 0, L"\n");
}
wchar_t szExitCode[40];
if (gnExitCode > 255)
swprintf_c(szExitCode, L"x%08X(%u)", gnExitCode, gnExitCode);
else
swprintf_c(szExitCode, L"%u", gnExitCode);
swprintf_c(szMsg,
L"\n\nConEmuC: Root process was alive less than 10 sec, ExitCode=%s.\nPress Enter or Esc to close console...",
szExitCode);
pszMsg = szMsg;
}
else
{
pszMsg = L"\n\nPress Enter or Esc to close console...";
}
}
}
if (!pszMsg
&& (gnConfirmExitParm != RConStartArgs::eConfEmpty)
&& (gnConfirmExitParm != RConStartArgs::eConfHalt))
{
// Let's show anything (default message)
pszMsg = L"\n\nPress Enter or Esc to close console, or wait...";
#ifdef _DEBUG
static wchar_t szDbgMsg[255];
swprintf_c(szDbgMsg,
L"\n\ngbInShutdown=%i, iRc=%i, gbAlwaysConfirmExit=%i, nExitQueryPlace=%i"
L"%s",
(int)gbInShutdown, iRc, (int)gbAlwaysConfirmExit, nExitQueryPlace,
pszMsg);
pszMsg = szDbgMsg;
#endif
}
DWORD keys = (gnConfirmExitParm == RConStartArgs::eConfHalt) ? 0
: (VK_RETURN|(VK_ESCAPE<<8));
ExitWaitForKey(keys, pszMsg, lbLineFeedAfter, lbDontShowConsole);
UNREFERENCED_PARAMETER(nProcCount);
UNREFERENCED_PARAMETER(nProcesses[0]);
// During the wait, new process may be started in our console
{
int nCount = gpSrv->processes->nProcessCount;
if ((gpSrv->ConnectInfo.bConnected && (nCount > 1))
|| gpSrv->DbgInfo.bDebuggerActive)
{
// OK, new root found, wait for it
goto wait;
}
}
}
// На всякий случай - выставим событие
if (ghExitQueryEvent)
{
_ASSERTE(gbTerminateOnCtrlBreak==FALSE);
if (!nExitQueryPlace) nExitQueryPlace = 11+(nExitPlaceStep);
SetTerminateEvent(ste_ConsoleMain);
}
// Завершение RefreshThread, InputThread, ServerThread
if (ghQuitEvent) SetEvent(ghQuitEvent);
ShutdownSrvStep(L"Finalizing.3");
#ifdef _DEBUG
xf_validate(NULL);
#endif
/* ***************************** */
/* *** "Режимное" завершение *** */
/* ***************************** */
if (gnRunMode == RM_SERVER)
{
ServerDone(iRc, true);
//MessageBox(0,L"Server done...",L"ConEmuC",0);
SafeCloseHandle(gpSrv->DbgInfo.hDebugReady);
SafeCloseHandle(gpSrv->DbgInfo.hDebugThread);
}
else if (gnRunMode == RM_COMSPEC)
{
_ASSERTE(iRc==CERR_RUNNEWCONSOLE || gbComspecInitCalled);
if (gbComspecInitCalled)
{
ComspecDone(iRc);
}
//MessageBox(0,L"Comspec done...",L"ConEmuC",0);
}
else if (gnRunMode == RM_APPLICATION)
{
SendStopped();
}
ShutdownSrvStep(L"Finalizing.4");
/* ************************** */
/* *** "Общее" завершение *** */
/* ************************** */
#ifdef _DEBUG
#if 0
if (gnRunMode == RM_COMSPEC)
{
if (gpszPrevConTitle)
{
if (ghConWnd)
SetTitle(gpszPrevConTitle);
}
}
#endif
SafeFree(gpszPrevConTitle);
#endif
SafeCloseHandle(ghRootProcessFlag);
LogSize(NULL, 0, "Shutdown");
//ghConIn.Close();
ghConOut.Close();
SafeDelete(gpLogSize);
//if (wpszLogSizeFile)
//{
// //DeleteFile(wpszLogSizeFile);
// free(wpszLogSizeFile); wpszLogSizeFile = NULL;
//}
#ifdef _DEBUG
SafeCloseHandle(ghFarInExecuteEvent);
#endif
SafeFree(gpszRunCmd);
SafeFree(gpszTaskCmd);
SafeFree(gpszForcedTitle);
CommonShutdown();
ShutdownSrvStep(L"Finalizing.5");
// -> DllMain
//if (ghHeap)
//{
// HeapDestroy(ghHeap);
// ghHeap = NULL;
//}
// борьба с оптимизатором
if (szDebugCmdLine[0] != 0)
{
int nLen = lstrlen(szDebugCmdLine);
UNREFERENCED_PARAMETER(nLen);
}
// Если режим ComSpec - вернуть код возврата из запущенного процесса
if (iRc == 0 && gnRunMode == RM_COMSPEC)
iRc = gnExitCode;
#ifdef SHOW_STARTED_MSGBOX
MessageBox(GetConEmuHWND(2), L"Exiting", (gnRunMode == RM_SERVER) ? L"ConEmuC.Server" : L"ConEmuC.ComSpec", 0);
#endif
if (gpSrv)
{
gpSrv->FinalizeFields();
free(gpSrv);
gpSrv = NULL;
}
AltServerDone:
ShutdownSrvStep(L"Finalizing done");
UNREFERENCED_PARAMETER(gpszCheck4NeedCmd);
UNREFERENCED_PARAMETER(nWaitDebugExit);
UNREFERENCED_PARAMETER(nWaitComspecExit);
#if 0
if (gnRunMode == RM_SERVER)
{
xf_dump();
}
#endif
return iRc;
}
#if defined(__GNUC__)
extern "C"
#endif
int __stdcall ConsoleMain2(int anWorkMode/*0-Server&ComSpec,1-AltServer,2-Reserved*/)
{
return ConsoleMain3(anWorkMode, GetCommandLineW());
}
int WINAPI RequestLocalServer(/*[IN/OUT]*/RequestLocalServerParm* Parm)
{
//_ASSERTE(FALSE && "ConEmuCD. Continue to RequestLocalServer");
int iRc = 0;
wchar_t szName[64];
if (!Parm || (Parm->StructSize != sizeof(*Parm)))
{
iRc = CERR_CARGUMENT;
goto wrap;
}
// Если больше ничего кроме регистрации событий нет
if ((Parm->Flags & slsf__EventsOnly) == Parm->Flags)
{
goto DoEvents;
}
Parm->pAnnotation = NULL;
Parm->Flags &= ~slsf_PrevAltServerPID;
// Хэндл обновим сразу
if (Parm->Flags & slsf_SetOutHandle)
{
ghConOut.SetBufferPtr(Parm->ppConOutBuffer);
}
if (gnRunMode != RM_ALTSERVER)
{
#ifdef SHOW_ALTERNATIVE_MSGBOX
if (!IsDebuggerPresent())
{
char szMsg[128]; msprintf(szMsg, countof(szMsg), "AltServer: " WIN3264TEST("ConEmuCD.dll","ConEmuCD64.dll") " loaded, PID=%u, TID=%u", GetCurrentProcessId(), GetCurrentThreadId());
MessageBoxA(NULL, szMsg, "ConEmu AltServer" WIN3264TEST(""," x64"), 0);
}
#endif
_ASSERTE(gpSrv == NULL);
_ASSERTE(gnRunMode == RM_UNDEFINED);
HWND hConEmu = GetConEmuHWND(1/*Gui Main window*/);
if (!hConEmu || !IsWindow(hConEmu))
{
iRc = CERR_GUI_NOT_FOUND;
goto wrap;
}
// Need to block all requests to output buffer in other threads
MSectionLockSimple csRead;
if (gpSrv)
csRead.Lock(&gpSrv->csReadConsoleInfo, LOCK_READOUTPUT_TIMEOUT);
// Инициализировать gcrVisibleSize и прочие переменные
CONSOLE_SCREEN_BUFFER_INFO sbi = {};
// MyGetConsoleScreenBufferInfo пользовать нельзя - оно gpSrv и gnRunMode хочет
if (GetConsoleScreenBufferInfo(ghConOut, &sbi))
{
gcrVisibleSize.X = sbi.srWindow.Right - sbi.srWindow.Left + 1;
gcrVisibleSize.Y = sbi.srWindow.Bottom - sbi.srWindow.Top + 1;
gbParmVisibleSize = FALSE;
gnBufferHeight = (sbi.dwSize.Y == gcrVisibleSize.Y) ? 0 : sbi.dwSize.Y;
gnBufferWidth = (sbi.dwSize.X == gcrVisibleSize.X) ? 0 : sbi.dwSize.X;
gbParmBufSize = (gnBufferHeight != 0);
}
_ASSERTE(gcrVisibleSize.X>0 && gcrVisibleSize.X<=400 && gcrVisibleSize.Y>0 && gcrVisibleSize.Y<=300);
csRead.Unlock();
iRc = ConsoleMain2(1/*0-Server&ComSpec,1-AltServer,2-Reserved*/);
if ((iRc == 0) && gpSrv && gpSrv->dwPrevAltServerPID)
{
Parm->Flags |= slsf_PrevAltServerPID;
Parm->nPrevAltServerPID = gpSrv->dwPrevAltServerPID;
}
}
// Если поток RefreshThread был "заморожен" при запуске другого сервера
if ((gpSrv->nRefreshFreezeRequests > 0) && !(Parm->Flags & slsf_OnAllocConsole))
{
ThawRefreshThread();
}
TODO("Инициализация TrueColor буфера - Parm->ppAnnotation");
DoEvents:
if (Parm->Flags & slsf_GetFarCommitEvent)
{
if (gpSrv)
{
_ASSERTE(gpSrv->hFarCommitEvent != NULL); // Уже должно быть создано!
}
else
{
;
}
swprintf_c(szName, CEFARWRITECMTEVENT, gnSelfPID);
Parm->hFarCommitEvent = OpenEvent(EVENT_MODIFY_STATE, FALSE, szName);
_ASSERTE(Parm->hFarCommitEvent!=NULL);
if (Parm->Flags & slsf_FarCommitForce)
{
gpSrv->bFarCommitRegistered = TRUE;
}
}
if (Parm->Flags & slsf_GetCursorEvent)
{
_ASSERTE(gpSrv->hCursorChangeEvent != NULL); // Уже должно быть создано!
swprintf_c(szName, CECURSORCHANGEEVENT, gnSelfPID);
Parm->hCursorChangeEvent = OpenEvent(EVENT_MODIFY_STATE, FALSE, szName);
_ASSERTE(Parm->hCursorChangeEvent!=NULL);
gpSrv->bCursorChangeRegistered = TRUE;
}
if (Parm->Flags & slsf_OnFreeConsole)
{
FreezeRefreshThread();
}
if (Parm->Flags & slsf_OnAllocConsole)
{
ghConWnd = GetConEmuHWND(2);
LoadSrvInfoMap();
//TODO: Request AltServer state from MainServer?
ThawRefreshThread();
}
wrap:
return iRc;
}
//#if defined(CRTSTARTUP)
//extern "C"{
// BOOL WINAPI _DllMainCRTStartup(HANDLE hDll,DWORD dwReason,LPVOID lpReserved);
//};
//
//BOOL WINAPI mainCRTStartup(HANDLE hDll,DWORD dwReason,LPVOID lpReserved)
//{
// DllMain(hDll, dwReason, lpReserved);
// return TRUE;
//}
//#endif
void PrintVersion()
{
char szProgInfo[255];
sprintf_c(szProgInfo,
"ConEmuC build %s %s. " CECOPYRIGHTSTRING_A "\n",
CONEMUVERS, WIN3264TEST("x86","x64"));
_printf(szProgInfo);
}
void Help()
{
PrintVersion();
// See definition in "ConEmuCD/ConsoleHelp.h"
_wprintf(pConsoleHelp);
_wprintf(pNewConsoleHelp);
// Don't ask keypress before exit
gbInShutdown = TRUE;
}
void DosBoxHelp()
{
// See definition in "ConEmuCD/ConsoleHelp.h"
_wprintf(pDosBoxHelp);
}
void PrintExecuteError(LPCWSTR asCmd, DWORD dwErr, LPCWSTR asSpecialInfo/*=NULL*/)
{
if (asSpecialInfo)
{
if (*asSpecialInfo)
_wprintf(asSpecialInfo);
}
else
{
wchar_t* lpMsgBuf = NULL;
DWORD nFmtRc, nFmtErr = 0;
if (dwErr == 5)
{
lpMsgBuf = (wchar_t*)LocalAlloc(LPTR, 128*sizeof(wchar_t));
_wcscpy_c(lpMsgBuf, 128, L"Access is denied.\nThis may be cause of antiviral or file permissions denial.");
}
else
{
nFmtRc = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, dwErr, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&lpMsgBuf, 0, NULL);
if (!nFmtRc)
nFmtErr = GetLastError();
}
_printf("Can't create process, ErrCode=0x%08X, Description:\n", dwErr);
_wprintf((lpMsgBuf == NULL) ? L"<Unknown error>" : lpMsgBuf);
if (lpMsgBuf) LocalFree(lpMsgBuf);
UNREFERENCED_PARAMETER(nFmtErr);
}
size_t nCchMax = MAX_PATH*2+32;
wchar_t* lpInfo = (wchar_t*)calloc(nCchMax,sizeof(*lpInfo));
if (lpInfo)
{
_wcscpy_c(lpInfo, nCchMax, L"\nCurrent directory:\n");
_ASSERTE(nCchMax>=(MAX_PATH*2+32));
if (gpStartEnv && gpStartEnv->pszWorkDir)
{
_wcscat_c(lpInfo, nCchMax, gpStartEnv->pszWorkDir);
}
else
{
_ASSERTE(gpStartEnv && gpStartEnv->pszWorkDir);
GetCurrentDirectory(MAX_PATH*2, lpInfo+lstrlen(lpInfo));
}
_wcscat_c(lpInfo, nCchMax, L"\n");
_wprintf(lpInfo);
free(lpInfo);
}
_printf("\nCommand to be executed:\n");
_wprintf(asCmd ? asCmd : L"<null>");
_printf("\n");
}
int CheckAttachProcess()
{
LogFunction(L"CheckAttachProcess");
int liArgsFailed = 0;
wchar_t szFailMsg[512]; szFailMsg[0] = 0;
DWORD nProcesses[20] = {};
DWORD nProcCount;
BOOL lbRootExists = FALSE;
wchar_t szProc[255] = {}, szTmp[10] = {};
DWORD nFindId;
if (gpSrv->hRootProcessGui)
{
if (!IsWindow(gpSrv->hRootProcessGui))
{
swprintf_c(szFailMsg, L"Attach of GUI application was requested,\n"
L"but required HWND(0x%08X) not found!", LODWORD(gpSrv->hRootProcessGui));
LogString(szFailMsg);
liArgsFailed = 1;
// will return CERR_CARGUMENT
}
else
{
DWORD nPid; GetWindowThreadProcessId(gpSrv->hRootProcessGui, &nPid);
if (!gpSrv->dwRootProcess || (gpSrv->dwRootProcess != nPid))
{
swprintf_c(szFailMsg, L"Attach of GUI application was requested,\n"
L"but PID(%u) of HWND(0x%08X) does not match Root(%u)!",
nPid, LODWORD(gpSrv->hRootProcessGui), gpSrv->dwRootProcess);
LogString(szFailMsg);
liArgsFailed = 2;
// will return CERR_CARGUMENT
}
}
}
else if (pfnGetConsoleProcessList==NULL)
{
wcscpy_c(szFailMsg, L"Attach to console app was requested, but required WinXP or higher!");
LogString(szFailMsg);
liArgsFailed = 3;
// will return CERR_CARGUMENT
}
else
{
nProcCount = pfnGetConsoleProcessList(nProcesses, 20);
if ((nProcCount == 1) && gbCreatingHiddenConsole)
{
// Подождать, пока вызвавший процесс прицепится к нашей созданной консоли
DWORD nStart = GetTickCount(), nMaxDelta = 30000, nDelta = 0;
while (nDelta < nMaxDelta)
{
Sleep(100);
nProcCount = pfnGetConsoleProcessList(nProcesses, 20);
if (nProcCount > 1)
break;
nDelta = (GetTickCount() - nStart);
}
}
// 2 процесса, потому что это мы сами и минимум еще один процесс в этой консоли,
// иначе смысла в аттаче нет
if (nProcCount < 2)
{
wcscpy_c(szFailMsg, L"Attach to console app was requested, but there is no console processes!");
LogString(szFailMsg);
liArgsFailed = 4;
//will return CERR_CARGUMENT
}
// не помню, зачем такая проверка была введена, но (nProcCount > 2) мешает аттачу.
// в момент запуска сервера (/ATTACH /PID=n) еще жив родительский (/ATTACH /NOCMD)
//// Если cmd.exe запущен из cmd.exe (в консоли уже больше двух процессов) - ничего не делать
else if ((gpSrv->dwRootProcess != 0) || (nProcCount > 2))
{
lbRootExists = (gpSrv->dwRootProcess == 0);
// И ругаться только под отладчиком
nFindId = 0;
for (int n = ((int)nProcCount-1); n >= 0; n--)
{
if (szProc[0]) wcscat_c(szProc, L", ");
swprintf_c(szTmp, L"%i", nProcesses[n]);
wcscat_c(szProc, szTmp);
if (gpSrv->dwRootProcess)
{
if (!lbRootExists && nProcesses[n] == gpSrv->dwRootProcess)
lbRootExists = TRUE;
}
else if ((nFindId == 0) && (nProcesses[n] != gnSelfPID))
{
// Будем считать его корневым.
// Собственно, кого считать корневым не важно, т.к.
// сервер не закроется до тех пор пока жив хотя бы один процесс
nFindId = nProcesses[n];
}
}
if ((gpSrv->dwRootProcess == 0) && (nFindId != 0))
{
gpSrv->dwRootProcess = nFindId;
lbRootExists = TRUE;
}
if ((gpSrv->dwRootProcess != 0) && !lbRootExists)
{
swprintf_c(szFailMsg, L"Attach to GUI was requested, but\n" L"root process (%u) does not exists", gpSrv->dwRootProcess);
LogString(szFailMsg);
liArgsFailed = 5;
//will return CERR_CARGUMENT
}
else if ((gpSrv->dwRootProcess == 0) && (nProcCount > 2))
{
swprintf_c(szFailMsg, L"Attach to GUI was requested, but\n" L"there is more than 2 console processes: %s\n", szProc);
LogString(szFailMsg);
liArgsFailed = 6;
//will return CERR_CARGUMENT
}
}
}
if (liArgsFailed)
{
DWORD nSelfPID = GetCurrentProcessId();
PROCESSENTRY32 self = {sizeof(self)}, parent = {sizeof(parent)};
// Not optimal, needs refactoring
if (GetProcessInfo(nSelfPID, &self))
GetProcessInfo(self.th32ParentProcessID, &parent);
LPCWSTR pszCmdLine = GetCommandLineW(); if (!pszCmdLine) pszCmdLine = L"";
wchar_t szTitle[MAX_PATH*2];
swprintf_c(szTitle,
L"ConEmuC %s [%u], PID=%u, Code=%i" L"\r\n"
L"ParentPID=%u: %s" L"\r\n"
L" ", // szFailMsg follows this
gsVersion, WIN3264TEST(32,64), nSelfPID, liArgsFailed,
self.th32ParentProcessID, parent.szExeFile[0] ? parent.szExeFile : L"<terminated>");
CEStr lsMsg = lstrmerge(szTitle, szFailMsg, L"\r\nCommand line:\r\n ", pszCmdLine);
// Avoid automatic termination of ExitWaitForKey
gbInShutdown = FALSE;
// Force light-red on black for error message
MSetConTextAttr setAttr(ghConOut, 12);
const DWORD nAttachErrorTimeoutMessage = 15*1000; // 15 sec
ExitWaitForKey(VK_RETURN|(VK_ESCAPE<<8), lsMsg, true, true, nAttachErrorTimeoutMessage);
LogString(L"CheckAttachProcess: CERR_CARGUMENT after ExitWaitForKey");
gbInShutdown = TRUE;
return CERR_CARGUMENT;
}
return 0; // OK
}
void SetWorkEnvVar()
{
_ASSERTE(gnRunMode == RM_SERVER && !gbNoCreateProcess);
SetConEmuWorkEnvVar(ghOurModule);
}
// 1. Заменить подстановки вида: !ConEmuHWND!, !ConEmuDrawHWND!, !ConEmuBackHWND!, !ConEmuWorkDir!
// 2. Развернуть переменные окружения (PowerShell, например, не признает переменные в качестве параметров)
wchar_t* ParseConEmuSubst(LPCWSTR asCmd)
{
if (!asCmd || !*asCmd)
{
LogFunction(L"ParseConEmuSubst - skipped");
return NULL;
}
LogFunction(L"ParseConEmuSubst");
// Другие имена нет смысла передавать через "!" вместо "%"
LPCWSTR szNames[] = {ENV_CONEMUHWND_VAR_W, ENV_CONEMUDRAW_VAR_W, ENV_CONEMUBACK_VAR_W, ENV_CONEMUWORKDIR_VAR_W};
#ifdef _DEBUG
// Переменные уже должны быть определены!
for (size_t i = 0; i < countof(szNames); ++i)
{
LPCWSTR pszName = szNames[i];
wchar_t szDbg[MAX_PATH+1] = L"";
GetEnvironmentVariable(pszName, szDbg, countof(szDbg));
if (!*szDbg)
{
LogFunction(L"Variables must be set already!");
_ASSERTE(*szDbg && "Variables must be set already!");
break; // другие не проверять - лишние ассерты
}
}
#endif
// Если ничего похожего нет, то и не дергаться
wchar_t szFind[] = L"!ConEmu";
bool bExclSubst = (StrStrI(asCmd, szFind) != NULL);
if (!bExclSubst && (wcschr(asCmd, L'%') == NULL))
return NULL;
//_ASSERTE(FALSE && "Continue to ParseConEmuSubst");
wchar_t* pszCmdCopy = NULL;
if (bExclSubst)
{
wchar_t* pszCmdCopy = lstrdup(asCmd);
if (!pszCmdCopy)
return NULL; // Ошибка выделения памяти вообще-то
for (size_t i = 0; i < countof(szNames); ++i)
{
wchar_t szName[64]; swprintf_c(szName, L"!%s!", szNames[i]);
size_t iLen = lstrlen(szName);
wchar_t* pszStart = StrStrI(pszCmdCopy, szName);
if (!pszStart)
continue;
while (pszStart)
{
pszStart[0] = L'%';
pszStart[iLen-1] = L'%';
pszStart = StrStrI(pszStart+iLen, szName);
}
}
asCmd = pszCmdCopy;
}
wchar_t* pszExpand = ExpandEnvStr(pszCmdCopy ? pszCmdCopy : asCmd);
SafeFree(pszCmdCopy);
return pszExpand;
}
BOOL SetTitle(LPCWSTR lsTitle)
{
LogFunction(L"SetTitle");
LPCWSTR pszSetTitle = lsTitle ? lsTitle : L"";
#ifdef SHOW_SETCONTITLE_MSGBOX
MessageBox(NULL, pszSetTitle, WIN3264TEST(L"ConEmuCD - set title",L"ConEmuCD64 - set title"), MB_SYSTEMMODAL);
#endif
BOOL bRc = SetConsoleTitle(pszSetTitle);
if (gpLogSize)
{
wchar_t* pszLog = lstrmerge(bRc ? L"Done: " : L"Fail: ", pszSetTitle);
LogFunction(pszLog);
SafeFree(pszLog);
}
return bRc;
}
void UpdateConsoleTitle()
{
LogFunction(L"UpdateConsoleTitle");
CEStr szTemp;
wchar_t *pszBuffer = NULL;
LPCWSTR pszSetTitle = NULL, pszCopy;
LPCWSTR pszReq = gpszForcedTitle ? gpszForcedTitle : gpszRunCmd;
if (!pszReq || !*pszReq)
{
// Не должны сюда попадать - сброс заголовка не допустим
#ifdef _DEBUG
if (!(gbAttachMode & am_Modes))
{
_ASSERTE(pszReq && *pszReq);
}
#endif
return;
}
pszBuffer = ParseConEmuSubst(pszReq);
if (pszBuffer)
pszReq = pszBuffer;
pszCopy = pszReq;
if (!gpszForcedTitle && (NextArg(&pszCopy, szTemp) == 0))
{
wchar_t* pszName = (wchar_t*)PointToName(szTemp.ms_Val);
wchar_t* pszExt = (wchar_t*)PointToExt(pszName);
if (pszExt)
*pszExt = 0;
pszSetTitle = pszName;
}
else
{
pszSetTitle = pszReq;
}
// Need to change title? Do it.
if (pszSetTitle && *pszSetTitle)
{
#ifdef _DEBUG
int nLen = 4096; //GetWindowTextLength(ghConWnd); -- KIS2009 гундит "Посылка оконного сообщения"...
gpszPrevConTitle = (wchar_t*)calloc(nLen+1,2);
if (gpszPrevConTitle)
GetConsoleTitleW(gpszPrevConTitle, nLen+1);
#endif
SetTitle(pszSetTitle);
}
SafeFree(pszBuffer);
}
void CdToProfileDir()
{
BOOL bRc = FALSE;
wchar_t szPath[MAX_PATH] = L"";
HRESULT hr = SHGetFolderPath(NULL, CSIDL_PROFILE, NULL, 0, szPath);
if (FAILED(hr))
GetEnvironmentVariable(L"USERPROFILE", szPath, countof(szPath));
if (szPath[0])
bRc = SetCurrentDirectory(szPath);
// Write action to log file
if (gpLogSize)
{
wchar_t* pszMsg = lstrmerge(bRc ? L"Work dir changed to %USERPROFILE%: " : L"CD failed to %USERPROFILE%: ", szPath);
LogFunction(pszMsg);
SafeFree(pszMsg);
}
}
#ifndef WIN64
void CheckNeedSkipWowChange(LPCWSTR asCmdLine)
{
LogFunction(L"CheckNeedSkipWowChange");
// Команды вида: C:\Windows\SysNative\reg.exe Query "HKCU\Software\Far2"|find "Far"
// Для них нельзя отключать редиректор (wow.Disable()), иначе SysNative будет недоступен
if (IsWindows64())
{
LPCWSTR pszTest = asCmdLine;
CEStr szApp;
if (NextArg(&pszTest, szApp) == 0)
{
wchar_t szSysnative[MAX_PATH+32];
int nLen = GetWindowsDirectory(szSysnative, MAX_PATH);
if (nLen >= 2 && nLen < MAX_PATH)
{
AddEndSlash(szSysnative, countof(szSysnative));
wcscat_c(szSysnative, L"Sysnative\\");
nLen = lstrlenW(szSysnative);
int nAppLen = lstrlenW(szApp);
if (nAppLen > nLen)
{
szApp.ms_Val[nLen] = 0;
if (lstrcmpiW(szApp, szSysnative) == 0)
{
gbSkipWowChange = TRUE;
}
}
}
}
}
}
#endif
// When DefTerm debug console is started for Win32 app
// we need to allocate hidden console, and there is no
// active process, until parent DevEnv successfully starts
// new debugging process session
DWORD WaitForRootConsoleProcess(DWORD nTimeout)
{
if (pfnGetConsoleProcessList==NULL)
{
_ASSERTE(FALSE && "Attach to console app was requested, but required WinXP or higher!");
return 0;
}
_ASSERTE(gbCreatingHiddenConsole);
_ASSERTE(ghConWnd!=NULL);
DWORD nFoundPID = 0;
DWORD nStart = GetTickCount(), nDelta = 0;
DWORD nProcesses[20] = {}, nProcCount, i;
PROCESSENTRY32 pi = {};
GetProcessInfo(gnSelfPID, &pi);
while (!nFoundPID && (nDelta < nTimeout))
{
Sleep(50);
nProcCount = pfnGetConsoleProcessList(nProcesses, countof(nProcesses));
for (i = 0; i < nProcCount; i++)
{
DWORD nPID = nProcesses[i];
if (nPID && (nPID != gnSelfPID) && (nPID != pi.th32ParentProcessID))
{
nFoundPID = nPID;
break;
}
}
nDelta = (GetTickCount() - nStart);
}
if (!nFoundPID)
{
apiShowWindow(ghConWnd, SW_SHOWNORMAL);
_ASSERTE(FALSE && "Was unable to find starting process");
}
return nFoundPID;
}
void ApplyProcessSetEnvCmd()
{
#ifdef _DEBUG
CStartEnv::UnitTests();
#endif
if (gpSetEnv)
{
CStartEnv setEnv;
gpSetEnv->Apply(&setEnv);
}
}
// Lines come from Settings/Environment page
void ApplyEnvironmentCommands(LPCWSTR pszCommands)
{
if (!pszCommands || !*pszCommands)
{
_ASSERTE(pszCommands && *pszCommands);
return;
}
UINT nSetCP = 0; // Postponed
if (!gpSetEnv)
gpSetEnv = new CProcessEnvCmd();
// These must be applied before commands from CommandLine
gpSetEnv->AddLines(pszCommands, true);
}
// Allow smth like: ConEmuC -c {Far} /e text.txt
wchar_t* ExpandTaskCmd(LPCWSTR asCmdLine)
{
if (!ghConWnd)
{
_ASSERTE(ghConWnd);
return NULL;
}
if (!asCmdLine || (asCmdLine[0] != TaskBracketLeft))
{
_ASSERTE(asCmdLine && (asCmdLine[0] == TaskBracketLeft));
return NULL;
}
LPCWSTR pszNameEnd = wcschr(asCmdLine, TaskBracketRight);
if (!pszNameEnd)
return NULL;
pszNameEnd++;
size_t cchCount = (pszNameEnd - asCmdLine);
DWORD cbSize = sizeof(CESERVER_REQ_HDR) + sizeof(CESERVER_REQ_TASK) + cchCount*sizeof(asCmdLine[0]);
CESERVER_REQ* pIn = ExecuteNewCmd(CECMD_GETTASKCMD, cbSize);
if (!pIn)
return NULL;
wmemmove(pIn->GetTask.data, asCmdLine, cchCount);
_ASSERTE(pIn->GetTask.data[cchCount] == 0);
wchar_t* pszResult = NULL;
CESERVER_REQ* pOut = ExecuteGuiCmd(ghConWnd, pIn, ghConWnd);
if (pOut && (pOut->DataSize() > sizeof(pOut->GetTask)) && pOut->GetTask.data[0])
{
LPCWSTR pszTail = SkipNonPrintable(pszNameEnd);
pszResult = lstrmerge(pOut->GetTask.data, (pszTail && *pszTail) ? L" " : NULL, pszTail);
}
ExecuteFreeResult(pIn);
ExecuteFreeResult(pOut);
return pszResult;
}
// Parse ConEmuC command line switches
int ParseCommandLine(LPCWSTR asCmdLine)
{
int iRc = 0;
CEStr szArg;
CEStr szExeTest;
LPCWSTR pszArgStarts = NULL;
gbRunViaCmdExe = TRUE;
gbRootIsCmdExe = TRUE;
gbRunInBackgroundTab = FALSE;
size_t nCmdLine = 0;
LPCWSTR pwszStartCmdLine = asCmdLine;
LPCWSTR lsCmdLine = asCmdLine;
BOOL lbNeedCutStartEndQuot = FALSE;
bool lbNeedCdToProfileDir = false;
ConEmuStateCheck eStateCheck = ec_None;
ConEmuExecAction eExecAction = ea_None;
MacroInstance MacroInst = {}; // Special ConEmu instance for GUIMACRO and other options
if (!lsCmdLine || !*lsCmdLine)
{
DWORD dwErr = GetLastError();
_printf("GetCommandLineW failed! ErrCode=0x%08X\n", dwErr);
return CERR_GETCOMMANDLINE;
}
#ifdef _DEBUG
// Для отлова запуска дебаггера
//_ASSERTE(wcsstr(lsCmdLine, L"/DEBUGPID=")==0);
#endif
gnRunMode = RM_UNDEFINED;
BOOL lbAttachGuiApp = FALSE;
struct {
CEStr szConEmuAddArgs;
void Append(LPCWSTR asSwitch, LPCWSTR asValue)
{
lstrmerge(&szConEmuAddArgs.ms_Val, asSwitch);
if (asValue && *asValue)
{
bool needQuot = IsQuotationNeeded(asValue);
lstrmerge(&szConEmuAddArgs.ms_Val,
needQuot ? L" \"" : L" ",
asValue,
needQuot ? L"\"" : NULL);
}
SetEnvironmentVariable(ENV_CONEMU_EXEARGS_W, szConEmuAddArgs);
}
} AddArgs;
while ((iRc = NextArg(&lsCmdLine, szArg, &pszArgStarts)) == 0)
{
xf_check();
if ((szArg[0] == L'/' || szArg[0] == L'-')
&& (szArg[1] == L'?' || ((szArg[1] & ~0x20) == L'H'))
&& szArg[2] == 0)
{
Help();
return CERR_HELPREQUESTED;
}
// Following code wants '/'style arguments
// Change '-'style to '/'style
if (szArg[0] == L'-')
szArg.SetAt(0, L'/');
else if (szArg[0] != L'/')
continue;
#ifdef _DEBUG
if (lstrcmpi(szArg, L"/DEBUGTRAP")==0)
{
int i, j = 1; j--; i = 1 / j;
}
else
#endif
// **** Unit tests ****
if (lstrcmpi(szArg, L"/Args")==0 || lstrcmpi(szArg, L"/ParseArgs")==0)
{
eExecAction = ea_ParseArgs;
break;
}
else if (lstrcmpi(szArg, L"/ConInfo")==0)
{
eExecAction = ea_PrintConsoleInfo;
break;
}
else if (lstrcmpi(szArg, L"/CheckUnicode")==0)
{
eExecAction = ea_CheckUnicodeFont;
break;
}
else if (lstrcmpi(szArg, L"/TestUnicode")==0)
{
eExecAction = ea_TestUnicodeCvt;
break;
}
else if (lstrcmpi(szArg, L"/OsVerInfo")==0)
{
eExecAction = ea_OsVerInfo;
break;
}
else if (lstrcmpi(szArg, L"/ErrorLevel")==0)
{
eExecAction = ea_ErrorLevel;
break;
}
else if (lstrcmpi(szArg, L"/Result")==0)
{
gbPrintRetErrLevel = TRUE;
}
else if (lstrcmpi(szArg, L"/echo")==0 || lstrcmpi(szArg, L"/e")==0)
{
eExecAction = ea_OutEcho;
break;
}
else if (lstrcmpi(szArg, L"/type")==0 || lstrcmpi(szArg, L"/t")==0)
{
eExecAction = ea_OutType;
break;
}
// **** Regular use ****
else if (wcsncmp(szArg, L"/REGCONFONT=", 12)==0)
{
eExecAction = ea_RegConFont;
lsCmdLine = szArg.Mid(12);
break;
}
else if (wcsncmp(szArg, L"/SETHOOKS=", 10) == 0)
{
eExecAction = ea_InjectHooks;
lsCmdLine = szArg.Mid(10);
break;
}
else if (wcsncmp(szArg, L"/INJECT=", 8) == 0)
{
eExecAction = ea_InjectRemote;
lsCmdLine = szArg.Mid(8);
break;
}
else if (wcsncmp(szArg, L"/DEFTRM=", 8) == 0)
{
eExecAction = ea_InjectDefTrm;
lsCmdLine = szArg.Mid(8);
break;
}
// /GUIMACRO[:PID|HWND] <Macro string>
else if (lstrcmpni(szArg, L"/GUIMACRO", 9) == 0)
{
// Все что в lsCmdLine - выполнить в Gui
ArgGuiMacro(szArg, MacroInst);
eExecAction = ea_GuiMacro;
break;
}
else if (lstrcmpi(szArg, L"/STORECWD") == 0)
{
eExecAction = ea_StoreCWD;
break;
}
else if (lstrcmpi(szArg, L"/STRUCT") == 0)
{
eExecAction = ea_DumpStruct;
break;
}
else if (lstrcmpi(szArg, L"/SILENT")==0)
{
gbPreferSilentMode = true;
}
else if (lstrcmpi(szArg, L"/USEEXPORT")==0)
{
gbMacroExportResult = true;
}
else if (lstrcmpni(szArg, L"/EXPORT", 7)==0)
{
//_ASSERTE(FALSE && "Continue to export");
if (lstrcmpi(szArg, L"/EXPORT=ALL")==0 || lstrcmpi(szArg, L"/EXPORTALL")==0)
eExecAction = ea_ExportAll;
else if (lstrcmpi(szArg, L"/EXPORT=CON")==0 || lstrcmpi(szArg, L"/EXPORTCON")==0)
eExecAction = ea_ExportCon;
else if (lstrcmpi(szArg, L"/EXPORT=GUI")==0 || lstrcmpi(szArg, L"/EXPORTGUI")==0)
eExecAction = ea_ExportGui;
else
eExecAction = ea_ExportTab;
break;
}
else if (lstrcmpi(szArg, L"/IsConEmu")==0)
{
eStateCheck = ec_IsConEmu;
break;
}
else if (lstrcmpi(szArg, L"/IsTerm")==0)
{
eStateCheck = ec_IsTerm;
break;
}
else if (lstrcmpi(szArg, L"/IsAnsi")==0)
{
eStateCheck = ec_IsAnsi;
break;
}
else if (lstrcmpi(szArg, L"/IsAdmin")==0)
{
eStateCheck = ec_IsAdmin;
break;
}
else if (lstrcmpi(szArg, L"/IsRedirect")==0)
{
eStateCheck = ec_IsRedirect;
break;
}
else if ((wcscmp(szArg, L"/CONFIRM")==0)
|| (wcscmp(szArg, L"/CONFHALT")==0)
|| (wcscmp(szArg, L"/ECONFIRM")==0))
{
gnConfirmExitParm = (wcscmp(szArg, L"/CONFIRM")==0) ? RConStartArgs::eConfAlways
: (wcscmp(szArg, L"/CONFHALT")==0) ? RConStartArgs::eConfHalt
: RConStartArgs::eConfEmpty;
gbAlwaysConfirmExit = TRUE; gbAutoDisableConfirmExit = FALSE;
}
else if (wcscmp(szArg, L"/NOCONFIRM")==0)
{
gnConfirmExitParm = RConStartArgs::eConfNever;
gbAlwaysConfirmExit = FALSE; gbAutoDisableConfirmExit = FALSE;
}
else if (wcscmp(szArg, L"/OMITHOOKSWARN")==0)
{
gbSkipHookersCheck = true;
}
else if (wcscmp(szArg, L"/ADMIN")==0)
{
#if defined(SHOW_ATTACH_MSGBOX)
if (!IsDebuggerPresent())
{
wchar_t szTitle[100]; swprintf_c(szTitle, L"%s PID=%u /ADMIN", gsModuleName, gnSelfPID);
const wchar_t* pszCmdLine = GetCommandLineW();
MessageBox(NULL,pszCmdLine,szTitle,MB_SYSTEMMODAL);
}
#endif
gbAttachMode |= am_Admin;
gnRunMode = RM_SERVER;
}
else if (wcscmp(szArg, L"/ATTACH")==0)
{
#if defined(SHOW_ATTACH_MSGBOX)
if (!IsDebuggerPresent())
{
wchar_t szTitle[100]; swprintf_c(szTitle, L"%s PID=%u /ATTACH", gsModuleName, gnSelfPID);
const wchar_t* pszCmdLine = GetCommandLineW();
MessageBox(NULL,pszCmdLine,szTitle,MB_SYSTEMMODAL);
}
#endif
if (!(gbAttachMode & am_Modes))
gbAttachMode |= am_Simple;
gnRunMode = RM_SERVER;
}
else if ((lstrcmpi(szArg, L"/AUTOATTACH")==0) || (lstrcmpi(szArg, L"/ATTACHDEFTERM")==0))
{
#if defined(SHOW_ATTACH_MSGBOX)
if (!IsDebuggerPresent())
{
wchar_t szTitle[100]; swprintf_c(szTitle, L"%s PID=%u %s", gsModuleName, gnSelfPID, szArg.ms_Val);
const wchar_t* pszCmdLine = GetCommandLineW();
MessageBox(NULL,pszCmdLine,szTitle,MB_SYSTEMMODAL);
}
#endif
gbAttachMode |= am_Auto;
gbAlienMode = TRUE;
gbNoCreateProcess = TRUE;
if (lstrcmpi(szArg, L"/AUTOATTACH")==0)
{
gnRunMode = RM_AUTOATTACH;
gbAttachMode |= am_Async;
}
if (lstrcmpi(szArg, L"/ATTACHDEFTERM")==0)
{
gnRunMode = RM_SERVER;
gbAttachMode |= am_DefTerm;
}
// Еще может быть "/GHWND=NEW" но оно ниже. Там ставится "gpSrv->bRequestNewGuiWnd=TRUE"
//ConEmu autorun (c) Maximus5
//Starting "%ConEmuPath%" in "Attach" mode (NewWnd=%FORCE_NEW_WND%)
if (!IsAutoAttachAllowed())
{
if (ghConWnd && IsWindowVisible(ghConWnd))
{
_printf("AutoAttach was requested, but skipped\n");
}
DisableAutoConfirmExit();
//_ASSERTE(FALSE && "AutoAttach was called while Update process is in progress?");
return CERR_AUTOATTACH_NOT_ALLOWED;
}
}
else if (wcsncmp(szArg, L"/GUIATTACH=", 11)==0)
{
#if defined(SHOW_ATTACH_MSGBOX)
if (!IsDebuggerPresent())
{
wchar_t szTitle[100]; swprintf_c(szTitle, L"%s PID=%u /GUIATTACH", gsModuleName, gnSelfPID);
const wchar_t* pszCmdLine = GetCommandLineW();
MessageBox(NULL,pszCmdLine,szTitle,MB_SYSTEMMODAL);
}
#endif
if (!(gbAttachMode & am_Modes))
gbAttachMode |= am_Simple;
lbAttachGuiApp = TRUE;
wchar_t* pszEnd;
// suppress warning C4312 'type cast': conversion from 'unsigned long' to 'HWND' of greater size
HWND hAppWnd = (HWND)(UINT_PTR)wcstoul(szArg.Mid(11), &pszEnd, 16);
if (IsWindow(hAppWnd))
gpSrv->hRootProcessGui = hAppWnd;
gnRunMode = RM_SERVER;
}
else if (wcscmp(szArg, L"/NOCMD")==0)
{
gnRunMode = RM_SERVER;
gbNoCreateProcess = TRUE;
gbAlienMode = TRUE;
}
else if (wcsncmp(szArg, L"/PARENTFARPID=", 14)==0)
{
// Для режима RM_COMSPEC нужно будет сохранить "длинный вывод"
wchar_t* pszEnd = NULL, *pszStart;
pszStart = szArg.ms_Val+14;
gpSrv->dwParentFarPID = wcstoul(pszStart, &pszEnd, 10);
}
else if (wcscmp(szArg, L"/CREATECON")==0)
{
gbCreatingHiddenConsole = TRUE;
//_ASSERTE(FALSE && "Continue to create con");
}
else if (wcscmp(szArg, L"/ROOTEXE")==0)
{
if (0 == NextArg(&lsCmdLine, szArg))
gpszRootExe = lstrmerge(L"\"", szArg, L"\"");
}
else if (wcsncmp(szArg, L"/PID=", 5)==0 || wcsncmp(szArg, L"/TRMPID=", 8)==0
|| wcsncmp(szArg, L"/FARPID=", 8)==0 || wcsncmp(szArg, L"/CONPID=", 8)==0)
{
gnRunMode = RM_SERVER;
gbNoCreateProcess = TRUE; // Процесс УЖЕ запущен
gbAlienMode = TRUE; // Консоль создана НЕ нами
wchar_t* pszEnd = NULL, *pszStart;
if (wcsncmp(szArg, L"/TRMPID=", 8)==0)
{
// This is called from *.vshost.exe when "AllocConsole" just created
gbDefTermCall = TRUE;
gbDontInjectConEmuHk = TRUE;
pszStart = szArg.ms_Val+8;
}
else if (wcsncmp(szArg, L"/FARPID=", 8)==0)
{
gbAttachFromFar = TRUE;
gbRootIsCmdExe = FALSE;
pszStart = szArg.ms_Val+8;
}
else if (wcsncmp(szArg, L"/CONPID=", 8)==0)
{
//_ASSERTE(FALSE && "Continue to alternative attach mode");
gbAlternativeAttach = TRUE;
gbRootIsCmdExe = FALSE;
pszStart = szArg.ms_Val+8;
}
else
{
pszStart = szArg.ms_Val+5;
}
gpSrv->dwRootProcess = wcstoul(pszStart, &pszEnd, 10);
if ((gpSrv->dwRootProcess == 0) && gbCreatingHiddenConsole)
{
gpSrv->dwRootProcess = WaitForRootConsoleProcess(30000);
}
// --
//if (gpSrv->dwRootProcess)
//{
// _ASSERTE(gpSrv->hRootProcess==NULL); // Еще не должен был быть открыт
// gpSrv->hRootProcess = OpenProcess(MY_PROCESS_ALL_ACCESS, FALSE, gpSrv->dwRootProcess);
// if (gpSrv->hRootProcess == NULL)
// {
// gpSrv->hRootProcess = OpenProcess(SYNCHRONIZE|PROCESS_QUERY_INFORMATION, FALSE, gpSrv->dwRootProcess);
// }
//}
if (gbAlternativeAttach && gpSrv->dwRootProcess)
{
// Если процесс был запущен "с консольным окном"
if (ghConWnd)
{
#ifdef _DEBUG
SafeCloseHandle(ghFarInExecuteEvent);
#endif
}
BOOL bAttach = FALSE;
HMODULE hKernel = GetModuleHandle(L"kernel32.dll");
AttachConsole_t AttachConsole_f = hKernel ? (AttachConsole_t)GetProcAddress(hKernel,"AttachConsole") : NULL;
HWND hSaveCon = GetConsoleWindow();
RetryAttach:
if (AttachConsole_f)
{
// FreeConsole нужно дергать даже если ghConWnd уже NULL. Что-то в винде глючит и
// AttachConsole вернет ERROR_ACCESS_DENIED, если FreeConsole не звать...
FreeConsole();
ghConWnd = NULL;
// Issue 998: Need to wait, while real console will appear
// gpSrv->hRootProcess еще не открыт
HANDLE hProcess = OpenProcess(SYNCHRONIZE, FALSE, gpSrv->dwRootProcess);
while (hProcess && hProcess != INVALID_HANDLE_VALUE)
{
DWORD nConPid = 0;
HWND hNewCon = FindWindowEx(NULL, NULL, RealConsoleClass, NULL);
while (hNewCon)
{
if (GetWindowThreadProcessId(hNewCon, &nConPid) && (nConPid == gpSrv->dwRootProcess))
break;
hNewCon = FindWindowEx(NULL, hNewCon, RealConsoleClass, NULL);
}
if ((hNewCon != NULL) || (WaitForSingleObject(hProcess, 100) == WAIT_OBJECT_0))
break;
}
SafeCloseHandle(hProcess);
// Sometimes conhost handles are created with lags, wait for a while
DWORD nStartTick = GetTickCount();
const DWORD reattach_duration = 5000; // 5 sec
while (!bAttach)
{
bAttach = AttachConsole_f(gpSrv->dwRootProcess);
if (bAttach)
break;
Sleep(50);
DWORD nDelta = (GetTickCount() - nStartTick);
if (nDelta >= reattach_duration)
break;
LogString(L"Retrying AttachConsole after 50ms delay");
}
}
else
{
SetLastError(ERROR_PROC_NOT_FOUND);
}
if (!bAttach)
{
DWORD nErr = GetLastError();
size_t cchMsgMax = 10*MAX_PATH;
wchar_t* pszMsg = (wchar_t*)calloc(cchMsgMax,sizeof(*pszMsg));
wchar_t szTitle[MAX_PATH];
HWND hFindConWnd = FindWindowEx(NULL, NULL, RealConsoleClass, NULL);
DWORD nFindConPID = 0; if (hFindConWnd) GetWindowThreadProcessId(hFindConWnd, &nFindConPID);
PROCESSENTRY32 piCon = {}, piRoot = {};
GetProcessInfo(gpSrv->dwRootProcess, &piRoot);
if (nFindConPID == gpSrv->dwRootProcess)
piCon = piRoot;
else if (nFindConPID)
GetProcessInfo(nFindConPID, &piCon);
if (hFindConWnd)
GetWindowText(hFindConWnd, szTitle, countof(szTitle));
else
szTitle[0] = 0;
_wsprintf(pszMsg, SKIPLEN(cchMsgMax)
L"AttachConsole(PID=%u) failed, code=%u\n"
L"[%u]: %s\n"
L"Top console HWND=x%08X, PID=%u, %s\n%s\n---\n"
L"Prev (self) console HWND=x%08X\n\n"
L"Retry?",
gpSrv->dwRootProcess, nErr,
gpSrv->dwRootProcess, piRoot.szExeFile,
LODWORD(hFindConWnd), nFindConPID, piCon.szExeFile, szTitle,
LODWORD(hSaveCon)
);
swprintf_c(szTitle, L"%s: PID=%u", gsModuleName, GetCurrentProcessId());
int nBtn = MessageBox(NULL, pszMsg, szTitle, MB_ICONSTOP|MB_SYSTEMMODAL|MB_RETRYCANCEL);
free(pszMsg);
if (nBtn == IDRETRY)
{
goto RetryAttach;
}
gbInShutdown = TRUE;
gbAlwaysConfirmExit = FALSE;
LogString(L"CERR_CARGUMENT: (gbAlternativeAttach && gpSrv->dwRootProcess)");
return CERR_CARGUMENT;
}
ghConWnd = GetConEmuHWND(2);
gbVisibleOnStartup = IsWindowVisible(ghConWnd);
// Need to be set, because of new console === new handler
SetConsoleCtrlHandler((PHANDLER_ROUTINE)HandlerRoutine, true);
#ifdef _DEBUG
_ASSERTE(ghFarInExecuteEvent==NULL);
_ASSERTE(ghConWnd!=NULL);
#endif
}
else if (gpSrv->dwRootProcess == 0)
{
LogString("CERR_CARGUMENT: Attach to GUI was requested, but invalid PID specified");
_printf("Attach to GUI was requested, but invalid PID specified:\n");
_wprintf(GetCommandLineW());
_printf("\n");
_ASSERTE(FALSE && "Attach to GUI was requested, but invalid PID specified");
return CERR_CARGUMENT;
}
}
else if (wcsncmp(szArg, L"/CINMODE=", 9)==0)
{
wchar_t* pszEnd = NULL, *pszStart = szArg.ms_Val+9;
gnConsoleModeFlags = wcstoul(pszStart, &pszEnd, 16);
// если передан 0 - включится (ENABLE_QUICK_EDIT_MODE|ENABLE_EXTENDED_FLAGS|ENABLE_INSERT_MODE)
gbConsoleModeFlags = (gnConsoleModeFlags != 0);
}
else if (wcscmp(szArg, L"/HIDE")==0)
{
gbForceHideConWnd = TRUE;
}
else if (wcsncmp(szArg, L"/B", 2)==0)
{
wchar_t* pszEnd = NULL;
if (wcsncmp(szArg, L"/BW=", 4)==0)
{
gcrVisibleSize.X = /*_wtoi(szArg+4);*/(SHORT)wcstol(szArg.Mid(4),&pszEnd,10); gbParmVisibleSize = TRUE;
}
else if (wcsncmp(szArg, L"/BH=", 4)==0)
{
gcrVisibleSize.Y = /*_wtoi(szArg+4);*/(SHORT)wcstol(szArg.Mid(4),&pszEnd,10); gbParmVisibleSize = TRUE;
}
else if (wcsncmp(szArg, L"/BZ=", 4)==0)
{
gnBufferHeight = /*_wtoi(szArg+4);*/(SHORT)wcstol(szArg.Mid(4),&pszEnd,10); gbParmBufSize = TRUE;
}
TODO("/BX для ширины буфера?");
}
else if (wcsncmp(szArg, L"/F", 2)==0 && szArg[2] && szArg[3] == L'=')
{
wchar_t* pszEnd = NULL;
if (wcsncmp(szArg, L"/FN=", 4)==0) //-V112
{
lstrcpynW(gpSrv->szConsoleFont, szArg.Mid(4), 32); //-V112
}
else if (wcsncmp(szArg, L"/FW=", 4)==0) //-V112
{
gpSrv->nConFontWidth = /*_wtoi(szArg+4);*/(SHORT)wcstol(szArg.Mid(4),&pszEnd,10);
}
else if (wcsncmp(szArg, L"/FH=", 4)==0) //-V112
{
gpSrv->nConFontHeight = /*_wtoi(szArg+4);*/(SHORT)wcstol(szArg.Mid(4),&pszEnd,10);
//} else if (wcsncmp(szArg, L"/FF=", 4)==0) {
// lstrcpynW(gpSrv->szConsoleFontFile, szArg+4, MAX_PATH);
}
}
else if (lstrcmpni(szArg, L"/LOG", 4) == 0) //-V112
{
int nLevel = 0;
if (szArg[4]==L'1') nLevel = 1; else if (szArg[4]>=L'2') nLevel = 2;
CreateLogSizeFile(nLevel);
}
else if (wcsncmp(szArg, L"/GID=", 5)==0)
{
gnRunMode = RM_SERVER;
wchar_t* pszEnd = NULL;
gnConEmuPID = wcstoul(szArg.Mid(5), &pszEnd, 10);
if (gnConEmuPID == 0)
{
LogString(L"CERR_CARGUMENT: Invalid GUI PID specified");
_printf("Invalid GUI PID specified:\n");
_wprintf(GetCommandLineW());
_printf("\n");
_ASSERTE(FALSE);
return CERR_CARGUMENT;
}
}
else if (wcsncmp(szArg, L"/AID=", 5)==0)
{
wchar_t* pszEnd = NULL;
gpSrv->dwGuiAID = wcstoul(szArg.Mid(5), &pszEnd, 10);
}
else if (wcsncmp(szArg, L"/GHWND=", 7)==0)
{
if (gnRunMode == RM_UNDEFINED)
{
gnRunMode = RM_SERVER;
}
else
{
_ASSERTE(gnRunMode == RM_AUTOATTACH || gnRunMode == RM_SERVER || gnRunMode == RM_ALTSERVER);
}
wchar_t* pszEnd = NULL;
if (lstrcmpi(szArg.Mid(7), L"NEW") == 0)
{
gpSrv->hGuiWnd = NULL;
_ASSERTE(gnConEmuPID == 0);
gnConEmuPID = 0;
gpSrv->bRequestNewGuiWnd = TRUE;
}
else
{
wchar_t szLog[120];
LPCWSTR pszDescr = szArg.Mid(7);
if (pszDescr[0] == L'0' && (pszDescr[1] == L'x' || pszDescr[1] == L'X'))
pszDescr += 2; // That may be useful for calling from batch files
gpSrv->hGuiWnd = (HWND)(UINT_PTR)wcstoul(pszDescr, &pszEnd, 16);
gpSrv->bRequestNewGuiWnd = FALSE;
BOOL isWnd = gpSrv->hGuiWnd ? IsWindow(gpSrv->hGuiWnd) : FALSE;
DWORD nErr = gpSrv->hGuiWnd ? GetLastError() : 0;
swprintf_c(szLog, L"GUI HWND=0x%08X, %s, ErrCode=%u", LODWORD(gpSrv->hGuiWnd), isWnd ? L"Valid" : L"Invalid", nErr);
LogString(szLog);
if (!isWnd)
{
LogString(L"CERR_CARGUMENT: Invalid GUI HWND was specified in /GHWND arg");
_printf("Invalid GUI HWND specified: ");
_wprintf(szArg);
_printf("\n" "Command line:\n");
_wprintf(GetCommandLineW());
_printf("\n");
_ASSERTE(FALSE && "Invalid window was specified in /GHWND arg");
return CERR_CARGUMENT;
}
DWORD nPID = 0;
GetWindowThreadProcessId(gpSrv->hGuiWnd, &nPID);
_ASSERTE(gnConEmuPID == 0 || gnConEmuPID == nPID);
gnConEmuPID = nPID;
}
}
else if (wcsncmp(szArg, L"/TA=", 4)==0)
{
wchar_t* pszEnd = NULL;
DWORD nColors = wcstoul(szArg.Mid(4), &pszEnd, 16);
if (nColors)
{
DWORD nTextIdx = (nColors & 0xFF);
DWORD nBackIdx = ((nColors >> 8) & 0xFF);
DWORD nPopTextIdx = ((nColors >> 16) & 0xFF);
DWORD nPopBackIdx = ((nColors >> 24) & 0xFF);
if ((nTextIdx <= 15) && (nBackIdx <= 15) && (nTextIdx != nBackIdx))
gnDefTextColors = MAKECONCOLOR(nTextIdx, nBackIdx);
if ((nPopTextIdx <= 15) && (nPopBackIdx <= 15) && (nPopTextIdx != nPopBackIdx))
gnDefPopupColors = MAKECONCOLOR(nPopTextIdx, nPopBackIdx);
HANDLE hConOut = ghConOut;
CONSOLE_SCREEN_BUFFER_INFO csbi5 = {};
GetConsoleScreenBufferInfo(hConOut, &csbi5);
if (gnDefTextColors || gnDefPopupColors)
{
BOOL bPassed = FALSE;
if (gnDefPopupColors && (gnOsVer >= 0x600))
{
MY_CONSOLE_SCREEN_BUFFER_INFOEX csbi = {sizeof(csbi)};
if (apiGetConsoleScreenBufferInfoEx(hConOut, &csbi))
{
// Microsoft bug? When console is started elevated - it does NOT show
// required attributes, BUT GetConsoleScreenBufferInfoEx returns them.
if (!(gbAttachMode & am_Admin)
&& (!gnDefTextColors || (csbi.wAttributes = gnDefTextColors))
&& (!gnDefPopupColors || (csbi.wPopupAttributes = gnDefPopupColors)))
{
bPassed = TRUE; // Менять не нужно, консоль соответствует
}
else
{
if (gnDefTextColors)
csbi.wAttributes = gnDefTextColors;
if (gnDefPopupColors)
csbi.wPopupAttributes = gnDefPopupColors;
_ASSERTE(FALSE && "Continue to SetConsoleScreenBufferInfoEx");
// Vista/Win7. _SetConsoleScreenBufferInfoEx unexpectedly SHOWS console window
//if (gnOsVer == 0x0601)
//{
// RECT rcGui = {};
// if (gpSrv->hGuiWnd)
// GetWindowRect(gpSrv->hGuiWnd, &rcGui);
// //SetWindowPos(ghConWnd, HWND_BOTTOM, rcGui.left+3, rcGui.top+3, 0,0, SWP_NOSIZE|SWP_SHOWWINDOW|SWP_NOZORDER);
// SetWindowPos(ghConWnd, NULL, -30000, -30000, 0,0, SWP_NOSIZE|SWP_SHOWWINDOW|SWP_NOZORDER);
// apiShowWindow(ghConWnd, SW_SHOWMINNOACTIVE);
// #ifdef _DEBUG
// apiShowWindow(ghConWnd, SW_SHOWNORMAL);
// apiShowWindow(ghConWnd, SW_HIDE);
// #endif
//}
bPassed = apiSetConsoleScreenBufferInfoEx(hConOut, &csbi);
// Что-то Win7 хулиганит
if (!gbVisibleOnStartup)
{
apiShowWindow(ghConWnd, SW_HIDE);
}
}
}
}
if (!bPassed && gnDefTextColors)
{
SetConsoleTextAttribute(hConOut, gnDefTextColors);
RefillConsoleAttributes(csbi5, csbi5.wAttributes, gnDefTextColors);
}
}
}
}
else if (lstrcmpni(szArg, L"/DEBUGPID=", 10)==0)
{
//gnRunMode = RM_SERVER; -- не будем ставить, RM_UNDEFINED будет признаком того, что просто хотят дебаггер
gbNoCreateProcess = TRUE;
gpSrv->DbgInfo.bDebugProcess = TRUE;
gpSrv->DbgInfo.bDebugProcessTree = FALSE;
wchar_t* pszEnd = NULL;
gpSrv->dwRootProcess = wcstoul(szArg.Mid(10), &pszEnd, 10);
if (gpSrv->dwRootProcess == 0)
{
LogString(L"CERR_CARGUMENT: Debug of process was requested, but invalid PID specified");
_printf("Debug of process was requested, but invalid PID specified:\n");
_wprintf(GetCommandLineW());
_printf("\n");
_ASSERTE(FALSE);
return CERR_CARGUMENT;
}
// "Comma" is a mark that debug/dump was requested for a bunch of processes
if (pszEnd && (*pszEnd == L','))
{
gpSrv->DbgInfo.bDebugMultiProcess = TRUE;
gpSrv->DbgInfo.pDebugAttachProcesses = new MArray<DWORD>;
while (pszEnd && (*pszEnd == L',') && *(pszEnd+1))
{
DWORD nPID = wcstoul(pszEnd+1, &pszEnd, 10);
if (nPID != 0)
gpSrv->DbgInfo.pDebugAttachProcesses->push_back(nPID);
}
}
}
else if (lstrcmpi(szArg, L"/DEBUGEXE")==0 || lstrcmpi(szArg, L"/DEBUGTREE")==0)
{
//gnRunMode = RM_SERVER; -- не будем ставить, RM_UNDEFINED будет признаком того, что просто хотят дебаггер
_ASSERTE(gpSrv->DbgInfo.bDebugProcess==FALSE);
gbNoCreateProcess = TRUE;
gpSrv->DbgInfo.bDebugProcess = TRUE;
gpSrv->DbgInfo.bDebugProcessTree = (lstrcmpi(szArg, L"/DEBUGTREE")==0);
wchar_t* pszLine = lstrdup(GetCommandLineW());
if (!pszLine || !*pszLine)
{
LogString(L"CERR_CARGUMENT: Debug of process was requested, but GetCommandLineW failed");
_printf("Debug of process was requested, but GetCommandLineW failed\n");
_ASSERTE(FALSE);
return CERR_CARGUMENT;
}
LPWSTR pszDebugCmd = wcsstr(pszLine, szArg);
if (pszDebugCmd)
{
pszDebugCmd = (LPWSTR)SkipNonPrintable(pszDebugCmd + lstrlen(szArg));
}
if (!pszDebugCmd || !*pszDebugCmd)
{
LogString(L"CERR_CARGUMENT: Debug of process was requested, but command was not found");
_printf("Debug of process was requested, but command was not found\n");
_ASSERTE(FALSE);
return CERR_CARGUMENT;
}
gpSrv->DbgInfo.pszDebuggingCmdLine = pszDebugCmd;
break;
}
else if (lstrcmpi(szArg, L"/DUMP")==0)
{
gpSrv->DbgInfo.nDebugDumpProcess = 1;
}
else if (lstrcmpi(szArg, L"/MINIDUMP")==0 || lstrcmpi(szArg, L"/MINI")==0)
{
gpSrv->DbgInfo.nDebugDumpProcess = 2;
}
else if (lstrcmpi(szArg, L"/FULLDUMP")==0 || lstrcmpi(szArg, L"/FULL")==0)
{
gpSrv->DbgInfo.nDebugDumpProcess = 3;
}
else if (lstrcmpi(szArg, L"/AUTOMINI")==0)
{
//_ASSERTE(FALSE && "Continue to /AUTOMINI");
gpSrv->DbgInfo.nDebugDumpProcess = 0;
gpSrv->DbgInfo.bAutoDump = TRUE;
gpSrv->DbgInfo.nAutoInterval = 1000;
if (lsCmdLine && *lsCmdLine && isDigit(lsCmdLine[0])
&& (NextArg(&lsCmdLine, szArg, &pszArgStarts) == 0))
{
wchar_t* pszEnd;
DWORD nVal = wcstol(szArg, &pszEnd, 10);
if (nVal)
{
if (pszEnd && *pszEnd)
{
if (lstrcmpni(pszEnd, L"ms", 2) == 0)
{
// Already milliseconds
pszEnd += 2;
}
else if (lstrcmpni(pszEnd, L"s", 1) == 0)
{
nVal *= 60; // seconds
pszEnd++;
}
else if (lstrcmpni(pszEnd, L"m", 2) == 0)
{
nVal *= 60*60; // minutes
pszEnd++;
}
}
gpSrv->DbgInfo.nAutoInterval = nVal;
}
}
}
else if (lstrcmpi(szArg, L"/PROFILECD")==0)
{
lbNeedCdToProfileDir = true;
}
else if (lstrcmpi(szArg, L"/CONFIG")==0)
{
if ((iRc = NextArg(&lsCmdLine, szArg)) != 0)
{
_ASSERTE(FALSE && "Config name was not specified!");
_wprintf(L"Config name was not specified!\r\n");
break;
}
// Reuse config if starting "ConEmu.exe" from console server!
SetEnvironmentVariable(ENV_CONEMU_CONFIG_W, szArg);
AddArgs.Append(L"-config", szArg);
}
else if (lstrcmpi(szArg, L"/LoadCfgFile")==0)
{
// Reuse specified xml file if starting "ConEmu.exe" from console server!
#ifdef SHOW_LOADCFGFILE_MSGBOX
MessageBox(NULL, lsCmdLine, L"/LoadCfgFile", MB_SYSTEMMODAL);
#endif
if ((iRc = NextArg(&lsCmdLine, szArg)) != 0)
{
_ASSERTE(FALSE && "Xml file name was not specified!");
_wprintf(L"Xml file name was not specified!\r\n");
break;
}
AddArgs.Append(L"-LoadCfgFile", szArg);
}
else if (lstrcmpi(szArg, L"/ASYNC") == 0 || lstrcmpi(szArg, L"/FORK") == 0)
{
gbAsyncRun = TRUE;
}
else if (lstrcmpi(szArg, L"/NOINJECT")==0)
{
gbDontInjectConEmuHk = TRUE;
}
else if (lstrcmpi(szArg, L"/DOSBOX")==0)
{
gbUseDosBox = TRUE;
}
// После этих аргументов - идет то, что передается в CreateProcess!
else if (lstrcmpi(szArg, L"/ROOT")==0)
{
#ifdef SHOW_SERVER_STARTED_MSGBOX
ShowServerStartedMsgBox(asCmdLine);
#endif
gnRunMode = RM_SERVER; gbNoCreateProcess = FALSE;
gbAsyncRun = FALSE;
SetWorkEnvVar();
break; // lsCmdLine уже указывает на запускаемую программу
}
// После этих аргументов - идет то, что передается в COMSPEC (CreateProcess)!
//if (wcscmp(szArg, L"/C")==0 || wcscmp(szArg, L"/c")==0 || wcscmp(szArg, L"/K")==0 || wcscmp(szArg, L"/k")==0) {
else if (szArg[0] == L'/' && (((szArg[1] & ~0x20) == L'C') || ((szArg[1] & ~0x20) == L'K')))
{
gbNoCreateProcess = FALSE;
if (szArg[2] == 0) // "/c" или "/k"
gnRunMode = RM_COMSPEC;
if (gnRunMode == RM_UNDEFINED && szArg[4] == 0
&& ((szArg[2] & ~0x20) == L'M') && ((szArg[3] & ~0x20) == L'D'))
{
_ASSERTE(FALSE && "'/cmd' obsolete switch. use /c, /k, /root");
gnRunMode = RM_SERVER;
}
// Если тип работа до сих пор не определили - считаем что режим ComSpec
// и команда начинается сразу после /c (может быть "cmd /cecho xxx")
if (gnRunMode == RM_UNDEFINED)
{
gnRunMode = RM_COMSPEC;
// Поддержка возможности "cmd /cecho xxx"
lsCmdLine = SkipNonPrintable(pszArgStarts + 2);
}
if (gnRunMode == RM_COMSPEC)
{
gpSrv->bK = (szArg[1] & ~0x20) == L'K';
}
if (lsCmdLine && (lsCmdLine[0] == TaskBracketLeft) && wcschr(lsCmdLine, TaskBracketRight))
{
// Allow smth like: ConEmuC -c {Far} /e text.txt
gpszTaskCmd = ExpandTaskCmd(lsCmdLine);
if (gpszTaskCmd && *gpszTaskCmd)
lsCmdLine = gpszTaskCmd;
}
break; // lsCmdLine уже указывает на запускаемую программу
}
else
{
_ASSERTE(FALSE && "Unknown switch!");
_wprintf(L"Unknown switch: ");
_wprintf(szArg);
_wprintf(L"\r\n");
}
}
LogFunction(L"ParseCommandLine{in-progress}");
// Switch "/PROFILECD" used when server to be started under different credentials as GUI.
// So, we need to do "cd %USERPROFILE%" which is more suitable to user.
if (lbNeedCdToProfileDir)
{
CdToProfileDir();
}
// Some checks or actions
if (eStateCheck || eExecAction)
{
int iFRc = CERR_CARGUMENT;
if (eStateCheck)
{
bool bOn = DoStateCheck(eStateCheck);
iFRc = bOn ? CERR_CHKSTATE_ON : CERR_CHKSTATE_OFF;
}
else if (eExecAction)
{
iFRc = DoExecAction(eExecAction, lsCmdLine, MacroInst);
}
// И сразу на выход
gbInShutdown = TRUE;
return iFRc;
}
if ((gbAttachMode & am_DefTerm) && !gbParmVisibleSize)
{
// To avoid "small" and trimmed text after starting console
_ASSERTE(gcrVisibleSize.X==80 && gcrVisibleSize.Y==25);
gbParmVisibleSize = TRUE;
}
// Параметры из комстроки разобраны. Здесь могут уже быть известны
// gpSrv->hGuiWnd {/GHWND}, gnConEmuPID {/GPID}, gpSrv->dwGuiAID {/AID}
// gbAttachMode для ключей {/ADMIN}, {/ATTACH}, {/AUTOATTACH}, {/GUIATTACH}
// В принципе, gbAttachMode включается и при "/ADMIN", но при запуске из ConEmu такого быть не может,
// будут установлены и gpSrv->hGuiWnd, и gnConEmuPID
// Issue 364, например, идет билд в VS, запускается CustomStep, в этот момент автоаттач нафиг не нужен
// Теоретически, в Студии не должно бы быть запуска ConEmuC.exe, но он может оказаться в "COMSPEC", так что проверим.
if (gbAttachMode
&& ((gnRunMode == RM_SERVER) || (gnRunMode == RM_AUTOATTACH))
&& (gnConEmuPID == 0))
{
//-- ассерт не нужен вроде
//_ASSERTE(!gbAlternativeAttach && "Alternative mode must be already processed!");
BOOL lbIsWindowVisible = FALSE;
// Добавим проверку на telnet
if (!ghConWnd
|| !(lbIsWindowVisible = IsAutoAttachAllowed())
|| isTerminalMode())
{
if (gpLogSize)
{
if (!ghConWnd) { LogFunction(L"!ghConWnd"); }
else if (!lbIsWindowVisible) { LogFunction(L"!IsAutoAttachAllowed"); }
else { LogFunction(L"isTerminalMode"); }
}
// Но это может быть все-таки наше окошко. Как проверить...
// Найдем первый параметр
LPCWSTR pszSlash = lsCmdLine ? wcschr(lsCmdLine, L'/') : NULL;
if (pszSlash)
{
LogFunction(pszSlash);
// И сравним с используемыми у нас. Возможно потом еще что-то добавить придется
if (wmemcmp(pszSlash, L"/DEBUGPID=", 10) != 0)
pszSlash = NULL;
}
if (pszSlash == NULL)
{
// Не наше окошко, выходим
gbInShutdown = TRUE;
return CERR_ATTACH_NO_CONWND;
}
}
if (!gbAlternativeAttach && !(gbAttachMode & am_DefTerm) && !gpSrv->dwRootProcess)
{
// В принципе, сюда мы можем попасть при запуске, например: "ConEmuC.exe /ADMIN /ROOT cmd"
// Но только не при запуске "из ConEmu" (т.к. будут установлены gpSrv->hGuiWnd, gnConEmuPID)
// Из батника убрал, покажем инфу тут
PrintVersion();
char szAutoRunMsg[128];
sprintf_c(szAutoRunMsg, "Starting attach autorun (NewWnd=%s)\n", gpSrv->bRequestNewGuiWnd ? "YES" : "NO");
_printf(szAutoRunMsg);
}
}
xf_check();
// Debugger or minidump requested?
// Switches ‘/DEBUGPID=PID1[,PID2[...]]’ to debug already running process
// or ‘/DEBUGEXE <your command line>’ or ‘/DEBUGTREE <your command line>’
// to start new process and debug it (and its children if ‘/DEBUGTREE’)
if (gpSrv->DbgInfo.bDebugProcess)
{
_ASSERTE(gnRunMode == RM_UNDEFINED);
// Run debugger thread and wait for its completion
int iDbgRc = RunDebugger();
return iDbgRc;
}
// Validate Сonsole (find it may be) or ChildGui process we need to attach into ConEmu window
if (((gnRunMode == RM_SERVER) || (gnRunMode == RM_AUTOATTACH))
&& (gbNoCreateProcess && gbAttachMode))
{
// Проверить процессы в консоли, подобрать тот, который будем считать "корневым"
int nChk = CheckAttachProcess();
if (nChk != 0)
return nChk;
gpszRunCmd = (wchar_t*)calloc(1,2);
if (!gpszRunCmd)
{
_printf("Can't allocate 1 wchar!\n");
return CERR_NOTENOUGHMEM1;
}
gpszRunCmd[0] = 0;
return 0;
}
xf_check();
// iRc is result of our ‘NextArg(&lsCmdLine,...)’
if (iRc != 0)
{
if (iRc == CERR_CMDLINEEMPTY)
{
Help();
_printf("\n\nParsing command line failed (/C argument not found):\n");
_wprintf(GetCommandLineW());
_printf("\n");
}
else
{
_printf("Parsing command line failed:\n");
_wprintf(asCmdLine);
_printf("\n");
}
return iRc;
}
if (gnRunMode == RM_UNDEFINED)
{
LogString(L"CERR_CARGUMENT: Parsing command line failed (/C argument not found)");
_printf("Parsing command line failed (/C argument not found):\n");
_wprintf(GetCommandLineW());
_printf("\n");
_ASSERTE(FALSE);
return CERR_CARGUMENT;
}
xf_check();
// Prepare our environment and GUI window
if (gnRunMode == RM_SERVER)
{
// We need to reserve or start new ConEmu tab/window...
// Если уже известен HWND ConEmu (root window)
if (gpSrv->hGuiWnd)
{
DWORD nGuiPID = 0; GetWindowThreadProcessId(gpSrv->hGuiWnd, &nGuiPID);
DWORD nWrongValue = 0;
SetLastError(0);
LGSResult lgsRc = ReloadGuiSettings(NULL, &nWrongValue);
if (lgsRc < lgs_Succeeded)
{
wchar_t szLgsError[200], szLGS[80];
swprintf_c(szLGS, L"LGS=%u, Code=%u, GUI PID=%u, Srv PID=%u", lgsRc, GetLastError(), nGuiPID, GetCurrentProcessId());
switch (lgsRc)
{
case lgs_WrongVersion:
swprintf_c(szLgsError, L"Failed to load ConEmu info!\n"
L"Found ProtocolVer=%u but Required=%u.\n"
L"%s.\n"
L"Please update all ConEmu components!",
nWrongValue, (DWORD)CESERVER_REQ_VER, szLGS);
break;
case lgs_WrongSize:
swprintf_c(szLgsError, L"Failed to load ConEmu info!\n"
L"Found MapSize=%u but Required=%u."
L"%s.\n"
L"Please update all ConEmu components!",
nWrongValue, (DWORD)sizeof(ConEmuGuiMapping), szLGS);
break;
default:
swprintf_c(szLgsError, L"Failed to load ConEmu info!\n"
L"%s.\n"
L"Please update all ConEmu components!",
szLGS);
}
// Add log info
LogFunction(szLGS);
// Show user message
wchar_t szTitle[128];
swprintf_c(szTitle, L"ConEmuC[Srv]: PID=%u", GetCurrentProcessId());
MessageBox(NULL, szLgsError, szTitle, MB_ICONSTOP|MB_SYSTEMMODAL);
return CERR_WRONG_GUI_VERSION;
}
}
}
xf_check();
if (gnRunMode == RM_COMSPEC)
{
// New console was requested?
if (IsNewConsoleArg(lsCmdLine))
{
HWND hConWnd = ghConWnd, hConEmu = ghConEmuWnd;
if (!hConWnd)
{
// This may be ConEmuC started from WSL or connector
CEStr guiPid(GetEnvVar(ENV_CONEMUPID_VAR_W));
CEStr srvPid(GetEnvVar(ENV_CONEMUSERVERPID_VAR_W));
if (guiPid && srvPid)
{
DWORD GuiPID = wcstoul(guiPid, NULL, 10);
DWORD SrvPID = wcstoul(srvPid, NULL, 10);
ConEmuGuiMapping GuiMapping = {sizeof(GuiMapping)};
if (GuiPID && LoadGuiMapping(GuiPID, GuiMapping))
{
for (size_t i = 0; i < countof(GuiMapping.Consoles); ++i)
{
if (GuiMapping.Consoles[i].ServerPID == SrvPID)
{
hConWnd = GuiMapping.Consoles[i].Console;
hConEmu = GuiMapping.hGuiWnd;
break;
}
}
}
}
}
if (!hConWnd)
{
// Executed outside of ConEmu, impossible to continue
_ASSERTE(hConWnd != NULL);
}
else
{
xf_check();
// тогда обрабатываем
gpSrv->bNewConsole = TRUE;
// По идее, должен запускаться в табе ConEmu (в существующей консоли), но если нет
if (!hConEmu || !IsWindow(hConEmu))
{
// попытаться найти открытый ConEmu
hConEmu = FindWindowEx(NULL, NULL, VirtualConsoleClassMain, NULL);
if (hConEmu)
gbNonGuiMode = TRUE; // Чтобы не пытаться выполнить SendStopped (ибо некому)
}
int iNewConRc = CERR_RUNNEWCONSOLE;
// Query current environment
CEnvStrings strs(GetEnvironmentStringsW());
DWORD nCmdLen = lstrlen(lsCmdLine)+1;
CESERVER_REQ* pIn = ExecuteNewCmd(CECMD_NEWCMD, sizeof(CESERVER_REQ_HDR)+sizeof(CESERVER_REQ_NEWCMD)+((nCmdLen+strs.mcch_Length)*sizeof(wchar_t)));
if (pIn)
{
pIn->NewCmd.hFromConWnd = hConWnd;
// hConWnd may differ from parent process, but ENV_CONEMUDRAW_VAR_W would be inherited
wchar_t* pszDcWnd = GetEnvVar(ENV_CONEMUDRAW_VAR_W);
if (pszDcWnd && (pszDcWnd[0] == L'0') && (pszDcWnd[1] == L'x'))
{
wchar_t* pszEnd = NULL;
pIn->NewCmd.hFromDcWnd.u = wcstoul(pszDcWnd+2, &pszEnd, 16);
}
SafeFree(pszDcWnd);
GetCurrentDirectory(countof(pIn->NewCmd.szCurDir), pIn->NewCmd.szCurDir);
pIn->NewCmd.SetCommand(lsCmdLine);
pIn->NewCmd.SetEnvStrings(strs.ms_Strings, strs.mcch_Length);
CESERVER_REQ* pOut = ExecuteGuiCmd(hConEmu, pIn, hConWnd);
if (pOut)
{
if (pOut->hdr.cbSize <= sizeof(pOut->hdr) || pOut->Data[0] == FALSE)
{
iNewConRc = CERR_RUNNEWCONSOLEFAILED;
}
ExecuteFreeResult(pOut);
}
else
{
_ASSERTE(pOut!=NULL);
iNewConRc = CERR_RUNNEWCONSOLEFAILED;
}
ExecuteFreeResult(pIn);
}
else
{
iNewConRc = CERR_NOTENOUGHMEM1;
}
DisableAutoConfirmExit();
return iNewConRc;
}
}
//pwszCopy = lsCmdLine;
//if ((iRc = NextArg(&pwszCopy, szArg)) != 0) {
// wprintf (L"Parsing command line failed:\n%s\n", lsCmdLine);
// return iRc;
//}
//pwszCopy = wcsrchr(szArg, L'\\'); if (!pwszCopy) pwszCopy = szArg;
//#pragma warning( push )
//#pragma warning(disable : 6400)
//if (lstrcmpiW(pwszCopy, L"cmd")==0 || lstrcmpiW(pwszCopy, L"cmd.exe")==0) {
// gbRunViaCmdExe = FALSE; // уже указан командный процессор, cmd.exe в начало добавлять не нужно
//}
//#pragma warning( pop )
//} else {
// gbRunViaCmdExe = FALSE; // командным процессором выступает сам ConEmuC (серверный режим)
}
LPCWSTR pszArguments4EnvVar = NULL;
if (gnRunMode == RM_COMSPEC && (!lsCmdLine || !*lsCmdLine))
{
if (gpSrv->bK)
{
gbRunViaCmdExe = TRUE;
}
else
{
// В фаре могут повесить пустую ассоциацию на маску
// *.ini -> "@" - тогда фар как бы ничего не делает при запуске этого файла, но ComSpec зовет...
gbNonGuiMode = TRUE;
DisableAutoConfirmExit();
return CERR_EMPTY_COMSPEC_CMDLINE;
}
}
else
{
BOOL bAlwaysConfirmExit = gbAlwaysConfirmExit, bAutoDisableConfirmExit = gbAutoDisableConfirmExit;
if (gnRunMode == RM_SERVER)
{
LogFunction(L"ProcessSetEnvCmd {set, title, chcp, etc.}");
// Console may be started as follows:
// "set PATH=C:\Program Files;%PATH%" & ... & cmd
// Supported commands:
// set abc=val
// "set PATH=C:\Program Files;%PATH%"
// chcp [utf8|ansi|oem|<cp_no>]
// title "Console init title"
if (!gpSetEnv)
gpSetEnv = new CProcessEnvCmd();
CStartEnvTitle setTitleVar(&gpszForcedTitle);
ProcessSetEnvCmd(lsCmdLine, gpSetEnv, &setTitleVar);
}
gpszCheck4NeedCmd = lsCmdLine; // Для отладки
gbRunViaCmdExe = IsNeedCmd((gnRunMode == RM_SERVER), lsCmdLine, szExeTest,
&pszArguments4EnvVar, &lbNeedCutStartEndQuot, &gbRootIsCmdExe, &bAlwaysConfirmExit, &bAutoDisableConfirmExit);
if (gnConfirmExitParm == 0)
{
gbAlwaysConfirmExit = bAlwaysConfirmExit;
gbAutoDisableConfirmExit = bAutoDisableConfirmExit;
}
}
#ifndef WIN64
// Команды вида: C:\Windows\SysNative\reg.exe Query "HKCU\Software\Far2"|find "Far"
// Для них нельзя отключать редиректор (wow.Disable()), иначе SysNative будет недоступен
CheckNeedSkipWowChange(lsCmdLine);
#endif
nCmdLine = lstrlenW(lsCmdLine);
if (!gbRunViaCmdExe)
{
nCmdLine += 1; // только место под 0
if (pszArguments4EnvVar && *szExeTest)
nCmdLine += lstrlen(szExeTest)+3;
}
else
{
gszComSpec[0] = 0;
if (!GetEnvironmentVariable(L"ComSpec", gszComSpec, MAX_PATH) || gszComSpec[0] == 0)
gszComSpec[0] = 0;
// ComSpec/ComSpecC не определен, используем cmd.exe
if (gszComSpec[0] == 0)
{
LPCWSTR pszFind = GetComspecFromEnvVar(gszComSpec, countof(gszComSpec));
if (!pszFind || !wcschr(pszFind, L'\\') || !FileExists(pszFind))
{
_ASSERTE("cmd.exe not found!");
_printf("Can't find cmd.exe!\n");
return CERR_CMDEXENOTFOUND;
}
}
nCmdLine += lstrlenW(gszComSpec)+15; // "/C", кавычки и возможный "/U"
}
size_t nCchLen = nCmdLine+1; // nCmdLine учитывает длину lsCmdLine + gszComSpec + еще чуть-чуть на "/C" и прочее
gpszRunCmd = (wchar_t*)calloc(nCchLen,sizeof(wchar_t));
if (!gpszRunCmd)
{
_printf("Can't allocate %i wchars!\n", (DWORD)nCmdLine);
return CERR_NOTENOUGHMEM1;
}
// это нужно для смены заголовка консоли. при необходимости COMSPEC впишем ниже, после смены
if (pszArguments4EnvVar && *szExeTest && !gbRunViaCmdExe)
{
gpszRunCmd[0] = L'"';
_wcscat_c(gpszRunCmd, nCchLen, szExeTest);
if (*pszArguments4EnvVar)
{
_wcscat_c(gpszRunCmd, nCchLen, L"\" ");
_wcscat_c(gpszRunCmd, nCchLen, pszArguments4EnvVar);
}
else
{
_wcscat_c(gpszRunCmd, nCchLen, L"\"");
}
}
else
{
_wcscpy_c(gpszRunCmd, nCchLen, lsCmdLine);
}
// !!! gpszRunCmd может поменяться ниже!
// ====
if (gbRunViaCmdExe)
{
// -- always quotate
gpszRunCmd[0] = L'"';
_wcscpy_c(gpszRunCmd+1, nCchLen-1, gszComSpec);
_wcscat_c(gpszRunCmd, nCchLen, gpSrv->bK ? L"\" /K " : L"\" /C ");
// Собственно, командная строка
_wcscat_c(gpszRunCmd, nCchLen, lsCmdLine);
}
else if (lbNeedCutStartEndQuot)
{
// ""c:\arc\7z.exe -?"" - не запустится!
_wcscpy_c(gpszRunCmd, nCchLen, lsCmdLine+1);
wchar_t *pszEndQ = gpszRunCmd + lstrlenW(gpszRunCmd) - 1;
_ASSERTE(pszEndQ && *pszEndQ == L'"');
if (pszEndQ && *pszEndQ == L'"') *pszEndQ = 0;
}
// Теперь выкусить и обработать "-new_console" / "-cur_console"
RConStartArgs args;
args.pszSpecialCmd = gpszRunCmd;
args.ProcessNewConArg();
args.pszSpecialCmd = NULL; // Чтобы не разрушилась память отведенная в gpszRunCmd
// Если указана рабочая папка
if (args.pszStartupDir && *args.pszStartupDir)
{
SetCurrentDirectory(args.pszStartupDir);
}
//
gbRunInBackgroundTab = (args.BackgroundTab == crb_On);
if (args.BufHeight == crb_On)
{
TODO("gcrBufferSize - и ширину буфера");
gnBufferHeight = args.nBufHeight;
gbParmBufSize = TRUE;
}
// DosBox?
if (args.ForceDosBox == crb_On)
{
gbUseDosBox = TRUE;
}
// Overwrite mode in Prompt?
if (args.OverwriteMode == crb_On)
{
gnConsoleModeFlags |= (ENABLE_INSERT_MODE << 16); // Mask
gnConsoleModeFlags &= ~ENABLE_INSERT_MODE; // Turn bit OFF
// Поскольку ключик указан через "-cur_console/-new_console"
// смену режима нужно сделать сразу, т.к. функа зовется только для сервера
ServerInitConsoleMode();
}
#ifdef _DEBUG
OutputDebugString(gpszRunCmd); OutputDebugString(L"\n");
#endif
UNREFERENCED_PARAMETER(pwszStartCmdLine);
_ASSERTE(pwszStartCmdLine==asCmdLine);
return 0;
}
// Проверить, что nPID это "ConEmuC.exe" или "ConEmuC64.exe"
bool IsMainServerPID(DWORD nPID)
{
PROCESSENTRY32 Info;
if (!GetProcessInfo(nPID, &Info))
return false;
if ((lstrcmpi(Info.szExeFile, L"ConEmuC.exe") == 0)
|| (lstrcmpi(Info.szExeFile, L"ConEmuC64.exe") == 0))
{
return true;
}
return false;
}
int ExitWaitForKey(DWORD vkKeys, LPCWSTR asConfirm, BOOL abNewLine, BOOL abDontShowConsole, DWORD anMaxTimeout /*= 0*/)
{
gbInExitWaitForKey = TRUE;
int nKeyPressed = -1;
//-- Don't exit on ANY key if -new_console:c1
//if (!vkKeys) vkKeys = VK_ESCAPE;
// Чтобы ошибку было нормально видно
if (!abDontShowConsole)
{
BOOL lbNeedVisible = FALSE;
if (!ghConWnd) ghConWnd = GetConEmuHWND(2);
if (ghConWnd) // Если консоль была скрыта
{
WARNING("Если GUI жив - отвечает на запросы SendMessageTimeout - показывать консоль не нужно. Не красиво получается");
if (!IsWindowVisible(ghConWnd))
{
BOOL lbGuiAlive = FALSE;
if (ghConEmuWndDC && !isConEmuTerminated())
{
// ConEmu will deal the situation?
// EmergencyShow annoys user if parent window was killed (InsideMode)
lbGuiAlive = TRUE;
}
else if (ghConEmuWnd && IsWindow(ghConEmuWnd))
{
DWORD_PTR dwLRc = 0;
if (SendMessageTimeout(ghConEmuWnd, WM_NULL, 0, 0, SMTO_ABORTIFHUNG, 1000, &dwLRc))
lbGuiAlive = TRUE;
}
if (!lbGuiAlive && !IsWindowVisible(ghConWnd))
{
lbNeedVisible = TRUE;
// не надо наверное... // поставить "стандартный" 80x25, или то, что было передано к ком.строке
//SMALL_RECT rcNil = {0}; SetConsoleSize(0, gcrVisibleSize, rcNil, ":Exiting");
//SetConsoleFontSizeTo(ghConWnd, 8, 12); // установим шрифт побольше
//apiShowWindow(ghConWnd, SW_SHOWNORMAL); // и покажем окошко
EmergencyShow(ghConWnd);
}
}
}
}
HANDLE hIn = GetStdHandle(STD_INPUT_HANDLE);
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
// Сначала почистить буфер
INPUT_RECORD r = {0}; DWORD dwCount = 0;
DWORD nPreFlush = 0, nPostFlush = 0;
#ifdef _DEBUG
DWORD nPreQuit = 0;
#endif
GetNumberOfConsoleInputEvents(hIn, &nPreFlush);
FlushConsoleInputBuffer(hIn);
PRINT_COMSPEC(L"Finalizing. gbInShutdown=%i\n", gbInShutdown);
GetNumberOfConsoleInputEvents(hIn, &nPostFlush);
if (gbInShutdown)
goto wrap; // Event закрытия мог припоздниться
SetConsoleMode(hOut, ENABLE_PROCESSED_OUTPUT|ENABLE_WRAP_AT_EOL_OUTPUT);
//
if (asConfirm && *asConfirm)
{
_wprintf(asConfirm);
}
DWORD nStartTick = GetTickCount(), nDelta = 0;
while (TRUE)
{
if (gbStopExitWaitForKey)
{
// Был вызван HandlerRoutine(CLOSE)
break;
}
// Allow exit by timeout
if (anMaxTimeout)
{
nDelta = GetTickCount() - nStartTick;
if (nDelta >= anMaxTimeout)
{
break;
}
}
// If server was connected to GUI, but we get here because
// root process was not attached to console yet (antivirus lags?)
if (gpSrv->ConnectInfo.bConnected)
{
TODO("It would be nice to check for new console processed started in console?");
}
if (!PeekConsoleInput(GetStdHandle(STD_INPUT_HANDLE), &r, 1, &dwCount))
dwCount = 0;
if (!gbInExitWaitForKey)
{
if (gnRunMode == RM_SERVER)
{
int nCount = gpSrv->processes->nProcessCount;
if (nCount > 1)
{
// Теперь Peek, так что просто выходим
//// ! Процесс таки запустился, закрываться не будем. Вернуть событие в буфер!
//WriteConsoleInput(GetStdHandle(STD_INPUT_HANDLE), &r, 1, &dwCount);
break;
}
}
if (gbInShutdown)
{
break;
}
}
if (dwCount)
{
#ifdef _DEBUG
GetNumberOfConsoleInputEvents(hIn, &nPreQuit);
#endif
// Avoid ConIn overflow, even if (vkKeys == 0)
if (ReadConsoleInput(GetStdHandle(STD_INPUT_HANDLE), &r, 1, &dwCount)
&& dwCount
&& vkKeys)
{
bool lbMatch = false;
if (r.EventType == KEY_EVENT && r.Event.KeyEvent.bKeyDown)
{
for (DWORD vk = vkKeys; !lbMatch && LOBYTE(vk); vk=vk>>8)
{
lbMatch = (r.Event.KeyEvent.wVirtualKeyCode == LOBYTE(vk));
}
}
if (lbMatch)
{
nKeyPressed = r.Event.KeyEvent.wVirtualKeyCode;
break;
}
}
}
Sleep(50);
}
//MessageBox(0,L"Debug message...............1",L"ConEmuC",0);
//int nCh = _getch();
if (abNewLine)
_printf("\n");
wrap:
#if defined(_DEBUG) && defined(SHOW_EXITWAITKEY_MSGBOX)
wchar_t szTitle[128];
swprintf_c(szTitle, L"ConEmuC[Srv]: PID=%u", GetCurrentProcessId());
if (!gbStopExitWaitForKey)
MessageBox(NULL, asConfirm ? asConfirm : L"???", szTitle, MB_ICONEXCLAMATION|MB_SYSTEMMODAL);
#endif
return nKeyPressed;
}
// Используется в режиме RM_APPLICATION, чтобы не тормозить основной поток (жалобы на замедление запуска программ из батников)
DWORD gnSendStartedThread = 0;
HANDLE ghSendStartedThread = NULL;
DWORD WINAPI SendStartedThreadProc(LPVOID lpParameter)
{
_ASSERTE(gnMainServerPID!=0 && gnMainServerPID!=GetCurrentProcessId() && "Main server PID must be determined!");
CESERVER_REQ *pIn = (CESERVER_REQ*)lpParameter;
_ASSERTE(pIn && (pIn->hdr.cbSize>=sizeof(pIn->hdr)) && (pIn->hdr.nCmd==CECMD_CMDSTARTSTOP));
// Сам результат не интересует
CESERVER_REQ *pSrvOut = ExecuteSrvCmd(gnMainServerPID, pIn, ghConWnd, TRUE/*async*/);
ExecuteFreeResult(pSrvOut);
ExecuteFreeResult(pIn);
return 0;
}
void SetTerminateEvent(SetTerminateEventPlace eFrom)
{
#ifdef DEBUG_ISSUE_623
_ASSERTE((eFrom == ste_ProcessCountChanged) && "Calling SetTerminateEvent");
#endif
if (!gTerminateEventPlace)
gTerminateEventPlace = eFrom;
SetEvent(ghExitQueryEvent);
}
bool isConEmuTerminated()
{
// HWND of our VirtualConsole
if (!ghConEmuWndDC)
{
_ASSERTE(FALSE && "ghConEmuWndDC is expected to be NOT NULL");
return false;
}
if (::IsWindow(ghConEmuWndDC))
{
// ConEmu is alive
return false;
}
//TODO: It would be better to check process presence via connected Pipe
//TODO: Same as in ConEmu, it must check server presence via pipe
// For now, don't annoy user with RealConsole if all processes were finished
if (gbInExitWaitForKey // We are waiting for Enter or Esc
&& (gpSrv->processes->nProcessCount <= 1) // No active processes are found in console (except our SrvPID)
)
{
// Let RealConsole remain invisible, ConEmu will deal the situation
return false;
}
// ConEmu was killed?
return true;
}
void SendStarted()
{
LogFunction(L"SendStarted");
WARNING("Подозрение, что слишком много вызовов при старте сервера. Неаккуратно");
static bool bSent = false;
if (bSent)
{
_ASSERTE(FALSE && "SendStarted repetition");
return; // отсылать только один раз
}
//crNewSize = gpSrv->sbi.dwSize;
//_ASSERTE(crNewSize.X>=MIN_CON_WIDTH && crNewSize.Y>=MIN_CON_HEIGHT);
HWND hConWnd = GetConEmuHWND(2);
if (!gnSelfPID)
{
_ASSERTE(gnSelfPID!=0);
gnSelfPID = GetCurrentProcessId();
}
if (!hConWnd)
{
// Это Detached консоль. Скорее всего запущен вместо COMSPEC
_ASSERTE(gnRunMode == RM_COMSPEC);
gbNonGuiMode = TRUE; // Не посылать ExecuteGuiCmd при выходе. Это не наша консоль
return;
}
_ASSERTE(hConWnd == ghConWnd);
ghConWnd = hConWnd;
DWORD nMainServerPID = 0, nAltServerPID = 0, nGuiPID = 0;
// Для ComSpec-а сразу можно проверить, а есть-ли сервер в этой консоли...
if ((gnRunMode != RM_AUTOATTACH) && (gnRunMode /*== RM_COMSPEC*/ > RM_SERVER))
{
MFileMapping<CESERVER_CONSOLE_MAPPING_HDR> ConsoleMap;
ConsoleMap.InitName(CECONMAPNAME, LODWORD(hConWnd)); //-V205
const CESERVER_CONSOLE_MAPPING_HDR* pConsoleInfo = ConsoleMap.Open();
if (!pConsoleInfo)
{
_ASSERTE((gnRunMode == RM_COMSPEC) && (ghConWnd && !ghConEmuWnd && IsWindowVisible(ghConWnd)) && "ConsoleMap was not initialized for AltServer/ComSpec");
}
else
{
nMainServerPID = pConsoleInfo->nServerPID;
nAltServerPID = pConsoleInfo->nAltServerPID;
nGuiPID = pConsoleInfo->nGuiPID;
if (pConsoleInfo->cbSize >= sizeof(CESERVER_CONSOLE_MAPPING_HDR))
{
if (pConsoleInfo->nLogLevel)
CreateLogSizeFile(pConsoleInfo->nLogLevel, pConsoleInfo);
}
//UnmapViewOfFile(pConsoleInfo);
ConsoleMap.CloseMap();
}
if (nMainServerPID == 0)
{
gbNonGuiMode = TRUE; // Не посылать ExecuteGuiCmd при выходе. Это не наша консоль
return; // Режим ComSpec, но сервера нет, соответственно, в GUI ничего посылать не нужно
}
}
else
{
nGuiPID = gnConEmuPID;
}
CESERVER_REQ *pIn = NULL, *pOut = NULL, *pSrvOut = NULL;
int nSize = sizeof(CESERVER_REQ_HDR)+sizeof(CESERVER_REQ_STARTSTOP);
pIn = ExecuteNewCmd(CECMD_CMDSTARTSTOP, nSize);
if (pIn)
{
if (!GetModuleFileName(NULL, pIn->StartStop.sModuleName, countof(pIn->StartStop.sModuleName)))
pIn->StartStop.sModuleName[0] = 0;
#ifdef _DEBUG
LPCWSTR pszFileName = PointToName(pIn->StartStop.sModuleName);
#endif
// Cmd/Srv режим начат
switch (gnRunMode)
{
case RM_SERVER:
pIn->StartStop.nStarted = sst_ServerStart;
IsKeyboardLayoutChanged(pIn->StartStop.dwKeybLayout);
break;
case RM_ALTSERVER:
pIn->StartStop.nStarted = sst_AltServerStart;
IsKeyboardLayoutChanged(pIn->StartStop.dwKeybLayout);
break;
case RM_COMSPEC:
pIn->StartStop.nParentFarPID = gpSrv->dwParentFarPID;
pIn->StartStop.nStarted = sst_ComspecStart;
break;
default:
pIn->StartStop.nStarted = sst_AppStart;
}
pIn->StartStop.hWnd = ghConWnd;
pIn->StartStop.dwPID = gnSelfPID;
pIn->StartStop.dwAID = gpSrv->dwGuiAID;
#ifdef _WIN64
pIn->StartStop.nImageBits = 64;
#else
pIn->StartStop.nImageBits = 32;
#endif
TODO("Ntvdm/DosBox -> 16");
//pIn->StartStop.dwInputTID = (gnRunMode == RM_SERVER) ? gpSrv->dwInputThreadId : 0;
if ((gnRunMode == RM_SERVER) || (gnRunMode == RM_ALTSERVER))
pIn->StartStop.bUserIsAdmin = IsUserAdmin();
// Перед запуском 16бит приложений нужно подресайзить консоль...
gnImageSubsystem = 0;
LPCWSTR pszTemp = gpszRunCmd;
CEStr lsRoot;
if (gnRunMode == RM_SERVER && gpSrv->DbgInfo.bDebuggerActive)
{
// "Отладчик"
gnImageSubsystem = 0x101;
gbRootIsCmdExe = TRUE; // Чтобы буфер появился
}
else if (/*!gpszRunCmd &&*/ gbAttachFromFar)
{
// Аттач из фар-плагина
gnImageSubsystem = 0x100;
}
else if (gpszRunCmd && ((0 == NextArg(&pszTemp, lsRoot))))
{
PRINT_COMSPEC(L"Starting: <%s>", lsRoot);
MWow64Disable wow;
if (!gbSkipWowChange) wow.Disable();
DWORD nImageFileAttr = 0;
if (!GetImageSubsystem(lsRoot, gnImageSubsystem, gnImageBits, nImageFileAttr))
gnImageSubsystem = 0;
PRINT_COMSPEC(L", Subsystem: <%i>\n", gnImageSubsystem);
PRINT_COMSPEC(L" Args: %s\n", pszTemp);
}
else
{
GetImageSubsystem(gnImageSubsystem, gnImageBits);
}
pIn->StartStop.nSubSystem = gnImageSubsystem;
if ((gnImageSubsystem == IMAGE_SUBSYSTEM_DOS_EXECUTABLE) || (gbUseDosBox))
pIn->StartStop.nImageBits = 16;
else if (gnImageBits)
pIn->StartStop.nImageBits = gnImageBits;
pIn->StartStop.bRootIsCmdExe = gbRootIsCmdExe; //2009-09-14
// НЕ MyGet..., а то можем заблокироваться...
DWORD dwErr1 = 0;
BOOL lbRc1;
{
HANDLE hOut;
// Need to block all requests to output buffer in other threads
MSectionLockSimple csRead; csRead.Lock(&gpSrv->csReadConsoleInfo, LOCK_READOUTPUT_TIMEOUT);
if ((gnRunMode == RM_SERVER) || (gnRunMode == RM_ALTSERVER))
hOut = (HANDLE)ghConOut;
else
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
lbRc1 = GetConsoleScreenBufferInfo(hOut, &pIn->StartStop.sbi);
if (!lbRc1)
dwErr1 = GetLastError();
else
pIn->StartStop.crMaxSize = MyGetLargestConsoleWindowSize(hOut);
}
// Если (для ComSpec) указан параметр "-cur_console:h<N>"
if (gbParmBufSize)
{
pIn->StartStop.bForceBufferHeight = TRUE;
TODO("gcrBufferSize - и ширину буфера");
pIn->StartStop.nForceBufferHeight = gnBufferHeight;
}
PRINT_COMSPEC(L"Starting %s mode (ExecuteGuiCmd started)\n", (RunMode==RM_SERVER) ? L"Server" : (RunMode==RM_ALTSERVER) ? L"AltServer" : L"ComSpec");
// CECMD_CMDSTARTSTOP
if (gnRunMode == RM_SERVER)
{
_ASSERTE(nGuiPID!=0 && gnRunMode==RM_SERVER);
pIn->StartStop.hServerProcessHandle = DuplicateProcessHandle(nGuiPID);
// послать CECMD_CMDSTARTSTOP/sst_ServerStart в GUI
pOut = ExecuteGuiCmd(ghConEmuWnd, pIn, ghConWnd);
}
else if (gnRunMode == RM_ALTSERVER)
{
// Подготовить хэндл своего процесса для MainServer
pIn->StartStop.hServerProcessHandle = DuplicateProcessHandle(nMainServerPID);
_ASSERTE(pIn->hdr.nCmd == CECMD_CMDSTARTSTOP);
pSrvOut = ExecuteSrvCmd(nMainServerPID, pIn, ghConWnd);
// MainServer должен был вернуть PID предыдущего AltServer (если он был)
if (pSrvOut && (pSrvOut->DataSize() >= sizeof(CESERVER_REQ_STARTSTOPRET)))
{
gpSrv->dwPrevAltServerPID = pSrvOut->StartStopRet.dwPrevAltServerPID;
}
else
{
_ASSERTE(pSrvOut && (pSrvOut->DataSize() >= sizeof(CESERVER_REQ_STARTSTOPRET)) && "StartStopRet.dwPrevAltServerPID expected");
}
}
else if (gnRunMode == RM_APPLICATION)
{
if (nMainServerPID == 0)
{
_ASSERTE(nMainServerPID && "Main Server must be detected already!");
}
else
{
// Сразу запомнить в глобальной переменной PID сервера
gnMainServerPID = nMainServerPID;
gnAltServerPID = nAltServerPID;
// чтобы не тормозить основной поток (жалобы на замедление запуска программ из батников)
ghSendStartedThread = apiCreateThread(SendStartedThreadProc, pIn, &gnSendStartedThread, "SendStartedThreadProc");
DWORD nErrCode = ghSendStartedThread ? 0 : GetLastError();
if (ghSendStartedThread == NULL)
{
_ASSERTE(ghSendStartedThread && L"SendStartedThreadProc creation failed!")
pSrvOut = ExecuteSrvCmd(nMainServerPID, pIn, ghConWnd);
}
else
{
pIn = NULL; // Освободит сама SendStartedThreadProc
}
UNREFERENCED_PARAMETER(nErrCode);
}
_ASSERTE(pOut == NULL); // нада
}
else
{
WARNING("TODO: Может быть это тоже в главный сервер посылать?");
_ASSERTE(nGuiPID!=0 && gnRunMode==RM_COMSPEC);
pOut = ExecuteGuiCmd(ghConWnd, pIn, ghConWnd);
// pOut должен содержать инфу, что должен сделать ComSpec
// при завершении (вернуть высоту буфера)
_ASSERTE(pOut!=NULL && "Prev buffer size must be returned!");
}
#if 0
if (nServerPID && (nServerPID != gnSelfPID))
{
_ASSERTE(nServerPID!=0 && (gnRunMode==RM_ALTSERVER || gnRunMode==RM_COMSPEC));
if ((gnRunMode == RM_ALTSERVER) || (gnRunMode == RM_SERVER))
{
pIn->StartStop.hServerProcessHandle = DuplicateProcessHandle(nServerPID);
}
WARNING("Optimize!!!");
WARNING("Async");
pSrvOut = ExecuteSrvCmd(nServerPID, pIn, ghConWnd);
if (gnRunMode == RM_ALTSERVER)
{
if (pSrvOut && (pSrvOut->DataSize() >= sizeof(CESERVER_REQ_STARTSTOPRET)))
{
gpSrv->dwPrevAltServerPID = pSrvOut->StartStopRet.dwPrevAltServerPID;
}
else
{
_ASSERTE(pSrvOut && (pSrvOut->DataSize() >= sizeof(CESERVER_REQ_STARTSTOPRET)));
}
}
}
else
{
_ASSERTE(gnRunMode==RM_SERVER && (nServerPID && (nServerPID != gnSelfPID)) && "nServerPID MUST be known already!");
}
#endif
#if 0
WARNING("Только для RM_SERVER. Все остальные должны докладываться главному серверу, а уж он разберется");
if (gnRunMode != RM_APPLICATION)
{
_ASSERTE(nGuiPID!=0 || gnRunMode==RM_SERVER);
if ((gnRunMode == RM_ALTSERVER) || (gnRunMode == RM_SERVER))
{
pIn->StartStop.hServerProcessHandle = DuplicateProcessHandle(nGuiPID);
}
WARNING("Optimize!!!");
pOut = ExecuteGuiCmd(ghConWnd, pIn, ghConWnd);
}
#endif
PRINT_COMSPEC(L"Starting %s mode (ExecuteGuiCmd finished)\n",(RunMode==RM_SERVER) ? L"Server" : (RunMode==RM_ALTSERVER) ? L"AltServer" : L"ComSpec");
if (pOut == NULL)
{
if (gnRunMode != RM_COMSPEC)
{
// для RM_APPLICATION будет pOut==NULL?
_ASSERTE(gnRunMode == RM_ALTSERVER);
}
else
{
gbNonGuiMode = TRUE; // Не посылать ExecuteGuiCmd при выходе. Это не наша консоль
}
}
else
{
bSent = true;
BOOL bAlreadyBufferHeight = pOut->StartStopRet.bWasBufferHeight;
DWORD nGuiPID = pOut->StartStopRet.dwPID;
SetConEmuWindows(pOut->StartStopRet.hWnd, pOut->StartStopRet.hWndDc, pOut->StartStopRet.hWndBack);
if (gpSrv)
{
_ASSERTE(gnConEmuPID == pOut->StartStopRet.dwPID);
gnConEmuPID = pOut->StartStopRet.dwPID;
#ifdef _DEBUG
DWORD dwPID; GetWindowThreadProcessId(ghConEmuWnd, &dwPID);
_ASSERTE(ghConEmuWnd==NULL || dwPID==gnConEmuPID);
#endif
}
if ((gnRunMode == RM_SERVER) || (gnRunMode == RM_ALTSERVER))
{
if (gpSrv)
{
gpSrv->bWasDetached = FALSE;
}
else
{
_ASSERTE(gpSrv!=NULL);
}
}
UpdateConsoleMapHeader(L"SendStarted");
_ASSERTE(gnMainServerPID==0 || gnMainServerPID==pOut->StartStopRet.dwMainSrvPID || (gbAttachMode && gbAlienMode && (pOut->StartStopRet.dwMainSrvPID==gnSelfPID)));
gnMainServerPID = pOut->StartStopRet.dwMainSrvPID;
gnAltServerPID = pOut->StartStopRet.dwAltSrvPID;
AllowSetForegroundWindow(nGuiPID);
TODO("gnBufferHeight->gcrBufferSize");
TODO("gcrBufferSize - и ширину буфера");
gnBufferHeight = (SHORT)pOut->StartStopRet.nBufferHeight;
gbParmBufSize = TRUE;
// gcrBufferSize переименован в gcrVisibleSize
_ASSERTE(pOut->StartStopRet.nWidth && pOut->StartStopRet.nHeight);
gcrVisibleSize.X = (SHORT)pOut->StartStopRet.nWidth;
gcrVisibleSize.Y = (SHORT)pOut->StartStopRet.nHeight;
gbParmVisibleSize = TRUE;
if ((gnRunMode == RM_SERVER) || (gnRunMode == RM_ALTSERVER))
{
// Если режим отладчика - принудительно включить прокрутку
if (gpSrv->DbgInfo.bDebuggerActive && !gnBufferHeight)
{
_ASSERTE(gnRunMode != RM_ALTSERVER);
gnBufferHeight = 9999;
}
SMALL_RECT rcNil = {0};
SetConsoleSize(gnBufferHeight, gcrVisibleSize, rcNil, "::SendStarted");
// Смена раскладки клавиатуры
if ((gnRunMode != RM_ALTSERVER) && pOut->StartStopRet.bNeedLangChange)
{
#ifndef INPUTLANGCHANGE_SYSCHARSET
#define INPUTLANGCHANGE_SYSCHARSET 0x0001
#endif
WPARAM wParam = INPUTLANGCHANGE_SYSCHARSET;
TODO("Проверить на x64, не будет ли проблем с 0xFFFFFFFFFFFFFFFFFFFFF");
LPARAM lParam = (LPARAM)(DWORD_PTR)pOut->StartStopRet.NewConsoleLang;
SendMessage(ghConWnd, WM_INPUTLANGCHANGEREQUEST, wParam, lParam);
}
}
else
{
// Может так получиться, что один COMSPEC запущен из другого.
// 100628 - неактуально. COMSPEC сбрасывается в cmd.exe
//if (bAlreadyBufferHeight)
// gpSrv->bNonGuiMode = TRUE; // Не посылать ExecuteGuiCmd при выходе - прокрутка должна остаться
gbWasBufferHeight = bAlreadyBufferHeight;
}
//nNewBufferHeight = ((DWORD*)(pOut->Data))[0];
//crNewSize.X = (SHORT)((DWORD*)(pOut->Data))[1];
//crNewSize.Y = (SHORT)((DWORD*)(pOut->Data))[2];
TODO("Если он запущен как COMSPEC - то к GUI никакого отношения иметь не должен");
//if (rNewWindow.Right >= crNewSize.X) // размер был уменьшен за счет полосы прокрутки
// rNewWindow.Right = crNewSize.X-1;
ExecuteFreeResult(pOut); //pOut = NULL;
//gnBufferHeight = nNewBufferHeight;
} // (pOut != NULL)
ExecuteFreeResult(pIn);
ExecuteFreeResult(pSrvOut);
}
}
CESERVER_REQ* SendStopped(CONSOLE_SCREEN_BUFFER_INFO* psbi)
{
LogFunction(L"SendStopped");
int iHookRc = -1;
if (gnRunMode == RM_ALTSERVER)
{
// сообщение о завершении будет посылать ConEmuHk.dll
HMODULE hHooks = GetModuleHandle(WIN3264TEST(L"ConEmuHk.dll",L"ConEmuHk64.dll"));
RequestLocalServer_t fRequestLocalServer = (RequestLocalServer_t)(hHooks ? GetProcAddress(hHooks, "RequestLocalServer") : NULL);
if (fRequestLocalServer)
{
RequestLocalServerParm Parm = {sizeof(Parm), slsf_AltServerStopped};
iHookRc = fRequestLocalServer(&Parm);
}
_ASSERTE((iHookRc == 0) && "SendStopped must be sent from ConEmuHk.dll");
return NULL;
}
if (ghSendStartedThread)
{
_ASSERTE(gnRunMode!=RM_COMSPEC);
// Чуть-чуть подождать, может все-таки успеет?
DWORD nWait = WaitForSingleObject(ghSendStartedThread, 50);
if (nWait == WAIT_TIMEOUT)
{
#ifndef __GNUC__
#pragma warning( push )
#pragma warning( disable : 6258 )
#endif
apiTerminateThread(ghSendStartedThread, 100); // раз корректно не хочет...
#ifndef __GNUC__
#pragma warning( pop )
#endif
}
HANDLE h = ghSendStartedThread; ghSendStartedThread = NULL;
CloseHandle(h);
}
else
{
_ASSERTE(gnRunMode!=RM_APPLICATION);
}
CESERVER_REQ *pIn = NULL, *pOut = NULL;
int nSize = sizeof(CESERVER_REQ_HDR)+sizeof(CESERVER_REQ_STARTSTOP);
pIn = ExecuteNewCmd(CECMD_CMDSTARTSTOP,nSize);
if (pIn)
{
switch (gnRunMode)
{
case RM_SERVER:
// По идее, sst_ServerStop не посылается
_ASSERTE(gnRunMode != RM_SERVER);
pIn->StartStop.nStarted = sst_ServerStop;
break;
case RM_ALTSERVER:
pIn->StartStop.nStarted = sst_AltServerStop;
break;
case RM_COMSPEC:
pIn->StartStop.nStarted = sst_ComspecStop;
pIn->StartStop.nOtherPID = gpSrv->dwRootProcess;
pIn->StartStop.nParentFarPID = gpSrv->dwParentFarPID;
break;
default:
pIn->StartStop.nStarted = sst_AppStop;
}
if (!GetModuleFileName(NULL, pIn->StartStop.sModuleName, countof(pIn->StartStop.sModuleName)))
pIn->StartStop.sModuleName[0] = 0;
pIn->StartStop.hWnd = ghConWnd;
pIn->StartStop.dwPID = gnSelfPID;
pIn->StartStop.nSubSystem = gnImageSubsystem;
if ((gnImageSubsystem == IMAGE_SUBSYSTEM_DOS_EXECUTABLE) || (gbUseDosBox))
pIn->StartStop.nImageBits = 16;
else if (gnImageBits)
pIn->StartStop.nImageBits = gnImageBits;
else
{
#ifdef _WIN64
pIn->StartStop.nImageBits = 64;
#else
pIn->StartStop.nImageBits = 32;
#endif
}
pIn->StartStop.bWasBufferHeight = gbWasBufferHeight;
if (psbi != NULL)
{
pIn->StartStop.sbi = *psbi;
}
else
{
// НЕ MyGet..., а то можем заблокироваться...
// ghConOut может быть NULL, если ошибка произошла во время разбора аргументов
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &pIn->StartStop.sbi);
}
pIn->StartStop.crMaxSize = MyGetLargestConsoleWindowSize(GetStdHandle(STD_OUTPUT_HANDLE));
if ((gnRunMode == RM_APPLICATION) || (gnRunMode == RM_ALTSERVER))
{
if (gnMainServerPID == 0)
{
_ASSERTE(gnMainServerPID!=0 && "MainServer PID must be determined");
}
else
{
pIn->StartStop.nOtherPID = (gnRunMode == RM_ALTSERVER) ? gpSrv->dwPrevAltServerPID : 0;
pOut = ExecuteSrvCmd(gnMainServerPID, pIn, ghConWnd);
}
}
else
{
PRINT_COMSPEC(L"Finalizing comspec mode (ExecuteGuiCmd started)\n",0);
WARNING("Это надо бы совместить, но пока - нужно сначала передернуть главный сервер!");
pOut = ExecuteSrvCmd(gnMainServerPID, pIn, ghConWnd);
_ASSERTE(pOut!=NULL);
ExecuteFreeResult(pOut);
pOut = ExecuteGuiCmd(ghConWnd, pIn, ghConWnd);
PRINT_COMSPEC(L"Finalizing comspec mode (ExecuteGuiCmd finished)\n",0);
}
ExecuteFreeResult(pIn); pIn = NULL;
}
return pOut;
}
void CreateLogSizeFile(int nLevel, const CESERVER_CONSOLE_MAPPING_HDR* pConsoleInfo /*= NULL*/)
{
if (gpLogSize) return; // уже
DWORD dwErr = 0;
wchar_t szFile[MAX_PATH+64], *pszDot, *pszName, *pszDir = NULL;
wchar_t szDir[MAX_PATH+16];
if (!GetModuleFileName(NULL, szFile, MAX_PATH))
{
dwErr = GetLastError();
_printf("GetModuleFileName failed! ErrCode=0x%08X\n", dwErr);
return; // не удалось
}
pszName = (wchar_t*)PointToName(szFile);
if ((pszDot = wcsrchr(pszName, L'.')) == NULL)
{
_printf("wcsrchr failed!\n", 0, szFile); //-V576
return; // ошибка
}
if (pszName && (pszName > szFile))
{
// If we were started from ConEmu, the pConsoleInfo must be defined...
if (pConsoleInfo && pConsoleInfo->cbSize && pConsoleInfo->sConEmuExe[0])
{
lstrcpyn(szDir, pConsoleInfo->sConEmuExe, countof(szDir));
wchar_t* pszConEmuExe = (wchar_t*)PointToName(szDir);
if (pszConEmuExe)
{
*(pszConEmuExe-1) = 0;
pszDir = szDir;
}
}
if (!pszDir)
{
// if our exe lays in subfolder of ConEmu.exe?
*(pszName-1) = 0;
wcscpy_c(szDir, szFile);
pszDir = wcsrchr(szDir, L'\\');
if (!pszDir || (lstrcmpi(pszDir, L"\\ConEmu") != 0))
{
// Если ConEmuC.exe лежит НЕ в папке "ConEmu"
pszDir = szDir; // писать в текущую папку или на десктоп
}
else
{
// Иначе - попытаться найти соответствующий файл GUI
wchar_t szGuiFiles[] = L"\\ConEmu.exe" L"\0" L"\\ConEmu64.exe" L"\0\0";
if (FilesExists(szDir, szGuiFiles))
{
pszDir = szFile; // GUI лежит в той же папке, что и "сервер"
}
else
{
// На уровень выше?
*pszDir = 0;
if (FilesExists(szDir, szGuiFiles))
{
*pszDir = 0;
pszDir = szDir; // GUI лежит в родительской папке
}
else
{
pszDir = szFile; // GUI не нашли
}
}
}
}
}
gpLogSize = new MFileLogEx(L"ConEmu-srv", pszDir, GetCurrentProcessId());
if (!gpLogSize)
return;
dwErr = (DWORD)gpLogSize->CreateLogFile();
if (dwErr != 0)
{
_printf("Create console log file failed! ErrCode=0x%08X\n", dwErr, gpLogSize->GetLogFileName()); //-V576
_ASSERTE(FALSE && "gpLogSize->CreateLogFile failed");
SafeDelete(gpLogSize);
return;
}
gpLogSize->LogStartEnv(gpStartEnv);
LogSize(NULL, 0, "Startup");
}
bool LogString(LPCSTR asText)
{
if (!gpLogSize)
{
#ifdef _DEBUG
if (asText && *asText)
{
wchar_t* pszWide = lstrdupW(asText);
if (pszWide)
{
DEBUGSTR(pszWide);
free(pszWide);
}
}
#endif
return false;
}
char szInfo[255]; szInfo[0] = 0;
LPCSTR pszThread = " <unknown thread>";
DWORD dwId = GetCurrentThreadId();
if (dwId == gdwMainThreadId)
pszThread = "MainThread";
else if (gpSrv->CmdServer.IsPipeThread(dwId))
pszThread = "ServThread";
else if (dwId == gpSrv->dwRefreshThread)
pszThread = "RefrThread";
//#ifdef USE_WINEVENT_SRV
//else if (dwId == gpSrv->dwWinEventThread)
// pszThread = " WinEventThread";
//#endif
else if (gpSrv->InputServer.IsPipeThread(dwId))
pszThread = "InptThread";
else if (gpSrv->DataServer.IsPipeThread(dwId))
pszThread = "DataThread";
gpLogSize->LogString(asText, true, pszThread);
return true;
}
bool LogString(LPCWSTR asText)
{
if (!gpLogSize)
{
DEBUGSTR(asText);
return false;
}
wchar_t szInfo[255]; szInfo[0] = 0;
LPCWSTR pszThread = L" <unknown thread>";
DWORD dwId = GetCurrentThreadId();
if (dwId == gdwMainThreadId)
pszThread = L"MainThread";
else if (gpSrv->CmdServer.IsPipeThread(dwId))
pszThread = L"ServThread";
else if (dwId == gpSrv->dwRefreshThread)
pszThread = L"RefrThread";
else if (gpSrv->InputServer.IsPipeThread(dwId))
pszThread = L"InptThread";
else if (gpSrv->DataServer.IsPipeThread(dwId))
pszThread = L"DataThread";
gpLogSize->LogString(asText, true, pszThread);
return false;
}
void LogSize(const COORD* pcrSize, int newBufferHeight, LPCSTR pszLabel, bool bForceWriteLog)
{
if (!gpLogSize) return;
static DWORD nLastWriteTick = 0;
const DWORD TickDelta = 1000;
static LONG nSkipped = 0;
const LONG SkipDelta = 50;
static CONSOLE_SCREEN_BUFFER_INFO lsbiLast = {};
bool bWriteLog = false;
CONSOLE_SCREEN_BUFFER_INFO lsbi = {};
CONSOLE_CURSOR_INFO ci = {(DWORD)-1};
HANDLE hCon = ghConOut;
BOOL bHandleOK = (hCon != NULL);
if (!bHandleOK)
hCon = GetStdHandle(STD_OUTPUT_HANDLE);
// В дебажный лог помещаем реальные значения
BOOL bConsoleOK = GetConsoleScreenBufferInfo(hCon, &lsbi);
char szInfo[400]; szInfo[0] = 0;
DWORD nErrCode = GetLastError();
// Cursor information (gh-718)
GetConsoleCursorInfo(hCon, &ci);
int fontX = 0, fontY = 0; wchar_t szFontName[LF_FACESIZE] = L""; char szFontInfo[60] = "<NA>";
if (apiGetConsoleFontSize(hCon, fontY, fontX, szFontName))
{
LPCSTR szState = "";
if (!g_LastSetConsoleFont.cbSize)
{
szState = " <?>";
}
else if ((g_LastSetConsoleFont.dwFontSize.Y != fontY)
|| (g_LastSetConsoleFont.dwFontSize.X != fontX))
{
// nConFontHeight/nConFontWidth не совпадает с получаемым,
// нужно организовать спец переменные в WConsole
_ASSERTE(g_LastSetConsoleFont.dwFontSize.Y==fontY && g_LastSetConsoleFont.dwFontSize.X==fontX);
szState = " <!>";
}
szFontInfo[0] = '`';
int iCvt = WideCharToMultiByte(CP_UTF8, 0, szFontName, -1, szFontInfo+1, 40, NULL, NULL);
if (iCvt <= 0) lstrcpynA(szFontInfo+1, "??", 40); else szFontInfo[iCvt+1] = 0;
int iLen = lstrlenA(szFontInfo); // result of WideCharToMultiByte is not suitable (contains trailing zero)
sprintf_c(szFontInfo+iLen, countof(szFontInfo)-iLen/*#SECURELEN*/, "` %ix%i%s",
fontY, fontX, szState);
}
#ifdef _DEBUG
wchar_t szClass[100] = L"";
GetClassName(ghConWnd, szClass, countof(szClass));
_ASSERTE(lstrcmp(szClass, L"ConsoleWindowClass")==0);
#endif
char szWindowInfo[40] = "<NA>"; RECT rcConsole = {};
if (GetWindowRect(ghConWnd, &rcConsole))
{
sprintf_c(szWindowInfo, "{(%i,%i) (%ix%i)}", rcConsole.left, rcConsole.top, LOGRECTSIZE(rcConsole));
}
if (pcrSize)
{
bWriteLog = true;
sprintf_c(szInfo, "CurSize={%i,%i,%i} ChangeTo={%i,%i,%i} Cursor={%i,%i,%i%%%c} ConRect={%i,%i}-{%i,%i} %s (skipped=%i) {%u:%u:x%X:%u} %s %s",
lsbi.dwSize.X, lsbi.srWindow.Bottom-lsbi.srWindow.Top+1, lsbi.dwSize.Y, pcrSize->X, pcrSize->Y, newBufferHeight,
lsbi.dwCursorPosition.X, lsbi.dwCursorPosition.Y, ci.dwSize, ci.bVisible ? L'V' : L'H',
lsbi.srWindow.Left, lsbi.srWindow.Top, lsbi.srWindow.Right, lsbi.srWindow.Bottom,
(pszLabel ? pszLabel : ""), nSkipped,
bConsoleOK, bHandleOK, (DWORD)(DWORD_PTR)hCon, nErrCode,
szWindowInfo, szFontInfo);
}
else
{
if (bForceWriteLog)
bWriteLog = true;
// Avoid numerous writing of equal lines to log
else if ((lsbi.dwSize.X != lsbiLast.dwSize.X) || (lsbi.dwSize.Y != lsbiLast.dwSize.Y))
bWriteLog = true;
else if (((GetTickCount() - nLastWriteTick) >= TickDelta) || (nSkipped >= SkipDelta))
bWriteLog = true;
sprintf_c(szInfo, "CurSize={%i,%i,%i} Cursor={%i,%i,%i%%%c} ConRect={%i,%i}-{%i,%i} %s (skipped=%i) {%u:%u:x%X:%u} %s %s",
lsbi.dwSize.X, lsbi.srWindow.Bottom-lsbi.srWindow.Top+1, lsbi.dwSize.Y,
lsbi.dwCursorPosition.X, lsbi.dwCursorPosition.Y, ci.dwSize, ci.bVisible ? L'V' : L'H',
lsbi.srWindow.Left, lsbi.srWindow.Top, lsbi.srWindow.Right, lsbi.srWindow.Bottom,
(pszLabel ? pszLabel : ""), nSkipped,
bConsoleOK, bHandleOK, (DWORD)(DWORD_PTR)hCon, nErrCode,
szWindowInfo, szFontInfo);
}
lsbiLast = lsbi;
if (!bWriteLog)
{
InterlockedIncrement(&nSkipped);
}
else
{
nSkipped = 0;
LogFunction(szInfo);
nLastWriteTick = GetTickCount();
}
}
void LogModeChange(LPCWSTR asName, DWORD oldVal, DWORD newVal)
{
if (!gpLogSize) return;
LPCWSTR pszLabel = asName ? asName : L"???";
CEStr lsInfo;
INT_PTR cchLen = lstrlen(pszLabel) + 80;
swprintf_c(lsInfo.GetBuffer(cchLen), cchLen/*#SECURELEN*/, L"Mode %s changed: old=x%04X new=x%04X", pszLabel, oldVal, newVal);
LogString(lsInfo);
}
int CLogFunction::m_FnLevel = 0; // Simple, without per-thread devision
CLogFunction::CLogFunction() : mb_Logged(false)
{
}
CLogFunction::CLogFunction(const char* asFnName) : mb_Logged(false)
{
int nLen = MultiByteToWideChar(CP_ACP, 0, asFnName, -1, NULL, 0);
wchar_t sBuf[80] = L"";
wchar_t *pszBuf = NULL;
if (nLen >= 80)
pszBuf = (wchar_t*)calloc(nLen+1,sizeof(*pszBuf));
else
pszBuf = sBuf;
MultiByteToWideChar(CP_ACP, 0, asFnName, -1, pszBuf, nLen+1);
DoLogFunction(pszBuf);
if (pszBuf != sBuf)
SafeFree(pszBuf);
}
CLogFunction::CLogFunction(const wchar_t* asFnName) : mb_Logged(false)
{
DoLogFunction(asFnName);
}
void CLogFunction::DoLogFunction(const wchar_t* asFnName)
{
if (mb_Logged)
return;
LONG lLevel = InterlockedIncrement((LONG*)&m_FnLevel);
mb_Logged = true;
if (!gpLogSize) return;
if (lLevel > 20) lLevel = 20;
wchar_t cFnInfo[120];
wchar_t* pc = cFnInfo;
for (LONG l = 1; l < lLevel; l++)
{
*(pc++) = L' '; *(pc++) = L' '; *(pc++) = L' ';
}
*pc = 0;
INT_PTR nPrefix = (pc - cFnInfo);
INT_PTR nFnLen = lstrlen(asFnName);
if (nFnLen < ((INT_PTR)countof(cFnInfo) - nPrefix))
{
lstrcpyn(pc, asFnName, countof(cFnInfo) - (pc - cFnInfo));
LogString(cFnInfo);
}
else
{
wchar_t* pszMrg = lstrmerge(cFnInfo, asFnName);
LogString(pszMrg);
SafeFree(pszMrg);
}
}
CLogFunction::~CLogFunction()
{
if (!mb_Logged)
return;
InterlockedDecrement((LONG*)&m_FnLevel);
}
int CALLBACK FontEnumProc(ENUMLOGFONTEX *lpelfe, NEWTEXTMETRICEX *lpntme, DWORD FontType, LPARAM lParam)
{
if ((FontType & TRUETYPE_FONTTYPE) == TRUETYPE_FONTTYPE)
{
// OK, подходит
wcscpy_c(gpSrv->szConsoleFont, lpelfe->elfLogFont.lfFaceName);
return 0;
}
return TRUE; // ищем следующий фонт
}
static void UndoConsoleWindowZoom()
{
BOOL lbRc = FALSE;
// Если юзер случайно нажал максимизацию, когда консольное окно видимо - ничего хорошего не будет
if (IsZoomed(ghConWnd))
{
SendMessage(ghConWnd, WM_SYSCOMMAND, SC_RESTORE, 0);
DWORD dwStartTick = GetTickCount();
do
{
Sleep(20); // подождем чуть, но не больше секунды
}
while (IsZoomed(ghConWnd) && (GetTickCount()-dwStartTick)<=1000);
Sleep(20); // и еще чуть-чуть, чтобы консоль прочухалась
// Теперь нужно вернуть (вдруг он изменился) размер буфера консоли
// Если этого не сделать - размер консоли нельзя УМЕНЬШИТЬ
RECT rcConPos;
GetWindowRect(ghConWnd, &rcConPos);
MoveWindow(ghConWnd, rcConPos.left, rcConPos.top, 1, 1, 1);
TODO("Horizontal scroll");
if (gnBufferHeight == 0)
{
//specified width and height cannot be less than the width and height of the console screen buffer's window
lbRc = SetConsoleScreenBufferSize(ghConOut, gcrVisibleSize);
}
else
{
// ресайз для BufferHeight
COORD crHeight = {gcrVisibleSize.X, gnBufferHeight};
MoveWindow(ghConWnd, rcConPos.left, rcConPos.top, 1, 1, 1);
lbRc = SetConsoleScreenBufferSize(ghConOut, crHeight); // а не crNewSize - там "оконные" размеры
}
// И вернуть тот видимый прямоугольник, который был получен в последний раз (успешный раз)
lbRc = SetConsoleWindowInfo(ghConOut, TRUE, &gpSrv->sbi.srWindow);
}
UNREFERENCED_PARAMETER(lbRc);
}
bool static NeedLegacyCursorCorrection()
{
static bool bNeedCorrection = false, bChecked = false;
if (!bChecked)
{
// gh-1051: In NON DBCS systems there are cursor problems too (Win10 stable build 15063 or higher)
if (IsWin10() && !IsWinDBCS() && !IsWin10LegacyConsole())
{
OSVERSIONINFOEXW osvi = { sizeof(osvi), 10, 0, 15063 };
DWORDLONG const dwlConditionMask = VerSetConditionMask(VerSetConditionMask(VerSetConditionMask(0,
VER_MAJORVERSION, VER_GREATER_EQUAL),
VER_MINORVERSION, VER_GREATER_EQUAL),
VER_BUILDNUMBER, VER_GREATER_EQUAL);
BOOL ibIsWin = _VerifyVersionInfo(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_BUILDNUMBER, dwlConditionMask);
if (ibIsWin)
{
bNeedCorrection = true;
}
}
bChecked = true;
}
return bNeedCorrection;
}
// TODO: Optimize - combine ReadConsoleData/ReadConsoleInfo
void static CorrectDBCSCursorPosition(HANDLE ahConOut, CONSOLE_SCREEN_BUFFER_INFO& csbi)
{
if (csbi.dwSize.X <= 0 || csbi.dwCursorPosition.X <= 0)
return;
// Issue 577: Chinese display error on Chinese
// -- GetConsoleScreenBufferInfo returns DBCS cursor coordinates, but we require wchar_t !!!
if (!IsConsoleDoubleCellCP()
// gh-1057: In NON DBCS systems there are cursor problems too (Win10 stable build 15063)
&& !NeedLegacyCursorCorrection())
return;
// The correction process
{
CHAR Chars[200];
LONG cchMax = countof(Chars);
LPSTR pChars = (csbi.dwCursorPosition.X <= cchMax) ? Chars : (LPSTR)calloc(csbi.dwCursorPosition.X, sizeof(*pChars));
if (pChars)
cchMax = csbi.dwCursorPosition.X;
else
pChars = Chars; // memory allocation fail? try part of line?
COORD crRead = {0, csbi.dwCursorPosition.Y};
// gh-1501: Windows 10 CJK version set COMMON_LVB_*_BYTE even for SOME non-ASCII characters (e.g. Greek "Α", Russian "Я", etc.)
#if 0
//120830 - DBCS uses 2 cells per hieroglyph
// TODO: Optimize
DWORD nRead = 0;
BOOL bRead = NeedLegacyCursorCorrection() ? FALSE : ReadConsoleOutputCharacterA(ahConOut, pChars, cchMax, crRead, &nRead);
// ReadConsoleOutputCharacterA may return "???" instead of DBCS codes in Non-DBCS systems
if (bRead && (nRead == cchMax))
{
_ASSERTE(nRead==cchMax);
int nXShift = 0;
LPSTR p = pChars, pEnd = pChars+nRead;
while (p < pEnd)
{
if (IsDBCSLeadByte(*p))
{
nXShift++;
p++;
_ASSERTE(p < pEnd);
}
p++;
}
_ASSERTE(nXShift <= csbi.dwCursorPosition.X);
csbi.dwCursorPosition.X = std::max(0,(csbi.dwCursorPosition.X - nXShift));
}
else if (IsWin10() && (NeedLegacyCursorCorrection() || (GetConsoleOutputCP() == CP_UTF8)))
#endif
{
// Temporary workaround for conhost bug!
CHAR_INFO CharsEx[200];
CHAR_INFO* pCharsEx = (cchMax <= countof(CharsEx)) ? CharsEx
: (CHAR_INFO*)calloc(cchMax, sizeof(*pCharsEx));
if (pCharsEx)
{
COORD bufSize = {cchMax, 1}; COORD bufCoord = {0,0};
SMALL_RECT rgn = MakeSmallRect(0, csbi.dwCursorPosition.Y, cchMax-1, csbi.dwCursorPosition.Y);
BOOL bRead = ReadConsoleOutputW(ahConOut, pCharsEx, bufSize, bufCoord, &rgn);
if (bRead)
{
int nXShift = 0;
CHAR_INFO *p = pCharsEx, *pEnd = pCharsEx+cchMax;
// gh-1206: correct position after "こんばんはGood Evening"
while (p < pEnd)
{
if (!(p->Attributes & COMMON_LVB_TRAILING_BYTE)
/*&& get_wcwidth(p->Char.UnicodeChar) == 2*/)
{
_ASSERTE(p < pEnd);
if (((p + 1) < pEnd)
&& (p->Attributes & COMMON_LVB_LEADING_BYTE)
&& ((p+1)->Attributes & COMMON_LVB_TRAILING_BYTE)
&& (p->Char.UnicodeChar == (p+1)->Char.UnicodeChar))
{
p++; nXShift++;
}
_ASSERTE(p < pEnd);
}
p++;
}
_ASSERTE(nXShift <= csbi.dwCursorPosition.X);
csbi.dwCursorPosition.X = std::max<int>(0, (csbi.dwCursorPosition.X - nXShift));
if (pCharsEx != CharsEx)
free(pCharsEx);
}
}
}
if (pChars != Chars)
free(pChars);
}
}
/**
Reload current console palette, IF it WAS NOT specified explicitly before
@param ahConOut << (HANDLE)ghConOut
@result true if palette was successfully retrieved
**/
bool MyLoadConsolePalette(HANDLE ahConOut, CESERVER_CONSOLE_PALETTE& Palette)
{
bool bRc = false;
if (gpSrv->ConsolePalette.bPalletteLoaded)
{
Palette = gpSrv->ConsolePalette;
bRc = true;
}
else
{
Palette.bPalletteLoaded = false;
}
CONSOLE_SCREEN_BUFFER_INFO sbi = {};
MY_CONSOLE_SCREEN_BUFFER_INFOEX sbi_ex = {sizeof(sbi_ex)};
if (apiGetConsoleScreenBufferInfoEx(ahConOut, &sbi_ex))
{
Palette.wAttributes = sbi_ex.wAttributes;
Palette.wPopupAttributes = sbi_ex.wPopupAttributes;
if (!bRc)
{
_ASSERTE(sizeof(Palette.ColorTable) == sizeof(sbi_ex.ColorTable));
memmove(Palette.ColorTable, sbi_ex.ColorTable, sizeof(Palette.ColorTable));
// Store for future use?
// -- gpSrv->ConsolePalette = Palette;
bRc = true;
}
}
else if (GetConsoleScreenBufferInfo(ahConOut, &sbi))
{
Palette.wAttributes = Palette.wPopupAttributes = sbi.wAttributes;
// Load palette from registry?
}
return bRc;
}
WARNING("Use MyGetConsoleScreenBufferInfo instead of GetConsoleScreenBufferInfo");
// Действует аналогично функции WinApi (GetConsoleScreenBufferInfo), но в режиме сервера:
// 1. запрещает (то есть отменяет) максимизацию консольного окна
// 2. корректирует srWindow: сбрасывает горизонтальную прокрутку,
// а если не обнаружен "буферный режим" - то и вертикальную.
BOOL MyGetConsoleScreenBufferInfo(HANDLE ahConOut, PCONSOLE_SCREEN_BUFFER_INFO apsc)
{
BOOL lbRc = FALSE, lbSetRc = TRUE;
DWORD nErrCode = 0;
// ComSpec окно менять НЕ ДОЛЖЕН!
if ((gnRunMode == RM_SERVER || gnRunMode == RM_ALTSERVER)
&& ghConEmuWnd && IsWindow(ghConEmuWnd))
{
// Если юзер случайно нажал максимизацию, когда консольное окно видимо - ничего хорошего не будет
if (IsZoomed(ghConWnd))
{
UndoConsoleWindowZoom();
}
}
SMALL_RECT srRealWindow = {};
CONSOLE_SCREEN_BUFFER_INFO csbi = {};
lbRc = GetConsoleScreenBufferInfo(ahConOut, &csbi);
if (!lbRc)
{
nErrCode = GetLastError();
if (gpLogSize) LogSize(NULL, 0, ":MyGetConsoleScreenBufferInfo(FAIL)");
_ASSERTE(FALSE && "GetConsoleScreenBufferInfo failed, conhost was destroyed?");
goto wrap;
}
if ((csbi.dwSize.X <= 0)
|| (csbi.dwSize.Y <= 0)
|| (csbi.dwSize.Y > LONGOUTPUTHEIGHT_MAX)
)
{
nErrCode = GetLastError();
if (gpLogSize) LogSize(NULL, 0, ":MyGetConsoleScreenBufferInfo(dwSize)");
_ASSERTE(FALSE && "GetConsoleScreenBufferInfo failed, conhost was destroyed?");
goto wrap;
}
if (csbi.srWindow.Left < 0 || csbi.srWindow.Top < 0 || csbi.srWindow.Right < csbi.srWindow.Left || csbi.srWindow.Bottom < csbi.srWindow.Top)
{
nErrCode = GetLastError();
if (gpLogSize) LogSize(NULL, 0, ":MyGetConsoleScreenBufferInfo(srWindow)");
_ASSERTE(FALSE && "GetConsoleScreenBufferInfo failed, Invalid srWindow coordinates");
goto wrap;
}
srRealWindow = csbi.srWindow;
// Issue 373: wmic (Horizontal buffer)
{
TODO("Его надо и из ConEmu обновлять");
if (csbi.dwSize.X && (gnBufferWidth != csbi.dwSize.X))
gnBufferWidth = csbi.dwSize.X;
else if (gnBufferWidth == (csbi.srWindow.Right - csbi.srWindow.Left + 1))
gnBufferWidth = 0;
}
// CONSOLE_FULLSCREEN/*1*/ or CONSOLE_FULLSCREEN_HARDWARE/*2*/
if (pfnGetConsoleDisplayMode && pfnGetConsoleDisplayMode(&gpSrv->dwDisplayMode))
{
// The bug of Windows 10 b9879
if ((gnOsVer == 0x0604) && (gOSVer.dwBuildNumber == 9879))
gpSrv->dwDisplayMode = 0;
if (gpSrv->dwDisplayMode & CONSOLE_FULLSCREEN_HARDWARE)
{
// While in hardware fullscreen - srWindow still shows window region
// as it can be, if returned in GUI mode (I suppose)
//_ASSERTE(!csbi.srWindow.Left && !csbi.srWindow.Top);
csbi.dwSize.X = csbi.srWindow.Right+1-csbi.srWindow.Left;
csbi.dwSize.Y = csbi.srWindow.Bottom+1+csbi.srWindow.Top;
// Log that change
if (gpLogSize)
{
char szLabel[80];
sprintf_c(szLabel, "CONSOLE_FULLSCREEN_HARDWARE{x%08X}", gpSrv->dwDisplayMode);
LogSize(&csbi.dwSize, 0, szLabel);
}
}
}
//
_ASSERTE((csbi.srWindow.Bottom-csbi.srWindow.Top)<200);
// ComSpec окно менять НЕ ДОЛЖЕН!
// ??? Приложениям запрещено менять размер видимой области.
// ??? Размер буфера - могут менять, но не менее чем текущая видимая область
if ((gnRunMode == RM_SERVER || gnRunMode == RM_ALTSERVER) && gpSrv)
{
// Если мы НЕ в ресайзе, проверить максимально допустимый размер консоли
if (!gpSrv->nRequestChangeSize && (gpSrv->crReqSizeNewSize.X > 0) && (gpSrv->crReqSizeNewSize.Y > 0))
{
COORD crMax = MyGetLargestConsoleWindowSize(ghConOut);
// Это может случиться, если пользователь резко уменьшил разрешение экрана
// ??? Польза здесь сомнительная
if (crMax.X > 0 && crMax.X < gpSrv->crReqSizeNewSize.X)
{
gpSrv->crReqSizeNewSize.X = crMax.X;
TODO("Обновить gcrVisibleSize");
}
if (crMax.Y > 0 && crMax.Y < gpSrv->crReqSizeNewSize.Y)
{
gpSrv->crReqSizeNewSize.Y = crMax.Y;
TODO("Обновить gcrVisibleSize");
}
}
}
// Issue 577: Chinese display error on Chinese
// -- GetConsoleScreenBufferInfo возвращает координаты курсора в DBCS, а нам нужен wchar_t !!!
if (csbi.dwSize.X && csbi.dwCursorPosition.X)
{
CorrectDBCSCursorPosition(ahConOut, csbi);
}
// Блокировка видимой области, TopLeft задается из GUI
if ((gnRunMode == RM_SERVER || gnRunMode == RM_ALTSERVER) && gpSrv)
{
// Коррекция srWindow
if (gpSrv->TopLeft.isLocked())
{
SHORT nWidth = (csbi.srWindow.Right - csbi.srWindow.Left + 1);
SHORT nHeight = (csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
if (gpSrv->TopLeft.x >= 0)
{
csbi.srWindow.Right = std::min<int>(csbi.dwSize.X, gpSrv->TopLeft.x + nWidth) - 1;
csbi.srWindow.Left = std::max<int>(0, csbi.srWindow.Right - nWidth + 1);
}
if (gpSrv->TopLeft.y >= 0)
{
csbi.srWindow.Bottom = std::min<int>(csbi.dwSize.Y, gpSrv->TopLeft.y+nHeight) - 1;
csbi.srWindow.Top = std::max<int>(0, csbi.srWindow.Bottom-nHeight+1);
}
}
// Eсли
// a) в прошлый раз курсор БЫЛ видим, а сейчас нет, И
// b) TopLeft не был изменен с тех пор (GUI не прокручивали)
// Это значит, что в консоли, например, нажали Enter в prompt
// или приложение продолжает вывод в консоль, в общем,
// содержимое консоли прокручивается,
// и то же самое нужно сделать в GUI
if (gpSrv->pConsole && gpSrv->TopLeft.isLocked())
{
// Был видим в той области, которая ушла в GUI
if (CoordInSmallRect(gpSrv->pConsole->ConState.sbi.dwCursorPosition, gpSrv->pConsole->ConState.sbi.srWindow)
// и видим сейчас в RealConsole
&& CoordInSmallRect(csbi.dwCursorPosition, srRealWindow)
// но стал НЕ видим в скорректированном (по TopLeft) прямоугольнике
&& !CoordInSmallRect(csbi.dwCursorPosition, csbi.srWindow)
// И TopLeft в GUI не менялся
&& gpSrv->TopLeft.Equal(gpSrv->pConsole->ConState.TopLeft))
{
// Сбросить блокировку и вернуть реальное положение в консоли
gpSrv->TopLeft.Reset();
csbi.srWindow = srRealWindow;
}
}
if (gpSrv->pConsole)
{
gpSrv->pConsole->ConState.TopLeft = gpSrv->TopLeft;
gpSrv->pConsole->ConState.srRealWindow = srRealWindow;
}
}
wrap:
if (apsc)
*apsc = csbi;
// Возвращаем (возможно) скорректированные данные
UNREFERENCED_PARAMETER(nErrCode);
return lbRc;
}
static bool AdaptConsoleFontSize(const COORD& crNewSize)
{
bool lbRc = true;
char szLogInfo[128];
// Minimum console size
int curSizeY = -1, curSizeX = -1;
wchar_t sFontName[LF_FACESIZE] = L"";
bool bCanChangeFontSize = false; // Vista+ only
if (apiGetConsoleFontSize(ghConOut, curSizeY, curSizeX, sFontName) && curSizeY && curSizeX)
{
bCanChangeFontSize = true;
int nMinY = GetSystemMetrics(SM_CYMIN) - GetSystemMetrics(SM_CYSIZEFRAME) - GetSystemMetrics(SM_CYCAPTION);
int nMinX = GetSystemMetrics(SM_CXMIN) - 2*GetSystemMetrics(SM_CXSIZEFRAME);
if ((nMinX > 0) && (nMinY > 0))
{
// Теперь прикинуть, какой размер шрифта нам нужен
int minSizeY = (nMinY / curSizeY);
int minSizeX = (nMinX / curSizeX);
if ((minSizeX > crNewSize.X) || (minSizeY > crNewSize.Y))
{
if (gpLogSize)
{
sprintf_c(szLogInfo, "Need to reduce minSize. Cur={%i,%i}, Req={%i,%i}", minSizeX, minSizeY, crNewSize.X, crNewSize.Y);
LogString(szLogInfo);
}
apiFixFontSizeForBufferSize(ghConOut, crNewSize, szLogInfo, countof(szLogInfo));
LogString(szLogInfo);
apiGetConsoleFontSize(ghConOut, curSizeY, curSizeX, sFontName);
}
}
if (gpLogSize)
{
sprintf_c(szLogInfo, "Console font size H=%i W=%i N=", curSizeY, curSizeX);
int nLen = lstrlenA(szLogInfo);
WideCharToMultiByte(CP_UTF8, 0, sFontName, -1, szLogInfo+nLen, countof(szLogInfo)-nLen, NULL, NULL);
LogFunction(szLogInfo);
}
}
else
{
LogFunction(L"Function GetConsoleFontSize is not available");
}
RECT rcConPos = {0};
COORD crMax = MyGetLargestConsoleWindowSize(ghConOut);
// Если размер превышает допустимый - лучше ничего не делать,
// иначе получается неприятный эффект при попытке AltEnter:
// размер окна становится сильно больше чем был, но FullScreen НЕ включается
//if (crMax.X && crNewSize.X > crMax.X)
// crNewSize.X = crMax.X;
//if (crMax.Y && crNewSize.Y > crMax.Y)
// crNewSize.Y = crMax.Y;
if ((crMax.X && crNewSize.X > crMax.X)
|| (crMax.Y && crNewSize.Y > crMax.Y))
{
if (bCanChangeFontSize)
{
BOOL bChangeRc = apiFixFontSizeForBufferSize(ghConOut, crNewSize, szLogInfo, countof(szLogInfo));
LogString(szLogInfo);
if (bChangeRc)
{
crMax = MyGetLargestConsoleWindowSize(ghConOut);
if (gpLogSize)
{
sprintf_c(szLogInfo, "Largest console size is {%i,%i}", crMax.X, crMax.Y);
LogString(szLogInfo);
}
}
if (!bChangeRc
|| (crMax.X && crNewSize.X > crMax.X)
|| (crMax.Y && crNewSize.Y > crMax.Y))
{
lbRc = false;
LogString("Change console size skipped: can't adapt font");
goto wrap;
}
}
else
{
LogString("Change console size skipped: too large");
lbRc = false;
goto wrap;
}
}
wrap:
return lbRc;
}
// No buffer (scrolling) in the console
// По идее, это только для приложений которые сами меняют высоту буфера
// для работы в "полноэкранном" режиме, типа Far 1.7x или Far 2+ без ключа /w
static bool ApplyConsoleSizeSimple(const COORD& crNewSize, const CONSOLE_SCREEN_BUFFER_INFO& csbi, DWORD& dwErr, bool bForceWriteLog)
{
bool lbRc = true;
dwErr = 0;
DEBUGSTRSIZE(L"SetConsoleSize: ApplyConsoleSizeSimple started");
bool lbNeedChange = (csbi.dwSize.X != crNewSize.X) || (csbi.dwSize.Y != crNewSize.Y)
|| ((csbi.srWindow.Right - csbi.srWindow.Left + 1) != crNewSize.X)
|| ((csbi.srWindow.Bottom - csbi.srWindow.Top + 1) != crNewSize.Y);
RECT rcConPos = {};
GetWindowRect(ghConWnd, &rcConPos);
SMALL_RECT rNewRect = {};
#ifdef _DEBUG
if (!lbNeedChange)
{
int nDbg = 0;
}
#endif
if (lbNeedChange)
{
// Если этого не сделать - размер консоли нельзя УМЕНЬШИТЬ
if (crNewSize.X <= (csbi.srWindow.Right-csbi.srWindow.Left) || crNewSize.Y <= (csbi.srWindow.Bottom-csbi.srWindow.Top))
{
rNewRect.Left = 0; rNewRect.Top = 0;
rNewRect.Right = std::min<int>((crNewSize.X - 1), (csbi.srWindow.Right - csbi.srWindow.Left));
rNewRect.Bottom = std::min<int>((crNewSize.Y - 1), (csbi.srWindow.Bottom - csbi.srWindow.Top));
if (!SetConsoleWindowInfo(ghConOut, TRUE, &rNewRect))
{
// Last chance to shrink visible area of the console if ConApi was failed
MoveWindow(ghConWnd, rcConPos.left, rcConPos.top, 1, 1, 1);
}
}
//specified width and height cannot be less than the width and height of the console screen buffer's window
if (!SetConsoleScreenBufferSize(ghConOut, crNewSize))
{
lbRc = false;
dwErr = GetLastError();
}
//TODO: а если правый нижний край вылезет за пределы экрана?
rNewRect.Left = 0; rNewRect.Top = 0;
rNewRect.Right = crNewSize.X - 1;
rNewRect.Bottom = crNewSize.Y - 1;
if (!SetConsoleWindowInfo(ghConOut, TRUE, &rNewRect))
{
// Non-critical error?
dwErr = GetLastError();
}
}
LogSize(NULL, 0, lbRc ? "ApplyConsoleSizeSimple OK" : "ApplyConsoleSizeSimple FAIL", bForceWriteLog);
return lbRc;
}
static SHORT FindFirstDirtyLine(SHORT anFrom, SHORT anTo, SHORT anWidth, WORD wDefAttrs)
{
SHORT iFound = anFrom;
SHORT iStep = (anTo < anFrom) ? -1 : 1;
HANDLE hCon = ghConOut;
BOOL bReadRc;
CHAR_INFO* pch = (CHAR_INFO*)calloc(anWidth, sizeof(*pch));
COORD crBufSize = {anWidth, 1}, crNil = {};
SMALL_RECT rcRead = {0, anFrom, anWidth-1, anFrom};
BYTE bDefAttr = LOBYTE(wDefAttrs); // Trim to colors only, do not compare extended attributes!
for (rcRead.Top = anFrom; rcRead.Top != anTo; rcRead.Top += iStep)
{
rcRead.Bottom = rcRead.Top;
InterlockedIncrement(&gnInReadConsoleOutput);
bReadRc = ReadConsoleOutput(hCon, pch, crBufSize, crNil, &rcRead);
InterlockedDecrement(&gnInReadConsoleOutput);
if (!bReadRc)
break;
// Is line dirty?
for (SHORT i = 0; i < anWidth; i++)
{
// Non-space char or non-default color/background
if ((pch[i].Char.UnicodeChar != L' ') || (LOBYTE(pch[i].Attributes) != bDefAttr))
{
iFound = rcRead.Top;
goto wrap;
}
}
}
iFound = std::min<SHORT>(anTo, anFrom);
wrap:
SafeFree(pch);
return iFound;
}
// По идее, rNewRect должен на входе содержать текущую видимую область
static void EvalVisibleResizeRect(SMALL_RECT& rNewRect,
SHORT anOldBottom,
const COORD& crNewSize,
bool bCursorInScreen, SHORT nCursorAtBottom,
SHORT nScreenAtBottom,
const CONSOLE_SCREEN_BUFFER_INFO& csbi)
{
// Абсолютная (буферная) координата
const SHORT nMaxX = csbi.dwSize.X-1, nMaxY = csbi.dwSize.Y-1;
// сначала - не трогая rNewRect.Left, вдруг там горизонтальная прокрутка?
// anWidth - желаемая ширина видимой области
rNewRect.Right = rNewRect.Left + crNewSize.X - 1;
// не может выходить за пределы ширины буфера
if (rNewRect.Right > nMaxX)
{
rNewRect.Left = std::max<int>(0, (csbi.dwSize.X - crNewSize.X));
rNewRect.Right = std::min<int>(nMaxX, (rNewRect.Left + crNewSize.X - 1));
}
// Теперь - танцы с вертикалью. Логика такая
// * Если ДО ресайза все видимые строки были заполнены (кейбар фара внизу экрана) - оставить anOldBottom
// * Иначе, если курсор был видим
// * приоритетно - двигать верхнюю границу видимой области (показывать максимум строк из back-scroll-buffer)
// * не допускать, чтобы расстояние между курсором и низом видимой области УМЕНЬШИЛОСЬ до менее чем 2-х строк
// * Иначе если курсор был НЕ видим
// * просто показывать максимум стро из back-scroll-buffer (фиксирую нижнюю границу)
// BTW, сейчас при ресайзе меняется только ширина csbi.dwSize.X (ну, кроме случаев изменения высоты буфера)
if ((nScreenAtBottom <= 0) && (nCursorAtBottom <= 0))
{
// Все просто, фиксируем нижнюю границу по размеру буфера
rNewRect.Bottom = csbi.dwSize.Y-1;
rNewRect.Top = std::max<int>(0, (rNewRect.Bottom - crNewSize.Y + 1));
}
else
{
// Значит консоль еще не дошла до низа
SHORT nRectHeight = (rNewRect.Bottom - rNewRect.Top + 1);
if (nCursorAtBottom > 0)
{
_ASSERTE(nCursorAtBottom<=3);
// Оставить строку с курсором "приклеенной" к нижней границе окна (с макс. отступом nCursorAtBottom строк)
rNewRect.Bottom = std::min<int>(nMaxY, (csbi.dwCursorPosition.Y + nCursorAtBottom - 1));
}
// Уменьшение видимой области
else if (crNewSize.Y < nRectHeight)
{
if ((nScreenAtBottom > 0) && (nScreenAtBottom <= 3))
{
// Оставить nScreenAtBottom строк (включая) между anOldBottom и низом консоли
rNewRect.Bottom = std::min<int>(nMaxY, anOldBottom+nScreenAtBottom-1);
}
else if (anOldBottom > (rNewRect.Top + crNewSize.Y - 1))
{
// Если нижняя граница приблизилась или перекрыла
// нашу старую строку (которая была anOldBottom)
rNewRect.Bottom = std::min<int>(anOldBottom, csbi.dwSize.Y-1);
}
else
{
// Иначе - не трогать верхнюю границу
rNewRect.Bottom = std::min<int>(nMaxY, rNewRect.Top+crNewSize.Y-1);
}
//rNewRect.Top = rNewRect.Bottom-crNewSize.Y+1; // на 0 скорректируем в конце
}
// Увеличение видимой области
else if (crNewSize.Y > nRectHeight)
{
if (nScreenAtBottom > 0)
{
// Оставить nScreenAtBottom строк (включая) между anOldBottom и низом консоли
rNewRect.Bottom = std::min<int>(nMaxY, anOldBottom+nScreenAtBottom-1);
}
//rNewRect.Top = rNewRect.Bottom-crNewSize.Y+1; // на 0 скорректируем в конце
}
// Но курсор не должен уходить за пределы экрана
if (bCursorInScreen && (csbi.dwCursorPosition.Y < (rNewRect.Bottom-crNewSize.Y+1)))
{
rNewRect.Bottom = std::max<int>(0, csbi.dwCursorPosition.Y+crNewSize.Y-1);
}
// And top, will be corrected to (>0) below
rNewRect.Top = rNewRect.Bottom-crNewSize.Y+1;
// Проверка на выход за пределы буфера
if (rNewRect.Bottom > nMaxY)
{
rNewRect.Bottom = nMaxY;
rNewRect.Top = std::max<int>(0, rNewRect.Bottom-crNewSize.Y+1);
}
else if (rNewRect.Top < 0)
{
rNewRect.Top = 0;
rNewRect.Bottom = std::min<int>(nMaxY, rNewRect.Top+crNewSize.Y-1);
}
}
_ASSERTE((rNewRect.Bottom-rNewRect.Top+1) == crNewSize.Y);
}
// There is the buffer (scrolling) in the console
// Ресайз для BufferHeight
static bool ApplyConsoleSizeBuffer(const USHORT BufferHeight, const COORD& crNewSize, const CONSOLE_SCREEN_BUFFER_INFO& csbi, DWORD& dwErr, bool bForceWriteLog)
{
bool lbRc = true;
dwErr = 0;
DEBUGSTRSIZE(L"SetConsoleSize: ApplyConsoleSizeBuffer started");
RECT rcConPos = {};
GetWindowRect(ghConWnd, &rcConPos);
TODO("Horizontal scrolling?");
COORD crHeight = MakeCoord(crNewSize.X, BufferHeight);
SMALL_RECT rcTemp = {};
// По идее (в планах), lbCursorInScreen всегда должен быть true,
// если только само консольное приложение не выполняет прокрутку.
// Сам ConEmu должен "крутить" консоль только виртуально, не трогая физический скролл.
bool lbCursorInScreen = CoordInSmallRect(csbi.dwCursorPosition, csbi.srWindow);
bool lbScreenAtBottom = (csbi.srWindow.Top > 0) && (csbi.srWindow.Bottom >= (csbi.dwSize.Y - 1));
bool lbCursorAtBottom = (lbCursorInScreen && (csbi.dwCursorPosition.Y >= (csbi.srWindow.Bottom - 2)));
SHORT nCursorAtBottom = lbCursorAtBottom ? (csbi.srWindow.Bottom - csbi.dwCursorPosition.Y + 1) : 0;
SHORT nBottomLine = csbi.srWindow.Bottom;
SHORT nScreenAtBottom = 0;
// Прикинуть, где должна будет быть нижняя граница видимой области
if (!lbScreenAtBottom)
{
// Ищем снизу вверх (найти самую нижнюю грязную строку)
SHORT nTo = lbCursorInScreen ? csbi.dwCursorPosition.Y : csbi.srWindow.Top;
SHORT nWidth = (csbi.srWindow.Right - csbi.srWindow.Left + 1);
SHORT nDirtyLine = FindFirstDirtyLine(nBottomLine, nTo, nWidth, csbi.wAttributes);
// Если удачно
if (nDirtyLine >= csbi.srWindow.Top && nDirtyLine < csbi.dwSize.Y)
{
if (lbCursorInScreen)
{
nBottomLine = std::max<int>(nDirtyLine, std::min<int>(csbi.dwCursorPosition.Y+1/*-*/,csbi.srWindow.Bottom));
}
else
{
nBottomLine = nDirtyLine;
}
}
nScreenAtBottom = (csbi.srWindow.Bottom - nBottomLine + 1);
// Чтобы информации НАД курсором не стало меньше чем пустых строк ПОД курсором
if (lbCursorInScreen)
{
if (nScreenAtBottom <= 4)
{
SHORT nAboveLines = (crNewSize.Y - nScreenAtBottom);
if (nAboveLines <= (nScreenAtBottom + 1))
{
nCursorAtBottom = std::max<int>(1, crNewSize.Y - nScreenAtBottom - 1);
}
}
}
}
SMALL_RECT rNewRect = csbi.srWindow;
EvalVisibleResizeRect(rNewRect, nBottomLine, crNewSize, lbCursorInScreen, nCursorAtBottom, nScreenAtBottom, csbi);
#if 0
// Подправим будущую видимую область
if (csbi.dwSize.Y == (csbi.srWindow.Bottom - csbi.srWindow.Top + 1))
{
// Прокрутки сейчас нет, оставляем .Top без изменений!
}
// При изменении высоты буфера (если он уже был включен), нужно скорректировать новую видимую область
else if (rNewRect.Bottom >= (csbi.dwSize.Y - (csbi.srWindow.Bottom - csbi.srWindow.Top)))
{
// Считаем, что рабочая область прижата к низу экрана. Нужно подвинуть .Top
int nBottomLines = (csbi.dwSize.Y - csbi.srWindow.Bottom - 1); // Сколько строк сейчас снизу от видимой области?
SHORT nTop = BufferHeight - crNewSize.Y - nBottomLines;
rNewRect.Top = (nTop > 0) ? nTop : 0;
// .Bottom подправится ниже, перед последним SetConsoleWindowInfo
}
else
{
// Считаем, что верх рабочей области фиксирован, коррекция не требуется
}
#endif
// Если этого не сделать - размер консоли нельзя УМЕНЬШИТЬ
if (crNewSize.X <= (csbi.srWindow.Right-csbi.srWindow.Left)
|| crNewSize.Y <= (csbi.srWindow.Bottom-csbi.srWindow.Top))
{
#if 0
rcTemp.Left = 0;
WARNING("А при уменьшении высоты, тащим нижнюю границе окна вверх, Top глючить не будет?");
rcTemp.Top = std::max(0,(csbi.srWindow.Bottom-crNewSize.Y+1));
rcTemp.Right = std::min((crNewSize.X - 1),(csbi.srWindow.Right-csbi.srWindow.Left));
rcTemp.Bottom = std::min((BufferHeight - 1),(rcTemp.Top+crNewSize.Y-1));//(csbi.srWindow.Bottom-csbi.srWindow.Top)); //-V592
_ASSERTE(((rcTemp.Bottom-rcTemp.Top+1)==crNewSize.Y) && ((rcTemp.Bottom-rcTemp.Top)==(rNewRect.Bottom-rNewRect.Top)));
#endif
if (!SetConsoleWindowInfo(ghConOut, TRUE, &rNewRect))
{
// Last chance to shrink visible area of the console if ConApi was failed
MoveWindow(ghConWnd, rcConPos.left, rcConPos.top, 1, 1, 1);
}
}
// crHeight, а не crNewSize - там "оконные" размеры
if (!SetConsoleScreenBufferSize(ghConOut, crHeight))
{
lbRc = false;
dwErr = GetLastError();
}
// Особенно в Win10 после "заворота строк",
// нужно получить новое реальное состояние консоли после изменения буфера
CONSOLE_SCREEN_BUFFER_INFO csbiNew = {};
if (GetConsoleScreenBufferInfo(ghConOut, &csbiNew))
{
rNewRect = csbiNew.srWindow;
EvalVisibleResizeRect(rNewRect, nBottomLine, crNewSize, lbCursorAtBottom, nCursorAtBottom, nScreenAtBottom, csbiNew);
}
#if 0
// Последняя коррекция видимой области.
// Левую граница - всегда 0 (горизонтальную прокрутку пока не поддерживаем)
// Вертикальное положение - пляшем от rNewRect.Top
rNewRect.Left = 0;
rNewRect.Right = crHeight.X-1;
if (lbScreenAtBottom)
{
}
else if (lbCursorInScreen)
{
}
else
{
TODO("Маркеры для блокировки положения в окне после заворота строк в Win10?");
}
rNewRect.Bottom = std::min((crHeight.Y-1), (rNewRect.Top+gcrVisibleSize.Y-1)); //-V592
#endif
_ASSERTE((rNewRect.Bottom-rNewRect.Top)<200);
if (!SetConsoleWindowInfo(ghConOut, TRUE, &rNewRect))
{
dwErr = GetLastError();
}
LogSize(NULL, 0, lbRc ? "ApplyConsoleSizeBuffer OK" : "ApplyConsoleSizeBuffer FAIL", bForceWriteLog);
return lbRc;
}
void RefillConsoleAttributes(const CONSOLE_SCREEN_BUFFER_INFO& csbi5, WORD OldText, WORD NewText)
{
wchar_t szLog[140];
swprintf_c(szLog, L"RefillConsoleAttributes started Lines=%u Cols=%u Old=x%02X New=x%02X", csbi5.dwSize.Y, csbi5.dwSize.X, OldText, NewText);
LogString(szLog);
// Считать из консоли текущие атрибуты (построчно/поблочно)
// И там, где они совпадают с OldText - заменить на in.SetConColor.NewTextAttributes
DWORD nMaxLines = std::max<int>(1, std::min<int>((8000 / csbi5.dwSize.X), csbi5.dwSize.Y));
WORD* pnAttrs = (WORD*)malloc(nMaxLines*csbi5.dwSize.X*sizeof(*pnAttrs));
if (!pnAttrs)
{
// Memory allocation error
return;
}
PerfCounter c_read = {0}, c_fill = {1};
MPerfCounter perf(2);
BOOL b;
COORD crRead = {0,0};
while (crRead.Y < csbi5.dwSize.Y)
{
DWORD nReadLn = std::min<int>(nMaxLines, (csbi5.dwSize.Y-crRead.Y));
DWORD nReady = 0;
perf.Start(c_read);
b = ReadConsoleOutputAttribute(ghConOut, pnAttrs, nReadLn * csbi5.dwSize.X, crRead, &nReady);
perf.Stop(c_read);
if (!b)
break;
bool bStarted = false;
COORD crFrom = crRead;
//SHORT nLines = (SHORT)(nReady / csbi5.dwSize.X);
DWORD i = 0, iStarted = 0, iWritten;
while (i < nReady)
{
if ((pnAttrs[i] & 0xFF) == OldText)
{
if (!bStarted)
{
_ASSERT(crRead.X == 0);
crFrom.Y = (SHORT)(crRead.Y + (i / csbi5.dwSize.X));
crFrom.X = i % csbi5.dwSize.X;
iStarted = i;
bStarted = true;
}
}
else
{
if (bStarted)
{
bStarted = false;
if (iStarted < i)
{
perf.Start(c_fill);
FillConsoleOutputAttribute(ghConOut, NewText, i - iStarted, crFrom, &iWritten);
perf.Stop(c_fill);
}
}
}
// Next cell checking
i++;
}
// Если хвост остался
if (bStarted && (iStarted < i))
{
perf.Start(c_fill);
FillConsoleOutputAttribute(ghConOut, NewText, i - iStarted, crFrom, &iWritten);
perf.Stop(c_fill);
}
// Next block
crRead.Y += (USHORT)nReadLn;
}
free(pnAttrs);
ULONG l_read_p, l_read = perf.GetCounter(c_read.ID, &l_read_p, NULL, NULL);
ULONG l_fill_p, l_fill = perf.GetCounter(c_fill.ID, &l_fill_p, NULL, NULL);
swprintf_c(szLog, L"RefillConsoleAttributes finished, Reads(%u, %u%%), Fills(%u, %u%%)", l_read, l_read_p, l_fill, l_fill_p);
LogString(szLog);
}
// BufferHeight - высота БУФЕРА (0 - без прокрутки)
// crNewSize - размер ОКНА (ширина окна == ширине буфера)
// rNewRect - для (BufferHeight!=0) определяет new upper-left and lower-right corners of the window
// !!! rNewRect по идее вообще не нужен, за блокировку при прокрутке отвечает nSendTopLine
BOOL SetConsoleSize(USHORT BufferHeight, COORD crNewSize, SMALL_RECT rNewRect, LPCSTR asLabel, bool bForceWriteLog)
{
_ASSERTE(ghConWnd);
_ASSERTE(BufferHeight==0 || BufferHeight>crNewSize.Y); // Otherwise - it will be NOT a bufferheight...
if (!ghConWnd)
{
DEBUGSTRSIZE(L"SetConsoleSize: Skipped due to ghConWnd==NULL");
return FALSE;
}
if (CheckWasFullScreen())
{
DEBUGSTRSIZE(L"SetConsoleSize was skipped due to CONSOLE_FULLSCREEN_HARDWARE");
LogString("SetConsoleSize was skipped due to CONSOLE_FULLSCREEN_HARDWARE");
return FALSE;
}
DWORD dwCurThId = GetCurrentThreadId();
DWORD dwWait = 0;
DWORD dwErr = 0;
if ((gnRunMode == RM_SERVER) || (gnRunMode == RM_ALTSERVER))
{
// Запомним то, что последний раз установил сервер. пригодится
gpSrv->nReqSizeBufferHeight = BufferHeight;
gpSrv->crReqSizeNewSize = crNewSize;
_ASSERTE(gpSrv->crReqSizeNewSize.X!=0);
WARNING("выпилить gpSrv->rReqSizeNewRect и rNewRect");
gpSrv->rReqSizeNewRect = rNewRect;
gpSrv->sReqSizeLabel = asLabel;
gpSrv->bReqSizeForceLog = bForceWriteLog;
// Ресайз выполнять только в нити RefreshThread. Поэтому если нить другая - ждем...
if (gpSrv->dwRefreshThread && dwCurThId != gpSrv->dwRefreshThread)
{
DEBUGSTRSIZE(L"SetConsoleSize: Waiting for RefreshThread");
ResetEvent(gpSrv->hReqSizeChanged);
if (InterlockedIncrement(&gpSrv->nRequestChangeSize) <= 0)
{
_ASSERTE(FALSE && "gpSrv->nRequestChangeSize has invalid value");
gpSrv->nRequestChangeSize = 1;
}
// Ожидание, пока сработает RefreshThread
HANDLE hEvents[2] = {ghQuitEvent, gpSrv->hReqSizeChanged};
DWORD nSizeTimeout = REQSIZE_TIMEOUT;
#ifdef _DEBUG
if (IsDebuggerPresent())
nSizeTimeout = INFINITE;
#endif
dwWait = WaitForMultipleObjects(2, hEvents, FALSE, nSizeTimeout);
// Generally, it must be decremented by RefreshThread...
if ((dwWait == WAIT_TIMEOUT) && (gpSrv->nRequestChangeSize > 0))
{
InterlockedDecrement(&gpSrv->nRequestChangeSize);
}
// Checking invalid value...
if (gpSrv->nRequestChangeSize < 0)
{
// Decremented by RefreshThread and CurrentThread? Must not be...
_ASSERTE(gpSrv->nRequestChangeSize >= 0);
gpSrv->nRequestChangeSize = 0;
}
if (dwWait == WAIT_OBJECT_0)
{
// ghQuitEvent !!
return FALSE;
}
if (dwWait == (WAIT_OBJECT_0+1))
{
return gpSrv->bRequestChangeSizeResult;
}
// ?? Может быть стоит самим попробовать?
return FALSE;
}
}
DEBUGSTRSIZE(L"SetConsoleSize: Started");
MSectionLock RCS;
if (gpSrv->pReqSizeSection && !RCS.Lock(gpSrv->pReqSizeSection, TRUE, 30000))
{
DEBUGSTRSIZE(L"SetConsoleSize: !!!Failed to lock section!!!");
_ASSERTE(FALSE);
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
if (gpLogSize) LogSize(&crNewSize, BufferHeight, asLabel);
_ASSERTE(crNewSize.X>=MIN_CON_WIDTH && crNewSize.Y>=MIN_CON_HEIGHT);
// Проверка минимального размера
if (crNewSize.X</*4*/MIN_CON_WIDTH)
crNewSize.X = /*4*/MIN_CON_WIDTH;
if (crNewSize.Y</*3*/MIN_CON_HEIGHT)
crNewSize.Y = /*3*/MIN_CON_HEIGHT;
CONSOLE_SCREEN_BUFFER_INFO csbi = {};
// Нам нужно реальное состояние консоли, чтобы не поломать ее вид после ресайза
if (!GetConsoleScreenBufferInfo(ghConOut, &csbi))
{
DWORD nErrCode = GetLastError();
DEBUGSTRSIZE(L"SetConsoleSize: !!!GetConsoleScreenBufferInfo failed!!!");
_ASSERTE(FALSE && "GetConsoleScreenBufferInfo was failed");
SetLastError(nErrCode ? nErrCode : ERROR_INVALID_HANDLE);
return FALSE;
}
BOOL lbRc = TRUE;
if (!AdaptConsoleFontSize(crNewSize))
{
DEBUGSTRSIZE(L"SetConsoleSize: !!!AdaptConsoleFontSize failed!!!");
lbRc = FALSE;
goto wrap;
}
// Делаем это ПОСЛЕ MyGetConsoleScreenBufferInfo, т.к. некоторые коррекции размера окна
// она делает ориентируясь на gnBufferHeight
gnBufferHeight = BufferHeight;
// Размер видимой области (слишком большой?)
_ASSERTE(crNewSize.X<=500 && crNewSize.Y<=300);
gcrVisibleSize = crNewSize;
if (gnRunMode == RM_SERVER || gnRunMode == RM_ALTSERVER)
UpdateConsoleMapHeader(L"SetConsoleSize"); // Обновить pConsoleMap.crLockedVisible
if (gnBufferHeight)
{
// В режиме BufferHeight - высота ДОЛЖНА быть больше допустимого размера окна консоли
// иначе мы запутаемся при проверках "буферный ли это режим"...
if (gnBufferHeight <= (csbi.dwMaximumWindowSize.Y * 12 / 10))
gnBufferHeight = std::max<int>(300, (csbi.dwMaximumWindowSize.Y * 12 / 10));
// В режиме cmd сразу уменьшим максимальный FPS
gpSrv->dwLastUserTick = GetTickCount() - USER_IDLE_TIMEOUT - 1;
}
// The resize itself
if (BufferHeight == 0)
{
// No buffer in the console
lbRc = ApplyConsoleSizeSimple(crNewSize, csbi, dwErr, bForceWriteLog);
}
else
{
// Начался ресайз для BufferHeight
lbRc = ApplyConsoleSizeBuffer(gnBufferHeight, crNewSize, csbi, dwErr, bForceWriteLog);
}
#ifdef _DEBUG
DEBUGSTRSIZE(lbRc ? L"SetConsoleSize: FINISHED" : L"SetConsoleSize: !!! FAILED !!!");
#endif
wrap:
gpSrv->bRequestChangeSizeResult = lbRc;
if ((gnRunMode == RM_SERVER) && gpSrv->hRefreshEvent)
{
SetEvent(gpSrv->hRefreshEvent);
}
return lbRc;
}
#if defined(__GNUC__)
extern "C"
#endif
BOOL WINAPI HandlerRoutine(DWORD dwCtrlType)
{
// Log it first
wchar_t szLog[80], szType[20];
switch (dwCtrlType)
{
case CTRL_C_EVENT:
wcscpy_c(szType, L"CTRL_C_EVENT"); break;
case CTRL_BREAK_EVENT:
wcscpy_c(szType, L"CTRL_BREAK_EVENT"); break;
case CTRL_CLOSE_EVENT:
wcscpy_c(szType, L"CTRL_CLOSE_EVENT"); break;
case CTRL_LOGOFF_EVENT:
wcscpy_c(szType, L"CTRL_LOGOFF_EVENT"); break;
case CTRL_SHUTDOWN_EVENT:
wcscpy_c(szType, L"CTRL_SHUTDOWN_EVENT"); break;
default:
msprintf(szType, countof(szType), L"ID=%u", dwCtrlType);
}
wcscpy_c(szLog, L" --- ConsoleCtrlHandler triggered: ");
wcscat_c(szLog, szType);
LogString(szLog);
// Continue processing
//PRINT_COMSPEC(L"HandlerRoutine triggered. Event type=%i\n", dwCtrlType);
if ((dwCtrlType == CTRL_CLOSE_EVENT)
|| (dwCtrlType == CTRL_LOGOFF_EVENT)
|| (dwCtrlType == CTRL_SHUTDOWN_EVENT))
{
PRINT_COMSPEC(L"Console about to be closed\n", 0);
WARNING("Тут бы подождать немного, пока другие консольные процессы завершатся... а то таб закрывается раньше времени");
gbInShutdown = TRUE;
if (gbInExitWaitForKey)
gbStopExitWaitForKey = TRUE;
// Our debugger is running?
if (gpSrv->DbgInfo.bDebuggerActive)
{
// pfnDebugActiveProcessStop is useless, because
// 1. pfnDebugSetProcessKillOnExit was called already
// 2. we can debug more than a one process
//gpSrv->DbgInfo.bDebuggerActive = FALSE;
}
else
{
#if 0
wchar_t szTitle[128]; wsprintf(szTitle, L"ConEmuC, PID=%u", GetCurrentProcessId());
//MessageBox(NULL, L"CTRL_CLOSE_EVENT in ConEmuC", szTitle, MB_SYSTEMMODAL);
DWORD nWait = WaitForSingleObject(ghExitQueryEvent, CLOSE_CONSOLE_TIMEOUT);
if (nWait == WAIT_OBJECT_0)
{
#ifdef _DEBUG
OutputDebugString(L"All console processes was terminated\n");
#endif
}
else
{
// Поскольку мы (сервер) сейчас свалимся, то нужно показать
// консольное окно, раз в нем остались какие-то процессы
EmergencyShow();
}
#endif
// trick to let ConsoleMain2() finish correctly
ExitThread(1);
}
}
else if ((dwCtrlType == CTRL_C_EVENT) || (dwCtrlType == CTRL_BREAK_EVENT))
{
if (gbTerminateOnCtrlBreak)
{
PRINT_COMSPEC(L"Ctrl+Break received, server will be terminated\n", 0);
gbInShutdown = TRUE;
}
else if (gpSrv->DbgInfo.bDebugProcess)
{
DWORD nWait = WaitForSingleObject(gpSrv->hRootProcess, 0);
#ifdef _DEBUG
DWORD nErr = GetLastError();
#endif
if (nWait == WAIT_OBJECT_0)
{
_ASSERTE(gbTerminateOnCtrlBreak==FALSE);
PRINT_COMSPEC(L"Ctrl+Break received, debugger will be stopped\n", 0);
//if (pfnDebugActiveProcessStop) pfnDebugActiveProcessStop(gpSrv->dwRootProcess);
//gpSrv->DbgInfo.bDebuggerActive = FALSE;
//gbInShutdown = TRUE;
SetTerminateEvent(ste_HandlerRoutine);
}
else
{
GenerateMiniDumpFromCtrlBreak();
}
}
}
return TRUE;
}
int GetProcessCount(DWORD *rpdwPID, UINT nMaxCount)
{
if (!rpdwPID || (nMaxCount < 3))
{
_ASSERTE(rpdwPID && (nMaxCount >= 3));
return gpSrv->processes->nProcessCount;
}
UINT nRetCount = 0;
rpdwPID[nRetCount++] = gnSelfPID;
// Windows 7 and higher: there is "conhost.exe"
if (gnOsVer >= 0x0601)
{
#if 0
typedef BOOL (WINAPI* GetNamedPipeServerProcessId_t)(HANDLE Pipe,PULONG ServerProcessId);
HMODULE hKernel = GetModuleHandle(L"kernel32.dll");
GetNamedPipeServerProcessId_t GetNamedPipeServerProcessId_f = hKernel
? (GetNamedPipeServerProcessId_t)GetProcAddress(hKernel, "GetNamedPipeServerProcessId") : NULL;
HANDLE hOut; BOOL bSrv = FALSE; ULONG nSrvPid = 0;
_ASSERTE(FALSE && "calling GetNamedPipeServerProcessId_f");
if (GetNamedPipeServerProcessId_f)
{
hOut = (HANDLE)ghConOut;
if (hOut)
{
bSrv = GetNamedPipeServerProcessId_f(hOut, &nSrvPid);
}
}
#endif
if (!gpSrv->processes->nConhostPID)
{
// Найти порожденный conhost.exe
//TODO: Reuse MToolHelp.h
HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (h && (h != INVALID_HANDLE_VALUE))
{
// Учтем альтернативные серверы (Far/Telnet/...)
DWORD nSrvPID = gpSrv->dwMainServerPID ? gpSrv->dwMainServerPID : gnSelfPID;
PROCESSENTRY32 PI = {sizeof(PI)};
if (Process32First(h, &PI))
{
do {
if ((PI.th32ParentProcessID == nSrvPID)
&& (lstrcmpi(PI.szExeFile, L"conhost.exe") == 0))
{
gpSrv->processes->nConhostPID = PI.th32ProcessID;
break;
}
} while (Process32Next(h, &PI));
}
CloseHandle(h);
}
if (!gpSrv->processes->nConhostPID)
gpSrv->processes->nConhostPID = (UINT)-1;
}
if (gpSrv->processes->nConhostPID && (gpSrv->processes->nConhostPID != (UINT)-1))
{
rpdwPID[nRetCount++] = gpSrv->processes->nConhostPID;
}
}
MSectionLock CS;
UINT nCurCount = 0;
if (CS.Lock(gpSrv->processes->csProc, TRUE/*abExclusive*/, 200))
{
nCurCount = gpSrv->processes->nProcessCount;
for (INT_PTR i1 = (nCurCount-1); (i1 >= 0) && (nRetCount < nMaxCount); i1--)
{
DWORD PID = gpSrv->processes->pnProcesses[i1];
if (PID && PID != gnSelfPID)
{
rpdwPID[nRetCount++] = PID;
}
}
}
for (size_t i = nRetCount; i < nMaxCount; i++)
{
rpdwPID[i] = 0;
}
//if (nSize > nMaxCount)
//{
// memset(rpdwPID, 0, sizeof(DWORD)*nMaxCount);
// rpdwPID[0] = gnSelfPID;
// for(int i1=0, i2=(nMaxCount-1); i1<(int)nSize && i2>0; i1++, i2--)
// rpdwPID[i2] = gpSrv->processes->pnProcesses[i1]; //-V108
// nSize = nMaxCount;
//}
//else
//{
// memmove(rpdwPID, gpSrv->processes->pnProcesses, sizeof(DWORD)*nSize);
// for (UINT i=nSize; i<nMaxCount; i++)
// rpdwPID[i] = 0; //-V108
//}
_ASSERTE(rpdwPID[0]);
return nRetCount;
}
void _printf(LPCSTR asFormat, DWORD dw1, DWORD dw2, LPCWSTR asAddLine)
{
char szError[MAX_PATH];
sprintf_c(szError, asFormat, dw1, dw2);
_printf(szError);
if (asAddLine)
{
_wprintf(asAddLine);
_printf("\n");
}
}
void _printf(LPCSTR asFormat, DWORD dwErr, LPCWSTR asAddLine)
{
char szError[MAX_PATH];
sprintf_c(szError, asFormat, dwErr);
_printf(szError);
if (asAddLine)
{
_wprintf(asAddLine);
_printf("\n");
}
}
void _printf(LPCSTR asFormat, DWORD dwErr)
{
char szError[MAX_PATH];
sprintf_c(szError, asFormat, dwErr);
_printf(szError);
}
void _printf(LPCSTR asBuffer)
{
if (!asBuffer) return;
int nAllLen = lstrlenA(asBuffer);
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD dwWritten = 0;
DEBUGTEST(BOOL bWriteRC =)
WriteFile(hOut, asBuffer, nAllLen, &dwWritten, 0);
UNREFERENCED_PARAMETER(dwWritten);
}
void print_error(DWORD dwErr/*= 0*/, LPCSTR asFormat/*= NULL*/)
{
if (!dwErr)
dwErr = GetLastError();
wchar_t* lpMsgBuf = NULL;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwErr, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&lpMsgBuf, 0, NULL);
_printf(asFormat ? asFormat : "\nErrCode=0x%08X, Description:\n", dwErr);
_wprintf((!lpMsgBuf || !*lpMsgBuf) ? L"<Unknown error>" : lpMsgBuf);
if (lpMsgBuf) LocalFree(lpMsgBuf);
SetLastError(dwErr);
}
bool IsOutputRedirected()
{
static int isRedirected = 0;
if (isRedirected)
{
return (isRedirected == 2);
}
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO sbi = {};
BOOL bIsConsole = GetConsoleScreenBufferInfo(hOut, &sbi);
if (bIsConsole)
{
isRedirected = 1;
return false;
}
else
{
isRedirected = 2;
return true;
}
}
void _wprintf(LPCWSTR asBuffer)
{
if (!asBuffer) return;
WriteOutput(asBuffer);
}
void DisableAutoConfirmExit(BOOL abFromFarPlugin)
{
// Консоль могла быть приаттачена к GUI в тот момент, когда сервер ожидает
// от юзера подтверждение закрытия консоли
if (!gbInExitWaitForKey)
{
_ASSERTE(gnConfirmExitParm==0 || abFromFarPlugin);
gbAutoDisableConfirmExit = FALSE; gbAlwaysConfirmExit = FALSE;
// менять nProcessStartTick не нужно. проверка только по флажкам
//gpSrv->nProcessStartTick = GetTickCount() - 2*CHECK_ROOTSTART_TIMEOUT;
}
}
bool IsKeyboardLayoutChanged(DWORD& pdwLayout, LPDWORD pdwErrCode /*= NULL*/)
{
bool bChanged = false;
if (!gpSrv)
{
_ASSERTE(gpSrv!=NULL);
return false;
}
static bool bGetConsoleKeyboardLayoutNameImplemented = true;
if (bGetConsoleKeyboardLayoutNameImplemented && pfnGetConsoleKeyboardLayoutName)
{
wchar_t szCurKeybLayout[32] = L"";
//#ifdef _DEBUG
//wchar_t szDbgKeybLayout[KL_NAMELENGTH/*==9*/];
//BOOL lbGetRC = GetKeyboardLayoutName(szDbgKeybLayout); // -- не дает эффекта, поскольку "на процесс", а не на консоль
//#endif
// The expected result of GetConsoleKeyboardLayoutName is like "00000419"
BOOL bConApiRc = pfnGetConsoleKeyboardLayoutName(szCurKeybLayout) && szCurKeybLayout[0];
DWORD nErr = bConApiRc ? 0 : GetLastError();
if (pdwErrCode)
*pdwErrCode = nErr;
/*
if (!bConApiRc && (nErr == ERROR_GEN_FAILURE))
{
_ASSERTE(FALSE && "ConsKeybLayout failed");
MModule kernel(GetModuleHandle(L"kernel32.dll"));
BOOL (WINAPI* getLayoutName)(LPWSTR,int);
if (kernel.GetProcAddress("GetConsoleKeyboardLayoutNameW", getLayoutName))
{
bConApiRc = getLayoutName(szCurKeybLayout, countof(szCurKeybLayout));
nErr = bConApiRc ? 0 : GetLastError();
}
}
*/
if (!bConApiRc)
{
// If GetConsoleKeyboardLayoutName is not implemented in Windows, ERROR_MR_MID_NOT_FOUND or E_NOTIMPL will be returned.
// (there is no matching DOS/Win32 error code for NTSTATUS code returned)
// When this happens, we don't want to continue to call the function.
if (nErr == ERROR_MR_MID_NOT_FOUND || LOWORD(nErr) == LOWORD(E_NOTIMPL))
{
bGetConsoleKeyboardLayoutNameImplemented = false;
}
if (gpSrv->szKeybLayout[0])
{
// Log only first error per session
wcscpy_c(szCurKeybLayout, gpSrv->szKeybLayout);
}
else
{
wchar_t szErr[80];
swprintf_c(szErr, L"ConsKeybLayout failed with code=%u forcing to GetKeyboardLayoutName or 0409", nErr);
_ASSERTE(!bGetConsoleKeyboardLayoutNameImplemented && "ConsKeybLayout failed");
LogString(szErr);
if (!GetKeyboardLayoutName(szCurKeybLayout) || (szCurKeybLayout[0] == 0))
{
wcscpy_c(szCurKeybLayout, L"00000419");
}
}
}
if (szCurKeybLayout[0])
{
if (lstrcmpW(szCurKeybLayout, gpSrv->szKeybLayout))
{
#ifdef _DEBUG
wchar_t szDbg[128];
swprintf_c(szDbg,
L"ConEmuC: InputLayoutChanged (GetConsoleKeyboardLayoutName returns) '%s'\n",
szCurKeybLayout);
OutputDebugString(szDbg);
#endif
if (gpLogSize)
{
char szInfo[128]; wchar_t szWide[128];
swprintf_c(szWide, L"ConsKeybLayout changed from %s to %s", gpSrv->szKeybLayout, szCurKeybLayout);
WideCharToMultiByte(CP_ACP,0,szWide,-1,szInfo,128,0,0);
LogFunction(szInfo);
}
// Сменился
wcscpy_c(gpSrv->szKeybLayout, szCurKeybLayout);
bChanged = true;
}
}
}
else if (pdwErrCode)
{
*pdwErrCode = (DWORD)-1;
}
// The result, if possible
{
wchar_t *pszEnd = NULL; //szCurKeybLayout+8;
//WARNING("BUGBUG: 16 цифр не вернет"); -- тут именно 8 цифр. Это LayoutNAME, а не string(HKL)
// LayoutName: "00000409", "00010409", ...
// А HKL от него отличается, так что передаем DWORD
// HKL в x64 выглядит как: "0x0000000000020409", "0xFFFFFFFFF0010409"
pdwLayout = wcstoul(gpSrv->szKeybLayout, &pszEnd, 16);
}
return bChanged;
}
//WARNING("BUGBUG: x64 US-Dvorak"); - done
void CheckKeyboardLayout()
{
DWORD dwLayout = 0;
//WARNING("BUGBUG: 16 цифр не вернет"); -- тут именно 8 цифр. Это LayoutNAME, а не string(HKL)
// LayoutName: "00000409", "00010409", ...
// А HKL от него отличается, так что передаем DWORD
// HKL в x64 выглядит как: "0x0000000000020409", "0xFFFFFFFFF0010409"
if (IsKeyboardLayoutChanged(dwLayout))
{
// Сменился, Отошлем в GUI
CESERVER_REQ* pIn = ExecuteNewCmd(CECMD_LANGCHANGE,sizeof(CESERVER_REQ_HDR)+sizeof(DWORD)); //-V119
if (pIn)
{
//memmove(pIn->Data, &dwLayout, 4);
pIn->dwData[0] = dwLayout;
CESERVER_REQ* pOut = ExecuteGuiCmd(ghConWnd, pIn, ghConWnd);
ExecuteFreeResult(pOut);
ExecuteFreeResult(pIn);
}
}
}
/*
LPVOID calloc(size_t nCount, size_t nSize)
{
#ifdef _DEBUG
//HeapValidate(ghHeap, 0, NULL);
#endif
size_t nWhole = nCount * nSize;
_ASSERTE(nWhole>0);
LPVOID ptr = HeapAlloc ( ghHeap, HEAP_GENERATE_EXCEPTIONS|HEAP_ZERO_MEMORY, nWhole );
#ifdef HEAP_LOGGING
wchar_t szDbg[64];
swprintf_c(szDbg, L"%i: ALLOCATED 0x%08X..0x%08X (%i bytes)\n", GetCurrentThreadId(), (DWORD)ptr, ((DWORD)ptr)+nWhole, nWhole);
DEBUGSTR(szDbg);
#endif
#ifdef _DEBUG
HeapValidate(ghHeap, 0, NULL);
if (ptr)
{
gnHeapUsed += nWhole;
if (gnHeapMax < gnHeapUsed)
gnHeapMax = gnHeapUsed;
}
#endif
return ptr;
}
void free(LPVOID ptr)
{
if (ptr && ghHeap)
{
#ifdef _DEBUG
//HeapValidate(ghHeap, 0, NULL);
size_t nMemSize = HeapSize(ghHeap, 0, ptr);
#endif
#ifdef HEAP_LOGGING
wchar_t szDbg[64];
swprintf_c(szDbg, L"%i: FREE BLOCK 0x%08X..0x%08X (%i bytes)\n", GetCurrentThreadId(), (DWORD)ptr, ((DWORD)ptr)+nMemSize, nMemSize);
DEBUGSTR(szDbg);
#endif
HeapFree ( ghHeap, 0, ptr );
#ifdef _DEBUG
HeapValidate(ghHeap, 0, NULL);
if (gnHeapUsed > nMemSize)
gnHeapUsed -= nMemSize;
#endif
}
}
*/
/* Используются как extern в ConEmuCheck.cpp */
/*
LPVOID _calloc(size_t nCount,size_t nSize) {
return calloc(nCount,nSize);
}
LPVOID _malloc(size_t nCount) {
return calloc(nCount,1);
}
void _free(LPVOID ptr) {
free(ptr);
}
*/
/*
void * __cdecl operator new(size_t _Size)
{
void * p = calloc(_Size,1);
return p;
}
void __cdecl operator delete(void *p)
{
free(p);
}
*/
| 210,988 | 98,284 |
// System.Net.IPEndPoint.MaxPort; System.Net.IPEndPoint.MinPort;
// System.Net.IPEndPoint.AddressFamily; System.Net.IPEndPoint.IPEndPoint(long,int)
// System.Net.IPEndPoint.Address; System.Net.IPEndPoint.Port;
/*This program demonstrates the properties 'MaxPort', 'MinPort','Address','Port'
and 'AddressFamily' and a constructor 'IPEndPoint(long,int)' of class 'IPEndPoint'.
A procedure DoSocketGet is created which internally uses a socket to transmit http "Get" requests to a Web resource.
The program accepts a resource Url, Resolves it to obtain 'IPAddress',Constructs 'IPEndPoint' instance using this
'IPAddress' and port 80.Invokes DoSocketGet procedure to obtain a response and displays the response to a console.
It then accepts another Url, Resolves it to obtain 'IPAddress'. Assigns this IPAddress and port to the 'IPEndPoint'
and again invokes DoSocketGet to obtain a response and display.
*/
#using <System.dll>
using namespace System;
using namespace System::Net;
using namespace System::Text;
using namespace System::Net::Sockets;
using namespace System::Runtime::InteropServices;
String^ DoSocketGet( IPEndPoint^ hostIPEndPoint, String^ getString ); // forward reference
int main()
{
try
{
Console::Write( "\nPlease enter an INTRANET Url as shown: [e.g. www.microsoft.com]:" );
String^ hostString1 = Console::ReadLine();
// <Snippet1>
// <Snippet2>
// <Snippet3>
// <Snippet4>
IPAddress^ hostIPAddress1 = (Dns::Resolve( hostString1 ))->AddressList[ 0 ];
Console::WriteLine( hostIPAddress1 );
IPEndPoint^ hostIPEndPoint = gcnew IPEndPoint( hostIPAddress1,80 );
Console::WriteLine( "\nIPEndPoint information:{0}", hostIPEndPoint );
Console::WriteLine( "\n\tMaximum allowed Port Address :{0}", IPEndPoint::MaxPort );
Console::WriteLine( "\n\tMinimum allowed Port Address :{0}", (int^)IPEndPoint::MinPort );
Console::WriteLine( "\n\tAddress Family :{0}", hostIPEndPoint->AddressFamily );
// </Snippet4>
Console::Write( "\nPress Enter to continue" );
Console::ReadLine();
String^ getString = String::Format( "GET / HTTP/1.1\r\nHost: {0}\r\nConnection: Close\r\n\r\n", hostString1 );
String^ pageContent = DoSocketGet( hostIPEndPoint, getString );
if ( pageContent != nullptr )
{
Console::WriteLine( "Default HTML page on {0} is:\r\n{1}", hostString1, pageContent );
}
// </Snippet3>
// </Snippet2>
// </Snippet1>
Console::Write( "\n\n\nPlease enter another INTRANET Url as shown[e.g. www.microsoft.com]: " );
String^ hostString2 = Console::ReadLine();
// <Snippet5>
// <Snippet6>
IPAddress^ hostIPAddress2 = (Dns::Resolve( hostString2 ))->AddressList[ 0 ];
hostIPEndPoint->Address = hostIPAddress2;
hostIPEndPoint->Port = 80;
getString = String::Format( "GET / HTTP/1.1\r\nHost: {0}\r\nConnection: Close\r\n\r\n", hostString2 );
pageContent = DoSocketGet( hostIPEndPoint, getString );
if ( pageContent != nullptr )
{
Console::WriteLine( "Default HTML page on {0} is:\r\n{1}", hostString2, pageContent );
}
// </Snippet6>
// </Snippet5>
}
catch ( SocketException^ e )
{
Console::WriteLine( "SocketException caught!!!" );
Console::WriteLine( "Source : {0}", e->Source );
Console::WriteLine( "Message : {0}", e->Message );
}
catch ( Exception^ e )
{
Console::WriteLine( "Exception caught!!!" );
Console::WriteLine( "Message : {0}", e->Message );
}
}
String^ DoSocketGet( IPEndPoint^ hostIPEndPoint, String^ getString )
{
try
{
// Set up variables and String to write to the server.
Encoding^ ASCII = Encoding::ASCII;
array<Byte>^ byteGet = ASCII->GetBytes( getString );
array<Byte>^ recvBytes = gcnew array<Byte>(256);
String^ strRetPage = nullptr;
// Create the Socket for sending data over TCP.
Socket^ mySocket = gcnew Socket( AddressFamily::InterNetwork,
SocketType::Stream,ProtocolType::Tcp );
// Connect to host using IPEndPoint.
mySocket->Connect( hostIPEndPoint );
// Send the GET text to the host.
mySocket->Send( byteGet, byteGet->Length, (SocketFlags)( 0 ) );
// Receive the page, loop until all bytes are received.
Int32 byteCount = mySocket->Receive( recvBytes, recvBytes->Length, (SocketFlags)( 0 ) );
strRetPage = String::Concat( strRetPage, ASCII->GetString( recvBytes, 0, byteCount ) );
while ( byteCount > 0 )
{
byteCount = mySocket->Receive( recvBytes, recvBytes->Length, (SocketFlags)( 0 ) );
strRetPage = String::Concat( strRetPage, ASCII->GetString( recvBytes, 0, byteCount ) );
}
return strRetPage;
}
catch ( Exception^ e )
{
Console::WriteLine( "Exception : {0}", e->Message );
Console::WriteLine( "WinSock Error : {0}", Convert::ToString( Marshal::GetLastWin32Error() ) );
return nullptr;
}
}
| 4,968 | 1,586 |
// Copyright 2014 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 "net/third_party/quiche/src/quic/tools/quic_toy_server.h"
#include <utility>
#include <vector>
#include "net/third_party/quiche/src/quic/core/quic_versions.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_default_proof_providers.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_socket_address.h"
#include "net/third_party/quiche/src/quic/tools/quic_memory_cache_backend.h"
DEFINE_QUIC_COMMAND_LINE_FLAG(int32_t,
port,
6121,
"The port the quic server will listen on.");
DEFINE_QUIC_COMMAND_LINE_FLAG(
std::string,
quic_response_cache_dir,
"",
"Specifies the directory used during QuicHttpResponseCache "
"construction to seed the cache. Cache directory can be "
"generated using `wget -p --save-headers <url>`");
DEFINE_QUIC_COMMAND_LINE_FLAG(
bool,
generate_dynamic_responses,
false,
"If true, then URLs which have a numeric path will send a dynamically "
"generated response of that many bytes.");
DEFINE_QUIC_COMMAND_LINE_FLAG(bool,
quic_ietf_draft,
false,
"Use the IETF draft version. This also enables "
"required internal QUIC flags.");
namespace quic {
std::unique_ptr<quic::QuicSimpleServerBackend>
QuicToyServer::MemoryCacheBackendFactory::CreateBackend() {
auto memory_cache_backend = std::make_unique<QuicMemoryCacheBackend>();
if (GetQuicFlag(FLAGS_generate_dynamic_responses)) {
memory_cache_backend->GenerateDynamicResponses();
}
if (!GetQuicFlag(FLAGS_quic_response_cache_dir).empty()) {
memory_cache_backend->InitializeBackend(
GetQuicFlag(FLAGS_quic_response_cache_dir));
}
return memory_cache_backend;
}
QuicToyServer::QuicToyServer(BackendFactory* backend_factory,
ServerFactory* server_factory)
: backend_factory_(backend_factory), server_factory_(server_factory) {}
int QuicToyServer::Start() {
ParsedQuicVersionVector supported_versions;
if (GetQuicFlag(FLAGS_quic_ietf_draft)) {
QuicVersionInitializeSupportForIetfDraft();
ParsedQuicVersion version(PROTOCOL_TLS1_3, QUIC_VERSION_99);
QuicEnableVersion(version);
supported_versions = {version};
} else {
supported_versions = AllSupportedVersions();
}
auto proof_source = quic::CreateDefaultProofSource();
auto backend = backend_factory_->CreateBackend();
auto server = server_factory_->CreateServer(
backend.get(), std::move(proof_source), supported_versions);
if (!server->CreateUDPSocketAndListen(quic::QuicSocketAddress(
quic::QuicIpAddress::Any6(), GetQuicFlag(FLAGS_port)))) {
return 1;
}
server->HandleEventsForever();
return 0;
}
} // namespace quic
| 3,091 | 1,003 |
#include <gtest/gtest.h>
#include <vector>
#include <spcppl/ranges/wrappers.hpp>
#include <spcppl/ranges/Range.hpp>
TEST(WrappersTest, Reversed) {
EXPECT_EQ(reversed(std::vector<int>{5, 7, 2, 3}), (std::vector<int>{3, 2, 7, 5}));
}
TEST(WrappersTest, Sorted) {
EXPECT_EQ(sorted(std::vector<int>{5, 7, 2, 3}), (std::vector<int>{2, 3, 5, 7}));
}
TEST(WrapperTest, SortedWithComparator) {
EXPECT_EQ(sorted(std::vector<int>{5, 7, 2, 3}, std::greater<int>()), (std::vector<int>{7, 5, 3, 2}));
}
TEST(WrapperTest, Unique) {
std::vector<int> v = {5, 7, 7, 7, 3};
unique(v);
EXPECT_EQ(v, (std::vector<int>{5, 7, 3}));
}
TEST(WrapperTest, UniquePreservesNotAdjascentElements) {
std::vector<int> v = {1, 2, 1};
std::vector<int> original_v = v;
unique(v);
EXPECT_EQ(v, original_v);
}
TEST(WrapperTest, FindsMaxElement) {
std::vector<int> v = {5, 7, 3};
EXPECT_EQ(*max_element(v), 7);
}
TEST(WrapperTest, MaxOfEmptyRangeIsBegin) {
std::vector<int> v;
EXPECT_EQ(max_element(v), v.begin());
}
TEST(WrapperTest, FindsMinElement) {
std::vector<int> v = {5, 7, 3};
EXPECT_EQ(*min_element(v), 3);
}
TEST(WrapperTest, MinOfEmptyRangeIsBegin) {
std::vector<int> v;
EXPECT_EQ(min_element(v), v.begin());
}
TEST(WrapperTest, FindsMaxOfPartOfRange) {
std::vector<int> v = {100, 1, 2, 5, 0, 15, -1};
EXPECT_EQ(*max_element(make_range(v.begin() + 1, v.begin() + 4)), 5);
}
TEST(WrappersTest, FindsNextPermutation) {
std::vector<int> v = {1, 3, 2};
EXPECT_TRUE(next_permutation(v));
EXPECT_EQ(v, (std::vector<int>{2, 1, 3}));
}
TEST(WrappersTest, NextPermuationCyclesAfterLastPermutation) {
std::vector<int> v = {3, 2, 1};
EXPECT_FALSE(next_permutation(v));
EXPECT_EQ(v, (std::vector<int>{1, 2, 3}));
}
| 1,715 | 833 |
#pragma once
#include <fc/variant.hpp>
#include <fc/container/flat_fwd.hpp>
#include <fc/container/container_detail.hpp>
#include <fc/crypto/hex.hpp>
namespace fc {
namespace raw {
template<typename Stream, typename T, typename A>
void
pack(Stream& s, const boost::container::vector<T, A>& value) {
FC_ASSERT(value.size() <= MAX_NUM_ARRAY_ELEMENTS);
pack(s, unsigned_int((uint32_t)value.size()));
if(!std::is_fundamental<T>::value) {
for(const auto& item : value) {
pack(s, item);
}
}
else if(value.size()) {
s.write((const char*)value.data(), value.size());
}
}
template<typename Stream, typename T, typename A>
void
unpack(Stream& s, boost::container::vector<T, A>& value) {
unsigned_int size;
unpack(s, size);
FC_ASSERT(size.value <= MAX_NUM_ARRAY_ELEMENTS);
value.clear();
value.resize(size.value);
if(!std::is_fundamental<T>::value) {
for(auto& item : value) {
unpack(s, item);
}
}
else if(value.size()) {
s.read((char*)value.data(), value.size());
}
}
template<typename Stream, typename A>
void
pack(Stream& s, const boost::container::vector<char, A>& value) {
FC_ASSERT(value.size() <= MAX_SIZE_OF_BYTE_ARRAYS);
pack(s, unsigned_int((uint32_t)value.size()));
if(value.size())
s.write((const char*)value.data(), value.size());
}
template<typename Stream, typename A>
void
unpack(Stream& s, boost::container::vector<char, A>& value) {
unsigned_int size;
unpack(s, size);
FC_ASSERT(size.value <= MAX_SIZE_OF_BYTE_ARRAYS);
value.clear();
value.resize(size.value);
if(value.size())
s.read((char*)value.data(), value.size());
}
template<typename Stream, typename T, typename... U>
void
pack(Stream& s, const flat_set<T, U...>& value) {
detail::pack_set(s, value);
}
template<typename Stream, typename T, typename... U>
void
unpack(Stream& s, flat_set<T, U...>& value) {
detail::unpack_flat_set(s, value);
}
template<typename Stream, typename K, typename V, typename... U>
void
pack(Stream& s, const flat_map<K, V, U...>& value) {
detail::pack_map(s, value);
}
template<typename Stream, typename K, typename V, typename... U>
void
unpack(Stream& s, flat_map<K, V, U...>& value) {
detail::unpack_flat_map(s, value);
}
} // namespace raw
template<typename T, typename... U>
void
to_variant(const boost::container::vector<T, U...>& vec, fc::variant& vo) {
FC_ASSERT(vec.size() <= MAX_NUM_ARRAY_ELEMENTS);
variants vars;
vars.reserve(vec.size());
for(const auto& item : vec) {
vars.emplace_back(item);
}
vo = std::move(vars);
}
template<typename T, typename... U>
void
from_variant(const fc::variant& v, boost::container::vector<T, U...>& vec) {
const variants& vars = v.get_array();
FC_ASSERT(vars.size() <= MAX_NUM_ARRAY_ELEMENTS);
vec.clear();
vec.resize(vars.size());
for(uint32_t i = 0; i < vars.size(); ++i) {
from_variant(vars[i], vec[i]);
}
}
template<typename... U>
void
to_variant(const boost::container::vector<char, U...>& vec, fc::variant& vo) {
FC_ASSERT(vec.size() <= MAX_SIZE_OF_BYTE_ARRAYS);
if(vec.size())
vo = variant(fc::to_hex(vec.data(), vec.size()));
else
vo = "";
}
template<typename... U>
void
from_variant(const fc::variant& v, boost::container::vector<char, U...>& vec) {
const auto& str = v.get_string();
FC_ASSERT(str.size() <= 2 * MAX_SIZE_OF_BYTE_ARRAYS); // Doubled because hex strings needs two characters per byte
vec.resize(str.size() / 2);
if(vec.size()) {
size_t r = fc::from_hex(str, vec.data(), vec.size());
FC_ASSERT(r == vec.size());
}
}
template<typename T, typename... U>
void
to_variant(const flat_set<T, U...>& s, fc::variant& vo) {
detail::to_variant_from_set(s, vo);
}
template<typename T, typename... U>
void
from_variant(const fc::variant& v, flat_set<T, U...>& s) {
detail::from_variant_to_flat_set(v, s);
}
template<typename K, typename V, typename... U>
void
to_variant(const flat_map<K, V, U...>& m, fc::variant& vo) {
detail::to_variant_from_map(m, vo);
}
template<typename K, typename V, typename... U>
void
from_variant(const variant& v, flat_map<K, V, U...>& m) {
detail::from_variant_to_flat_map(v, m);
}
} // namespace fc
| 4,343 | 1,604 |
#include <string>
using std::string;
class Solution {
public:
char findTheDifference(const string s, const string t) {
size_t dict_s[26] = {0};
size_t dict_t[26] = {0};
for (const char ch : s) ++dict_s[ch - 'a'];
for (const char ch : t) ++dict_t[ch - 'a'];
for (size_t i = 0; i < 26; ++i)
if (dict_s[i] != dict_t[i]) return static_cast<char>(i + 'a');
return '?';
}
private:
char moreGeneralFunction(const string s, const string t) {
size_t dict_s[0x100] = {0};
size_t dict_t[0x100] = {0};
for (const char ch : s) ++dict_s[ch];
for (const char ch : t) ++dict_t[ch];
for (size_t i = 0; i < 0x100; ++i)
if (dict_s[i] != dict_t[i]) return static_cast<char>(i);
return '?';
}
};
int main(void) {
Solution sln;
return 0;
}
| 801 | 348 |
// ----------------------------------------------------------------------------
// - Open3D: www.open3d.org -
// ----------------------------------------------------------------------------
// The MIT License (MIT)
//
// Copyright (c) 2018 www.open3d.org
//
// 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 "Python/integration/integration.h"
#include "Python/docstring.h"
#include <Open3D/Integration/TSDFVolume.h>
#include <Open3D/Integration/UniformTSDFVolume.h>
#include <Open3D/Integration/ScalableTSDFVolume.h>
using namespace open3d;
template <class TSDFVolumeBase = integration::TSDFVolume>
class PyTSDFVolume : public TSDFVolumeBase {
public:
using TSDFVolumeBase::TSDFVolumeBase;
void Reset() override { PYBIND11_OVERLOAD_PURE(void, TSDFVolumeBase, ); }
void Integrate(const geometry::RGBDImage &image,
const camera::PinholeCameraIntrinsic &intrinsic,
const Eigen::Matrix4d &extrinsic) override {
PYBIND11_OVERLOAD_PURE(void, TSDFVolumeBase, image, intrinsic,
extrinsic);
}
std::shared_ptr<geometry::PointCloud> ExtractPointCloud() override {
PYBIND11_OVERLOAD_PURE(std::shared_ptr<geometry::PointCloud>,
TSDFVolumeBase, );
}
std::shared_ptr<geometry::TriangleMesh> ExtractTriangleMesh() override {
PYBIND11_OVERLOAD_PURE(std::shared_ptr<geometry::TriangleMesh>,
TSDFVolumeBase, );
}
};
void pybind_integration_classes(py::module &m) {
// open3d.integration.TSDFVolumeColorType
py::enum_<integration::TSDFVolumeColorType> tsdf_volume_color_type(
m, "TSDFVolumeColorType", py::arithmetic());
tsdf_volume_color_type.value("None", integration::TSDFVolumeColorType::None)
.value("RGB8", integration::TSDFVolumeColorType::RGB8)
.value("Gray32", integration::TSDFVolumeColorType::Gray32)
.export_values();
// Trick to write docs without listing the members in the enum class again.
tsdf_volume_color_type.attr("__doc__") = docstring::static_property(
py::cpp_function([](py::handle arg) -> std::string {
return "Enum class for TSDFVolumeColorType.";
}),
py::none(), py::none(), "");
// open3d.integration.TSDFVolume
py::class_<integration::TSDFVolume, PyTSDFVolume<integration::TSDFVolume>>
tsdfvolume(m, "TSDFVolume", R"(Base class of the Truncated
Signed Distance Function (TSDF) volume This volume is usually used to integrate
surface data (e.g., a series of RGB-D images) into a Mesh or PointCloud. The
basic technique is presented in the following paper:
A volumetric method for building complex models from range images
B. Curless and M. Levoy
In SIGGRAPH, 1996)");
tsdfvolume
.def("reset", &integration::TSDFVolume::Reset,
"Function to reset the integration::TSDFVolume")
.def("integrate", &integration::TSDFVolume::Integrate,
"Function to integrate an RGB-D image into the volume",
"image"_a, "intrinsic"_a, "extrinsic"_a)
.def("extract_point_cloud",
&integration::TSDFVolume::ExtractPointCloud,
"Function to extract a point cloud with normals")
.def("extract_triangle_mesh",
&integration::TSDFVolume::ExtractTriangleMesh,
"Function to extract a triangle mesh")
.def_readwrite("voxel_length",
&integration::TSDFVolume::voxel_length_,
"float: Voxel size.")
.def_readwrite("sdf_trunc", &integration::TSDFVolume::sdf_trunc_,
"float: Truncation value for signed distance "
"function (SDF).")
.def_readwrite("color_type", &integration::TSDFVolume::color_type_,
"integration.TSDFVolumeColorType: Color type of the "
"TSDF volume.");
docstring::ClassMethodDocInject(m, "TSDFVolume", "extract_point_cloud");
docstring::ClassMethodDocInject(m, "TSDFVolume", "extract_triangle_mesh");
docstring::ClassMethodDocInject(
m, "TSDFVolume", "integrate",
{{"image", "RGBD image."},
{"intrinsic", "Pinhole camera intrinsic parameters."},
{"extrinsic", "Extrinsic parameters."}});
docstring::ClassMethodDocInject(m, "TSDFVolume", "reset");
// open3d.integration.UniformTSDFVolume: open3d.integration.TSDFVolume
py::class_<integration::UniformTSDFVolume,
PyTSDFVolume<integration::UniformTSDFVolume>,
integration::TSDFVolume>
uniform_tsdfvolume(
m, "UniformTSDFVolume",
"UniformTSDFVolume implements the classic TSDF "
"volume with uniform voxel grid (Curless and Levoy 1996).");
py::detail::bind_copy_functions<integration::UniformTSDFVolume>(
uniform_tsdfvolume);
uniform_tsdfvolume
.def(py::init([](double length, int resolution, double sdf_trunc,
integration::TSDFVolumeColorType color_type) {
return new integration::UniformTSDFVolume(
length, resolution, sdf_trunc, color_type);
}),
"length"_a, "resolution"_a, "sdf_trunc"_a, "color_type"_a)
.def("__repr__",
[](const integration::UniformTSDFVolume &vol) {
return std::string("integration::UniformTSDFVolume ") +
(vol.color_type_ ==
integration::TSDFVolumeColorType::
None
? std::string("without color.")
: std::string("with color."));
}) // todo: extend
.def("extract_voxel_point_cloud",
&integration::UniformTSDFVolume::ExtractVoxelPointCloud,
"Debug function to extract the voxel data into a point cloud.")
.def_readwrite("length", &integration::UniformTSDFVolume::length_,
"Total length, where ``voxel_length = length / "
"resolution``.")
.def_readwrite("resolution",
&integration::UniformTSDFVolume::resolution_,
"Resolution over the total length, where "
"``voxel_length = length / resolution``");
docstring::ClassMethodDocInject(m, "UniformTSDFVolume",
"extract_voxel_point_cloud");
// open3d.integration.ScalableTSDFVolume: open3d.integration.TSDFVolume
py::class_<integration::ScalableTSDFVolume,
PyTSDFVolume<integration::ScalableTSDFVolume>,
integration::TSDFVolume>
scalable_tsdfvolume(m, "ScalableTSDFVolume", R"(The
ScalableTSDFVolume implements a more memory efficient data structure for
volumetric integration.
An observed depth pixel gives two types of information: (a) an approximation
of the nearby surface, and (b) empty space from the camera to the surface.
They induce two core concepts of volumetric integration: weighted average of
a truncated signed distance function (TSDF), and carving. The weighted
average of TSDF is great in addressing the Gaussian noise along surface
normal and producing a smooth surface output. The carving is great in
removing outlier structures like floating noise pixels and bumps along
structure edges.
Ref: Dense Scene Reconstruction with Points of Interest
Q.-Y. Zhou and V. Koltun
In SIGGRAPH, 2013)");
py::detail::bind_copy_functions<integration::ScalableTSDFVolume>(
scalable_tsdfvolume);
scalable_tsdfvolume
.def(py::init([](double voxel_length, double sdf_trunc,
integration::TSDFVolumeColorType color_type,
int volume_unit_resolution,
int depth_sampling_stride) {
return new integration::ScalableTSDFVolume(
voxel_length, sdf_trunc, color_type,
volume_unit_resolution, depth_sampling_stride);
}),
"voxel_length"_a, "sdf_trunc"_a, "color_type"_a,
"volume_unit_resolution"_a = 16, "depth_sampling_stride"_a = 4)
.def("__repr__",
[](const integration::ScalableTSDFVolume &vol) {
return std::string("integration::ScalableTSDFVolume ") +
(vol.color_type_ ==
integration::TSDFVolumeColorType::
None
? std::string("without color.")
: std::string("with color."));
})
.def("extract_voxel_point_cloud",
&integration::ScalableTSDFVolume::ExtractVoxelPointCloud,
"Debug function to extract the voxel data into a point "
"cloud.");
docstring::ClassMethodDocInject(m, "ScalableTSDFVolume",
"extract_voxel_point_cloud");
}
void pybind_integration_methods(py::module &m) {
// Currently empty
}
void pybind_integration(py::module &m) {
py::module m_submodule = m.def_submodule("integration");
pybind_integration_classes(m_submodule);
pybind_integration_methods(m_submodule);
}
| 10,863 | 2,964 |
#ifndef LEXER_HPP
#define LEXER_HPP
#include "lexer/Token.hpp"
#include "llvm/ADT/StringSwitch.h"
#include <functional>
#include <iterator>
#include <memory>
#include <optional>
#include <string>
#include <type_traits>
template <class InputIterator>
class Lexer : public std::iterator<std::input_iterator_tag, Token> {
static_assert(std::is_same<typename std::iterator_traits<InputIterator>::value_type, char>(),
"Expecting iterator over 'char' type.");
InputIterator current_character;
InputIterator characters_end;
std::optional<Token> current_token;
public:
Lexer(InputIterator begin, InputIterator end);
Lexer() = default;
Token operator*() const;
Token &operator++();
Token operator++(int);
bool operator==(const Lexer &other) const;
bool operator!=(const Lexer &other) const;
private:
std::optional<Token> next();
template <class TokenMatcher>
std::string get_while_matching(const TokenMatcher &matcher);
static bool is_operator(char c);
static bool is_identifier(char c);
};
template <class InputIterator>
Lexer<InputIterator>::Lexer(InputIterator begin, InputIterator end)
: current_character(begin)
, characters_end(end) {
if (current_character != characters_end) {
++(*this);
}
}
template <class InputIterator>
Token Lexer<InputIterator>::operator*() const {
return *current_token;
}
template <class InputIterator>
Token &Lexer<InputIterator>::operator++() {
return *(current_token = next());
}
template <class InputIterator>
Token Lexer<InputIterator>::operator++(int) {
auto tmp_token = std::move(current_token);
++(*this);
return *tmp_token;
}
template <class InputIterator>
bool Lexer<InputIterator>::operator==(const Lexer &other) const {
return current_token.has_value() == other.current_token.has_value();
}
template <class InputIterator>
bool Lexer<InputIterator>::operator!=(const Lexer &other) const {
return !(*this == other);
}
template <class InputIterator>
std::optional<Token> Lexer<InputIterator>::next() {
while (current_character != characters_end) {
if (isspace(*current_character) != 0) {
++current_character;
} else if (isdigit(*current_character) != 0) {
return Token(TokenType::number_t, get_while_matching(isdigit));
} else if (is_operator(*current_character)) {
return Token(TokenType::operator_t, get_while_matching(is_operator));
} else if (*current_character == '=') {
return Token(TokenType::assignment_t, *current_character++);
} else if (*current_character == '(') {
return Token(TokenType::left_parenthesis_t, *current_character++);
} else if (*current_character == ')') {
return Token(TokenType::right_parenthesis_t, *current_character++);
} else if (is_identifier(*current_character)) {
auto token = get_while_matching(is_identifier);
auto token_type = llvm::StringSwitch<TokenType>(token)
.Case("BEGIN", TokenType::begin_t)
.Case("END", TokenType::end_t)
.Case("LOOP", TokenType::loop_t)
.Case("BREAK", TokenType::break_t)
.Case("IFN", TokenType::ifn_t)
.Case("IFP", TokenType::ifp_t)
.Case("IFZ", TokenType::ifz_t)
.Case("ELSE", TokenType::else_t)
.Case("PRINT", TokenType::print_t)
.Case("READ", TokenType::read_t)
.Default(TokenType::variable_t);
return Token(token_type, token);
} else if (*current_character == '{') {
current_character = std::next(std::find(current_character, characters_end, '}'));
} else {
throw std::logic_error("Cannot handle the current character.");
}
}
return {};
}
template <class InputIterator>
template <class TokenMatcher>
std::string Lexer<InputIterator>::get_while_matching(const TokenMatcher &matcher) {
std::string value;
do {
value += *current_character++;
} while (current_character != characters_end && matcher(*current_character));
return value;
}
template <class InputIterator>
bool Lexer<InputIterator>::is_operator(const char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '%';
}
template <class InputIterator>
bool Lexer<InputIterator>::is_identifier(const char c) {
return (isalnum(c) != 0) || c == '_';
}
#endif
| 4,708 | 1,372 |
// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "rasterize.h"
#include <stdio.h>
using namespace std;
// Global declarations
bool g_verbose = true;
typedef vector<VPoints> VVPoints;
struct InternalGrid {
double xmin;
double ymin;
double resolution;
int rows;
int cols;
VVPoints points;
};
void ComputeXYBounds(VPoints& points,
double resolution,
InternalGrid& internalGrid)
{
double xmin, xmax, ymin, ymax;
xmin = ymin = INFINITY;
xmax = ymax = -INFINITY;
int numPoints = points.size();
int i;
for(i=0; i<numPoints; i++) {
if (points[i].x < xmin) {
xmin = points[i].x;
}
if (points[i].y < ymin) {
ymin = points[i].y;
}
if (points[i].x > xmax) {
xmax = points[i].x;
}
if (points[i].y > ymax) {
ymax = points[i].y;
}
}
int rows = (int)ceil(double(ymax - ymin)/resolution + 1);
int cols = (int)ceil(double(xmax - xmin)/resolution + 1);
internalGrid.xmin = xmin;
internalGrid.ymin = ymin;
internalGrid.resolution = resolution;
internalGrid.rows = rows;
internalGrid.cols = cols;
return;
}
InternalGrid CreateXYMesh( VPoints points,
double resolution)
{
InternalGrid internalGrid;
ComputeXYBounds(points, resolution, internalGrid);
if (g_verbose) {
fprintf(stdout, "Rows: %d\n", internalGrid.rows);
fprintf(stdout, "Cols: %d\n", internalGrid.cols);
}
int i, j;
for (i=0; i<internalGrid.rows; i++) {
VPoints row;
for (j=0; j<internalGrid.cols; j++) {
Point aPoint = {internalGrid.xmin + j*resolution, internalGrid.ymin + i*resolution, 0};
row.push_back(aPoint);
}
internalGrid.points.push_back(row);
}
return internalGrid;
}
inline double Compute2DDistance(Point a, Point b)
{
return sqrt((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y));
}
int FindNearestPoint(VPoints& points,
Point aPoint)
{
int index=0;
double minDistance = INFINITY;
int numPoints = points.size();
int i;
for (i=0; i<numPoints; i++) {
double distance = Compute2DDistance(points[i], aPoint);
if (distance < minDistance) {
minDistance = distance;
index = i;
}
}
return index;
}
double FindNeighboringGridPoint(InternalGrid& internalGrid,
VVDouble& minDistanceGrid,
int row,
int col,
int radius )
{
int i, j;
double minDist=INFINITY;
double distance;
double minZ = KH_MISSING_ZVALUE;
for (i=row-(radius-1); i<row+radius; i++) {
if (i<0 || i>=internalGrid.rows) {
continue;
}
for (j=col-(radius-1); j<col+radius; j++) {
if (j<0 || j>=internalGrid.cols) {
continue;
}
if (minDistanceGrid[i][j] < INFINITY) {
distance = i*i + j*j;
if (distance < minDist) {
minZ = internalGrid.points[i][j].z;
}
}
}
}
return minZ;
}
void RasterizeNearest(VPoints& points,
InternalGrid& internalGrid,
int fillRadius=3)
{
VVDouble minDistanceGrid;
// initalize the minimum distance grid
int i, j;
VDouble row;
row.resize(internalGrid.cols*sizeof(double));
for (j=0; j<internalGrid.cols; j++) {
row[j] = INFINITY;
}
for (i=0; i<internalGrid.rows; i++) {
minDistanceGrid.push_back(row);
}
int numPoints = points.size();
double xd, yd;
int cx, cy, fx, fy;
for (i=0; i<numPoints; i++) {
// find the index of the 4 grid points
// surrounding the point
xd = (points[i].x - internalGrid.xmin) / internalGrid.resolution;
cx = (int)ceil(xd);
fx = (int)floor(xd);
yd = (points[i].y - internalGrid.ymin) / internalGrid.resolution;
cy = (int)ceil(yd);
fy = (int)floor(yd);
// this point will affect all 4 points surrounding it
int xarr[] = {fx, cx, fx, cx};
int yarr[] = {fy, fy, cy, cy};
int k;
int xi, yi;
for(k=0; k<4; k++) {
xi = xarr[k];
yi = yarr[k];
double distance = Compute2DDistance(points[i], internalGrid.points[yi][xi]);
if (distance < minDistanceGrid[yi][xi]) {
minDistanceGrid[yi][xi] = distance;
internalGrid.points[yi][xi].z = points[i].z;
}
}
}
int ip=0;
const int progStep = 10;
double dp=0;
if (g_verbose) {
fprintf(stdout, "0");
}
/*
for (i=0; i<internalGrid.rows; i++) {
for (j=0; j<internalGrid.cols; j++) {
if (minDistanceGrid[i][j] < INFINITY) {
continue;
}
int index = FindNearestPoint(points, internalGrid.points[i][j]);
internalGrid.points[i][j].z = points[index].z;
}
if (g_verbose) {
dp += 100.0/double(internalGrid.rows-1);
if ((int(dp) % progStep == 0) && int(dp) != ip) {
ip += progStep;
fprintf(stdout, "..%d", ip);
}
}
}
*/
for (i=0; i<internalGrid.rows; i++) {
for (j=0; j<internalGrid.cols; j++) {
if (minDistanceGrid[i][j] < INFINITY) {
continue;
}
internalGrid.points[i][j].z = FindNeighboringGridPoint(internalGrid, minDistanceGrid, i, j, fillRadius);
}
if (g_verbose) {
dp += 100.0/double(internalGrid.rows-1);
if ((int(dp) % progStep == 0) && int(dp) != ip) {
ip += progStep;
fprintf(stdout, "..%d", ip);
}
}
}
fprintf(stdout, "\n");
return;
}
void RasterizeLinear(VPoints& points,
InternalGrid& internalGrid)
{
fprintf(stderr, "Notice: Only Nearest Neighbor Interpolation implemented so far\n");
RasterizeNearest(points, internalGrid);
return;
}
Grid Rasterize( VPoints points,
double resolution,
int fillRadius,
int method,
bool verbose)
{
Grid grid;
int numPoints = points.size();
if (numPoints <= 3) {
fprintf(stderr, "Error: Insufficient points\n");
return grid;
}
if (resolution <= 0) {
fprintf(stderr, "Error: Bad resolution\n");
return grid;
}
g_verbose = verbose;
// Create the XY mesh
InternalGrid internalGrid = CreateXYMesh(points, resolution);
// Now compute z values based on one of the
// following methods
switch (method) {
case INTP_NEAREST:
RasterizeNearest(points, internalGrid, fillRadius);
break;
case INTP_LINEAR:
RasterizeLinear(points, internalGrid);
break;
}
grid.rows = internalGrid.rows;
grid.cols = internalGrid.cols;
grid.xmin = internalGrid.xmin;
grid.ymin = internalGrid.ymin;
grid.resolution = internalGrid.resolution;
int i,j;
for (i=0; i<internalGrid.rows; i++) {
VDouble row;
for (j=0; j<internalGrid.cols; j++) {
row.push_back(internalGrid.points[i][j].z);
}
grid.z.push_back(row);
}
return grid;
}
| 7,593 | 2,703 |
#include "rein.h"
void Rein::insert(IntervalSub sub)
{
for (int i = 0; i < sub.size; i++)
{
IntervalCnt cnt = sub.constraints.at(i);
Combo c;
c.val = cnt.lowValue;
c.subID = sub.id;
data[cnt.att][0][c.val / buckStep].push_back(c);
c.val = cnt.highValue;
data[cnt.att][1][c.val / buckStep].push_back(c);
}
}
void Rein::match(const Pub &pub, int &matchSubs, const vector<IntervalSub> &subList, int x)
{
Timer subStart;
vector<bool> bits (subList.size(), false);
for (int i = 0; i < pub.size; i++)
{
int value = pub.pairs[i].value, att = pub.pairs[i].att, buck = value / buckStep;
int upper = min(bucks, buck + x);
int lower = max(0, buck - x);
for (int k = 0; k < data[att][0][buck].size(); k++)
if (data[att][0][buck].at(k).val > value)
bits.at(data[att][0][buck].at(k).subID) = true;
for (int j = buck + 1; j < upper; j++)
for (int k = 0; k < data[att][0][j].size(); k++)
bits.at(data[att][0][j].at(k).subID) = true;
for (int k = 0; k < data[att][1][buck].size(); k++)
if (data[att][1][buck].at(k).val < value)
bits.at(data[att][1][buck].at(k).subID) = true;
for (int j = buck - 1; j >= lower; j--)
for (int k = 0; k < data[att][1][j].size(); k++)
bits.at(data[att][1][j].at(k).subID) = true;
}
int att2value[MAX_ATTS];
for (int i = 0; i < pub.size; i ++)
att2value[pub.pairs.at(i).att] = pub.pairs.at(i).value;
for (int i = 0; i < subList.size(); i++)
if (!bits.at(i))
{
IntervalSub sub = subList.at(i);
bool flag = true;
for (int j = 0; j < sub.size; j ++)
{
int att = sub.constraints.at(j).att, pub_value = att2value[att];
if (pub_value < sub.constraints.at(j).lowValue || pub_value > sub.constraints.at(j).highValue)
{
flag = false;
break;
}
}
if (flag)
++ matchSubs;
}
}
| 2,176 | 816 |
#pragma once
//------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI 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 "core/future_timepoint.hpp"
#include "core/logging.hpp"
#include "core/service_ids.hpp"
#include "crypto/merkle_tree.hpp"
#include "ledger/shard_config.hpp"
#include "ledger/storage_unit/lane_connectivity_details.hpp"
#include "ledger/storage_unit/lane_identity.hpp"
#include "ledger/storage_unit/lane_identity_protocol.hpp"
#include "ledger/storage_unit/lane_service.hpp"
#include "ledger/storage_unit/storage_unit_interface.hpp"
#include "network/generics/backgrounded_work.hpp"
#include "network/generics/has_worker_thread.hpp"
#include "network/management/connection_register.hpp"
#include "network/muddle/muddle.hpp"
#include "network/muddle/rpc/client.hpp"
#include "network/muddle/rpc/server.hpp"
#include "network/service/service_client.hpp"
#include "storage/document_store_protocol.hpp"
#include "storage/object_stack.hpp"
#include "storage/object_store_protocol.hpp"
#include <array>
#include <cassert>
#include <cstdint>
#include <cstring>
#include <exception>
#include <memory>
#include <string>
#include <vector>
namespace fetch {
namespace ledger {
class StorageUnitClient final : public StorageUnitInterface
{
public:
using MuddleEndpoint = muddle::MuddleEndpoint;
using Address = MuddleEndpoint::Address;
static constexpr char const *LOGGING_NAME = "StorageUnitClient";
// Construction / Destruction
StorageUnitClient(MuddleEndpoint &muddle, ShardConfigs const &shards, uint32_t log2_num_lanes);
StorageUnitClient(StorageUnitClient const &) = delete;
StorageUnitClient(StorageUnitClient &&) = delete;
~StorageUnitClient() override = default;
// Helpers
uint32_t num_lanes() const;
/// @name Storage Unit Interface
/// @{
void AddTransaction(Transaction const &tx) override;
bool GetTransaction(ConstByteArray const &digest, Transaction &tx) override;
bool HasTransaction(ConstByteArray const &digest) override;
void IssueCallForMissingTxs(DigestSet const &tx_set) override;
TxLayouts PollRecentTx(uint32_t max_to_poll) override;
Document GetOrCreate(ResourceAddress const &key) override;
Document Get(ResourceAddress const &key) override;
void Set(ResourceAddress const &key, StateValue const &value) override;
Keys KeyDump() const override;
void Reset() override;
// state hash functions
byte_array::ConstByteArray CurrentHash() override;
byte_array::ConstByteArray LastCommitHash() override;
bool RevertToHash(Hash const &hash, uint64_t index) override;
byte_array::ConstByteArray Commit(uint64_t index) override;
bool HashExists(Hash const &hash, uint64_t index) override;
bool Lock(ShardIndex index) override;
bool Unlock(ShardIndex index) override;
/// @}
StorageUnitClient &operator=(StorageUnitClient const &) = delete;
StorageUnitClient &operator=(StorageUnitClient &&) = delete;
private:
using Client = muddle::rpc::Client;
using ClientPtr = std::shared_ptr<Client>;
using LaneIndex = LaneIdentity::lane_type;
using AddressList = std::vector<MuddleEndpoint::Address>;
using MerkleTree = crypto::MerkleTree;
using PermanentMerkleStack = fetch::storage::ObjectStack<crypto::MerkleTree>;
static constexpr char const *MERKLE_FILENAME_DOC = "merkle_stack.db";
static constexpr char const *MERKLE_FILENAME_INDEX = "merkle_stack_index.db";
Address const &LookupAddress(ShardIndex shard) const;
Address const &LookupAddress(storage::ResourceID const &resource) const;
bool HashInStack(Hash const &hash, uint64_t index);
/// @name Client Information
/// @{
AddressList const addresses_;
uint32_t const log2_num_lanes_ = 0;
ClientPtr rpc_client_;
/// @}
/// @name State Hash Support
/// @{
mutable Mutex merkle_mutex_;
MerkleTree current_merkle_;
PermanentMerkleStack permanent_state_merkle_stack_{};
/// @}
};
} // namespace ledger
} // namespace fetch
| 4,835 | 1,479 |
/*=============================================================================
Copyright (c) 2011-2017 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
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)
=============================================================================*/
#ifndef SPROUT_FIXED_CONTAINER_GET_DEEP_INTERNAL_HPP
#define SPROUT_FIXED_CONTAINER_GET_DEEP_INTERNAL_HPP
#include <type_traits>
#include <sprout/config.hpp>
#include <sprout/container/get_internal.hpp>
#include <sprout/container/deep_internal.hpp>
#include <sprout/container/is_sub_container.hpp>
#include <sprout/utility/forward.hpp>
#include <sprout/type_traits/enabler_if.hpp>
namespace sprout {
namespace detail {
template<
typename Container,
typename sprout::enabler_if<!sprout::containers::is_sub_container<Container>::value>::type = sprout::enabler
>
inline SPROUT_CONSTEXPR typename sprout::containers::deep_internal<Container>::type
get_deep_internal_impl(Container&& cont) {
return SPROUT_FORWARD(Container, cont);
}
template<
typename Container,
typename sprout::enabler_if<sprout::containers::is_sub_container<Container>::value>::type = sprout::enabler
>
inline SPROUT_CONSTEXPR typename sprout::containers::deep_internal<Container>::type
get_deep_internal_impl(Container&& cont) {
return sprout::detail::get_deep_internal_impl(
sprout::get_internal(SPROUT_FORWARD(Container, cont))
);
}
} // namespace detail
//
// get_deep_internal
//
template<typename Container>
inline SPROUT_CONSTEXPR typename sprout::containers::deep_internal<Container>::type
get_deep_internal(Container&& cont) {
return sprout::detail::get_deep_internal_impl(SPROUT_FORWARD(Container, cont));
}
} // namespace sprout
#endif // #ifndef SPROUT_FIXED_CONTAINER_GET_DEEP_INTERNAL_HPP
| 1,977 | 726 |
// Copyright eeGeo Ltd (2012-2014), All Rights Reserved
#include "RouteSimulationAnimationExampleFactory.h"
#include "RouteSimulationAnimationExample.h"
#include "LocalAsyncTextureLoader.h"
#include "RenderContext.h"
#include "CollisionMeshResourceRepository.h"
#include "MapModule.h"
#include "TerrainModelModule.h"
#include "RoutesModule.h"
#include "RenderingModule.h"
#include "IPlatformAbstractionModule.h"
#include "AsyncLoadersModule.h"
#include "SceneModelsModule.h"
namespace Examples
{
RouteSimulationAnimationExampleFactory::RouteSimulationAnimationExampleFactory(Eegeo::EegeoWorld& world,
DefaultCameraControllerFactory& defaultCameraControllerFactory,
Eegeo::Camera::GlobeCamera::GlobeCameraTouchController& globeCameraTouchController,
const IScreenPropertiesProvider& screenPropertiesProvider)
: m_world(world)
, m_screenPropertiesProvider(screenPropertiesProvider)
, m_pRouteSimulationGlobeCameraControllerFactory(NULL)
{
Eegeo::Modules::Map::MapModule& mapModule = m_world.GetMapModule();
Eegeo::Modules::Map::Layers::TerrainModelModule& terrainModelModule = m_world.GetTerrainModelModule();
m_pRouteSimulationGlobeCameraControllerFactory = new Eegeo::Routes::Simulation::Camera::RouteSimulationGlobeCameraControllerFactory
(
terrainModelModule.GetTerrainHeightProvider(),
mapModule.GetEnvironmentFlatteningService(),
mapModule.GetResourceCeilingProvider(),
terrainModelModule.GetTerrainCollisionMeshResourceRepository()
);
}
RouteSimulationAnimationExampleFactory::~RouteSimulationAnimationExampleFactory()
{
delete m_pRouteSimulationGlobeCameraControllerFactory;
}
IExample* RouteSimulationAnimationExampleFactory::CreateExample() const
{
Eegeo::Modules::RoutesModule& routesModule = m_world.GetRoutesModule();
Eegeo::Modules::Core::SceneModelsModule& sceneModelsModule = m_world.GetCoreModule().GetSceneModelsModule();
return new Examples::RouteSimulationAnimationExample(routesModule.GetRouteService(),
routesModule.GetRouteSimulationService(),
routesModule.GetRouteSimulationViewService(),
sceneModelsModule.GetLocalModelLoader(),
*m_pRouteSimulationGlobeCameraControllerFactory,
m_screenPropertiesProvider,
m_world);
}
std::string RouteSimulationAnimationExampleFactory::ExampleName() const
{
return Examples::RouteSimulationAnimationExample::GetName();
}
}
| 2,660 | 707 |
#include <iostream>
#include <stack>
#include <cassert>
#include <vector>
#include <sstream>
bool isdigit (char c)
{
return c >= '0' && c <= '9';
}
int apply (char op, int x, int y)
{
switch (op)
{
case '+': return x+y;
case '*': return x*y;
default: assert (false);
}
return 0;
}
void killwhite (std::istream &in)
{
while (in.peek () == ' ' || in.peek() == '\n')
{
in.get();
}
}
int calcrpp (std::istream &in)
{
killwhite (in);
std::stack <int> s;
while (in.peek() != ';')
{
if (isdigit (in.peek()))
{
int arg;
in >> arg;
s.push (arg);
} else {
char op = in.get();
assert (s.size() >= 2);
int larg = s.top(); s.pop();
int rarg = s.top(); s.pop();
s.push (apply(op,larg,rarg));
}
killwhite (in);
}
assert (s.size() == 1);
return s.top();
}
struct Token
{
int type;
static const int NUM = 0;
static const int OPER = 1;
static const int LPAR = 2;
static const int RPAR = 3;
int val;
char op;
};
int priority (char op)
{
switch (op)
{
case '*': return 10;
case '+': return 5;
default: assert (false);
}
return 0;
}
std::vector<Token> makerpn (std::istream &in)
{
std::vector<Token> result;
std::stack<Token> s;
killwhite (in);
while (in.peek() != ';')
{
Token next;
if (isdigit (in.peek()))
{
next.type = Token::NUM;
in >> next.val;
result.push_back (next);
} else if (in.peek() == '(')
{
next.type = Token::LPAR;
s.push (next);
in.get();
} else if (in.peek() == ')')
{
in.get();
while (s.size() >= 1 &&
s.top().type != Token::LPAR)
{
next = s.top(); s.pop();
result.push_back (next);
assert (next.type == Token::OPER);
}
assert (s.size () >= 1);
s.pop();
} else {
next.type = Token::OPER;
next.op = in.get();
while (s.size()>=1 &&
s.top().type == Token::OPER &&
priority(s.top().op) > priority (next.op))
{
result.push_back(s.top());
s.pop();
}
s.push (next);
}
killwhite (in);
}
while (s.size () > 0)
{
result.push_back (s.top()); s.pop();
}
return result;
}
std::stringstream tostream (std::vector<Token> rpn)
{
std::stringstream res;
for (Token t : rpn)
{
switch (t.type)
{
case Token::NUM: res << t.val; break;
case Token::OPER: res << t.op; break;
default: assert (false);
}
res << " ";
}
return res;
}
int calcexprrec (std::istream &in)
{
killwhite (in);
if (isdigit (in.peek()))
{
int x;
in >> x;
return x;
}
assert (in.peek() == '(');
in.get();
int larg = calcexprrec (in);
killwhite (in);
char op = in.get();
int rarg = calcexprrec (in);
killwhite (in);
assert (in.get() == ')');
return apply (op,larg,rarg);
}
Token readToken (std::istream &in)
{
killwhite (in);
Token t;
if (isdigit (in.peek()))
{
t.type = Token::NUM;
in >> t.val;
return t;
} else if (in.peek() == '(')
{
t.type = Token::LPAR;
in.get();
return t;
} else if (in.peek() == ')')
{
t.type = Token::RPAR;
in.get();
return t;
} else
{
t.type = Token::OPER;
t.op = in.get();
return t;
}
}
int calcexprit (std::istream &in)
{
std::stack <Token> s;
Token next = readToken (in);
s.push (next);
while (s.size () > 1 || s.top().type != Token::NUM)
{
next = readToken (in);
if (next.type == Token::RPAR)
{
assert (s.top().type == Token::NUM);
int rarg = s.top().val; s.pop();
assert (s.top().type == Token::OPER);
char op = s.top().op; s.pop();
assert (s.top().type == Token::NUM);
int larg = s.top().val; s.pop();
assert (s.top().type == Token::LPAR);
s.pop();
next.type = Token::NUM;
next.val = apply (op,larg,rarg);
s.push (next);
} else {
s.push (next);
}
}
// std::cerr << "Top of stack = " << s.top().type << std::endl;
assert (s.top().type == Token::NUM);
return s.top().val;
}
int main ()
{
//std::cout << calcrpp (std::cin);
//std::vector<Token> rpn = makerpn (std::cin);
//std::stringstream srpn = tostream (rpn);
//std::cout << srpn.str();
//std::cout << calcexprrec (std::cin);
std::cout << calcexprit (std::cin);
} | 5,084 | 1,789 |
/*++
Copyright (c) 2006 Microsoft Corporation
Module Name:
der.cpp
Abstract:
<abstract>
Author:
Leonardo de Moura (leonardo) 2008-01-27.
Revision History:
Christoph Wintersteiger, 2010-03-30: Added Destr. Multi-Equality Resolution
--*/
#include "ast/rewriter/der.h"
#include "ast/occurs.h"
#include "ast/for_each_expr.h"
#include "ast/rewriter/rewriter_def.h"
#include "ast/ast_util.h"
#include "ast/ast_pp.h"
#include "ast/ast_ll_pp.h"
#include "ast/ast_smt2_pp.h"
static bool is_var(expr * e, unsigned num_decls) {
return is_var(e) && to_var(e)->get_idx() < num_decls;
}
static bool is_neg_var(ast_manager & m, expr * e, var*& v, unsigned num_decls) {
expr* n = nullptr;
return m.is_not(e, n) && is_var(n) && (v = to_var(n), v->get_idx() < num_decls);
}
/**
\brief Return true if \c e is of the form (not (= VAR t)) or (not (iff VAR t)) or (iff VAR t) or (iff (not VAR) t) or (VAR IDX) or (not (VAR IDX)).
The last case can be viewed
Remark: Occurs check is not necessary here... the top-sort procedure will check for cycles...
*/
bool der::is_var_diseq(expr * e, unsigned num_decls, var * & v, expr_ref & t) {
expr *eq, * lhs, *rhs;
auto set_result = [&](var *w, expr* s) {
v = w;
t = s;
TRACE("der", tout << mk_pp(e, m) << "\n";);
return true;
};
// (not (= VAR t))
if (m.is_not(e, eq) && m.is_eq(eq, lhs, rhs)) {
if (!is_var(lhs, num_decls))
std::swap(lhs, rhs);
if (!is_var(lhs, num_decls))
return false;
return set_result(to_var(lhs), rhs);
}
// (= VAR t)
if (m.is_eq(e, lhs, rhs) && m.is_bool(lhs)) {
// (iff VAR t) case
if (!is_var(lhs, num_decls))
std::swap(lhs, rhs);
if (is_var(lhs, num_decls)) {
rhs = mk_not(m, rhs);
m_new_exprs.push_back(rhs);
return set_result(to_var(lhs), rhs);
}
// (iff (not VAR) t) case
if (!is_neg_var(m, lhs, v, num_decls))
std::swap(lhs, rhs);
if (is_neg_var(m, lhs, v, num_decls)) {
return set_result(v, rhs);
}
return false;
}
// VAR
if (is_var(e, num_decls)) {
return set_result(to_var(e), m.mk_false());
}
// (not VAR)
if (is_neg_var(m, e, v, num_decls)) {
return set_result(v, m.mk_true());
}
return false;
}
void der::operator()(quantifier * q, expr_ref & r, proof_ref & pr) {
bool reduced = false;
pr = nullptr;
r = q;
TRACE("der", tout << mk_pp(q, m) << "\n";);
// Keep applying it until r doesn't change anymore
do {
proof_ref curr_pr(m);
q = to_quantifier(r);
reduce1(q, r, curr_pr);
if (q != r)
reduced = true;
if (m.proofs_enabled()) {
pr = m.mk_transitivity(pr, curr_pr);
}
}
while (q != r && is_quantifier(r));
// Eliminate variables that have become unused
if (reduced && is_forall(r)) {
quantifier * q = to_quantifier(r);
r = elim_unused_vars(m, q, params_ref());
if (m.proofs_enabled()) {
proof * p1 = m.mk_elim_unused_vars(q, r);
pr = m.mk_transitivity(pr, p1);
}
}
m_new_exprs.reset();
}
void der::reduce1(quantifier * q, expr_ref & r, proof_ref & pr) {
if (!is_forall(q)) {
pr = nullptr;
r = q;
return;
}
expr * e = q->get_expr();
unsigned num_decls = q->get_num_decls();
var * v = nullptr;
expr_ref t(m);
if (m.is_or(e)) {
unsigned num_args = to_app(e)->get_num_args();
unsigned diseq_count = 0;
unsigned largest_vinx = 0;
m_map.reset();
m_pos2var.reset();
m_inx2var.reset();
m_pos2var.reserve(num_args, -1);
// Find all disequalities
for (unsigned i = 0; i < num_args; i++) {
if (is_var_diseq(to_app(e)->get_arg(i), num_decls, v, t)) {
unsigned idx = v->get_idx();
if (m_map.get(idx, nullptr) == nullptr) {
m_map.reserve(idx + 1);
m_inx2var.reserve(idx + 1, 0);
m_map[idx] = t;
m_inx2var[idx] = v;
m_pos2var[i] = idx;
diseq_count++;
largest_vinx = (idx>largest_vinx) ? idx : largest_vinx;
}
}
}
if (diseq_count > 0) {
get_elimination_order();
SASSERT(m_order.size() <= diseq_count); // some might be missing because of cycles
if (!m_order.empty()) {
create_substitution(largest_vinx + 1);
apply_substitution(q, r);
}
}
else {
TRACE("der_bug", tout << "Did not find any diseq\n" << mk_pp(q, m) << "\n";);
r = q;
}
}
// Remark: get_elimination_order/top-sort checks for cycles, but it is not invoked for unit clauses.
// So, we must perform a occurs check here.
else if (is_var_diseq(e, num_decls, v, t) && !occurs(v, t)) {
r = m.mk_false();
}
else
r = q;
if (m.proofs_enabled()) {
pr = r == q ? nullptr : m.mk_der(q, r);
}
}
static void der_sort_vars(ptr_vector<var> & vars, expr_ref_vector & definitions, unsigned_vector & order) {
order.reset();
// eliminate self loops, and definitions containing quantifiers.
bool found = false;
for (unsigned i = 0; i < definitions.size(); i++) {
var * v = vars[i];
expr * t = definitions.get(i);
if (t == nullptr || has_quantifiers(t) || occurs(v, t))
definitions[i] = nullptr;
else
found = true; // found at least one candidate
}
if (!found)
return;
typedef std::pair<expr *, unsigned> frame;
svector<frame> todo;
expr_fast_mark1 visiting;
expr_fast_mark2 done;
unsigned vidx, num;
for (unsigned i = 0; i < definitions.size(); i++) {
if (!definitions.get(i))
continue;
var * v = vars[i];
SASSERT(v->get_idx() == i);
SASSERT(todo.empty());
todo.push_back(frame(v, 0));
while (!todo.empty()) {
start:
frame & fr = todo.back();
expr * t = fr.first;
if (done.is_marked(t)) {
todo.pop_back();
continue;
}
switch (t->get_kind()) {
case AST_VAR:
vidx = to_var(t)->get_idx();
if (fr.second == 0) {
CTRACE("der_bug", vidx >= definitions.size(), tout << "vidx: " << vidx << "\n";);
// Remark: The size of definitions may be smaller than the number of variables occurring in the quantified formula.
if (definitions.get(vidx, nullptr) != nullptr) {
if (visiting.is_marked(t)) {
// cycle detected: remove t
visiting.reset_mark(t);
definitions[vidx] = nullptr;
}
else {
visiting.mark(t);
fr.second = 1;
todo.push_back(frame(definitions.get(vidx), 0));
goto start;
}
}
}
else {
SASSERT(fr.second == 1);
if (definitions.get(vidx, nullptr) != nullptr) {
visiting.reset_mark(t);
order.push_back(vidx);
}
else {
// var was removed from the list of candidate vars to elim cycle
// do nothing
}
}
done.mark(t);
todo.pop_back();
break;
case AST_QUANTIFIER:
UNREACHABLE();
todo.pop_back();
break;
case AST_APP:
num = to_app(t)->get_num_args();
while (fr.second < num) {
expr * arg = to_app(t)->get_arg(fr.second);
fr.second++;
if (done.is_marked(arg))
continue;
todo.push_back(frame(arg, 0));
goto start;
}
done.mark(t);
todo.pop_back();
break;
default:
UNREACHABLE();
todo.pop_back();
break;
}
}
}
}
void der::get_elimination_order() {
m_order.reset();
TRACE("top_sort",
tout << "DEFINITIONS: " << std::endl;
unsigned i = 0;
for (expr* e : m_map) {
if (e) tout << "VAR " << i << " = " << mk_pp(e, m) << std::endl;
++i;
}
);
// der::top_sort ts(m);
der_sort_vars(m_inx2var, m_map, m_order);
TRACE("der",
tout << "Elimination m_order:" << "\n";
tout << m_order << "\n";);
}
void der::create_substitution(unsigned sz) {
m_subst_map.reset();
m_subst_map.resize(sz, nullptr);
for(unsigned i = 0; i < m_order.size(); i++) {
expr_ref cur(m_map.get(m_order[i]), m);
// do all the previous substitutions before inserting
expr_ref r = m_subst(cur, m_subst_map.size(), m_subst_map.c_ptr());
unsigned inx = sz - m_order[i]- 1;
SASSERT(m_subst_map[inx]==0);
m_subst_map[inx] = r;
}
}
void der::apply_substitution(quantifier * q, expr_ref & r) {
expr * e = q->get_expr();
unsigned num_args=to_app(e)->get_num_args();
// get a new expression
m_new_args.reset();
for(unsigned i = 0; i < num_args; i++) {
int x = m_pos2var[i];
if (x != -1 && m_map.get(x) != nullptr)
continue; // this is a disequality with definition (vanishes)
m_new_args.push_back(to_app(e)->get_arg(i));
}
unsigned sz = m_new_args.size();
expr_ref t(m);
t = (sz == 1) ? m_new_args[0] : m.mk_or(sz, m_new_args.c_ptr());
expr_ref new_e = m_subst(t, m_subst_map.size(), m_subst_map.c_ptr());
// don't forget to update the quantifier patterns
expr_ref_buffer new_patterns(m);
expr_ref_buffer new_no_patterns(m);
for (unsigned j = 0; j < q->get_num_patterns(); j++) {
new_patterns.push_back(m_subst(q->get_pattern(j), m_subst_map.size(), m_subst_map.c_ptr()));
}
for (unsigned j = 0; j < q->get_num_no_patterns(); j++) {
new_no_patterns.push_back(m_subst(q->get_no_pattern(j), m_subst_map.size(), m_subst_map.c_ptr()));
}
r = m.update_quantifier(q, new_patterns.size(), new_patterns.c_ptr(),
new_no_patterns.size(), new_no_patterns.c_ptr(), new_e);
}
struct der_rewriter_cfg : public default_rewriter_cfg {
ast_manager& m;
der m_der;
der_rewriter_cfg(ast_manager & m): m(m), m_der(m) {}
bool reduce_quantifier(quantifier * old_q,
expr * new_body,
expr * const * new_patterns,
expr * const * new_no_patterns,
expr_ref & result,
proof_ref & result_pr) {
quantifier_ref q1(m);
q1 = m.update_quantifier(old_q, old_q->get_num_patterns(), new_patterns,
old_q->get_num_no_patterns(), new_no_patterns, new_body);
m_der(q1, result, result_pr);
return true;
}
};
template class rewriter_tpl<der_rewriter_cfg>;
struct der_rewriter::imp : public rewriter_tpl<der_rewriter_cfg> {
der_rewriter_cfg m_cfg;
imp(ast_manager & m):
rewriter_tpl<der_rewriter_cfg>(m, m.proofs_enabled(), m_cfg),
m_cfg(m) {
}
};
der_rewriter::der_rewriter(ast_manager & m) {
m_imp = alloc(imp, m);
}
der_rewriter::~der_rewriter() {
dealloc(m_imp);
}
void der_rewriter::operator()(expr * t, expr_ref & result, proof_ref & result_pr) {
m_imp->operator()(t, result, result_pr);
}
void der_rewriter::cleanup() {
ast_manager & m = m_imp->m_cfg.m;
dealloc(m_imp);
m_imp = alloc(imp, m);
}
void der_rewriter::reset() {
m_imp->reset();
}
| 12,432 | 4,349 |
#include <c10/util/Metaprogramming.h>
#include <c10/util/TypeIndex.h>
#include <gtest/gtest.h>
using c10::string_view;
using c10::util::get_fully_qualified_type_name;
using c10::util::get_type_index;
namespace {
static_assert(get_type_index<int>() == get_type_index<int>(), "");
static_assert(get_type_index<float>() == get_type_index<float>(), "");
static_assert(get_type_index<int>() != get_type_index<float>(), "");
static_assert(
get_type_index<int(double, double)>() ==
get_type_index<int(double, double)>(),
"");
static_assert(
get_type_index<int(double, double)>() != get_type_index<int(double)>(),
"");
static_assert(
get_type_index<int(double, double)>() ==
get_type_index<int (*)(double, double)>(),
"");
static_assert(
get_type_index<std::function<int(double, double)>>() ==
get_type_index<std::function<int(double, double)>>(),
"");
static_assert(
get_type_index<std::function<int(double, double)>>() !=
get_type_index<std::function<int(double)>>(),
"");
static_assert(get_type_index<int>() == get_type_index<int&>(), "");
static_assert(get_type_index<int>() == get_type_index<int&&>(), "");
static_assert(get_type_index<int>() == get_type_index<const int&>(), "");
static_assert(get_type_index<int>() == get_type_index<const int>(), "");
static_assert(get_type_index<const int>() == get_type_index<int&>(), "");
static_assert(get_type_index<int>() != get_type_index<int*>(), "");
static_assert(get_type_index<int*>() != get_type_index<int**>(), "");
static_assert(
get_type_index<int(double&, double)>() !=
get_type_index<int(double, double)>(),
"");
struct Dummy final {};
struct Functor final {
int64_t operator()(uint32_t, Dummy&&, const Dummy&) const;
};
static_assert(
get_type_index<int64_t(uint32_t, Dummy&&, const Dummy&)>() ==
get_type_index<
c10::guts::infer_function_traits_t<Functor>::func_type>(),
"");
namespace test_top_level_name {
#if C10_TYPENAME_SUPPORTS_CONSTEXPR
static_assert(
string_view::npos != get_fully_qualified_type_name<Dummy>().find("Dummy"),
"");
#endif
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(TypeIndex, TopLevelName) {
EXPECT_NE(
string_view::npos, get_fully_qualified_type_name<Dummy>().find("Dummy"));
}
} // namespace test_top_level_name
namespace test_nested_name {
struct Dummy final {};
#if C10_TYPENAME_SUPPORTS_CONSTEXPR
static_assert(
string_view::npos !=
get_fully_qualified_type_name<Dummy>().find("test_nested_name::Dummy"),
"");
#endif
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(TypeIndex, NestedName) {
EXPECT_NE(
string_view::npos,
get_fully_qualified_type_name<Dummy>().find("test_nested_name::Dummy"));
}
} // namespace test_nested_name
namespace test_type_template_parameter {
template <class T>
struct Outer final {};
struct Inner final {};
#if C10_TYPENAME_SUPPORTS_CONSTEXPR
static_assert(
string_view::npos !=
get_fully_qualified_type_name<Outer<Inner>>().find(
"test_type_template_parameter::Outer"),
"");
static_assert(
string_view::npos !=
get_fully_qualified_type_name<Outer<Inner>>().find(
"test_type_template_parameter::Inner"),
"");
#endif
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(TypeIndex, TypeTemplateParameter) {
EXPECT_NE(
string_view::npos,
get_fully_qualified_type_name<Outer<Inner>>().find(
"test_type_template_parameter::Outer"));
EXPECT_NE(
string_view::npos,
get_fully_qualified_type_name<Outer<Inner>>().find(
"test_type_template_parameter::Inner"));
}
} // namespace test_type_template_parameter
namespace test_nontype_template_parameter {
template <size_t N>
struct Class final {};
#if C10_TYPENAME_SUPPORTS_CONSTEXPR
static_assert(
string_view::npos !=
get_fully_qualified_type_name<Class<38474355>>().find("38474355"),
"");
#endif
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(TypeIndex, NonTypeTemplateParameter) {
EXPECT_NE(
string_view::npos,
get_fully_qualified_type_name<Class<38474355>>().find("38474355"));
}
} // namespace test_nontype_template_parameter
namespace test_type_computations_are_resolved {
template <class T>
struct Type final {
using type = const T*;
};
#if C10_TYPENAME_SUPPORTS_CONSTEXPR
static_assert(
string_view::npos !=
get_fully_qualified_type_name<typename Type<int>::type>().find("int"),
"");
static_assert(
string_view::npos !=
get_fully_qualified_type_name<typename Type<int>::type>().find("*"),
"");
// but with remove_pointer applied, there is no '*' in the type name anymore
static_assert(
string_view::npos ==
get_fully_qualified_type_name<
typename std::remove_pointer<typename Type<int>::type>::type>()
.find("*"),
"");
#endif
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(TypeIndex, TypeComputationsAreResolved) {
EXPECT_NE(
string_view::npos,
get_fully_qualified_type_name<typename Type<int>::type>().find("int"));
EXPECT_NE(
string_view::npos,
get_fully_qualified_type_name<typename Type<int>::type>().find("*"));
// but with remove_pointer applied, there is no '*' in the type name anymore
EXPECT_EQ(
string_view::npos,
get_fully_qualified_type_name<
typename std::remove_pointer<typename Type<int>::type>::type>()
.find("*"));
}
struct Functor final {
std::string operator()(int64_t a, const Type<int>& b) const;
};
#if C10_TYPENAME_SUPPORTS_CONSTEXPR
static_assert(
get_fully_qualified_type_name<std::string(int64_t, const Type<int>&)>() ==
get_fully_qualified_type_name<
typename c10::guts::infer_function_traits_t<Functor>::func_type>(),
"");
#endif
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(TypeIndex, FunctionTypeComputationsAreResolved) {
EXPECT_EQ(
get_fully_qualified_type_name<std::string(int64_t, const Type<int>&)>(),
get_fully_qualified_type_name<
typename c10::guts::infer_function_traits_t<Functor>::func_type>());
}
} // namespace test_type_computations_are_resolved
namespace test_function_arguments_and_returns {
class Dummy final {};
#if C10_TYPENAME_SUPPORTS_CONSTEXPR
static_assert(
string_view::npos !=
get_fully_qualified_type_name<Dummy(int)>().find(
"test_function_arguments_and_returns::Dummy"),
"");
static_assert(
string_view::npos !=
get_fully_qualified_type_name<void(Dummy)>().find(
"test_function_arguments_and_returns::Dummy"),
"");
#endif
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(TypeIndex, FunctionArgumentsAndReturns) {
EXPECT_NE(
string_view::npos,
get_fully_qualified_type_name<Dummy(int)>().find(
"test_function_arguments_and_returns::Dummy"));
EXPECT_NE(
string_view::npos,
get_fully_qualified_type_name<void(Dummy)>().find(
"test_function_arguments_and_returns::Dummy"));
}
} // namespace test_function_arguments_and_returns
} // namespace
| 7,254 | 2,616 |
// Copyright © 2017-2020 Trust Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#include "../interface/TWTestUtilities.h"
#include <PPTrustWalletCore/TWBitcoinScript.h>
#include <gtest/gtest.h>
TEST(Doge, LockScripts) {
auto script = WRAP(TWBitcoinScript, TWBitcoinScriptBuildForAddress(STRING("DLSSSUS3ex7YNDACJDxMER1ZMW579Vy8Zy").get(), TWCoinTypeDogecoin));
auto scriptData = WRAPD(TWBitcoinScriptData(script.get()));
assertHexEqual(scriptData, "76a914a7d191ec42aa113e28cd858cceaa7c733ba2f77788ac");
auto script2 = WRAP(TWBitcoinScript, TWBitcoinScriptBuildForAddress(STRING("AETZJzedcmLM2rxCM6VqCGF3YEMUjA3jMw").get(), TWCoinTypeDogecoin));
auto scriptData2 = WRAPD(TWBitcoinScriptData(script2.get()));
assertHexEqual(scriptData2, "a914f191149f72f235548746654f5b473c58258f7fb687");
}
| 997 | 430 |
/**
* Copyright (c) 2016-2017 Los Alamos National Security, LLC
* All rights reserved.
*
* Copyright (c) 2016 Stanford University
*
* 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.
*
* 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.
*
* LA-CC 10-123
*/
#pragma once
#include "TaskTIDs.hpp"
#include "Types.hpp"
#include "legion.h"
#include <vector>
#include <map>
#include <unistd.h>
using namespace LegionRuntime::HighLevel;
using namespace LegionRuntime::Accessor;
using namespace LegionRuntime::HighLevel;
#define RW READ_WRITE
#define RO READ_ONLY
#define WO WRITE_ONLY
#define RW_E READ_WRITE, EXCLUSIVE
#define RO_E READ_ONLY , EXCLUSIVE
#define WO_E WRITE_ONLY, EXCLUSIVE
#define RW_S READ_WRITE, SIMULTANEOUS
#define RO_S READ_ONLY , SIMULTANEOUS
#define WO_S WRITE_ONLY, SIMULTANEOUS
// Let the RT know that we 'know what we are doing'
static constexpr bool silenceWarnings = true;
////////////////////////////////////////////////////////////////////////////////
// Task forward declarations.
////////////////////////////////////////////////////////////////////////////////
void
mainTask(
const Task *task,
const std::vector<PhysicalRegion> ®ions,
Context ctx, HighLevelRuntime *runtime
);
void
genProblemTask(
const Task *task,
const std::vector<PhysicalRegion> ®ions,
Context ctx, HighLevelRuntime *runtime
);
void
startBenchmarkTask(
const Task *task,
const std::vector<PhysicalRegion> ®ions,
Context ctx, HighLevelRuntime *runtime
);
void
regionToRegionCopyTask(
const Task *task,
const std::vector<PhysicalRegion> ®ions,
Context ctx, HighLevelRuntime *runtime
);
void
registerCollectiveOpsTasks(void);
void
registerVectorOpTasks(void);
void
registerWAXPBYTasks(void);
void
registerSPMVTasks(void);
void
registerDDotTasks(void);
void
registerSYMGSTasks(void);
void
registerProlongationTasks(void);
void
registerRestrictionTasks(void);
void
registerFutureMathTasks(void);
void
registerComputeResidualTasks(void);
void
registerExchangeHaloTasks(void);
////////////////////////////////////////////////////////////////////////////////
// Task Registration
////////////////////////////////////////////////////////////////////////////////
inline void
registerTasks(void)
{
TaskVariantRegistrar tvr(MAIN_TID, "mainTask");
tvr.add_constraint(ProcessorConstraint(Processor::LOC_PROC));
Runtime::preregister_task_variant<mainTask>(tvr, "mainTask");
Runtime::set_top_level_task_id(MAIN_TID);
//
HighLevelRuntime::register_legion_task<genProblemTask>(
GEN_PROB_TID /* task id */,
Processor::LOC_PROC /* proc kind */,
true /* single */,
true /* index */,
AUTO_GENERATE_ID,
TaskConfigOptions(false /* leaf task */),
"genProblemTask"
);
HighLevelRuntime::register_legion_task<startBenchmarkTask>(
START_BENCHMARK_TID /* task id */,
Processor::LOC_PROC /* proc kind */,
true /* single */,
true /* index */,
AUTO_GENERATE_ID,
TaskConfigOptions(false /* leaf task */),
"startBenchmarkTask"
);
HighLevelRuntime::register_legion_task<regionToRegionCopyTask>(
REGION_TO_REGION_COPY_TID /* task id */,
Processor::LOC_PROC /* proc kind */,
true /* single */,
true /* index */,
AUTO_GENERATE_ID,
TaskConfigOptions(true /* leaf task */),
"regionToRegionCopyTask"
);
//
registerCollectiveOpsTasks();
//
registerVectorOpTasks();
//
registerWAXPBYTasks();
//
registerSPMVTasks();
//
registerDDotTasks();
//
registerSYMGSTasks();
//
registerProlongationTasks();
//
registerRestrictionTasks();
//
registerFutureMathTasks();
//
registerComputeResidualTasks();
//
registerExchangeHaloTasks();
}
////////////////////////////////////////////////////////////////////////////////
inline void
updateMappers(
Machine machine,
HighLevelRuntime *runtime,
const std::set<Processor> &local_procs
) {
#if 0 // Disable for now.
for (const auto &p : local_procs) {
runtime->replace_default_mapper(new CGMapper(machine, runtime, p), p);
}
#endif
}
////////////////////////////////////////////////////////////////////////////////
inline void
LegionInit(void)
{
registerTasks();
HighLevelRuntime::set_registration_callback(updateMappers);
}
/**
* Courtesy of some other legion code.
*/
template <unsigned DIM, typename T>
inline bool
offsetsAreDense(
const Rect<DIM> &bounds,
const LegionRuntime::Accessor::ByteOffset *offset
) {
#ifdef LGNCG_ASSUME_DENSE_OFFSETS
return true;
#else
off_t exp_offset = sizeof(T);
for (unsigned i = 0; i < DIM; i++) {
bool found = false;
for (unsigned j = 0; j < DIM; j++)
if (offset[j].offset == exp_offset) {
found = true;
exp_offset *= (bounds.hi[j] - bounds.lo[j] + 1);
break;
}
if (!found) return false;
}
return true;
#endif
}
/**
* Courtesy of some other legion code.
*/
inline bool
offsetMismatch(
int i,
const LegionRuntime::Accessor::ByteOffset *off1,
const LegionRuntime::Accessor::ByteOffset *off2
) {
#ifdef LGNCG_ASSUME_MATCHING_OFFSETS
return false;
#else
while (i-- > 0) {
if ((off1++)->offset != (off2++)->offset) return true;
}
return false;
#endif
}
/**
* Convenience routine to get a task's ID.
*/
inline int
getTaskID(
const Task *task
) {
return task->index_point.point_data[0];
}
/**
*
*/
inline size_t
getNumProcs(void)
{
size_t nProc = 0;
std::set<Processor> allProcs;
Realm::Machine::get_machine().get_all_processors(allProcs);
for (auto &p : allProcs) {
if (p.kind() == Processor::LOC_PROC) nProc++;
}
return nProc;
}
| 7,112 | 2,316 |
/*
ISC License
Copyright (c) 2016, Antonio SJ Musumeci <trapexit@spawn.link>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "blkdev.hpp"
#include "captcha.hpp"
#include "errors.hpp"
#include "file.hpp"
#include "filetoblkdev.hpp"
#include "options.hpp"
#include "signals.hpp"
#include <iostream>
#include <utility>
#include <errno.h>
#include <stdint.h>
namespace l
{
static
int
fix_file_loop_core(BlkDev &blkdev_,
char *buf_,
const uint64_t buflen_,
const unsigned int retries_,
const uint64_t badblock_)
{
int rv;
uint64_t attempts;
if(signals::signaled_to_exit())
return -EINTR;
rv = blkdev_.read(badblock_,1,buf_,buflen_);
for(attempts = 1; ((attempts <= retries_) && (rv < 0)); attempts++)
{
std::cout << "Reading block "
<< badblock_
<< " failed (attempt "
<< attempts << " of " << retries_
<< "[" << Error::to_string(-rv) << "]: trying again"
<< std::endl;
rv = blkdev_.read(badblock_,1,buf_,buflen_);
}
if(rv < 0)
{
std::cout << "Reading block "
<< badblock_
<< " failed ("
<< attempts << " attempts) "
<< "[" << Error::to_string(-rv) << "]: using zeros"
<< std::endl;
::memset(buf_,0,buflen_);
}
rv = blkdev_.write(badblock_,1,buf_,buflen_);
for(attempts = 1; ((attempts <= retries_) && (rv < 0)); attempts++)
{
std::cout << "Writing block "
<< badblock_
<< " failed (attempt "
<< attempts << " of " << retries_
<< "[" << Error::to_string(-rv) << "]: trying again"
<< std::endl;
rv = blkdev_.write(badblock_,1,buf_,buflen_);
}
if(rv < 0)
std::cout << "Writing block "
<< badblock_
<< " failed ("
<< attempts << " attempts) "
<< "[" << Error::to_string(-rv) << "]"
<< std::endl;
return 0;
}
static
int
fix_file_loop(BlkDev &blkdev_,
const File::BlockVector &blockvector_,
const unsigned int retries_)
{
int rv;
char *buf;
uint64_t buflen;
buflen = blkdev_.logical_block_size();
buf = new char[buflen];
for(uint64_t i = 0, ei = blockvector_.size(); i != ei; i++)
{
uint64_t j = blockvector_[i].block;
const uint64_t ej = blockvector_[i].length + j;
for(; j != ej; j++)
{
rv = l::fix_file_loop_core(blkdev_,buf,buflen,retries_,j);
if(rv < 0)
break;
}
}
delete[] buf;
return rv;
}
static
void
set_blkdev_rwtype(BlkDev &blkdev,
const Options::RWType rwtype)
{
switch(rwtype)
{
case Options::ATA:
blkdev.set_rw_ata();
break;
case Options::OS:
blkdev.set_rw_os();
break;
}
}
static
AppError
fix_file(const Options &opts_)
{
int rv;
BlkDev blkdev;
std::string devpath;
File::BlockVector blockvector;
rv = File::blocks(opts_.device,blockvector);
if(rv < 0)
return AppError::opening_file(-rv,opts_.device);
devpath = FileToBlkDev::find(opts_.device);
if(devpath.empty())
return AppError::opening_device(ENOENT,opts_.device);
rv = blkdev.open_rdwr(devpath,!opts_.force);
if(rv < 0)
return AppError::opening_device(-rv,devpath);
l::set_blkdev_rwtype(blkdev,opts_.rwtype);
const std::string captcha = captcha::calculate(blkdev);
if(opts_.captcha != captcha)
return AppError::captcha(opts_.captcha,captcha);
rv = l::fix_file_loop(blkdev,blockvector,opts_.retries);
rv = blkdev.close();
if(rv < 0)
return AppError::closing_device(-rv,opts_.device);
return AppError::success();
}
}
namespace bbf
{
AppError
fix_file(const Options &opts_)
{
return l::fix_file(opts_);
}
}
| 4,921 | 1,724 |
//
// MemoryFuzzer.cpp
// Clock Signal
//
// Created by Thomas Harte on 19/10/2016.
// Copyright 2016 Thomas Harte. All rights reserved.
//
#include "MemoryFuzzer.hpp"
#include <cstdlib>
void Memory::Fuzz(uint8_t *buffer, std::size_t size) {
unsigned int divider = (static_cast<unsigned int>(RAND_MAX) + 1) / 256;
unsigned int shift = 1, value = 1;
while(value < divider) {
value <<= 1;
shift++;
}
for(std::size_t c = 0; c < size; c++) {
buffer[c] = static_cast<uint8_t>(std::rand() >> shift);
}
}
void Memory::Fuzz(std::vector<uint8_t> &buffer) {
Fuzz(buffer.data(), buffer.size());
}
| 608 | 265 |
//
// FILE NAME: CIDMacroEng_SysInfoClass.cpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 02/20/2003
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2019
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This file implements the macro level MEng.System.Runtime.SysInfo class.
// It just provides some global information of interest, and defines a
// commonly used error enum.
//
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $_CIDLib_Log_$
//
// ---------------------------------------------------------------------------
// Facility specific includes
// ---------------------------------------------------------------------------
#include "CIDMacroEng_.hpp"
// ---------------------------------------------------------------------------
// Magic RTTI macros
// ---------------------------------------------------------------------------
RTTIDecls(TMEngSysInfoInfo,TMEngClassInfo)
// ---------------------------------------------------------------------------
// Local data
// ---------------------------------------------------------------------------
namespace CIDMacroEng_SysInfoClass
{
};
// ---------------------------------------------------------------------------
// CLASS: TMEngSysInfoInfo
// PREFIX: meci
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TMEngSysInfoInfo: Constructors and Destructor
// ---------------------------------------------------------------------------
TMEngSysInfoInfo::TMEngSysInfoInfo(TCIDMacroEngine& meOwner) :
TMEngClassInfo
(
L"SysInfo"
, TFacCIDMacroEng::strRuntimeClassPath
, meOwner
, kCIDLib::False
, tCIDMacroEng::EClassExt::Final
, L"MEng.Object"
)
, m_c2MethId_DefCtor(kMacroEng::c2BadId)
, m_c2MethId_GetCPUCount(kMacroEng::c2BadId)
, m_c2MethId_GetNodeName(kMacroEng::c2BadId)
{
}
TMEngSysInfoInfo::~TMEngSysInfoInfo()
{
}
// ---------------------------------------------------------------------------
// TMEngSysInfoInfo: Public, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TVoid TMEngSysInfoInfo::Init(TCIDMacroEngine&)
{
// Add the default constructor
{
TMEngMethodInfo methiNew
(
L"ctor1_MEng.System.Runtime.SysInfo"
, tCIDMacroEng::EIntrinsics::Void
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
);
methiNew.bIsCtor(kCIDLib::True);
m_c2MethId_DefCtor = c2AddMethodInfo(methiNew);
}
// Get the local node name
{
TMEngMethodInfo methiNew
(
L"GetNodeName"
, tCIDMacroEng::EIntrinsics::String
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
m_c2MethId_GetNodeName = c2AddMethodInfo(methiNew);
}
// Get the number of CPUs
{
TMEngMethodInfo methiNew
(
L"GetCPUCount"
, tCIDMacroEng::EIntrinsics::Card4
, tCIDMacroEng::EVisTypes::Public
, tCIDMacroEng::EMethExt::Final
, tCIDMacroEng::EConstTypes::Const
);
m_c2MethId_GetCPUCount = c2AddMethodInfo(methiNew);
}
}
TMEngClassVal*
TMEngSysInfoInfo::pmecvMakeStorage( const TString& strName
, TCIDMacroEngine& meOwner
, const tCIDMacroEng::EConstTypes eConst) const
{
return new TMEngStdClassVal(strName, c2Id(), eConst);
}
// ---------------------------------------------------------------------------
// TMacroEngSysInfoInfo: Protected, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TBoolean
TMEngSysInfoInfo::bInvokeMethod( TCIDMacroEngine& meOwner
, const TMEngMethodInfo& methiTarget
, TMEngClassVal& mecvInstance)
{
const tCIDLib::TCard4 c4FirstInd = meOwner.c4FirstParmInd(methiTarget);
const tCIDLib::TCard2 c2MethId = methiTarget.c2Id();
if (c2MethId == m_c2MethId_DefCtor)
{
// Nothing to do
}
else if (c2MethId == m_c2MethId_GetCPUCount)
{
// Get the return value and set it with the indicated char
TMEngCard4Val& mecvRet
= meOwner.mecvStackAtAs<TMEngCard4Val>(c4FirstInd - 1);
mecvRet.c4Value(TSysInfo::c4CPUCount());
}
else if (c2MethId == m_c2MethId_GetNodeName)
{
// Get the return value and set it with the indicated char
TMEngStringVal& mecvRet
= meOwner.mecvStackAtAs<TMEngStringVal>(c4FirstInd - 1);
mecvRet.strValue(TSysInfo::strIPHostName());
}
else
{
return kCIDLib::False;
}
return kCIDLib::True;
}
| 5,172 | 1,625 |
/*
Copyright (c) 2016-2020 Xavier Leclercq
Released under the MIT License
See https://github.com/Ishiko-cpp/Process/blob/master/LICENSE.txt
*/
#include "ChildProcessTests.h"
#include "Ishiko/Process/ChildProcess.h"
using namespace Ishiko;
using namespace Ishiko::Process;
using namespace Ishiko::Tests;
ChildProcessTests::ChildProcessTests(const TestNumber& number, const TestEnvironment& environment)
: TestSequence(number, "ChildProcess tests", environment)
{
append<HeapAllocationErrorsTest>("Constructor test 1", ConstructorTest1);
append<HeapAllocationErrorsTest>("Spawn test 1", SpawnTest1);
append<HeapAllocationErrorsTest>("Spawn test 2", SpawnTest2);
}
void ChildProcessTests::ConstructorTest1(Test& test)
{
ChildProcess handle;
ISHTF_PASS();
}
void ChildProcessTests::SpawnTest1(Test& test)
{
#ifdef __linux__
boost::filesystem::path executablePath(test.environment().getTestDataDirectory() / "Bin/ExitCodeTestHelper");
#else
boost::filesystem::path executablePath(test.environment().getTestDataDirectory() / "Bin/ExitCodeTestHelper.exe");
#endif
ChildProcess handle = ChildProcess::Spawn(executablePath.string());
handle.waitForExit();
ISHTF_FAIL_IF_NEQ(handle.exitCode(), 0);
ISHTF_PASS();
}
void ChildProcessTests::SpawnTest2(Test& test)
{
#ifdef __linux__
boost::filesystem::path executablePath(test.environment().getTestDataDirectory() / "Bin/ExitCodeTestHelper");
#else
boost::filesystem::path executablePath(test.environment().getTestDataDirectory() / "Bin/ExitCodeTestHelper.exe");
#endif
Error error(0);
ChildProcess handle = ChildProcess::Spawn(executablePath.string(), error);
ISHTF_ABORT_IF(error);
handle.waitForExit();
ISHTF_FAIL_IF_NEQ(handle.exitCode(), 0);
ISHTF_PASS();
}
| 1,810 | 597 |
#include <jni.h>
#include <string>
#include <termios.h>
#include <fcntl.h>
#include <unistd.h>
#include "include/SerialPort.h"
#include "include/SerialPortLog.h"
static speed_t getBaudRate(jint baud_rate) {
switch (baud_rate) {
case 0:
return B0;
case 50:
return B50;
case 75:
return B75;
case 110:
return B110;
case 134:
return B134;
case 150:
return B150;
case 200:
return B200;
case 300:
return B300;
case 600:
return B600;
case 1200:
return B1200;
case 1800:
return B1800;
case 2400:
return B2400;
case 4800:
return B4800;
case 9600:
return B9600;
case 19200:
return B19200;
case 38400:
return B38400;
case 57600:
return B57600;
case 115200:
return B115200;
case 230400:
return B230400;
case 460800:
return B460800;
case 500000:
return B500000;
case 576000:
return B576000;
case 921600:
return B921600;
case 1000000:
return B1000000;
case 1152000:
return B1152000;
case 1500000:
return B1500000;
case 2000000:
return B2000000;
case 2500000:
return B2500000;
case 3000000:
return B3000000;
case 3500000:
return B3500000;
case 4000000:
return B4000000;
default:
return -1;
}
}
extern "C"
JNIEXPORT jobject JNICALL
Java_com_serial_port_kit_core_SerialPort_open(JNIEnv *env, jobject thiz, jstring path,
jint baud_rate, jint flags) {
int fd;
speed_t speed;
jobject mFileDescriptor;
/* Check arguments */
speed = getBaudRate(baud_rate);
if (speed == -1) {
LOGE("Invalid baudRate");
return nullptr;
}
/* Opening device */
const char *path_utf = env->GetStringUTFChars(path, nullptr);
LOGD("Opening serial port %s with flags 0x%x", path_utf, O_RDWR | flags);
fd = open(path_utf, O_RDWR | flags);
LOGD("open() fd = %d", fd);
env->ReleaseStringUTFChars(path, path_utf);
if (fd == -1) {
LOGE("不能打开串口:%s", path_utf);
return nullptr;
}
/* Configure device */
struct termios cfg{};
LOGD("Configuring serial port");
if (tcgetattr(fd, &cfg)) {
LOGE("读取终端的配置失败");
close(fd);
return nullptr;
}
cfmakeraw(&cfg);
cfsetispeed(&cfg, speed);
cfsetospeed(&cfg, speed);
if (tcsetattr(fd, TCSANOW, &cfg)) {
LOGE("写入终端的配置失败");
close(fd);
return nullptr;
}
/* Create a corresponding file descriptor */
jclass cFileDescriptor = env->FindClass("java/io/FileDescriptor");
jmethodID iFileDescriptor = env->GetMethodID(cFileDescriptor, "<init>", "()V");
jfieldID descriptorID = env->GetFieldID(cFileDescriptor, "descriptor", "I");
mFileDescriptor = env->NewObject(cFileDescriptor, iFileDescriptor);
env->SetIntField(mFileDescriptor, descriptorID, (jint) fd);
return mFileDescriptor;
}
extern "C"
JNIEXPORT void JNICALL
Java_com_serial_port_kit_core_SerialPort_close(JNIEnv *env, jobject thiz) {
jclass SerialPortClass = env->GetObjectClass(thiz);
jclass FileDescriptorClass = env->FindClass("java/io/FileDescriptor");
jfieldID mFdID = env->GetFieldID(SerialPortClass, "mFd", "Ljava/io/FileDescriptor;");
jfieldID descriptorID = env->GetFieldID(FileDescriptorClass, "descriptor", "I");
jobject mFd = env->GetObjectField(thiz, mFdID);
jint descriptor = env->GetIntField(mFd, descriptorID);
LOGD("close(fd = %d)", descriptor);
close(descriptor);
} | 3,962 | 1,526 |
#include "stdhdr.h"
#include "simveh.h"
#include "digi.h"
#include "object.h"
#include "simbase.h"
#include "airframe.h"
#include "team.h"
#include "aircrft.h"
#include "sms.h"
#define INIT_GUN_VEL 4500.0f //me123 changed from 3500.0F
extern float SimLibLastMajorFrameTime;
void DigitalBrain::GunsJinkCheck(void)
{
float tgt_time=0.0F,att_time=0.0F,z=0.0F, timeDelta=0.0F;
int twoSeconds=0;
unsigned long lastUpdate=0;
SimObjectType* obj = targetPtr;
SimObjectLocalData* localData=NULL;
/*-----------------------------------------------*/
/* Entry conditions- */
/* */
/* 1. Target range <= INIT_GUN_VEL feet. */
/* 2. Target time to fire < ownship time to fire */
/* 3. Predicted bullet fire <= 2 seconds. */
/*-----------------------------------------------*/
//me123 lets check is closure is resonable too before goin into jink mode
if (curMode != GunsJinkMode)
{
if ( obj == NULL )
return;
if ( obj->BaseData()->IsSim() &&
(((SimBaseClass*)obj->BaseData())->IsFiring() ||
TeamInfo[self->GetTeam()]->TStance(obj->BaseData()->GetTeam()) == War))
{
localData = obj->localData;
if ((localData->range > 0.0f) && (localData->range < 6000.0f))//localData->rangedot > -240.0f * FTPSEC_TO_KNOTS )//me123 don't jink if he's got a high closure, he probaly woun't shoot a low Pk shot
{
if (localData->range < INIT_GUN_VEL )
{
/*-----------------------------------*/
/* predict time of possible gun fire */
/*-----------------------------------*/
twoSeconds = FALSE;
jinkTime = -1;
z = localData->range / INIT_GUN_VEL;
if ( localData->azFrom > -15.0F * DTR && localData->azFrom < (15.0F * DTR))//me123 status test. changed from 2.0 to 5.0 multible places here becourse we are not always in plane when gunning
{
twoSeconds = TRUE;
}
else if (localData->azFrom > (5.0F * DTR) && localData->azFromdot < 0.0F)
{
if (localData->azFrom + z * localData->azFromdot < (5.0F * DTR))
twoSeconds = TRUE;
}
else if (localData->azFrom < (-5.0F * DTR) && localData->azFromdot > 0.0F)
{
if (localData->azFrom + z * localData->azFromdot > (-5.0F * DTR))
twoSeconds = TRUE;
}
if (twoSeconds)
{
twoSeconds = FALSE;
if (localData->elFrom < (4.0F *DTR) && localData->elFrom > (-10.0F * DTR))//me123 status test. changed all
{
twoSeconds = TRUE;
}
// else if (localData->elFrom > (-2.0F *DTR) && localData->elFromdot < 0.0F)
// {
// if (localData->elFrom + z* localData->elFromdot < (-2.0F *DTR))
// twoSeconds = TRUE;
// }
// else if (localData->elFrom < (-13.0F * DTR) && localData->elFromdot > 0.0F)
// {
// if (localData->elFrom + z* localData->elFromdot > (-13.0F * DTR))
// twoSeconds = TRUE;
// }
/*-------------------------------------------------*/
/* estimate time to be targeted and time to attack */
/*-------------------------------------------------*/
lastUpdate = targetPtr->BaseData()->LastUpdateTime();
if (lastUpdate == vuxGameTime)
timeDelta = SimLibMajorFrameTime;
else
timeDelta = SimLibLastMajorFrameTime;
/*-----------*/
/* him -> me */
/*-----------*/
tgt_time = ((localData->ataFrom / localData->ataFromdot) * timeDelta);
// if (tgt_time < 0.0F)//me123 status test,
// tgt_time = 99.0F;//me123 status test,
if (localData->ataFrom > -13.0f *DTR && localData->ataFrom < 13.0f *DTR) {tgt_time = 0.0f;}//me123 status test,
/*-----------*/
/* me -> him */
/*-----------*/
att_time = (localData->ata / localData->atadot) * timeDelta;
// if (att_time < 0.0F)//me123 status test,
// att_time = 99.0F;//me123 status test,
if (localData->ata > -13.0f *DTR && localData->ata < 13.0f *DTR) {att_time = 0.0f;}//me123 status test,
}
/*--------------*/
/* trigger jink */
/*--------------*/
if (twoSeconds && tgt_time <= att_time)
{
AddMode(GunsJinkMode);
}
}
}
}
} // if not guns jink mode
/*------------------------------------*/
/* else already in guns jink */
/* this maneuver is timed and removes */
/* itself, but we must make sure the */
/* threat is still around */
/*------------------------------------*/
}
void DigitalBrain::GunsJink(void)
{
float aspect, roll_offset, eroll;
SimObjectLocalData* gunsJinkData;
SimObjectType* obj = targetList;
//int randVal;
float maxPull;
/*------------------------------------*/
/* this maneuver is timed and removes */
/* itself, but we must make sure the */
/* threat is still around */
/*------------------------------------*/
if ( targetPtr == NULL || targetPtr->BaseData()->IsExploding() ||
targetPtr && targetPtr->localData->range > 4000)
{
// bail, no target
jinkTime = -1;
return;
}
// Cobra No need to go through all the stuff if we need to avoid the ground
if(groundAvoidNeeded)
return;
/*-------------------*/
/* energy management */
/*-------------------*/
MachHold(cornerSpeed,self->GetKias(), FALSE);//me123 from TRUE
/*--------------------*/
/* find target aspect */
/*--------------------*/
gunsJinkData = targetPtr->localData;
aspect = 180.0F * DTR - gunsJinkData->ata;
/*-----------------*/
/* pick roll angle */
/*-----------------*/
if (jinkTime == -1)
{
// Should I jettison stores?
if (self->CombatClass() != MnvrClassBomber)
{
//Cobra we do this always
self->Sms->AGJettison();
SelectGroundWeapon();
}
ResetMaxRoll();
/*--------------------------------*/
/* aspect >= 60 degrees */
/* put plane of wings on attacker */
/*--------------------------------*/
if (aspect >= 90.0F * DTR)//me123 changed from 60
{
/* offset required to put wings on attacker */
if (gunsJinkData->droll >= 0.0F) roll_offset = gunsJinkData->droll - 90.0F * DTR;
else roll_offset = gunsJinkData->droll + 90.0F * DTR;
/* generate new phi angle */
newroll = self->Roll() + roll_offset;
}
/*---------------------*/
/* aspect < 60 degrees */
/* roll +- 90 degrees */
/*---------------------*/
else
{
/* special in-plane crossing case, go the opposite direction */
if (targetPtr && ((targetPtr->BaseData()->Yaw() - self->Yaw() < 15.0F * DTR) &&
(targetPtr->BaseData()->Pitch() - self->Pitch() < 15.0F * DTR) &&
(targetPtr->BaseData()->Roll() - self->Roll() < 15.0F * DTR)))
{
if (gunsJinkData->droll >= 0.0F && gunsJinkData->az > 0.0F)
{
newroll = self->Roll() + 90.0F * DTR;
}
else if (gunsJinkData->droll < 0.0F && gunsJinkData->az < 0.0F)
{
newroll = self->Roll() - 90.0F * DTR;
}
else /* fall out, normal case */
{
if (gunsJinkData->droll > 0.0F)
newroll = self->Roll() - 70.0F * DTR; //me123 status test changed from 90
else
newroll = self->Roll() + 70.0F * DTR;//me123 status test changed from 90
}
}
/* normal jink */
else
{
if (gunsJinkData->droll > 0.0F)
newroll = self->Roll() - 70.0F * DTR;//me123 status test changed from 90
else
newroll = self->Roll() + 70.0F * DTR;//me123 status test changed from 90
}
/*--------------------------------------------*/
/* roll down if speed <= 60% of corner speed */
/*--------------------------------------------*/
if (self->GetKias() <= 0.8F * cornerSpeed)//me123 status test. changed from 0.6
{
if (newroll >= 0.0F && newroll <= 45.0F * DTR)
newroll += 30.0F * DTR;//me123 status test changed from 20
else if (newroll <= 0.0F && newroll >= -45.0F * DTR)
newroll -= 30.0F * DTR;//me123 status test changed from 20
}
}
/*------------------------*/
/* roll angle corrections */
/*------------------------*/
if (newroll > 180.0F * DTR)
newroll -= 360.0F * DTR;
else if (newroll < -180.0F * DTR)
newroll += 360.0F * DTR;
// Clamp roll to limits
if (newroll > af->MaxRoll())
newroll = af->MaxRoll();
else if (newroll < -af->MaxRoll())
newroll = -af->MaxRoll();
jinkTime = 0;
}
// Allow unlimited rolling
if (self->CombatClass() != MnvrClassBomber)
SetMaxRoll (190.0F);
/*---------------------------*/
/* roll to the desired angle */
/*---------------------------*/
if (jinkTime == 0)
{
SetPstick (-2.0F, maxGs, AirframeClass::GCommand);
/*------------*/
/* roll error */
/*------------*/
eroll = newroll - self->Roll();
/*-----------------------------*/
/* roll the shortest direction */
/*-----------------------------*/
eroll = SetRstick( eroll * RTD * 4.0F) * DTR;
SetMaxRollDelta (eroll);
//me123 and pull like hell
maxPull = max (0.8F * af->MaxGs(), maxGs);
SetPstick ( maxPull, af->MaxGs(), AirframeClass::GCommand);
/*-----------------------*/
/* stop rolling and pull */
/*-----------------------*/
if (fabs(eroll) < 5.0F * DTR)//me123 status test, from 5
{
jinkTime = 1;
SetRstick( 0.5F );//me123 status test, from 0
}
}
/*-----------------------*/
/* pull max gs for 2 sec */
/*-----------------------*/
if (jinkTime > 0 || groundAvoidNeeded)
{
maxPull = max (0.8F * af->MaxGs(), maxGs);
SetPstick ( maxPull, af->MaxGs(), AirframeClass::GCommand);
if (jinkTime++ > SimLibMajorFrameRate*2.0F + 1.0F)//me123 status test, pull for 5sec instead of 2
{
ResetMaxRoll();
jinkTime = -1;
}
else
{
// Stay in guns jink
AddMode(GunsJinkMode);
}
}
else
{
// Stay in guns jink
AddMode(GunsJinkMode);
}
}
| 10,476 | 3,951 |
#include "FileContainer.h"
/**
*
* Class FileContainer:
*
* Member Variables:
* std::string file_name; -> initialised in the constructor
* std::vector<std::string> -> loaded from file file_name in the constructor.
*
*
**/
// FileContainer::FileContainer(std::string file_name_in);
// @param file_name_in - the name of the input file the FileContainer object represents.
// FileContainer is a 1:1 relationship between an input file and it's representation in the program.
// each FileContainer is a container for one specific file.
// The constructor loads the file into a std::vector<std::string> stored as a member variable.
FileContainer::FileContainer(std::string file_name_in) : file_name(file_name_in){
std::ifstream input(FileContainer::file_name);
std::string line_buffer_temp;
int line_counter_temp = 1;
// Iterate through the whole file.
while( std::getline( input, line_buffer_temp ) ) {
// if a line is too short, remove it and mark it as a comment (where line length < MINIMUM_LINE_LENGTH)
line_buffer_temp = removeShortLines(line_buffer_temp, line_counter_temp);
// If a line is blank, remove it and mark it as a comment.
line_buffer_temp = removeNewlines(line_buffer_temp);
// Build a member variable of the complete file text.
FileContainer::file_text.push_back(line_buffer_temp);
// update line counter.
line_counter_temp++;
}
if(Globals::dump_data_structures){
// enabled through a commmand line flag, dump the file to the command line if required.
dumpFileText();
}
}
// std::vector<Segment> FileContainer::dissectSegments(){
// @return std::vector<Segment> - The built list of Segment objects contained within the file represented by the FileContainer object.
// This function breaks down the program text contained in the member variable file_text into a list of Segment objects.
// This function does not change class state
std::vector<Segment> FileContainer::dissectSegments(){
std::vector<Segment> segment_arr;
// Start outside a segment, the first line of the file willl input
bool in_function_or_subroutine_block = false;
// Start inside the main program block, remain there until we see a FUNCTION or SUBROUTINE statement.
bool in_main_block = true;
// Indicating the current type of segment we are inside, FUNCTION, SUBROUTINE or MAIN PROGRAM.
SEGMENT_TYPE current_type = {};
int start_line = 0;
/**
* This loop iterates through each line in the file text
* The loop tracks which a) type of segment it is currently in b) if it is currently in a segment c) where the current segment started
* At the end of each segment (i.e. when a return or END statement is seen) the loop backtracks, builds a string vector of
* all the lines in that segment (since the starting line), and then builds a segment object with this list
* Once a segment object is built, it is added to segment_arr, the return value for the whole function.
* This algorithm hence breaks down the file into a list of segments, and warns the user when they try to do things
* they shouldn't either outside of a segment or in the wrong segment type
* */
for(std::vector<std::string>::size_type i = 0; i != FileContainer::file_text.size(); i++) {
// Skip comments
if(!::lineIsComment(FileContainer::file_text[i])){
// Set the program text to a local variable. Ignore the line label i.e. chars 0 -> 6
std::string useful_statement = FileContainer::file_text[i].substr(LINE_LABEL_LENGTH, FileContainer::file_text[i].length());
// If the line is an END statement. Note that there might be possible problems here with ENDVARIABLE, for example.
if(useful_statement.substr(0,END_STATEMENT_LENGTH) == "END" && useful_statement.length() == END_STATEMENT_LENGTH){
// END should signify the END of the program as a whole. If we're inside a segment, the prgorammer needs to RETURN first.
// This only applies to FUNCTION and SUBROUTINE blocks, as the MAIN program can exit without a return.
if(in_function_or_subroutine_block){
Logging::logErrorMessage( "END statement found inside a segment block. Are you missing a return? [" + std::to_string(i) + "].");
} else if(in_main_block){
// Leave the main block
in_main_block = false;
// Begin building a list of thee lines inside that segment.
std::vector<std::string> segment_text;
// For each line in the segment
for(int x = start_line; x < ( i+1 ); x++){
segment_text.push_back(FileContainer::file_text.at(x));
}
Logging::logMessage("+" + ::getEnumString(SEGMENT_TYPE::PROGRAM) + " [" + std::to_string(start_line + 1) + "," + std::to_string(i + 1) + "]");
// Build a segment with our list of strings, add it to the overarching data structure.
segment_arr.push_back(Segment(SEGMENT_TYPE::PROGRAM, start_line, i, segment_text));
} else {
Logging::logWarnMessage("END detected outside of Main Program Block[" + std::to_string(i) + "]"); // THis should only catch if the program starts with END.
}
} else if(useful_statement.substr(0, 6) == "RETURN") {
// If we're not in a function or subroutine block, we can't call return. Throw the user an error if they try this.
if(in_function_or_subroutine_block){
// Build an array of the program lines in this segment
std::vector<std::string> segment_text;
// iterate through the segment
for(int x = start_line; x < ( i+1 ); x++){
segment_text.push_back(FileContainer::file_text.at(x));
}
Logging::logMessage("+" + ::getEnumString(current_type) + " [" + std::to_string(start_line + 1) + "," + std::to_string(i + 1) + "]{" + ::stripWhitespaceString(segment_text.at(0)) + "}.");
// Construct a segment object, add it back to our return array. This segment is now finished with.
segment_arr.push_back(Segment(current_type, start_line, i, segment_text));
// We are no longer in a function or subroutine block, the user has just exited this by calling return.
in_function_or_subroutine_block = false;
start_line = i+1;
current_type = {};
} else {
// if we're in the main program block - the user should not be calling return.
Logging::logWarnMessage("RETURN detected outside of Subroutine Block [start=" + std::to_string(start_line + 1) + ", end=" + std::to_string(i+1) + "].");
}
} else if(useful_statement.substr(0, 10) == "SUBROUTINE"){
// Nested subrutines / functions aren't allowed - so we should never see this statement inside another function or subroutine.
if(!in_function_or_subroutine_block){
// Set current type
current_type = SEGMENT_TYPE::SUBROUTINE;
// Set start line - once we see a RETURN statement, we'll iterate from this line down and build the segment.
start_line = i;
in_function_or_subroutine_block = true;
} else {
Logging::logWarnMessage("SUBROUTINE Block detected inside another segment block [start=" + std::to_string(start_line+1) + ", end=" + std::to_string(i+1) + "].");
}
} else if(useful_statement.substr(0, 8) == "FUNCTION"){
// Nested subroutines / functions aren't allowed - we should never see this statemenet when inside another function or subroutine
if(!in_function_or_subroutine_block){
// Set current segmetn type
current_type = SEGMENT_TYPE::FUNCTION;
// Set start line - we'll iterate from this to the end of the function once we see it
start_line = i;
in_function_or_subroutine_block = true;
} else {
Logging::logWarnMessage("FUNCTION Block detected inside another segment block [start=" + std::to_string(start_line+1)+ ", end=" + std::to_string(i+1) + "].");
}
// If we're not in the main block, and see a statement that isn't already specified - enter the main block!
} else if(!in_main_block) {
in_main_block = true;
current_type = SEGMENT_TYPE::PROGRAM;
Logging::logInfoMessage("Entered main program at line " + std::to_string(i + 1));
}
}
}
// If we find a segment with no statements in it - warn the user.
// This also catches non-terminated segments - i.e. a Main Program segment without an END.
if(segment_arr.size() == 0){
Logging::logErrorMessage("Warning - failed to load a fail program block from file " + file_name);
Logging::logErrorMessage("Did you forget to include an END Statement?");
}
Logging::logNewLine();
// Returns std::vector<Segment> -> built inside above for loop.
return segment_arr;
}
// void FileContainer::dumpFileText()
//
//
// This function takes and returns no arguments
// the purpose of this function is to dump + format the file text to the command line.
// This is activated upon a user enabled command line flag.
// The file text is loaded and constructed in the constructor.
void FileContainer::dumpFileText(){
Logging::logMessage("Begin File Dump(Name=" + file_name + "):\n"); // Pretty printing
for (std::vector<std::string>::const_iterator i = FileContainer::file_text.begin(); i != FileContainer::file_text.end(); ++i) //
Logging::logMessage(*i + ' '); // For each - print that line with no formmatting.
Logging::logMessage("\nEnd File Dump\n");
}
// bool FileContainer::expandContinuations()
//
// @return bool -> indicates success / failure.
// @member file_text
//
// This function modifies class state
// This function iterates through the member variable file_text, removing continuations and appending them into a single line.
// The continuation lines removed as replaced by comments.
// This modification is done *in place* inside FileContainer::file_text.
bool FileContainer::expandContinuations(){
int continuation_count = CONTINUATION_COUNT_STARTING;
// Iterate through file text
for(std::vector<std::string>::size_type i = 0; i != FileContainer::file_text.size(); i++) {
// Ignore comments in the file text - they cannot be continuations.
if(!::lineIsComment(FileContainer::file_text[i])){
// FAIL - if over 20 consecutive continuations have been seen.
if(continuation_count == 20) {
// Exit with an error - return this to the calling class.
Logging::logErrorMessage("Over 20 Continuations detected! Aborting. Line[" + std::to_string(i-19) + "]{'" + FileContainer::file_text[i-continuation_count] + "'}.");
return false;
} else if(
( FileContainer::file_text[i].at(CONTINUATION_INDICATION_BIT) != ' ')
&& (i != 0))
{
// Continuations cannot be line labels. Warn the user and abort if it is.
if( FileContainer::file_text[i].substr(0,4).find_first_not_of(' ') != std::string::npos){
Logging::logErrorMessage("Line {'" + FileContainer::file_text[i] + "'}[" + std::to_string(i+1) + "] is marked as a continuation, but contains a label. Aborting.");
return false; // Exit to the calling class.
} else {
// Make a copy of the line we're modifying - in case we need to print it later.
std::string line_text_backup = FileContainer::file_text[i];
// This MUST be empty - so it can be removed. This includes deleting the continuation character.
FileContainer::file_text[i].erase(0,6);
// Check that the rest of the line is not zero.
if(FileContainer::file_text[i].length() == 0){
Logging::logErrorMessage("Empty continuation - Continuation labelled lines must contained at least one character.");
// Print an error - note use case of previous backup.
::printErrorLocation(7, line_text_backup);
} else {
// Append continuation to prervious non-continuation line, forming one longer line.
FileContainer::file_text[i-continuation_count] += FileContainer::file_text[i];
// Mark the line IN PLACE as a blank comment
FileContainer::file_text[i] = std::string("C");
// Keep track of the number of continuations we've seen.
continuation_count += 1;
}
}
} else {
// If the line is not a continuation - reset the continuation count.
continuation_count = 1;
}
}
}
return true;
}
// std::string FileContainer::removeNewlines(std::string line)
//
// @param an input line - a single line input which will have it's newline characters removed.
// @return The modified input line, with all CR LF characters removed
//
//This function acts as a utility class - it has no impact on class state nor does it use any member variables.
//
std::string FileContainer::removeNewlines(std::string line){
std::string::size_type pos = 0; // iterate from position zero
while ( ( pos = line.find ("\r",pos) ) != std::string::npos ) // Find all \r characters, remove them.
{
line.erase ( pos, 2 );
}
pos = 0; // Repeat this process for \r\n
while ( ( pos = line.find ("\r\n",pos) ) != std::string::npos ) //
{
line.erase ( pos, 2 );
}
return line; // Return the modified line.
}
// std::string FileContainer::removeShortLines(std::string line, int line_counter)
//
// @param std::string line - the input line to check
// @param int line_counter - The line number - used for error messages.
//
// This function takes an input line, check's it's length and informs the user if it's too short
// If the line is of a proper length, it's returned to the calling class intact.
// If the line is too shorrt, it's marked as a COMMENT and returned to the calling class alongside an error message to the user.
std::string FileContainer::removeShortLines(std::string line, int line_counter){
// If line length warnings are enabled, warn the user on lines < 5 chars long.
if((line.length() < MINIMUM_LINE_LENGTH) && !(::lineIsComment(line))) {
Logging::logWarnMessage("Line { " + line + " }[" + std::to_string(line_counter) + "] has an unusually short length. It will be marked as a comment and ignored.");
line.insert(0, COMMENT_STRING);
}
return line;
} | 16,978 | 4,349 |
/** \file
*
* $Date: 2008/04/10 16:36:41 $
* $Revision: 1.2 $
* \author Jim Pivarski - Texas A&M University
*/
#include "Alignment/MuonAlignment/interface/AlignableCSCRing.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
/// The constructor simply copies the vector of CSC Chambers and computes the surface from them
AlignableCSCRing::AlignableCSCRing( const std::vector<AlignableCSCChamber*>& cscChambers )
: AlignableComposite(cscChambers[0]->id(), align::AlignableCSCRing)
{
theCSCChambers.insert( theCSCChambers.end(), cscChambers.begin(), cscChambers.end() );
// maintain also list of components
for (const auto& chamber: cscChambers) {
const auto mother = chamber->mother();
this->addComponent(chamber); // components will be deleted by dtor of AlignableComposite
chamber->setMother(mother); // restore previous behaviour where mother is not set
}
setSurface( computeSurface() );
compConstraintType_ = Alignable::CompConstraintType::POSITION_Z;
}
/// Return Alignable CSC Chamber at given index
AlignableCSCChamber &AlignableCSCRing::chamber(int i)
{
if (i >= size() )
throw cms::Exception("LogicError") << "CSC Chamber index (" << i << ") out of range";
return *theCSCChambers[i];
}
/// Returns surface corresponding to current position
/// and orientation, as given by average on all components
AlignableSurface AlignableCSCRing::computeSurface()
{
return AlignableSurface( computePosition(), computeOrientation() );
}
/// Compute average z position from all components (x and y forced to 0)
AlignableCSCRing::PositionType AlignableCSCRing::computePosition()
{
float zz = 0.;
for ( std::vector<AlignableCSCChamber*>::iterator ichamber = theCSCChambers.begin();
ichamber != theCSCChambers.end(); ichamber++ )
zz += (*ichamber)->globalPosition().z();
zz /= static_cast<float>(theCSCChambers.size());
return PositionType( 0.0, 0.0, zz );
}
/// Just initialize to default given by default constructor of a RotationType
AlignableCSCRing::RotationType AlignableCSCRing::computeOrientation()
{
return RotationType();
}
// /// Twists all components by given angle
// void AlignableCSCRing::twist(float rad)
// {
// for ( std::vector<AlignableCSCChamber*>::iterator iter = theCSCChambers.begin();
// iter != theCSCChambers.end(); iter++ )
// (*iter)->twist(rad);
// }
/// Output Ring information
std::ostream &operator << (std::ostream& os, const AlignableCSCRing& b )
{
os << "This CSC Ring contains " << b.theCSCChambers.size() << " CSC chambers" << std::endl;
os << "(phi, r, z) = (" << b.globalPosition().phi() << ","
<< b.globalPosition().perp() << "," << b.globalPosition().z();
os << "), orientation:" << std::endl<< b.globalRotation() << std::endl;
return os;
}
/// Recursive printout of whole CSC Ring structure
void AlignableCSCRing::dump( void ) const
{
edm::LogInfo("AlignableDump") << (*this);
for ( std::vector<AlignableCSCChamber*>::const_iterator iChamber = theCSCChambers.begin();
iChamber != theCSCChambers.end(); iChamber++ )
edm::LogInfo("AlignableDump") << (**iChamber);
}
| 3,159 | 1,122 |
/* Implement a Queue (FIFO) using 2 Stacks (LIFO)
Method 1 (By making enQueue operation costly): This method makes sure that oldest entered element is
always at the top of stack 1, so that deQueue operation just pops from stack1.
To put the element at top of stack1, stack2 is used.
enQueue(q, x)
1) While stack1 is not empty, push everything from satck1 to stack2.
2) Push x to stack1 (assuming size of stacks is unlimited).
3) Push everything back to stack1.
dnQueue(q)
1) If stack1 is empty then error
2) Pop an item from stack1 and return it
Method 2 (By making deQueue operation costly): In this method, in en-queue operation,
the new element is entered at the top of stack1. In de-queue operation, if stack2 is empty
then all the elements are moved to stack2 and finally top of stack2 is returned.
enQueue(q, x)
1) Push x to stack1 (assuming size of stacks is unlimited).
deQueue(q)
1) If both stacks are empty then error.
2) If stack2 is empty
While stack1 is not empty, push everything from stack1 to stack2.
3) Pop the element from stack2 and return it.
Method 2 is definitely better than method 1.
Method 1 moves all the elements twice in enQueue operation, while method 2 (in deQueue operation)
moves the elements once and moves elements only if stack2 empty.
Space Complexity = O(n) where n is the number of elements in the stack
Time Complexuity = O(n) where n is the number of elements in the stack
*/
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
class Stack {
Node* head;
public:
Stack() {
head = NULL;
}
Node* getNewNode(int data) {
Node* newNode = new Node();
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void push(int data) {
if(head == NULL) {
head = getNewNode(data);
}
else {
Node* newNode = getNewNode(data);
newNode->next = head;
head = newNode;
}
}
int pop() {
if(head == NULL) {
return -1;
}
else {
int data = head->data;
if(head->next == NULL) {
free(head);
head = NULL;
}
else {
Node* tmp;
tmp = head;
head = head->next;
free(tmp);
}
return data;
}
}
bool isEmpty() {
if(head == NULL) {
return true;
}
else {
return false;
}
}
int getElementAtTop() {
if(head == NULL) {
return -1;
}
else {
return head->data;
}
}
};
class Queue {
Stack s1;
Stack s2;
public:
Queue() {
s1 = Stack();
s2 = Stack();
}
void enqueue(int data) {
s1.push(data);
}
int dequeue() {
if(s2.isEmpty()) {
while(!(s1.isEmpty())) {
s2.push(s1.pop());
}
}
return s2.pop();
}
bool isEmpty() {
return s1.isEmpty() && s2.isEmpty();
}
};
int main() {
Queue q = Queue();
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
q.enqueue(4);
cout<<q.dequeue();
cout<<q.dequeue();
cout<<q.dequeue();
cout<<q.dequeue();
} | 2,889 | 1,152 |
#include "il2cpp-config.h"
#if !RUNTIME_TINY
#include "NativeDelegateMethodCache.h"
#include "os/Mutex.h"
namespace il2cpp
{
namespace utils
{
baselib::ReentrantLock NativeDelegateMethodCache::m_CacheMutex;
NativeDelegateMap NativeDelegateMethodCache::m_NativeDelegateMethods;
const VmMethod* NativeDelegateMethodCache::GetNativeDelegate(Il2CppMethodPointer nativeFunctionPointer)
{
os::FastAutoLock lock(&m_CacheMutex);
NativeDelegateMap::iterator i = m_NativeDelegateMethods.find(nativeFunctionPointer);
if (i == m_NativeDelegateMethods.end())
return NULL;
return i->second;
}
void NativeDelegateMethodCache::AddNativeDelegate(Il2CppMethodPointer nativeFunctionPointer, const VmMethod* managedMethodInfo)
{
os::FastAutoLock lock(&m_CacheMutex);
m_NativeDelegateMethods.insert(std::make_pair(nativeFunctionPointer, managedMethodInfo));
}
} // namespace utils
} // namespace il2cpp
#endif
| 989 | 296 |
// Copyright 2020 kkozlov
#include <string>
#include <iostream>
#include "Form.h"
Form::Form(std::string const &name,
unsigned minGradeToSign,
unsigned minGradeToExecute,
std::string const &target) throw()
: name_(name) , minGradeToSign_(minGradeToSign),
minGradeToExecute_(minGradeToExecute), target_(target) {
if (minGradeToSign > Bureaucrat::MinGrade() ||
minGradeToExecute > Bureaucrat::MinGrade() )
throw GradeTooLowException();
if (minGradeToSign < Bureaucrat::MaxGrade() ||
minGradeToExecute < Bureaucrat::MaxGrade())
throw GradeTooHighException();
}
Form::Form(Form const &other)
: name_(other.Name()), minGradeToSign_(other.MinGradeToSign()),
minGradeToExecute_(other.MinGradeToExecute()) {}
Form::~Form(void) {}
Form &Form::operator=(Form const &rhs) {
if (&rhs != this) {
isSigned_ = rhs.IsSigned();
}
return *this;
}
std::string const &Form::Name(void) const {
return name_;
}
unsigned Form::MinGradeToSign(void) const {
return minGradeToSign_;
}
unsigned Form::MinGradeToExecute(void) const {
return minGradeToExecute_;
}
bool Form::IsSigned(void) const {
return isSigned_;
}
std::string const &Form::Target(void) const {
return target_;
}
void Form::BeSigned(Bureaucrat const &bureaucrat) throw() {
if (bureaucrat.Grade() > minGradeToSign_)
throw GradeTooLowException();
isSigned_ = true;
}
void Form::Execute(Bureaucrat const &bureaucrat) throw() {
if (bureaucrat.Grade() > minGradeToExecute_)
throw GradeTooLowException();
if (!isSigned_) {
std::cout << name_ << " is not signed." << std::endl;
} else {
this->Action();
}
}
char const *Form::GradeTooLowException::what(void) const throw() {
return "The grade too low exception\n";
}
char const *Form::GradeTooHighException::what(void) const throw() {
return "The maximum grade is 150\n";
}
std::ostream &operator<<(std::ostream &os, Form const &in) {
os << in.Name() << "\nMinimum grade to sign it: " << in.MinGradeToSign()
<< "\nMinimum grade to execute it: " << in.MinGradeToExecute()
<< "\nIs signed: " << (in.IsSigned() ? "yes" : "no") << std::endl;
return os;
}
| 2,192 | 782 |
/*=============================================================================
Library: CTK
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
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 "ctkQtResourcesTreeModel.h"
class ctkQtResourceTreeNode;
class ctkQtResourceTreeItem
{
public:
ctkQtResourceTreeItem(const QFileInfo& fileInfo, ctkQtResourceTreeNode* parent = 0);
virtual ~ctkQtResourceTreeItem();
virtual ctkQtResourceTreeItem* child(int row);
virtual int childCount() const;
int row();
QVariant data(int role) const;
ctkQtResourceTreeNode* parent() const;
protected:
QFileInfo entry;
ctkQtResourceTreeNode* parentNode;
};
class ctkQtResourceTreeNode : public ctkQtResourceTreeItem
{
public:
ctkQtResourceTreeNode(const QFileInfo& dirInfo, ctkQtResourceTreeNode* parent = 0);
~ctkQtResourceTreeNode();
ctkQtResourceTreeItem* child(int row);
int childCount() const;
int indexOf(ctkQtResourceTreeItem* child) const;
private:
QList<ctkQtResourceTreeItem*> children;
};
ctkQtResourceTreeItem::ctkQtResourceTreeItem(const QFileInfo& fileInfo, ctkQtResourceTreeNode* parent)
: entry(fileInfo), parentNode(parent)
{
}
ctkQtResourceTreeItem::~ctkQtResourceTreeItem()
{
}
ctkQtResourceTreeItem* ctkQtResourceTreeItem::child(int row)
{
Q_UNUSED(row)
return 0;
}
int ctkQtResourceTreeItem::childCount() const
{
return 0;
}
int ctkQtResourceTreeItem::row()
{
if (parentNode)
{
return parentNode->indexOf(this);
}
return 0;
}
QVariant ctkQtResourceTreeItem::data(int role) const
{
if (role == Qt::DisplayRole)
{
if (entry.isFile())
return entry.fileName();
QString lastDir = entry.absoluteFilePath();
int i = lastDir.lastIndexOf('/');
if (i == lastDir.size()-1) return lastDir;
return lastDir.mid(i+1);
}
return QVariant();
}
ctkQtResourceTreeNode* ctkQtResourceTreeItem::parent() const
{
return parentNode;
}
ctkQtResourceTreeNode::ctkQtResourceTreeNode(const QFileInfo& dirInfo, ctkQtResourceTreeNode* parent)
: ctkQtResourceTreeItem(dirInfo, parent)
{
QFileInfoList infoList = QDir(dirInfo.absoluteFilePath()).entryInfoList();
QListIterator<QFileInfo> it(infoList);
while (it.hasNext())
{
const QFileInfo& info = it.next();
if (info.isFile())
{
children.push_back(new ctkQtResourceTreeItem(info, this));
}
else
{
children.push_back(new ctkQtResourceTreeNode(info, this));
}
}
}
ctkQtResourceTreeNode::~ctkQtResourceTreeNode()
{
qDeleteAll(children);
}
ctkQtResourceTreeItem* ctkQtResourceTreeNode::child(int row)
{
return children.value(row);
}
int ctkQtResourceTreeNode::childCount() const
{
return children.size();
}
int ctkQtResourceTreeNode::indexOf(ctkQtResourceTreeItem* child) const
{
return children.indexOf(child);
}
ctkQtResourcesTreeModel::ctkQtResourcesTreeModel(QObject* parent)
: QAbstractItemModel(parent)
{
rootItem = new ctkQtResourceTreeNode(QFileInfo(":/"));
}
ctkQtResourcesTreeModel::~ctkQtResourcesTreeModel()
{
delete rootItem;
}
QVariant ctkQtResourcesTreeModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (role == Qt::DisplayRole)
{
ctkQtResourceTreeItem* item = static_cast<ctkQtResourceTreeItem*>(index.internalPointer());
return item->data(role);
}
return QVariant();
}
Qt::ItemFlags ctkQtResourcesTreeModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return 0;
return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}
QVariant ctkQtResourcesTreeModel::headerData(int section, Qt::Orientation orientation,
int role) const
{
Q_UNUSED(section)
Q_UNUSED(orientation)
Q_UNUSED(role)
return QVariant();
}
QModelIndex ctkQtResourcesTreeModel::index(int row, int column,
const QModelIndex &parent) const
{
if (!hasIndex(row, column, parent))
return QModelIndex();
if (!parent.isValid())
return createIndex(row, column, rootItem);
ctkQtResourceTreeItem* parentItem = static_cast<ctkQtResourceTreeItem*>(parent.internalPointer());
ctkQtResourceTreeItem* childItem = parentItem->child(row);
if (childItem)
return createIndex(row, column, childItem);
else
return QModelIndex();
}
QModelIndex ctkQtResourcesTreeModel::parent(const QModelIndex &index) const
{
if (!index.isValid())
return QModelIndex();
ctkQtResourceTreeItem* childItem = static_cast<ctkQtResourceTreeItem*>(index.internalPointer());
ctkQtResourceTreeItem* parentItem = childItem->parent();
if (parentItem)
return createIndex(parentItem->row(), 0, parentItem);
return QModelIndex();
}
int ctkQtResourcesTreeModel::rowCount(const QModelIndex &parent) const
{
if (parent.column() > 0) return 0;
if (!parent.isValid())
{
return 1;
}
else
{
ctkQtResourceTreeItem* parentItem = static_cast<ctkQtResourceTreeItem*>(parent.internalPointer());
return parentItem->childCount();
}
}
int ctkQtResourcesTreeModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent)
return 1;
}
| 5,722 | 1,890 |
#include "Application.h"
#include <engine/core/util/PathUtil.h>
#include <engine/core/main/Engine.h>
#include <engine/core/render/base/Renderer.h>
extern float iOSGetScreenWidth();
extern float iOSGetScreenHeight();
namespace Echo
{
Application::Application()
{
}
Application::~Application()
{
}
Application* Application::instance()
{
static Application* inst = EchoNew(Application);
return inst;
}
void Application::init(int width, int height, const String& rootPath, const String& userPath)
{
m_log = EchoNew(GameLog("Game"));
Echo::Log::instance()->addOutput(m_log);
Echo::initRender(0);
Engine::Config rootcfg;
rootcfg.m_projectFile = rootPath + "/data/app.echo";
rootcfg.m_userPath = userPath;
rootcfg.m_isGame = true;
Engine::instance()->initialize(rootcfg);
}
// tick ms
void Application::tick(float elapsedTime)
{
checkScreenSize();
Engine::instance()->tick(elapsedTime);
}
// check screen size
void Application::checkScreenSize()
{
static float width = 0;
static float height = 0;
if(width!=iOSGetScreenWidth() || height!=iOSGetScreenHeight())
{
width = iOSGetScreenWidth();
height = iOSGetScreenHeight();
Engine::instance()->onSize( width, height);
}
}
}
| 1,404 | 423 |
// Copyright (c) the JPEG XL Project Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#include "jxl/encode.h"
#include "gtest/gtest.h"
#include "jxl/encode_cxx.h"
#include "lib/extras/codec.h"
#include "lib/jxl/dec_file.h"
#include "lib/jxl/enc_butteraugli_comparator.h"
#include "lib/jxl/encode_internal.h"
#include "lib/jxl/jpeg/dec_jpeg_data.h"
#include "lib/jxl/jpeg/dec_jpeg_data_writer.h"
#include "lib/jxl/test_utils.h"
#include "lib/jxl/testdata.h"
TEST(EncodeTest, AddFrameAfterCloseInputTest) {
JxlEncoderPtr enc = JxlEncoderMake(nullptr);
EXPECT_NE(nullptr, enc.get());
JxlEncoderCloseInput(enc.get());
size_t xsize = 64;
size_t ysize = 64;
JxlPixelFormat pixel_format = {4, JXL_TYPE_UINT16, JXL_BIG_ENDIAN, 0};
std::vector<uint8_t> pixels = jxl::test::GetSomeTestImage(xsize, ysize, 4, 0);
jxl::CodecInOut input_io =
jxl::test::SomeTestImageToCodecInOut(pixels, 4, xsize, ysize);
JxlBasicInfo basic_info;
jxl::test::JxlBasicInfoSetFromPixelFormat(&basic_info, &pixel_format);
basic_info.xsize = xsize;
basic_info.ysize = ysize;
basic_info.uses_original_profile = false;
EXPECT_EQ(JXL_ENC_SUCCESS, JxlEncoderSetBasicInfo(enc.get(), &basic_info));
JxlColorEncoding color_encoding;
JxlColorEncodingSetToSRGB(&color_encoding,
/*is_gray=*/pixel_format.num_channels < 3);
EXPECT_EQ(JXL_ENC_SUCCESS,
JxlEncoderSetColorEncoding(enc.get(), &color_encoding));
JxlEncoderOptions* options = JxlEncoderOptionsCreate(enc.get(), NULL);
EXPECT_EQ(JXL_ENC_ERROR,
JxlEncoderAddImageFrame(options, &pixel_format, pixels.data(),
pixels.size()));
}
TEST(EncodeTest, AddJPEGAfterCloseTest) {
JxlEncoderPtr enc = JxlEncoderMake(nullptr);
EXPECT_NE(nullptr, enc.get());
JxlEncoderCloseInput(enc.get());
const std::string jpeg_path =
"imagecompression.info/flower_foveon.png.im_q85_420.jpg";
const jxl::PaddedBytes orig = jxl::ReadTestData(jpeg_path);
JxlEncoderOptions* options = JxlEncoderOptionsCreate(enc.get(), NULL);
EXPECT_EQ(JXL_ENC_ERROR,
JxlEncoderAddJPEGFrame(options, orig.data(), orig.size()));
}
TEST(EncodeTest, AddFrameBeforeColorEncodingTest) {
JxlEncoderPtr enc = JxlEncoderMake(nullptr);
EXPECT_NE(nullptr, enc.get());
size_t xsize = 64;
size_t ysize = 64;
JxlPixelFormat pixel_format = {4, JXL_TYPE_UINT16, JXL_BIG_ENDIAN, 0};
std::vector<uint8_t> pixels = jxl::test::GetSomeTestImage(xsize, ysize, 4, 0);
jxl::CodecInOut input_io =
jxl::test::SomeTestImageToCodecInOut(pixels, 4, xsize, ysize);
JxlBasicInfo basic_info;
jxl::test::JxlBasicInfoSetFromPixelFormat(&basic_info, &pixel_format);
basic_info.xsize = xsize;
basic_info.ysize = ysize;
basic_info.uses_original_profile = false;
EXPECT_EQ(JXL_ENC_SUCCESS, JxlEncoderSetBasicInfo(enc.get(), &basic_info));
JxlEncoderOptions* options = JxlEncoderOptionsCreate(enc.get(), NULL);
EXPECT_EQ(JXL_ENC_ERROR,
JxlEncoderAddImageFrame(options, &pixel_format, pixels.data(),
pixels.size()));
}
TEST(EncodeTest, AddFrameBeforeBasicInfoTest) {
JxlEncoderPtr enc = JxlEncoderMake(nullptr);
EXPECT_NE(nullptr, enc.get());
size_t xsize = 64;
size_t ysize = 64;
JxlPixelFormat pixel_format = {4, JXL_TYPE_UINT16, JXL_BIG_ENDIAN, 0};
std::vector<uint8_t> pixels = jxl::test::GetSomeTestImage(xsize, ysize, 4, 0);
jxl::CodecInOut input_io =
jxl::test::SomeTestImageToCodecInOut(pixels, 4, xsize, ysize);
JxlColorEncoding color_encoding;
JxlColorEncodingSetToSRGB(&color_encoding,
/*is_gray=*/pixel_format.num_channels < 3);
EXPECT_EQ(JXL_ENC_SUCCESS,
JxlEncoderSetColorEncoding(enc.get(), &color_encoding));
JxlEncoderOptions* options = JxlEncoderOptionsCreate(enc.get(), NULL);
EXPECT_EQ(JXL_ENC_ERROR,
JxlEncoderAddImageFrame(options, &pixel_format, pixels.data(),
pixels.size()));
}
TEST(EncodeTest, DefaultAllocTest) {
JxlEncoder* enc = JxlEncoderCreate(nullptr);
EXPECT_NE(nullptr, enc);
JxlEncoderDestroy(enc);
}
TEST(EncodeTest, CustomAllocTest) {
struct CalledCounters {
int allocs = 0;
int frees = 0;
} counters;
JxlMemoryManager mm;
mm.opaque = &counters;
mm.alloc = [](void* opaque, size_t size) {
reinterpret_cast<CalledCounters*>(opaque)->allocs++;
return malloc(size);
};
mm.free = [](void* opaque, void* address) {
reinterpret_cast<CalledCounters*>(opaque)->frees++;
free(address);
};
{
JxlEncoderPtr enc = JxlEncoderMake(&mm);
EXPECT_NE(nullptr, enc.get());
EXPECT_LE(1, counters.allocs);
EXPECT_EQ(0, counters.frees);
}
EXPECT_LE(1, counters.frees);
}
TEST(EncodeTest, DefaultParallelRunnerTest) {
JxlEncoderPtr enc = JxlEncoderMake(nullptr);
EXPECT_NE(nullptr, enc.get());
EXPECT_EQ(JXL_ENC_SUCCESS,
JxlEncoderSetParallelRunner(enc.get(), nullptr, nullptr));
}
void VerifyFrameEncoding(size_t xsize, size_t ysize, JxlEncoder* enc,
const JxlEncoderOptions* options) {
JxlPixelFormat pixel_format = {4, JXL_TYPE_UINT16, JXL_BIG_ENDIAN, 0};
std::vector<uint8_t> pixels = jxl::test::GetSomeTestImage(xsize, ysize, 4, 0);
jxl::CodecInOut input_io =
jxl::test::SomeTestImageToCodecInOut(pixels, 4, xsize, ysize);
JxlBasicInfo basic_info;
jxl::test::JxlBasicInfoSetFromPixelFormat(&basic_info, &pixel_format);
basic_info.xsize = xsize;
basic_info.ysize = ysize;
if (options->values.lossless) {
basic_info.uses_original_profile = true;
} else {
basic_info.uses_original_profile = false;
}
EXPECT_EQ(JXL_ENC_SUCCESS, JxlEncoderSetBasicInfo(enc, &basic_info));
JxlColorEncoding color_encoding;
JxlColorEncodingSetToSRGB(&color_encoding,
/*is_gray=*/pixel_format.num_channels < 3);
EXPECT_EQ(JXL_ENC_SUCCESS, JxlEncoderSetColorEncoding(enc, &color_encoding));
EXPECT_EQ(JXL_ENC_SUCCESS,
JxlEncoderAddImageFrame(options, &pixel_format, pixels.data(),
pixels.size()));
JxlEncoderCloseInput(enc);
std::vector<uint8_t> compressed = std::vector<uint8_t>(64);
uint8_t* next_out = compressed.data();
size_t avail_out = compressed.size() - (next_out - compressed.data());
JxlEncoderStatus process_result = JXL_ENC_NEED_MORE_OUTPUT;
while (process_result == JXL_ENC_NEED_MORE_OUTPUT) {
process_result = JxlEncoderProcessOutput(enc, &next_out, &avail_out);
if (process_result == JXL_ENC_NEED_MORE_OUTPUT) {
size_t offset = next_out - compressed.data();
compressed.resize(compressed.size() * 2);
next_out = compressed.data() + offset;
avail_out = compressed.size() - offset;
}
}
compressed.resize(next_out - compressed.data());
EXPECT_EQ(JXL_ENC_SUCCESS, process_result);
jxl::DecompressParams dparams;
jxl::CodecInOut decoded_io;
EXPECT_TRUE(jxl::DecodeFile(
dparams, jxl::Span<const uint8_t>(compressed.data(), compressed.size()),
&decoded_io, /*pool=*/nullptr));
jxl::ButteraugliParams ba;
EXPECT_LE(ButteraugliDistance(input_io, decoded_io, ba,
/*distmap=*/nullptr, nullptr),
3.0f);
}
void VerifyFrameEncoding(JxlEncoder* enc, const JxlEncoderOptions* options) {
VerifyFrameEncoding(63, 129, enc, options);
}
TEST(EncodeTest, FrameEncodingTest) {
JxlEncoderPtr enc = JxlEncoderMake(nullptr);
EXPECT_NE(nullptr, enc.get());
VerifyFrameEncoding(enc.get(), JxlEncoderOptionsCreate(enc.get(), nullptr));
}
TEST(EncodeTest, EncoderResetTest) {
JxlEncoderPtr enc = JxlEncoderMake(nullptr);
EXPECT_NE(nullptr, enc.get());
VerifyFrameEncoding(50, 200, enc.get(),
JxlEncoderOptionsCreate(enc.get(), nullptr));
// Encoder should become reusable for a new image from scratch after using
// reset.
JxlEncoderReset(enc.get());
VerifyFrameEncoding(157, 77, enc.get(),
JxlEncoderOptionsCreate(enc.get(), nullptr));
}
TEST(EncodeTest, OptionsTest) {
{
JxlEncoderPtr enc = JxlEncoderMake(nullptr);
EXPECT_NE(nullptr, enc.get());
JxlEncoderOptions* options = JxlEncoderOptionsCreate(enc.get(), NULL);
EXPECT_EQ(JXL_ENC_SUCCESS,
JxlEncoderOptionsSetInteger(options, JXL_ENC_OPTION_EFFORT, 5));
VerifyFrameEncoding(enc.get(), options);
EXPECT_EQ(jxl::SpeedTier::kHare, enc->last_used_cparams.speed_tier);
}
{
JxlEncoderPtr enc = JxlEncoderMake(nullptr);
EXPECT_NE(nullptr, enc.get());
JxlEncoderOptions* options = JxlEncoderOptionsCreate(enc.get(), NULL);
// Lower than currently supported values
EXPECT_EQ(JXL_ENC_ERROR,
JxlEncoderOptionsSetInteger(options, JXL_ENC_OPTION_EFFORT, 0));
// Higher than currently supported values
EXPECT_EQ(JXL_ENC_ERROR,
JxlEncoderOptionsSetInteger(options, JXL_ENC_OPTION_EFFORT, 10));
}
{
JxlEncoderPtr enc = JxlEncoderMake(nullptr);
EXPECT_NE(nullptr, enc.get());
JxlEncoderOptions* options = JxlEncoderOptionsCreate(enc.get(), NULL);
EXPECT_EQ(JXL_ENC_SUCCESS, JxlEncoderOptionsSetLossless(options, JXL_TRUE));
VerifyFrameEncoding(enc.get(), options);
EXPECT_EQ(true, enc->last_used_cparams.IsLossless());
}
{
JxlEncoderPtr enc = JxlEncoderMake(nullptr);
EXPECT_NE(nullptr, enc.get());
JxlEncoderOptions* options = JxlEncoderOptionsCreate(enc.get(), NULL);
EXPECT_EQ(JXL_ENC_SUCCESS, JxlEncoderOptionsSetDistance(options, 0.5));
VerifyFrameEncoding(enc.get(), options);
EXPECT_EQ(0.5, enc->last_used_cparams.butteraugli_distance);
}
{
JxlEncoderPtr enc = JxlEncoderMake(nullptr);
JxlEncoderOptions* options = JxlEncoderOptionsCreate(enc.get(), NULL);
// Disallowed negative distance
EXPECT_EQ(JXL_ENC_ERROR, JxlEncoderOptionsSetDistance(options, -1));
}
{
JxlEncoderPtr enc = JxlEncoderMake(nullptr);
EXPECT_NE(nullptr, enc.get());
JxlEncoderOptions* options = JxlEncoderOptionsCreate(enc.get(), NULL);
EXPECT_EQ(JXL_ENC_SUCCESS, JxlEncoderOptionsSetInteger(
options, JXL_ENC_OPTION_DECODING_SPEED, 2));
VerifyFrameEncoding(enc.get(), options);
EXPECT_EQ(2u, enc->last_used_cparams.decoding_speed_tier);
}
}
namespace {
// Returns a copy of buf from offset to offset+size, or a new zeroed vector if
// the result would have been out of bounds taking integer overflow into
// account.
const std::vector<uint8_t> SliceSpan(const jxl::Span<const uint8_t>& buf,
size_t offset, size_t size) {
if (offset + size >= buf.size()) {
return std::vector<uint8_t>(size, 0);
}
if (offset + size < offset) {
return std::vector<uint8_t>(size, 0);
}
return std::vector<uint8_t>(buf.data() + offset, buf.data() + offset + size);
}
struct Box {
// The type of the box.
// If "uuid", use extended_type instead
char type[4] = {0, 0, 0, 0};
// The extended_type is only used when type == "uuid".
// Extended types are not used in JXL. However, the box format itself
// supports this so they are handled correctly.
char extended_type[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
// Box data.
jxl::Span<const uint8_t> data = jxl::Span<const uint8_t>(nullptr, 0);
// If the size is not given, the datasize extends to the end of the file.
// If this field is false, the size field is not encoded when the box is
// serialized.
bool data_size_given = true;
// If successful, returns true and sets `in` to be the rest data (if any).
// If `in` contains a box with a size larger than `in.size()`, will not
// modify `in`, and will return true but the data `Span<uint8_t>` will
// remain set to nullptr.
// If unsuccessful, returns error and doesn't modify `in`.
jxl::Status Decode(jxl::Span<const uint8_t>* in) {
// Total box_size including this header itself.
uint64_t box_size = LoadBE32(SliceSpan(*in, 0, 4).data());
size_t pos = 4;
memcpy(type, SliceSpan(*in, pos, 4).data(), 4);
pos += 4;
if (box_size == 1) {
// If the size is 1, it indicates extended size read from 64-bit integer.
box_size = LoadBE64(SliceSpan(*in, pos, 8).data());
pos += 8;
}
if (!memcmp("uuid", type, 4)) {
memcpy(extended_type, SliceSpan(*in, pos, 16).data(), 16);
pos += 16;
}
// This is the end of the box header, the box data begins here. Handle
// the data size now.
const size_t header_size = pos;
if (box_size != 0) {
if (box_size < header_size) {
return JXL_FAILURE("Invalid box size");
}
if (box_size > in->size()) {
// The box is fine, but the input is too short.
return true;
}
data_size_given = true;
data = jxl::Span<const uint8_t>(in->data() + header_size,
box_size - header_size);
} else {
data_size_given = false;
data = jxl::Span<const uint8_t>(in->data() + header_size,
in->size() - header_size);
}
*in = jxl::Span<const uint8_t>(in->data() + header_size + data.size(),
in->size() - header_size - data.size());
return true;
}
};
struct Container {
std::vector<Box> boxes;
// If successful, returns true and sets `in` to be the rest data (if any).
// If unsuccessful, returns error and doesn't modify `in`.
jxl::Status Decode(jxl::Span<const uint8_t>* in) {
boxes.clear();
Box signature_box;
JXL_RETURN_IF_ERROR(signature_box.Decode(in));
if (memcmp("JXL ", signature_box.type, 4) != 0) {
return JXL_FAILURE("Invalid magic signature");
}
if (signature_box.data.size() != 4)
return JXL_FAILURE("Invalid magic signature");
if (signature_box.data[0] != 0xd || signature_box.data[1] != 0xa ||
signature_box.data[2] != 0x87 || signature_box.data[3] != 0xa) {
return JXL_FAILURE("Invalid magic signature");
}
Box ftyp_box;
JXL_RETURN_IF_ERROR(ftyp_box.Decode(in));
if (memcmp("ftyp", ftyp_box.type, 4) != 0) {
return JXL_FAILURE("Invalid ftyp");
}
if (ftyp_box.data.size() != 12) return JXL_FAILURE("Invalid ftyp");
const char* expected = "jxl \0\0\0\0jxl ";
if (memcmp(expected, ftyp_box.data.data(), 12) != 0)
return JXL_FAILURE("Invalid ftyp");
while (in->size() > 0) {
Box box = {};
JXL_RETURN_IF_ERROR(box.Decode(in));
if (box.data.data() == nullptr) {
// The decoding encountered a box, but not enough data yet.
return true;
}
boxes.emplace_back(box);
}
return true;
}
};
} // namespace
TEST(EncodeTest, SingleFrameBoundedJXLCTest) {
JxlEncoderPtr enc = JxlEncoderMake(nullptr);
EXPECT_NE(nullptr, enc.get());
EXPECT_EQ(JXL_ENC_SUCCESS, JxlEncoderUseContainer(enc.get(),
true));
JxlEncoderOptions* options = JxlEncoderOptionsCreate(enc.get(), NULL);
size_t xsize = 71;
size_t ysize = 23;
JxlPixelFormat pixel_format = {4, JXL_TYPE_UINT16, JXL_BIG_ENDIAN, 0};
std::vector<uint8_t> pixels = jxl::test::GetSomeTestImage(xsize, ysize, 4, 0);
JxlBasicInfo basic_info;
jxl::test::JxlBasicInfoSetFromPixelFormat(&basic_info, &pixel_format);
basic_info.xsize = xsize;
basic_info.ysize = ysize;
basic_info.uses_original_profile = false;
EXPECT_EQ(JXL_ENC_SUCCESS, JxlEncoderSetBasicInfo(enc.get(), &basic_info));
JxlColorEncoding color_encoding;
JxlColorEncodingSetToSRGB(&color_encoding,
/*is_gray=*/false);
EXPECT_EQ(JXL_ENC_SUCCESS, JxlEncoderSetColorEncoding(enc.get(), &color_encoding));
EXPECT_EQ(JXL_ENC_SUCCESS,
JxlEncoderAddImageFrame(options, &pixel_format, pixels.data(),
pixels.size()));
JxlEncoderCloseInput(enc.get());
std::vector<uint8_t> compressed = std::vector<uint8_t>(64);
uint8_t* next_out = compressed.data();
size_t avail_out = compressed.size() - (next_out - compressed.data());
JxlEncoderStatus process_result = JXL_ENC_NEED_MORE_OUTPUT;
while (process_result == JXL_ENC_NEED_MORE_OUTPUT) {
process_result = JxlEncoderProcessOutput(enc.get(), &next_out, &avail_out);
if (process_result == JXL_ENC_NEED_MORE_OUTPUT) {
size_t offset = next_out - compressed.data();
compressed.resize(compressed.size() * 2);
next_out = compressed.data() + offset;
avail_out = compressed.size() - offset;
}
}
compressed.resize(next_out - compressed.data());
EXPECT_EQ(JXL_ENC_SUCCESS, process_result);
Container container = {};
jxl::Span<const uint8_t> encoded_span =
jxl::Span<const uint8_t>(compressed.data(), compressed.size());
EXPECT_TRUE(container.Decode(&encoded_span));
EXPECT_EQ(0u, encoded_span.size());
EXPECT_EQ(0, memcmp("jxlc", container.boxes[0].type, 4));
EXPECT_EQ(true, container.boxes[0].data_size_given);
}
TEST(EncodeTest, CodestreamLevelTest) {
size_t xsize = 64;
size_t ysize = 64;
JxlPixelFormat pixel_format = {4, JXL_TYPE_UINT16, JXL_BIG_ENDIAN, 0};
std::vector<uint8_t> pixels = jxl::test::GetSomeTestImage(xsize, ysize, 4, 0);
jxl::CodecInOut input_io =
jxl::test::SomeTestImageToCodecInOut(pixels, 4, xsize, ysize);
JxlBasicInfo basic_info;
jxl::test::JxlBasicInfoSetFromPixelFormat(&basic_info, &pixel_format);
basic_info.xsize = xsize;
basic_info.ysize = ysize;
basic_info.uses_original_profile = false;
JxlEncoderPtr enc = JxlEncoderMake(nullptr);
EXPECT_EQ(JXL_ENC_SUCCESS, JxlEncoderSetCodestreamLevel(enc.get(), 10));
JxlEncoderOptions* options = JxlEncoderOptionsCreate(enc.get(), NULL);
EXPECT_EQ(JXL_ENC_SUCCESS, JxlEncoderSetBasicInfo(enc.get(), &basic_info));
JxlColorEncoding color_encoding;
JxlColorEncodingSetToSRGB(&color_encoding,
/*is_gray=*/pixel_format.num_channels < 3);
EXPECT_EQ(JXL_ENC_SUCCESS,
JxlEncoderSetColorEncoding(enc.get(), &color_encoding));
EXPECT_EQ(JXL_ENC_SUCCESS,
JxlEncoderAddImageFrame(options, &pixel_format, pixels.data(),
pixels.size()));
JxlEncoderCloseInput(enc.get());
std::vector<uint8_t> compressed = std::vector<uint8_t>(64);
uint8_t* next_out = compressed.data();
size_t avail_out = compressed.size() - (next_out - compressed.data());
JxlEncoderStatus process_result = JXL_ENC_NEED_MORE_OUTPUT;
while (process_result == JXL_ENC_NEED_MORE_OUTPUT) {
process_result = JxlEncoderProcessOutput(enc.get(), &next_out, &avail_out);
if (process_result == JXL_ENC_NEED_MORE_OUTPUT) {
size_t offset = next_out - compressed.data();
compressed.resize(compressed.size() * 2);
next_out = compressed.data() + offset;
avail_out = compressed.size() - offset;
}
}
compressed.resize(next_out - compressed.data());
EXPECT_EQ(JXL_ENC_SUCCESS, process_result);
Container container = {};
jxl::Span<const uint8_t> encoded_span =
jxl::Span<const uint8_t>(compressed.data(), compressed.size());
EXPECT_TRUE(container.Decode(&encoded_span));
EXPECT_EQ(0u, encoded_span.size());
EXPECT_EQ(0, memcmp("jxll", container.boxes[0].type, 4));
}
TEST(EncodeTest, JXL_TRANSCODE_JPEG_TEST(JPEGReconstructionTest)) {
const std::string jpeg_path =
"imagecompression.info/flower_foveon.png.im_q85_420.jpg";
const jxl::PaddedBytes orig = jxl::ReadTestData(jpeg_path);
JxlEncoderPtr enc = JxlEncoderMake(nullptr);
JxlEncoderOptions* options = JxlEncoderOptionsCreate(enc.get(), NULL);
EXPECT_EQ(JXL_ENC_SUCCESS, JxlEncoderStoreJPEGMetadata(enc.get(), JXL_TRUE));
EXPECT_EQ(JXL_ENC_SUCCESS,
JxlEncoderAddJPEGFrame(options, orig.data(), orig.size()));
JxlEncoderCloseInput(enc.get());
std::vector<uint8_t> compressed = std::vector<uint8_t>(64);
uint8_t* next_out = compressed.data();
size_t avail_out = compressed.size() - (next_out - compressed.data());
JxlEncoderStatus process_result = JXL_ENC_NEED_MORE_OUTPUT;
while (process_result == JXL_ENC_NEED_MORE_OUTPUT) {
process_result = JxlEncoderProcessOutput(enc.get(), &next_out, &avail_out);
if (process_result == JXL_ENC_NEED_MORE_OUTPUT) {
size_t offset = next_out - compressed.data();
compressed.resize(compressed.size() * 2);
next_out = compressed.data() + offset;
avail_out = compressed.size() - offset;
}
}
compressed.resize(next_out - compressed.data());
EXPECT_EQ(JXL_ENC_SUCCESS, process_result);
Container container = {};
jxl::Span<const uint8_t> encoded_span =
jxl::Span<const uint8_t>(compressed.data(), compressed.size());
EXPECT_TRUE(container.Decode(&encoded_span));
EXPECT_EQ(0u, encoded_span.size());
EXPECT_EQ(0, memcmp("jbrd", container.boxes[0].type, 4));
EXPECT_EQ(0, memcmp("jxlc", container.boxes[1].type, 4));
jxl::CodecInOut decoded_io;
decoded_io.Main().jpeg_data = jxl::make_unique<jxl::jpeg::JPEGData>();
EXPECT_TRUE(jxl::jpeg::DecodeJPEGData(container.boxes[0].data,
decoded_io.Main().jpeg_data.get()));
jxl::DecompressParams dparams;
dparams.keep_dct = true;
EXPECT_TRUE(
jxl::DecodeFile(dparams, container.boxes[1].data, &decoded_io, nullptr));
std::vector<uint8_t> decoded_jpeg_bytes;
auto write = [&decoded_jpeg_bytes](const uint8_t* buf, size_t len) {
decoded_jpeg_bytes.insert(decoded_jpeg_bytes.end(), buf, buf + len);
return len;
};
EXPECT_TRUE(jxl::jpeg::WriteJpeg(*decoded_io.Main().jpeg_data, write));
EXPECT_EQ(decoded_jpeg_bytes.size(), orig.size());
EXPECT_EQ(0, memcmp(decoded_jpeg_bytes.data(), orig.data(), orig.size()));
}
#if JPEGXL_ENABLE_JPEG // Loading .jpg files requires libjpeg support.
TEST(EncodeTest, JXL_TRANSCODE_JPEG_TEST(JPEGFrameTest)) {
for (int skip_basic_info = 0; skip_basic_info < 2; skip_basic_info++) {
for (int skip_color_encoding = 0; skip_color_encoding < 2;
skip_color_encoding++) {
const std::string jpeg_path =
"imagecompression.info/flower_foveon_cropped.jpg";
const jxl::PaddedBytes orig = jxl::ReadTestData(jpeg_path);
jxl::CodecInOut orig_io;
ASSERT_TRUE(SetFromBytes(jxl::Span<const uint8_t>(orig), &orig_io,
/*pool=*/nullptr));
JxlEncoderPtr enc = JxlEncoderMake(nullptr);
JxlEncoderOptions* options = JxlEncoderOptionsCreate(enc.get(), NULL);
if (!skip_basic_info) {
JxlBasicInfo basic_info;
JxlEncoderInitBasicInfo(&basic_info);
basic_info.xsize = orig_io.xsize();
basic_info.ysize = orig_io.ysize();
basic_info.uses_original_profile = true;
EXPECT_EQ(JXL_ENC_SUCCESS,
JxlEncoderSetBasicInfo(enc.get(), &basic_info));
}
if (!skip_color_encoding) {
JxlColorEncoding color_encoding;
JxlColorEncodingSetToSRGB(&color_encoding, /*is_gray=*/false);
EXPECT_EQ(JXL_ENC_SUCCESS,
JxlEncoderSetColorEncoding(enc.get(), &color_encoding));
}
EXPECT_EQ(JXL_ENC_SUCCESS,
JxlEncoderAddJPEGFrame(options, orig.data(), orig.size()));
JxlEncoderCloseInput(enc.get());
std::vector<uint8_t> compressed = std::vector<uint8_t>(64);
uint8_t* next_out = compressed.data();
size_t avail_out = compressed.size() - (next_out - compressed.data());
JxlEncoderStatus process_result = JXL_ENC_NEED_MORE_OUTPUT;
while (process_result == JXL_ENC_NEED_MORE_OUTPUT) {
process_result =
JxlEncoderProcessOutput(enc.get(), &next_out, &avail_out);
if (process_result == JXL_ENC_NEED_MORE_OUTPUT) {
size_t offset = next_out - compressed.data();
compressed.resize(compressed.size() * 2);
next_out = compressed.data() + offset;
avail_out = compressed.size() - offset;
}
}
compressed.resize(next_out - compressed.data());
EXPECT_EQ(JXL_ENC_SUCCESS, process_result);
jxl::DecompressParams dparams;
jxl::CodecInOut decoded_io;
EXPECT_TRUE(jxl::DecodeFile(
dparams,
jxl::Span<const uint8_t>(compressed.data(), compressed.size()),
&decoded_io, /*pool=*/nullptr));
jxl::ButteraugliParams ba;
EXPECT_LE(ButteraugliDistance(orig_io, decoded_io, ba,
/*distmap=*/nullptr, nullptr),
2.5f);
}
}
}
#endif // JPEGXL_ENABLE_JPEG
| 24,581 | 9,282 |
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2017 Couchbase, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "programs/hostname_utils.h"
#include "programs/getpass.h"
#include <getopt.h>
#include <memcached/protocol_binary.h>
#include <nlohmann/json.hpp>
#include <platform/string_hex.h>
#include <protocol/connection/client_connection.h>
#include <protocol/connection/client_mcbp_commands.h>
#include <utilities/json_utilities.h>
#include <utilities/terminate_handler.h>
#include <inttypes.h>
#include <strings.h>
#include <array>
#include <cstdlib>
#include <gsl/gsl>
#include <iostream>
#include <stdexcept>
#define JSON_DUMP_INDENT_SIZE 4
class Timings {
public:
explicit Timings(const nlohmann::json& json) {
initialize(json);
}
uint64_t getTotal() const {
return total;
}
void dumpHistogram(const std::string& opcode) {
if (data.is_null()) {
return;
}
std::cout << "The following data is collected for \"" << opcode << "\""
<< std::endl;
auto dataArray = data.get<std::vector<std::vector<nlohmann::json>>>();
for (auto item : dataArray) {
auto count = item[1].get<uint64_t>();
if (count > maxCount) {
maxCount = count;
}
}
using namespace std::chrono;
// loop though all the buckets in the json object and print them
// to std out
uint64_t lastBuckLow = bucketsLow;
for (auto bucket : dataArray) {
// Get the current bucket's highest value it would track counts for
auto buckHigh = bucket[0].get<uint64_t>();
// Get the counts for this bucket
auto count = bucket[1].get<uint64_t>();
// Get the percentile of counts that are <= buckHigh
auto percentile = bucket[2].get<double>();
if (lastBuckLow != buckHigh) {
// Cast the high bucket width to us, ms and seconds so we
// can check which units we should be using for this bucket
auto buckHighUs = microseconds(buckHigh);
auto buckHighMs = duration_cast<milliseconds>(buckHighUs);
auto buckHighS = duration_cast<seconds>(buckHighUs);
// If the bucket width values are in the order of tens of
// seconds or milli seconds then print them as seconds or milli
// seconds respectively. Otherwise print them as micro seconds
// We're using tens of unit thresh holds so that each bucket
// has 2 sig fig of differentiation in their width, so we dont
// have buckets that are [1 - 1]s 100 (90.000%)
if (buckHighS.count() > 10) {
auto low =
duration_cast<seconds>(microseconds(lastBuckLow));
dump("s",
low.count(),
buckHighS.count(),
count,
percentile);
} else if (buckHighMs.count() > 10) {
auto low = duration_cast<milliseconds>(
microseconds(lastBuckLow));
dump("ms",
low.count(),
buckHighMs.count(),
count,
percentile);
} else {
dump("us", lastBuckLow, buckHigh, count, percentile);
}
}
// Set the low bucket value to this buckets high width value.
lastBuckLow = buckHigh;
}
std::cout << "Total: " << total << " operations" << std::endl;
}
private:
void initialize(const nlohmann::json& root) {
if (root.find("error") != root.end()) {
// The server responded with an error.. send that to the user
throw std::runtime_error(root["error"].get<std::string>());
}
if (root.find("data") != root.end()) {
total = cb::jsonGet<uint64_t>(root, "total");
data = cb::jsonGet<nlohmann::json>(root, "data");
bucketsLow = cb::jsonGet<uint64_t>(root, "bucketsLow");
}
}
void dump(const char* timeunit,
int64_t low,
int64_t high,
int64_t count,
double percentile) {
char buffer[1024];
int offset = sprintf(
buffer, "[%5" PRId64 " - %5" PRId64 "]%s", low, high, timeunit);
offset += sprintf(buffer + offset, " (%6.4lf%%)\t", percentile);
// Determine how wide the max value would be, and pad all counts
// to that width.
int max_width = snprintf(buffer, 0, "%" PRIu64, maxCount);
offset += sprintf(buffer + offset, " %*" PRId64, max_width, count);
double factionOfHashes = (count / static_cast<double>(maxCount));
int num = static_cast<int>(44.0 * factionOfHashes);
offset += sprintf(buffer + offset, " | ");
for (int ii = 0; ii < 44 && ii < num; ++ii) {
offset += sprintf(buffer + offset, "#");
}
std::cout << buffer << std::endl;
}
/**
* The highest value of all the samples (used to figure out the width
* used for each sample in the printout)
*/
uint64_t maxCount = 0;
/**
* Json object to store the data returned by memcached
*/
nlohmann::json data;
/**
* The starting point of the lowest buckets width.
* E.g. if buckets were [10 - 20][20 - 30] it would be 10.
* Used to help reduce the amount the amount of json sent to
* mctimings
*/
uint64_t bucketsLow = 0;
/**
* Total number of counts recorded in the histogram
*/
uint64_t total = 0;
};
std::string opcode2string(cb::mcbp::ClientOpcode opcode) {
try {
return to_string(opcode);
} catch (const std::exception&) {
return cb::to_hex(uint8_t(opcode));
}
}
static void request_cmd_timings(MemcachedConnection& connection,
const std::string& bucket,
cb::mcbp::ClientOpcode opcode,
bool verbose,
bool skip,
bool json) {
BinprotGetCmdTimerCommand cmd;
cmd.setBucket(bucket);
cmd.setOpcode(opcode);
connection.sendCommand(cmd);
BinprotGetCmdTimerResponse resp;
connection.recvResponse(resp);
if (!resp.isSuccess()) {
switch (resp.getStatus()) {
case cb::mcbp::Status::KeyEnoent:
std::cerr << "Cannot find bucket: " << bucket << std::endl;
break;
case cb::mcbp::Status::Eaccess:
if (bucket == "/all/") {
std::cerr << "Not authorized to access aggregated timings data."
<< std::endl
<< "Try specifying a bucket by using -b bucketname"
<< std::endl;
} else {
std::cerr << "Not authorized to access timings data"
<< std::endl;
}
break;
default:
std::cerr << "Command failed: " << to_string(resp.getStatus())
<< std::endl;
}
exit(EXIT_FAILURE);
}
try {
auto command = opcode2string(opcode);
if (json) {
auto timings = resp.getTimings();
if (timings == nullptr) {
if (!skip) {
std::cerr << "The server doesn't have information about \""
<< command << "\"" << std::endl;
}
} else {
timings["command"] = command;
std::cout << timings.dump(JSON_DUMP_INDENT_SIZE) << std::endl;
}
} else {
Timings timings(resp.getTimings());
if (timings.getTotal() == 0) {
if (skip == 0) {
std::cout << "The server doesn't have information about \""
<< command << "\"" << std::endl;
}
} else {
if (verbose) {
timings.dumpHistogram(command);
} else {
std::cout << command << " " << timings.getTotal()
<< " operations" << std::endl;
}
}
}
} catch (const std::exception& e) {
std::cerr << "Fatal error: " << e.what() << std::endl;
exit(EXIT_FAILURE);
}
}
static void request_stat_timings(MemcachedConnection& connection,
const std::string& key,
bool verbose,
bool json_output) {
std::map<std::string, std::string> map;
try {
map = connection.statsMap(key);
} catch (const ConnectionError& ex) {
if (ex.isNotFound()) {
std::cerr << "Cannot find statistic: " << key << std::endl;
} else if (ex.isAccessDenied()) {
std::cerr << "Not authorized to access timings data" << std::endl;
} else {
std::cerr << "Fatal error: " << ex.what() << std::endl;
}
exit(EXIT_FAILURE);
}
// The return value from stats injects the result in a k-v pair, but
// these responses (i.e. subdoc_execute) don't include a key,
// so the statsMap adds them into the map with a counter to make sure
// that you can fetch all of them. We only expect a single entry, which
// would be named "0"
auto iter = map.find("0");
if (iter == map.end()) {
std::cerr << "Failed to fetch statistics for \"" << key << "\""
<< std::endl;
exit(EXIT_FAILURE);
}
// And the value for the item should be valid JSON
nlohmann::json json = nlohmann::json::parse(iter->second);
if (json.is_null()) {
std::cerr << "Failed to fetch statistics for \"" << key
<< "\". Not json" << std::endl;
exit(EXIT_FAILURE);
}
try {
if (json_output) {
json["command"] = key;
std::cout << json.dump(JSON_DUMP_INDENT_SIZE) << std::endl;
} else {
Timings timings(json);
if (verbose) {
timings.dumpHistogram(key);
} else {
std::cout << key << " " << timings.getTotal() << " operations"
<< std::endl;
}
}
} catch (const std::exception& e) {
std::cerr << "Fatal error: " << e.what() << std::endl;
exit(EXIT_FAILURE);
}
}
void usage() {
std::cerr << "Usage mctimings [options] [opcode / statname]\n"
<< R"(Options:
-h or --host hostname[:port] The host (with an optional port) to connect to
-p or --port port The port number to connect to
-b or --bucket bucketname The name of the bucket to operate on
-u or --user username The name of the user to authenticate as
-P or --password password The passord to use for authentication
(use '-' to read from standard input)
-s or --ssl Connect to the server over SSL
-4 or --ipv4 Connect over IPv4
-6 or --ipv6 Connect over IPv6
-v or --verbose Use verbose output
-S Read password from standard input
-j or --json[=pretty] Print JSON instead of histograms
--help This help text
)" << std::endl
<< std::endl
<< "Example:" << std::endl
<< " mctimings --user operator --bucket /all/ --password - "
"--verbose GET SET"
<< std::endl;
}
int main(int argc, char** argv) {
// Make sure that we dump callstacks on the console
install_backtrace_terminate_handler();
int cmd;
std::string port{"11210"};
std::string host{"localhost"};
std::string user{};
std::string password{};
std::string bucket{"/all/"};
sa_family_t family = AF_UNSPEC;
bool verbose = false;
bool secure = false;
bool json = false;
/* Initialize the socket subsystem */
cb_initialize_sockets();
struct option long_options[] = {
{"ipv4", no_argument, nullptr, '4'},
{"ipv6", no_argument, nullptr, '6'},
{"host", required_argument, nullptr, 'h'},
{"port", required_argument, nullptr, 'p'},
{"bucket", required_argument, nullptr, 'b'},
{"password", required_argument, nullptr, 'P'},
{"user", required_argument, nullptr, 'u'},
{"ssl", no_argument, nullptr, 's'},
{"verbose", no_argument, nullptr, 'v'},
{"json", optional_argument, nullptr, 'j'},
{"help", no_argument, nullptr, 0},
{nullptr, 0, nullptr, 0}};
while ((cmd = getopt_long(
argc, argv, "46h:p:u:b:P:sSvj", long_options, nullptr)) !=
EOF) {
switch (cmd) {
case '6':
family = AF_INET6;
break;
case '4':
family = AF_INET;
break;
case 'h':
host.assign(optarg);
break;
case 'p':
port.assign(optarg);
break;
case 'S':
password.assign("-");
break;
case 'b':
bucket.assign(optarg);
break;
case 'u':
user.assign(optarg);
break;
case 'P':
password.assign(optarg);
break;
case 's':
secure = true;
break;
case 'v':
verbose = true;
break;
case 'j':
json = true;
if (optarg && strcasecmp(optarg, "pretty") == 0) {
verbose = true;
}
break;
default:
usage();
return cmd == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
}
}
if (password == "-") {
password.assign(getpass());
} else if (password.empty()) {
const char* env_password = std::getenv("CB_PASSWORD");
if (env_password) {
password = env_password;
}
}
try {
in_port_t in_port;
sa_family_t fam;
std::tie(host, in_port, fam) = cb::inet::parse_hostname(host, port);
if (family == AF_UNSPEC) { // The user may have used -4 or -6
family = fam;
}
MemcachedConnection connection(host, in_port, family, secure);
connection.connect();
// MEMCACHED_VERSION contains the git sha
connection.setAgentName("mctimings " MEMCACHED_VERSION);
connection.setFeatures({cb::mcbp::Feature::XERROR});
if (!user.empty()) {
connection.authenticate(user, password,
connection.getSaslMechanisms());
}
if (!bucket.empty() && bucket != "/all/") {
connection.selectBucket(bucket);
}
if (optind == argc) {
for (int ii = 0; ii < 256; ++ii) {
request_cmd_timings(connection,
bucket,
cb::mcbp::ClientOpcode(ii),
verbose,
true,
json);
}
} else {
for (; optind < argc; ++optind) {
try {
const auto opcode = to_opcode(argv[optind]);
request_cmd_timings(
connection, bucket, opcode, verbose, false, json);
} catch (const std::invalid_argument&) {
// Not a command timing, try as statistic timing.
request_stat_timings(
connection, argv[optind], verbose, json);
}
}
}
} catch (const ConnectionError& ex) {
std::cerr << ex.what() << std::endl;
return EXIT_FAILURE;
} catch (const std::runtime_error& ex) {
std::cerr << ex.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| 17,015 | 4,895 |
/*
Copyright (c) 2020, Ford Motor Company, Livio
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 the copyright holders nor the names of their
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 "sdl_rpc_plugin/commands/hmi/bc_get_app_properties_request.h"
#include "application_manager/policies/policy_handler_interface.h"
#include "application_manager/rpc_service.h"
#include "interfaces/MOBILE_API.h"
namespace sdl_rpc_plugin {
using namespace application_manager;
namespace commands {
SDL_CREATE_LOG_VARIABLE("Commands")
BCGetAppPropertiesRequest::BCGetAppPropertiesRequest(
const application_manager::commands::MessageSharedPtr& message,
ApplicationManager& application_manager,
app_mngr::rpc_service::RPCService& rpc_service,
app_mngr::HMICapabilities& hmi_capabilities,
policy::PolicyHandlerInterface& policy_handler)
: RequestFromHMI(message,
application_manager,
rpc_service,
hmi_capabilities,
policy_handler) {}
void BCGetAppPropertiesRequest::FillAppProperties(
const std::string& policy_app_id,
smart_objects::SmartObject& out_properties) const {
SDL_LOG_AUTO_TRACE();
policy::AppProperties app_properties;
const bool result =
policy_handler_.GetAppProperties(policy_app_id, app_properties);
if (!result) {
SDL_LOG_DEBUG(
"Failed to get app parameters for policy_app_id: " << policy_app_id);
return;
}
out_properties[strings::policy_app_id] = policy_app_id;
out_properties[strings::enabled] = app_properties.enabled;
policy::StringArray nicknames;
policy::StringArray app_hmi_types;
policy_handler_.GetInitialAppData(policy_app_id, &nicknames, &app_hmi_types);
smart_objects::SmartObject nicknames_array(smart_objects::SmartType_Array);
size_t i = 0;
for (const auto& nickname : nicknames) {
nicknames_array[i++] = nickname;
}
out_properties[strings::nicknames] = nicknames_array;
if (!app_properties.auth_token.empty()) {
out_properties[strings::auth_token] = app_properties.auth_token;
}
if (!app_properties.transport_type.empty()) {
out_properties[strings::transport_type] = app_properties.transport_type;
}
if (!app_properties.hybrid_app_preference.empty()) {
out_properties[strings::hybrid_app_preference] =
app_properties.hybrid_app_preference;
}
if (!app_properties.endpoint.empty()) {
out_properties[strings::endpoint] = app_properties.endpoint;
}
}
void BCGetAppPropertiesRequest::Run() {
SDL_LOG_AUTO_TRACE();
const auto& msg_params = (*message_)[strings::msg_params];
smart_objects::SmartObject response_params(smart_objects::SmartType_Map);
if (msg_params.keyExists(strings::policy_app_id)) {
const auto policy_app_id = msg_params[strings::policy_app_id].asString();
smart_objects::SmartObject properties(smart_objects::SmartType_Map);
FillAppProperties(policy_app_id, properties);
if (!properties.empty()) {
response_params[strings::properties][0] = properties;
}
} else {
SDL_LOG_DEBUG(
"policyAppID was absent in request, all apps properties "
"will be returned.");
const auto app_ids = policy_handler_.GetApplicationPolicyIDs();
int i = 0;
for (auto& app_id : app_ids) {
smart_objects::SmartObject properties(smart_objects::SmartType_Map);
FillAppProperties(app_id, properties);
response_params[strings::properties][i++] = properties;
}
}
if (response_params[strings::properties].empty()) {
SendErrorResponse(
(*message_)[strings::params][strings::correlation_id].asUInt(),
hmi_apis::FunctionID::BasicCommunication_GetAppProperties,
hmi_apis::Common_Result::DATA_NOT_AVAILABLE,
"Requested data not available",
application_manager::commands::Command::SOURCE_SDL_TO_HMI);
return;
}
SendResponse(true,
(*message_)[strings::params][strings::correlation_id].asUInt(),
hmi_apis::FunctionID::BasicCommunication_GetAppProperties,
hmi_apis::Common_Result::SUCCESS,
&response_params);
}
} // namespace commands
} // namespace sdl_rpc_plugin
| 5,536 | 1,756 |
/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file Log.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include "Log.h"
#include "common.h"
#include <iomanip>
#include <iostream>
#include <mutex>
#include <thread>
#ifdef __APPLE__
#include <pthread.h>
#endif
using namespace std;
using namespace energi;
//⊳⊲◀▶■▣▢□▷◁▧▨▩▲◆◉◈◇◎●◍◌○◼☑☒☎☢☣☰☀♽♥♠✩✭❓✔✓✖✕✘✓✔✅⚒⚡⦸⬌∅⁕«««»»»⚙
// Logging
int g_logVerbosity = 5;
bool g_logNoColor = false;
bool g_logSyslog = false;
const char* LogChannel::name()
{
return EthGray "..";
}
const char* WarnChannel::name()
{
return EthRed " X";
}
const char* NoteChannel::name()
{
return EthBlue " i";
}
LogOutputStreamBase::LogOutputStreamBase(char const* _id, unsigned _v) : m_verbosity(_v)
{
static std::locale logLocl = std::locale("");
if ((int)_v <= g_logVerbosity) {
m_sstr.imbue(logLocl);
if (g_logSyslog)
m_sstr << std::left << std::setw(8) << getThreadName() << " " EthReset;
else {
time_t rawTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
char buf[24];
if (strftime(buf, 24, "%X", localtime(&rawTime)) == 0)
buf[0] = '\0'; // empty if case strftime fails
m_sstr << _id << " " EthViolet << buf << " " EthBlue << std::left << std::setw(8)
<< getThreadName() << " " EthReset;
}
}
}
/// Associate a name with each thread for nice logging.
struct ThreadLocalLogName
{
ThreadLocalLogName(char const* _name) { name = _name; }
thread_local static char const* name;
};
thread_local char const* ThreadLocalLogName::name;
ThreadLocalLogName g_logThreadName("main");
string energi::getThreadName()
{
#if defined(__linux__) || defined(__APPLE__)
char buffer[128];
pthread_getname_np(pthread_self(), buffer, 127);
buffer[127] = 0;
return buffer;
#else
return ThreadLocalLogName::name ? ThreadLocalLogName::name : "<unknown>";
#endif
}
void energi::setThreadName(char const* _n)
{
#if defined(__linux__)
pthread_setname_np(pthread_self(), _n);
#elif defined(__APPLE__)
pthread_setname_np(_n);
#else
ThreadLocalLogName::name = _n;
#endif
}
void energi::simpleDebugOut(std::string const& _s)
{
try {
if (!g_logNoColor) {
std::cerr << _s + '\n';
return;
}
bool skip = false;
std::stringstream ss;
for (auto it : _s) {
if (!skip && it == '\x1b')
skip = true;
else if (skip && it == 'm')
skip = false;
else if (!skip)
ss << it;
}
ss << '\n';
std::cerr << ss.str();
} catch (...) {
return;
}
}
| 3,368 | 1,271 |
#include "../search/analysisdata.h"
AnalysisData::AnalysisData()
:move(Board::NULL_LOC),
numVisits(0),
playSelectionValue(0.0),
lcb(0.0),
radius(0.0),
utility(0.0),
resultUtility(0.0),
scoreUtility(0.0),
winLossValue(0.0),
policyPrior(0.0),
scoreMean(0.0),
scoreStdev(0.0),
lead(0.0),
ess(0.0),
weightFactor(0.0),
order(0),
isSymmetryOf(Board::NULL_LOC),
symmetry(0),
pv(),
pvVisits(),
node(NULL)
{}
AnalysisData::AnalysisData(const AnalysisData& other)
:move(other.move),
numVisits(other.numVisits),
playSelectionValue(other.playSelectionValue),
lcb(other.lcb),
radius(other.radius),
utility(other.utility),
resultUtility(other.resultUtility),
scoreUtility(other.scoreUtility),
winLossValue(other.winLossValue),
policyPrior(other.policyPrior),
scoreMean(other.scoreMean),
scoreStdev(other.scoreStdev),
lead(other.lead),
ess(other.ess),
weightFactor(other.weightFactor),
order(other.order),
isSymmetryOf(other.isSymmetryOf),
symmetry(other.symmetry),
pv(other.pv),
pvVisits(other.pvVisits),
node(other.node)
{}
AnalysisData::AnalysisData(AnalysisData&& other) noexcept
:move(other.move),
numVisits(other.numVisits),
playSelectionValue(other.playSelectionValue),
lcb(other.lcb),
radius(other.radius),
utility(other.utility),
resultUtility(other.resultUtility),
scoreUtility(other.scoreUtility),
winLossValue(other.winLossValue),
policyPrior(other.policyPrior),
scoreMean(other.scoreMean),
scoreStdev(other.scoreStdev),
lead(other.lead),
ess(other.ess),
weightFactor(other.weightFactor),
order(other.order),
isSymmetryOf(other.isSymmetryOf),
symmetry(other.symmetry),
pv(std::move(other.pv)),
pvVisits(std::move(other.pvVisits)),
node(other.node)
{}
AnalysisData::~AnalysisData()
{}
AnalysisData& AnalysisData::operator=(const AnalysisData& other) {
if(this == &other)
return *this;
move = other.move;
numVisits = other.numVisits;
playSelectionValue = other.playSelectionValue;
lcb = other.lcb;
radius = other.radius;
utility = other.utility;
resultUtility = other.resultUtility;
scoreUtility = other.scoreUtility;
winLossValue = other.winLossValue;
policyPrior = other.policyPrior;
scoreMean = other.scoreMean;
scoreStdev = other.scoreStdev;
lead = other.lead;
ess = other.ess;
weightFactor = other.weightFactor;
order = other.order;
isSymmetryOf = other.isSymmetryOf;
symmetry = other.symmetry;
pv = other.pv;
pvVisits = other.pvVisits;
node = other.node;
return *this;
}
AnalysisData& AnalysisData::operator=(AnalysisData&& other) noexcept {
if(this == &other)
return *this;
move = other.move;
numVisits = other.numVisits;
playSelectionValue = other.playSelectionValue;
lcb = other.lcb;
radius = other.radius;
utility = other.utility;
resultUtility = other.resultUtility;
scoreUtility = other.scoreUtility;
winLossValue = other.winLossValue;
policyPrior = other.policyPrior;
scoreMean = other.scoreMean;
scoreStdev = other.scoreStdev;
lead = other.lead;
ess = other.ess;
weightFactor = other.weightFactor;
order = other.order;
isSymmetryOf = other.isSymmetryOf;
symmetry = other.symmetry;
pv = std::move(other.pv);
pvVisits = std::move(other.pvVisits);
node = other.node;
return *this;
}
bool operator<(const AnalysisData& a0, const AnalysisData& a1) {
if(a0.playSelectionValue > a1.playSelectionValue)
return true;
else if(a0.playSelectionValue < a1.playSelectionValue)
return false;
if(a0.numVisits > a1.numVisits)
return true;
else if(a0.numVisits < a1.numVisits)
return false;
// else if(a0.utility > a1.utility)
// return true;
// else if(a0.utility < a1.utility)
// return false;
else
return a0.policyPrior > a1.policyPrior;
}
bool AnalysisData::pvContainsPass() const {
for(int i = 0; i<pv.size(); i++)
if(pv[i] == Board::PASS_LOC)
return true;
return false;
}
void AnalysisData::writePV(std::ostream& out, const Board& board) const {
for(int j = 0; j<pv.size(); j++) {
if(j > 0)
out << " ";
out << Location::toString(pv[j],board);
}
}
void AnalysisData::writePVVisits(std::ostream& out) const {
for(int j = 0; j<pvVisits.size(); j++) {
if(j > 0)
out << " ";
out << pvVisits[j];
}
}
int AnalysisData::getPVLenUpToPhaseEnd(const Board& initialBoard, const BoardHistory& initialHist, Player initialPla) const {
Board board(initialBoard);
BoardHistory hist(initialHist);
Player nextPla = initialPla;
int j;
for(j = 0; j<pv.size(); j++) {
hist.makeBoardMoveAssumeLegal(board,pv[j],nextPla,NULL);
nextPla = getOpp(nextPla);
if(hist.encorePhase != initialHist.encorePhase)
break;
}
return j;
}
void AnalysisData::writePVUpToPhaseEnd(std::ostream& out, const Board& initialBoard, const BoardHistory& initialHist, Player initialPla) const {
Board board(initialBoard);
BoardHistory hist(initialHist);
Player nextPla = initialPla;
for(int j = 0; j<pv.size(); j++) {
if(j > 0)
out << " ";
out << Location::toString(pv[j],board);
hist.makeBoardMoveAssumeLegal(board,pv[j],nextPla,NULL);
nextPla = getOpp(nextPla);
if(hist.encorePhase != initialHist.encorePhase)
break;
}
}
void AnalysisData::writePVVisitsUpToPhaseEnd(std::ostream& out, const Board& initialBoard, const BoardHistory& initialHist, Player initialPla) const {
Board board(initialBoard);
BoardHistory hist(initialHist);
Player nextPla = initialPla;
assert(pv.size() == pvVisits.size());
for(int j = 0; j<pv.size(); j++) {
if(j > 0)
out << " ";
out << pvVisits[j];
hist.makeBoardMoveAssumeLegal(board,pv[j],nextPla,NULL);
nextPla = getOpp(nextPla);
if(hist.encorePhase != initialHist.encorePhase)
break;
}
}
| 5,877 | 2,234 |
/***************************************************************
*
* Copyright (C) 1990-2011, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "filename_tools.h"
#include "condor_debug.h"
#include "MyString.h"
#include "condor_uid.h"
#include "filesystem_remap.h"
#include "condor_config.h"
#include "directory.h"
#if defined(LINUX)
#include <sys/mount.h>
#endif
FilesystemRemap::FilesystemRemap() :
m_mappings(),
m_mounts_shared(),
m_remap_proc(false)
{
ParseMountinfo();
FixAutofsMounts();
}
int FilesystemRemap::AddMapping(std::string source, std::string dest) {
if (!is_relative_to_cwd(source) && !is_relative_to_cwd(dest)) {
std::list<pair_strings>::const_iterator it;
for (it = m_mappings.begin(); it != m_mappings.end(); it++) {
if ((it->second.length() == dest.length()) && (it->second.compare(dest) == 0)) {
dprintf(D_ALWAYS, "Mapping already present for %s.\n", dest.c_str());
return -1;
}
}
if (CheckMapping(dest)) {
dprintf(D_ALWAYS, "Failed to convert shared mount to private mapping");
return -1;
}
m_mappings.push_back( std::pair<std::string, std::string>(source, dest) );
} else {
dprintf(D_ALWAYS, "Unable to add mappings for relative directories (%s, %s).\n", source.c_str(), dest.c_str());
return -1;
}
return 0;
}
int FilesystemRemap::CheckMapping(const std::string & mount_point) {
#ifndef HAVE_UNSHARE
dprintf(D_ALWAYS, "This system doesn't support remounting of filesystems: %s\n", mount_point.c_str());
return -1;
#else
bool best_is_shared = false;
size_t best_len = 0;
const std::string *best = NULL;
dprintf(D_FULLDEBUG, "Checking the mapping of mount point %s.\n", mount_point.c_str());
for (std::list<pair_str_bool>::const_iterator it = m_mounts_shared.begin(); it != m_mounts_shared.end(); it++) {
std::string first = it->first;
if ((strncmp(first.c_str(), mount_point.c_str(), first.size()) == 0) && (first.size() > best_len)) {
best_len = first.size();
best = &(it->first);
best_is_shared = it->second;
}
}
if (!best_is_shared) {
return 0;
}
dprintf(D_ALWAYS, "Current mount, %s, is shared.\n", best->c_str());
#if !defined(HAVE_MS_SLAVE) && !defined(HAVE_MS_REC)
TemporaryPrivSentry sentry(PRIV_ROOT);
// Re-mount the mount point as a bind mount, so we can subsequently
// re-mount it as private.
if (mount(mount_point.c_str(), mount_point.c_str(), NULL, MS_BIND, NULL)) {
dprintf(D_ALWAYS, "Marking %s as a bind mount failed. (errno=%d, %s)\n", mount_point.c_str(), errno, strerror(errno));
return -1;
}
#ifdef HAVE_MS_PRIVATE
if (mount(mount_point.c_str(), mount_point.c_str(), NULL, MS_PRIVATE, NULL)) {
dprintf(D_ALWAYS, "Marking %s as a private mount failed. (errno=%d, %s)\n", mount_point.c_str(), errno, strerror(errno));
return -1;
} else {
dprintf(D_FULLDEBUG, "Marking %s as a private mount successful.\n", mount_point.c_str());
}
#endif
#endif
return 0;
#endif
}
int FilesystemRemap::FixAutofsMounts() {
#ifndef HAVE_UNSHARE
// An appropriate error message is printed in FilesystemRemap::CheckMapping;
// Not doing anything here.
return -1;
#else
#ifdef HAVE_MS_SHARED
TemporaryPrivSentry sentry(PRIV_ROOT);
for (std::list<pair_strings>::const_iterator it=m_mounts_autofs.begin(); it != m_mounts_autofs.end(); it++) {
if (mount(it->first.c_str(), it->second.c_str(), NULL, MS_SHARED, NULL)) {
dprintf(D_ALWAYS, "Marking %s->%s as a shared-subtree autofs mount failed. (errno=%d, %s)\n", it->first.c_str(), it->second.c_str(), errno, strerror(errno));
return -1;
} else {
dprintf(D_FULLDEBUG, "Marking %s as a shared-subtree autofs mount successful.\n", it->second.c_str());
}
}
#endif
return 0;
#endif
}
// This is called within the exec
// IT CANNOT CALL DPRINTF!
int FilesystemRemap::PerformMappings() {
int retval = 0;
#if defined(LINUX)
std::list<pair_strings>::iterator it;
for (it = m_mappings.begin(); it != m_mappings.end(); it++) {
if (strcmp(it->second.c_str(), "/") == 0) {
if ((retval = chroot(it->first.c_str()))) {
break;
}
if ((retval = chdir("/"))) {
break;
}
} else if ((retval = mount(it->first.c_str(), it->second.c_str(), NULL, MS_BIND, NULL))) {
break;
}
}
if ((!retval) && m_remap_proc) {
retval = mount("proc", "/proc", "proc", 0, NULL);
}
#endif
return retval;
}
std::string FilesystemRemap::RemapFile(std::string target) {
if (target[0] != '/')
return std::string();
size_t pos = target.rfind("/");
if (pos == std::string::npos)
return target;
std::string filename = target.substr(pos, target.size() - pos);
std::string directory = target.substr(0, target.size() - filename.size());
return RemapDir(directory) + filename;
}
std::string FilesystemRemap::RemapDir(std::string target) {
if (target[0] != '/')
return std::string();
std::list<pair_strings>::iterator it;
for (it = m_mappings.begin(); it != m_mappings.end(); it++) {
if ((it->first.compare(0, it->first.length(), target, 0, it->first.length()) == 0)
&& (it->second.compare(0, it->second.length(), it->first, 0, it->second.length()) == 0)) {
target.replace(0, it->first.length(), it->second);
}
}
return target;
}
void FilesystemRemap::RemapProc() {
m_remap_proc = true;
}
/*
Sample mountinfo contents (from http://www.kernel.org/doc/Documentation/filesystems/proc.txt):
36 35 98:0 /mnt1 /mnt2 rw,noatime master:1 - ext3 /dev/root rw,errors=continue
(1)(2)(3) (4) (5) (6) (7) (8) (9) (10) (11)
(1) mount ID: unique identifier of the mount (may be reused after umount)
(2) parent ID: ID of parent (or of self for the top of the mount tree)
(3) major:minor: value of st_dev for files on filesystem
(4) root: root of the mount within the filesystem
(5) mount point: mount point relative to the process's root
(6) mount options: per mount options
(7) optional fields: zero or more fields of the form "tag[:value]"
(8) separator: marks the end of the optional fields
(9) filesystem type: name of filesystem of the form "type[.subtype]"
(10) mount source: filesystem specific information or "none"
(11) super options: per super block options
*/
#define ADVANCE_TOKEN(token, str) { \
if ((token = str.GetNextToken(" ", false)) == NULL) { \
fclose(fd); \
dprintf(D_ALWAYS, "Invalid line in mountinfo file: %s\n", str.Value()); \
return; \
} \
}
#define SHARED_STR "shared:"
void FilesystemRemap::ParseMountinfo() {
MyString str, str2;
const char * token;
FILE *fd;
bool is_shared;
if ((fd = fopen("/proc/self/mountinfo", "r")) == NULL) {
if (errno == ENOENT) {
dprintf(D_FULLDEBUG, "The /proc/self/mountinfo file does not exist; kernel support probably lacking. Will assume normal mount structure.\n");
} else {
dprintf(D_ALWAYS, "Unable to open the mountinfo file (/proc/self/mountinfo). (errno=%d, %s)\n", errno, strerror(errno));
}
return;
}
while (str2.readLine(fd, false)) {
str = str2;
str.Tokenize();
ADVANCE_TOKEN(token, str) // mount ID
ADVANCE_TOKEN(token, str) // parent ID
ADVANCE_TOKEN(token, str) // major:minor
ADVANCE_TOKEN(token, str) // root
ADVANCE_TOKEN(token, str) // mount point
std::string mp(token);
ADVANCE_TOKEN(token, str) // mount options
ADVANCE_TOKEN(token, str) // optional fields
is_shared = false;
while (strcmp(token, "-") != 0) {
is_shared = is_shared || (strncmp(token, SHARED_STR, strlen(SHARED_STR)) == 0);
ADVANCE_TOKEN(token, str)
}
ADVANCE_TOKEN(token, str) // filesystem type
if ((!is_shared) && (strcmp(token, "autofs") == 0)) {
ADVANCE_TOKEN(token, str)
m_mounts_autofs.push_back(pair_strings(token, mp));
}
// This seems a bit too chatty - disabling for now.
// dprintf(D_FULLDEBUG, "Mount: %s, shared: %d.\n", mp.c_str(), is_shared);
m_mounts_shared.push_back(pair_str_bool(mp, is_shared));
}
fclose(fd);
}
pair_strings_vector
root_dir_list()
{
pair_strings_vector execute_dir_list;
execute_dir_list.push_back(pair_strings("root","/"));
const char * allowed_root_dirs = param("NAMED_CHROOT");
if (allowed_root_dirs) {
StringList chroot_list(allowed_root_dirs);
chroot_list.rewind();
const char * next_chroot;
while ( (next_chroot=chroot_list.next()) ) {
MyString chroot_spec(next_chroot);
chroot_spec.Tokenize();
const char * chroot_name = chroot_spec.GetNextToken("=", false);
if (chroot_name == NULL) {
dprintf(D_ALWAYS, "Invalid named chroot: %s\n", chroot_spec.Value());
continue;
}
const char * next_dir = chroot_spec.GetNextToken("=", false);
if (next_dir == NULL) {
dprintf(D_ALWAYS, "Invalid named chroot: %s\n", chroot_spec.Value());
continue;
}
if (IsDirectory(next_dir)) {
pair_strings p(chroot_name, next_dir);
execute_dir_list.push_back(p);
}
}
}
return execute_dir_list;
}
bool
is_trivial_rootdir(const std::string &root_dir)
{
for (std::string::const_iterator it=root_dir.begin(); it!=root_dir.end(); it++) {
if (*it != '/')
return false;
}
return true;
}
| 9,665 | 3,830 |
/*-------------------------------------------------------------------------
* drawElements Quality Program OpenGL ES 3.1 Module
* -------------------------------------------------
*
* Copyright 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief Basic Compute Shader Tests.
*//*--------------------------------------------------------------------*/
#include "es31fAtomicCounterTests.hpp"
#include "gluShaderProgram.hpp"
#include "gluObjectWrapper.hpp"
#include "gluRenderContext.hpp"
#include "glwFunctions.hpp"
#include "glwEnums.hpp"
#include "tcuTestLog.hpp"
#include "deStringUtil.hpp"
#include "deRandom.hpp"
#include "deMemory.h"
#include <vector>
#include <string>
using namespace glw;
using tcu::TestLog;
using std::vector;
using std::string;
namespace deqp
{
namespace gles31
{
namespace Functional
{
namespace
{
class AtomicCounterTest : public TestCase
{
public:
enum Operation
{
OPERATION_INC = (1<<0),
OPERATION_DEC = (1<<1),
OPERATION_GET = (1<<2)
};
enum OffsetType
{
OFFSETTYPE_NONE = 0,
OFFSETTYPE_BASIC,
OFFSETTYPE_REVERSE,
OFFSETTYPE_FIRST_AUTO,
OFFSETTYPE_DEFAULT_AUTO,
OFFSETTYPE_RESET_DEFAULT,
OFFSETTYPE_INVALID,
OFFSETTYPE_INVALID_OVERLAPPING,
OFFSETTYPE_INVALID_DEFAULT
};
enum BindingType
{
BINDINGTYPE_BASIC = 0,
BINDINGTYPE_INVALID,
BINDINGTYPE_INVALID_DEFAULT
};
struct TestSpec
{
TestSpec (void)
: atomicCounterCount (0)
, operations ((Operation)0)
, callCount (0)
, useBranches (false)
, threadCount (0)
, offsetType (OFFSETTYPE_NONE)
, bindingType (BINDINGTYPE_BASIC)
{
}
int atomicCounterCount;
Operation operations;
int callCount;
bool useBranches;
int threadCount;
OffsetType offsetType;
BindingType bindingType;
};
AtomicCounterTest (Context& context, const char* name, const char* description, const TestSpec& spec);
~AtomicCounterTest (void);
void init (void);
void deinit (void);
IterateResult iterate (void);
private:
const TestSpec m_spec;
bool checkAndLogCounterValues (TestLog& log, const vector<deUint32>& counters) const;
bool checkAndLogCallValues (TestLog& log, const vector<deUint32>& increments, const vector<deUint32>& decrements, const vector<deUint32>& preGets, const vector<deUint32>& postGets, const vector<deUint32>& gets) const;
void splitBuffer (const vector<deUint32>& buffer, vector<deUint32>& increments, vector<deUint32>& decrements, vector<deUint32>& preGets, vector<deUint32>& postGets, vector<deUint32>& gets) const;
deUint32 getInitialValue (void) const { return m_spec.callCount * m_spec.threadCount + 1; }
static string generateShaderSource (const TestSpec& spec);
static void getCountersValues (vector<deUint32>& counterValues, const vector<deUint32>& values, int ndx, int counterCount);
static bool checkRange (TestLog& log, const vector<deUint32>& values, const vector<deUint32>& min, const vector<deUint32>& max);
static bool checkUniquenessAndLinearity (TestLog& log, const vector<deUint32>& values);
static bool checkPath (const vector<deUint32>& increments, const vector<deUint32>& decrements, int initialValue, const TestSpec& spec);
int getOperationCount (void) const;
AtomicCounterTest& operator= (const AtomicCounterTest&);
AtomicCounterTest (const AtomicCounterTest&);
};
int AtomicCounterTest::getOperationCount (void) const
{
int count = 0;
if (m_spec.operations & OPERATION_INC)
count++;
if (m_spec.operations & OPERATION_DEC)
count++;
if (m_spec.operations == OPERATION_GET)
count++;
else if (m_spec.operations & OPERATION_GET)
count += 2;
return count;
}
AtomicCounterTest::AtomicCounterTest (Context& context, const char* name, const char* description, const TestSpec& spec)
: TestCase (context, name, description)
, m_spec (spec)
{
}
AtomicCounterTest::~AtomicCounterTest (void)
{
}
void AtomicCounterTest::init (void)
{
}
void AtomicCounterTest::deinit (void)
{
}
string AtomicCounterTest::generateShaderSource (const TestSpec& spec)
{
std::ostringstream src;
src
<< "#version 310 es\n"
<< "layout (local_size_x = 1, local_size_y = 1, local_size_z = 1) in;\n";
{
bool wroteLayout = false;
switch (spec.bindingType)
{
case BINDINGTYPE_INVALID_DEFAULT:
src << "layout(binding=10000";
wroteLayout = true;
break;
default:
// Do nothing
break;
}
switch (spec.offsetType)
{
case OFFSETTYPE_DEFAULT_AUTO:
if (!wroteLayout)
src << "layout(binding=0, ";
else
src << ", ";
src << "offset=4";
wroteLayout = true;
break;
case OFFSETTYPE_RESET_DEFAULT:
DE_ASSERT(spec.atomicCounterCount > 2);
if (!wroteLayout)
src << "layout(binding=0, ";
else
src << ", ";
src << "offset=" << (4 * spec.atomicCounterCount/2);
wroteLayout = true;
break;
case OFFSETTYPE_INVALID_DEFAULT:
if (!wroteLayout)
src << "layout(binding=0, ";
else
src << ", ";
src << "offset=1";
wroteLayout = true;
break;
default:
// Do nothing
break;
}
if (wroteLayout)
src << ") uniform atomic_uint;\n";
}
src
<< "layout(binding = 1, std430) buffer Output {\n";
if ((spec.operations & OPERATION_GET) != 0 && spec.operations != OPERATION_GET)
src << " uint preGet[" << spec.threadCount * spec.atomicCounterCount * spec.callCount << "];\n";
if ((spec.operations & OPERATION_INC) != 0)
src << " uint increment[" << spec.threadCount * spec.atomicCounterCount * spec.callCount << "];\n";
if ((spec.operations & OPERATION_DEC) != 0)
src << " uint decrement[" << spec.threadCount * spec.atomicCounterCount * spec.callCount << "];\n";
if ((spec.operations & OPERATION_GET) != 0 && spec.operations != OPERATION_GET)
src << " uint postGet[" << spec.threadCount * spec.atomicCounterCount * spec.callCount << "];\n";
if (spec.operations == OPERATION_GET)
src << " uint get[" << spec.threadCount * spec.atomicCounterCount * spec.callCount << "];\n";
src << "} sb_in;\n\n";
for (int counterNdx = 0; counterNdx < spec.atomicCounterCount; counterNdx++)
{
bool layoutStarted = false;
if (spec.offsetType == OFFSETTYPE_RESET_DEFAULT && counterNdx == spec.atomicCounterCount/2)
src << "layout(binding=0, offset=0) uniform atomic_uint;\n";
switch (spec.bindingType)
{
case BINDINGTYPE_BASIC:
layoutStarted = true;
src << "layout(binding=0";
break;
case BINDINGTYPE_INVALID:
layoutStarted = true;
src << "layout(binding=10000";
break;
case BINDINGTYPE_INVALID_DEFAULT:
// Nothing
break;
default:
DE_ASSERT(false);
}
switch (spec.offsetType)
{
case OFFSETTYPE_NONE:
if (layoutStarted)
src << ") ";
src << "uniform atomic_uint counter" << counterNdx << ";\n";
break;
case OFFSETTYPE_BASIC:
if (!layoutStarted)
src << "layout(";
else
src << ", ";
src << "offset=" << (counterNdx * 4) << ") uniform atomic_uint counter" << counterNdx << ";\n";
break;
case OFFSETTYPE_INVALID_DEFAULT:
if (layoutStarted)
src << ") ";
src << "uniform atomic_uint counter" << counterNdx << ";\n";
break;
case OFFSETTYPE_INVALID:
if (!layoutStarted)
src << "layout(";
else
src << ", ";
src << "offset=" << (1 + counterNdx * 2) << ") uniform atomic_uint counter" << counterNdx << ";\n";
break;
case OFFSETTYPE_INVALID_OVERLAPPING:
if (!layoutStarted)
src << "layout(";
else
src << ", ";
src << "offset=0) uniform atomic_uint counter" << counterNdx << ";\n";
break;
case OFFSETTYPE_REVERSE:
if (!layoutStarted)
src << "layout(";
else
src << ", ";
src << "offset=" << (spec.atomicCounterCount - counterNdx - 1) * 4 << ") uniform atomic_uint counter" << (spec.atomicCounterCount - counterNdx - 1) << ";\n";
break;
case OFFSETTYPE_FIRST_AUTO:
DE_ASSERT(spec.atomicCounterCount > 2);
if (counterNdx + 1 == spec.atomicCounterCount)
{
if (!layoutStarted)
src << "layout(";
else
src << ", ";
src << "offset=0) uniform atomic_uint counter0;\n";
}
else if (counterNdx == 0)
{
if (!layoutStarted)
src << "layout(";
else
src << ", ";
src << "offset=4) uniform atomic_uint counter1;\n";
}
else
{
if (layoutStarted)
src << ") ";
src << "uniform atomic_uint counter" << (counterNdx + 1) << ";\n";
}
break;
case OFFSETTYPE_DEFAULT_AUTO:
if (counterNdx + 1 == spec.atomicCounterCount)
{
if (!layoutStarted)
src << "layout(";
else
src << ", ";
src << "offset=0) uniform atomic_uint counter0;\n";
}
else
{
if (layoutStarted)
src << ") ";
src << "uniform atomic_uint counter" << (counterNdx + 1) << ";\n";
}
break;
case OFFSETTYPE_RESET_DEFAULT:
if (layoutStarted)
src << ") ";
if (counterNdx < spec.atomicCounterCount/2)
src << "uniform atomic_uint counter" << (counterNdx + spec.atomicCounterCount/2) << ";\n";
else
src << "uniform atomic_uint counter" << (counterNdx - spec.atomicCounterCount/2) << ";\n";
break;
default:
DE_ASSERT(false);
}
}
src
<< "\n"
<< "void main (void)\n"
<< "{\n";
if (spec.callCount > 1)
src << "\tfor (uint i = 0u; i < " << spec.callCount << "u; i++)\n";
src
<< "\t{\n"
<< "\t\tuint id = (gl_GlobalInvocationID.x";
if (spec.callCount > 1)
src << " * "<< spec.callCount << "u";
if (spec.callCount > 1)
src << " + i)";
else
src << ")";
if (spec.atomicCounterCount > 1)
src << " * " << spec.atomicCounterCount << "u";
src << ";\n";
for (int counterNdx = 0; counterNdx < spec.atomicCounterCount; counterNdx++)
{
if ((spec.operations & OPERATION_GET) != 0 && spec.operations != OPERATION_GET)
src << "\t\tsb_in.preGet[id + " << counterNdx << "u] = atomicCounter(counter" << counterNdx << ");\n";
if (spec.useBranches && ((spec.operations & (OPERATION_INC|OPERATION_DEC)) == (OPERATION_INC|OPERATION_DEC)))
{
src
<< "\t\tif (((gl_GlobalInvocationID.x" << (spec.callCount > 1 ? " + i" : "") << ") % 2u) == 0u)\n"
<< "\t\t{\n"
<< "\t\t\tsb_in.increment[id + " << counterNdx << "u] = atomicCounterIncrement(counter" << counterNdx << ");\n"
<< "\t\t\tsb_in.decrement[id + " << counterNdx << "u] = uint(-1);\n"
<< "\t\t}\n"
<< "\t\telse\n"
<< "\t\t{\n"
<< "\t\t\tsb_in.decrement[id + " << counterNdx << "u] = atomicCounterDecrement(counter" << counterNdx << ") + 1u;\n"
<< "\t\t\tsb_in.increment[id + " << counterNdx << "u] = uint(-1);\n"
<< "\t\t}\n";
}
else
{
if ((spec.operations & OPERATION_INC) != 0)
{
if (spec.useBranches)
{
src
<< "\t\tif (((gl_GlobalInvocationID.x" << (spec.callCount > 1 ? " + i" : "") << ") % 2u) == 0u)\n"
<< "\t\t{\n"
<< "\t\t\tsb_in.increment[id + " << counterNdx << "u] = atomicCounterIncrement(counter" << counterNdx << ");\n"
<< "\t\t}\n"
<< "\t\telse\n"
<< "\t\t{\n"
<< "\t\t\tsb_in.increment[id + " << counterNdx << "u] = uint(-1);\n"
<< "\t\t}\n";
}
else
src << "\t\tsb_in.increment[id + " << counterNdx << "u] = atomicCounterIncrement(counter" << counterNdx << ");\n";
}
if ((spec.operations & OPERATION_DEC) != 0)
{
if (spec.useBranches)
{
src
<< "\t\tif (((gl_GlobalInvocationID.x" << (spec.callCount > 1 ? " + i" : "") << ") % 2u) == 0u)\n"
<< "\t\t{\n"
<< "\t\t\tsb_in.decrement[id + " << counterNdx << "u] = atomicCounterDecrement(counter" << counterNdx << ") + 1u;\n"
<< "\t\t}\n"
<< "\t\telse\n"
<< "\t\t{\n"
<< "\t\t\tsb_in.decrement[id + " << counterNdx << "u] = uint(-1);\n"
<< "\t\t}\n";
}
else
src << "\t\tsb_in.decrement[id + " << counterNdx << "u] = atomicCounterDecrement(counter" << counterNdx << ") + 1u;\n";
}
}
if ((spec.operations & OPERATION_GET) != 0 && spec.operations != OPERATION_GET)
src << "\t\tsb_in.postGet[id + " << counterNdx << "u] = atomicCounter(counter" << counterNdx << ");\n";
if ((spec.operations == OPERATION_GET) != 0)
{
if (spec.useBranches)
{
src
<< "\t\tif (((gl_GlobalInvocationID.x" << (spec.callCount > 1 ? " + i" : "") << ") % 2u) == 0u)\n"
<< "\t\t{\n"
<< "\t\t\tsb_in.get[id + " << counterNdx << "u] = atomicCounter(counter" << counterNdx << ");\n"
<< "\t\t}\n"
<< "\t\telse\n"
<< "\t\t{\n"
<< "\t\t\tsb_in.get[id + " << counterNdx << "u] = uint(-1);\n"
<< "\t\t}\n";
}
else
src << "\t\tsb_in.get[id + " << counterNdx << "u] = atomicCounter(counter" << counterNdx << ");\n";
}
}
src
<< "\t}\n"
<< "}\n";
return src.str();
}
bool AtomicCounterTest::checkAndLogCounterValues (TestLog& log, const vector<deUint32>& counters) const
{
tcu::ScopedLogSection counterSection (log, "Counter info", "Show initial value, current value and expected value of each counter.");
bool isOk = true;
// Check that atomic counters have sensible results
for (int counterNdx = 0; counterNdx < (int)counters.size(); counterNdx++)
{
const deUint32 value = counters[counterNdx];
const deUint32 initialValue = getInitialValue();
deUint32 expectedValue = (deUint32)-1;
if ((m_spec.operations & OPERATION_INC) != 0 && (m_spec.operations & OPERATION_DEC) == 0)
expectedValue = initialValue + (m_spec.useBranches ? m_spec.threadCount*m_spec.callCount - m_spec.threadCount*m_spec.callCount/2 : m_spec.threadCount*m_spec.callCount);
if ((m_spec.operations & OPERATION_INC) == 0 && (m_spec.operations & OPERATION_DEC) != 0)
expectedValue = initialValue - (m_spec.useBranches ? m_spec.threadCount*m_spec.callCount - m_spec.threadCount*m_spec.callCount/2 : m_spec.threadCount*m_spec.callCount);
if ((m_spec.operations & OPERATION_INC) != 0 && (m_spec.operations & OPERATION_DEC) != 0)
expectedValue = initialValue + (m_spec.useBranches ? m_spec.threadCount*m_spec.callCount - m_spec.threadCount*m_spec.callCount/2 : 0) - (m_spec.useBranches ? m_spec.threadCount*m_spec.callCount/2 : 0);
if ((m_spec.operations & OPERATION_INC) == 0 && (m_spec.operations & OPERATION_DEC) == 0)
expectedValue = initialValue;
log << TestLog::Message << "atomic_uint counter" << counterNdx << " initial value: " << initialValue << ", value: " << value << ", expected: " << expectedValue << (value == expectedValue ? "" : ", failed!") << TestLog::EndMessage;
if (value != expectedValue)
isOk = false;
}
return isOk;
}
void AtomicCounterTest::splitBuffer (const vector<deUint32>& buffer, vector<deUint32>& increments, vector<deUint32>& decrements, vector<deUint32>& preGets, vector<deUint32>& postGets, vector<deUint32>& gets) const
{
const int bufferValueCount = m_spec.callCount * m_spec.threadCount * m_spec.atomicCounterCount;
int firstPreGet = -1;
int firstPostGet = -1;
int firstGet = -1;
int firstInc = -1;
int firstDec = -1;
increments.clear();
decrements.clear();
preGets.clear();
postGets.clear();
gets.clear();
if (m_spec.operations == OPERATION_GET)
firstGet = 0;
else if (m_spec.operations == OPERATION_INC)
firstInc = 0;
else if (m_spec.operations == OPERATION_DEC)
firstDec = 0;
else if (m_spec.operations == (OPERATION_GET|OPERATION_INC))
{
firstPreGet = 0;
firstInc = bufferValueCount;
firstPostGet = bufferValueCount * 2;
}
else if (m_spec.operations == (OPERATION_GET|OPERATION_DEC))
{
firstPreGet = 0;
firstDec = bufferValueCount;
firstPostGet = bufferValueCount * 2;
}
else if (m_spec.operations == (OPERATION_GET|OPERATION_DEC|OPERATION_INC))
{
firstPreGet = 0;
firstInc = bufferValueCount;
firstDec = bufferValueCount * 2;
firstPostGet = bufferValueCount * 3;
}
else if (m_spec.operations == (OPERATION_DEC|OPERATION_INC))
{
firstInc = 0;
firstDec = bufferValueCount;
}
else
DE_ASSERT(false);
for (int threadNdx = 0; threadNdx < m_spec.threadCount; threadNdx++)
{
for (int callNdx = 0; callNdx < m_spec.callCount; callNdx++)
{
for (int counterNdx = 0; counterNdx < m_spec.atomicCounterCount; counterNdx++)
{
const int id = ((threadNdx * m_spec.callCount) + callNdx) * m_spec.atomicCounterCount + counterNdx;
if (firstInc != -1)
increments.push_back(buffer[firstInc + id]);
if (firstDec != -1)
decrements.push_back(buffer[firstDec + id]);
if (firstPreGet != -1)
preGets.push_back(buffer[firstPreGet + id]);
if (firstPostGet != -1)
postGets.push_back(buffer[firstPostGet + id]);
if (firstGet != -1)
gets.push_back(buffer[firstGet + id]);
}
}
}
}
void AtomicCounterTest::getCountersValues (vector<deUint32>& counterValues, const vector<deUint32>& values, int ndx, int counterCount)
{
counterValues.resize(values.size()/counterCount, 0);
DE_ASSERT(values.size() % counterCount == 0);
for (int valueNdx = 0; valueNdx < (int)counterValues.size(); valueNdx++)
counterValues[valueNdx] = values[valueNdx * counterCount + ndx];
}
bool AtomicCounterTest::checkRange (TestLog& log, const vector<deUint32>& values, const vector<deUint32>& min, const vector<deUint32>& max)
{
int failedCount = 0;
DE_ASSERT(values.size() == min.size());
DE_ASSERT(values.size() == max.size());
for (int valueNdx = 0; valueNdx < (int)values.size(); valueNdx++)
{
if (values[valueNdx] != (deUint32)-1)
{
if (!deInRange32(values[valueNdx], min[valueNdx], max[valueNdx]))
{
if (failedCount < 20)
log << TestLog::Message << "Value " << values[valueNdx] << " not in range [" << min[valueNdx] << ", " << max[valueNdx] << "]." << TestLog::EndMessage;
failedCount++;
}
}
}
if (failedCount > 20)
log << TestLog::Message << "Number of values not in range: " << failedCount << ", displaying first 20 values." << TestLog::EndMessage;
return failedCount == 0;
}
bool AtomicCounterTest::checkUniquenessAndLinearity (TestLog& log, const vector<deUint32>& values)
{
vector<deUint32> counts;
int failedCount = 0;
deUint32 minValue = (deUint32)-1;
deUint32 maxValue = 0;
DE_ASSERT(!values.empty());
for (int valueNdx = 0; valueNdx < (int)values.size(); valueNdx++)
{
if (values[valueNdx] != (deUint32)-1)
{
minValue = std::min(minValue, values[valueNdx]);
maxValue = std::max(maxValue, values[valueNdx]);
}
}
counts.resize(maxValue - minValue + 1, 0);
for (int valueNdx = 0; valueNdx < (int)values.size(); valueNdx++)
{
if (values[valueNdx] != (deUint32)-1)
counts[values[valueNdx] - minValue]++;
}
for (int countNdx = 0; countNdx < (int)counts.size(); countNdx++)
{
if (counts[countNdx] != 1)
{
if (failedCount < 20)
log << TestLog::Message << "Value " << (minValue + countNdx) << " is not unique. Returned " << counts[countNdx] << " times." << TestLog::EndMessage;
failedCount++;
}
}
if (failedCount > 20)
log << TestLog::Message << "Number of values not unique: " << failedCount << ", displaying first 20 values." << TestLog::EndMessage;
return failedCount == 0;
}
bool AtomicCounterTest::checkPath (const vector<deUint32>& increments, const vector<deUint32>& decrements, int initialValue, const TestSpec& spec)
{
const deUint32 lastValue = initialValue + (spec.useBranches ? spec.threadCount*spec.callCount - spec.threadCount*spec.callCount/2 : 0) - (spec.useBranches ? spec.threadCount*spec.callCount/2 : 0);
bool isOk = true;
vector<deUint32> incrementCounts;
vector<deUint32> decrementCounts;
deUint32 minValue = 0xFFFFFFFFu;
deUint32 maxValue = 0;
for (int valueNdx = 0; valueNdx < (int)increments.size(); valueNdx++)
{
if (increments[valueNdx] != (deUint32)-1)
{
minValue = std::min(minValue, increments[valueNdx]);
maxValue = std::max(maxValue, increments[valueNdx]);
}
}
for (int valueNdx = 0; valueNdx < (int)decrements.size(); valueNdx++)
{
if (decrements[valueNdx] != (deUint32)-1)
{
minValue = std::min(minValue, decrements[valueNdx]);
maxValue = std::max(maxValue, decrements[valueNdx]);
}
}
minValue = std::min(minValue, (deUint32)initialValue);
maxValue = std::max(maxValue, (deUint32)initialValue);
incrementCounts.resize(maxValue - minValue + 1, 0);
decrementCounts.resize(maxValue - minValue + 1, 0);
for (int valueNdx = 0; valueNdx < (int)increments.size(); valueNdx++)
{
if (increments[valueNdx] != (deUint32)-1)
incrementCounts[increments[valueNdx] - minValue]++;
}
for (int valueNdx = 0; valueNdx < (int)decrements.size(); valueNdx++)
{
if (decrements[valueNdx] != (deUint32)-1)
decrementCounts[decrements[valueNdx] - minValue]++;
}
int pos = initialValue - minValue;
while (incrementCounts[pos] + decrementCounts[pos] != 0)
{
if (incrementCounts[pos] > 0 && pos >= (int)(lastValue - minValue))
{
// If can increment and incrementation would move us away from result value, increment
incrementCounts[pos]--;
pos++;
}
else if (decrementCounts[pos] > 0)
{
// If can, decrement
decrementCounts[pos]--;
pos--;
}
else if (incrementCounts[pos] > 0)
{
// If increment moves closer to result value and can't decrement, increment
incrementCounts[pos]--;
pos++;
}
else
DE_ASSERT(false);
if (pos < 0 || pos >= (int)incrementCounts.size())
break;
}
if (minValue + pos != lastValue)
isOk = false;
for (int valueNdx = 0; valueNdx < (int)incrementCounts.size(); valueNdx++)
{
if (incrementCounts[valueNdx] != 0)
isOk = false;
}
for (int valueNdx = 0; valueNdx < (int)decrementCounts.size(); valueNdx++)
{
if (decrementCounts[valueNdx] != 0)
isOk = false;
}
return isOk;
}
bool AtomicCounterTest::checkAndLogCallValues (TestLog& log, const vector<deUint32>& increments, const vector<deUint32>& decrements, const vector<deUint32>& preGets, const vector<deUint32>& postGets, const vector<deUint32>& gets) const
{
bool isOk = true;
for (int counterNdx = 0; counterNdx < m_spec.atomicCounterCount; counterNdx++)
{
vector<deUint32> counterIncrements;
vector<deUint32> counterDecrements;
vector<deUint32> counterPreGets;
vector<deUint32> counterPostGets;
vector<deUint32> counterGets;
getCountersValues(counterIncrements, increments, counterNdx, m_spec.atomicCounterCount);
getCountersValues(counterDecrements, decrements, counterNdx, m_spec.atomicCounterCount);
getCountersValues(counterPreGets, preGets, counterNdx, m_spec.atomicCounterCount);
getCountersValues(counterPostGets, postGets, counterNdx, m_spec.atomicCounterCount);
getCountersValues(counterGets, gets, counterNdx, m_spec.atomicCounterCount);
if (m_spec.operations == OPERATION_GET)
{
tcu::ScopedLogSection valueCheck(log, ("counter" + de::toString(counterNdx) + " value check").c_str(), ("Check that counter" + de::toString(counterNdx) + " values haven't changed.").c_str());
int changedValues = 0;
for (int valueNdx = 0; valueNdx < (int)gets.size(); valueNdx++)
{
if ((!m_spec.useBranches || gets[valueNdx] != (deUint32)-1) && gets[valueNdx] != getInitialValue())
{
if (changedValues < 20)
log << TestLog::Message << "atomicCounter(counter" << counterNdx << ") returned " << gets[valueNdx] << " expected " << getInitialValue() << TestLog::EndMessage;
isOk = false;
changedValues++;
}
}
if (changedValues == 0)
log << TestLog::Message << "All values returned by atomicCounter(counter" << counterNdx << ") match initial value " << getInitialValue() << "." << TestLog::EndMessage;
else if (changedValues > 20)
log << TestLog::Message << "Total number of invalid values returned by atomicCounter(counter" << counterNdx << ") " << changedValues << " displaying first 20 values." << TestLog::EndMessage;
}
else if ((m_spec.operations & (OPERATION_INC|OPERATION_DEC)) == (OPERATION_INC|OPERATION_DEC))
{
tcu::ScopedLogSection valueCheck(log, ("counter" + de::toString(counterNdx) + " path check").c_str(), ("Check that there is order in which counter" + de::toString(counterNdx) + " increments and decrements could have happened.").c_str());
if (!checkPath(counterIncrements, counterDecrements, getInitialValue(), m_spec))
{
isOk = false;
log << TestLog::Message << "No possible order of calls to atomicCounterIncrement(counter" << counterNdx << ") and atomicCounterDecrement(counter" << counterNdx << ") found." << TestLog::EndMessage;
}
else
log << TestLog::Message << "Found possible order of calls to atomicCounterIncrement(counter" << counterNdx << ") and atomicCounterDecrement(counter" << counterNdx << ")." << TestLog::EndMessage;
}
else if ((m_spec.operations & OPERATION_INC) != 0)
{
{
tcu::ScopedLogSection uniquenesCheck(log, ("counter" + de::toString(counterNdx) + " check uniqueness and linearity").c_str(), ("Check that counter" + de::toString(counterNdx) + " returned only unique and linear values.").c_str());
if (!checkUniquenessAndLinearity(log, counterIncrements))
{
isOk = false;
log << TestLog::Message << "atomicCounterIncrement(counter" << counterNdx << ") returned non unique values." << TestLog::EndMessage;
}
else
log << TestLog::Message << "atomicCounterIncrement(counter" << counterNdx << ") returned only unique values." << TestLog::EndMessage;
}
if (isOk && ((m_spec.operations & OPERATION_GET) != 0))
{
tcu::ScopedLogSection uniquenesCheck(log, ("counter" + de::toString(counterNdx) + " check range").c_str(), ("Check that counter" + de::toString(counterNdx) + " returned only values values between previous and next atomicCounter(counter" + de::toString(counterNdx) + ").").c_str());
if (!checkRange(log, counterIncrements, counterPreGets, counterPostGets))
{
isOk = false;
log << TestLog::Message << "atomicCounterIncrement(counter" << counterNdx << ") returned value that is not between previous and next call to atomicCounter(counter" << counterNdx << ")." << TestLog::EndMessage;
}
else
log << TestLog::Message << "atomicCounterIncrement(counter" << counterNdx << ") returned only values between previous and next call to atomicCounter(counter" << counterNdx << ")." << TestLog::EndMessage;
}
}
else if ((m_spec.operations & OPERATION_DEC) != 0)
{
{
tcu::ScopedLogSection uniquenesCheck(log, ("counter" + de::toString(counterNdx) + " check uniqueness and linearity").c_str(), ("Check that counter" + de::toString(counterNdx) + " returned only unique and linear values.").c_str());
if (!checkUniquenessAndLinearity(log, counterDecrements))
{
isOk = false;
log << TestLog::Message << "atomicCounterDecrement(counter" << counterNdx << ") returned non unique values." << TestLog::EndMessage;
}
else
log << TestLog::Message << "atomicCounterDecrement(counter" << counterNdx << ") returned only unique values." << TestLog::EndMessage;
}
if (isOk && ((m_spec.operations & OPERATION_GET) != 0))
{
tcu::ScopedLogSection uniquenesCheck(log, ("counter" + de::toString(counterNdx) + " check range").c_str(), ("Check that counter" + de::toString(counterNdx) + " returned only values values between previous and next atomicCounter(counter" + de::toString(counterNdx) + ".").c_str());
if (!checkRange(log, counterDecrements, counterPostGets, counterPreGets))
{
isOk = false;
log << TestLog::Message << "atomicCounterDecrement(counter" << counterNdx << ") returned value that is not between previous and next call to atomicCounter(counter" << counterNdx << ")." << TestLog::EndMessage;
}
else
log << TestLog::Message << "atomicCounterDecrement(counter" << counterNdx << ") returned only values between previous and next call to atomicCounter(counter" << counterNdx << ")." << TestLog::EndMessage;
}
}
}
return isOk;
}
TestCase::IterateResult AtomicCounterTest::iterate (void)
{
const glw::Functions& gl = m_context.getRenderContext().getFunctions();
TestLog& log = m_testCtx.getLog();
const glu::Buffer counterBuffer (m_context.getRenderContext());
const glu::Buffer outputBuffer (m_context.getRenderContext());
const glu::ShaderProgram program (m_context.getRenderContext(), glu::ProgramSources() << glu::ShaderSource(glu::SHADERTYPE_COMPUTE, generateShaderSource(m_spec)));
const deInt32 counterBufferSize = m_spec.atomicCounterCount * 4;
const deInt32 ssoSize = m_spec.atomicCounterCount * m_spec.callCount * m_spec.threadCount * 4 * getOperationCount();
log << program;
if (m_spec.offsetType == OFFSETTYPE_INVALID || m_spec.offsetType == OFFSETTYPE_INVALID_DEFAULT || m_spec.bindingType == BINDINGTYPE_INVALID || m_spec.bindingType == BINDINGTYPE_INVALID_DEFAULT || m_spec.offsetType == OFFSETTYPE_INVALID_OVERLAPPING)
{
if (program.isOk())
{
log << TestLog::Message << "Expected program to fail, but compilation passed." << TestLog::EndMessage;
m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Compile succeeded");
return STOP;
}
else
{
log << TestLog::Message << "Compilation failed as expected." << TestLog::EndMessage;
m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Compile failed");
return STOP;
}
}
else if (!program.isOk())
{
log << TestLog::Message << "Compile failed." << TestLog::EndMessage;
m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Compile failed");
return STOP;
}
gl.useProgram(program.getProgram());
GLU_EXPECT_NO_ERROR(gl.getError(), "glUseProgram()");
// Create output buffer
gl.bindBuffer(GL_SHADER_STORAGE_BUFFER, *outputBuffer);
gl.bufferData(GL_SHADER_STORAGE_BUFFER, ssoSize, NULL, GL_STATIC_DRAW);
GLU_EXPECT_NO_ERROR(gl.getError(), "Failed to create output buffer");
// Create atomic counter buffer
{
vector<deUint32> data(m_spec.atomicCounterCount, getInitialValue());
gl.bindBuffer(GL_SHADER_STORAGE_BUFFER, *counterBuffer);
gl.bufferData(GL_SHADER_STORAGE_BUFFER, counterBufferSize, &(data[0]), GL_STATIC_DRAW);
GLU_EXPECT_NO_ERROR(gl.getError(), "Failed to create buffer for atomic counters");
}
// Bind output buffer
gl.bindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, *outputBuffer);
GLU_EXPECT_NO_ERROR(gl.getError(), "Failed to setup output buffer");
// Bind atomic counter buffer
gl.bindBufferBase(GL_ATOMIC_COUNTER_BUFFER, 0, *counterBuffer);
GLU_EXPECT_NO_ERROR(gl.getError(), "Failed to setup atomic counter buffer");
// Dispath compute
gl.dispatchCompute(m_spec.threadCount, 1, 1);
GLU_EXPECT_NO_ERROR(gl.getError(), "glDispatchCompute()");
gl.finish();
GLU_EXPECT_NO_ERROR(gl.getError(), "glFinish()");
vector<deUint32> output(ssoSize/4, 0);
vector<deUint32> counters(m_spec.atomicCounterCount, 0);
// Read back output buffer
{
gl.bindBuffer(GL_SHADER_STORAGE_BUFFER, *outputBuffer);
GLU_EXPECT_NO_ERROR(gl.getError(), "glBindBuffer()");
void* ptr = gl.mapBufferRange(GL_SHADER_STORAGE_BUFFER, 0, (GLsizeiptr)(output.size() * sizeof(deUint32)), GL_MAP_READ_BIT);
GLU_EXPECT_NO_ERROR(gl.getError(), "glMapBufferRange()");
deMemcpy(&(output[0]), ptr, (int)output.size() * sizeof(deUint32));
if (!gl.unmapBuffer(GL_SHADER_STORAGE_BUFFER))
{
GLU_EXPECT_NO_ERROR(gl.getError(), "glUnmapBuffer()");
TCU_CHECK_MSG(false, "Mapped buffer corrupted");
}
gl.bindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
GLU_EXPECT_NO_ERROR(gl.getError(), "glBindBuffer()");
}
// Read back counter buffer
{
gl.bindBuffer(GL_SHADER_STORAGE_BUFFER, *counterBuffer);
GLU_EXPECT_NO_ERROR(gl.getError(), "glBindBuffer()");
void* ptr = gl.mapBufferRange(GL_SHADER_STORAGE_BUFFER, 0, (GLsizeiptr)(counters.size() * sizeof(deUint32)), GL_MAP_READ_BIT);
GLU_EXPECT_NO_ERROR(gl.getError(), "glMapBufferRange()");
deMemcpy(&(counters[0]), ptr, (int)counters.size() * sizeof(deUint32));
if (!gl.unmapBuffer(GL_SHADER_STORAGE_BUFFER))
{
GLU_EXPECT_NO_ERROR(gl.getError(), "glUnmapBuffer()");
TCU_CHECK_MSG(false, "Mapped buffer corrupted");
}
gl.bindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
GLU_EXPECT_NO_ERROR(gl.getError(), "glBindBuffer()");
}
bool isOk = true;
if (!checkAndLogCounterValues(log, counters))
isOk = false;
{
vector<deUint32> increments;
vector<deUint32> decrements;
vector<deUint32> preGets;
vector<deUint32> postGets;
vector<deUint32> gets;
splitBuffer(output, increments, decrements, preGets, postGets, gets);
if (!checkAndLogCallValues(log, increments, decrements, preGets, postGets, gets))
isOk = false;
}
if (isOk)
m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass");
else
m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Fail");
return STOP;
}
string specToTestName (const AtomicCounterTest::TestSpec& spec)
{
std::ostringstream stream;
stream << spec.atomicCounterCount << (spec.atomicCounterCount == 1 ? "_counter" : "_counters");
stream << "_" << spec.callCount << (spec.callCount == 1 ? "_call" : "_calls");
stream << "_" << spec.threadCount << (spec.threadCount == 1 ? "_thread" : "_threads");
return stream.str();
}
string specToTestDescription (const AtomicCounterTest::TestSpec& spec)
{
std::ostringstream stream;
bool firstOperation = 0;
stream
<< "Test ";
if ((spec.operations & AtomicCounterTest::OPERATION_GET) != 0)
{
stream << "atomicCounter()";
firstOperation = false;
}
if ((spec.operations & AtomicCounterTest::OPERATION_INC) != 0)
{
if (!firstOperation)
stream << ", ";
stream << " atomicCounterIncrement()";
firstOperation = false;
}
if ((spec.operations & AtomicCounterTest::OPERATION_DEC) != 0)
{
if (!firstOperation)
stream << ", ";
stream << " atomicCounterDecrement()";
firstOperation = false;
}
stream << " calls with ";
if (spec.useBranches)
stream << " branches, ";
stream << spec.atomicCounterCount << " atomic counters, " << spec.callCount << " calls and " << spec.threadCount << " threads.";
return stream.str();
}
string operationToName (const AtomicCounterTest::Operation& operations, bool useBranch)
{
std::ostringstream stream;
bool first = true;
if ((operations & AtomicCounterTest::OPERATION_GET) != 0)
{
stream << "get";
first = false;
}
if ((operations & AtomicCounterTest::OPERATION_INC) != 0)
{
if (!first)
stream << "_";
stream << "inc";
first = false;
}
if ((operations & AtomicCounterTest::OPERATION_DEC) != 0)
{
if (!first)
stream << "_";
stream << "dec";
first = false;
}
if (useBranch)
stream << "_branch";
return stream.str();
}
string operationToDescription (const AtomicCounterTest::Operation& operations, bool useBranch)
{
std::ostringstream stream;
bool firstOperation = 0;
stream
<< "Test ";
if ((operations & AtomicCounterTest::OPERATION_GET) != 0)
{
stream << "atomicCounter()";
firstOperation = false;
}
if ((operations & AtomicCounterTest::OPERATION_INC) != 0)
{
if (!firstOperation)
stream << ", ";
stream << " atomicCounterIncrement()";
firstOperation = false;
}
if ((operations & AtomicCounterTest::OPERATION_DEC) != 0)
{
if (!firstOperation)
stream << ", ";
stream << " atomicCounterDecrement()";
firstOperation = false;
}
if (useBranch)
stream << " calls with branches.";
else
stream << ".";
return stream.str();
}
string layoutTypesToName (const AtomicCounterTest::BindingType& bindingType, const AtomicCounterTest::OffsetType& offsetType)
{
std::ostringstream stream;
switch (bindingType)
{
case AtomicCounterTest::BINDINGTYPE_BASIC:
// Nothing
break;
case AtomicCounterTest::BINDINGTYPE_INVALID:
stream << "invalid_binding";
break;
default:
DE_ASSERT(false);
}
if (bindingType != AtomicCounterTest::BINDINGTYPE_BASIC && offsetType != AtomicCounterTest::OFFSETTYPE_NONE)
stream << "_";
switch (offsetType)
{
case AtomicCounterTest::OFFSETTYPE_BASIC:
stream << "basic_offset";
break;
case AtomicCounterTest::OFFSETTYPE_REVERSE:
stream << "reverse_offset";
break;
case AtomicCounterTest::OFFSETTYPE_INVALID:
stream << "invalid_offset";
break;
case AtomicCounterTest::OFFSETTYPE_FIRST_AUTO:
stream << "first_offset_set";
break;
case AtomicCounterTest::OFFSETTYPE_DEFAULT_AUTO:
stream << "default_offset_set";
break;
case AtomicCounterTest::OFFSETTYPE_RESET_DEFAULT:
stream << "reset_default_offset";
break;
case AtomicCounterTest::OFFSETTYPE_NONE:
// Do nothing
break;
default:
DE_ASSERT(false);
}
return stream.str();
}
string layoutTypesToDesc (const AtomicCounterTest::BindingType& bindingType, const AtomicCounterTest::OffsetType& offsetType)
{
std::ostringstream stream;
switch (bindingType)
{
case AtomicCounterTest::BINDINGTYPE_BASIC:
stream << "Test using atomic counters with explicit layout bindings and";
break;
case AtomicCounterTest::BINDINGTYPE_INVALID:
stream << "Test using atomic counters with invalid explicit layout bindings and";
break;
case AtomicCounterTest::BINDINGTYPE_INVALID_DEFAULT:
stream << "Test using atomic counters with invalid default layout binding and";
break;
default:
DE_ASSERT(false);
}
switch (offsetType)
{
case AtomicCounterTest::OFFSETTYPE_NONE:
stream << " no explicit offsets.";
break;
case AtomicCounterTest::OFFSETTYPE_BASIC:
stream << "explicit continuos offsets.";
break;
case AtomicCounterTest::OFFSETTYPE_REVERSE:
stream << "reversed explicit offsets.";
break;
case AtomicCounterTest::OFFSETTYPE_INVALID:
stream << "invalid explicit offsets.";
break;
case AtomicCounterTest::OFFSETTYPE_FIRST_AUTO:
stream << "only first counter with explicit offset.";
break;
case AtomicCounterTest::OFFSETTYPE_DEFAULT_AUTO:
stream << "default offset.";
break;
case AtomicCounterTest::OFFSETTYPE_RESET_DEFAULT:
stream << "default offset specified twice.";
break;
default:
DE_ASSERT(false);
}
return stream.str();
}
} // Anonymous
AtomicCounterTests::AtomicCounterTests (Context& context)
: TestCaseGroup(context, "atomic_counter", "Atomic counter tests")
{
// Runtime use tests
{
const int counterCounts[] =
{
1, 4, 8
};
const int callCounts[] =
{
1, 5, 100
};
const int threadCounts[] =
{
1, 10, 5000
};
const AtomicCounterTest::Operation operations[] =
{
AtomicCounterTest::OPERATION_GET,
AtomicCounterTest::OPERATION_INC,
AtomicCounterTest::OPERATION_DEC,
(AtomicCounterTest::Operation)(AtomicCounterTest::OPERATION_INC|AtomicCounterTest::OPERATION_GET),
(AtomicCounterTest::Operation)(AtomicCounterTest::OPERATION_DEC|AtomicCounterTest::OPERATION_GET),
(AtomicCounterTest::Operation)(AtomicCounterTest::OPERATION_INC|AtomicCounterTest::OPERATION_DEC),
(AtomicCounterTest::Operation)(AtomicCounterTest::OPERATION_INC|AtomicCounterTest::OPERATION_DEC|AtomicCounterTest::OPERATION_GET)
};
for (int operationNdx = 0; operationNdx < DE_LENGTH_OF_ARRAY(operations); operationNdx++)
{
const AtomicCounterTest::Operation operation = operations[operationNdx];
for (int branch = 0; branch < 2; branch++)
{
const bool useBranch = (branch == 1);
TestCaseGroup* operationGroup = new TestCaseGroup(m_context, operationToName(operation, useBranch).c_str(), operationToDescription(operation, useBranch).c_str());
for (int counterCountNdx = 0; counterCountNdx < DE_LENGTH_OF_ARRAY(counterCounts); counterCountNdx++)
{
const int counterCount = counterCounts[counterCountNdx];
for (int callCountNdx = 0; callCountNdx < DE_LENGTH_OF_ARRAY(callCounts); callCountNdx++)
{
const int callCount = callCounts[callCountNdx];
for (int threadCountNdx = 0; threadCountNdx < DE_LENGTH_OF_ARRAY(threadCounts); threadCountNdx++)
{
const int threadCount = threadCounts[threadCountNdx];
if (threadCount * callCount * counterCount > 10000)
continue;
if (useBranch && threadCount * callCount == 1)
continue;
AtomicCounterTest::TestSpec spec;
spec.atomicCounterCount = counterCount;
spec.operations = operation;
spec.callCount = callCount;
spec.useBranches = useBranch;
spec.threadCount = threadCount;
spec.bindingType = AtomicCounterTest::BINDINGTYPE_BASIC;
spec.offsetType = AtomicCounterTest::OFFSETTYPE_NONE;
operationGroup->addChild(new AtomicCounterTest(m_context, specToTestName(spec).c_str(), specToTestDescription(spec).c_str(), spec));
}
}
}
addChild(operationGroup);
}
}
}
{
TestCaseGroup* layoutGroup = new TestCaseGroup(m_context, "layout", "Layout qualifier tests.");
const int counterCounts[] = { 1, 8 };
const int callCounts[] = { 1, 5 };
const int threadCounts[] = { 1, 1000 };
const AtomicCounterTest::Operation operations[] =
{
(AtomicCounterTest::Operation)(AtomicCounterTest::OPERATION_INC|AtomicCounterTest::OPERATION_GET),
(AtomicCounterTest::Operation)(AtomicCounterTest::OPERATION_DEC|AtomicCounterTest::OPERATION_GET),
(AtomicCounterTest::Operation)(AtomicCounterTest::OPERATION_INC|AtomicCounterTest::OPERATION_DEC)
};
const AtomicCounterTest::OffsetType offsetTypes[] =
{
AtomicCounterTest::OFFSETTYPE_REVERSE,
AtomicCounterTest::OFFSETTYPE_FIRST_AUTO,
AtomicCounterTest::OFFSETTYPE_DEFAULT_AUTO,
AtomicCounterTest::OFFSETTYPE_RESET_DEFAULT
};
for (int offsetTypeNdx = 0; offsetTypeNdx < DE_LENGTH_OF_ARRAY(offsetTypes); offsetTypeNdx++)
{
const AtomicCounterTest::OffsetType offsetType = offsetTypes[offsetTypeNdx];
TestCaseGroup* layoutQualifierGroup = new TestCaseGroup(m_context, layoutTypesToName(AtomicCounterTest::BINDINGTYPE_BASIC, offsetType).c_str(), layoutTypesToDesc(AtomicCounterTest::BINDINGTYPE_BASIC, offsetType).c_str());
for (int operationNdx = 0; operationNdx < DE_LENGTH_OF_ARRAY(operations); operationNdx++)
{
const AtomicCounterTest::Operation operation = operations[operationNdx];
TestCaseGroup* operationGroup = new TestCaseGroup(m_context, operationToName(operation, false).c_str(), operationToDescription(operation, false).c_str());
for (int counterCountNdx = 0; counterCountNdx < DE_LENGTH_OF_ARRAY(counterCounts); counterCountNdx++)
{
const int counterCount = counterCounts[counterCountNdx];
if (offsetType == AtomicCounterTest::OFFSETTYPE_FIRST_AUTO && counterCount < 3)
continue;
if (offsetType == AtomicCounterTest::OFFSETTYPE_DEFAULT_AUTO && counterCount < 2)
continue;
if (offsetType == AtomicCounterTest::OFFSETTYPE_RESET_DEFAULT && counterCount < 2)
continue;
if (offsetType == AtomicCounterTest::OFFSETTYPE_REVERSE && counterCount < 2)
continue;
for (int callCountNdx = 0; callCountNdx < DE_LENGTH_OF_ARRAY(callCounts); callCountNdx++)
{
const int callCount = callCounts[callCountNdx];
for (int threadCountNdx = 0; threadCountNdx < DE_LENGTH_OF_ARRAY(threadCounts); threadCountNdx++)
{
const int threadCount = threadCounts[threadCountNdx];
AtomicCounterTest::TestSpec spec;
spec.atomicCounterCount = counterCount;
spec.operations = operation;
spec.callCount = callCount;
spec.useBranches = false;
spec.threadCount = threadCount;
spec.bindingType = AtomicCounterTest::BINDINGTYPE_BASIC;
spec.offsetType = offsetType;
operationGroup->addChild(new AtomicCounterTest(m_context, specToTestName(spec).c_str(), specToTestDescription(spec).c_str(), spec));
}
}
}
layoutQualifierGroup->addChild(operationGroup);
}
layoutGroup->addChild(layoutQualifierGroup);
}
{
TestCaseGroup* invalidGroup = new TestCaseGroup(m_context, "invalid", "Test invalid layouts");
{
AtomicCounterTest::TestSpec spec;
spec.atomicCounterCount = 1;
spec.operations = AtomicCounterTest::OPERATION_INC;
spec.callCount = 1;
spec.useBranches = false;
spec.threadCount = 1;
spec.bindingType = AtomicCounterTest::BINDINGTYPE_INVALID;
spec.offsetType = AtomicCounterTest::OFFSETTYPE_NONE;
invalidGroup->addChild(new AtomicCounterTest(m_context, "invalid_binding", "Test layout qualifiers with invalid binding.", spec));
}
{
AtomicCounterTest::TestSpec spec;
spec.atomicCounterCount = 1;
spec.operations = AtomicCounterTest::OPERATION_INC;
spec.callCount = 1;
spec.useBranches = false;
spec.threadCount = 1;
spec.bindingType = AtomicCounterTest::BINDINGTYPE_INVALID_DEFAULT;
spec.offsetType = AtomicCounterTest::OFFSETTYPE_NONE;
invalidGroup->addChild(new AtomicCounterTest(m_context, "invalid_default_binding", "Test layout qualifiers with invalid default binding.", spec));
}
{
AtomicCounterTest::TestSpec spec;
spec.atomicCounterCount = 1;
spec.operations = AtomicCounterTest::OPERATION_INC;
spec.callCount = 1;
spec.useBranches = false;
spec.threadCount = 1;
spec.bindingType = AtomicCounterTest::BINDINGTYPE_BASIC;
spec.offsetType = AtomicCounterTest::OFFSETTYPE_INVALID;
invalidGroup->addChild(new AtomicCounterTest(m_context, "invalid_offset_align", "Test layout qualifiers with invalid alignment offset.", spec));
}
{
AtomicCounterTest::TestSpec spec;
spec.atomicCounterCount = 2;
spec.operations = AtomicCounterTest::OPERATION_INC;
spec.callCount = 1;
spec.useBranches = false;
spec.threadCount = 1;
spec.bindingType = AtomicCounterTest::BINDINGTYPE_BASIC;
spec.offsetType = AtomicCounterTest::OFFSETTYPE_INVALID_OVERLAPPING;
invalidGroup->addChild(new AtomicCounterTest(m_context, "invalid_offset_overlap", "Test layout qualifiers with invalid overlapping offset.", spec));
}
{
AtomicCounterTest::TestSpec spec;
spec.atomicCounterCount = 1;
spec.operations = AtomicCounterTest::OPERATION_INC;
spec.callCount = 1;
spec.useBranches = false;
spec.threadCount = 1;
spec.bindingType = AtomicCounterTest::BINDINGTYPE_BASIC;
spec.offsetType = AtomicCounterTest::OFFSETTYPE_INVALID_DEFAULT;
invalidGroup->addChild(new AtomicCounterTest(m_context, "invalid_default_offset", "Test layout qualifiers with invalid default offset.", spec));
}
layoutGroup->addChild(invalidGroup);
}
addChild(layoutGroup);
}
}
AtomicCounterTests::~AtomicCounterTests (void)
{
}
void AtomicCounterTests::init (void)
{
}
} // Functional
} // gles31
} // deqp
| 46,926 | 19,058 |
/*
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbImage.h"
#include "otbVectorImage.h"
#include "itkImageRegionIterator.h"
#include "otbCLHistogramEqualizationFilter.h"
int otbHelperCLAHE(int itkNotUsed(argc), char* argv[])
{
typedef int InputPixelType;
const unsigned int Dimension = 2;
typedef otb::Image<InputPixelType, Dimension> InputImageType;
typedef otb::ImageFileReader<InputImageType> ReaderType;
typedef otb::ImageFileWriter<InputImageType> WriterType;
ReaderType::Pointer reader(ReaderType::New());
WriterType::Pointer writer(WriterType::New());
reader->SetFileName(argv[1]);
writer->SetFileName(argv[2]);
reader->UpdateOutputInformation();
typedef otb::VectorImage<int, 2> HistogramType;
typedef otb::VectorImage<double, 2> LutType;
typedef itk::StreamingImageFilter<LutType, LutType> StreamingImageFilter;
typedef otb::InPlacePassFilter<InputImageType> BufferFilter;
typedef otb::ComputeHistoFilter<InputImageType, HistogramType> HistoFilter;
typedef otb::ComputeGainLutFilter<HistogramType, LutType> GainLutFilter;
typedef otb::ApplyGainFilter<InputImageType, LutType, InputImageType> ApplyGainFilter;
HistoFilter::Pointer histoFilter(HistoFilter::New());
GainLutFilter::Pointer lutFilter(GainLutFilter::New());
ApplyGainFilter::Pointer applyFilter(ApplyGainFilter::New());
BufferFilter::Pointer buffer(BufferFilter::New());
StreamingImageFilter::Pointer streamFilter(StreamingImageFilter::New());
InputImageType::SizeType size;
size = reader->GetOutput()->GetLargestPossibleRegion().GetSize();
// histoEqualize->SetThreshold(100);
histoFilter->SetInput(reader->GetOutput());
buffer->SetInput(reader->GetOutput());
lutFilter->SetInput(histoFilter->GetHistoOutput());
streamFilter->SetInput(lutFilter->GetOutput());
applyFilter->SetInputLut(streamFilter->GetOutput());
applyFilter->SetInputImage(buffer->GetOutput());
histoFilter->SetMin(0);
histoFilter->SetMax(255);
lutFilter->SetMin(0);
lutFilter->SetMax(255);
applyFilter->SetMin(0);
applyFilter->SetMax(255);
histoFilter->SetThumbSize(size);
applyFilter->SetThumbSize(size);
lutFilter->SetNbPixel(size[0] * size[1]);
writer->SetInput(applyFilter->GetOutput());
writer->Update();
return EXIT_SUCCESS;
}
| 3,110 | 1,005 |
/*
* sem.cpp
*
* Created on: Apr 21, 2017
* Author: Paul
*/
#include "sem.h"
namespace xv6 {
} /* namespace xv6 */
| 129 | 61 |