text
stringlengths
54
60.6k
<commit_before><commit_msg>zero sigaction structure in debugger<commit_after><|endoftext|>
<commit_before>Int_t AliTPCtest() { Int_t rc=0; //Test TPC simulation gROOT->LoadMacro("$(ALICE_ROOT)/macros/grun.C"); grun(); AliKalmanTrack::SetConvConst(100/0.299792458/0.2/gAlice->Field()->Factor()); Int_t ver=gAlice->GetDetector("TPC")->IsVersion(); delete gAlice; gAlice=0; if ((ver!=1)&&(ver!=2)) { cerr<<"Invalid TPC version: "<<ver<<" ! (must be 1 or 2)\n"; return 12345; } if (ver==2) { gROOT->LoadMacro("$(ALICE_ROOT)/TPC/AliTPCHits2Digits.C"); if (rc=AliTPCHits2Digits()) return rc; // gROOT->LoadMacro("$(ALICE_ROOT)/TPC/AliTPCDisplayDigits.C"); // if (rc=AliTPCDisplayDigits(1,1)) return rc; } //Test TPC reconstruction gROOT->LoadMacro("$(ALICE_ROOT)/TPC/AliTPCFindClusters.C"); if (rc=AliTPCFindClusters()) return rc; // gROOT->LoadMacro("$(ALICE_ROOT)/TPC/AliTPCDisplayClusters.C"); // if (rc=AliTPCDisplayClusters()) return rc; gROOT->LoadMacro("$(ALICE_ROOT)/TPC/AliTPCFindTracks.C"); if (rc=AliTPCFindTracks()) return rc; gROOT->LoadMacro("$(ALICE_ROOT)/TPC/AliTPCComparison.C"); if (rc=AliTPCComparison()) return rc; return rc; } <commit_msg>Changes with the field conversion factor setting<commit_after>Int_t AliTPCtest() { Int_t rc=0; //Test TPC simulation gROOT->LoadMacro("$(ALICE_ROOT)/macros/grun.C"); grun(); AliKalmanTrack::SetConvConst(1000/0.299792458/gAlice->Field()->SolenoidField()); Int_t ver=gAlice->GetDetector("TPC")->IsVersion(); delete gAlice; gAlice=0; if ((ver!=1)&&(ver!=2)) { cerr<<"Invalid TPC version: "<<ver<<" ! (must be 1 or 2)\n"; return 12345; } if (ver==2) { gROOT->LoadMacro("$(ALICE_ROOT)/TPC/AliTPCHits2Digits.C"); if (rc=AliTPCHits2Digits()) return rc; // gROOT->LoadMacro("$(ALICE_ROOT)/TPC/AliTPCDisplayDigits.C"); // if (rc=AliTPCDisplayDigits(1,1)) return rc; } //Test TPC reconstruction gROOT->LoadMacro("$(ALICE_ROOT)/TPC/AliTPCFindClusters.C"); if (rc=AliTPCFindClusters()) return rc; // gROOT->LoadMacro("$(ALICE_ROOT)/TPC/AliTPCDisplayClusters.C"); // if (rc=AliTPCDisplayClusters()) return rc; gROOT->LoadMacro("$(ALICE_ROOT)/TPC/AliTPCFindTracks.C"); if (rc=AliTPCFindTracks()) return rc; gROOT->LoadMacro("$(ALICE_ROOT)/TPC/AliTPCComparison.C"); if (rc=AliTPCComparison()) return rc; return rc; } <|endoftext|>
<commit_before>#include "GameObject.h" #include "Application.h" #include "ModuleRenderer3D.h" #include "ModuleEditor.h" #include "ModuleScene.h" #include "cTransform.h" #include "cMesh.h" #include "cMaterial.h" #include "ResourceMesh.h" #include "cCamera.h" #include "MathGeoLib/MathGeoLib.h" #include "JSON/parson.h" #include "glew/include/glew.h" #include "SDL/include/SDL_opengl.h" #include <gl/GL.h> #include <gl/GLU.h> class cTransform; GameObject::GameObject(std::string _name, bool _active, GameObject * _parent) : name(_name) , active(_active) , parent(_parent) { aabbBox.SetNegativeInfinity(); } void GameObject::PreUpdate() { if (active) { for (auto itSons : sons) { itSons->PreUpdate(); } insideFrustum = false; } } void GameObject::Update() { if (active) { for (auto comp : components) { comp.second->Update(); } //Multiply all the matrixTransform with their sons glPushMatrix(); glMultMatrixf(((cTransform*)FindComponent(TRANSFORM))->GetLocalMatrixTransf().Transposed().ptr()); //Update AABB BOX for Game Objects if (((cTransform*)FindComponent(TRANSFORM))->transformChange) { float4x4 matrix = ((cTransform*)FindComponent(TRANSFORM))->GetGlobalMatrixTransf(); float4x4 matrix1 = ((cTransform*)FindComponent(TRANSFORM))->GetLocalMatrixTransf(); //if has a mesh it is modified if (SonHasMesh()) { UpdateAABB(matrix); } //IF has frustum it is modified if (((cCamera*)FindComponent(CAMERA)) != nullptr) { ((cCamera*)FindComponent(CAMERA))->transformFrustum = true; } ((cTransform*)FindComponent(TRANSFORM))->transformChange = false; } if (!sons.empty()) { for (auto itSons : sons) { itSons->Update(); } } if (App->renderer3D->bEnableWireframe) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); else glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); if(insideFrustum) App->renderer3D->DrawGameObject(this); if (!isInsideQuad && statiC) { //QUADTREE App->scene->quad.AddGameObject(this); isInsideQuad = true; } glPopMatrix(); if (App->isPlaying) { IsPlaying(App->GetGameDt()); } } } void GameObject::IsPlaying(float dt) { } Component * GameObject::FindComponent(componentType type) { Component * ret = nullptr; std::map<componentType, Component*>::iterator it = components.find(type); if (it != components.end()) { return it->second; } return nullptr; } void GameObject::DrawUI() { if (ImGui::CollapsingHeader(name.data())) { for (auto itComp : components) { itComp.second->DrawUI(); } } } void GameObject::UpdateAABB(float4x4 matrix) { for (auto sonsGO : sons) { sonsGO->UpdateAABB(matrix); } if (FindComponent(MESH) != nullptr) { aabbBox.SetNegativeInfinity(); OBB obb = ((cMesh*)FindComponent(MESH))->resource->aabbBox.Transform(matrix); aabbBox.Enclose(obb); } } void GameObject::DrawHeriarchy(GameObject* son) { //static int selection_mask = (1 << 2); // Dumb representation of what may be user-side selection state. You may carry selection state inside or outside your objects in whatever format you see fit. int node_clicked = -1; ImGuiTreeNodeFlags node_flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; //| ImGuiTreeNodeFlags_Selected; bool node_open; if (node_open = ImGui::TreeNodeEx(name.data(), node_flags)) { if (ImGui::IsItemClicked()) { node_clicked = 7; this->clicked = true; if (App->editor->selected != nullptr) { App->editor->selected->clicked = false; } App->editor->selected = this; } if (node_open) { for (auto sonsSons : son->sons) { sonsSons->DrawHeriarchy(sonsSons); } } //if (clicked) //{ // // Update selection state. Process outside of tree loop to avoid visual inconsistencies during the clicking-frame. // if (ImGui::GetIO().KeyCtrl) // selection_mask ^= (1 << node_clicked); // CTRL+click to toggle // else //if (!(selection_mask & (1 << node_clicked))) // Depending on selection behavior you want, this commented bit preserve selection when clicking on item that is part of the selection // selection_mask = (1 << node_clicked); // Click to single-select //} ImGui::TreePop(); } else { if (ImGui::IsItemClicked()) { node_clicked = 7; this->clicked = true; if (App->editor->selected != nullptr) { App->editor->selected->clicked = false; } App->editor->selected = this; } } } void GameObject::DrawProperties() { ImGui::Checkbox("Static", &statiC); ImGui::SameLine(); if (!ImGui::Checkbox("Enable/Disable", &active)) { if (active) { for (auto itComponents : components) { itComponents.second->DrawUI(); } } } } bool GameObject::SonHasMesh() { bool ret = false; if (FindComponent(MESH) != nullptr) { ret = true; } for (auto sonsGO : sons) { ret = sonsGO->SonHasMesh(); if (ret) { break; } } return ret; } void GameObject::AddComponent(Component* addComponent) { components.insert(std::pair<componentType, Component*>(addComponent->type, addComponent)); } void GameObject::Save(JSON_Object *go) const { json_object_set_string(go, "Name", name.data()); json_object_set_boolean(go, "Active", active); JSON_Value* value = json_value_init_array(); JSON_Array* compArray = json_value_get_array(value); for (auto it : components) { //it.second->Save(); } for (auto child : sons) { //child->Save(); } json_object_set_value(go, "Components", value); } void GameObject::Load(const JSON_Object * go) { } uint GameObject::Serialize(char * &buf) { uint length = 0; // Size of the GameObject uint myLength = 0; myLength += sizeof(uint); // Size of Name Length variable myLength += name.length(); // Size of the Name String myLength += sizeof(uint); // Size of Components myLength += sizeof(uint); // Size of Childs length = myLength; char* myself = new char[myLength]; // Actual size of 8 char* it = myself; // Name Length uint size = name.length(); memcpy(it, &size, sizeof(uint)); it += sizeof(uint); // Name memcpy(it, name.data(), name.length()); it += name.length(); // Components Size size = components.size(); memcpy(it, &size, sizeof(uint)); it += sizeof(uint); // Childs Size size = sons.size(); memcpy(it, &size, sizeof(uint)); it += sizeof(uint); std::vector<std::pair<uint, char*>> toAdd; for (auto i : components) { std::pair<uint, char*> pair; pair.first = i.second->Serialize(pair.second); length += pair.first; toAdd.push_back(pair); } for (std::vector<GameObject*>::iterator child = sons.begin(); child != sons.end(); child++) { std::pair<uint, char*> pair; pair.first = (*child)->Serialize(pair.second); length += pair.first; toAdd.push_back(pair); } buf = new char[length]; it = buf; memcpy(it, myself, myLength); it += myLength; for (std::vector<std::pair<uint, char*>>::iterator i = toAdd.begin(); i != toAdd.end(); i++) { memcpy(it, i->second, i->first); it += i->first; delete[] i->second; } delete[] myself; return length; } uint GameObject::DeSerialize(char * &buffer, GameObject * parent) { uint ret = 0; uint size = 0; uint sizeChilds = 0; char* it = buffer; // Setting Parent if (parent == nullptr) { this->parent = App->scene->root; App->scene->root->sons.push_back(this); } else { this->parent = parent; parent->sons.push_back(this); } // Name Length memcpy(&size, it, sizeof(uint)); it += sizeof(uint); ret += sizeof(uint); // Name name.assign(&it[0], size); it += size; ret += size; // Components Size memcpy(&size, it, sizeof(uint)); it += sizeof(uint); ret += sizeof(uint); // Childs Size memcpy(&sizeChilds, it, sizeof(uint)); it += sizeof(uint); ret += sizeof(uint); if (size > NULL) { uint tmp = size; while (tmp > NULL) { componentType type; // Component Type int iType; uint t; memcpy(&iType, it, sizeof(int)); it += sizeof(int); ret += sizeof(int); type = (componentType)iType; switch (type) { case componentType::TRANSFORM: { cTransform transform(this); t = transform.DeSerialize(it, this); it += t; ret += t; break; } case componentType::MATERIAL: { cMaterial material(this); t = material.DeSerialize(it, this); it += t; ret += t; break; } case componentType::MESH: { cMesh mesh(this); t = mesh.DeSerialize(it, this); it += t; ret += t; break; } case componentType::CAMERA: { cCamera camera(this); t = camera.DeSerialize(it, this); it += t; ret += t; break; } default: { MYLOG("File was corrupted. Emergency exit, possible Scene bug."); return ret; break; } } tmp--; } } if (sizeChilds > NULL) { uint tmp = sizeChilds; while (tmp > NULL) { uint t = 0; GameObject* go = new GameObject("", true, this); t = go->DeSerialize(it, this); it += t; ret += t; tmp--; } } return ret; } void GameObject::Enable() { active =true ; } void GameObject::Disable() { active = false; }<commit_msg>Update<commit_after>#include "GameObject.h" #include "Application.h" #include "ModuleRenderer3D.h" #include "ModuleEditor.h" #include "ModuleScene.h" #include "cTransform.h" #include "cMesh.h" #include "cMaterial.h" #include "ResourceMesh.h" #include "cCamera.h" #include "MathGeoLib/MathGeoLib.h" #include "JSON/parson.h" #include "glew/include/glew.h" #include "SDL/include/SDL_opengl.h" #include <gl/GL.h> #include <gl/GLU.h> class cTransform; GameObject::GameObject(std::string _name, bool _active, GameObject * _parent) : name(_name) , active(_active) , parent(_parent) { aabbBox.SetNegativeInfinity(); } void GameObject::PreUpdate() { if (active) { for (auto itSons : sons) { itSons->PreUpdate(); } insideFrustum = false; } } void GameObject::Update() { if (active) { for (auto comp : components) { comp.second->Update(); } //Multiply all the matrixTransform with their sons glPushMatrix(); glMultMatrixf(((cTransform*)FindComponent(TRANSFORM))->GetLocalMatrixTransf().Transposed().ptr()); //Update AABB BOX for Game Objects if (((cTransform*)FindComponent(TRANSFORM))->transformChange) { float4x4 matrix = ((cTransform*)FindComponent(TRANSFORM))->GetGlobalMatrixTransf(); float4x4 matrix1 = ((cTransform*)FindComponent(TRANSFORM))->GetLocalMatrixTransf(); //if has a mesh it is modified if (SonHasMesh()) { UpdateAABB(matrix); } //IF has frustum it is modified if (((cCamera*)FindComponent(CAMERA)) != nullptr) { ((cCamera*)FindComponent(CAMERA))->transformFrustum = true; } ((cTransform*)FindComponent(TRANSFORM))->transformChange = false; } if (!sons.empty()) { for (auto itSons : sons) { itSons->Update(); } } if (App->renderer3D->bEnableWireframe) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); else glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); if(insideFrustum) App->renderer3D->DrawGameObject(this); if (!isInsideQuad && statiC) { //QUADTREE App->scene->quad.AddGameObject(this); isInsideQuad = true; } glPopMatrix(); if (App->isPlaying) { IsPlaying(App->GetGameDt()); } } } void GameObject::IsPlaying(float dt) { } Component * GameObject::FindComponent(componentType type) { Component * ret = nullptr; std::map<componentType, Component*>::iterator it = components.find(type); if (it != components.end()) { return it->second; } return nullptr; } void GameObject::DrawUI() { if (ImGui::CollapsingHeader(name.data())) { for (auto itComp : components) { itComp.second->DrawUI(); } } } void GameObject::UpdateAABB(float4x4 matrix) { for (auto sonsGO : sons) { sonsGO->UpdateAABB(matrix); } if (FindComponent(MESH) != nullptr) { aabbBox.SetNegativeInfinity(); OBB obb = ((cMesh*)FindComponent(MESH))->resource->aabbBox.Transform(matrix); aabbBox.Enclose(obb); } } void GameObject::DrawHeriarchy(GameObject* son) { //static int selection_mask = (1 << 2); // Dumb representation of what may be user-side selection state. You may carry selection state inside or outside your objects in whatever format you see fit. int node_clicked = -1; ImGuiTreeNodeFlags node_flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; //| ImGuiTreeNodeFlags_Selected; bool node_open; if (node_open = ImGui::TreeNodeEx(name.data(), node_flags)) { if (ImGui::IsItemClicked()) { node_clicked = 7; this->clicked = true; if (App->editor->selected != nullptr) { App->editor->selected->clicked = false; } App->editor->selected = this; } if (node_open) { for (auto sonsSons : son->sons) { sonsSons->DrawHeriarchy(sonsSons); } } //if (clicked) //{ // // Update selection state. Process outside of tree loop to avoid visual inconsistencies during the clicking-frame. // if (ImGui::GetIO().KeyCtrl) // selection_mask ^= (1 << node_clicked); // CTRL+click to toggle // else //if (!(selection_mask & (1 << node_clicked))) // Depending on selection behavior you want, this commented bit preserve selection when clicking on item that is part of the selection // selection_mask = (1 << node_clicked); // Click to single-select //} ImGui::TreePop(); } else { if (ImGui::IsItemClicked()) { node_clicked = 7; this->clicked = true; if (App->editor->selected != nullptr) { App->editor->selected->clicked = false; } App->editor->selected = this; } } } void GameObject::DrawProperties() { ImGui::Checkbox("Static", &statiC); ImGui::SameLine(); if (!ImGui::Checkbox("Enable/Disable", &active)) { if (active) { for (auto itComponents : components) { itComponents.second->DrawUI(); } } } } bool GameObject::SonHasMesh() { bool ret = false; if (FindComponent(MESH) != nullptr) { ret = true; } for (auto sonsGO : sons) { ret = sonsGO->SonHasMesh(); if (ret) { break; } } return ret; } void GameObject::AddComponent(Component* addComponent) { components.insert(std::pair<componentType, Component*>(addComponent->type, addComponent)); } void GameObject::Save(JSON_Object *go) const { json_object_set_string(go, "Name", name.data()); json_object_set_boolean(go, "Active", active); JSON_Value* value = json_value_init_array(); JSON_Array* compArray = json_value_get_array(value); for (auto it : components) { //it.second->Save(); } for (auto child : sons) { //child->Save(); } json_object_set_value(go, "Components", value); } void GameObject::Load(const JSON_Object * go) { } uint GameObject::Serialize(char * &buf) { uint length = 0; // Size of the GameObject uint myLength = 0; myLength += sizeof(uint); // Size of Name Length variable myLength += name.length(); // Size of the Name String myLength += sizeof(uint); // Size of Components myLength += sizeof(uint); // Size of Childs length = myLength; char* myself = new char[myLength]; // Actual size of 8 char* it = myself; // Name Length uint size = name.length(); memcpy(it, &size, sizeof(uint)); it += sizeof(uint); // Name memcpy(it, name.data(), name.length()); it += name.length(); // Components Size size = components.size(); memcpy(it, &size, sizeof(uint)); it += sizeof(uint); // Childs Size size = sons.size(); memcpy(it, &size, sizeof(uint)); it += sizeof(uint); std::vector<std::pair<uint, char*>> toAdd; for (auto i : components) { std::pair<uint, char*> pair; pair.first = i.second->Serialize(pair.second); length += pair.first; toAdd.push_back(pair); } for (std::vector<GameObject*>::iterator child = sons.begin(); child != sons.end(); child++) { std::pair<uint, char*> pair; pair.first = (*child)->Serialize(pair.second); length += pair.first; toAdd.push_back(pair); } buf = new char[length]; it = buf; memcpy(it, myself, myLength); it += myLength; for (std::vector<std::pair<uint, char*>>::iterator i = toAdd.begin(); i != toAdd.end(); i++) { memcpy(it, i->second, i->first); it += i->first; delete[] i->second; } delete[] myself; return length; } uint GameObject::DeSerialize(char * &buffer, GameObject * parent) { uint ret = 0; uint size = 0; uint sizeChilds = 0; char* it = buffer; // Setting Parent if (parent == nullptr) { this->parent = App->scene->root; App->scene->root->sons.push_back(this); } else { this->parent = parent; parent->sons.push_back(this); } // Name Length memcpy(&size, it, sizeof(uint)); it += sizeof(uint); ret += sizeof(uint); // Name name.assign(&it[0], size); it += size; ret += size; // Components Size memcpy(&size, it, sizeof(uint)); it += sizeof(uint); ret += sizeof(uint); // Childs Size memcpy(&sizeChilds, it, sizeof(uint)); it += sizeof(uint); ret += sizeof(uint); if (size > NULL) { uint tmp = size; while (tmp > NULL) { componentType type; // Component Type int iType; uint t; memcpy(&iType, it, sizeof(int)); it += sizeof(int); ret += sizeof(int); type = (componentType)iType; switch (type) { case componentType::TRANSFORM: { //cTransform* c = (cTransform*)FindComponent(TRANSFORM); cTransform * c = (cTransform*)this->FindComponent(TRANSFORM); t = (c->DeSerialize(it, this)); //t = transform.DeSerialize(it, this); it += t; ret += t; break; } case componentType::MATERIAL: { cMaterial material(this); t = material.DeSerialize(it, this); it += t; ret += t; break; } case componentType::MESH: { cMesh mesh(this); t = mesh.DeSerialize(it, this); it += t; ret += t; break; } case componentType::CAMERA: { cCamera camera(this); t = camera.DeSerialize(it, this); it += t; ret += t; break; } default: { MYLOG("File was corrupted. Emergency exit, possible Scene bug."); return ret; break; } } tmp--; } } if (sizeChilds > NULL) { uint tmp = sizeChilds; while (tmp > NULL) { uint t = 0; GameObject* go = new GameObject("", true, this); t = go->DeSerialize(it, this); sons.push_back(go); it += t; ret += t; tmp--; } } return ret; } void GameObject::Enable() { active =true ; } void GameObject::Disable() { active = false; }<|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://www.qt.io/licensing. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "detailederrorview.h" #include <coreplugin/coreconstants.h> #include <coreplugin/editormanager/editormanager.h> #include <utils/qtcassert.h> #include <QApplication> #include <QClipboard> #include <QContextMenuEvent> #include <QFontMetrics> #include <QPainter> #include <QScrollBar> namespace Analyzer { DetailedErrorDelegate::DetailedErrorDelegate(QListView *parent) : QStyledItemDelegate(parent), m_detailsWidget(0) { connect(parent->verticalScrollBar(), &QScrollBar::valueChanged, this, &DetailedErrorDelegate::onVerticalScroll); } QSize DetailedErrorDelegate::sizeHint(const QStyleOptionViewItem &opt, const QModelIndex &index) const { if (!index.isValid()) return QStyledItemDelegate::sizeHint(opt, index); const QListView *view = qobject_cast<const QListView *>(parent()); const int viewportWidth = view->viewport()->width(); const bool isSelected = view->selectionModel()->currentIndex() == index; const int dy = 2 * s_itemMargin; if (!isSelected) { QFontMetrics fm(opt.font); return QSize(viewportWidth, fm.height() + dy); } if (m_detailsWidget && m_detailsIndex != index) { m_detailsWidget->deleteLater(); m_detailsWidget = 0; } if (!m_detailsWidget) { m_detailsWidget = createDetailsWidget(opt.font, index, view->viewport()); QTC_ASSERT(m_detailsWidget->parent() == view->viewport(), m_detailsWidget->setParent(view->viewport())); m_detailsIndex = index; } else { QTC_ASSERT(m_detailsIndex == index, /**/); } const int widthExcludingMargins = viewportWidth - 2 * s_itemMargin; m_detailsWidget->setFixedWidth(widthExcludingMargins); m_detailsWidgetHeight = m_detailsWidget->heightForWidth(widthExcludingMargins); // HACK: it's a bug in QLabel(?) that we have to force the widget to have the size it said // it would have. m_detailsWidget->setFixedHeight(m_detailsWidgetHeight); return QSize(viewportWidth, dy + m_detailsWidget->heightForWidth(widthExcludingMargins)); } void DetailedErrorDelegate::paint(QPainter *painter, const QStyleOptionViewItem &basicOption, const QModelIndex &index) const { QStyleOptionViewItemV4 opt(basicOption); initStyleOption(&opt, index); const QListView *const view = qobject_cast<const QListView *>(parent()); const bool isSelected = view->selectionModel()->currentIndex() == index; QFontMetrics fm(opt.font); QPoint pos = opt.rect.topLeft(); painter->save(); const QColor bgColor = isSelected ? opt.palette.highlight().color() : opt.palette.background().color(); painter->setBrush(bgColor); // clear background painter->setPen(Qt::NoPen); painter->drawRect(opt.rect); pos.rx() += s_itemMargin; pos.ry() += s_itemMargin; if (isSelected) { // only show detailed widget and let it handle everything QTC_ASSERT(m_detailsIndex == index, /**/); QTC_ASSERT(m_detailsWidget, return); // should have been set in sizeHint() m_detailsWidget->move(pos); // when scrolling quickly, the widget can get stuck in a visible part of the scroll area // even though it should not be visible. therefore we hide it every time the scroll value // changes and un-hide it when the item with details widget is paint()ed, i.e. visible. m_detailsWidget->show(); const int viewportWidth = view->viewport()->width(); const int widthExcludingMargins = viewportWidth - 2 * s_itemMargin; QTC_ASSERT(m_detailsWidget->width() == widthExcludingMargins, /**/); QTC_ASSERT(m_detailsWidgetHeight == m_detailsWidget->height(), /**/); } else { // the reference coordinate for text drawing is the text baseline; move it inside the view rect. pos.ry() += fm.ascent(); const QColor textColor = opt.palette.text().color(); painter->setPen(textColor); // draw only text + location const SummaryLineInfo info = summaryInfo(index); const QString errorText = info.errorText; painter->drawText(pos, errorText); const int whatWidth = QFontMetrics(opt.font).width(errorText); const int space = 10; const int widthLeft = opt.rect.width() - (pos.x() + whatWidth + space + s_itemMargin); if (widthLeft > 0) { QFont monospace = opt.font; monospace.setFamily(QLatin1String("monospace")); QFontMetrics metrics(monospace); QColor nameColor = textColor; nameColor.setAlphaF(0.7); painter->setFont(monospace); painter->setPen(nameColor); QPoint namePos = pos; namePos.rx() += whatWidth + space; painter->drawText(namePos, metrics.elidedText(info.errorLocation, Qt::ElideLeft, widthLeft)); } } // Separator lines (like Issues pane) painter->setPen(QColor::fromRgb(150,150,150)); painter->drawLine(0, opt.rect.bottom(), opt.rect.right(), opt.rect.bottom()); painter->restore(); } void DetailedErrorDelegate::onCurrentSelectionChanged(const QModelIndex &now, const QModelIndex &previous) { if (m_detailsWidget) { m_detailsWidget->deleteLater(); m_detailsWidget = 0; } m_detailsIndex = QModelIndex(); if (now.isValid()) emit sizeHintChanged(now); if (previous.isValid()) emit sizeHintChanged(previous); } void DetailedErrorDelegate::onLayoutChanged() { if (m_detailsWidget) { m_detailsWidget->deleteLater(); m_detailsWidget = 0; m_detailsIndex = QModelIndex(); } } void DetailedErrorDelegate::onViewResized() { const QListView *view = qobject_cast<const QListView *>(parent()); if (m_detailsWidget) emit sizeHintChanged(view->selectionModel()->currentIndex()); } void DetailedErrorDelegate::onVerticalScroll() { if (m_detailsWidget) m_detailsWidget->hide(); } // Expects "file://some/path[:line[:column]]" - the line/column part is optional void DetailedErrorDelegate::openLinkInEditor(const QString &link) { const QString linkWithoutPrefix = link.mid(strlen("file://")); const QChar separator = QLatin1Char(':'); const int lineColon = linkWithoutPrefix.indexOf(separator, /*after drive letter + colon =*/ 2); const QString path = linkWithoutPrefix.left(lineColon); const QString lineColumn = linkWithoutPrefix.mid(lineColon + 1); const int line = lineColumn.section(separator, 0, 0).toInt(); const int column = lineColumn.section(separator, 1, 1).toInt(); Core::EditorManager::openEditorAt(path, qMax(line, 0), qMax(column, 0)); } void DetailedErrorDelegate::copyToClipboard() { QApplication::clipboard()->setText(textualRepresentation()); } DetailedErrorView::DetailedErrorView(QWidget *parent) : QListView(parent) { } DetailedErrorView::~DetailedErrorView() { itemDelegate()->deleteLater(); } void DetailedErrorView::setItemDelegate(QAbstractItemDelegate *delegate) { QListView::setItemDelegate(delegate); DetailedErrorDelegate *myDelegate = qobject_cast<DetailedErrorDelegate *>(itemDelegate()); connect(this, &DetailedErrorView::resized, myDelegate, &DetailedErrorDelegate::onViewResized); m_copyAction = new QAction(this); m_copyAction->setText(tr("Copy")); m_copyAction->setIcon(QIcon(QLatin1String(Core::Constants::ICON_COPY))); m_copyAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_C)); m_copyAction->setShortcutContext(Qt::WidgetWithChildrenShortcut); connect(m_copyAction, &QAction::triggered, myDelegate, &DetailedErrorDelegate::copyToClipboard); addAction(m_copyAction); } void DetailedErrorView::setModel(QAbstractItemModel *model) { QListView::setModel(model); DetailedErrorDelegate *delegate = qobject_cast<DetailedErrorDelegate *>(itemDelegate()); QTC_ASSERT(delegate, return); connect(selectionModel(), &QItemSelectionModel::currentChanged, delegate, &DetailedErrorDelegate::onCurrentSelectionChanged); connect(model, &QAbstractItemModel::layoutChanged, delegate, &DetailedErrorDelegate::onLayoutChanged); } void DetailedErrorView::resizeEvent(QResizeEvent *e) { emit resized(); QListView::resizeEvent(e); } void DetailedErrorView::contextMenuEvent(QContextMenuEvent *e) { if (selectionModel()->selectedRows().isEmpty()) return; QMenu menu; menu.addActions(commonActions()); const QList<QAction *> custom = customActions(); if (!custom.isEmpty()) { menu.addSeparator(); menu.addActions(custom); } menu.exec(e->globalPos()); } void DetailedErrorView::updateGeometries() { if (model()) { QModelIndex index = model()->index(0, modelColumn(), rootIndex()); QStyleOptionViewItem option = viewOptions(); // delegate for row / column QSize step = itemDelegate()->sizeHint(option, index); horizontalScrollBar()->setSingleStep(step.width() + spacing()); verticalScrollBar()->setSingleStep(step.height() + spacing()); } QListView::updateGeometries(); } void DetailedErrorView::goNext() { QTC_ASSERT(rowCount(), return); setCurrentRow((currentRow() + 1) % rowCount()); } void DetailedErrorView::goBack() { QTC_ASSERT(rowCount(), return); const int prevRow = currentRow() - 1; setCurrentRow(prevRow >= 0 ? prevRow : rowCount() - 1); } int DetailedErrorView::rowCount() const { return model() ? model()->rowCount() : 0; } QList<QAction *> DetailedErrorView::commonActions() const { QList<QAction *> actions; actions << m_copyAction; return actions; } QList<QAction *> DetailedErrorView::customActions() const { return QList<QAction *>(); } int DetailedErrorView::currentRow() const { const QModelIndex index = selectionModel()->currentIndex(); return index.row(); } void DetailedErrorView::setCurrentRow(int row) { const QModelIndex index = model()->index(row, 0); selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); scrollTo(index); } } // namespace Analyzer <commit_msg>Analyzer: Use QKeySequence::copy for copying to clipboard.<commit_after>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://www.qt.io/licensing. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "detailederrorview.h" #include <coreplugin/coreconstants.h> #include <coreplugin/editormanager/editormanager.h> #include <utils/qtcassert.h> #include <QApplication> #include <QClipboard> #include <QContextMenuEvent> #include <QFontMetrics> #include <QPainter> #include <QScrollBar> namespace Analyzer { DetailedErrorDelegate::DetailedErrorDelegate(QListView *parent) : QStyledItemDelegate(parent), m_detailsWidget(0) { connect(parent->verticalScrollBar(), &QScrollBar::valueChanged, this, &DetailedErrorDelegate::onVerticalScroll); } QSize DetailedErrorDelegate::sizeHint(const QStyleOptionViewItem &opt, const QModelIndex &index) const { if (!index.isValid()) return QStyledItemDelegate::sizeHint(opt, index); const QListView *view = qobject_cast<const QListView *>(parent()); const int viewportWidth = view->viewport()->width(); const bool isSelected = view->selectionModel()->currentIndex() == index; const int dy = 2 * s_itemMargin; if (!isSelected) { QFontMetrics fm(opt.font); return QSize(viewportWidth, fm.height() + dy); } if (m_detailsWidget && m_detailsIndex != index) { m_detailsWidget->deleteLater(); m_detailsWidget = 0; } if (!m_detailsWidget) { m_detailsWidget = createDetailsWidget(opt.font, index, view->viewport()); QTC_ASSERT(m_detailsWidget->parent() == view->viewport(), m_detailsWidget->setParent(view->viewport())); m_detailsIndex = index; } else { QTC_ASSERT(m_detailsIndex == index, /**/); } const int widthExcludingMargins = viewportWidth - 2 * s_itemMargin; m_detailsWidget->setFixedWidth(widthExcludingMargins); m_detailsWidgetHeight = m_detailsWidget->heightForWidth(widthExcludingMargins); // HACK: it's a bug in QLabel(?) that we have to force the widget to have the size it said // it would have. m_detailsWidget->setFixedHeight(m_detailsWidgetHeight); return QSize(viewportWidth, dy + m_detailsWidget->heightForWidth(widthExcludingMargins)); } void DetailedErrorDelegate::paint(QPainter *painter, const QStyleOptionViewItem &basicOption, const QModelIndex &index) const { QStyleOptionViewItemV4 opt(basicOption); initStyleOption(&opt, index); const QListView *const view = qobject_cast<const QListView *>(parent()); const bool isSelected = view->selectionModel()->currentIndex() == index; QFontMetrics fm(opt.font); QPoint pos = opt.rect.topLeft(); painter->save(); const QColor bgColor = isSelected ? opt.palette.highlight().color() : opt.palette.background().color(); painter->setBrush(bgColor); // clear background painter->setPen(Qt::NoPen); painter->drawRect(opt.rect); pos.rx() += s_itemMargin; pos.ry() += s_itemMargin; if (isSelected) { // only show detailed widget and let it handle everything QTC_ASSERT(m_detailsIndex == index, /**/); QTC_ASSERT(m_detailsWidget, return); // should have been set in sizeHint() m_detailsWidget->move(pos); // when scrolling quickly, the widget can get stuck in a visible part of the scroll area // even though it should not be visible. therefore we hide it every time the scroll value // changes and un-hide it when the item with details widget is paint()ed, i.e. visible. m_detailsWidget->show(); const int viewportWidth = view->viewport()->width(); const int widthExcludingMargins = viewportWidth - 2 * s_itemMargin; QTC_ASSERT(m_detailsWidget->width() == widthExcludingMargins, /**/); QTC_ASSERT(m_detailsWidgetHeight == m_detailsWidget->height(), /**/); } else { // the reference coordinate for text drawing is the text baseline; move it inside the view rect. pos.ry() += fm.ascent(); const QColor textColor = opt.palette.text().color(); painter->setPen(textColor); // draw only text + location const SummaryLineInfo info = summaryInfo(index); const QString errorText = info.errorText; painter->drawText(pos, errorText); const int whatWidth = QFontMetrics(opt.font).width(errorText); const int space = 10; const int widthLeft = opt.rect.width() - (pos.x() + whatWidth + space + s_itemMargin); if (widthLeft > 0) { QFont monospace = opt.font; monospace.setFamily(QLatin1String("monospace")); QFontMetrics metrics(monospace); QColor nameColor = textColor; nameColor.setAlphaF(0.7); painter->setFont(monospace); painter->setPen(nameColor); QPoint namePos = pos; namePos.rx() += whatWidth + space; painter->drawText(namePos, metrics.elidedText(info.errorLocation, Qt::ElideLeft, widthLeft)); } } // Separator lines (like Issues pane) painter->setPen(QColor::fromRgb(150,150,150)); painter->drawLine(0, opt.rect.bottom(), opt.rect.right(), opt.rect.bottom()); painter->restore(); } void DetailedErrorDelegate::onCurrentSelectionChanged(const QModelIndex &now, const QModelIndex &previous) { if (m_detailsWidget) { m_detailsWidget->deleteLater(); m_detailsWidget = 0; } m_detailsIndex = QModelIndex(); if (now.isValid()) emit sizeHintChanged(now); if (previous.isValid()) emit sizeHintChanged(previous); } void DetailedErrorDelegate::onLayoutChanged() { if (m_detailsWidget) { m_detailsWidget->deleteLater(); m_detailsWidget = 0; m_detailsIndex = QModelIndex(); } } void DetailedErrorDelegate::onViewResized() { const QListView *view = qobject_cast<const QListView *>(parent()); if (m_detailsWidget) emit sizeHintChanged(view->selectionModel()->currentIndex()); } void DetailedErrorDelegate::onVerticalScroll() { if (m_detailsWidget) m_detailsWidget->hide(); } // Expects "file://some/path[:line[:column]]" - the line/column part is optional void DetailedErrorDelegate::openLinkInEditor(const QString &link) { const QString linkWithoutPrefix = link.mid(strlen("file://")); const QChar separator = QLatin1Char(':'); const int lineColon = linkWithoutPrefix.indexOf(separator, /*after drive letter + colon =*/ 2); const QString path = linkWithoutPrefix.left(lineColon); const QString lineColumn = linkWithoutPrefix.mid(lineColon + 1); const int line = lineColumn.section(separator, 0, 0).toInt(); const int column = lineColumn.section(separator, 1, 1).toInt(); Core::EditorManager::openEditorAt(path, qMax(line, 0), qMax(column, 0)); } void DetailedErrorDelegate::copyToClipboard() { QApplication::clipboard()->setText(textualRepresentation()); } DetailedErrorView::DetailedErrorView(QWidget *parent) : QListView(parent) { } DetailedErrorView::~DetailedErrorView() { itemDelegate()->deleteLater(); } void DetailedErrorView::setItemDelegate(QAbstractItemDelegate *delegate) { QListView::setItemDelegate(delegate); DetailedErrorDelegate *myDelegate = qobject_cast<DetailedErrorDelegate *>(itemDelegate()); connect(this, &DetailedErrorView::resized, myDelegate, &DetailedErrorDelegate::onViewResized); m_copyAction = new QAction(this); m_copyAction->setText(tr("Copy")); m_copyAction->setIcon(QIcon(QLatin1String(Core::Constants::ICON_COPY))); m_copyAction->setShortcut(QKeySequence::Copy); m_copyAction->setShortcutContext(Qt::WidgetWithChildrenShortcut); connect(m_copyAction, &QAction::triggered, myDelegate, &DetailedErrorDelegate::copyToClipboard); addAction(m_copyAction); } void DetailedErrorView::setModel(QAbstractItemModel *model) { QListView::setModel(model); DetailedErrorDelegate *delegate = qobject_cast<DetailedErrorDelegate *>(itemDelegate()); QTC_ASSERT(delegate, return); connect(selectionModel(), &QItemSelectionModel::currentChanged, delegate, &DetailedErrorDelegate::onCurrentSelectionChanged); connect(model, &QAbstractItemModel::layoutChanged, delegate, &DetailedErrorDelegate::onLayoutChanged); } void DetailedErrorView::resizeEvent(QResizeEvent *e) { emit resized(); QListView::resizeEvent(e); } void DetailedErrorView::contextMenuEvent(QContextMenuEvent *e) { if (selectionModel()->selectedRows().isEmpty()) return; QMenu menu; menu.addActions(commonActions()); const QList<QAction *> custom = customActions(); if (!custom.isEmpty()) { menu.addSeparator(); menu.addActions(custom); } menu.exec(e->globalPos()); } void DetailedErrorView::updateGeometries() { if (model()) { QModelIndex index = model()->index(0, modelColumn(), rootIndex()); QStyleOptionViewItem option = viewOptions(); // delegate for row / column QSize step = itemDelegate()->sizeHint(option, index); horizontalScrollBar()->setSingleStep(step.width() + spacing()); verticalScrollBar()->setSingleStep(step.height() + spacing()); } QListView::updateGeometries(); } void DetailedErrorView::goNext() { QTC_ASSERT(rowCount(), return); setCurrentRow((currentRow() + 1) % rowCount()); } void DetailedErrorView::goBack() { QTC_ASSERT(rowCount(), return); const int prevRow = currentRow() - 1; setCurrentRow(prevRow >= 0 ? prevRow : rowCount() - 1); } int DetailedErrorView::rowCount() const { return model() ? model()->rowCount() : 0; } QList<QAction *> DetailedErrorView::commonActions() const { QList<QAction *> actions; actions << m_copyAction; return actions; } QList<QAction *> DetailedErrorView::customActions() const { return QList<QAction *>(); } int DetailedErrorView::currentRow() const { const QModelIndex index = selectionModel()->currentIndex(); return index.row(); } void DetailedErrorView::setCurrentRow(int row) { const QModelIndex index = model()->index(row, 0); selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); scrollTo(index); } } // namespace Analyzer <|endoftext|>
<commit_before>// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // // Unmanaged helpers called by the managed finalizer thread. // #include "common.h" #include "gcenv.h" #include "gc.h" #include "slist.h" #include "gcrhinterface.h" #include "RWLock.h" #include "RuntimeInstance.h" #include "shash.h" #include "module.h" // Block the current thread until at least one object needs to be finalized (returns true) or memory is low // (returns false and the finalizer thread should initiate a garbage collection). EXTERN_C REDHAWK_API UInt32_BOOL __cdecl RhpWaitForFinalizerRequest() { // We can wait for two events; finalization queue has been populated and low memory resource notification. // But if the latter is signalled we shouldn't wait on it again immediately -- if the garbage collection // the finalizer thread initiates as a result is not sufficient to remove the low memory condition the // event will still be signalled and we'll end up looping doing cpu intensive collections, which won't // help the situation at all and could make it worse. So we remember whether the last event we reported // was low memory and if so we'll wait at least two seconds (the CLR value) on just a finalization // request. static bool fLastEventWasLowMemory = false; GCHeap * pHeap = GCHeap::GetGCHeap(); // Wait in a loop because we may have to retry if we decide to only wait for finalization events but the // two second timeout expires. do { HANDLE lowMemEvent = NULL; #if 0 // TODO: hook up low memory notification lowMemEvent = pHeap->GetLowMemoryNotificationEvent(); #endif // 0 HANDLE rgWaitHandles[] = { FinalizerThread::GetFinalizerEvent(), lowMemEvent }; UInt32 cWaitHandles = (fLastEventWasLowMemory || (lowMemEvent == NULL)) ? 1 : 2; UInt32 uTimeout = fLastEventWasLowMemory ? 2000 : INFINITE; UInt32 uResult = PalWaitForMultipleObjectsEx(cWaitHandles, rgWaitHandles, FALSE, uTimeout, FALSE); switch (uResult) { case WAIT_OBJECT_0: // At least one object is ready for finalization. return TRUE; case WAIT_OBJECT_0 + 1: // Memory is low, tell the finalizer thread to garbage collect. ASSERT(!fLastEventWasLowMemory); fLastEventWasLowMemory = true; return FALSE; case WAIT_TIMEOUT: // We were waiting only for finalization events but didn't get one within the timeout period. Go // back to waiting for any event. ASSERT(fLastEventWasLowMemory); fLastEventWasLowMemory = false; break; default: ASSERT(!"Unexpected PalWaitForMultipleObjectsEx() result"); return FALSE; } } while (true); } // Indicate that the current round of finalizations is complete. EXTERN_C REDHAWK_API void __cdecl RhpSignalFinalizationComplete() { FinalizerThread::SignalFinalizationDone(TRUE); } #ifndef CORERT // @TODO: Remove on next breaking change sweep #ifdef FEATURE_PREMORTEM_FINALIZATION // Enable a last pass of the finalizer during (clean) runtime shutdown. Specify the number of milliseconds // we'll wait before giving up a proceeding with the shutdown (INFINITE is an allowable value). COOP_PINVOKE_HELPER(void, RhEnableShutdownFinalization, (UInt32 uiTimeout)) { UNREFERENCED_PARAMETER(uiTimeout); } // Returns true when shutdown has started and it is no longer safe to access other objects from finalizers. COOP_PINVOKE_HELPER(UInt8, RhHasShutdownStarted, ()) { return 0; } #endif // FEATURE_PREMORTEM_FINALIZATION #endif // // The following helpers are special in that they interact with internal GC state or directly manipulate // managed references so they're called with a special co-operative p/invoke. // // Fetch next object which needs finalization or return null if we've reached the end of the list. COOP_PINVOKE_HELPER(OBJECTREF, RhpGetNextFinalizableObject, ()) { while (true) { // Get the next finalizable object. If we get back NULL we've reached the end of the list. OBJECTREF refNext = GCHeap::GetGCHeap()->GetNextFinalizable(); if (refNext == NULL) return NULL; // The queue may contain objects which have been marked as finalized already (via GC.SuppressFinalize() // for instance). Skip finalization for these but reset the flag so that the object can be put back on // the list with RegisterForFinalization(). if (refNext->GetHeader()->GetBits() & BIT_SBLK_FINALIZER_RUN) { refNext->GetHeader()->ClrBit(BIT_SBLK_FINALIZER_RUN); continue; } // We've found the first finalizable object, return it to the caller. return refNext; } } // This function walks the list of modules looking for any module that is a class library and has not yet // had its finalizer init callback invoked. It gets invoked in a loop, so it's technically O(n*m), but the // number of classlibs subscribing to this callback is almost certainly going to be 1. COOP_PINVOKE_HELPER(void *, RhpGetNextFinalizerInitCallback, ()) { FOREACH_MODULE(pModule) { if (pModule->IsClasslibModule() && !pModule->IsFinalizerInitComplete()) { pModule->SetFinalizerInitComplete(); void * retval = pModule->GetClasslibInitializeFinalizerThread(); // The caller loops until we return null, so we should only be returning null if we've walked all // the modules and found no callbacks yet to be made. if (retval != NULL) { return retval; } } } END_FOREACH_MODULE; return NULL; } <commit_msg>Delete RhEnableShutdownFinalization and RhHasShutdownStarted<commit_after>// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // // Unmanaged helpers called by the managed finalizer thread. // #include "common.h" #include "gcenv.h" #include "gc.h" #include "slist.h" #include "gcrhinterface.h" #include "RWLock.h" #include "RuntimeInstance.h" #include "shash.h" #include "module.h" // Block the current thread until at least one object needs to be finalized (returns true) or memory is low // (returns false and the finalizer thread should initiate a garbage collection). EXTERN_C REDHAWK_API UInt32_BOOL __cdecl RhpWaitForFinalizerRequest() { // We can wait for two events; finalization queue has been populated and low memory resource notification. // But if the latter is signalled we shouldn't wait on it again immediately -- if the garbage collection // the finalizer thread initiates as a result is not sufficient to remove the low memory condition the // event will still be signalled and we'll end up looping doing cpu intensive collections, which won't // help the situation at all and could make it worse. So we remember whether the last event we reported // was low memory and if so we'll wait at least two seconds (the CLR value) on just a finalization // request. static bool fLastEventWasLowMemory = false; GCHeap * pHeap = GCHeap::GetGCHeap(); // Wait in a loop because we may have to retry if we decide to only wait for finalization events but the // two second timeout expires. do { HANDLE lowMemEvent = NULL; #if 0 // TODO: hook up low memory notification lowMemEvent = pHeap->GetLowMemoryNotificationEvent(); #endif // 0 HANDLE rgWaitHandles[] = { FinalizerThread::GetFinalizerEvent(), lowMemEvent }; UInt32 cWaitHandles = (fLastEventWasLowMemory || (lowMemEvent == NULL)) ? 1 : 2; UInt32 uTimeout = fLastEventWasLowMemory ? 2000 : INFINITE; UInt32 uResult = PalWaitForMultipleObjectsEx(cWaitHandles, rgWaitHandles, FALSE, uTimeout, FALSE); switch (uResult) { case WAIT_OBJECT_0: // At least one object is ready for finalization. return TRUE; case WAIT_OBJECT_0 + 1: // Memory is low, tell the finalizer thread to garbage collect. ASSERT(!fLastEventWasLowMemory); fLastEventWasLowMemory = true; return FALSE; case WAIT_TIMEOUT: // We were waiting only for finalization events but didn't get one within the timeout period. Go // back to waiting for any event. ASSERT(fLastEventWasLowMemory); fLastEventWasLowMemory = false; break; default: ASSERT(!"Unexpected PalWaitForMultipleObjectsEx() result"); return FALSE; } } while (true); } // Indicate that the current round of finalizations is complete. EXTERN_C REDHAWK_API void __cdecl RhpSignalFinalizationComplete() { FinalizerThread::SignalFinalizationDone(TRUE); } // // The following helpers are special in that they interact with internal GC state or directly manipulate // managed references so they're called with a special co-operative p/invoke. // // Fetch next object which needs finalization or return null if we've reached the end of the list. COOP_PINVOKE_HELPER(OBJECTREF, RhpGetNextFinalizableObject, ()) { while (true) { // Get the next finalizable object. If we get back NULL we've reached the end of the list. OBJECTREF refNext = GCHeap::GetGCHeap()->GetNextFinalizable(); if (refNext == NULL) return NULL; // The queue may contain objects which have been marked as finalized already (via GC.SuppressFinalize() // for instance). Skip finalization for these but reset the flag so that the object can be put back on // the list with RegisterForFinalization(). if (refNext->GetHeader()->GetBits() & BIT_SBLK_FINALIZER_RUN) { refNext->GetHeader()->ClrBit(BIT_SBLK_FINALIZER_RUN); continue; } // We've found the first finalizable object, return it to the caller. return refNext; } } // This function walks the list of modules looking for any module that is a class library and has not yet // had its finalizer init callback invoked. It gets invoked in a loop, so it's technically O(n*m), but the // number of classlibs subscribing to this callback is almost certainly going to be 1. COOP_PINVOKE_HELPER(void *, RhpGetNextFinalizerInitCallback, ()) { FOREACH_MODULE(pModule) { if (pModule->IsClasslibModule() && !pModule->IsFinalizerInitComplete()) { pModule->SetFinalizerInitComplete(); void * retval = pModule->GetClasslibInitializeFinalizerThread(); // The caller loops until we return null, so we should only be returning null if we've walked all // the modules and found no callbacks yet to be made. if (retval != NULL) { return retval; } } } END_FOREACH_MODULE; return NULL; } <|endoftext|>
<commit_before>/******************************************************************************* * Project: libopencad * Purpose: OpenSource CAD formats support library * Author: Alexandr Borzykh, mush3d at gmail.com * Author: Dmitry Baryshnikov, bishop.dev@gmail.com * Language: C++ ******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2016 Alexandr Borzykh * Copyright (c) 2016 NextGIS, <info@nextgis.com> * * 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 "cadtables.h" #include "opencad_api.h" #include <memory> #include <cassert> using namespace std; CADTables::CADTables() { } void CADTables::addTable(TableType eType, CADHandle hHandle) { tableMap[eType] = hHandle; } int CADTables::readTable( CADFile * const file, CADTables::TableType eType) { auto it = tableMap.find (eType); if(it == tableMap.end ()) return CADErrorCodes::TABLE_READ_FAILED; // TODO: read different tables switch (eType) { case LayersTable: return readLayersTable(file, it->second.getAsLong ()); } return CADErrorCodes::SUCCESS; } size_t CADTables::getLayerCount() const { return layers.size (); } CADLayer& CADTables::getLayer(size_t index) { return layers[index]; } CADHandle CADTables::getTableHandle ( enum TableType type ) { // FIXME: need to add try/catch to prevent crashes on not found elem. return tableMap[type]; } int CADTables::readLayersTable( CADFile * const file, long index) { // Reading Layer Control obj, and layers. unique_ptr<CADLayerControlObject> layerControl( static_cast<CADLayerControlObject*>(file->getObject (index))); if(nullptr == layerControl) return CADErrorCodes::TABLE_READ_FAILED; for ( size_t i = 0; i < layerControl->hLayers.size(); ++i ) { if ( !layerControl->hLayers[i].isNull()) { CADLayer layer(file); // Init CADLayer from objLayer properties unique_ptr<CADLayerObject> objLayer( static_cast<CADLayerObject*>(file->getObject ( layerControl->hLayers[i].getAsLong ()))); layer.setName (objLayer->sLayerName); layer.setFrozen (objLayer->bFrozen); layer.setOn (objLayer->bOn); layer.setFrozenByDefault (objLayer->bFrozenInNewVPORT); layer.setLocked (objLayer->bLocked); layer.setLineWeight (objLayer->dLineWeight); layer.setColor (objLayer->dCMColor); layer.setId (layers.size () + 1); layer.setHandle (objLayer->hObjectHandle.getAsLong ()); layers.push_back (layer); } } auto it = tableMap.find (BlockRecordModelSpace); if(it == tableMap.end ()) return CADErrorCodes::TABLE_READ_FAILED; unique_ptr<CADBlockHeaderObject> pstModelSpace ( static_cast<CADBlockHeaderObject *>(file->getObject ( it->second.getAsLong ()))); auto dCurrentEntHandle = pstModelSpace->hEntities[0].getAsLong (); auto dLastEntHandle = pstModelSpace->hEntities[1].getAsLong (); while ( true ) { unique_ptr<CADEntityObject> ent( static_cast<CADEntityObject *>( file->getObject (dCurrentEntHandle, true))); // true = read CED && handles only /* TODO: this check is excessive, but if something goes wrong way - * some part of geometries will be parsed. */ if ( ent != nullptr ) { fillLayer(ent.get ()); if ( ent->stCed.bNoLinks ) ++dCurrentEntHandle; else dCurrentEntHandle = ent->stChed.hNextEntity.getAsLong ( ent->stCed.hObjectHandle); } else{ #ifdef _DEBUG assert(0); #endif //_DEBUG } if ( dCurrentEntHandle == dLastEntHandle ) { ent.reset (static_cast<CADEntityObject *>( file->getObject (dCurrentEntHandle, true) ) ); if(nullptr != ent) fillLayer(ent.get ()); else{ #ifdef _DEBUG assert(0); #endif //_DEBUG } break; } } DebugMsg ("Readed layers using LayerControl object count: %d\n", layers.size ()); return CADErrorCodes::SUCCESS; } void CADTables::fillLayer(const CADEntityObject *ent) { for ( CADLayer &layer : layers ) { if ( ent->stChed.hLayer.getAsLong (ent->stCed.hObjectHandle) == layer.getHandle () ) { DebugMsg ("Object with type: %s is attached to layer named: %s\n", getNameByType(ent->getType()).c_str (), layer.getName ().c_str ()); layer.addHandle (ent->stCed.hObjectHandle.getAsLong (), ent->getType()); break; // TODO: check if only can be add to one layer } } } <commit_msg>Fixed reading of files with single object<commit_after>/******************************************************************************* * Project: libopencad * Purpose: OpenSource CAD formats support library * Author: Alexandr Borzykh, mush3d at gmail.com * Author: Dmitry Baryshnikov, bishop.dev@gmail.com * Language: C++ ******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2016 Alexandr Borzykh * Copyright (c) 2016 NextGIS, <info@nextgis.com> * * 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 "cadtables.h" #include "opencad_api.h" #include <memory> #include <cassert> using namespace std; CADTables::CADTables() { } void CADTables::addTable(TableType eType, CADHandle hHandle) { tableMap[eType] = hHandle; } int CADTables::readTable( CADFile * const file, CADTables::TableType eType) { auto it = tableMap.find (eType); if(it == tableMap.end ()) return CADErrorCodes::TABLE_READ_FAILED; // TODO: read different tables switch (eType) { case LayersTable: return readLayersTable(file, it->second.getAsLong ()); } return CADErrorCodes::SUCCESS; } size_t CADTables::getLayerCount() const { return layers.size (); } CADLayer& CADTables::getLayer(size_t index) { return layers[index]; } CADHandle CADTables::getTableHandle ( enum TableType type ) { // FIXME: need to add try/catch to prevent crashes on not found elem. return tableMap[type]; } int CADTables::readLayersTable( CADFile * const file, long index) { // Reading Layer Control obj, and layers. unique_ptr<CADLayerControlObject> layerControl( static_cast<CADLayerControlObject*>(file->getObject (index))); if(nullptr == layerControl) return CADErrorCodes::TABLE_READ_FAILED; for ( size_t i = 0; i < layerControl->hLayers.size(); ++i ) { if ( !layerControl->hLayers[i].isNull()) { CADLayer layer(file); // Init CADLayer from objLayer properties unique_ptr<CADLayerObject> objLayer( static_cast<CADLayerObject*>(file->getObject ( layerControl->hLayers[i].getAsLong ()))); layer.setName (objLayer->sLayerName); layer.setFrozen (objLayer->bFrozen); layer.setOn (objLayer->bOn); layer.setFrozenByDefault (objLayer->bFrozenInNewVPORT); layer.setLocked (objLayer->bLocked); layer.setLineWeight (objLayer->dLineWeight); layer.setColor (objLayer->dCMColor); layer.setId (layers.size () + 1); layer.setHandle (objLayer->hObjectHandle.getAsLong ()); layers.push_back (layer); } } auto it = tableMap.find (BlockRecordModelSpace); if(it == tableMap.end ()) return CADErrorCodes::TABLE_READ_FAILED; unique_ptr<CADBlockHeaderObject> pstModelSpace ( static_cast<CADBlockHeaderObject *>(file->getObject ( it->second.getAsLong ()))); auto dCurrentEntHandle = pstModelSpace->hEntities[0].getAsLong (); auto dLastEntHandle = pstModelSpace->hEntities[1].getAsLong (); while ( true ) { unique_ptr<CADEntityObject> ent( static_cast<CADEntityObject *>( file->getObject (dCurrentEntHandle, true))); // true = read CED && handles only /* TODO: this check is excessive, but if something goes wrong way - * some part of geometries will be parsed. */ if ( ent != nullptr ) { fillLayer(ent.get ()); if ( ent->stCed.bNoLinks ) ++dCurrentEntHandle; else dCurrentEntHandle = ent->stChed.hNextEntity.getAsLong ( ent->stCed.hObjectHandle); } else{ #ifdef _DEBUG assert(0); #endif //_DEBUG } if ( dCurrentEntHandle == dLastEntHandle ) { ent.reset (static_cast<CADEntityObject *>( file->getObject (dCurrentEntHandle, true) ) ); if(nullptr != ent) fillLayer(ent.get ()); else{ #ifdef _DEBUG assert(0); #endif //_DEBUG } break; } if( dCurrentEntHandle == 0 ) // it means we have reached the end, object with 0 handle does not exist. break; } DebugMsg ("Readed layers using LayerControl object count: %d\n", layers.size ()); return CADErrorCodes::SUCCESS; } void CADTables::fillLayer(const CADEntityObject *ent) { for ( CADLayer &layer : layers ) { if ( ent->stChed.hLayer.getAsLong (ent->stCed.hObjectHandle) == layer.getHandle () ) { DebugMsg ("Object with type: %s is attached to layer named: %s\n", getNameByType(ent->getType()).c_str (), layer.getName ().c_str ()); layer.addHandle (ent->stCed.hObjectHandle.getAsLong (), ent->getType()); break; // TODO: check if only can be add to one layer } } } <|endoftext|>
<commit_before>/***************************************************************************************** * * * GHOUL * * General Helpful Open Utility Library * * * * Copyright (c) 2012-2014 * * * * 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. * ****************************************************************************************/ #if defined(WIN32) #include <ghoul/filesystem/filesystem.h> #include <ghoul/filesystem/cachemanager.h> #include <ghoul/logging/logmanager.h> #include <algorithm> #include <cassert> #include <regex> #include <cstdio> #include <direct.h> #include <windows.h> #include <Shlobj.h> using std::string; namespace { const string _loggerCat = "FileSystem"; void CALLBACK completionHandler( DWORD dwErrorCode, DWORD dwNumberOfBytesTransferred, LPOVERLAPPED lpOverlapped); const unsigned int changeBufferSize = 16384u; #define _CRT_SECURE_NO_WARNINGS } namespace ghoul { namespace filesystem { struct DirectoryHandle { HANDLE _handle; unsigned char _activeBuffer; std::vector<BYTE> _changeBuffer[2]; OVERLAPPED _overlappedBuffer; }; void FileSystem::deinitializeInternalWindows() { for (auto d : _fileSystem->_directories) { DirectoryHandle* dh = d.second; CancelIo(dh->_handle); CloseHandle(dh->_handle); delete dh; } } void FileSystem::addFileListener(File* file) { assert(file != nullptr); //LDEBUG("Trying to insert " << file); std::string d = file->directoryName(); auto f = _directories.find(d); if (f == _directories.end()) { LDEBUG("started watching: " << d); DirectoryHandle* handle = new DirectoryHandle; handle->_activeBuffer = 0; handle->_handle = nullptr; handle->_handle = CreateFile( d.c_str(), FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL); if (handle->_handle == INVALID_HANDLE_VALUE) { LERROR("Directory handle for '" << d << "' could not be obtained"); return; } _directories[d] = handle; beginRead(handle); } #ifdef GHL_DEBUG auto eqRange = _trackedFiles.equal_range(file->path()); for (auto it = eqRange.first; it != eqRange.second; ++it) { if (it->second == file) { LERROR("Already tracking fileobject"); return; } } #endif _trackedFiles.emplace(file->path(), file); } void FileSystem::removeFileListener(File* file) { assert(file != nullptr); auto eqRange = _trackedFiles.equal_range(file->path()); for (auto it = eqRange.first; it != eqRange.second; ++it) { if (it->second == file) { _trackedFiles.erase(it); return; } } LWARNING("Could not find tracked '" << file <<"' for path '"<< file->path() << "'"); } void FileSystem::callbackHandler(DirectoryHandle* directoryHandle, const std::string& file) { std::string fullPath; for (auto d : FileSys._directories) { if (d.second == directoryHandle) fullPath = d.first + PathSeparator + file; } size_t n = FileSys._trackedFiles.count(fullPath); if (n > 0) { auto eqRange = FileSys._trackedFiles.equal_range(fullPath); for (auto it = eqRange.first; it != eqRange.second; ++it) { File* f = (*it).second; f->_fileChangedCallback(*f); } } } void callbackHandler(DirectoryHandle* directoryHandle, const std::string& file) { FileSys.callbackHandler(directoryHandle, file); } void readStarter(DirectoryHandle* directoryHandle) { FileSys.beginRead(directoryHandle); } void CALLBACK completionHandler( DWORD /*dwErrorCode*/, DWORD /*dwNumberOfBytesTransferred*/, LPOVERLAPPED lpOverlapped) { DirectoryHandle* directoryHandle = static_cast<DirectoryHandle*>(lpOverlapped->hEvent); unsigned char currentBuffer = directoryHandle->_activeBuffer; // Change active buffer (ping-pong buffering) directoryHandle->_activeBuffer = (directoryHandle->_activeBuffer + 1) % 2; // Restart change listener as soon as possible readStarter(directoryHandle); char* buffer = reinterpret_cast<char*>(&(directoryHandle->_changeBuffer[currentBuffer][0])); // data might have queued up, so we need to check all changes while (true) { // extract the information which file has changed FILE_NOTIFY_INFORMATION& information = reinterpret_cast<FILE_NOTIFY_INFORMATION&>(*buffer); if (information.Action == FILE_ACTION_MODIFIED) { char* currentFilenameBuffer = new char[information.FileNameLength]; // Convert from DWORD to char* size_t i; wcstombs_s(&i, currentFilenameBuffer, information.FileNameLength, information.FileName, information.FileNameLength); // make sure the last char is string terminating currentFilenameBuffer[i - 1] = '\0'; const string currentFilename(currentFilenameBuffer, i - 1); delete[] currentFilenameBuffer; //switch (information.Action) { //case FILE_ACTION_ADDED: // LDEBUG("Action: FILE_ACTION_ADDED"); // break; //case FILE_ACTION_REMOVED: // LDEBUG("Action: FILE_ACTION_REMOVED"); // break; //case FILE_ACTION_MODIFIED: // LDEBUG("Action: FILE_ACTION_MODIFIED"); // break; //case FILE_ACTION_RENAMED_OLD_NAME: // LDEBUG("Action: FILE_ACTION_RENAMED_OLD_NAME"); // break; //case FILE_ACTION_RENAMED_NEW_NAME: // LDEBUG("Action: FILE_ACTION_RENAMED_NEW_NAME"); // break; //default: // LDEBUG("Action: UNKNOWN"); // break; //} //LDEBUG("FileNameLength: " << information.FileNameLength); //LDEBUG("file: " << currentFilename); //LDEBUG("currentFilenamelength: " << currentFilename.length()); //LDEBUG("NextEntryOffset: " << information.NextEntryOffset); callbackHandler(directoryHandle, currentFilename); } if (!information.NextEntryOffset) // we are done with all entries and didn't find our file break; else //continue with the next entry buffer += information.NextEntryOffset; } //LWARNING("================"); } void FileSystem::beginRead(DirectoryHandle* directoryHandle) { HANDLE handle = directoryHandle->_handle; unsigned char activeBuffer = directoryHandle->_activeBuffer; std::vector<BYTE>* changeBuffer = directoryHandle->_changeBuffer; OVERLAPPED* overlappedBuffer = &directoryHandle->_overlappedBuffer; ZeroMemory(overlappedBuffer, sizeof(OVERLAPPED)); overlappedBuffer->hEvent = directoryHandle; changeBuffer[activeBuffer].resize(changeBufferSize); ZeroMemory(&(changeBuffer[activeBuffer][0]), changeBufferSize); DWORD returnedBytes; BOOL success = ReadDirectoryChangesW( handle, &changeBuffer[activeBuffer][0], static_cast<DWORD>(changeBuffer[activeBuffer].size()), false, FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_CREATION, &returnedBytes, overlappedBuffer, &completionHandler); if (success == 0) { LERROR("Could not begin read directory"); const DWORD error = GetLastError(); LPTSTR errorBuffer = nullptr; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errorBuffer, 0, NULL); if (errorBuffer != nullptr) { std::string errorString(errorBuffer); LocalFree(errorBuffer); LERROR("Error reading directory changes: " << errorString); } else { LERROR("Error reading directory changes: " << error); } } } } // namespace filesystem } // namespace ghoul #endif <commit_msg>Windows filesystem callback bugfix<commit_after>/***************************************************************************************** * * * GHOUL * * General Helpful Open Utility Library * * * * Copyright (c) 2012-2014 * * * * 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. * ****************************************************************************************/ #if defined(WIN32) #include <ghoul/filesystem/filesystem.h> #include <ghoul/filesystem/cachemanager.h> #include <ghoul/logging/logmanager.h> #include <algorithm> #include <cassert> #include <regex> #include <cstdio> #include <direct.h> #include <windows.h> #include <Shlobj.h> using std::string; namespace { const string _loggerCat = "FileSystem"; void CALLBACK completionHandler( DWORD dwErrorCode, DWORD dwNumberOfBytesTransferred, LPOVERLAPPED lpOverlapped); const unsigned int changeBufferSize = 16384u; #define _CRT_SECURE_NO_WARNINGS } namespace ghoul { namespace filesystem { struct DirectoryHandle { HANDLE _handle; unsigned char _activeBuffer; std::vector<BYTE> _changeBuffer[2]; OVERLAPPED _overlappedBuffer; }; void FileSystem::deinitializeInternalWindows() { for (auto d : _fileSystem->_directories) { DirectoryHandle* dh = d.second; CancelIo(dh->_handle); CloseHandle(dh->_handle); delete dh; } } void FileSystem::addFileListener(File* file) { assert(file != nullptr); //LDEBUG("Trying to insert " << file); std::string d = file->directoryName(); auto f = _directories.find(d); if (f == _directories.end()) { LDEBUG("started watching: " << d); DirectoryHandle* handle = new DirectoryHandle; handle->_activeBuffer = 0; handle->_handle = nullptr; handle->_handle = CreateFile( d.c_str(), FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL); if (handle->_handle == INVALID_HANDLE_VALUE) { LERROR("Directory handle for '" << d << "' could not be obtained"); return; } _directories[d] = handle; beginRead(handle); } #ifdef GHL_DEBUG auto eqRange = _trackedFiles.equal_range(file->path()); for (auto it = eqRange.first; it != eqRange.second; ++it) { if (it->second == file) { LERROR("Already tracking fileobject"); return; } } #endif _trackedFiles.emplace(file->path(), file); } void FileSystem::removeFileListener(File* file) { assert(file != nullptr); auto eqRange = _trackedFiles.equal_range(file->path()); for (auto it = eqRange.first; it != eqRange.second; ++it) { if (it->second == file) { _trackedFiles.erase(it); return; } } LWARNING("Could not find tracked '" << file <<"' for path '"<< file->path() << "'"); } void FileSystem::callbackHandler(DirectoryHandle* directoryHandle, const std::string& file) { std::string fullPath; for (auto d : FileSys._directories) { if (d.second == directoryHandle) fullPath = d.first + PathSeparator + file; } size_t n = FileSys._trackedFiles.count(fullPath); if (n > 0) { auto eqRange = FileSys._trackedFiles.equal_range(fullPath); for (auto it = eqRange.first; it != eqRange.second; ++it) { File* f = (*it).second; f->_fileChangedCallback(*f); } } } void callbackHandler(DirectoryHandle* directoryHandle, const std::string& file) { FileSys.callbackHandler(directoryHandle, file); } void readStarter(DirectoryHandle* directoryHandle) { FileSys.beginRead(directoryHandle); } void CALLBACK completionHandler( DWORD /*dwErrorCode*/, DWORD /*dwNumberOfBytesTransferred*/, LPOVERLAPPED lpOverlapped) { DirectoryHandle* directoryHandle = static_cast<DirectoryHandle*>(lpOverlapped->hEvent); unsigned char currentBuffer = directoryHandle->_activeBuffer; // Change active buffer (ping-pong buffering) directoryHandle->_activeBuffer = (directoryHandle->_activeBuffer + 1) % 2; // Restart change listener as soon as possible readStarter(directoryHandle); char* buffer = reinterpret_cast<char*>(&(directoryHandle->_changeBuffer[currentBuffer][0])); // data might have queued up, so we need to check all changes while (true) { // extract the information which file has changed FILE_NOTIFY_INFORMATION& information = reinterpret_cast<FILE_NOTIFY_INFORMATION&>(*buffer); if (information.Action == FILE_ACTION_MODIFIED) { char* currentFilenameBuffer = new char[information.FileNameLength]; // Convert from DWORD to char* size_t i; wcstombs_s(&i, currentFilenameBuffer, information.FileNameLength, information.FileName, information.FileNameLength); if (i > 0) { // make sure the last char is string terminating currentFilenameBuffer[i - 1] = '\0'; const string currentFilename(currentFilenameBuffer, i - 1); //switch (information.Action) { //case FILE_ACTION_ADDED: // LDEBUG("Action: FILE_ACTION_ADDED"); // break; //case FILE_ACTION_REMOVED: // LDEBUG("Action: FILE_ACTION_REMOVED"); // break; //case FILE_ACTION_MODIFIED: // LDEBUG("Action: FILE_ACTION_MODIFIED"); // break; //case FILE_ACTION_RENAMED_OLD_NAME: // LDEBUG("Action: FILE_ACTION_RENAMED_OLD_NAME"); // break; //case FILE_ACTION_RENAMED_NEW_NAME: // LDEBUG("Action: FILE_ACTION_RENAMED_NEW_NAME"); // break; //default: // LDEBUG("Action: UNKNOWN"); // break; //} //LDEBUG("FileNameLength: " << information.FileNameLength); //LDEBUG("file: " << currentFilename); //LDEBUG("currentFilenamelength: " << currentFilename.length()); //LDEBUG("NextEntryOffset: " << information.NextEntryOffset); callbackHandler(directoryHandle, currentFilename); } delete[] currentFilenameBuffer; } if (!information.NextEntryOffset) // we are done with all entries and didn't find our file break; else //continue with the next entry buffer += information.NextEntryOffset; } //LWARNING("================"); } void FileSystem::beginRead(DirectoryHandle* directoryHandle) { HANDLE handle = directoryHandle->_handle; unsigned char activeBuffer = directoryHandle->_activeBuffer; std::vector<BYTE>* changeBuffer = directoryHandle->_changeBuffer; OVERLAPPED* overlappedBuffer = &directoryHandle->_overlappedBuffer; ZeroMemory(overlappedBuffer, sizeof(OVERLAPPED)); overlappedBuffer->hEvent = directoryHandle; changeBuffer[activeBuffer].resize(changeBufferSize); ZeroMemory(&(changeBuffer[activeBuffer][0]), changeBufferSize); DWORD returnedBytes; BOOL success = ReadDirectoryChangesW( handle, &changeBuffer[activeBuffer][0], static_cast<DWORD>(changeBuffer[activeBuffer].size()), false, FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_CREATION, &returnedBytes, overlappedBuffer, &completionHandler); if (success == 0) { LERROR("Could not begin read directory"); const DWORD error = GetLastError(); LPTSTR errorBuffer = nullptr; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errorBuffer, 0, NULL); if (errorBuffer != nullptr) { std::string errorString(errorBuffer); LocalFree(errorBuffer); LERROR("Error reading directory changes: " << errorString); } else { LERROR("Error reading directory changes: " << error); } } } } // namespace filesystem } // namespace ghoul #endif <|endoftext|>
<commit_before>/* * The MIT License * * Copyright 2017-2018 Norwegian University 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. */ #include <iostream> #include <fmicpp/fmi2/import/FmiLibrary.hpp> #include <sstream> using namespace std; using namespace fmicpp::fmi2::import; namespace { static const char* status_to_string(fmi2Status status) { switch (status){ case 0: return "OK"; case 1: return "Warning"; case 2: return "Discard"; case 3: return "Error"; case 4: return "Fatal"; case 5: return "Pending"; default: return "Unknown"; } } static void logger(void* fmi2ComponentEnvironment, fmi2String instance_name, fmi2Status status, fmi2String category, fmi2String message, ...) { printf("status = %s, instanceName = %s, category = %s: %s\n", status_to_string(status), instance_name, category, message); } static const fmi2CallbackFunctions callback = { logger, calloc, free, NULL, NULL }; } const char *FmiLibrary::getLastError() const { #ifdef WIN32 std::ostringstream os; os << GetLastError(); return os.str().c_str(); #else return dlerror(); #endif } FmiLibrary::FmiLibrary(string lib_name) { #ifdef WIN32 handle_ = LoadLibrary(lib_name.c_str()); #else handle_ = dlopen(lib_name.c_str(), RTLD_NOW | RTLD_LOCAL); #endif if (!handle_) { cout << getLastError() << endl; string msg = "Unable to load dynamic library '" + lib_name + "'!"; throw runtime_error(msg); } } fmi2String FmiLibrary::getVersion() const { return loadFunction<fmi2GetVersionTYPE *>("fmi2GetVersion")(); } fmi2String FmiLibrary::getTypesPlatform() const { return loadFunction<fmi2GetTypesPlatformTYPE *>("fmi2GetTypesPlatform")(); } void FmiLibrary::instantiate(const string instanceName, const fmi2Type type, const string guid, const string resourceLocation, const bool visible, const bool loggingOn) { c_ = loadFunction<fmi2InstantiateTYPE *>("fmi2Instantiate")(instanceName.c_str(), type, guid.c_str(), resourceLocation.c_str(), &callback, visible ? 1 : 0, loggingOn ? 1 : 0); if (c_ == nullptr) { throw runtime_error("Unable to instantiate FMU instance!"); } } fmi2Status FmiLibrary::setupExperiment(const bool toleranceDefined, const double tolerance, const double startTime, const double stopTime) const { fmi2Boolean stopDefined = stopTime > startTime; return loadFunction<fmi2SetupExperimentTYPE *>("fmi2SetupExperiment") (c_, toleranceDefined ? 1 : 0, tolerance, startTime, stopDefined, stopTime); } fmi2Status FmiLibrary::enterInitializationMode() const { return loadFunction<fmi2EnterInitializationModeTYPE *>("fmi2EnterInitializationMode")(c_); } fmi2Status FmiLibrary::exitInitializationMode() const { return loadFunction<fmi2ExitInitializationModeTYPE *>("fmi2ExitInitializationMode")(c_); } fmi2Status FmiLibrary::reset() const { return loadFunction<fmi2ResetTYPE *>("fmi2Reset")(c_); } fmi2Status FmiLibrary::terminate() { return loadFunction<fmi2TerminateTYPE *>("fmi2Terminate")(c_); } fmi2Status FmiLibrary::readInteger(const fmi2ValueReference vr, fmi2Integer &ref) const { return loadFunction<fmi2GetIntegerTYPE *>("fmi2GetInteger")(c_, &vr, 1, &ref); } fmi2Status FmiLibrary::readInteger(const vector<fmi2ValueReference> &vr, vector<fmi2Integer> &ref) const { return loadFunction<fmi2GetIntegerTYPE *>("fmi2GetInteger")(c_, vr.data(), vr.size(), ref.data()); } fmi2Status FmiLibrary::readReal(const fmi2ValueReference vr, fmi2Real &ref) const { return loadFunction<fmi2GetRealTYPE *>("fmi2GetReal")(c_, &vr, 1, &ref); } fmi2Status FmiLibrary::readReal(const vector<fmi2ValueReference > &vr, vector<fmi2Real> &ref) const { return loadFunction<fmi2GetRealTYPE *>("fmi2GetReal")(c_, vr.data(), vr.size(), ref.data()); } fmi2Status FmiLibrary::readString(const fmi2ValueReference vr, fmi2String &ref) const { return loadFunction<fmi2GetStringTYPE *>("fmi2GetString")(c_, &vr, 1, &ref); } fmi2Status FmiLibrary::readString(const vector<fmi2ValueReference> &vr, vector<fmi2String > &ref) const { return loadFunction<fmi2GetStringTYPE *>("fmi2GetString")(c_, vr.data(), vr.size(), ref.data()); } fmi2Status FmiLibrary::readBoolean(const fmi2ValueReference vr, fmi2Boolean &ref) const { return loadFunction<fmi2GetBooleanTYPE *>("fmi2GetBoolean")(c_, &vr, 1, &ref); } fmi2Status FmiLibrary::readBoolean(const vector<fmi2ValueReference> &vr, vector<fmi2Boolean> &ref) const { return loadFunction<fmi2GetBooleanTYPE *>("fmi2GetBoolean")(c_, vr.data(), vr.size(), ref.data()); } void FmiLibrary::freeInstance() { return loadFunction<fmi2FreeInstanceTYPE *>("fmi2FreeInstance")(c_); } template<class T> T FmiLibrary::loadFunction(const char *function_name) const { #ifdef WIN32 return (T) GetProcAddress(handle_, function_name); #else return (T) dlsym(handle_, function_name); #endif } FmiLibrary::~FmiLibrary() { cout << "FmiLibrary destructor called.." << endl; if (c_) { terminate(); freeInstance(); c_ = nullptr; } if (handle_) { bool success; #ifdef WIN32 success = FreeLibrary(handle_); #else success = (dlclose(handle_) == 0); #endif if (!success) { cout << getLastError() << endl; } handle_ = nullptr; } } CoSimulationLibrary::CoSimulationLibrary(const string lib_name) : FmiLibrary(lib_name) {} fmi2Status CoSimulationLibrary::doStep(fmi2Real currentCommunicationPoint, fmi2Real communicationStepSize, bool noSetFMUStatePriorToCurrentPoint) const { return loadFunction<fmi2DoStepTYPE *>("fmi2DoStep")(c_, currentCommunicationPoint, communicationStepSize, noSetFMUStatePriorToCurrentPoint ? 1 : 0); } fmi2Status CoSimulationLibrary::cancelStep() const { return loadFunction<fmi2CancelStepTYPE *>("fmi2CancelStep")(c_); } ModelExchangeLibrary::ModelExchangeLibrary(const string lib_name) : FmiLibrary(lib_name) {} <commit_msg>break line<commit_after>/* * The MIT License * * Copyright 2017-2018 Norwegian University 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. */ #include <iostream> #include <fmicpp/fmi2/import/FmiLibrary.hpp> #include <sstream> using namespace std; using namespace fmicpp::fmi2::import; namespace { static const char* status_to_string(fmi2Status status) { switch (status){ case 0: return "OK"; case 1: return "Warning"; case 2: return "Discard"; case 3: return "Error"; case 4: return "Fatal"; case 5: return "Pending"; default: return "Unknown"; } } static void logger(void* fmi2ComponentEnvironment, fmi2String instance_name, fmi2Status status, fmi2String category, fmi2String message, ...) { printf("status = %s, instanceName = %s, category = %s: %s\n", status_to_string(status), instance_name, category, message); } static const fmi2CallbackFunctions callback = { logger, calloc, free, NULL, NULL }; } const char *FmiLibrary::getLastError() const { #ifdef WIN32 std::ostringstream os; os << GetLastError(); return os.str().c_str(); #else return dlerror(); #endif } FmiLibrary::FmiLibrary(string lib_name) { #ifdef WIN32 handle_ = LoadLibrary(lib_name.c_str()); #else handle_ = dlopen(lib_name.c_str(), RTLD_NOW | RTLD_LOCAL); #endif if (!handle_) { cout << getLastError() << endl; string msg = "Unable to load dynamic library '" + lib_name + "'!"; throw runtime_error(msg); } } fmi2String FmiLibrary::getVersion() const { return loadFunction<fmi2GetVersionTYPE *>("fmi2GetVersion")(); } fmi2String FmiLibrary::getTypesPlatform() const { return loadFunction<fmi2GetTypesPlatformTYPE *>("fmi2GetTypesPlatform")(); } void FmiLibrary::instantiate(const string instanceName, const fmi2Type type, const string guid, const string resourceLocation, const bool visible, const bool loggingOn) { c_ = loadFunction<fmi2InstantiateTYPE *>("fmi2Instantiate")(instanceName.c_str(), type, guid.c_str(), resourceLocation.c_str(), &callback, visible ? 1 : 0, loggingOn ? 1 : 0); if (c_ == nullptr) { throw runtime_error("Unable to instantiate FMU instance!"); } } fmi2Status FmiLibrary::setupExperiment(const bool toleranceDefined, const double tolerance, const double startTime, const double stopTime) const { fmi2Boolean stopDefined = stopTime > startTime; return loadFunction<fmi2SetupExperimentTYPE *>("fmi2SetupExperiment") (c_, toleranceDefined ? 1 : 0, tolerance, startTime, stopDefined, stopTime); } fmi2Status FmiLibrary::enterInitializationMode() const { return loadFunction<fmi2EnterInitializationModeTYPE *>("fmi2EnterInitializationMode")(c_); } fmi2Status FmiLibrary::exitInitializationMode() const { return loadFunction<fmi2ExitInitializationModeTYPE *>("fmi2ExitInitializationMode")(c_); } fmi2Status FmiLibrary::reset() const { return loadFunction<fmi2ResetTYPE *>("fmi2Reset")(c_); } fmi2Status FmiLibrary::terminate() { return loadFunction<fmi2TerminateTYPE *>("fmi2Terminate")(c_); } fmi2Status FmiLibrary::readInteger(const fmi2ValueReference vr, fmi2Integer &ref) const { return loadFunction<fmi2GetIntegerTYPE *>("fmi2GetInteger")(c_, &vr, 1, &ref); } fmi2Status FmiLibrary::readInteger(const vector<fmi2ValueReference> &vr, vector<fmi2Integer> &ref) const { return loadFunction<fmi2GetIntegerTYPE *>("fmi2GetInteger")(c_, vr.data(), vr.size(), ref.data()); } fmi2Status FmiLibrary::readReal(const fmi2ValueReference vr, fmi2Real &ref) const { return loadFunction<fmi2GetRealTYPE *>("fmi2GetReal")(c_, &vr, 1, &ref); } fmi2Status FmiLibrary::readReal(const vector<fmi2ValueReference > &vr, vector<fmi2Real> &ref) const { return loadFunction<fmi2GetRealTYPE *>("fmi2GetReal")(c_, vr.data(), vr.size(), ref.data()); } fmi2Status FmiLibrary::readString(const fmi2ValueReference vr, fmi2String &ref) const { return loadFunction<fmi2GetStringTYPE *>("fmi2GetString")(c_, &vr, 1, &ref); } fmi2Status FmiLibrary::readString(const vector<fmi2ValueReference> &vr, vector<fmi2String > &ref) const { return loadFunction<fmi2GetStringTYPE *>("fmi2GetString")(c_, vr.data(), vr.size(), ref.data()); } fmi2Status FmiLibrary::readBoolean(const fmi2ValueReference vr, fmi2Boolean &ref) const { return loadFunction<fmi2GetBooleanTYPE *>("fmi2GetBoolean")(c_, &vr, 1, &ref); } fmi2Status FmiLibrary::readBoolean(const vector<fmi2ValueReference> &vr, vector<fmi2Boolean> &ref) const { return loadFunction<fmi2GetBooleanTYPE *>("fmi2GetBoolean")(c_, vr.data(), vr.size(), ref.data()); } void FmiLibrary::freeInstance() { return loadFunction<fmi2FreeInstanceTYPE *>("fmi2FreeInstance")(c_); } template<class T> T FmiLibrary::loadFunction(const char *function_name) const { #ifdef WIN32 return (T) GetProcAddress(handle_, function_name); #else return (T) dlsym(handle_, function_name); #endif } FmiLibrary::~FmiLibrary() { cout << "FmiLibrary destructor called.." << endl; if (c_) { terminate(); freeInstance(); c_ = nullptr; } if (handle_) { bool success; #ifdef WIN32 success = FreeLibrary(handle_); #else success = (dlclose(handle_) == 0); #endif if (!success) { cout << getLastError() << endl; } handle_ = nullptr; } } CoSimulationLibrary::CoSimulationLibrary(const string lib_name) : FmiLibrary(lib_name) {} fmi2Status CoSimulationLibrary::doStep(fmi2Real currentCommunicationPoint, fmi2Real communicationStepSize, bool noSetFMUStatePriorToCurrentPoint) const { return loadFunction<fmi2DoStepTYPE *>("fmi2DoStep")( c_, currentCommunicationPoint, communicationStepSize, noSetFMUStatePriorToCurrentPoint ? 1 : 0); } fmi2Status CoSimulationLibrary::cancelStep() const { return loadFunction<fmi2CancelStepTYPE *>("fmi2CancelStep")(c_); } ModelExchangeLibrary::ModelExchangeLibrary(const string lib_name) : FmiLibrary(lib_name) {} <|endoftext|>
<commit_before>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * DataManReader.cpp * * Created on: Feb 12, 2018 * Author: Jason Wang */ #include "DataManCommon.h" namespace adios2 { namespace core { namespace engine { DataManCommon::DataManCommon(const std::string engineType, IO &io, const std::string &name, const Mode mode, MPI_Comm mpiComm) : Engine(engineType, io, name, mode, mpiComm), m_FileTransport(mpiComm, m_DebugMode) { // initialize parameters MPI_Comm_rank(mpiComm, &m_MpiRank); MPI_Comm_size(mpiComm, &m_MpiSize); m_IsLittleEndian = helper::IsLittleEndian(); m_IsRowMajor = helper::IsRowMajor(io.m_HostLanguage); GetStringParameter(m_IO.m_Parameters, "WorkflowMode", m_WorkflowMode); GetBoolParameter(m_IO.m_Parameters, "AlwaysProvideLatestTimestep", m_ProvideLatest); if (m_WorkflowMode != "file" && m_WorkflowMode != "stream") { throw(std::invalid_argument( "WorkflowMode parameter for DataMan must be File or Stream")); } m_Channels = m_IO.m_TransportsParameters.size(); if (m_Channels == 0) { m_Channels = 1; m_IO.m_TransportsParameters.push_back({{"Library", "ZMQ"}, {"IPAddress", "127.0.0.1"}, {"Port", "12306"}, {"Name", m_Name}}); } for (size_t i = 0; i < m_Channels; ++i) { m_IO.m_TransportsParameters[i]["Name"] = m_Name + std::to_string(i); } } bool DataManCommon::GetStringParameter(Params &params, std::string key, std::string &value) { auto it = params.find(key); if (it != params.end()) { value = it->second; std::transform(value.begin(), value.end(), value.begin(), ::tolower); return true; } return false; } } // end namespace engine } // end namespace core } // end namespace adios2 <commit_msg>Clang-format<commit_after>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * DataManReader.cpp * * Created on: Feb 12, 2018 * Author: Jason Wang */ #include "DataManCommon.h" namespace adios2 { namespace core { namespace engine { DataManCommon::DataManCommon(const std::string engineType, IO &io, const std::string &name, const Mode mode, MPI_Comm mpiComm) : Engine(engineType, io, name, mode, mpiComm), m_FileTransport(mpiComm, m_DebugMode) { // initialize parameters MPI_Comm_rank(mpiComm, &m_MpiRank); MPI_Comm_size(mpiComm, &m_MpiSize); m_IsLittleEndian = helper::IsLittleEndian(); m_IsRowMajor = helper::IsRowMajor(io.m_HostLanguage); GetStringParameter(m_IO.m_Parameters, "WorkflowMode", m_WorkflowMode); GetBoolParameter(m_IO.m_Parameters, "AlwaysProvideLatestTimestep", m_ProvideLatest); if (m_WorkflowMode != "file" && m_WorkflowMode != "stream") { throw(std::invalid_argument( "WorkflowMode parameter for DataMan must be File or Stream")); } m_Channels = m_IO.m_TransportsParameters.size(); if (m_Channels == 0) { m_Channels = 1; m_IO.m_TransportsParameters.push_back({{"Library", "ZMQ"}, {"IPAddress", "127.0.0.1"}, {"Port", "12306"}, {"Name", m_Name}}); } for (size_t i = 0; i < m_Channels; ++i) { m_IO.m_TransportsParameters[i]["Name"] = m_Name + std::to_string(i); } } bool DataManCommon::GetStringParameter(Params &params, std::string key, std::string &value) { auto it = params.find(key); if (it != params.end()) { value = it->second; std::transform(value.begin(), value.end(), value.begin(), ::tolower); return true; } return false; } } // end namespace engine } // end namespace core } // end namespace adios2 <|endoftext|>
<commit_before>#include "common/api/os_sys_calls_impl.h" #include "common/common/assert.h" #include "common/common/fmt.h" #include "common/common/thread_impl.h" #include "common/filesystem/watcher_impl.h" namespace Envoy { namespace Filesystem { WatcherImpl::WatcherImpl(Event::Dispatcher& dispatcher, Api::Api& api) : api_(api), os_sys_calls_(Api::OsSysCallsSingleton::get()) { os_fd_t socks[2]; Api::SysCallIntResult result = os_sys_calls_.socketpair(AF_INET, SOCK_STREAM, IPPROTO_TCP, socks); ASSERT(result.rc_ == 0); read_handle_ = std::make_unique<Network::IoSocketHandleImpl>(socks[0], false, AF_INET); result = read_handle_->setBlocking(false); ASSERT(result.rc_ == 0); write_handle_ = std::make_unique<Network::IoSocketHandleImpl>(socks[1], false, AF_INET); result = write_handle_->setBlocking(false); ASSERT(result.rc_ == 0); read_handle_->initializeFileEvent( dispatcher, [this](uint32_t events) -> void { ASSERT(events == Event::FileReadyType::Read); onDirectoryEvent(); }, Event::FileTriggerType::Level, Event::FileReadyType::Read); thread_exit_event_ = ::CreateEvent(nullptr, false, false, nullptr); ASSERT(thread_exit_event_ != NULL); keep_watching_ = true; // See comments in WorkerImpl::start for the naming convention. Thread::Options options{absl::StrCat("wat:", dispatcher.name())}; watch_thread_ = thread_factory_.createThread([this]() -> void { watchLoop(); }, options); } WatcherImpl::~WatcherImpl() { const BOOL rc = ::SetEvent(thread_exit_event_); ASSERT(rc); watch_thread_->join(); for (auto& entry : callback_map_) { ::CloseHandle(entry.second->dir_handle_); ::CloseHandle(entry.second->overlapped_.hEvent); } ::CloseHandle(thread_exit_event_); } void WatcherImpl::addWatch(absl::string_view path, uint32_t events, OnChangedCb cb) { if (path == Platform::null_device_path) { return; } const PathSplitResult result = api_.fileSystem().splitPathFromFilename(path); // ReadDirectoryChangesW only has a Unicode version, so we need // to use wide strings here const std::wstring directory = wstring_converter_.from_bytes(std::string(result.directory_)); const std::wstring file = wstring_converter_.from_bytes(std::string(result.file_)); const HANDLE dir_handle = CreateFileW( directory.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL); if (dir_handle == INVALID_HANDLE_VALUE) { throw EnvoyException( fmt::format("unable to open directory {}: {}", result.directory_, GetLastError())); } std::string fii_key(sizeof(FILE_ID_INFO), '\0'); RELEASE_ASSERT( GetFileInformationByHandleEx(dir_handle, FileIdInfo, &fii_key[0], sizeof(FILE_ID_INFO)), fmt::format("unable to identify directory {}: {}", result.directory_, GetLastError())); if (callback_map_.find(fii_key) != callback_map_.end()) { CloseHandle(dir_handle); } else { callback_map_[fii_key] = std::make_unique<DirectoryWatch>(); callback_map_[fii_key]->dir_handle_ = dir_handle; callback_map_[fii_key]->buffer_.resize(16384); callback_map_[fii_key]->watcher_ = this; // According to Microsoft docs, "the hEvent member of the OVERLAPPED structure is not used by // the system, so you can use it yourself". We will use it for synchronization of the completion // routines HANDLE event_handle = ::CreateEvent(nullptr, false, false, nullptr); RELEASE_ASSERT(event_handle, fmt::format("CreateEvent failed: {}", GetLastError())); callback_map_[fii_key]->overlapped_.hEvent = event_handle; dir_watch_complete_events_.push_back(event_handle); // send the first ReadDirectoryChangesW request to our watch thread. This ensures that all of // the io completion routines will run in that thread DWORD rc = ::QueueUserAPC(&issueFirstRead, static_cast<Thread::ThreadImplWin32*>(watch_thread_.get())->handle(), reinterpret_cast<ULONG_PTR>(callback_map_[fii_key].get())); RELEASE_ASSERT(rc, fmt::format("QueueUserAPC failed: {}", GetLastError())); // wait for issueFirstRead to confirm that it has issued a call to ReadDirectoryChangesW rc = ::WaitForSingleObject(event_handle, INFINITE); RELEASE_ASSERT(rc == WAIT_OBJECT_0, fmt::format("WaitForSingleObject failed: {}", GetLastError())); ENVOY_LOG(debug, "created watch for directory: '{}' handle: {}", result.directory_, dir_handle); } callback_map_[fii_key]->watches_.push_back({file, events, cb}); ENVOY_LOG(debug, "added watch for file '{}' in directory '{}'", result.file_, result.directory_); } void WatcherImpl::onDirectoryEvent() { while (true) { char data = 0; const auto result = read_handle_->recv(&data, sizeof(data), 0); if (result.err_ && result.err_->getErrorCode() == Api::IoError::IoErrorCode::Again) { return; } RELEASE_ASSERT(result.err_ == nullptr, fmt::format("recv errored: {}", result.err_)); if (data == 0) { // no callbacks to run; this is just a notification that a DirectoryWatch exited return; } CbClosure callback; bool exists = active_callbacks_.try_pop(callback); RELEASE_ASSERT(exists, "expected callback, found none"); ENVOY_LOG(debug, "executing callback"); callback(); } } void WatcherImpl::issueFirstRead(ULONG_PTR param) { DirectoryWatch* dir_watch = reinterpret_cast<DirectoryWatch*>(param); // Since the first member in each DirectoryWatch is an OVERLAPPED, we can pass // a pointer to DirectoryWatch as the OVERLAPPED for ReadDirectoryChangesW. Then, the // completion routine can use its OVERLAPPED* parameter to access the DirectoryWatch see: // https://docs.microsoft.com/en-us/windows/desktop/ipc/named-pipe-server-using-completion-routines ReadDirectoryChangesW(dir_watch->dir_handle_, &(dir_watch->buffer_[0]), dir_watch->buffer_.capacity(), false, FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE, nullptr, reinterpret_cast<LPOVERLAPPED>(param), &directoryChangeCompletion); const BOOL rc = ::SetEvent(dir_watch->overlapped_.hEvent); ASSERT(rc); } void WatcherImpl::endDirectoryWatch(Network::IoHandle& io_handle, HANDLE event_handle) { const BOOL rc = ::SetEvent(event_handle); ASSERT(rc); // let libevent know that a ReadDirectoryChangesW call returned Buffer::OwnedImpl buffer; constexpr absl::string_view data{"a"}; buffer.add(data); auto result = io_handle.write(buffer); RELEASE_ASSERT(result.rc_ == 1, fmt::format("failed to write 1 byte: {}", result.err_->getErrorDetails())); } void WatcherImpl::directoryChangeCompletion(DWORD err, DWORD num_bytes, LPOVERLAPPED overlapped) { DirectoryWatch* dir_watch = reinterpret_cast<DirectoryWatch*>(overlapped); WatcherImpl* watcher = dir_watch->watcher_; PFILE_NOTIFY_INFORMATION fni = reinterpret_cast<PFILE_NOTIFY_INFORMATION>(&dir_watch->buffer_[0]); if (err == ERROR_OPERATION_ABORTED) { ENVOY_LOG(debug, "ReadDirectoryChangesW aborted, exiting"); endDirectoryWatch(*watcher->write_handle_, dir_watch->overlapped_.hEvent); return; } else if (err != 0) { ENVOY_LOG(error, "ReadDirectoryChangesW errored: {}, exiting", err); endDirectoryWatch(*watcher->write_handle_, dir_watch->overlapped_.hEvent); return; } else if (num_bytes < sizeof(_FILE_NOTIFY_INFORMATION)) { ENVOY_LOG(error, "ReadDirectoryChangesW returned {} bytes, expected {}, exiting", num_bytes, sizeof(_FILE_NOTIFY_INFORMATION)); endDirectoryWatch(*watcher->write_handle_, dir_watch->overlapped_.hEvent); return; } DWORD next_entry = 0; do { fni = reinterpret_cast<PFILE_NOTIFY_INFORMATION>(reinterpret_cast<char*>(fni) + next_entry); // the length of the file name is given in bytes, not wide characters std::wstring file(fni->FileName, fni->FileNameLength / 2); ENVOY_LOG(debug, "notification: handle: {} action: {:x} file: {}", dir_watch->dir_handle_, fni->Action, watcher->wstring_converter_.to_bytes(file)); uint32_t events = 0; if (fni->Action == FILE_ACTION_RENAMED_NEW_NAME) { events |= Events::MovedTo; } if (fni->Action == FILE_ACTION_MODIFIED) { events |= Events::Modified; } constexpr absl::string_view data{"a"}; for (FileWatch& watch : dir_watch->watches_) { if (watch.file_ == file && (watch.events_ & events)) { ENVOY_LOG(debug, "matched callback: file: {}", watcher->wstring_converter_.to_bytes(file)); const auto cb = watch.cb_; const auto cb_closure = [cb, events]() -> void { cb(events); }; watcher->active_callbacks_.push(cb_closure); // write a byte to the other end of the socket that libevent is watching // this tells the libevent callback to pull this callback off the active_callbacks_ // queue. We do this so that the callbacks are executed in the main libevent loop, // not in this completion routine Buffer::OwnedImpl buffer; buffer.add(data); auto result = watcher->write_handle_->write(buffer); RELEASE_ASSERT(result.rc_ == 1, fmt::format("failed to write 1 byte: {}", result.err_->getErrorDetails())); } } next_entry = fni->NextEntryOffset; } while (next_entry != 0); if (!watcher->keep_watching_.load()) { ENVOY_LOG(debug, "ending watch on directory: handle: {}", dir_watch->dir_handle_); endDirectoryWatch(*watcher->write_handle_, dir_watch->overlapped_.hEvent); return; } ReadDirectoryChangesW(dir_watch->dir_handle_, &(dir_watch->buffer_[0]), dir_watch->buffer_.capacity(), false, FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE, nullptr, overlapped, directoryChangeCompletion); } void WatcherImpl::watchLoop() { while (keep_watching_.load()) { DWORD wait = WaitForSingleObjectEx(thread_exit_event_, INFINITE, true); switch (wait) { case WAIT_OBJECT_0: // object is getting destroyed, exit the loop keep_watching_.store(false); break; case WAIT_IO_COMPLETION: // an IO completion routine finished, nothing to do break; default: ENVOY_LOG(error, "WaitForSingleObjectEx: {}, GetLastError: {}, exiting", wait, GetLastError()); keep_watching_.store(false); } } for (auto& entry : callback_map_) { ::CancelIoEx(entry.second->dir_handle_, nullptr); } const int num_directories = dir_watch_complete_events_.size(); if (num_directories > 0) { while (true) { DWORD wait = ::WaitForMultipleObjectsEx(num_directories, &dir_watch_complete_events_[0], true, INFINITE, true); if (WAIT_OBJECT_0 <= wait && wait < (WAIT_OBJECT_0 + num_directories)) { // we have no pending IO remaining return; } else if (wait == WAIT_IO_COMPLETION) { // an io completion routine finished, keep waiting continue; } else { ENVOY_LOG(error, "WaitForMultipleObjectsEx: {}, GetLastError: {}, exiting", wait, GetLastError()); return; } } } } } // namespace Filesystem } // namespace Envoy <commit_msg>remove memory allocation in WatcherImpl for Windows (#14408)<commit_after>#include "common/api/os_sys_calls_impl.h" #include "common/common/assert.h" #include "common/common/fmt.h" #include "common/common/thread_impl.h" #include "common/filesystem/watcher_impl.h" namespace Envoy { namespace Filesystem { WatcherImpl::WatcherImpl(Event::Dispatcher& dispatcher, Api::Api& api) : api_(api), os_sys_calls_(Api::OsSysCallsSingleton::get()) { os_fd_t socks[2]; Api::SysCallIntResult result = os_sys_calls_.socketpair(AF_INET, SOCK_STREAM, IPPROTO_TCP, socks); ASSERT(result.rc_ == 0); read_handle_ = std::make_unique<Network::IoSocketHandleImpl>(socks[0], false, AF_INET); result = read_handle_->setBlocking(false); ASSERT(result.rc_ == 0); write_handle_ = std::make_unique<Network::IoSocketHandleImpl>(socks[1], false, AF_INET); result = write_handle_->setBlocking(false); ASSERT(result.rc_ == 0); read_handle_->initializeFileEvent( dispatcher, [this](uint32_t events) -> void { ASSERT(events == Event::FileReadyType::Read); onDirectoryEvent(); }, Event::FileTriggerType::Level, Event::FileReadyType::Read); thread_exit_event_ = ::CreateEvent(nullptr, false, false, nullptr); ASSERT(thread_exit_event_ != NULL); keep_watching_ = true; // See comments in WorkerImpl::start for the naming convention. Thread::Options options{absl::StrCat("wat:", dispatcher.name())}; watch_thread_ = thread_factory_.createThread([this]() -> void { watchLoop(); }, options); } WatcherImpl::~WatcherImpl() { const BOOL rc = ::SetEvent(thread_exit_event_); ASSERT(rc); watch_thread_->join(); for (auto& entry : callback_map_) { ::CloseHandle(entry.second->dir_handle_); ::CloseHandle(entry.second->overlapped_.hEvent); } ::CloseHandle(thread_exit_event_); } void WatcherImpl::addWatch(absl::string_view path, uint32_t events, OnChangedCb cb) { if (path == Platform::null_device_path) { return; } const PathSplitResult result = api_.fileSystem().splitPathFromFilename(path); // ReadDirectoryChangesW only has a Unicode version, so we need // to use wide strings here const std::wstring directory = wstring_converter_.from_bytes(std::string(result.directory_)); const std::wstring file = wstring_converter_.from_bytes(std::string(result.file_)); const HANDLE dir_handle = CreateFileW( directory.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL); if (dir_handle == INVALID_HANDLE_VALUE) { throw EnvoyException( fmt::format("unable to open directory {}: {}", result.directory_, GetLastError())); } std::string fii_key(sizeof(FILE_ID_INFO), '\0'); RELEASE_ASSERT( GetFileInformationByHandleEx(dir_handle, FileIdInfo, &fii_key[0], sizeof(FILE_ID_INFO)), fmt::format("unable to identify directory {}: {}", result.directory_, GetLastError())); if (callback_map_.find(fii_key) != callback_map_.end()) { CloseHandle(dir_handle); } else { callback_map_[fii_key] = std::make_unique<DirectoryWatch>(); callback_map_[fii_key]->dir_handle_ = dir_handle; callback_map_[fii_key]->buffer_.resize(16384); callback_map_[fii_key]->watcher_ = this; // According to Microsoft docs, "the hEvent member of the OVERLAPPED structure is not used by // the system, so you can use it yourself". We will use it for synchronization of the completion // routines HANDLE event_handle = ::CreateEvent(nullptr, false, false, nullptr); RELEASE_ASSERT(event_handle, fmt::format("CreateEvent failed: {}", GetLastError())); callback_map_[fii_key]->overlapped_.hEvent = event_handle; dir_watch_complete_events_.push_back(event_handle); // send the first ReadDirectoryChangesW request to our watch thread. This ensures that all of // the io completion routines will run in that thread DWORD rc = ::QueueUserAPC(&issueFirstRead, static_cast<Thread::ThreadImplWin32*>(watch_thread_.get())->handle(), reinterpret_cast<ULONG_PTR>(callback_map_[fii_key].get())); RELEASE_ASSERT(rc, fmt::format("QueueUserAPC failed: {}", GetLastError())); // wait for issueFirstRead to confirm that it has issued a call to ReadDirectoryChangesW rc = ::WaitForSingleObject(event_handle, INFINITE); RELEASE_ASSERT(rc == WAIT_OBJECT_0, fmt::format("WaitForSingleObject failed: {}", GetLastError())); ENVOY_LOG(debug, "created watch for directory: '{}' handle: {}", result.directory_, dir_handle); } callback_map_[fii_key]->watches_.push_back({file, events, cb}); ENVOY_LOG(debug, "added watch for file '{}' in directory '{}'", result.file_, result.directory_); } void WatcherImpl::onDirectoryEvent() { while (true) { char data = 0; const auto result = read_handle_->recv(&data, sizeof(data), 0); if (result.err_ && result.err_->getErrorCode() == Api::IoError::IoErrorCode::Again) { return; } RELEASE_ASSERT(result.err_ == nullptr, fmt::format("recv errored: {}", result.err_)); if (data == 0) { // no callbacks to run; this is just a notification that a DirectoryWatch exited return; } CbClosure callback; bool exists = active_callbacks_.try_pop(callback); RELEASE_ASSERT(exists, "expected callback, found none"); ENVOY_LOG(debug, "executing callback"); callback(); } } void WatcherImpl::issueFirstRead(ULONG_PTR param) { DirectoryWatch* dir_watch = reinterpret_cast<DirectoryWatch*>(param); // Since the first member in each DirectoryWatch is an OVERLAPPED, we can pass // a pointer to DirectoryWatch as the OVERLAPPED for ReadDirectoryChangesW. Then, the // completion routine can use its OVERLAPPED* parameter to access the DirectoryWatch see: // https://docs.microsoft.com/en-us/windows/desktop/ipc/named-pipe-server-using-completion-routines ReadDirectoryChangesW(dir_watch->dir_handle_, &(dir_watch->buffer_[0]), dir_watch->buffer_.capacity(), false, FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE, nullptr, reinterpret_cast<LPOVERLAPPED>(param), &directoryChangeCompletion); const BOOL rc = ::SetEvent(dir_watch->overlapped_.hEvent); ASSERT(rc); } void WatcherImpl::endDirectoryWatch(Network::IoHandle& io_handle, HANDLE event_handle) { const BOOL rc = ::SetEvent(event_handle); ASSERT(rc); // let libevent know that a ReadDirectoryChangesW call returned Buffer::OwnedImpl buffer; constexpr absl::string_view data{"a"}; buffer.add(data); auto result = io_handle.write(buffer); RELEASE_ASSERT(result.rc_ == 1, fmt::format("failed to write 1 byte: {}", result.err_->getErrorDetails())); } void WatcherImpl::directoryChangeCompletion(DWORD err, DWORD num_bytes, LPOVERLAPPED overlapped) { DirectoryWatch* dir_watch = reinterpret_cast<DirectoryWatch*>(overlapped); WatcherImpl* watcher = dir_watch->watcher_; PFILE_NOTIFY_INFORMATION fni = reinterpret_cast<PFILE_NOTIFY_INFORMATION>(&dir_watch->buffer_[0]); if (err == ERROR_OPERATION_ABORTED) { ENVOY_LOG(debug, "ReadDirectoryChangesW aborted, exiting"); endDirectoryWatch(*watcher->write_handle_, dir_watch->overlapped_.hEvent); return; } else if (err != 0) { ENVOY_LOG(error, "ReadDirectoryChangesW errored: {}, exiting", err); endDirectoryWatch(*watcher->write_handle_, dir_watch->overlapped_.hEvent); return; } else if (num_bytes < sizeof(_FILE_NOTIFY_INFORMATION)) { ENVOY_LOG(error, "ReadDirectoryChangesW returned {} bytes, expected {}, exiting", num_bytes, sizeof(_FILE_NOTIFY_INFORMATION)); endDirectoryWatch(*watcher->write_handle_, dir_watch->overlapped_.hEvent); return; } DWORD next_entry = 0; do { fni = reinterpret_cast<PFILE_NOTIFY_INFORMATION>(reinterpret_cast<char*>(fni) + next_entry); // the length of the file name is given in bytes, not wide characters std::wstring file(fni->FileName, fni->FileNameLength / 2); ENVOY_LOG(debug, "notification: handle: {} action: {:x} file: {}", dir_watch->dir_handle_, fni->Action, watcher->wstring_converter_.to_bytes(file)); uint32_t events = 0; if (fni->Action == FILE_ACTION_RENAMED_NEW_NAME) { events |= Events::MovedTo; } if (fni->Action == FILE_ACTION_MODIFIED) { events |= Events::Modified; } constexpr absl::string_view data{"a"}; for (FileWatch& watch : dir_watch->watches_) { if (watch.file_ == file && (watch.events_ & events)) { ENVOY_LOG(debug, "matched callback: file: {}", watcher->wstring_converter_.to_bytes(file)); const auto cb = watch.cb_; const auto cb_closure = [cb, events]() -> void { cb(events); }; watcher->active_callbacks_.push(cb_closure); // write a byte to the other end of the socket that libevent is watching // this tells the libevent callback to pull this callback off the active_callbacks_ // queue. We do this so that the callbacks are executed in the main libevent loop, // not in this completion routine Buffer::RawSlice buffer{(void*)data.data(), 1}; auto result = watcher->write_handle_->writev(&buffer, 1); RELEASE_ASSERT(result.rc_ == 1, fmt::format("failed to write 1 byte: {}", result.err_->getErrorDetails())); } } next_entry = fni->NextEntryOffset; } while (next_entry != 0); if (!watcher->keep_watching_.load()) { ENVOY_LOG(debug, "ending watch on directory: handle: {}", dir_watch->dir_handle_); endDirectoryWatch(*watcher->write_handle_, dir_watch->overlapped_.hEvent); return; } ReadDirectoryChangesW(dir_watch->dir_handle_, &(dir_watch->buffer_[0]), dir_watch->buffer_.capacity(), false, FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE, nullptr, overlapped, directoryChangeCompletion); } void WatcherImpl::watchLoop() { while (keep_watching_.load()) { DWORD wait = WaitForSingleObjectEx(thread_exit_event_, INFINITE, true); switch (wait) { case WAIT_OBJECT_0: // object is getting destroyed, exit the loop keep_watching_.store(false); break; case WAIT_IO_COMPLETION: // an IO completion routine finished, nothing to do break; default: ENVOY_LOG(error, "WaitForSingleObjectEx: {}, GetLastError: {}, exiting", wait, GetLastError()); keep_watching_.store(false); } } for (auto& entry : callback_map_) { ::CancelIoEx(entry.second->dir_handle_, nullptr); } const int num_directories = dir_watch_complete_events_.size(); if (num_directories > 0) { while (true) { DWORD wait = ::WaitForMultipleObjectsEx(num_directories, &dir_watch_complete_events_[0], true, INFINITE, true); if (WAIT_OBJECT_0 <= wait && wait < (WAIT_OBJECT_0 + num_directories)) { // we have no pending IO remaining return; } else if (wait == WAIT_IO_COMPLETION) { // an io completion routine finished, keep waiting continue; } else { ENVOY_LOG(error, "WaitForMultipleObjectsEx: {}, GetLastError: {}, exiting", wait, GetLastError()); return; } } } } } // namespace Filesystem } // namespace Envoy <|endoftext|>
<commit_before>/***************************************************************************** FILE : generate_mesh_netgen.cpp DESCRIPTION : This interface is used to call netgen internally inside CMGUI. CMGUI will generate triangular surface and export the surface into netgen. After netgen returns the volume mesh, CMGUI will visualize them to the user. ==============================================================================*/ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is cmgui. * * The Initial Developer of the Original Code is * Auckland Uniservices Ltd, Auckland, New Zealand. * Portions created by the Initial Developer are Copyright (C) 2005 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "graphics/triangle_mesh.hpp" extern "C" { #include <stdio.h> #include <stddef.h> #include <stdlib.h> #include <math.h> #include "general/debug.h" #include "finite_element/generate_mesh_netgen.h" #include "finite_element/finite_element.h" #include "finite_element/finite_element_region.h" #include "finite_element/finite_element_helper.h" #include "computed_field/computed_field.h" #include "computed_field/computed_field_wrappers.h" } #include "graphics/triangle_mesh.hpp" namespace nglib { #include <nglib.h> } using namespace nglib; // Netgen Meshing Parameters class struct Generate_netgen_parameters { double maxh; double fineness; int secondorder; Triangle_mesh *trimesh; };/*struct Generate_netgen_parameters*/ int set_netgen_parameters_trimesh(struct Generate_netgen_parameters *para, void *trimesh) { ENTER(set_netgen_parameters_trimesh); int return_code=0; Triangle_mesh* tri_mesh_tmp; if(para==NULL) return return_code; if(trimesh==NULL) return return_code; tri_mesh_tmp=(Triangle_mesh*)trimesh; para->trimesh=tri_mesh_tmp; return_code=1; LEAVE; return return_code; } int set_netgen_parameters_fineness(struct Generate_netgen_parameters *para, double fineness) { ENTER(set_netgen_parameters_fineness); int return_code=0; if(para==NULL) return return_code; para->fineness=fineness; return_code=1; LEAVE; return return_code; } int set_netgen_parameters_maxh(struct Generate_netgen_parameters *para, double maxh) { ENTER(set_netgen_parameters_maxh); int return_code=0; if(para==NULL) return return_code; para->maxh=maxh; return_code=1; LEAVE; return return_code; } int set_netgen_parameters_secondorder(struct Generate_netgen_parameters *para, int secondorder) { ENTER(set_netgen_parameters_secondorder); int return_code=0; if(para==NULL) return return_code; para->secondorder=secondorder; return_code=1; LEAVE; return return_code; } struct Generate_netgen_parameters * create_netgen_parameters() { ENTER(create_netgen_parameters); struct Generate_netgen_parameters *para; para= new struct Generate_netgen_parameters(); LEAVE; return para; } int release_netgen_parameters(struct Generate_netgen_parameters *para) { ENTER(release_netgen_parameters); int return_code=0; if(para==NULL) return return_code; delete para; return_code=1; LEAVE; return return_code; } int generate_mesh_netgen(struct FE_region *fe_region, void *netgen_para_void)//(struct FE_region *fe_region, void *netgen_para_void) { ENTER(generate_mesh_netgen); Generate_netgen_parameters *generate_netgen_para = static_cast<Generate_netgen_parameters *>(netgen_para_void); Triangle_mesh *trimesh=generate_netgen_para->trimesh; int return_code; Ng_Mesh * mesh; Ng_STL_Geometry * geom; Ng_Meshing_Parameters *mp=new Ng_Meshing_Parameters(); mp->maxh=generate_netgen_para->maxh; mp->fineness=generate_netgen_para->fineness; mp->secondorder=generate_netgen_para->secondorder; /******************************* *for testing *mp.maxh=100000; *mp.fineness = 0.5; *mp.secondorder = 0; ******************************/ Ng_Init(); geom=Ng_STL_NewGeometry(); const Mesh_triangle_list triangle_list = trimesh->get_triangle_list(); Mesh_triangle_list_const_iterator triangle_iter; float coord1[3], coord2[3],coord3[3]; double dcoord1[3], dcoord2[3], dcoord3[3]; const Triangle_vertex *vertex1, *vertex2, *vertex3; for (triangle_iter = triangle_list.begin(); triangle_iter!=triangle_list.end(); ++triangle_iter) { (*triangle_iter)->get_vertexes(&vertex1/*point 1*/,&vertex2/*point 2*/,&vertex3/*point 3*/); vertex1->get_coordinates(coord1, coord1+1,coord1+2); vertex2->get_coordinates(coord2, coord2+1,coord2+2); vertex3->get_coordinates(coord3, coord3+1,coord3+2); dcoord1[0] = (double)coord1[0]; dcoord1[1] = (double)coord1[1]; dcoord1[2] = (double)coord1[2]; dcoord2[0] = (double)coord2[0]; dcoord2[1] = (double)coord2[1]; dcoord2[2] = (double)coord2[2]; dcoord3[0] = (double)coord3[0]; dcoord3[1] = (double)coord3[1]; dcoord3[2] = (double)coord3[2]; Ng_STL_AddTriangle(geom/*new geometry*/, dcoord1/*point 1*/, dcoord2/*point 2*/, dcoord3/*point 3*/); } //////////////////////////////// //for testing //geom=Ng_STL_LoadGeometry("part1.stl"); //////////////////////////////// return_code=Ng_STL_InitSTLGeometry(geom); if(return_code!=NG_OK) { Ng_Exit(); return 0; } mesh = Ng_NewMesh (); return_code=Ng_STL_MakeEdges(geom, mesh, mp); if(return_code!=NG_OK) { Ng_Exit(); return 0; } return_code=Ng_STL_GenerateSurfaceMesh(geom, mesh, mp); if(return_code!=NG_OK) { Ng_Exit(); return 0; } /************************************************************** * export the surface mesh and volume mesh in netgen format * this line might be deleted in the future **************************************************************/ //Ng_SaveMesh (mesh, "surface.vol"); /////////////////////////////////////////////////////////////////////////// return_code=Ng_GenerateVolumeMesh(mesh,mp); if(return_code!=NG_OK) { Ng_Exit(); return 0; } //Ng_SaveMesh (mesh, "volume.vol"); /**************************************************************/ FE_region_begin_change(fe_region); /* create a 3-D coordinate field*/ FE_field *coordinate_field = FE_field_create_coordinate_3d(fe_region,(char*)"coordinate"); ACCESS(FE_field)(coordinate_field); /* create and fill nodes*/ struct FE_node *template_node = CREATE(FE_node)( /*cm_node_identifier*/1, fe_region, /*template_node*/NULL); return_code = define_FE_field_at_node_simple( template_node, coordinate_field, /*number_of_derivatives*/0, /*derivative_value_types*/NULL); const int number_of_nodes = Ng_GetNP(mesh); FE_value coordinates[3]; double coor_tmp[3]; int initial_identifier = FE_region_get_last_FE_nodes_idenifier(fe_region)+1; int i; for (i = 0; i < number_of_nodes; i++) { Ng_GetPoint (mesh, i+1/*index in netgen starts from 1*/, coor_tmp); coordinates[0] = coor_tmp[0]; coordinates[1] = coor_tmp[1]; coordinates[2] = coor_tmp[2]; int identifier = i + initial_identifier; struct FE_node *node = CREATE(FE_node)(identifier, /*fe_region*/NULL, template_node); FE_region_merge_FE_node(fe_region, node); ACCESS(FE_node)(node); int number_of_values_confirmed; return_code=set_FE_nodal_field_FE_value_values( coordinate_field, node, coordinates, &number_of_values_confirmed); DEACCESS(FE_node)(&node); } DESTROY(FE_node)(&template_node); /* establish mode which automates creation of shared faces*/ FE_region_begin_define_faces(fe_region); struct CM_element_information element_identifier; FE_element *element; FE_element *template_element; /* create a tetrahedron with linear simplex field*/ template_element = FE_element_create_with_simplex_shape(fe_region, /*dimension*/3); set_FE_element_number_of_nodes(template_element, 4); FE_element_define_field_simple(template_element, coordinate_field, LINEAR_SIMPLEX); const int number_of_elements = Ng_GetNE(mesh); int nodal_idx[4]; for (i = 0 ; i < number_of_elements; i++) { Ng_GetVolumeElement (mesh, i+1, nodal_idx); element_identifier.type = CM_ELEMENT; element_identifier.number = FE_region_get_next_FE_element_identifier(fe_region, CM_ELEMENT, i); element = CREATE(FE_element)(&element_identifier, (struct FE_element_shape *)NULL, (struct FE_region *)NULL, template_element); ACCESS(FE_element)(element); return_code=set_FE_element_node(element, 0, FE_region_get_FE_node_from_identifier(fe_region,nodal_idx[0])); return_code=set_FE_element_node(element, 1, FE_region_get_FE_node_from_identifier(fe_region,nodal_idx[1])); return_code=set_FE_element_node(element, 2, FE_region_get_FE_node_from_identifier(fe_region,nodal_idx[2])); return_code=set_FE_element_node(element, 3, FE_region_get_FE_node_from_identifier(fe_region,nodal_idx[3])); FE_region_merge_FE_element_and_faces_and_nodes(fe_region, element); DEACCESS(FE_element)(&element); } DEACCESS(FE_element)(&template_element); /* must remember to end define faces mode*/ FE_region_end_define_faces(fe_region); DEACCESS(FE_field)(&coordinate_field); FE_region_end_change(fe_region); if (mesh) Ng_DeleteMesh (mesh); Ng_Exit(); LEAVE; return return_code; } /* generate_mesh_netgen */ <commit_msg><commit_after>/***************************************************************************** FILE : generate_mesh_netgen.cpp DESCRIPTION : This interface is used to call netgen internally inside CMGUI. CMGUI will generate triangular surface and export the surface into netgen. After netgen returns the volume mesh, CMGUI will visualize them to the user. ==============================================================================*/ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is cmgui. * * The Initial Developer of the Original Code is * Auckland Uniservices Ltd, Auckland, New Zealand. * Portions created by the Initial Developer are Copyright (C) 2005 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "graphics/triangle_mesh.hpp" extern "C" { #include <stdio.h> #include <stddef.h> #include <stdlib.h> #include <math.h> #include "general/debug.h" #include "finite_element/generate_mesh_netgen.h" #include "finite_element/finite_element.h" #include "finite_element/finite_element_region.h" #include "finite_element/finite_element_helper.h" #include "computed_field/computed_field.h" #include "computed_field/computed_field_wrappers.h" } #include "graphics/triangle_mesh.hpp" namespace nglib { #include <nglib.h> } using namespace nglib; // Netgen Meshing Parameters class struct Generate_netgen_parameters { double maxh; double fineness; int secondorder; Triangle_mesh *trimesh; char *meshsize_filename; };/*struct Generate_netgen_parameters*/ /***************************************************************************//** * Calls set_netgen_parameters_trimesh for setting the triangular surface mesh * * @param para Pointer to a parameter set for netgen. * @param trimesh Pointer to a triangular surface mesh for netgen. * @return 1 if setting is successful * 0 if setting is failed */ int set_netgen_parameters_trimesh(struct Generate_netgen_parameters *para, void *trimesh) { ENTER(set_netgen_parameters_trimesh); int return_code=0; Triangle_mesh* tri_mesh_tmp; if(para==NULL) return return_code; if(trimesh==NULL) return return_code; tri_mesh_tmp=(Triangle_mesh*)trimesh; para->trimesh=tri_mesh_tmp; return_code=1; LEAVE; return return_code; } /***************************************************************************//** * Calls set_netgen_parameters_trimesh for setting the fineness of volumetric mesh * * @param para Pointer to a parameter set for netgen. * @param fineness is the fineness of volumetric mesh * @return 1 if setting is successful * 0 if setting is failed */ int set_netgen_parameters_fineness(struct Generate_netgen_parameters *para, double fineness) { ENTER(set_netgen_parameters_fineness); int return_code=0; if(para==NULL) return return_code; para->fineness=fineness; return_code=1; LEAVE; return return_code; } /***************************************************************************//** * Calls set_netgen_parameters_maxh for setting the maximum length of volumetric element * * @param para Pointer to a parameter set for netgen. * @param maxh is the maximum length of volumetric element * @return 1 if setting is successful * 0 if setting is failed */ int set_netgen_parameters_maxh(struct Generate_netgen_parameters *para, double maxh) { ENTER(set_netgen_parameters_maxh); int return_code=0; if(para==NULL) return return_code; para->maxh=maxh; return_code=1; LEAVE; return return_code; } /***************************************************************************//** * Calls set_netgen_parameters_secondorder for setting the secondorder switch * * @param para Pointer to a parameter set for netgen. * @param secondorder is switch for secondorder * @return 1 if setting is successful * 0 if setting is failed */ int set_netgen_parameters_secondorder(struct Generate_netgen_parameters *para, double secondorder) { ENTER(set_netgen_parameters_secondorder); int return_code=0; if(para==NULL) return return_code; para->secondorder=secondorder; return_code=1; LEAVE; return return_code; } /***************************************************************************//** * Calls set_netgen_parameters_meshsize_filename for setting mesh size file name * * @param para Pointer to a parameter set for netgen. * @param meshsize_filename is mesh size file name * @return 1 if setting is successful * 0 if setting is failed */ int set_netgen_parameters_meshsize_filename(struct Generate_netgen_parameters *para, char* meshsize_filename) { ENTER(set_netgen_parameters_meshsize_filename); int return_code=0; if(para==NULL) return return_code; para->meshsize_filename=meshsize_filename; return_code=1; LEAVE; return return_code; } /***************************************************************************//** * Calls create_netgen_parameters for creating a parameter set for netgen. * * @param para Pointer to a parameter set for netgen. * @return 1 if creating is successful * 0 if creating is failed */ struct Generate_netgen_parameters * create_netgen_parameters() { ENTER(create_netgen_parameters); struct Generate_netgen_parameters *para; para= new struct Generate_netgen_parameters(); LEAVE; return para; } /***************************************************************************//** * Calls release_netgen_parameters for releasing a parameter set for netgen. * * @param para Pointer to a parameter set for netgen. * @return 1 if releasing is successful * 0 if releasing is failed */ int release_netgen_parameters(struct Generate_netgen_parameters *para) { ENTER(release_netgen_parameters); int return_code=0; if(para==NULL) return return_code; delete para; return_code=1; LEAVE; return return_code; } /***************************************************************************//** * Calls generate_mesh_netgen for invoking netgen and will visualize the 3D mesh automatically. * * @param fe_region Pointer to finite element which must be initialised to contain the * meshing object. It will not change in this call. * @param netgen_para_void Pointer to parameters for the specification of meshing. It comes with * such information:pointer to the triangular surface mesh, parameters to control the quality of * volume mesh * @return 1 if meshsing is successful * 0 if meshing is failed */ int generate_mesh_netgen(struct FE_region *fe_region, void *netgen_para_void)//(struct FE_region *fe_region, void *netgen_para_void) { ENTER(generate_mesh_netgen); Generate_netgen_parameters *generate_netgen_para = static_cast<Generate_netgen_parameters *>(netgen_para_void); Triangle_mesh *trimesh=generate_netgen_para->trimesh; int return_code; Ng_Mesh * mesh; Ng_STL_Geometry * geom; Ng_Meshing_Parameters *mp=new Ng_Meshing_Parameters(); mp->maxh=generate_netgen_para->maxh; mp->fineness=generate_netgen_para->fineness; mp->secondorder=generate_netgen_para->secondorder; mp->meshsize_filename=generate_netgen_para->meshsize_filename; /******************************* *for testing *mp.maxh=100000; *mp.fineness = 0.5; *mp.secondorder = 0; ******************************/ Ng_Init(); geom=Ng_STL_NewGeometry(); const Mesh_triangle_list triangle_list = trimesh->get_triangle_list(); Mesh_triangle_list_const_iterator triangle_iter; float coord1[3], coord2[3],coord3[3]; double dcoord1[3], dcoord2[3], dcoord3[3]; const Triangle_vertex *vertex1, *vertex2, *vertex3; for (triangle_iter = triangle_list.begin(); triangle_iter!=triangle_list.end(); ++triangle_iter) { (*triangle_iter)->get_vertexes(&vertex1/*point 1*/,&vertex2/*point 2*/,&vertex3/*point 3*/); vertex1->get_coordinates(coord1, coord1+1,coord1+2); vertex2->get_coordinates(coord2, coord2+1,coord2+2); vertex3->get_coordinates(coord3, coord3+1,coord3+2); dcoord1[0] = (double)coord1[0]; dcoord1[1] = (double)coord1[1]; dcoord1[2] = (double)coord1[2]; dcoord2[0] = (double)coord2[0]; dcoord2[1] = (double)coord2[1]; dcoord2[2] = (double)coord2[2]; dcoord3[0] = (double)coord3[0]; dcoord3[1] = (double)coord3[1]; dcoord3[2] = (double)coord3[2]; Ng_STL_AddTriangle(geom/*new geometry*/, dcoord1/*point 1*/, dcoord2/*point 2*/, dcoord3/*point 3*/); } //////////////////////////////// //for testing //geom=Ng_STL_LoadGeometry("part1.stl"); //////////////////////////////// return_code=Ng_STL_InitSTLGeometry(geom); if(return_code!=NG_OK) {Ng_Exit();return 0;} mesh = Ng_NewMesh (); return_code=Ng_STL_MakeEdges(geom, mesh, mp); if(return_code!=NG_OK) {Ng_Exit();return 0;} return_code=Ng_STL_GenerateSurfaceMesh(geom, mesh, mp); if(return_code!=NG_OK) {Ng_Exit();return 0;} /************************************************************** * export the surface mesh and volume mesh in netgen format * this line might be delted in the future **************************************************************/ //Ng_SaveMesh (mesh, "surface.vol"); /////////////////////////////////////////////////////////////////////////// //return_code=Ng_GenerateVolumeMesh(mesh,mp); //if(return_code!=NG_OK) {Ng_Exit();return 0;} //Ng_SaveMesh (mesh, "volume.vol"); /**************************************************************/ FE_region_begin_change(fe_region); /* create a 3-D coordinate field*/ FE_field *coordinate_field = FE_field_create_coordinate_3d(fe_region,(char*)"coordinate"); ACCESS(FE_field)(coordinate_field); /* create and fill nodes*/ struct FE_node *template_node = CREATE(FE_node)(/*cm_node_identifier*/1, fe_region, /*template_node*/NULL); return_code = define_FE_field_at_node_simple(template_node, coordinate_field, /*number_of_derivatives*/0, /*derivative_value_types*/NULL); const int number_of_nodes = Ng_GetNP(mesh); FE_value coordinates[3]; double coor_tmp[3]; int initial_identifier = FE_region_get_last_FE_nodes_idenifier(fe_region)+1; int i; for (i = 0; i < number_of_nodes; i++) { Ng_GetPoint (mesh, i+1/*index in netgen starts from 1*/, coor_tmp); coordinates[0] = coor_tmp[0]; coordinates[1] = coor_tmp[1]; coordinates[2] = coor_tmp[2]; int identifier = i + initial_identifier; struct FE_node *node = CREATE(FE_node)(identifier, /*fe_region*/NULL, template_node); FE_region_merge_FE_node(fe_region, node); ACCESS(FE_node)(node); int number_of_values_confirmed; return_code=set_FE_nodal_field_FE_value_values(coordinate_field, node, coordinates, &number_of_values_confirmed); DEACCESS(FE_node)(&node); } DESTROY(FE_node)(&template_node); /* establish mode which automates creation of shared faces*/ FE_region_begin_define_faces(fe_region); struct CM_element_information element_identifier; FE_element *element; FE_element *template_element; /* create a tetrahedron with linear simplex field*/ template_element = FE_element_create_with_simplex_shape(fe_region, /*dimension*/3); set_FE_element_number_of_nodes(template_element, 4); FE_element_define_field_simple(template_element, coordinate_field, LINEAR_SIMPLEX); const int number_of_elements = Ng_GetNE(mesh); int nodal_idx[4]; for (i = 0 ; i < number_of_elements; i++) { Ng_GetVolumeElement (mesh, i+1, nodal_idx); element_identifier.type = CM_ELEMENT; element_identifier.number = FE_region_get_next_FE_element_identifier(fe_region, CM_ELEMENT, i); element = CREATE(FE_element)(&element_identifier, (struct FE_element_shape *)NULL, (struct FE_region *)NULL, template_element); ACCESS(FE_element)(element); return_code=set_FE_element_node(element, 0, FE_region_get_FE_node_from_identifier(fe_region,nodal_idx[0])); return_code=set_FE_element_node(element, 1, FE_region_get_FE_node_from_identifier(fe_region,nodal_idx[1])); return_code=set_FE_element_node(element, 2, FE_region_get_FE_node_from_identifier(fe_region,nodal_idx[2])); return_code=set_FE_element_node(element, 3, FE_region_get_FE_node_from_identifier(fe_region,nodal_idx[3])); FE_region_merge_FE_element_and_faces_and_nodes(fe_region, element); DEACCESS(FE_element)(&element); } DEACCESS(FE_element)(&template_element); /* must remember to end define faces mode*/ FE_region_end_define_faces(fe_region); DEACCESS(FE_field)(&coordinate_field); FE_region_end_change(fe_region); if (mesh) Ng_DeleteMesh (mesh); Ng_Exit(); LEAVE; return 1; } /* generate_mesh_netgen */ <|endoftext|>
<commit_before>#ifndef __CLITL_HPP__ #define __CLITL_HPP__ #include <cstdio> #include <locale> #include <ostream> #include <string> #include <tuple> #include <utility> #ifdef UNIX #include <sys/ioctl.h> #include <termios.h> #include <unistd.h> #elif WIN32 #include <conio.h> #include <Windows.h> #endif namespace clitl { /* Color class */ enum class color { #ifdef UNIX DEFAULT = 0, BLACK = 0, RED = 1, GREEN = 2, BROWN = 3, BLUE = 4, MAGENTA = 5, CYAN = 6, WHITE = 7, #elif WIN32 DEFAULT = 0x7, BLACK = 0x0, RED = 0x4, GREEN = 0x2, BROWN = 0x7, // Worthless BLUE = 0x1, MAGENTA = 0x7, // Worthless CYAN = 0x9, WHITE = 0x7, #endif }; /* Basic definitions and containers */ typedef int coord_t; //typedef int colornum_t; template <typename coordT, typename charT, typename traits = std::char_traits<charT>, typename Alloc = std::allocator<charT> > class basic_cli_object { std::pair<coordT, coordT> origin; std::pair<coordT, coordT> endpoint; std::basic_string<charT, traits, Alloc> str; color foreground; color background; public: explicit basic_cli_object( const std::pair<coordT, coordT>& origin = std::pair<coordT, coordT>(0, 0), const std::pair<coordT, coordT>& endpoint = std::pair<coordT, coordT>(0, 0), const std::basic_string<charT, traits, Alloc>& str = std::basic_string<charT, traits, Alloc>(), const color& foreground = clitl::color::WHITE, const color& background = clitl::color::BLACK) : origin(origin), endpoint(endpoint), str(str), foreground(foreground), background(background) {} const basic_cli_object<coordT, charT>& set_origin(const std::pair<coordT, coordT>& coord) { origin = coord; return *this; } const basic_cli_object<coordT, charT>& set_endpoint(const std::pair<coordT, coordT>& coord) { endpoint = coord; return *this; } const basic_cli_object<coordT, charT>& set_string(const std::basic_string<charT, traits, Alloc>& stri) { str = stri; return *this } const basic_cli_object<coordT, charT>& set_foreground(const color& foreg) { foreground = foreg; return *this; } const basic_cli_object<coordT, charT>& set_background(const color& backg) { background = backg; return *this; } const std::pair<coordT, coordT>& get_origin() const { return origin; } const std::pair<coordT, coordT>& get_endpoint() const { return endpoint; } const std::basic_string<charT, traits, Alloc>& get_string() const { return str; } const color& get_foreground() const { return foreground; } const color& get_background() const { return background; } }; template <typename coordT, typename charT = char, typename traits = std::char_traits<charT>, typename Alloc = std::allocator<charT> > class rect : public basic_cli_object<coordT, charT, traits, Alloc> { public: explicit rect( const std::pair<coordT, coordT>& origin = std::pair<coordT, coordT>(0, 0), const std::pair<coordT, coordT>& endpoint = std::pair<coordT, coordT>(0, 0), const color& background = color::WHITE) : basic_cli_object<coordT, charT, traits, Alloc>(origin, endpoint, std::basic_string<charT, traits, Alloc>(" "), color::DEFAULT, background) {} }; template <typename coordT, typename charT, typename traits = std::char_traits<charT>, typename Alloc = std::allocator<charT> > class coloredstring : public basic_cli_object<coordT, charT, traits, Alloc> { public: explicit coloredstring( const std::pair<coordT, coordT>& origin = std::pair<coordT, coordT>(0, 0), const std::pair<coordT, coordT>& endpoint = std::pair<coordT, coordT>(0, 0), const std::basic_string<charT, traits, Alloc>& str = std::basic_string<charT, traits, Alloc>(), const color& foreground = clitl::color::WHITE, const color& background = clitl::color::BLACK) : basic_cli_object<coordT, charT, traits, Alloc>( origin, endpoint, str, foreground, background) {} explicit coloredstring( const std::basic_string<charT, traits, Alloc>& str = std::basic_string<charT, traits, Alloc>(), const color& foreground = clitl::color::WHITE, const color& background = clitl::color::BLACK) : basic_cli_object<coordT, charT, traits, Alloc>( std::pair<coordT, coordT>(0, 0), std::pair<coordT, coordT>(0, 0), str, foreground, background) {} }; /* Output buffer */ template <typename charT, typename traits = std::char_traits<charT> > class basic_outbuf : public std::basic_streambuf<charT, traits> { protected: virtual typename traits::int_type overflow(typename traits::int_type c) { if (std::putchar(c) == EOF) { return traits::eof(); } return traits::not_eof(c); } }; typedef basic_outbuf<char> outbuf; typedef basic_outbuf<wchar_t> woutbuf; /* Output stream */ template <typename charT, typename traits = std::char_traits<charT> > class basic_ostream : public std::basic_ostream<charT, traits> { public: #ifdef UNIX struct winsize wsize; #endif #ifdef WIN32 HANDLE termout_handle; CONSOLE_CURSOR_INFO termout_curinfo; CONSOLE_SCREEN_BUFFER_INFO termout_sbufinfo; #endif explicit basic_ostream(basic_outbuf<charT, traits>* sb) : std::basic_ostream<charT, traits>(sb) { #ifdef UNIX wsize = { 0 }; #elif WIN32 termout_handle = GetStdHandle(STD_OUTPUT_HANDLE); #endif } basic_ostream<charT, traits>& moveto(const std::pair<coord_t, coord_t>& coord) { #ifdef UNIX *this << "\033[" << coord.second << ";" << coord.first << "f"; #elif WIN32 COORD pos = { static_cast<SHORT>(coord.first) - 1, static_cast<SHORT>(coord.second) - 1 }; SetConsoleCursorPosition(termout_handle, pos); #endif return *this; } std::pair<coord_t, coord_t> screensize() { static coord_t column; static coord_t row; #ifdef UNIX column = wsize.ws_col; row = wsize.ws_row; #elif WIN32 GetConsoleScreenBufferInfo(termout_handle, &termout_sbufinfo); column = static_cast<coord_t>(termout_sbufinfo.dwSize.X); row = static_cast<coord_t>(termout_sbufinfo.dwSize.Y); #endif return std::pair<coord_t, coord_t>(column, row); } basic_ostream<charT, traits>& paintmode(color fgd, color bgd) { #ifdef UNIX os << "\033[" << static_cast<int>(30 + fgd) << ";" << static_cast<int>(40 + bwd) << "m" << ; #elif WIN32 SetConsoleTextAttribute(this->termout_handle, static_cast<WORD>(static_cast<int>(fgd) + 0x10 * static_cast<int>(bgd))); #endif return *this; } basic_ostream<charT, traits>& operator<< (basic_ostream<charT, traits>& (*op)(basic_ostream<charT, traits>&)) { return (*op)(*this); } }; typedef basic_ostream<char> ostream; typedef basic_ostream<wchar_t> wostream; template <typename charT, typename traits> basic_ostream<charT, traits>& alternative_system_screenbuffer(basic_ostream<charT, traits>& os) { #if UNIX os << "\033[?1049h"; // Use alternate screen buffer #endif return os; } template <typename charT, typename traits> basic_ostream<charT, traits>& clear(basic_ostream<charT, traits>& os) { #ifdef UNIX os << "\033[2J"; #elif WIN32 COORD startpoint = { 0, 0 }; DWORD dw; GetConsoleScreenBufferInfo(os.termout_handle, &os.termout_sbufinfo); FillConsoleOutputCharacterA(os.termout_handle, ' ', os.termout_sbufinfo.dwSize.X * os.termout_sbufinfo.dwSize.Y, startpoint, &dw); FillConsoleOutputAttribute(os.termout_handle, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE, os.termout_sbufinfo.dwSize.X * os.termout_sbufinfo.dwSize.Y, startpoint, &dw); #endif return os; } template <typename charT, typename traits> basic_ostream<charT, traits>& hide_cursor(basic_ostream<charT, traits>& os) { #ifdef UNIX os << "\033[?25l"; // Hide cursor #elif WIN32 GetConsoleCursorInfo(os.termout_handle, &os.termout_curinfo); os.termout_curinfo.bVisible = 0; SetConsoleCursorInfo(os.termout_handle, &os.termout_curinfo); #endif return os; } template <typename charT, typename traits> basic_ostream<charT, traits>& normal_system_screenbuffer(basic_ostream<charT, traits>& os) { #if UNIX os << "\033[?1049l"; // Use normal screen buffer #endif return os; } template <typename charT, typename traits> basic_ostream<charT, traits>& refresh(basic_ostream<charT, traits>& os) { std::fflush(stdout); return os; } template <typename charT, typename traits> basic_ostream<charT, traits>& show_cursor(basic_ostream<charT, traits>& os) { #if UNIX os << "\033[?25h"; // Show cursor #elif WIN32 CONSOLE_CURSOR_INFO termout_curinfo; GetConsoleCursorInfo(os.termout_handle, &termout_curinfo); termout_curinfo.bVisible = 1; SetConsoleCursorInfo(os.termout_handle, &termout_curinfo); #endif return os; } template <typename charT, typename traits> basic_ostream<charT, traits>& pre_process(basic_ostream<charT, traits>& os) { os << alternative_system_screenbuffer; os << hide_cursor; os << clear; return os; } template <typename charT, typename traits> basic_ostream<charT, traits>& post_process(basic_ostream<charT, traits>& os) { os << clear; os.moveto(std::pair<coord_t, coord_t>(1, 1)); os.paintmode(color::WHITE, color::BLACK); os << normal_system_screenbuffer; os << show_cursor; return os; } template <typename coordT, typename charT, typename traits, typename Alloc> basic_ostream<charT, traits>& operator<< (basic_ostream<charT, traits>& os, const coloredstring<coordT, charT, traits, Alloc>& cs) { os.paintmode(cs.get_foreground(), cs.get_background()); os << cs.get_string().c_str(); return os; } template <typename coordT, typename charT, typename traits, typename Alloc> basic_ostream<charT, traits>& operator<< (basic_ostream<charT, traits>& os, const rect<coordT, charT, traits, Alloc>& re) { for (int i = re.get_origin().first; i <= re.get_endpoint().first; ++i) { for (int j = re.get_origin().second; j <= re.get_endpoint().second; ++j) { os.moveto(std::pair<coord_t, coord_t>(i, j)); os << coloredstring<coordT, charT, traits, Alloc>( re.get_string(), re.get_foreground(), re.get_background()); } } return os; } /* Input buffer */ /* Input stream */ template <typename charT, typename traits = std::char_traits<charT> > class basic_istream : public std::basic_istream<charT, traits> { }; typedef basic_istream<char> istream; typedef basic_istream<wchar_t> wistream; } #endif <commit_msg>Fix for bash<commit_after>#ifndef __CLITL_HPP__ #define __CLITL_HPP__ #include <cstdio> #include <locale> #include <ostream> #include <string> #include <tuple> #include <utility> #ifdef UNIX #include <sys/ioctl.h> #include <termios.h> #include <unistd.h> #elif WIN32 #include <conio.h> #include <Windows.h> #endif namespace clitl { /* Color class */ enum class color { #ifdef UNIX DEFAULT = 0, BLACK = 0, RED = 1, GREEN = 2, BROWN = 3, BLUE = 4, MAGENTA = 5, CYAN = 6, WHITE = 7, #elif WIN32 DEFAULT = 0x7, BLACK = 0x0, RED = 0x4, GREEN = 0x2, BROWN = 0x7, // Worthless BLUE = 0x1, MAGENTA = 0x7, // Worthless CYAN = 0x9, WHITE = 0x7, #endif }; /* Basic definitions and containers */ typedef int coord_t; //typedef int colornum_t; template <typename coordT, typename charT, typename traits = std::char_traits<charT>, typename Alloc = std::allocator<charT> > class basic_cli_object { std::pair<coordT, coordT> origin; std::pair<coordT, coordT> endpoint; std::basic_string<charT, traits, Alloc> str; color foreground; color background; public: explicit basic_cli_object( const std::pair<coordT, coordT>& origin = std::pair<coordT, coordT>(0, 0), const std::pair<coordT, coordT>& endpoint = std::pair<coordT, coordT>(0, 0), const std::basic_string<charT, traits, Alloc>& str = std::basic_string<charT, traits, Alloc>(), const color& foreground = color::WHITE, const color& background = color::BLACK) : origin(origin), endpoint(endpoint), str(str), foreground(foreground), background(background) {} const basic_cli_object<coordT, charT>& set_origin(const std::pair<coordT, coordT>& coord) { origin = coord; return *this; } const basic_cli_object<coordT, charT>& set_endpoint(const std::pair<coordT, coordT>& coord) { endpoint = coord; return *this; } const basic_cli_object<coordT, charT>& set_string(const std::basic_string<charT, traits, Alloc>& stri) { str = stri; return *this; } const basic_cli_object<coordT, charT>& set_foreground(const color& foreg) { foreground = foreg; return *this; } const basic_cli_object<coordT, charT>& set_background(const color& backg) { background = backg; return *this; } const std::pair<coordT, coordT>& get_origin() const { return origin; } const std::pair<coordT, coordT>& get_endpoint() const { return endpoint; } const std::basic_string<charT, traits, Alloc>& get_string() const { return str; } const color& get_foreground() const { return foreground; } const color& get_background() const { return background; } }; template <typename coordT, typename charT = char, typename traits = std::char_traits<charT>, typename Alloc = std::allocator<charT> > class rect : public basic_cli_object<coordT, charT, traits, Alloc> { public: explicit rect( const std::pair<coordT, coordT>& origin = std::pair<coordT, coordT>(0, 0), const std::pair<coordT, coordT>& endpoint = std::pair<coordT, coordT>(0, 0), const color& background = color::WHITE) : basic_cli_object<coordT, charT, traits, Alloc>(origin, endpoint, std::basic_string<charT, traits, Alloc>(" "), color::DEFAULT, background) {} }; template <typename coordT, typename charT, typename traits = std::char_traits<charT>, typename Alloc = std::allocator<charT> > class coloredstring : public basic_cli_object<coordT, charT, traits, Alloc> { public: explicit coloredstring( const std::pair<coordT, coordT>& origin = std::pair<coordT, coordT>(0, 0), const std::pair<coordT, coordT>& endpoint = std::pair<coordT, coordT>(0, 0), const std::basic_string<charT, traits, Alloc>& str = std::basic_string<charT, traits, Alloc>(), const color& foreground = clitl::color::WHITE, const color& background = clitl::color::BLACK) : basic_cli_object<coordT, charT, traits, Alloc>( origin, endpoint, str, foreground, background) {} explicit coloredstring( const std::basic_string<charT, traits, Alloc>& str = std::basic_string<charT, traits, Alloc>(), const color& foreground = clitl::color::WHITE, const color& background = clitl::color::BLACK) : basic_cli_object<coordT, charT, traits, Alloc>( std::pair<coordT, coordT>(0, 0), std::pair<coordT, coordT>(0, 0), str, foreground, background) {} }; /* Output buffer */ template <typename charT, typename traits = std::char_traits<charT> > class basic_outbuf : public std::basic_streambuf<charT, traits> { protected: virtual typename traits::int_type overflow(typename traits::int_type c) { if (std::putchar(c) == EOF) { return traits::eof(); } return traits::not_eof(c); } }; typedef basic_outbuf<char> outbuf; typedef basic_outbuf<wchar_t> woutbuf; /* Output stream */ template <typename charT, typename traits = std::char_traits<charT> > class basic_ostream : public std::basic_ostream<charT, traits> { public: #ifdef UNIX struct winsize wsize; #endif #ifdef WIN32 HANDLE termout_handle; CONSOLE_CURSOR_INFO termout_curinfo; CONSOLE_SCREEN_BUFFER_INFO termout_sbufinfo; #endif explicit basic_ostream(basic_outbuf<charT, traits>* sb) : std::basic_ostream<charT, traits>(sb) { #ifdef UNIX wsize = { 0 }; #elif WIN32 termout_handle = GetStdHandle(STD_OUTPUT_HANDLE); #endif } basic_ostream<charT, traits>& moveto(const std::pair<coord_t, coord_t>& coord) { #ifdef UNIX *this << "\033[" << coord.second << ";" << coord.first << "f"; #elif WIN32 COORD pos = { static_cast<SHORT>(coord.first) - 1, static_cast<SHORT>(coord.second) - 1 }; SetConsoleCursorPosition(termout_handle, pos); #endif return *this; } std::pair<coord_t, coord_t> screensize() { static coord_t column; static coord_t row; #ifdef UNIX column = wsize.ws_col; row = wsize.ws_row; #elif WIN32 GetConsoleScreenBufferInfo(termout_handle, &termout_sbufinfo); column = static_cast<coord_t>(termout_sbufinfo.dwSize.X); row = static_cast<coord_t>(termout_sbufinfo.dwSize.Y); #endif return std::pair<coord_t, coord_t>(column, row); } basic_ostream<charT, traits>& paintmode(color fgd, color bgd) { #ifdef UNIX *this << "\033[" << 30 + static_cast<int>(fgd) << ";" << 40 + static_cast<int>(bgd) << "m"; #elif WIN32 SetConsoleTextAttribute(this->termout_handle, static_cast<WORD>(static_cast<int>(fgd) + 0x10 * static_cast<int>(bgd))); #endif return *this; } basic_ostream<charT, traits>& operator<< (basic_ostream<charT, traits>& (*op)(basic_ostream<charT, traits>&)) { return (*op)(*this); } }; typedef basic_ostream<char> ostream; typedef basic_ostream<wchar_t> wostream; template <typename charT, typename traits> basic_ostream<charT, traits>& alternative_system_screenbuffer(basic_ostream<charT, traits>& os) { #if UNIX os << "\033[?1049h"; // Use alternate screen buffer #endif return os; } template <typename charT, typename traits> basic_ostream<charT, traits>& clear(basic_ostream<charT, traits>& os) { #ifdef UNIX os << "\033[2J"; #elif WIN32 COORD startpoint = { 0, 0 }; DWORD dw; GetConsoleScreenBufferInfo(os.termout_handle, &os.termout_sbufinfo); FillConsoleOutputCharacterA(os.termout_handle, ' ', os.termout_sbufinfo.dwSize.X * os.termout_sbufinfo.dwSize.Y, startpoint, &dw); FillConsoleOutputAttribute(os.termout_handle, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE, os.termout_sbufinfo.dwSize.X * os.termout_sbufinfo.dwSize.Y, startpoint, &dw); #endif return os; } template <typename charT, typename traits> basic_ostream<charT, traits>& hide_cursor(basic_ostream<charT, traits>& os) { #ifdef UNIX os << "\033[?25l"; // Hide cursor #elif WIN32 GetConsoleCursorInfo(os.termout_handle, &os.termout_curinfo); os.termout_curinfo.bVisible = 0; SetConsoleCursorInfo(os.termout_handle, &os.termout_curinfo); #endif return os; } template <typename charT, typename traits> basic_ostream<charT, traits>& normal_system_screenbuffer(basic_ostream<charT, traits>& os) { #if UNIX os << "\033[?1049l"; // Use normal screen buffer #endif return os; } template <typename charT, typename traits> basic_ostream<charT, traits>& refresh(basic_ostream<charT, traits>& os) { std::fflush(stdout); return os; } template <typename charT, typename traits> basic_ostream<charT, traits>& show_cursor(basic_ostream<charT, traits>& os) { #if UNIX os << "\033[?25h"; // Show cursor #elif WIN32 CONSOLE_CURSOR_INFO termout_curinfo; GetConsoleCursorInfo(os.termout_handle, &termout_curinfo); termout_curinfo.bVisible = 1; SetConsoleCursorInfo(os.termout_handle, &termout_curinfo); #endif return os; } template <typename charT, typename traits> basic_ostream<charT, traits>& pre_process(basic_ostream<charT, traits>& os) { os << alternative_system_screenbuffer; os << hide_cursor; os << clear; return os; } template <typename charT, typename traits> basic_ostream<charT, traits>& post_process(basic_ostream<charT, traits>& os) { os.paintmode(color::WHITE, color::BLACK); os << clear; os.moveto(std::pair<coord_t, coord_t>(1, 1)); os << show_cursor; os << normal_system_screenbuffer; return os; } template <typename coordT, typename charT, typename traits, typename Alloc> basic_ostream<charT, traits>& operator<< (basic_ostream<charT, traits>& os, const coloredstring<coordT, charT, traits, Alloc>& cs) { os.paintmode(cs.get_foreground(), cs.get_background()); os << cs.get_string().c_str(); return os; } template <typename coordT, typename charT, typename traits, typename Alloc> basic_ostream<charT, traits>& operator<< (basic_ostream<charT, traits>& os, const rect<coordT, charT, traits, Alloc>& re) { for (int i = re.get_origin().first; i <= re.get_endpoint().first; ++i) { for (int j = re.get_origin().second; j <= re.get_endpoint().second; ++j) { os.moveto(std::pair<coord_t, coord_t>(i, j)); os << coloredstring<coordT, charT, traits, Alloc>( re.get_string(), re.get_foreground(), re.get_background()); } } return os; } /* Input buffer */ /* Input stream */ template <typename charT, typename traits = std::char_traits<charT> > class basic_istream : public std::basic_istream<charT, traits> { }; typedef basic_istream<char> istream; typedef basic_istream<wchar_t> wistream; } #endif <|endoftext|>
<commit_before>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #include "cvtest.h" using namespace cv; using namespace std; #define WRITE_KEYPOINTS 0 #define WRITE_DESCRIPTORS 0 class CV_CalonderTest : public CvTest { public: CV_CalonderTest() : CvTest("CalonderDescriptorExtractor", "CalonderDescriptorExtractor::compute") {} protected: void run(int); }; void writeMatInBin( const Mat& mat, const string& filename ) { FILE* f = fopen( filename.c_str(), "wb"); int type = mat.type(); fwrite( (void*)&mat.rows, sizeof(int), 1, f ); fwrite( (void*)&mat.cols, sizeof(int), 1, f ); fwrite( (void*)&type, sizeof(int), 1, f ); fwrite( (void*)&mat.step, sizeof(int), 1, f ); fwrite( (void*)mat.data, 1, mat.step*mat.rows, f ); fclose(f); } Mat readMatFromBin( const string& filename ) { FILE* f = fopen( filename.c_str(), "rb" ); int rows, cols, type, step; fread( (void*)&rows, sizeof(int), 1, f ); fread( (void*)&cols, sizeof(int), 1, f ); fread( (void*)&type, sizeof(int), 1, f ); fread( (void*)&step, sizeof(int), 1, f ); uchar* data = (uchar*)cvAlloc(step*rows); fread( (void*)data, 1, step*rows, f ); fclose(f); return Mat( rows, cols, type, data ); } void CV_CalonderTest::run(int) { string dir = string(ts->get_data_path()) + "/calonder"; Mat img = imread(dir +"/boat.png",0); if( img.empty() ) { ts->printf(CvTS::LOG, "Test image can not be read\n"); ts->set_failed_test_info( CvTS::FAIL_INVALID_TEST_DATA ); return; } vector<KeyPoint> keypoints; #if WRITE_KEYPOINTS FastFeatureDetector fd; fd.detect(img, keypoints); FileStorage fs( dir + "/keypoints.xml", FileStorage::WRITE ); if( fs.isOpened() ) write( fs, "keypoints", keypoints ); else { ts->printf(CvTS::LOG, "File for writting keypoints can not be opened\n"); ts->set_failed_test_info( CvTS::FAIL_INVALID_TEST_DATA ); return; } #else FileStorage fs( dir + "/keypoints.xml", FileStorage::READ); if( fs.isOpened() ) read( fs.getFirstTopLevelNode(), keypoints ); else { ts->printf(CvTS::LOG, "File for reading keypoints can not be opened\n"); ts->set_failed_test_info( CvTS::FAIL_INVALID_TEST_DATA ); return; } #endif //WRITE_KEYPOINTS CalonderDescriptorExtractor<float> fde(dir + "/classifier.rtc"); Mat fdescriptors; double t = getTickCount(); fde.compute(img, keypoints, fdescriptors); t = getTickCount() - t; ts->printf(CvTS::LOG, "\nAverage time of computiting float descriptor = %g ms\n", t/((double)cvGetTickFrequency()*1000.)/fdescriptors.rows ); #if WRITE_DESCRIPTORS assert(fdescriptors.type() == CV_32FC1); writeMatInBin( fdescriptors, dir + "/ros_float_desc" ); #else Mat ros_fdescriptors = readMatFromBin( dir + "/ros_float_desc" ); double fnorm = norm(fdescriptors, ros_fdescriptors, NORM_INF ); ts->printf(CvTS::LOG, "nofm (inf) BTW valid and calculated float descriptors = %f\n", fnorm ); if( fnorm > FLT_EPSILON ) ts->set_failed_test_info( CvTS::FAIL_BAD_ACCURACY ); #endif // WRITE_DESCRIPTORS CalonderDescriptorExtractor<uchar> cde(dir + "/classifier.rtc"); Mat cdescriptors; t = getTickCount(); cde.compute(img, keypoints, cdescriptors); t = getTickCount() - t; ts->printf(CvTS::LOG, "Average time of computiting uchar descriptor = %g ms\n", t/((double)cvGetTickFrequency()*1000.)/cdescriptors.rows ); #if WRITE_DESCRIPTORS assert(cdescriptors.type() == CV_8UC1); writeMatInBin( cdescriptors, dir + "/ros_uchar_desc" ); #else Mat ros_cdescriptors = readMatFromBin( dir + "/ros_uchar_desc" ); double cnorm = norm(cdescriptors, ros_cdescriptors, NORM_INF ); ts->printf(CvTS::LOG, "nofm (inf) BTW valid and calculated uchar descriptors = %f\n", cnorm ); if( cnorm > FLT_EPSILON + 1 ) // + 1 because of quantization float to uchar ts->set_failed_test_info( CvTS::FAIL_BAD_ACCURACY ); #endif // WRITE_DESCRIPTORS } #if CV_SSE2 CV_CalonderTest calonderTest; #endif // CV_SSE2 <commit_msg>renamed test<commit_after>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #include "cvtest.h" using namespace cv; using namespace std; #define WRITE_KEYPOINTS 0 #define WRITE_DESCRIPTORS 0 class CV_CalonderTest : public CvTest { public: CV_CalonderTest() : CvTest("calonder-descriptor-extractor", "CalonderDescriptorExtractor::compute") {} protected: void run(int); }; void writeMatInBin( const Mat& mat, const string& filename ) { FILE* f = fopen( filename.c_str(), "wb"); int type = mat.type(); fwrite( (void*)&mat.rows, sizeof(int), 1, f ); fwrite( (void*)&mat.cols, sizeof(int), 1, f ); fwrite( (void*)&type, sizeof(int), 1, f ); fwrite( (void*)&mat.step, sizeof(int), 1, f ); fwrite( (void*)mat.data, 1, mat.step*mat.rows, f ); fclose(f); } Mat readMatFromBin( const string& filename ) { FILE* f = fopen( filename.c_str(), "rb" ); int rows, cols, type, step; fread( (void*)&rows, sizeof(int), 1, f ); fread( (void*)&cols, sizeof(int), 1, f ); fread( (void*)&type, sizeof(int), 1, f ); fread( (void*)&step, sizeof(int), 1, f ); uchar* data = (uchar*)cvAlloc(step*rows); fread( (void*)data, 1, step*rows, f ); fclose(f); return Mat( rows, cols, type, data ); } void CV_CalonderTest::run(int) { string dir = string(ts->get_data_path()) + "/calonder"; Mat img = imread(dir +"/boat.png",0); if( img.empty() ) { ts->printf(CvTS::LOG, "Test image can not be read\n"); ts->set_failed_test_info( CvTS::FAIL_INVALID_TEST_DATA ); return; } vector<KeyPoint> keypoints; #if WRITE_KEYPOINTS FastFeatureDetector fd; fd.detect(img, keypoints); FileStorage fs( dir + "/keypoints.xml", FileStorage::WRITE ); if( fs.isOpened() ) write( fs, "keypoints", keypoints ); else { ts->printf(CvTS::LOG, "File for writting keypoints can not be opened\n"); ts->set_failed_test_info( CvTS::FAIL_INVALID_TEST_DATA ); return; } #else FileStorage fs( dir + "/keypoints.xml", FileStorage::READ); if( fs.isOpened() ) read( fs.getFirstTopLevelNode(), keypoints ); else { ts->printf(CvTS::LOG, "File for reading keypoints can not be opened\n"); ts->set_failed_test_info( CvTS::FAIL_INVALID_TEST_DATA ); return; } #endif //WRITE_KEYPOINTS CalonderDescriptorExtractor<float> fde(dir + "/classifier.rtc"); Mat fdescriptors; double t = getTickCount(); fde.compute(img, keypoints, fdescriptors); t = getTickCount() - t; ts->printf(CvTS::LOG, "\nAverage time of computiting float descriptor = %g ms\n", t/((double)cvGetTickFrequency()*1000.)/fdescriptors.rows ); #if WRITE_DESCRIPTORS assert(fdescriptors.type() == CV_32FC1); writeMatInBin( fdescriptors, dir + "/ros_float_desc" ); #else Mat ros_fdescriptors = readMatFromBin( dir + "/ros_float_desc" ); double fnorm = norm(fdescriptors, ros_fdescriptors, NORM_INF ); ts->printf(CvTS::LOG, "nofm (inf) BTW valid and calculated float descriptors = %f\n", fnorm ); if( fnorm > FLT_EPSILON ) ts->set_failed_test_info( CvTS::FAIL_BAD_ACCURACY ); #endif // WRITE_DESCRIPTORS CalonderDescriptorExtractor<uchar> cde(dir + "/classifier.rtc"); Mat cdescriptors; t = getTickCount(); cde.compute(img, keypoints, cdescriptors); t = getTickCount() - t; ts->printf(CvTS::LOG, "Average time of computiting uchar descriptor = %g ms\n", t/((double)cvGetTickFrequency()*1000.)/cdescriptors.rows ); #if WRITE_DESCRIPTORS assert(cdescriptors.type() == CV_8UC1); writeMatInBin( cdescriptors, dir + "/ros_uchar_desc" ); #else Mat ros_cdescriptors = readMatFromBin( dir + "/ros_uchar_desc" ); double cnorm = norm(cdescriptors, ros_cdescriptors, NORM_INF ); ts->printf(CvTS::LOG, "nofm (inf) BTW valid and calculated uchar descriptors = %f\n", cnorm ); if( cnorm > FLT_EPSILON + 1 ) // + 1 because of quantization float to uchar ts->set_failed_test_info( CvTS::FAIL_BAD_ACCURACY ); #endif // WRITE_DESCRIPTORS } #if CV_SSE2 CV_CalonderTest calonderTest; #endif // CV_SSE2 <|endoftext|>
<commit_before>/* ************************************************************************ * Copyright 2015 Vratis, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ************************************************************************ */ #include <mlopen/kernel_cache.hpp> #include <mlopen/errors.hpp> #include <iostream> #include <iterator> namespace mlopen { Kernel KernelCache::GetKernel(const std::string& algorithm, const std::string& network_config) { std::pair<std::string, std::string> key = std::make_pair(algorithm, network_config); #ifndef NDEBUG std::cout << "key: " << key.first <<" "<< key.second<< std::endl; #endif auto kernel_iterator = kernel_map.find(key); if (kernel_iterator != kernel_map.end()) { return kernel_iterator->second; } else { MLOPEN_THROW("looking for default kernel (does not exist): " + algorithm + ", " + network_config); } } Kernel KernelCache::GetKernel(Handle &h, const std::string& algorithm, const std::string& network_config, const std::string& program_name, const std::string& kernel_name, const std::vector<size_t>& vld, const std::vector<size_t>& vgd, std::string params) { if (params.length() > 0) { // Ensure only one space after the -cl-std. // >1 space can cause an Apple compiler bug. See clSPARSE issue #141. if (params.at(0) != ' ') { params = " " + params; } } std::pair<std::string, std::string> key = std::make_pair(algorithm, network_config); #ifndef NDEBUG std::cout << "key: " << key.first << ',' << key.second << std::endl; #endif Program program; auto program_it = program_map.find(std::make_pair(program_name, params)); if (program_it != program_map.end()) { program = program_it->second; } else { bool is_kernel_str = algorithm.find("GEMM") != std::string::npos; program = h.LoadProgram(program_name, params, is_kernel_str); program_map[std::make_pair(program_name, params)] = program; } Kernel kernel{program, kernel_name, vld, vgd}; // TODO: how to cache kernels which do not have a config? if (!network_config.empty() && !algorithm.empty()) { kernel_map[key] = kernel; } return kernel; } KernelCache::KernelCache() {} } // namespace mlopen <commit_msg>removed comment<commit_after>/* ************************************************************************ * Copyright 2015 Vratis, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ************************************************************************ */ #include <mlopen/kernel_cache.hpp> #include <mlopen/errors.hpp> #include <iostream> #include <iterator> namespace mlopen { Kernel KernelCache::GetKernel(const std::string& algorithm, const std::string& network_config) { std::pair<std::string, std::string> key = std::make_pair(algorithm, network_config); #ifndef NDEBUG std::cout << "key: " << key.first <<" "<< key.second<< std::endl; #endif auto kernel_iterator = kernel_map.find(key); if (kernel_iterator != kernel_map.end()) { return kernel_iterator->second; } else { MLOPEN_THROW("looking for default kernel (does not exist): " + algorithm + ", " + network_config); } } Kernel KernelCache::GetKernel(Handle &h, const std::string& algorithm, const std::string& network_config, const std::string& program_name, const std::string& kernel_name, const std::vector<size_t>& vld, const std::vector<size_t>& vgd, std::string params) { if (params.length() > 0) { // Ensure only one space after the -cl-std. // >1 space can cause an Apple compiler bug. See clSPARSE issue #141. if (params.at(0) != ' ') { params = " " + params; } } std::pair<std::string, std::string> key = std::make_pair(algorithm, network_config); #ifndef NDEBUG std::cout << "key: " << key.first << ',' << key.second << std::endl; #endif Program program; auto program_it = program_map.find(std::make_pair(program_name, params)); if (program_it != program_map.end()) { program = program_it->second; } else { bool is_kernel_str = algorithm.find("GEMM") != std::string::npos; program = h.LoadProgram(program_name, params, is_kernel_str); program_map[std::make_pair(program_name, params)] = program; } Kernel kernel{program, kernel_name, vld, vgd}; if (!network_config.empty() && !algorithm.empty()) { kernel_map[key] = kernel; } return kernel; } KernelCache::KernelCache() {} } // namespace mlopen <|endoftext|>
<commit_before>#include <ap_int.h> #include "best_track.h" using namespace std; //ap_uint<4> zero_count(ap_uint<8> larger); void best_track::zero_count_36bits(ap_uint<36> larger, ap_uint<6> *sum){ ap_uint<6> temp; #pragma HLS INLINE off #pragma HLS LATENCY max=0 #pragma HLS INTERFACE ap_ctrl_none port=return #pragma HLS PIPELINE II=1 temp=0; ap_uint<1> a,b,c,d, a1,b1,c1,d1; ap_uint<1> y0,y1,y2 ,y0a,y1a,y2a; a=larger[3]; b=larger[2]; c=larger[1]; d=larger[0]; a1=larger[7]; b1=larger[6]; c1=larger[5]; d1=larger[4]; ap_uint<8> temp1,temp2,temp3,temp4,temp5; ap_uint<6> sum1,sum2,sum3,sum4,sum5; temp1=larger(7,0); temp2=larger(15,8); temp3=larger(23,16); temp4=larger(31,24); temp5=(ap_uint<4>(0xF),larger(35,32)); sum1=zero_count(temp1); sum2=zero_count(temp2); sum3=zero_count(temp3); sum4=zero_count(temp4); sum5=zero_count(temp5); temp=sum1+sum2+sum3+sum4+sum5; *sum=temp; } <commit_msg>Delete zero_count36bits.cpp<commit_after><|endoftext|>
<commit_before>#include "GamesDBScraper.h" #include "../components/ScraperSearchComponent.h" #include "../components/AsyncReqComponent.h" #include "../Log.h" #include "../pugiXML/pugixml.hpp" #include "../MetaData.h" #include "../Settings.h" #include <boost/assign.hpp> const char* GamesDBScraper::getName() { return "TheGamesDB"; } using namespace PlatformIds; const std::map<PlatformId, const char*> gamesdb_platformid_map = boost::assign::map_list_of (THREEDO, "3DO") (AMIGA, "Amiga") (ARCADE, "Arcade") (ATARI_2600, "Atari 2600") (ATARI_5200, "Atari 5200") (ATARI_7800, "Atari 7800") (ATARI_JAGUAR, "Atari Jaguar") (ATARI_JAGUAR_CD, "Atari Jaguar CD") (ATARI_LYNX, "Atari Lynx") (ATARI_XE, "Atari XE") (COLECOVISION, "Colecovision") (COMMODORE_64, "Commodore 64") (INTELLIVISION, "Intellivision") (MAC_OS, "Mac OS") (XBOX, "Microsoft Xbox") (XBOX_360, "Microsoft Xbox 360") (NEOGEO, "NeoGeo") (NEOGEO_POCKET, "Neo Geo Pocket") (NEOGEO_POCKET_COLOR, "Neo Geo Pocket Color") (NINTENDO_3DS, "Nintendo 3DS") (NINTENDO_64, "Nintendo 64") (NINTENDO_DS, "Nintendo DS") (NINTENDO_ENTERTAINMENT_SYSTEM, "Nintendo Entertainment System (NES)") (GAME_BOY, "Nintendo Game Boy") (GAME_BOY_ADVANCE, "Nintendo Game Boy Advance") (GAME_BOY_COLOR, "Nintendo Game Boy Color") (NINTENDO_GAMECUBE, "Nintendo GameCube") (NINTENDO_WII, "Nintendo Wii") (NINTENDO_WII_U, "Nintendo Wii U") (PC, "PC") (SEGA_32X, "Sega 32X") (SEGA_CD, "Sega CD") (SEGA_DREAMCAST, "Sega Dreamcast") (SEGA_GAME_GEAR, "Sega Game Gear") (SEGA_GENESIS, "Sega Genesis") (SEGA_MASTER_SYSTEM, "Sega Master System") (SEGA_MEGA_DRIVE, "Sega Mega Drive") (SEGA_SATURN, "Sega Saturn") (PLAYSTATION, "Sony Playstation") (PLAYSTATION_2, "Sony Playstation 2") (PLAYSTATION_3, "Sony Playstation 3") (PLAYSTATION_VITA, "Sony Playstation Vita") (PLAYSTATION_PORTABLE, "Sony PSP") (SUPER_NINTENDO, "Super Nintendo (SNES)") (TURBOGRAFX_16, "TurboGrafx 16") (WONDERSWAN, "WonderSwan") (WONDERSWAN_COLOR, "WonderSwan Color") (ZX_SPECTRUM, "Sinclair ZX Spectrum"); std::unique_ptr<ScraperSearchHandle> GamesDBScraper::getResultsAsync(const ScraperSearchParams& params) { std::string path = "/api/GetGame.php?"; std::string cleanName = params.nameOverride; if(cleanName.empty()) cleanName = params.game->getCleanName(); path += "name=" + HttpReq::urlEncode(cleanName); if(params.system->getPlatformId() != PLATFORM_UNKNOWN) { path += "&platform="; path += HttpReq::urlEncode(gamesdb_platformid_map.at(params.system->getPlatformId())); } path = "thegamesdb.net" + path; return std::unique_ptr<ScraperSearchHandle>(new GamesDBHandle(params, path)); } GamesDBHandle::GamesDBHandle(const ScraperSearchParams& params, const std::string& url) : mReq(std::unique_ptr<HttpReq>(new HttpReq(url))) { setStatus(ASYNC_IN_PROGRESS); } void GamesDBHandle::update() { if(mStatus == ASYNC_DONE) return; if(mReq->status() == HttpReq::REQ_IN_PROGRESS) return; if(mReq->status() != HttpReq::REQ_SUCCESS) { std::stringstream ss; ss << "Network error - " << mReq->getErrorMsg(); setError(ss.str()); return; } // our HTTP request was successful // try to build our result list std::vector<ScraperSearchResult> results; pugi::xml_document doc; pugi::xml_parse_result parseResult = doc.load(mReq->getContent().c_str()); if(!parseResult) { setError("Error parsing XML"); return; } pugi::xml_node data = doc.child("Data"); std::string baseImageUrl = data.child("baseImgUrl").text().get(); unsigned int resultNum = 0; pugi::xml_node game = data.child("Game"); while(game && resultNum < MAX_SCRAPER_RESULTS) { ScraperSearchResult result; result.mdl.set("name", game.child("GameTitle").text().get()); result.mdl.set("desc", game.child("Overview").text().get()); boost::posix_time::ptime rd = string_to_ptime(game.child("ReleaseDate").text().get(), "%m/%d/%Y"); result.mdl.setTime("releasedate", rd); result.mdl.set("developer", game.child("Developer").text().get()); result.mdl.set("publisher", game.child("Publisher").text().get()); result.mdl.set("genre", game.child("Genres").first_child().text().get()); result.mdl.set("players", game.child("Players").text().get()); if(Settings::getInstance()->getBool("ScrapeRatings") && game.child("Rating")) { float ratingVal = (game.child("Rating").text().as_int() / 10.0f); std::stringstream ss; ss << ratingVal; result.mdl.set("rating", ss.str()); } pugi::xml_node images = game.child("Images"); if(images) { pugi::xml_node art = images.find_child_by_attribute("boxart", "side", "front"); if(art) { result.thumbnailUrl = baseImageUrl + art.attribute("thumb").as_string(); result.imageUrl = baseImageUrl + art.text().get(); } } results.push_back(result); resultNum++; game = game.next_sibling("Game"); } setStatus(ASYNC_DONE); setResults(results); return; } <commit_msg>Fixed crash when TheGamesDB scraper sees a platform it doesn't support.<commit_after>#include "GamesDBScraper.h" #include "../components/ScraperSearchComponent.h" #include "../components/AsyncReqComponent.h" #include "../Log.h" #include "../pugiXML/pugixml.hpp" #include "../MetaData.h" #include "../Settings.h" #include <boost/assign.hpp> const char* GamesDBScraper::getName() { return "TheGamesDB"; } using namespace PlatformIds; const std::map<PlatformId, const char*> gamesdb_platformid_map = boost::assign::map_list_of (THREEDO, "3DO") (AMIGA, "Amiga") (ARCADE, "Arcade") (ATARI_2600, "Atari 2600") (ATARI_5200, "Atari 5200") (ATARI_7800, "Atari 7800") (ATARI_JAGUAR, "Atari Jaguar") (ATARI_JAGUAR_CD, "Atari Jaguar CD") (ATARI_LYNX, "Atari Lynx") (ATARI_XE, "Atari XE") (COLECOVISION, "Colecovision") (COMMODORE_64, "Commodore 64") (INTELLIVISION, "Intellivision") (MAC_OS, "Mac OS") (XBOX, "Microsoft Xbox") (XBOX_360, "Microsoft Xbox 360") (NEOGEO, "NeoGeo") (NEOGEO_POCKET, "Neo Geo Pocket") (NEOGEO_POCKET_COLOR, "Neo Geo Pocket Color") (NINTENDO_3DS, "Nintendo 3DS") (NINTENDO_64, "Nintendo 64") (NINTENDO_DS, "Nintendo DS") (NINTENDO_ENTERTAINMENT_SYSTEM, "Nintendo Entertainment System (NES)") (GAME_BOY, "Nintendo Game Boy") (GAME_BOY_ADVANCE, "Nintendo Game Boy Advance") (GAME_BOY_COLOR, "Nintendo Game Boy Color") (NINTENDO_GAMECUBE, "Nintendo GameCube") (NINTENDO_WII, "Nintendo Wii") (NINTENDO_WII_U, "Nintendo Wii U") (PC, "PC") (SEGA_32X, "Sega 32X") (SEGA_CD, "Sega CD") (SEGA_DREAMCAST, "Sega Dreamcast") (SEGA_GAME_GEAR, "Sega Game Gear") (SEGA_GENESIS, "Sega Genesis") (SEGA_MASTER_SYSTEM, "Sega Master System") (SEGA_MEGA_DRIVE, "Sega Mega Drive") (SEGA_SATURN, "Sega Saturn") (PLAYSTATION, "Sony Playstation") (PLAYSTATION_2, "Sony Playstation 2") (PLAYSTATION_3, "Sony Playstation 3") (PLAYSTATION_VITA, "Sony Playstation Vita") (PLAYSTATION_PORTABLE, "Sony PSP") (SUPER_NINTENDO, "Super Nintendo (SNES)") (TURBOGRAFX_16, "TurboGrafx 16") (WONDERSWAN, "WonderSwan") (WONDERSWAN_COLOR, "WonderSwan Color") (ZX_SPECTRUM, "Sinclair ZX Spectrum"); std::unique_ptr<ScraperSearchHandle> GamesDBScraper::getResultsAsync(const ScraperSearchParams& params) { std::string path = "/api/GetGame.php?"; std::string cleanName = params.nameOverride; if(cleanName.empty()) cleanName = params.game->getCleanName(); path += "name=" + HttpReq::urlEncode(cleanName); if(params.system->getPlatformId() != PLATFORM_UNKNOWN) { auto platformIt = gamesdb_platformid_map.find(params.system->getPlatformId()); if(platformIt != gamesdb_platformid_map.end()) { path += "&platform="; path += HttpReq::urlEncode(platformIt->second); }else{ LOG(LogWarning) << "TheGamesDB scraper warning - no support for platform " << getPlatformName(params.system->getPlatformId()); } } path = "thegamesdb.net" + path; return std::unique_ptr<ScraperSearchHandle>(new GamesDBHandle(params, path)); } GamesDBHandle::GamesDBHandle(const ScraperSearchParams& params, const std::string& url) : mReq(std::unique_ptr<HttpReq>(new HttpReq(url))) { setStatus(ASYNC_IN_PROGRESS); } void GamesDBHandle::update() { if(mStatus == ASYNC_DONE) return; if(mReq->status() == HttpReq::REQ_IN_PROGRESS) return; if(mReq->status() != HttpReq::REQ_SUCCESS) { std::stringstream ss; ss << "Network error - " << mReq->getErrorMsg(); setError(ss.str()); return; } // our HTTP request was successful // try to build our result list std::vector<ScraperSearchResult> results; pugi::xml_document doc; pugi::xml_parse_result parseResult = doc.load(mReq->getContent().c_str()); if(!parseResult) { setError("Error parsing XML"); return; } pugi::xml_node data = doc.child("Data"); std::string baseImageUrl = data.child("baseImgUrl").text().get(); unsigned int resultNum = 0; pugi::xml_node game = data.child("Game"); while(game && resultNum < MAX_SCRAPER_RESULTS) { ScraperSearchResult result; result.mdl.set("name", game.child("GameTitle").text().get()); result.mdl.set("desc", game.child("Overview").text().get()); boost::posix_time::ptime rd = string_to_ptime(game.child("ReleaseDate").text().get(), "%m/%d/%Y"); result.mdl.setTime("releasedate", rd); result.mdl.set("developer", game.child("Developer").text().get()); result.mdl.set("publisher", game.child("Publisher").text().get()); result.mdl.set("genre", game.child("Genres").first_child().text().get()); result.mdl.set("players", game.child("Players").text().get()); if(Settings::getInstance()->getBool("ScrapeRatings") && game.child("Rating")) { float ratingVal = (game.child("Rating").text().as_int() / 10.0f); std::stringstream ss; ss << ratingVal; result.mdl.set("rating", ss.str()); } pugi::xml_node images = game.child("Images"); if(images) { pugi::xml_node art = images.find_child_by_attribute("boxart", "side", "front"); if(art) { result.thumbnailUrl = baseImageUrl + art.attribute("thumb").as_string(); result.imageUrl = baseImageUrl + art.text().get(); } } results.push_back(result); resultNum++; game = game.next_sibling("Game"); } setStatus(ASYNC_DONE); setResults(results); return; } <|endoftext|>
<commit_before>#include "reader.h" #include <unistd.h> #include <iostream> #include <fcntl.h> #include <assert.h> using std::string; string linkResolve(string name) { char buf[1024]; int rc; for (;;) { rc = readlink(name.c_str(), buf, sizeof buf - 1); if (rc == -1) break; buf[rc] = 0; std::clog << "resolve " << name << " to " << buf << std::endl; if (buf[0] != '/') { auto lastSlash = name.rfind('/'); name = lastSlash == string::npos ? string(buf) : name.substr(0, lastSlash + 1) + string(buf); } else { name = buf; } } return name; } bool FileReader::openfile(int &file, std::string name_) { auto fd = open(name_.c_str(), O_RDONLY); if (fd != -1) { file = fd; name = name_; return true; } return false; } FileReader::FileReader(string name_, int file_) : name(name_) , file(file_) { if (file == -1 && !openfile(file, name_)) throw Exception() << "cannot open file '" << name_ << "': " << strerror(errno); } MemReader::MemReader(char *data_, size_t len_) : data(data_), len(len_) { } size_t MemReader::read(off_t off, size_t count, char *ptr) const { if (off > count) throw Exception() << "read past end of memory"; size_t rc = std::min(count, len - size_t(off)); memcpy(ptr, data + off, rc); return rc; } string MemReader::describe() const { return "from memory image"; } string Reader:: readString(off_t offset) const { char c; string res; for (;;) { readObj(offset++, &c); if (c == 0) break; res += c; } return res; } size_t FileReader::read(off_t off, size_t count, char *ptr) const { if (lseek(file, off, SEEK_SET) == -1) throw Exception() << "seek to " << off << " on " << describe() << " failed: " << strerror(errno); ssize_t rc = ::read(file, ptr, count); if (rc == -1) throw Exception() << "read " << count << " at " << off << " on " << describe() << " failed: " << strerror(errno); return rc; } CacheReader::Page::Page(Reader &r, off_t offset_) : offset(offset_) , len(r.read(offset_, PAGESIZE, data)) { assert(offset_ % PAGESIZE == 0); } CacheReader::CacheReader(std::shared_ptr<Reader> upstream_) : upstream(upstream_) { } CacheReader::~CacheReader() { for (auto i : pages) delete i; } CacheReader::Page * CacheReader::getPage(off_t pageoff) const { Page *p; for (auto i = pages.begin(); i != pages.end(); ++i) { p = *i; if (p->offset == pageoff) { // move page to front. pages.erase(i); pages.push_front(p); return p; } } p = new Page(*upstream, pageoff); if (pages.size() == MAXPAGES) { delete pages.back(); pages.pop_back(); } pages.push_front(p); return p; } size_t CacheReader::read(off_t absoff, size_t count, char *ptr) const { off_t startoff = absoff; for (;;) { if (count == 0) break; size_t offsetOfDataInPage = absoff % PAGESIZE; off_t offsetOfPageInFile = absoff - offsetOfDataInPage; Page *page = getPage(offsetOfPageInFile); if (page == 0) break; size_t chunk = std::min(page->len - offsetOfDataInPage, count); memcpy(ptr, page->data + offsetOfDataInPage, chunk); absoff += chunk; count -= chunk; ptr += chunk; if (page->len != PAGESIZE) break; } return absoff - startoff; } <commit_msg>Fix incorrect bound check<commit_after>#include "reader.h" #include <unistd.h> #include <iostream> #include <fcntl.h> #include <assert.h> using std::string; string linkResolve(string name) { char buf[1024]; int rc; for (;;) { rc = readlink(name.c_str(), buf, sizeof buf - 1); if (rc == -1) break; buf[rc] = 0; std::clog << "resolve " << name << " to " << buf << std::endl; if (buf[0] != '/') { auto lastSlash = name.rfind('/'); name = lastSlash == string::npos ? string(buf) : name.substr(0, lastSlash + 1) + string(buf); } else { name = buf; } } return name; } bool FileReader::openfile(int &file, std::string name_) { auto fd = open(name_.c_str(), O_RDONLY); if (fd != -1) { file = fd; name = name_; return true; } return false; } FileReader::FileReader(string name_, int file_) : name(name_) , file(file_) { if (file == -1 && !openfile(file, name_)) throw Exception() << "cannot open file '" << name_ << "': " << strerror(errno); } MemReader::MemReader(char *data_, size_t len_) : data(data_), len(len_) { } size_t MemReader::read(off_t off, size_t count, char *ptr) const { if (off > len) throw Exception() << "read past end of memory"; size_t rc = std::min(count, len - size_t(off)); memcpy(ptr, data + off, rc); return rc; } string MemReader::describe() const { return "from memory image"; } string Reader:: readString(off_t offset) const { char c; string res; for (;;) { readObj(offset++, &c); if (c == 0) break; res += c; } return res; } size_t FileReader::read(off_t off, size_t count, char *ptr) const { if (lseek(file, off, SEEK_SET) == -1) throw Exception() << "seek to " << off << " on " << describe() << " failed: " << strerror(errno); ssize_t rc = ::read(file, ptr, count); if (rc == -1) throw Exception() << "read " << count << " at " << off << " on " << describe() << " failed: " << strerror(errno); return rc; } CacheReader::Page::Page(Reader &r, off_t offset_) : offset(offset_) , len(r.read(offset_, PAGESIZE, data)) { assert(offset_ % PAGESIZE == 0); } CacheReader::CacheReader(std::shared_ptr<Reader> upstream_) : upstream(upstream_) { } CacheReader::~CacheReader() { for (auto i : pages) delete i; } CacheReader::Page * CacheReader::getPage(off_t pageoff) const { Page *p; for (auto i = pages.begin(); i != pages.end(); ++i) { p = *i; if (p->offset == pageoff) { // move page to front. pages.erase(i); pages.push_front(p); return p; } } p = new Page(*upstream, pageoff); if (pages.size() == MAXPAGES) { delete pages.back(); pages.pop_back(); } pages.push_front(p); return p; } size_t CacheReader::read(off_t absoff, size_t count, char *ptr) const { off_t startoff = absoff; for (;;) { if (count == 0) break; size_t offsetOfDataInPage = absoff % PAGESIZE; off_t offsetOfPageInFile = absoff - offsetOfDataInPage; Page *page = getPage(offsetOfPageInFile); if (page == 0) break; size_t chunk = std::min(page->len - offsetOfDataInPage, count); memcpy(ptr, page->data + offsetOfDataInPage, chunk); absoff += chunk; count -= chunk; ptr += chunk; if (page->len != PAGESIZE) break; } return absoff - startoff; } <|endoftext|>
<commit_before>/* This sample demonstrates the way you can perform independed tasks on the different GPUs */ // Disable some warnings which are caused with CUDA headers #if defined(_MSC_VER) #pragma warning(disable: 4201 4408 4100) #endif #include <iostream> #include "cvconfig.h" #include "opencv2/core/core.hpp" #include "opencv2/cudaarithm.hpp" #ifdef HAVE_TBB # include "tbb/tbb_stddef.h" # if TBB_VERSION_MAJOR*100 + TBB_VERSION_MINOR >= 202 # include "tbb/tbb.h" # include "tbb/task.h" # undef min # undef max # else # undef HAVE_TBB # endif #endif #if !defined(HAVE_CUDA) || !defined(HAVE_TBB) int main() { #if !defined(HAVE_CUDA) std::cout << "CUDA support is required (CMake key 'WITH_CUDA' must be true).\n"; #endif #if !defined(HAVE_TBB) std::cout << "TBB support is required (CMake key 'WITH_TBB' must be true).\n"; #endif return 0; } #else using namespace std; using namespace cv; using namespace cv::cuda; struct Worker { void operator()(int device_id) const; }; int main() { int num_devices = getCudaEnabledDeviceCount(); if (num_devices < 2) { std::cout << "Two or more GPUs are required\n"; return -1; } for (int i = 0; i < num_devices; ++i) { cv::cuda::printShortCudaDeviceInfo(i); DeviceInfo dev_info(i); if (!dev_info.isCompatible()) { std::cout << "CUDA module isn't built for GPU #" << i << " (" << dev_info.name() << ", CC " << dev_info.majorVersion() << dev_info.minorVersion() << "\n"; return -1; } } // Execute calculation in two threads using two GPUs int devices[] = {0, 1}; tbb::parallel_do(devices, devices + 2, Worker()); return 0; } void Worker::operator()(int device_id) const { setDevice(device_id); Mat src(1000, 1000, CV_32F); Mat dst; RNG rng(0); rng.fill(src, RNG::UNIFORM, 0, 1); // CPU works cv::transpose(src, dst); // GPU works GpuMat d_src(src); GpuMat d_dst; cuda::transpose(d_src, d_dst); // Check results bool passed = cv::norm(dst - Mat(d_dst), NORM_INF) < 1e-3; std::cout << "GPU #" << device_id << " (" << DeviceInfo().name() << "): " << (passed ? "passed" : "FAILED") << endl; // Deallocate data here, otherwise deallocation will be performed // after context is extracted from the stack d_src.release(); d_dst.release(); } #endif <commit_msg>Update multi.cpp<commit_after>/* This sample demonstrates the way you can perform independed tasks on the different GPUs */ // Disable some warnings which are caused with CUDA headers #if defined(_MSC_VER) #pragma warning(disable: 4201 4408 4100) #endif #include <iostream> #include "opencv2/cvconfig.h" #include "opencv2/core/core.hpp" #include "opencv2/cudaarithm.hpp" #ifdef HAVE_TBB # include "tbb/tbb_stddef.h" # if TBB_VERSION_MAJOR*100 + TBB_VERSION_MINOR >= 202 # include "tbb/tbb.h" # include "tbb/task.h" # undef min # undef max # else # undef HAVE_TBB # endif #endif #if !defined(HAVE_CUDA) || !defined(HAVE_TBB) int main() { #if !defined(HAVE_CUDA) std::cout << "CUDA support is required (CMake key 'WITH_CUDA' must be true).\n"; #endif #if !defined(HAVE_TBB) std::cout << "TBB support is required (CMake key 'WITH_TBB' must be true).\n"; #endif return 0; } #else using namespace std; using namespace cv; using namespace cv::cuda; struct Worker { void operator()(int device_id) const; }; int main() { int num_devices = getCudaEnabledDeviceCount(); if (num_devices < 2) { std::cout << "Two or more GPUs are required\n"; return -1; } for (int i = 0; i < num_devices; ++i) { cv::cuda::printShortCudaDeviceInfo(i); DeviceInfo dev_info(i); if (!dev_info.isCompatible()) { std::cout << "CUDA module isn't built for GPU #" << i << " (" << dev_info.name() << ", CC " << dev_info.majorVersion() << dev_info.minorVersion() << "\n"; return -1; } } // Execute calculation in two threads using two GPUs int devices[] = {0, 1}; tbb::parallel_do(devices, devices + 2, Worker()); return 0; } void Worker::operator()(int device_id) const { setDevice(device_id); Mat src(1000, 1000, CV_32F); Mat dst; RNG rng(0); rng.fill(src, RNG::UNIFORM, 0, 1); // CPU works cv::transpose(src, dst); // GPU works GpuMat d_src(src); GpuMat d_dst; cuda::transpose(d_src, d_dst); // Check results bool passed = cv::norm(dst - Mat(d_dst), NORM_INF) < 1e-3; std::cout << "GPU #" << device_id << " (" << DeviceInfo().name() << "): " << (passed ? "passed" : "FAILED") << endl; // Deallocate data here, otherwise deallocation will be performed // after context is extracted from the stack d_src.release(); d_dst.release(); } #endif <|endoftext|>
<commit_before>/* * eos - A 3D Morphable Model fitting library written in modern C++11/14. * * File: include/eos/render/detail/texture_extraction_detail.hpp * * Copyright 2014, 2015 Patrik Huber * * 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. */ #pragma once #ifndef TEXTURE_EXTRACTION_DETAIL_HPP_ #define TEXTURE_EXTRACTION_DETAIL_HPP_ #include "eos/core/Rect.hpp" #include "eos/core/Image.hpp" #include "eos/render/detail/render_detail.hpp" #include "glm/vec2.hpp" #include "glm/vec4.hpp" #include "opencv2/core/core.hpp" /** * Implementations of internal functions, not part of the * API we expose and not meant to be used by a user. */ namespace eos { namespace render { namespace detail { /** * Computes whether the given point is inside (or on the border of) the triangle * formed out of the given three vertices. * * @param[in] point The point to check. * @param[in] triV0 First vertex. * @param[in] triV1 Second vertex. * @param[in] triV2 Third vertex. * @return Whether the point is inside the triangle. */ inline bool is_point_in_triangle(cv::Point2f point, cv::Point2f triV0, cv::Point2f triV1, cv::Point2f triV2) { // See http://www.blackpawn.com/texts/pointinpoly/ // Compute vectors cv::Point2f v0 = triV2 - triV0; cv::Point2f v1 = triV1 - triV0; cv::Point2f v2 = point - triV0; // Compute dot products float dot00 = v0.dot(v0); float dot01 = v0.dot(v1); float dot02 = v0.dot(v2); float dot11 = v1.dot(v1); float dot12 = v1.dot(v2); // Compute barycentric coordinates float invDenom = 1 / (dot00 * dot11 - dot01 * dot01); float u = (dot11 * dot02 - dot01 * dot12) * invDenom; float v = (dot00 * dot12 - dot01 * dot02) * invDenom; // Check if point is in triangle return (u >= 0) && (v >= 0) && (u + v < 1); }; /** * Checks whether all pixels in the given triangle are visible and * returns true if and only if the whole triangle is visible. * The vertices should be given in screen coordinates, but with their * z-values preserved, so they can be compared against the depthbuffer. * * Obviously the depthbuffer given should have been created with the same projection * matrix than the texture extraction is called with. * * Also, we don't do perspective-correct interpolation here I think, so only * use it with affine and orthographic projection matrices. * * @param[in] v0 First vertex, in screen coordinates (but still with their z-value). * @param[in] v1 Second vertex. * @param[in] v2 Third vertex. * @param[in] depthbuffer Pre-calculated depthbuffer. * @return True if the whole triangle is visible in the image. */ inline bool is_triangle_visible(const glm::tvec4<float>& v0, const glm::tvec4<float>& v1, const glm::tvec4<float>& v2, const core::Image1d& depthbuffer) { // #Todo: Actually, only check the 3 vertex points, don't loop over the pixels - this should be enough. auto viewport_width = depthbuffer.cols; auto viewport_height = depthbuffer.rows; // Well, in in principle, we'd have to do the whole stuff as in render(), like // clipping against the frustums etc. // But as long as our model is fully on the screen, we're fine. Todo: Doublecheck that. if (!detail::are_vertices_ccw_in_screen_space(glm::tvec2<float>(v0), glm::tvec2<float>(v1), glm::tvec2<float>(v2))) return false; Rect<int> bbox = detail::calculate_clipped_bounding_box(glm::tvec2<float>(v0), glm::tvec2<float>(v1), glm::tvec2<float>(v2), viewport_width, viewport_height); int minX = bbox.x; int maxX = bbox.x + bbox.width; int minY = bbox.y; int maxY = bbox.y + bbox.height; //if (t.maxX <= t.minX || t.maxY <= t.minY) // Note: Can the width/height of the bbox be negative? Maybe we only need to check for equality here? // continue; // Also, I'm not entirely sure why I commented this out bool whole_triangle_is_visible = true; for (int yi = minY; yi <= maxY; yi++) { for (int xi = minX; xi <= maxX; xi++) { // we want centers of pixels to be used in computations. Do we? const float x = static_cast<float>(xi) + 0.5f; const float y = static_cast<float>(yi) + 0.5f; // these will be used for barycentric weights computation const double one_over_v0ToLine12 = 1.0 / detail::implicit_line(v0[0], v0[1], v1, v2); const double one_over_v1ToLine20 = 1.0 / detail::implicit_line(v1[0], v1[1], v2, v0); const double one_over_v2ToLine01 = 1.0 / detail::implicit_line(v2[0], v2[1], v0, v1); // affine barycentric weights const double alpha = detail::implicit_line(x, y, v1, v2) * one_over_v0ToLine12; const double beta = detail::implicit_line(x, y, v2, v0) * one_over_v1ToLine20; const double gamma = detail::implicit_line(x, y, v0, v1) * one_over_v2ToLine01; // if pixel (x, y) is inside the triangle or on one of its edges if (alpha >= 0 && beta >= 0 && gamma >= 0) { const double z_affine = alpha*static_cast<double>(v0[2]) + beta*static_cast<double>(v1[2]) + gamma*static_cast<double>(v2[2]); if (z_affine < depthbuffer(yi, xi)) { whole_triangle_is_visible = false; break; } } } if (!whole_triangle_is_visible) { break; } } if (!whole_triangle_is_visible) { return false; } return true; }; } /* namespace detail */ } /* namespace render */ } /* namespace eos */ #endif /* TEXTURE_EXTRACTION_DETAIL_HPP_ */ <commit_msg>Fixed Rect include<commit_after>/* * eos - A 3D Morphable Model fitting library written in modern C++11/14. * * File: include/eos/render/detail/texture_extraction_detail.hpp * * Copyright 2014, 2015 Patrik Huber * * 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. */ #pragma once #ifndef TEXTURE_EXTRACTION_DETAIL_HPP_ #define TEXTURE_EXTRACTION_DETAIL_HPP_ #include "eos/core/Image.hpp" #include "eos/render/Rect.hpp" #include "eos/render/detail/render_detail.hpp" #include "glm/vec2.hpp" #include "glm/vec4.hpp" #include "opencv2/core/core.hpp" /** * Implementations of internal functions, not part of the * API we expose and not meant to be used by a user. */ namespace eos { namespace render { namespace detail { /** * Computes whether the given point is inside (or on the border of) the triangle * formed out of the given three vertices. * * @param[in] point The point to check. * @param[in] triV0 First vertex. * @param[in] triV1 Second vertex. * @param[in] triV2 Third vertex. * @return Whether the point is inside the triangle. */ inline bool is_point_in_triangle(cv::Point2f point, cv::Point2f triV0, cv::Point2f triV1, cv::Point2f triV2) { // See http://www.blackpawn.com/texts/pointinpoly/ // Compute vectors cv::Point2f v0 = triV2 - triV0; cv::Point2f v1 = triV1 - triV0; cv::Point2f v2 = point - triV0; // Compute dot products float dot00 = v0.dot(v0); float dot01 = v0.dot(v1); float dot02 = v0.dot(v2); float dot11 = v1.dot(v1); float dot12 = v1.dot(v2); // Compute barycentric coordinates float invDenom = 1 / (dot00 * dot11 - dot01 * dot01); float u = (dot11 * dot02 - dot01 * dot12) * invDenom; float v = (dot00 * dot12 - dot01 * dot02) * invDenom; // Check if point is in triangle return (u >= 0) && (v >= 0) && (u + v < 1); }; /** * Checks whether all pixels in the given triangle are visible and * returns true if and only if the whole triangle is visible. * The vertices should be given in screen coordinates, but with their * z-values preserved, so they can be compared against the depthbuffer. * * Obviously the depthbuffer given should have been created with the same projection * matrix than the texture extraction is called with. * * Also, we don't do perspective-correct interpolation here I think, so only * use it with affine and orthographic projection matrices. * * @param[in] v0 First vertex, in screen coordinates (but still with their z-value). * @param[in] v1 Second vertex. * @param[in] v2 Third vertex. * @param[in] depthbuffer Pre-calculated depthbuffer. * @return True if the whole triangle is visible in the image. */ inline bool is_triangle_visible(const glm::tvec4<float>& v0, const glm::tvec4<float>& v1, const glm::tvec4<float>& v2, const core::Image1d& depthbuffer) { // #Todo: Actually, only check the 3 vertex points, don't loop over the pixels - this should be enough. auto viewport_width = depthbuffer.cols; auto viewport_height = depthbuffer.rows; // Well, in in principle, we'd have to do the whole stuff as in render(), like // clipping against the frustums etc. // But as long as our model is fully on the screen, we're fine. Todo: Doublecheck that. if (!detail::are_vertices_ccw_in_screen_space(glm::tvec2<float>(v0), glm::tvec2<float>(v1), glm::tvec2<float>(v2))) return false; Rect<int> bbox = detail::calculate_clipped_bounding_box(glm::tvec2<float>(v0), glm::tvec2<float>(v1), glm::tvec2<float>(v2), viewport_width, viewport_height); int minX = bbox.x; int maxX = bbox.x + bbox.width; int minY = bbox.y; int maxY = bbox.y + bbox.height; //if (t.maxX <= t.minX || t.maxY <= t.minY) // Note: Can the width/height of the bbox be negative? Maybe we only need to check for equality here? // continue; // Also, I'm not entirely sure why I commented this out bool whole_triangle_is_visible = true; for (int yi = minY; yi <= maxY; yi++) { for (int xi = minX; xi <= maxX; xi++) { // we want centers of pixels to be used in computations. Do we? const float x = static_cast<float>(xi) + 0.5f; const float y = static_cast<float>(yi) + 0.5f; // these will be used for barycentric weights computation const double one_over_v0ToLine12 = 1.0 / detail::implicit_line(v0[0], v0[1], v1, v2); const double one_over_v1ToLine20 = 1.0 / detail::implicit_line(v1[0], v1[1], v2, v0); const double one_over_v2ToLine01 = 1.0 / detail::implicit_line(v2[0], v2[1], v0, v1); // affine barycentric weights const double alpha = detail::implicit_line(x, y, v1, v2) * one_over_v0ToLine12; const double beta = detail::implicit_line(x, y, v2, v0) * one_over_v1ToLine20; const double gamma = detail::implicit_line(x, y, v0, v1) * one_over_v2ToLine01; // if pixel (x, y) is inside the triangle or on one of its edges if (alpha >= 0 && beta >= 0 && gamma >= 0) { const double z_affine = alpha*static_cast<double>(v0[2]) + beta*static_cast<double>(v1[2]) + gamma*static_cast<double>(v2[2]); if (z_affine < depthbuffer(yi, xi)) { whole_triangle_is_visible = false; break; } } } if (!whole_triangle_is_visible) { break; } } if (!whole_triangle_is_visible) { return false; } return true; }; } /* namespace detail */ } /* namespace render */ } /* namespace eos */ #endif /* TEXTURE_EXTRACTION_DETAIL_HPP_ */ <|endoftext|>
<commit_before>#ifndef BOUNDINGBOX_HPP_DEFINED #define BOUNDINGBOX_HPP_DEFINED #include "GeoCoordinate.hpp" namespace utymap { // Represents geo bounding box struct BoundingBox { // Point with minimal latitude and longitude. GeoCoordinate minPoint; // Point with maximum latitude and longitude. GeoCoordinate maxPoint; BoundingBox() : BoundingBox(GeoCoordinate(90, 180), GeoCoordinate(-90, -180)) { } BoundingBox(const GeoCoordinate& minPoint, const GeoCoordinate& maxPoint) : minPoint(minPoint), maxPoint(maxPoint) { } BoundingBox& operator+=(const BoundingBox& rhs) { expand(rhs); return *this; } inline bool isValid() const { // TODO possible that minLon > maxLon at some locations return minPoint.latitude <= maxPoint.latitude && minPoint.longitude <= maxPoint.longitude; } // Expands bounding box using another bounding box. inline void expand(const BoundingBox& rhs) { minPoint.latitude = minPoint.latitude < rhs.minPoint.latitude ? minPoint.latitude : rhs.minPoint.latitude; minPoint.longitude = minPoint.longitude < rhs.minPoint.longitude ? minPoint.longitude : rhs.minPoint.longitude; maxPoint.latitude = maxPoint.latitude > rhs.maxPoint.latitude ? maxPoint.latitude : rhs.maxPoint.latitude; maxPoint.longitude = maxPoint.longitude > rhs.maxPoint.longitude ? maxPoint.longitude : rhs.maxPoint.longitude; } // Expands bounding box using given coordinate. inline void expand(const GeoCoordinate& c) { minPoint = GeoCoordinate( minPoint.latitude < c.latitude ? minPoint.latitude : c.latitude, minPoint.longitude < c.longitude ? minPoint.longitude : c.longitude); maxPoint = GeoCoordinate( maxPoint.latitude > c.latitude ? maxPoint.latitude : c.latitude, maxPoint.longitude > c.longitude ? maxPoint.longitude : c.longitude); } // Expands bounging box from collection of geo data. template<typename ForwardIterator> inline void expand(ForwardIterator begin, ForwardIterator end) { for (; begin != end; ++begin) expand(*begin); } // Checks whether given bounding box inside the current one. inline bool contains(const BoundingBox& bbox) const { return contains(bbox.minPoint) && contains(bbox.maxPoint); } // Checks whether given coordinate inside the bounding box. inline bool contains(const GeoCoordinate& coordinate) const { return coordinate.latitude > minPoint.latitude && coordinate.longitude > minPoint.longitude && coordinate.latitude < maxPoint.latitude && coordinate.longitude < maxPoint.longitude; } // Checks whether given bounding box intersects the current one. inline bool intersects(const BoundingBox& rhs) const { double minLat = minPoint.latitude < rhs.minPoint.latitude ? rhs.minPoint.latitude : minPoint.latitude; double minLon = minPoint.longitude < rhs.minPoint.longitude ? rhs.minPoint.longitude : minPoint.longitude; double maxLat = maxPoint.latitude > rhs.maxPoint.latitude ? rhs.maxPoint.latitude : maxPoint.latitude; double maxLon = maxPoint.longitude > rhs.maxPoint.longitude ? rhs.maxPoint.longitude : maxPoint.longitude; return minLat <= maxLat && minLon <= maxLon; } // Returns center of bounding box. inline GeoCoordinate center() const { return GeoCoordinate( minPoint.latitude + (maxPoint.latitude - minPoint.latitude) / 2, minPoint.longitude + (maxPoint.longitude - minPoint.longitude) / 2); } // Returns width. inline double width() const { return maxPoint.longitude - minPoint.longitude; } }; } #endif // BOUNDINGBOX_HPP_DEFINED <commit_msg>core: use std's min/max instead of <> operations<commit_after>#ifndef BOUNDINGBOX_HPP_DEFINED #define BOUNDINGBOX_HPP_DEFINED #include "GeoCoordinate.hpp" #include <algorithm> namespace utymap { // Represents geo bounding box struct BoundingBox { // Point with minimal latitude and longitude. GeoCoordinate minPoint; // Point with maximum latitude and longitude. GeoCoordinate maxPoint; BoundingBox() : BoundingBox(GeoCoordinate(90, 180), GeoCoordinate(-90, -180)) { } BoundingBox(const GeoCoordinate& minPoint, const GeoCoordinate& maxPoint) : minPoint(minPoint), maxPoint(maxPoint) { } BoundingBox& operator+=(const BoundingBox& rhs) { expand(rhs); return *this; } inline bool isValid() const { // TODO possible that minLon > maxLon at some locations return minPoint.latitude <= maxPoint.latitude && minPoint.longitude <= maxPoint.longitude; } // Expands bounding box using another bounding box. inline void expand(const BoundingBox& rhs) { minPoint.latitude = std::min(minPoint.latitude, rhs.minPoint.latitude); minPoint.longitude = std::min(minPoint.longitude, rhs.minPoint.longitude); maxPoint.latitude = std::max(maxPoint.latitude, rhs.maxPoint.latitude); maxPoint.longitude = std::max(maxPoint.longitude, rhs.maxPoint.longitude); } // Expands bounding box using given coordinate. inline void expand(const GeoCoordinate& c) { minPoint = GeoCoordinate( std::min(minPoint.latitude, c.latitude), std::min(minPoint.longitude, c.longitude)); maxPoint = GeoCoordinate( std::max(maxPoint.latitude, c.latitude), std::max(maxPoint.longitude, c.longitude)); } // Expands bounging box from collection of geo data. template<typename ForwardIterator> inline void expand(ForwardIterator begin, ForwardIterator end) { for (; begin != end; ++begin) expand(*begin); } // Checks whether given bounding box inside the current one. inline bool contains(const BoundingBox& bbox) const { return contains(bbox.minPoint) && contains(bbox.maxPoint); } // Checks whether given coordinate inside the bounding box. inline bool contains(const GeoCoordinate& coordinate) const { return coordinate.latitude > minPoint.latitude && coordinate.longitude > minPoint.longitude && coordinate.latitude < maxPoint.latitude && coordinate.longitude < maxPoint.longitude; } // Checks whether given bounding box intersects the current one. inline bool intersects(const BoundingBox& rhs) const { double minLat = std::max(rhs.minPoint.latitude, minPoint.latitude); double minLon = std::max(rhs.minPoint.longitude, minPoint.longitude); double maxLat = std::min(rhs.maxPoint.latitude, maxPoint.latitude); double maxLon = std::min(rhs.maxPoint.longitude, maxPoint.longitude); return minLat <= maxLat && minLon <= maxLon; } // Returns center of bounding box. inline GeoCoordinate center() const { return GeoCoordinate( minPoint.latitude + (maxPoint.latitude - minPoint.latitude) / 2, minPoint.longitude + (maxPoint.longitude - minPoint.longitude) / 2); } // Returns width. inline double width() const { return maxPoint.longitude - minPoint.longitude; } }; } #endif // BOUNDINGBOX_HPP_DEFINED <|endoftext|>
<commit_before>#include <catch.hpp> #include <experimental/filesystem> #include <pddlparse/AST.h> #include <pddlparse/Parse.h> namespace fs = std::experimental::filesystem; const pddl::Context::WarningCallback ignoreWarnings = [](const auto &, const auto &warning){std::cout << warning << std::endl;}; //////////////////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("[PDDL parser] Check past issues", "[PDDL parser]") { pddl::Tokenizer tokenizer; pddl::Context context(std::move(tokenizer), ignoreWarnings); // Check that no infinite loop occurs SECTION("“either” in typing section") { const auto domainFile = fs::path("data") / "test-cases" / "typing-1.pddl"; context.tokenizer.read(domainFile); const auto description = pddl::parseDescription(context); const auto &types = description.domain->types; REQUIRE(types.size() == 5); CHECK(types[0]->name == "object"); REQUIRE(types[0]->parentTypes.size() == 1); CHECK(types[0]->parentTypes[0]->declaration == types[0].get()); CHECK(types[1]->name == "a1"); REQUIRE(types[1]->parentTypes.size() == 1); CHECK(types[1]->parentTypes[0]->declaration == types[0].get()); CHECK(types[2]->name == "a2"); REQUIRE(types[2]->parentTypes.size() == 1); CHECK(types[2]->parentTypes[0]->declaration == types[0].get()); CHECK(types[3]->name == "a3"); REQUIRE(types[3]->parentTypes.size() == 1); CHECK(types[3]->parentTypes[0]->declaration == types[0].get()); CHECK(types[4]->name == "bx"); REQUIRE(types[4]->parentTypes.size() == 3); CHECK(types[4]->parentTypes[0]->declaration == types[1].get()); CHECK(types[4]->parentTypes[1]->declaration == types[2].get()); CHECK(types[4]->parentTypes[2]->declaration == types[3].get()); } // Check that whitespace is handled appropriately SECTION("“either” in typing section") { const auto domainFile = fs::path("data") / "test-cases" / "white-space.pddl"; context.tokenizer.read(domainFile); CHECK_NOTHROW(pddl::parseDescription(context)); } } <commit_msg>Replicated test cases with missing or mismatched domains in PDDL parsing library.<commit_after>#include <catch.hpp> #include <experimental/filesystem> #include <pddlparse/AST.h> #include <pddlparse/Parse.h> namespace fs = std::experimental::filesystem; const pddl::Context::WarningCallback ignoreWarnings = [](const auto &, const auto &warning){std::cout << warning << std::endl;}; const auto pddlInstanceBasePath = fs::path("data") / "pddl-instances"; //////////////////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("[PDDL parser] Check past issues", "[PDDL parser]") { pddl::Tokenizer tokenizer; pddl::Context context(std::move(tokenizer), ignoreWarnings); // Check that no infinite loop occurs SECTION("“either” in typing section") { const auto domainFile = fs::path("data") / "test-cases" / "typing-1.pddl"; context.tokenizer.read(domainFile); const auto description = pddl::parseDescription(context); const auto &types = description.domain->types; REQUIRE(types.size() == 5); CHECK(types[0]->name == "object"); REQUIRE(types[0]->parentTypes.size() == 1); CHECK(types[0]->parentTypes[0]->declaration == types[0].get()); CHECK(types[1]->name == "a1"); REQUIRE(types[1]->parentTypes.size() == 1); CHECK(types[1]->parentTypes[0]->declaration == types[0].get()); CHECK(types[2]->name == "a2"); REQUIRE(types[2]->parentTypes.size() == 1); CHECK(types[2]->parentTypes[0]->declaration == types[0].get()); CHECK(types[3]->name == "a3"); REQUIRE(types[3]->parentTypes.size() == 1); CHECK(types[3]->parentTypes[0]->declaration == types[0].get()); CHECK(types[4]->name == "bx"); REQUIRE(types[4]->parentTypes.size() == 3); CHECK(types[4]->parentTypes[0]->declaration == types[1].get()); CHECK(types[4]->parentTypes[1]->declaration == types[2].get()); CHECK(types[4]->parentTypes[2]->declaration == types[3].get()); } // Check that whitespace is handled appropriately SECTION("“either” in typing section") { const auto domainFile = fs::path("data") / "test-cases" / "white-space.pddl"; context.tokenizer.read(domainFile); CHECK_NOTHROW(pddl::parseDescription(context)); } SECTION("missing domains are detected") { const auto instanceFile = fs::path("data") / "pddl-instances" / "ipc-2000" / "domains" / "blocks-strips-typed" / "instances" / "instance-1.pddl"; context.tokenizer.read(instanceFile); CHECK_THROWS(pddl::parseDescription(context)); } SECTION("mismatched domains are detected") { const auto domainFile = fs::path("data") / "pddl-instances" / "ipc-2000" / "domains" / "blocks-strips-typed" / "domain.pddl"; const auto instanceFile = fs::path("data") / "pddl-instances" / "ipc-2000" / "domains" / "freecell-strips-typed" / "instances" / "instance-1.pddl"; context.tokenizer.read(domainFile); context.tokenizer.read(instanceFile); CHECK_THROWS(pddl::parseDescription(context)); } } <|endoftext|>
<commit_before>#include "font.h" #include <GLFW/glfw3.h> #pragma comment(lib, "glfw3.lib") #pragma comment(lib, "opengl32.lib") #include <vector> class Map { std::vector<int> tiles; int width, height; public: Map(int width, int height) : tiles(width * height, 0), width(width), height(height) {} int GetWidth() const { return width; } int GetHeight() const { return height; } bool IsObstruction(int x, int y) const { return tiles[y*width+x] != 0; } void SetObstruction(int x, int y, bool isObstruction) { tiles[y*width+x] = isObstruction ? 1 : 0; } }; #include <iostream> int main() try { if(!glfwInit()) throw std::runtime_error("glfwInit() failed."); auto window = glfwCreateWindow(1280, 720, "Map Search Example", nullptr, nullptr); if(!window) throw std::runtime_error("glfwCreateWindow(...) failed."); glfwMakeContextCurrent(window); Font font; Map map(40, 30); map.SetObstruction(4,5,true); map.SetObstruction(5,5,true); map.SetObstruction(38,2,true); map.SetObstruction(6,27,true); while(!glfwWindowShouldClose(window)) { glfwPollEvents(); int width, height; glfwGetFramebufferSize(window, &width, &height); int mapPixelScale = 16; int mapPixelWidth = map.GetWidth() * mapPixelScale; int mapPixelHeight = map.GetHeight() * mapPixelScale; int mapOffsetX = (width - mapPixelWidth)/2; int mapOffsetY = (height - mapPixelHeight)/2; double mouseX, mouseY; glfwGetCursorPos(window, &mouseX, &mouseY); int tileX = static_cast<int>(floor((mouseX-mapOffsetX) / mapPixelScale)), tileY = static_cast<int>(floor((mouseY-mapOffsetY) / mapPixelScale)); if(tileX >= 0 && tileX < map.GetWidth() && tileY >= 0 && tileY < map.GetHeight()) { if(glfwGetMouseButton(window, 0) == GLFW_PRESS) { map.SetObstruction(tileX, tileY, true); } else if(glfwGetMouseButton(window, 1) == GLFW_PRESS) { map.SetObstruction(tileX, tileY, false); } } glViewport(0, 0, width, height); glClear(GL_COLOR_BUFFER_BIT); glPushMatrix(); glOrtho(0, width, height, 0, -1, +1); glColor3f(1,1,0); font.Print(32, 32, "Left-click to add obstruction, right-click to clear obstruction.", 8, 14); glPushMatrix(); glTranslated(mapOffsetX, mapOffsetY, 0); glBegin(GL_QUADS); glColor3f(0.2f,0.2f,0.2f); glVertex2i(0,0); glVertex2i(map.GetWidth()*mapPixelScale,0); glVertex2i(map.GetWidth()*mapPixelScale,map.GetHeight()*mapPixelScale); glVertex2i(0,map.GetHeight()*mapPixelScale); for(int y=0; y<map.GetHeight(); ++y) { for(int x=0; x<map.GetWidth(); ++x) { if(map.IsObstruction(x,y)) glColor3f(0.5f,0.5f,0.5f); else glColor3f(0,0,0); glVertex2i(x*mapPixelScale+1, y*mapPixelScale+1); glVertex2i((x+1)*mapPixelScale-1, y*mapPixelScale+1); glVertex2i((x+1)*mapPixelScale-1, (y+1)*mapPixelScale-1); glVertex2i(x*mapPixelScale+1, (y+1)*mapPixelScale-1); } } glEnd(); glPopMatrix(); glBegin(GL_QUADS); glColor3f(1,1,0); glVertex2d(mouseX-2, mouseY-2); glVertex2d(mouseX+2, mouseY-2); glVertex2d(mouseX+2, mouseY+2); glVertex2d(mouseX-2, mouseY+2); glEnd(); glPopMatrix(); glfwSwapBuffers(window); } glfwDestroyWindow(window); glfwTerminate(); return 0; } catch(const std::exception & e) { std::cerr << "Unhandled exception: " << e.what() << std::endl; return -1; }<commit_msg>Support a basic Dijkstra search algorithm.<commit_after>#include "font.h" #include <GLFW/glfw3.h> #pragma comment(lib, "glfw3.lib") #pragma comment(lib, "opengl32.lib") #include <vector> #include <algorithm> struct int2 { int x,y; }; class Map { std::vector<int> tiles; int width, height; public: Map(int width, int height) : tiles(width * height, 0), width(width), height(height) {} int GetWidth() const { return width; } int GetHeight() const { return height; } bool IsObstruction(int x, int y) const { return tiles[y*width+x] != 0; } void SetObstruction(int x, int y, bool isObstruction) { tiles[y*width+x] = isObstruction ? 1 : 0; } std::vector<int2> Search(const int2 & start, const int2 & goal) const { const int2 directions[] = {{1,0},{1,1},{0,1},{-1,1},{-1,0},{-1,-1},{0,-1},{1,-1}}; const int costs[] = {5,7,5,7,5,7,5,7}; struct OpenNode { int2 state; int lastAction, gCost; bool operator < (const OpenNode & r) const { return r.gCost < gCost; } }; std::vector<OpenNode> open; std::vector<int> closed(tiles.size(), -1); open.push_back({start, 0, 0}); while(!open.empty()) { auto node = open.front(); std::pop_heap(begin(open), end(open)); open.pop_back(); auto state = node.state; if(closed[state.y * width + state.x] != -1) continue; closed[state.y * width + state.x] = node.lastAction; if(state.x == goal.x && state.y == goal.y) { std::vector<int2> path(1,state); while(state.x != start.x || state.y != start.y) { int action = closed[state.y * width + state.x]; state.x -= directions[action].x; state.y -= directions[action].y; path.push_back(state); } std::reverse(begin(path), end(path)); return path; } for(int i=0; i<8; ++i) { auto newState = state; newState.x += directions[i].x; newState.y += directions[i].y; if(newState.x < 0 || newState.y < 0 || newState.x >= width || newState.y >= height) continue; if(IsObstruction(newState.x, newState.y)) continue; if(IsObstruction(state.x, newState.y) && IsObstruction(newState.x, state.y)) continue; open.push_back({newState, i, node.gCost + costs[i]}); std::push_heap(begin(open), end(open)); } } return {}; } }; #include <iostream> int main() try { if(!glfwInit()) throw std::runtime_error("glfwInit() failed."); auto window = glfwCreateWindow(1280, 720, "Map Search Example", nullptr, nullptr); if(!window) throw std::runtime_error("glfwCreateWindow(...) failed."); glfwMakeContextCurrent(window); Font font; Map map(40, 30); map.SetObstruction(4,5,true); map.SetObstruction(5,5,true); map.SetObstruction(38,2,true); map.SetObstruction(6,27,true); int2 startTile; bool middleClicked = false; while(!glfwWindowShouldClose(window)) { glfwPollEvents(); int width, height; glfwGetFramebufferSize(window, &width, &height); int mapPixelScale = 16; int mapPixelWidth = map.GetWidth() * mapPixelScale; int mapPixelHeight = map.GetHeight() * mapPixelScale; int mapOffsetX = (width - mapPixelWidth)/2; int mapOffsetY = (height - mapPixelHeight)/2; double mouseX, mouseY; glfwGetCursorPos(window, &mouseX, &mouseY); int tileX = static_cast<int>(floor((mouseX-mapOffsetX) / mapPixelScale)), tileY = static_cast<int>(floor((mouseY-mapOffsetY) / mapPixelScale)); if(tileX >= 0 && tileX < map.GetWidth() && tileY >= 0 && tileY < map.GetHeight()) { if(glfwGetMouseButton(window, 0) == GLFW_PRESS) { map.SetObstruction(tileX, tileY, true); } else if(glfwGetMouseButton(window, 1) == GLFW_PRESS) { map.SetObstruction(tileX, tileY, false); } if(!middleClicked && glfwGetMouseButton(window, 2) == GLFW_PRESS) { startTile = {tileX, tileY}; middleClicked = true; } } if(glfwGetMouseButton(window, 2) == GLFW_RELEASE) middleClicked = false; std::vector<int2> path; if(middleClicked) path = map.Search(startTile, {tileX,tileY}); glViewport(0, 0, width, height); glClear(GL_COLOR_BUFFER_BIT); glPushMatrix(); glOrtho(0, width, height, 0, -1, +1); glColor3f(1,1,0); font.Print(32, 32, "Left-click to add obstruction, right-click to clear obstruction."); font.Print(32, 48, "Middle-click and drag to find a path between two points."); glPushMatrix(); glTranslated(mapOffsetX, mapOffsetY, 0); glBegin(GL_QUADS); glColor3f(0.2f,0.2f,0.2f); glVertex2i(0,0); glVertex2i(map.GetWidth()*mapPixelScale,0); glVertex2i(map.GetWidth()*mapPixelScale,map.GetHeight()*mapPixelScale); glVertex2i(0,map.GetHeight()*mapPixelScale); for(int y=0; y<map.GetHeight(); ++y) { for(int x=0; x<map.GetWidth(); ++x) { if(map.IsObstruction(x,y)) glColor3f(0.5f,0.5f,0.5f); else glColor3f(0,0,0); glVertex2i(x*mapPixelScale+1, y*mapPixelScale+1); glVertex2i((x+1)*mapPixelScale-1, y*mapPixelScale+1); glVertex2i((x+1)*mapPixelScale-1, (y+1)*mapPixelScale-1); glVertex2i(x*mapPixelScale+1, (y+1)*mapPixelScale-1); } } glEnd(); if(middleClicked) { glBegin(GL_LINE_STRIP); glColor3f(1,1,0); for(auto tile : path) glVertex2i(tile.x * mapPixelScale + mapPixelScale/2, tile.y * mapPixelScale + mapPixelScale/2); glEnd(); glBegin(GL_QUADS); glColor3f(0,1,0); glVertex2d(startTile.x*mapPixelScale + mapPixelScale/2 - 2, startTile.y*mapPixelScale + mapPixelScale/2-2); glVertex2d(startTile.x*mapPixelScale + mapPixelScale/2 + 2, startTile.y*mapPixelScale + mapPixelScale/2-2); glVertex2d(startTile.x*mapPixelScale + mapPixelScale/2 + 2, startTile.y*mapPixelScale + mapPixelScale/2+2); glVertex2d(startTile.x*mapPixelScale + mapPixelScale/2 - 2, startTile.y*mapPixelScale + mapPixelScale/2+2); glEnd(); /*glBegin(GL_QUADS); glColor3f(0,1,1); glVertex2d(startTile.x-2, startTile.y-2); glVertex2d(startTile.x+2, startTile.y-2); glVertex2d(startTile.x+2, startTile.y+2); glVertex2d(startTile.x-2, startTile.y+2); glEnd();*/ } glPopMatrix(); glBegin(GL_QUADS); glColor3f(1,1,0); glVertex2d(mouseX-2, mouseY-2); glVertex2d(mouseX+2, mouseY-2); glVertex2d(mouseX+2, mouseY+2); glVertex2d(mouseX-2, mouseY+2); glEnd(); glPopMatrix(); glfwSwapBuffers(window); } glfwDestroyWindow(window); glfwTerminate(); return 0; } catch(const std::exception & e) { std::cerr << "Unhandled exception: " << e.what() << std::endl; return -1; }<|endoftext|>
<commit_before>#pragma once #include <gunrock/framework/operators/configs.hxx> namespace gunrock { namespace operators { namespace filter { namespace uniquify { template <filter_algorithm_t type, typename frontier_t> void execute(frontier_t* input, const float& uniquification_percent, cuda::standard_context_t& context) { if (uniquification_percent < 0 || uniquification_percent > 100) error::throw_if_exception( cudaErrorUnknown, "Uniquification percentage must be a +ve float between 0 and 100."); // Filter algorithm already produces a unique output, or no uniquification // needed. TODO: confirm if compact actually generates a unique output. if ((type == filter_algorithm_t::compact) || (uniquification_percent == 0)) return; // 100% uniquification; there could be multiple algorithms to perform this, we // will stick with thrust for now. else if (uniquification_percent == 100) { auto new_end = thrust::unique( thrust::cuda::par.on(context.stream()), // execution policy input->begin(), // input iterator: begin input->end() // input iterator: end ); auto new_size = thrust::distance(input->begin(), new_end); input->set_number_of_elements(new_size); } else error::throw_if_exception(cudaErrorUnknown, "Variable uniquification (less than 100% or " "greater than 0%) is not implemented."); } } // namespace uniquify } // namespace filter } // namespace operators } // namespace gunrock<commit_msg>uniquify: comments<commit_after>#pragma once #include <gunrock/framework/operators/configs.hxx> namespace gunrock { namespace operators { namespace filter { namespace uniquify { template <filter_algorithm_t type, typename frontier_t> void execute(frontier_t* input, const float& uniquification_percent, cuda::standard_context_t& context) { if (uniquification_percent < 0 || uniquification_percent > 100) error::throw_if_exception( cudaErrorUnknown, "Uniquification percentage must be a +ve float between 0 and 100."); /*! * Filter algorithm already produces a unique output, or no uniquification * needed. * @todo confirm if compact actually generates a unique output. */ if ((type == filter_algorithm_t::compact) || (uniquification_percent == 0)) return; /*! * 100% uniquification; there could be multiple algorithms to perform this, we * will stick with thrust for now. */ else if (uniquification_percent == 100) { auto new_end = thrust::unique( thrust::cuda::par.on(context.stream()), // execution policy input->begin(), // input iterator: begin input->end() // input iterator: end ); auto new_size = thrust::distance(input->begin(), new_end); input->set_number_of_elements(new_size); } else error::throw_if_exception(cudaErrorUnknown, "Variable uniquification (less than 100% or " "greater than 0%) is not implemented."); } } // namespace uniquify } // namespace filter } // namespace operators } // namespace gunrock<|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: sdclient.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2003-11-24 17:10:54 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _IPOBJ_HXX //autogen #include <so3/ipobj.hxx> #endif #ifndef _SVDOOLE2_HXX //autogen #include <svx/svdoole2.hxx> #endif #ifndef _SVDOGRAF_HXX //autogen #include <svx/svdograf.hxx> #endif #ifndef _CLIENT_HXX //autogen #include <so3/client.hxx> #endif #ifndef _IPENV_HXX //autogen #include <so3/ipenv.hxx> #endif #ifndef _SVDPAGV_HXX #include <svx/svdpagv.hxx> #endif #pragma hdrstop #include "misc.hxx" #ifdef STARIMAGE_AVAILABLE #ifndef _SIMDLL_HXX #include <sim2/simdll.hxx> #endif #endif #include "strings.hrc" #include "sdclient.hxx" #include "viewshel.hxx" #include "drviewsh.hxx" #include "sdview.hxx" #include "sdwindow.hxx" #include "sdresid.hxx" /************************************************************************* |* |* Ctor |* \************************************************************************/ SdClient::SdClient(SdrOle2Obj* pObj, SdViewShell* pSdViewShell, Window* pWindow) : SfxInPlaceClient(pSdViewShell, pWindow), pViewShell(pSdViewShell), pSdrOle2Obj(pObj), pSdrGrafObj(NULL), pOutlinerParaObj (NULL) { } /************************************************************************* |* |* Dtor |* \************************************************************************/ SdClient::~SdClient() { } /************************************************************************* |* |* Wenn IP-aktiv, dann kommt diese Anforderung um Vergroesserung des |* sichtbaren Ausschnitts des Objektes |* \************************************************************************/ void SdClient::RequestObjAreaPixel(const Rectangle& rRect) { Window* pWin = pViewShell->GetWindow(); Rectangle aObjRect( pWin->PixelToLogic( rRect.TopLeft() ), pWin->PixelToLogic( rRect.GetSize() ) ); SdView* pView = pViewShell->GetView(); Rectangle aWorkArea( pView->GetWorkArea() ); if (!aWorkArea.IsInside(aObjRect)) { // Position korrigieren Point aPos = aObjRect.TopLeft(); Size aSize = aObjRect.GetSize(); Point aWorkAreaTL = aWorkArea.TopLeft(); Point aWorkAreaBR = aWorkArea.BottomRight(); aPos.X() = Max(aPos.X(), aWorkAreaTL.X()); aPos.X() = Min(aPos.X(), aWorkAreaBR.X()-aSize.Width()); aPos.Y() = Max(aPos.Y(), aWorkAreaTL.Y()); aPos.Y() = Min(aPos.Y(), aWorkAreaBR.Y()-aSize.Height()); aObjRect.SetPos(aPos); SfxInPlaceClient::RequestObjAreaPixel(pViewShell->GetWindow()-> LogicToPixel(aObjRect) ); } else { SfxInPlaceClient::RequestObjAreaPixel(rRect); } const SdrMarkList& rMarkList = pView->GetMarkList(); if (rMarkList.GetMarkCount() == 1) { SdrMark* pMark = rMarkList.GetMark(0); SdrObject* pObj = pMark->GetObj(); Rectangle aOldRect( pObj->GetLogicRect() ); if ( aObjRect != aOldRect ) { // Rundungsfehler vermeiden - nur, wenn mindestens 1 Pixel Unterschied // (getrennt fuer Position und Groesse) Size aOnePixel = pWin->PixelToLogic( Size(1, 1) ); Size aLogicSize = aObjRect.GetSize(); Rectangle aNewRect = aOldRect; Size aNewSize = aNewRect.GetSize(); if ( Abs( aObjRect.Left() - aOldRect.Left() ) >= aOnePixel.Width() ) aNewRect.SetPos( Point( aObjRect.Left(), aNewRect.Top() ) ); if ( Abs( aObjRect.Top() - aOldRect.Top() ) >= aOnePixel.Height() ) aNewRect.SetPos( Point( aNewRect.Left(), aObjRect.Top() ) ); if ( Abs( aLogicSize.Width() - aNewSize.Width() ) >= aOnePixel.Width() ) aNewSize.Width() = aLogicSize.Width(); if ( Abs( aLogicSize.Height() - aNewSize.Height() ) >= aOnePixel.Height() ) aNewSize.Height() = aLogicSize.Height(); aNewRect.SetSize( aNewSize ); if ( aNewRect != aOldRect ) // veraendert nur, wenn mindestens 1 Pixel pObj->SetLogicRect( aNewRect ); } } } /************************************************************************* |* |* |* \************************************************************************/ void SdClient::ViewChanged(USHORT nAspect) { // Eventuell neues MetaFile holen SfxInPlaceClient::ViewChanged(nAspect); if (pViewShell->GetActiveWindow()) { SdView* pView = pViewShell->GetView(); if (pView) { SvClientData* pData = GetEnv(); if( pData ) { SvEmbeddedObject* pObj = GetEmbedObj(); MapMode aMap100( MAP_100TH_MM ); Rectangle aVisArea( OutputDevice::LogicToLogic( pObj->GetVisArea(), pObj->GetMapUnit(), aMap100 ) ); Rectangle aLogicRect( pSdrOle2Obj->GetLogicRect() ); Size aScaledSize( static_cast< long >( pData->GetScaleWidth() * Fraction( aVisArea.GetWidth() ) ), static_cast< long >( pData->GetScaleHeight() * Fraction( aVisArea.GetHeight() ) ) ); if( Application::GetDefaultDevice()->LogicToPixel( aScaledSize, aMap100 ) != Application::GetDefaultDevice()->LogicToPixel( aLogicRect.GetSize(), aMap100 ) ) { const sal_Bool bOldLock = pView->GetModel()->isLocked(); pView->GetModel()->setLock( sal_True ); pSdrOle2Obj->SetLogicRect( Rectangle( aLogicRect.TopLeft(), aScaledSize ) ); pView->GetModel()->setLock( bOldLock ); pSdrOle2Obj->BroadcastObjectChange(); } } } } } /************************************************************************* |* |* InPlace-Objekt aktivieren / deaktivieren |* \************************************************************************/ void SdClient::UIActivate(BOOL bActivate) { SfxInPlaceClient::UIActivate(bActivate); if (!bActivate) { #ifdef STARIMAGE_AVAILABLE if (pSdrGrafObj && pViewShell->GetActiveWindow()) { // Das Ole2Obj (Image) wird gegen das GrafObj ausgetauscht pSdrGrafObj->SetLogicRect(pSdrOle2Obj->GetLogicRect()); SvInPlaceObjectRef aIPObj = pSdrOle2Obj->GetObjRef(); pSdrGrafObj->SetGraphic ( SimDLL::GetGraphic( aIPObj ) ); SdView* pView = pViewShell->GetView(); SdrPageView* pPV = pView->GetPageViewPvNum(0); SdrPage* pPg = pPV->GetPage(); delete pPg->RemoveObject( pSdrOle2Obj->GetOrdNum() ); pSdrGrafObj = NULL; } #endif } } /************************************************************************* |* |* Daten fuer eine ggf. spaeter zu erzeugende View |* \************************************************************************/ void SdClient::MakeViewData() { SfxInPlaceClient::MakeViewData(); SvClientData* pCD = GetClientData(); if (pCD) { SvEmbeddedObject* pObj = GetEmbedObj(); Rectangle aObjVisArea = OutputDevice::LogicToLogic( pObj->GetVisArea(), pObj->GetMapUnit(), MAP_100TH_MM ); Size aVisSize = aObjVisArea.GetSize(); Fraction aFractX = pCD->GetScaleWidth(); Fraction aFractY = pCD->GetScaleHeight(); aFractX *= aVisSize.Width(); aFractY *= aVisSize.Height(); pCD->SetSizeScale(aFractX, aFractY); Rectangle aObjArea = pSdrOle2Obj->GetLogicRect(); pCD->SetObjArea(aObjArea); } } /************************************************************************* |* |* Objekt in den sichtbaren Breich scrollen |* \************************************************************************/ void SdClient::MakeVisible() { SfxInPlaceClient::MakeVisible(); if (pViewShell->ISA(SdDrawViewShell)) { ((SdDrawViewShell*) pViewShell)->MakeVisible(pSdrOle2Obj->GetLogicRect(), *pViewShell->GetActiveWindow()); } } <commit_msg>INTEGRATION: CWS impress1 (1.4.236); FILE MERGED 2003/11/27 15:08:20 af 1.4.236.2: RESYNC: (1.4-1.5); FILE MERGED 2003/09/17 09:31:51 af 1.4.236.1: #111996# Transition to stacked sub-shells. Introduction of namespace sd.<commit_after>/************************************************************************* * * $RCSfile: sdclient.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: obo $ $Date: 2004-01-20 10:54:37 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "Client.hxx" #ifndef _IPOBJ_HXX //autogen #include <so3/ipobj.hxx> #endif #ifndef _SVDOOLE2_HXX //autogen #include <svx/svdoole2.hxx> #endif #ifndef _SVDOGRAF_HXX //autogen #include <svx/svdograf.hxx> #endif #ifndef _CLIENT_HXX //autogen #include <so3/client.hxx> #endif #ifndef _IPENV_HXX //autogen #include <so3/ipenv.hxx> #endif #ifndef _SVDPAGV_HXX #include <svx/svdpagv.hxx> #endif #pragma hdrstop #include "misc.hxx" #ifdef STARIMAGE_AVAILABLE #ifndef _SIMDLL_HXX #include <sim2/simdll.hxx> #endif #endif #include "strings.hrc" #ifndef SD_VIEW_SHELL_HXX #include "ViewShell.hxx" #endif #ifndef SD_DRAW_VIEW_SHELL_HXX #include "DrawViewShell.hxx" #endif #ifndef SD_VIEW_HXX #include "View.hxx" #endif #ifndef SD_WINDOW_HXX #include "Window.hxx" #endif #include "sdresid.hxx" namespace sd { /************************************************************************* |* |* Ctor |* \************************************************************************/ Client::Client(SdrOle2Obj* pObj, ViewShell* pViewShell, ::Window* pWindow) : SfxInPlaceClient(pViewShell->GetViewShell(), pWindow), pViewShell(pViewShell), pSdrOle2Obj(pObj), pSdrGrafObj(NULL), pOutlinerParaObj (NULL) { } /************************************************************************* |* |* Dtor |* \************************************************************************/ Client::~Client() { } /************************************************************************* |* |* Wenn IP-aktiv, dann kommt diese Anforderung um Vergroesserung des |* sichtbaren Ausschnitts des Objektes |* \************************************************************************/ void Client::RequestObjAreaPixel(const Rectangle& rRect) { ::Window* pWin = pViewShell->GetWindow(); Rectangle aObjRect( pWin->PixelToLogic( rRect.TopLeft() ), pWin->PixelToLogic( rRect.GetSize() ) ); ::sd::View* pView = pViewShell->GetView(); Rectangle aWorkArea( pView->GetWorkArea() ); if (!aWorkArea.IsInside(aObjRect)) { // Position korrigieren Point aPos = aObjRect.TopLeft(); Size aSize = aObjRect.GetSize(); Point aWorkAreaTL = aWorkArea.TopLeft(); Point aWorkAreaBR = aWorkArea.BottomRight(); aPos.X() = Max(aPos.X(), aWorkAreaTL.X()); aPos.X() = Min(aPos.X(), aWorkAreaBR.X()-aSize.Width()); aPos.Y() = Max(aPos.Y(), aWorkAreaTL.Y()); aPos.Y() = Min(aPos.Y(), aWorkAreaBR.Y()-aSize.Height()); aObjRect.SetPos(aPos); SfxInPlaceClient::RequestObjAreaPixel(pViewShell->GetWindow()-> LogicToPixel(aObjRect) ); } else { SfxInPlaceClient::RequestObjAreaPixel(rRect); } const SdrMarkList& rMarkList = pView->GetMarkList(); if (rMarkList.GetMarkCount() == 1) { SdrMark* pMark = rMarkList.GetMark(0); SdrObject* pObj = pMark->GetObj(); Rectangle aOldRect( pObj->GetLogicRect() ); if ( aObjRect != aOldRect ) { // Rundungsfehler vermeiden - nur, wenn mindestens 1 Pixel Unterschied // (getrennt fuer Position und Groesse) Size aOnePixel = pWin->PixelToLogic( Size(1, 1) ); Size aLogicSize = aObjRect.GetSize(); Rectangle aNewRect = aOldRect; Size aNewSize = aNewRect.GetSize(); if ( Abs( aObjRect.Left() - aOldRect.Left() ) >= aOnePixel.Width() ) aNewRect.SetPos( Point( aObjRect.Left(), aNewRect.Top() ) ); if ( Abs( aObjRect.Top() - aOldRect.Top() ) >= aOnePixel.Height() ) aNewRect.SetPos( Point( aNewRect.Left(), aObjRect.Top() ) ); if ( Abs( aLogicSize.Width() - aNewSize.Width() ) >= aOnePixel.Width() ) aNewSize.Width() = aLogicSize.Width(); if ( Abs( aLogicSize.Height() - aNewSize.Height() ) >= aOnePixel.Height() ) aNewSize.Height() = aLogicSize.Height(); aNewRect.SetSize( aNewSize ); if ( aNewRect != aOldRect ) // veraendert nur, wenn mindestens 1 Pixel pObj->SetLogicRect( aNewRect ); } } } /************************************************************************* |* |* |* \************************************************************************/ void Client::ViewChanged(USHORT nAspect) { // Eventuell neues MetaFile holen SfxInPlaceClient::ViewChanged(nAspect); if (pViewShell->GetActiveWindow()) { ::sd::View* pView = pViewShell->GetView(); if (pView) { SvClientData* pData = GetEnv(); if( pData ) { SvEmbeddedObject* pObj = GetEmbedObj(); MapMode aMap100( MAP_100TH_MM ); Rectangle aVisArea( OutputDevice::LogicToLogic( pObj->GetVisArea(), pObj->GetMapUnit(), aMap100 ) ); Rectangle aLogicRect( pSdrOle2Obj->GetLogicRect() ); Size aScaledSize( static_cast< long >( pData->GetScaleWidth() * Fraction( aVisArea.GetWidth() ) ), static_cast< long >( pData->GetScaleHeight() * Fraction( aVisArea.GetHeight() ) ) ); if( Application::GetDefaultDevice()->LogicToPixel( aScaledSize, aMap100 ) != Application::GetDefaultDevice()->LogicToPixel( aLogicRect.GetSize(), aMap100 ) ) { const sal_Bool bOldLock = pView->GetModel()->isLocked(); pView->GetModel()->setLock( sal_True ); pSdrOle2Obj->SetLogicRect( Rectangle( aLogicRect.TopLeft(), aScaledSize ) ); pView->GetModel()->setLock( bOldLock ); pSdrOle2Obj->BroadcastObjectChange(); } } } } } /************************************************************************* |* |* InPlace-Objekt aktivieren / deaktivieren |* \************************************************************************/ void Client::UIActivate(BOOL bActivate) { SfxInPlaceClient::UIActivate(bActivate); if (!bActivate) { #ifdef STARIMAGE_AVAILABLE if (pSdrGrafObj && pViewShell->GetActiveWindow()) { // Das Ole2Obj (Image) wird gegen das GrafObj ausgetauscht pSdrGrafObj->SetLogicRect(pSdrOle2Obj->GetLogicRect()); SvInPlaceObjectRef aIPObj = pSdrOle2Obj->GetObjRef(); pSdrGrafObj->SetGraphic ( SimDLL::GetGraphic( aIPObj ) ); SdView* pView = pViewShell->GetView(); SdrPageView* pPV = pView->GetPageViewPvNum(0); SdrPage* pPg = pPV->GetPage(); delete pPg->RemoveObject( pSdrOle2Obj->GetOrdNum() ); pSdrGrafObj = NULL; } #endif } } /************************************************************************* |* |* Daten fuer eine ggf. spaeter zu erzeugende View |* \************************************************************************/ void Client::MakeViewData() { SfxInPlaceClient::MakeViewData(); SvClientData* pCD = GetClientData(); if (pCD) { SvEmbeddedObject* pObj = GetEmbedObj(); Rectangle aObjVisArea = OutputDevice::LogicToLogic( pObj->GetVisArea(), pObj->GetMapUnit(), MAP_100TH_MM ); Size aVisSize = aObjVisArea.GetSize(); Fraction aFractX = pCD->GetScaleWidth(); Fraction aFractY = pCD->GetScaleHeight(); aFractX *= aVisSize.Width(); aFractY *= aVisSize.Height(); pCD->SetSizeScale(aFractX, aFractY); Rectangle aObjArea = pSdrOle2Obj->GetLogicRect(); pCD->SetObjArea(aObjArea); } } /************************************************************************* |* |* Objekt in den sichtbaren Breich scrollen |* \************************************************************************/ void Client::MakeVisible() { SfxInPlaceClient::MakeVisible(); if (pViewShell->ISA(DrawViewShell)) { static_cast<DrawViewShell*>(pViewShell)->MakeVisible( pSdrOle2Obj->GetLogicRect(), *pViewShell->GetActiveWindow()); } } } // end of namespace sd <|endoftext|>
<commit_before>/* * Image.cpp * * Created on: Sep 8, 2009 * Author: rasmussn */ #include "Image.hpp" #include "../io/imageio.hpp"; #include <assert.h> namespace PV { Image::Image(const char * name, HyPerCol * hc) { initialize_base(name, hc); } Image::Image(const char * name, HyPerCol * hc, const char * filename) { initialize_base(name, hc); // get size info from image so that data buffer can be allocated int status = getImageInfo(filename, comm, &loc); // create mpi_datatypes for border transfer mpi_datatypes = Communicator::newDatatypes(&loc); if (status) return; double time = MPI_Wtime(); const int N = (loc.nx + 2*loc.nPad) * (loc.ny + 2*loc.nPad) * loc.nBands; data = new float [N]; for (int i = 0; i < N; ++i) { data[i] = 0; } time = MPI_Wtime() - time; // fprintf(stdout, "alloc: elapsed time = %f\n", (float) time*1000.); time = MPI_Wtime(); read(filename); time = MPI_Wtime() - time; // fprintf(stdout, "copy: elapsed time = %f\n", (float) time*1000.); // for now convert images to grayscale if (loc.nBands > 1) { this->toGrayScale(); } time = MPI_Wtime(); // exchange border information exchange(); time = MPI_Wtime() - time; // fprintf(stdout, "exchange: elapsed time = %f\n", (float) time*1000.); } Image::~Image() { free(name); if (data != NULL) { delete data; data = NULL; } } int Image::initialize_base(const char * name, HyPerCol * hc) { this->name = strdup(name); this->data = NULL; this->comm = hc->icCommunicator(); mpi_datatypes = NULL; PVParams * params = hc->parameters(); loc.nx = 0; loc.ny = 0; loc.nxGlobal = 0; loc.nyGlobal = 0; loc.kx0 = 0; loc.ky0 = 0; loc.nPad = 0; loc.nBands = 0; if (params->present(name, "marginWidth")) { loc.nPad = (int) params->value(name, "marginWidth"); } return 0; } pvdata_t * Image::getImageBuffer() { return data; } LayerLoc Image::getImageLoc() { return loc; } /** * update the image buffers * * return true if buffers have changed */ bool Image::updateImage(float time, float dt) { // default is to do nothing for now // eventually could go through a list of images return false; } int Image::read(const char * filename) { int status = 0; const int n = loc.nx * loc.ny * loc.nBands; unsigned char * buf = new unsigned char[n]; assert(buf != NULL); // read the image and scatter the local portions status = scatterImageFile(filename, comm, &loc, buf); if (status == 0) { status = copyFromInteriorBuffer(buf); } delete buf; return status; } int Image::write(const char * filename) { int status = 0; const int n = loc.nx * loc.ny * loc.nBands; unsigned char * buf = new unsigned char[n]; assert(buf != NULL); status = copyToInteriorBuffer(buf); // gather the local portions and write the image status = gatherImageFile(filename, comm, &loc, buf); delete buf; return status; } int Image::exchange() { comm->exchange(data, mpi_datatypes, &loc); } int Image::copyToInteriorBuffer(unsigned char * buf) { const int nx = loc.nx; const int ny = loc.ny; const int nxBorder = loc.nPad; const int nyBorder = loc.nPad; const int sy = nx + 2*nxBorder; const int sb = sy * (ny + 2*nyBorder); int ii = 0; for (int b = 0; b < loc.nBands; b++) { for (int j = 0; j < ny; j++) { int jex = j + nyBorder; for (int i = 0; i < nx; i++) { int iex = i + nxBorder; buf[ii++] = (unsigned char) data[iex + jex*sy + b*sb]; } } } return 0; } int Image::copyFromInteriorBuffer(const unsigned char * buf) { const int nx = loc.nx; const int ny = loc.ny; const int nxBorder = loc.nPad; const int nyBorder = loc.nPad; const int sy = nx + 2*nxBorder; const int sb = sy * (ny + 2*nyBorder); int ii = 0; for (int b = 0; b < loc.nBands; b++) { for (int j = 0; j < ny; j++) { int jex = j + nyBorder; for (int i = 0; i < nx; i++) { int iex = i + nxBorder; data[iex + jex*sy + b*sb] = (pvdata_t) buf[ii++]; } } } return 0; } int Image::toGrayScale() { const int nx_ex = loc.nx + 2*loc.nPad; const int ny_ex = loc.ny + 2*loc.nPad; const int numBands = loc.nBands; const int sx = 1; const int sy = nx_ex; const int sb = nx_ex * ny_ex; if (numBands < 2) return 0; for (int j = 0; j < ny_ex; j++) { for (int i = 0; i < nx_ex; i++) { float val = 0; for (int b = 0; b < numBands; b++) { float d = data[i*sx + j*sy + b*sb]; val += d*d; // val += d; } data[i*sx + j*sy + 0*sb] = sqrt(val/numBands); // data[i*sx + j*sy + 0*sb] = val/numBands; } } loc.nBands = 1; return 0; } int Image::convertToGrayScale(LayerLoc * loc, unsigned char * buf) { const int nx = loc->nx; const int ny = loc->ny; const int numBands = loc->nBands; const int sx = 1; const int sy = nx; const int sb = nx * ny; if (numBands < 2) return 0; for (int j = 0; j < ny; j++) { for (int i = 0; i < nx; i++) { float val = 0; for (int b = 0; b < numBands; b++) { float d = buf[i*sx + j*sy + b*sb]; val += d*d; } buf[i*sx + j*sy + 0*sb] = sqrt(val/numBands); } } loc->nBands = 1; return 0; } int Image::convolution() { const int nx = loc.nx; const int ny = loc.ny; const int numBands = loc.nBands; const int sx = 1; const int sy = nx; const int sb = nx * ny; for (int j = 0; j < ny; j++) { for (int i = 0; i < nx; i++) { float val = 0; for (int b = 0; b < numBands; b++) { float d = data[i*sx + j*sy + b*sb]; // val += d*d; val += d; } // data[i*sx + j*sy + 0*sb] = sqrt(val)/numBands; data[i*sx + j*sy + 0*sb] = val/numBands; } } loc.nBands = 1; const int nPad = 15; const int nPad_2 = nPad/2; float * buf = new float[nx*ny]; for (int i = 0; i < nx*ny; i++) buf[i] = 0; float max = -1.0e9; float min = -max; for (int j = nPad_2; j < ny-nPad_2; j++) { for (int i = nPad_2; i < nx-nPad_2; i++) { float av = 0; float sq = 0; for (int kj = 0; kj < nPad; kj++) { for (int ki = 0; ki < nPad; ki++) { int ix = i + ki - nPad_2; int iy = j + kj - nPad_2; float val = data[ix*sx + iy*sy]; av += val; sq += val * val; } } av = av / (nPad*nPad); if (av < min) min = av; if (av > max) max = av; sq = sqrt( sq/(nPad*nPad) - av*av ) + tau; // buf[i*sx + j*sy] = data[i*sx + j*sy] + mid - av; buf[i*sx + j*sy] = .95*255 * (data[i*sx + j*sy] - .95*av) / sq; } } printf("min==%f max==%f\n", min, max); for (int i = 0; i < nx*ny; i++) data[i] = buf[i]; return 0; } } // namespace PV <commit_msg>Fixed minor compiler warnings.<commit_after>/* * Image.cpp * * Created on: Sep 8, 2009 * Author: rasmussn */ #include "Image.hpp" #include "../io/imageio.hpp"; #include <assert.h> #include <string.h> namespace PV { Image::Image(const char * name, HyPerCol * hc) { initialize_base(name, hc); } Image::Image(const char * name, HyPerCol * hc, const char * filename) { initialize_base(name, hc); // get size info from image so that data buffer can be allocated int status = getImageInfo(filename, comm, &loc); // create mpi_datatypes for border transfer mpi_datatypes = Communicator::newDatatypes(&loc); if (status) return; double time = MPI_Wtime(); const int N = (loc.nx + 2*loc.nPad) * (loc.ny + 2*loc.nPad) * loc.nBands; data = new float [N]; for (int i = 0; i < N; ++i) { data[i] = 0; } time = MPI_Wtime() - time; // fprintf(stdout, "alloc: elapsed time = %f\n", (float) time*1000.); time = MPI_Wtime(); read(filename); time = MPI_Wtime() - time; // fprintf(stdout, "copy: elapsed time = %f\n", (float) time*1000.); // for now convert images to grayscale if (loc.nBands > 1) { this->toGrayScale(); } time = MPI_Wtime(); // exchange border information exchange(); time = MPI_Wtime() - time; // fprintf(stdout, "exchange: elapsed time = %f\n", (float) time*1000.); } Image::~Image() { free(name); if (data != NULL) { delete data; data = NULL; } } int Image::initialize_base(const char * name, HyPerCol * hc) { this->name = strdup(name); this->data = NULL; this->comm = hc->icCommunicator(); mpi_datatypes = NULL; PVParams * params = hc->parameters(); loc.nx = 0; loc.ny = 0; loc.nxGlobal = 0; loc.nyGlobal = 0; loc.kx0 = 0; loc.ky0 = 0; loc.nPad = 0; loc.nBands = 0; if (params->present(name, "marginWidth")) { loc.nPad = (int) params->value(name, "marginWidth"); } return 0; } pvdata_t * Image::getImageBuffer() { return data; } LayerLoc Image::getImageLoc() { return loc; } /** * update the image buffers * * return true if buffers have changed */ bool Image::updateImage(float time, float dt) { // default is to do nothing for now // eventually could go through a list of images return false; } int Image::read(const char * filename) { int status = 0; const int n = loc.nx * loc.ny * loc.nBands; unsigned char * buf = new unsigned char[n]; assert(buf != NULL); // read the image and scatter the local portions status = scatterImageFile(filename, comm, &loc, buf); if (status == 0) { status = copyFromInteriorBuffer(buf); } delete buf; return status; } int Image::write(const char * filename) { int status = 0; const int n = loc.nx * loc.ny * loc.nBands; unsigned char * buf = new unsigned char[n]; assert(buf != NULL); status = copyToInteriorBuffer(buf); // gather the local portions and write the image status = gatherImageFile(filename, comm, &loc, buf); delete buf; return status; } int Image::exchange() { return comm->exchange(data, mpi_datatypes, &loc); } int Image::copyToInteriorBuffer(unsigned char * buf) { const int nx = loc.nx; const int ny = loc.ny; const int nxBorder = loc.nPad; const int nyBorder = loc.nPad; const int sy = nx + 2*nxBorder; const int sb = sy * (ny + 2*nyBorder); int ii = 0; for (int b = 0; b < loc.nBands; b++) { for (int j = 0; j < ny; j++) { int jex = j + nyBorder; for (int i = 0; i < nx; i++) { int iex = i + nxBorder; buf[ii++] = (unsigned char) data[iex + jex*sy + b*sb]; } } } return 0; } int Image::copyFromInteriorBuffer(const unsigned char * buf) { const int nx = loc.nx; const int ny = loc.ny; const int nxBorder = loc.nPad; const int nyBorder = loc.nPad; const int sy = nx + 2*nxBorder; const int sb = sy * (ny + 2*nyBorder); int ii = 0; for (int b = 0; b < loc.nBands; b++) { for (int j = 0; j < ny; j++) { int jex = j + nyBorder; for (int i = 0; i < nx; i++) { int iex = i + nxBorder; data[iex + jex*sy + b*sb] = (pvdata_t) buf[ii++]; } } } return 0; } int Image::toGrayScale() { const int nx_ex = loc.nx + 2*loc.nPad; const int ny_ex = loc.ny + 2*loc.nPad; const int numBands = loc.nBands; const int sx = 1; const int sy = nx_ex; const int sb = nx_ex * ny_ex; if (numBands < 2) return 0; for (int j = 0; j < ny_ex; j++) { for (int i = 0; i < nx_ex; i++) { float val = 0; for (int b = 0; b < numBands; b++) { float d = data[i*sx + j*sy + b*sb]; val += d*d; // val += d; } data[i*sx + j*sy + 0*sb] = sqrt(val/numBands); // data[i*sx + j*sy + 0*sb] = val/numBands; } } loc.nBands = 1; return 0; } int Image::convertToGrayScale(LayerLoc * loc, unsigned char * buf) { const int nx = loc->nx; const int ny = loc->ny; const int numBands = loc->nBands; const int sx = 1; const int sy = nx; const int sb = nx * ny; if (numBands < 2) return 0; for (int j = 0; j < ny; j++) { for (int i = 0; i < nx; i++) { float val = 0; for (int b = 0; b < numBands; b++) { float d = buf[i*sx + j*sy + b*sb]; val += d*d; } buf[i*sx + j*sy + 0*sb] = sqrt(val/numBands); } } loc->nBands = 1; return 0; } int Image::convolution() { const int nx = loc.nx; const int ny = loc.ny; const int numBands = loc.nBands; const int sx = 1; const int sy = nx; const int sb = nx * ny; for (int j = 0; j < ny; j++) { for (int i = 0; i < nx; i++) { float val = 0; for (int b = 0; b < numBands; b++) { float d = data[i*sx + j*sy + b*sb]; // val += d*d; val += d; } // data[i*sx + j*sy + 0*sb] = sqrt(val)/numBands; data[i*sx + j*sy + 0*sb] = val/numBands; } } loc.nBands = 1; const int nPad = 15; const int nPad_2 = nPad/2; float * buf = new float[nx*ny]; for (int i = 0; i < nx*ny; i++) buf[i] = 0; float max = -1.0e9; float min = -max; for (int j = nPad_2; j < ny-nPad_2; j++) { for (int i = nPad_2; i < nx-nPad_2; i++) { float av = 0; float sq = 0; for (int kj = 0; kj < nPad; kj++) { for (int ki = 0; ki < nPad; ki++) { int ix = i + ki - nPad_2; int iy = j + kj - nPad_2; float val = data[ix*sx + iy*sy]; av += val; sq += val * val; } } av = av / (nPad*nPad); if (av < min) min = av; if (av > max) max = av; sq = sqrt( sq/(nPad*nPad) - av*av ) + tau; // buf[i*sx + j*sy] = data[i*sx + j*sy] + mid - av; buf[i*sx + j*sy] = .95*255 * (data[i*sx + j*sy] - .95*av) / sq; } } printf("min==%f max==%f\n", min, max); for (int i = 0; i < nx*ny; i++) data[i] = buf[i]; return 0; } } // namespace PV <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: sdclient.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: ka $ $Date: 2001-12-05 15:24:58 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _IPOBJ_HXX //autogen #include <so3/ipobj.hxx> #endif #ifndef _SVDOOLE2_HXX //autogen #include <svx/svdoole2.hxx> #endif #ifndef _SVDOGRAF_HXX //autogen #include <svx/svdograf.hxx> #endif #ifndef _CLIENT_HXX //autogen #include <so3/client.hxx> #endif #ifndef _IPENV_HXX //autogen #include <so3/ipenv.hxx> #endif #ifndef _SVDPAGV_HXX #include <svx/svdpagv.hxx> #endif #pragma hdrstop #include "misc.hxx" #ifdef STARIMAGE_AVAILABLE #ifndef _SIMDLL_HXX #include <sim2/simdll.hxx> #endif #endif #include "strings.hrc" #include "sdclient.hxx" #include "viewshel.hxx" #include "drviewsh.hxx" #include "sdview.hxx" #include "sdwindow.hxx" #include "sdresid.hxx" /************************************************************************* |* |* Ctor |* \************************************************************************/ SdClient::SdClient(SdrOle2Obj* pObj, SdViewShell* pSdViewShell, Window* pWindow) : SfxInPlaceClient(pSdViewShell, pWindow), pViewShell(pSdViewShell), pSdrOle2Obj(pObj), pSdrGrafObj(NULL), pOutlinerParaObj (NULL) { } /************************************************************************* |* |* Dtor |* \************************************************************************/ SdClient::~SdClient() { } /************************************************************************* |* |* Wenn IP-aktiv, dann kommt diese Anforderung um Vergroesserung des |* sichtbaren Ausschnitts des Objektes |* \************************************************************************/ void SdClient::RequestObjAreaPixel(const Rectangle& rRect) { Window* pWin = pViewShell->GetWindow(); Rectangle aObjRect( pWin->PixelToLogic( rRect.TopLeft() ), pWin->PixelToLogic( rRect.GetSize() ) ); SdView* pView = pViewShell->GetView(); Rectangle aWorkArea( pView->GetWorkArea() ); if (!aWorkArea.IsInside(aObjRect)) { // Position korrigieren Point aPos = aObjRect.TopLeft(); Size aSize = aObjRect.GetSize(); Point aWorkAreaTL = aWorkArea.TopLeft(); Point aWorkAreaBR = aWorkArea.BottomRight(); aPos.X() = Max(aPos.X(), aWorkAreaTL.X()); aPos.X() = Min(aPos.X(), aWorkAreaBR.X()-aSize.Width()); aPos.Y() = Max(aPos.Y(), aWorkAreaTL.Y()); aPos.Y() = Min(aPos.Y(), aWorkAreaBR.Y()-aSize.Height()); aObjRect.SetPos(aPos); SfxInPlaceClient::RequestObjAreaPixel(pViewShell->GetWindow()-> LogicToPixel(aObjRect) ); } else { SfxInPlaceClient::RequestObjAreaPixel(rRect); } const SdrMarkList& rMarkList = pView->GetMarkList(); if (rMarkList.GetMarkCount() == 1) { SdrMark* pMark = rMarkList.GetMark(0); SdrObject* pObj = pMark->GetObj(); Rectangle aOldRect( pObj->GetLogicRect() ); if ( aObjRect != aOldRect ) { // Rundungsfehler vermeiden - nur, wenn mindestens 1 Pixel Unterschied // (getrennt fuer Position und Groesse) Size aOnePixel = pWin->PixelToLogic( Size(1, 1) ); Size aLogicSize = aObjRect.GetSize(); Rectangle aNewRect = aOldRect; Size aNewSize = aNewRect.GetSize(); if ( Abs( aObjRect.Left() - aOldRect.Left() ) >= aOnePixel.Width() ) aNewRect.SetPos( Point( aObjRect.Left(), aNewRect.Top() ) ); if ( Abs( aObjRect.Top() - aOldRect.Top() ) >= aOnePixel.Height() ) aNewRect.SetPos( Point( aNewRect.Left(), aObjRect.Top() ) ); if ( Abs( aLogicSize.Width() - aNewSize.Width() ) >= aOnePixel.Width() ) aNewSize.Width() = aLogicSize.Width(); if ( Abs( aLogicSize.Height() - aNewSize.Height() ) >= aOnePixel.Height() ) aNewSize.Height() = aLogicSize.Height(); aNewRect.SetSize( aNewSize ); if ( aNewRect != aOldRect ) // veraendert nur, wenn mindestens 1 Pixel pObj->SetLogicRect( aNewRect ); } } } /************************************************************************* |* |* |* \************************************************************************/ void SdClient::ViewChanged(USHORT nAspect) { // Eventuell neues MetaFile holen SfxInPlaceClient::ViewChanged(nAspect); if (pViewShell->GetActiveWindow()) { SdView* pView = pViewShell->GetView(); if (pView) { SvClientData* pData = GetEnv(); if( pData ) { SvEmbeddedObject* pObj = GetEmbedObj(); MapMode aMap100( MAP_100TH_MM ); Rectangle aVisArea( OutputDevice::LogicToLogic( pObj->GetVisArea(), pObj->GetMapUnit(), aMap100 ) ); Rectangle aLogicRect( pSdrOle2Obj->GetLogicRect() ); Size aScaledSize( static_cast< long >( pData->GetScaleWidth() * Fraction( aVisArea.GetWidth() ) ), static_cast< long >( pData->GetScaleHeight() * Fraction( aVisArea.GetHeight() ) ) ); if( Application::GetDefaultDevice()->LogicToPixel( aScaledSize, aMap100 ) != Application::GetDefaultDevice()->LogicToPixel( aLogicRect.GetSize(), aMap100 ) ) { const sal_Bool bOldLock = pView->GetModel()->isLocked(); pView->GetModel()->setLock( sal_True ); pSdrOle2Obj->SetLogicRect( Rectangle( aLogicRect.TopLeft(), aScaledSize ) ); pView->GetModel()->setLock( bOldLock ); pSdrOle2Obj->SendRepaintBroadcast(); } } } } } /************************************************************************* |* |* InPlace-Objekt aktivieren / deaktivieren |* \************************************************************************/ void SdClient::UIActivate(BOOL bActivate) { SfxInPlaceClient::UIActivate(bActivate); if (!bActivate) { #ifdef STARIMAGE_AVAILABLE if (pSdrGrafObj && pViewShell->GetActiveWindow()) { // Das Ole2Obj (Image) wird gegen das GrafObj ausgetauscht pSdrGrafObj->SetLogicRect(pSdrOle2Obj->GetLogicRect()); SvInPlaceObjectRef aIPObj = pSdrOle2Obj->GetObjRef(); pSdrGrafObj->SetGraphic ( SimDLL::GetGraphic( aIPObj ) ); SdView* pView = pViewShell->GetView(); SdrPageView* pPV = pView->GetPageViewPvNum(0); SdrPage* pPg = pPV->GetPage(); delete pPg->RemoveObject( pSdrOle2Obj->GetOrdNum() ); pSdrGrafObj = NULL; } #endif } } /************************************************************************* |* |* Daten fuer eine ggf. spaeter zu erzeugende View |* \************************************************************************/ void SdClient::MakeViewData() { SfxInPlaceClient::MakeViewData(); SvClientData* pCD = GetClientData(); if (pCD) { SvEmbeddedObject* pObj = GetEmbedObj(); Rectangle aObjVisArea = OutputDevice::LogicToLogic( pObj->GetVisArea(), pObj->GetMapUnit(), MAP_100TH_MM ); Size aVisSize = aObjVisArea.GetSize(); Fraction aFractX = pCD->GetScaleWidth(); Fraction aFractY = pCD->GetScaleHeight(); aFractX *= aVisSize.Width(); aFractY *= aVisSize.Height(); pCD->SetSizeScale(aFractX, aFractY); Rectangle aObjArea = pSdrOle2Obj->GetLogicRect(); pCD->SetObjArea(aObjArea); } } /************************************************************************* |* |* Objekt in den sichtbaren Breich scrollen |* \************************************************************************/ void SdClient::MakeVisible() { SfxInPlaceClient::MakeVisible(); if (pViewShell->ISA(SdDrawViewShell)) { ((SdDrawViewShell*) pViewShell)->MakeVisible(pSdrOle2Obj->GetLogicRect(), *pViewShell->GetActiveWindow()); } } <commit_msg>INTEGRATION: CWS aw003 (1.4.134); FILE MERGED 2003/07/24 14:07:11 aw 1.4.134.1: #110094# Adaptions for DrawingLayer changes<commit_after>/************************************************************************* * * $RCSfile: sdclient.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2003-11-24 17:10:54 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _IPOBJ_HXX //autogen #include <so3/ipobj.hxx> #endif #ifndef _SVDOOLE2_HXX //autogen #include <svx/svdoole2.hxx> #endif #ifndef _SVDOGRAF_HXX //autogen #include <svx/svdograf.hxx> #endif #ifndef _CLIENT_HXX //autogen #include <so3/client.hxx> #endif #ifndef _IPENV_HXX //autogen #include <so3/ipenv.hxx> #endif #ifndef _SVDPAGV_HXX #include <svx/svdpagv.hxx> #endif #pragma hdrstop #include "misc.hxx" #ifdef STARIMAGE_AVAILABLE #ifndef _SIMDLL_HXX #include <sim2/simdll.hxx> #endif #endif #include "strings.hrc" #include "sdclient.hxx" #include "viewshel.hxx" #include "drviewsh.hxx" #include "sdview.hxx" #include "sdwindow.hxx" #include "sdresid.hxx" /************************************************************************* |* |* Ctor |* \************************************************************************/ SdClient::SdClient(SdrOle2Obj* pObj, SdViewShell* pSdViewShell, Window* pWindow) : SfxInPlaceClient(pSdViewShell, pWindow), pViewShell(pSdViewShell), pSdrOle2Obj(pObj), pSdrGrafObj(NULL), pOutlinerParaObj (NULL) { } /************************************************************************* |* |* Dtor |* \************************************************************************/ SdClient::~SdClient() { } /************************************************************************* |* |* Wenn IP-aktiv, dann kommt diese Anforderung um Vergroesserung des |* sichtbaren Ausschnitts des Objektes |* \************************************************************************/ void SdClient::RequestObjAreaPixel(const Rectangle& rRect) { Window* pWin = pViewShell->GetWindow(); Rectangle aObjRect( pWin->PixelToLogic( rRect.TopLeft() ), pWin->PixelToLogic( rRect.GetSize() ) ); SdView* pView = pViewShell->GetView(); Rectangle aWorkArea( pView->GetWorkArea() ); if (!aWorkArea.IsInside(aObjRect)) { // Position korrigieren Point aPos = aObjRect.TopLeft(); Size aSize = aObjRect.GetSize(); Point aWorkAreaTL = aWorkArea.TopLeft(); Point aWorkAreaBR = aWorkArea.BottomRight(); aPos.X() = Max(aPos.X(), aWorkAreaTL.X()); aPos.X() = Min(aPos.X(), aWorkAreaBR.X()-aSize.Width()); aPos.Y() = Max(aPos.Y(), aWorkAreaTL.Y()); aPos.Y() = Min(aPos.Y(), aWorkAreaBR.Y()-aSize.Height()); aObjRect.SetPos(aPos); SfxInPlaceClient::RequestObjAreaPixel(pViewShell->GetWindow()-> LogicToPixel(aObjRect) ); } else { SfxInPlaceClient::RequestObjAreaPixel(rRect); } const SdrMarkList& rMarkList = pView->GetMarkList(); if (rMarkList.GetMarkCount() == 1) { SdrMark* pMark = rMarkList.GetMark(0); SdrObject* pObj = pMark->GetObj(); Rectangle aOldRect( pObj->GetLogicRect() ); if ( aObjRect != aOldRect ) { // Rundungsfehler vermeiden - nur, wenn mindestens 1 Pixel Unterschied // (getrennt fuer Position und Groesse) Size aOnePixel = pWin->PixelToLogic( Size(1, 1) ); Size aLogicSize = aObjRect.GetSize(); Rectangle aNewRect = aOldRect; Size aNewSize = aNewRect.GetSize(); if ( Abs( aObjRect.Left() - aOldRect.Left() ) >= aOnePixel.Width() ) aNewRect.SetPos( Point( aObjRect.Left(), aNewRect.Top() ) ); if ( Abs( aObjRect.Top() - aOldRect.Top() ) >= aOnePixel.Height() ) aNewRect.SetPos( Point( aNewRect.Left(), aObjRect.Top() ) ); if ( Abs( aLogicSize.Width() - aNewSize.Width() ) >= aOnePixel.Width() ) aNewSize.Width() = aLogicSize.Width(); if ( Abs( aLogicSize.Height() - aNewSize.Height() ) >= aOnePixel.Height() ) aNewSize.Height() = aLogicSize.Height(); aNewRect.SetSize( aNewSize ); if ( aNewRect != aOldRect ) // veraendert nur, wenn mindestens 1 Pixel pObj->SetLogicRect( aNewRect ); } } } /************************************************************************* |* |* |* \************************************************************************/ void SdClient::ViewChanged(USHORT nAspect) { // Eventuell neues MetaFile holen SfxInPlaceClient::ViewChanged(nAspect); if (pViewShell->GetActiveWindow()) { SdView* pView = pViewShell->GetView(); if (pView) { SvClientData* pData = GetEnv(); if( pData ) { SvEmbeddedObject* pObj = GetEmbedObj(); MapMode aMap100( MAP_100TH_MM ); Rectangle aVisArea( OutputDevice::LogicToLogic( pObj->GetVisArea(), pObj->GetMapUnit(), aMap100 ) ); Rectangle aLogicRect( pSdrOle2Obj->GetLogicRect() ); Size aScaledSize( static_cast< long >( pData->GetScaleWidth() * Fraction( aVisArea.GetWidth() ) ), static_cast< long >( pData->GetScaleHeight() * Fraction( aVisArea.GetHeight() ) ) ); if( Application::GetDefaultDevice()->LogicToPixel( aScaledSize, aMap100 ) != Application::GetDefaultDevice()->LogicToPixel( aLogicRect.GetSize(), aMap100 ) ) { const sal_Bool bOldLock = pView->GetModel()->isLocked(); pView->GetModel()->setLock( sal_True ); pSdrOle2Obj->SetLogicRect( Rectangle( aLogicRect.TopLeft(), aScaledSize ) ); pView->GetModel()->setLock( bOldLock ); pSdrOle2Obj->BroadcastObjectChange(); } } } } } /************************************************************************* |* |* InPlace-Objekt aktivieren / deaktivieren |* \************************************************************************/ void SdClient::UIActivate(BOOL bActivate) { SfxInPlaceClient::UIActivate(bActivate); if (!bActivate) { #ifdef STARIMAGE_AVAILABLE if (pSdrGrafObj && pViewShell->GetActiveWindow()) { // Das Ole2Obj (Image) wird gegen das GrafObj ausgetauscht pSdrGrafObj->SetLogicRect(pSdrOle2Obj->GetLogicRect()); SvInPlaceObjectRef aIPObj = pSdrOle2Obj->GetObjRef(); pSdrGrafObj->SetGraphic ( SimDLL::GetGraphic( aIPObj ) ); SdView* pView = pViewShell->GetView(); SdrPageView* pPV = pView->GetPageViewPvNum(0); SdrPage* pPg = pPV->GetPage(); delete pPg->RemoveObject( pSdrOle2Obj->GetOrdNum() ); pSdrGrafObj = NULL; } #endif } } /************************************************************************* |* |* Daten fuer eine ggf. spaeter zu erzeugende View |* \************************************************************************/ void SdClient::MakeViewData() { SfxInPlaceClient::MakeViewData(); SvClientData* pCD = GetClientData(); if (pCD) { SvEmbeddedObject* pObj = GetEmbedObj(); Rectangle aObjVisArea = OutputDevice::LogicToLogic( pObj->GetVisArea(), pObj->GetMapUnit(), MAP_100TH_MM ); Size aVisSize = aObjVisArea.GetSize(); Fraction aFractX = pCD->GetScaleWidth(); Fraction aFractY = pCD->GetScaleHeight(); aFractX *= aVisSize.Width(); aFractY *= aVisSize.Height(); pCD->SetSizeScale(aFractX, aFractY); Rectangle aObjArea = pSdrOle2Obj->GetLogicRect(); pCD->SetObjArea(aObjArea); } } /************************************************************************* |* |* Objekt in den sichtbaren Breich scrollen |* \************************************************************************/ void SdClient::MakeVisible() { SfxInPlaceClient::MakeVisible(); if (pViewShell->ISA(SdDrawViewShell)) { ((SdDrawViewShell*) pViewShell)->MakeVisible(pSdrOle2Obj->GetLogicRect(), *pViewShell->GetActiveWindow()); } } <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2009 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 "OgreNaClGLContext.h" #include "OgreLog.h" #include "OgreException.h" #include "OgreRoot.h" #include "OgreException.h" #include "OgreLogManager.h" #include "OgreStringConverter.h" #include "OgreWindowEventUtilities.h" #include "OgreGLES2Prerequisites.h" #include "OgreGLES2RenderSystem.h" #include "OgreNaClGLSupport.h" #include "OgreNaClWindow.h" #include "OgreNaClGLContext.h" #include <stdint.h> namespace Ogre { NaClGLContext::NaClGLContext(const NaClWindow * window, const NaClGLSupport *glsupport, pp::Instance* instance, pp::CompletionCallback* swapCallback) : pp::Graphics3DClient(instance) , mWindow(window) , mGLSupport(glsupport) , mInstance(instance) , mSwapCallback(swapCallback) , mWidth(mWindow->getWidth()) , mHeight(mWindow->getHeight()) { } NaClGLContext::~NaClGLContext() { glSetCurrentContextPPAPI(0); } void NaClGLContext::setCurrent() { if (mInstance == NULL) { glSetCurrentContextPPAPI(0); return; } // Lazily create the Pepper context. if (mContext.is_null()) { LogManager::getSingleton().logMessage("\tcreate context started"); int32_t attribs[] = { PP_GRAPHICS3DATTRIB_ALPHA_SIZE, 0, PP_GRAPHICS3DATTRIB_BLUE_SIZE, 8, PP_GRAPHICS3DATTRIB_GREEN_SIZE, 8, PP_GRAPHICS3DATTRIB_RED_SIZE, 8, PP_GRAPHICS3DATTRIB_DEPTH_SIZE, 24, PP_GRAPHICS3DATTRIB_STENCIL_SIZE, 8, PP_GRAPHICS3DATTRIB_SAMPLES, 0, PP_GRAPHICS3DATTRIB_SAMPLE_BUFFERS, 0, PP_GRAPHICS3DATTRIB_WIDTH, mWindow->getWidth(), PP_GRAPHICS3DATTRIB_HEIGHT, mWindow->getHeight(), PP_GRAPHICS3DATTRIB_NONE }; mContext = pp::Graphics3D(mInstance, pp::Graphics3D(), attribs); if (mContext.is_null()) { glSetCurrentContextPPAPI(0); return; } mInstance->BindGraphics(mContext); } glSetCurrentContextPPAPI(mContext.pp_resource()); return; } void NaClGLContext::endCurrent() { glSetCurrentContextPPAPI(0); } GLES2Context* NaClGLContext::clone() const { NaClGLContext* res = new NaClGLContext(mWindow, mGLSupport, mInstance, mSwapCallback); res->mInstance = this->mInstance; return res; } void NaClGLContext::swapBuffers( bool waitForVSync ) { mContext.SwapBuffers(*mSwapCallback); } // overrides pp::Graphics3DClient void NaClGLContext::Graphics3DContextLost() { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unexpectedly lost graphics context.", "NaClGLContext::Graphics3DContextLost" ); } void NaClGLContext::resize() { if(mWidth != mWindow->getWidth() || mHeight != mWindow->getHeight() ) { LogManager::getSingleton().logMessage("\tresizing"); mWidth = mWindow->getWidth(); mHeight = mWindow->getHeight(); glSetCurrentContextPPAPI(0); mContext.ResizeBuffers( mWidth, mHeight ); glSetCurrentContextPPAPI(mContext.pp_resource()); LogManager::getSingleton().logMessage("\tdone resizing"); } } } // namespace <commit_msg>Backed out changeset: 7631baa16dc0 Seems that there are better solutions for this issue: https://groups.google.com/d/msg/native-client-discuss/DQvA8VyvEKY/rljYZc4qfQgJ<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2009 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 "OgreNaClGLContext.h" #include "OgreLog.h" #include "OgreException.h" #include "OgreRoot.h" #include "OgreException.h" #include "OgreLogManager.h" #include "OgreStringConverter.h" #include "OgreWindowEventUtilities.h" #include "OgreGLES2Prerequisites.h" #include "OgreGLES2RenderSystem.h" #include "OgreNaClGLSupport.h" #include "OgreNaClWindow.h" #include "OgreNaClGLContext.h" #include <stdint.h> namespace Ogre { NaClGLContext::NaClGLContext(const NaClWindow * window, const NaClGLSupport *glsupport, pp::Instance* instance, pp::CompletionCallback* swapCallback) : pp::Graphics3DClient(instance) , mWindow(window) , mGLSupport(glsupport) , mInstance(instance) , mSwapCallback(swapCallback) , mWidth(mWindow->getWidth()) , mHeight(mWindow->getHeight()) { } NaClGLContext::~NaClGLContext() { glSetCurrentContextPPAPI(0); } void NaClGLContext::setCurrent() { if (mInstance == NULL) { glSetCurrentContextPPAPI(0); return; } // Lazily create the Pepper context. if (mContext.is_null()) { LogManager::getSingleton().logMessage("\tcreate context started"); int32_t attribs[] = { PP_GRAPHICS3DATTRIB_ALPHA_SIZE, 8, PP_GRAPHICS3DATTRIB_DEPTH_SIZE, 24, PP_GRAPHICS3DATTRIB_STENCIL_SIZE, 8, PP_GRAPHICS3DATTRIB_SAMPLES, 0, PP_GRAPHICS3DATTRIB_SAMPLE_BUFFERS, 0, PP_GRAPHICS3DATTRIB_WIDTH, mWindow->getWidth(), PP_GRAPHICS3DATTRIB_HEIGHT, mWindow->getHeight(), PP_GRAPHICS3DATTRIB_NONE }; mContext = pp::Graphics3D(mInstance, pp::Graphics3D(), attribs); if (mContext.is_null()) { glSetCurrentContextPPAPI(0); return; } mInstance->BindGraphics(mContext); } glSetCurrentContextPPAPI(mContext.pp_resource()); return; } void NaClGLContext::endCurrent() { glSetCurrentContextPPAPI(0); } GLES2Context* NaClGLContext::clone() const { NaClGLContext* res = new NaClGLContext(mWindow, mGLSupport, mInstance, mSwapCallback); res->mInstance = this->mInstance; return res; } void NaClGLContext::swapBuffers( bool waitForVSync ) { mContext.SwapBuffers(*mSwapCallback); } // overrides pp::Graphics3DClient void NaClGLContext::Graphics3DContextLost() { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unexpectedly lost graphics context.", "NaClGLContext::Graphics3DContextLost" ); } void NaClGLContext::resize() { if(mWidth != mWindow->getWidth() || mHeight != mWindow->getHeight() ) { LogManager::getSingleton().logMessage("\tresizing"); mWidth = mWindow->getWidth(); mHeight = mWindow->getHeight(); glSetCurrentContextPPAPI(0); mContext.ResizeBuffers( mWidth, mHeight ); glSetCurrentContextPPAPI(mContext.pp_resource()); LogManager::getSingleton().logMessage("\tdone resizing"); } } } // namespace <|endoftext|>
<commit_before>/* * This source file is part of ArkGameFrame * For the latest info, see https://github.com/ArkGame * * Copyright (c) 2013-2018 ArkGame 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 "AFCPluginManager.h" #include "SDK/Core/Base/AFPlatform.hpp" #if ARK_PLATFORM == PLATFORM_UNIX #include <unistd.h> #include <netdb.h> #include <arpa/inet.h> #include <signal.h> #include <sys/prctl.h> #endif bool bExitApp = false; std::thread gBackThread; #if ARK_PLATFORM == PLATFORM_WIN #include <Dbghelp.h> #pragma comment(lib, "DbgHelp") #if ARK_RUN_MODE == ARK_RUN_MODE_DEBUG #pragma comment(lib, "AFCore_d.lib") #else #pragma comment(lib, "AFCore.lib") #endif // 创建Dump文件 void CreateDumpFile(const std::string& strDumpFilePathName, EXCEPTION_POINTERS* pException) { // 创建Dump文件 HANDLE hDumpFile = CreateFile(strDumpFilePathName.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); // Dump信息 MINIDUMP_EXCEPTION_INFORMATION dumpInfo; dumpInfo.ExceptionPointers = pException; dumpInfo.ThreadId = GetCurrentThreadId(); dumpInfo.ClientPointers = TRUE; // 写入Dump文件内容 MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL); CloseHandle(hDumpFile); } // 处理Unhandled Exception的回调函数 long ApplicationCrashHandler(EXCEPTION_POINTERS* pException) { time_t t = time(0); char szDmupName[MAX_PATH]; tm* ptm = localtime(&t); sprintf_s(szDmupName, "%04d_%02d_%02d_%02d_%02d_%02d.dmp", ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec); CreateDumpFile(szDmupName, pException); FatalAppExit(-1, szDmupName); return EXCEPTION_EXECUTE_HANDLER; } #endif void CloseXButton() { #if ARK_PLATFORM == PLATFORM_WIN HWND hWnd = GetConsoleWindow(); if(hWnd) { HMENU hMenu = GetSystemMenu(hWnd, FALSE); EnableMenuItem(hMenu, SC_CLOSE, MF_DISABLED | MF_BYCOMMAND); } #endif } void InitDaemon() { #if ARK_PLATFORM == PLATFORM_UNIX daemon(1, 0); // ignore signals signal(SIGINT, SIG_IGN); signal(SIGHUP, SIG_IGN); signal(SIGQUIT, SIG_IGN); signal(SIGPIPE, SIG_IGN); signal(SIGTTOU, SIG_IGN); signal(SIGTTIN, SIG_IGN); signal(SIGTERM, SIG_IGN); #endif } void EchoArkLogo() { #if ARK_PLATFORM == PLATFORM_WIN SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); #endif std::cout << " _ _ ____ _ _ _ " << std::endl; std::cout << " / \\ _ __| | __ / ___|| |_ _ _ __| (_) ___ " << std::endl; std::cout << " / _ \\ | '__| |/ / \\___ \\| __| | | |/ _` | |/ _ \\ " << std::endl; std::cout << " / ___ \\| | | < ___) | |_| |_| | (_| | | (_) |" << std::endl; std::cout << " /_/ \\_\\_| |_|\\_\\ |____/ \\__|\\__,_|\\__,_|_|\\___/ " << std::endl; std::cout << std::endl; std::cout << "COPYRIGHT (c) 2013-2018 Ark Studio" << std::endl; std::cout << "All RIGHTS RESERVED." << std::endl; std::cout << "HTTPS://ARKGAME.NET" << std::endl; std::cout << "********************************************" << std::endl; #if ARK_PLATFORM == PLATFORM_WIN SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); #endif } void Usage() { std::cout << "Ark PluginLoader usage:" << std::endl; std::cout << "./PluginLoader [options]" << std::endl; std::cout << "Option:" << std::endl; std::cout << "\t" << "-d, Run as daemon, just take effect in Linux" << std::endl; std::cout << "\t" << "-x, Remove close button, just take effect in Windows" << std::endl; std::cout << "\t" << "cfg=plugin.xml, plugin configuration files" << std::endl; std::cout << "\t" << "app_id=1, set application's id" << std::endl; std::cout << "\t" << "app_name=GameServer, set application's name" << std::endl; std::cout << "i.e. ./PluginLoader -d -x cfg=plugin.xml app_id=1 app_name=my_test" << std::endl; } void ThreadFunc() { while(!bExitApp) { std::this_thread::sleep_for(std::chrono::milliseconds(1000)); std::string s; std::cin >> s; std::transform(s.begin(), s.end(), s.begin(), ::tolower); if(s == "exit") { bExitApp = true; } else if(s == "help") { Usage(); } } } void CreateBackThread() { gBackThread = std::thread(std::bind(&ThreadFunc)); //std::cout << "CreateBackThread, thread ID = " << gThread.get_id() << std::endl; } struct ApplicationConfig { bool deamon = true; //run as deamon, Linux bool xbutton = true; //close X button in windows std::string plugin_file = "Plugin.xml"; //config file int app_id = 0; //app id std::string app_name = ""; //app name }; #if ARK_PLATFORM == PLATFORM_UNIX extern char** environ; struct environ_guard { public: ~environ_guard() { if(env_buf) { delete[] env_buf; env_buf = nullptr; } if(environ) { delete[] environ; environ = nullptr; } } char* env_buf; char** environ; }; environ_guard g_new_environ_guard{ nullptr, nullptr }; int realloc_environ() { int var_count = 0; int env_size = 0; { char** ep = environ; while(*ep) { env_size += std::strlen(*ep) + 1; ++var_count; ++ep; } } char* new_env_buf = new char[env_size]; std::memcpy((void *)new_env_buf, (void *)*environ, env_size); char** new_env = new char*[var_count + 1]; { int var = 0; int offset = 0; char** ep = environ; while(*ep) { new_env[var++] = (new_env_buf + offset); offset += std::strlen(*ep) + 1; ++ep; } } new_env[var_count] = 0; // RAII to prevent memory leak g_new_environ_guard = environ_guard{ new_env_buf, new_env }; environ = new_env; return env_size; } void setproctitle(const char* title, int argc, char** argv) { int argv_size = 0; for(int i = 0; i < argc; ++i) { int len = std::strlen(argv[i]); std::memset(argv[i], 0, len); argv_size += len; } int to_be_copied = std::strlen(title); if(argv_size <= to_be_copied) { int env_size = realloc_environ(); if(env_size < to_be_copied) { to_be_copied = env_size; } } std::strncpy(argv[0], title, to_be_copied); *(argv[0] + to_be_copied) = 0; } #endif bool ProcArgList(int argc, char* argv[]) { //Echo logo EchoArkLogo(); //Analyse arg list ApplicationConfig config; for(int i = 0; i < argc; ++i) { std::string arg = argv[i]; if(arg == "-d") { config.deamon = true; } else if(arg == "-x") { config.xbutton = true; } else if(arg.find("cfg") != std::string::npos) { size_t pos = arg.find("="); if(pos != std::string::npos) { config.plugin_file = arg.substr(pos + 1, arg.length() - pos - 1); } } else if(arg.find("app_id") != std::string::npos) { size_t pos = arg.find("="); if(pos != std::string::npos) { config.app_id = ARK_LEXICAL_CAST<int>(arg.substr(pos + 1, arg.length() - pos - 1)); } } else if(arg.find("app_name") != std::string::npos) { size_t pos = arg.find("="); if(pos != std::string::npos) { config.app_name = arg.substr(pos + 1, arg.length() - pos - 1); } } } if(config.deamon) { #if ARK_PLATFORM == PLATFORM_UNIX //Run as a daemon process signal(SIGPIPE, SIG_IGN); signal(SIGCHLD, SIG_IGN); #endif } if(config.xbutton) { #if ARK_PLATFORM == PLATFORM_WIN SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ApplicationCrashHandler); CloseXButton(); #endif } //暂时还从plugin.xml中获取app id,不做强制要求 //如果要做多开,则需要自己处理 //if(config.app_id == 0) //{ // std::cout << "parameter app_id is invalid, please check." << std::endl; // return false; //} //暂时app name也可以不用传参 //if(config.app_name.empty()) //{ // std::cout << "parameter app_name is invalid, please check." << std::endl; // return false; //} //Set plugin file AFCPluginManager::GetInstancePtr()->SetConfigName(config.plugin_file); AFCPluginManager::GetInstancePtr()->SetAppID(config.app_id); std::string process_name = "[" + config.app_name + ":" + ARK_TO_STRING(config.app_id) + "]"; //Set process name #if ARK_PLATFORM == PLATFORM_WIN SetConsoleTitle(process_name.c_str()); #elif ARK_PLATFORM == PLATFORM_UNIX setproctitle(process_name, argc, argv); #endif //Create back thread, for some cmd CreateBackThread(); return true; } void MainLoop() { #if ARK_PLATFORM == PLATFORM_WIN __try { AFCPluginManager::GetInstancePtr()->Update(); } __except(ApplicationCrashHandler(GetExceptionInformation())) { } #else AFCPluginManager::GetInstancePtr()->Update(); #endif } int main(int argc, char* argv[]) { //arg list //-d, Run as daemon, just take effect in Linux //-x, Remove close button, just take effect in Windows //cfg=plugin.xml, plugin configuration files //app_id=1, set application's id //app_name=GameServer, set application's name if(!ProcArgList(argc, argv)) { std::cout << "Application parameter is invalid, please check it..." << std::endl; Usage(); return -1; } AFCPluginManager::GetInstancePtr()->Init(); AFCPluginManager::GetInstancePtr()->PostInit(); AFCPluginManager::GetInstancePtr()->CheckConfig(); AFCPluginManager::GetInstancePtr()->PreUpdate(); while(!bExitApp) //DEBUG版本崩溃,RELEASE不崩 { while(true) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); if(bExitApp) { break; } MainLoop(); } } AFCPluginManager::GetInstancePtr()->PreShut(); AFCPluginManager::GetInstancePtr()->Shut(); AFCPluginManager::GetInstancePtr()->ReleaseInstance(); gBackThread.join(); return 0; }<commit_msg>fix error arg<commit_after>/* * This source file is part of ArkGameFrame * For the latest info, see https://github.com/ArkGame * * Copyright (c) 2013-2018 ArkGame 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 "AFCPluginManager.h" #include "SDK/Core/Base/AFPlatform.hpp" #if ARK_PLATFORM == PLATFORM_UNIX #include <unistd.h> #include <netdb.h> #include <arpa/inet.h> #include <signal.h> #include <sys/prctl.h> #endif bool bExitApp = false; std::thread gBackThread; #if ARK_PLATFORM == PLATFORM_WIN #include <Dbghelp.h> #pragma comment(lib, "DbgHelp") #if ARK_RUN_MODE == ARK_RUN_MODE_DEBUG #pragma comment(lib, "AFCore_d.lib") #else #pragma comment(lib, "AFCore.lib") #endif // 创建Dump文件 void CreateDumpFile(const std::string& strDumpFilePathName, EXCEPTION_POINTERS* pException) { // 创建Dump文件 HANDLE hDumpFile = CreateFile(strDumpFilePathName.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); // Dump信息 MINIDUMP_EXCEPTION_INFORMATION dumpInfo; dumpInfo.ExceptionPointers = pException; dumpInfo.ThreadId = GetCurrentThreadId(); dumpInfo.ClientPointers = TRUE; // 写入Dump文件内容 MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL); CloseHandle(hDumpFile); } // 处理Unhandled Exception的回调函数 long ApplicationCrashHandler(EXCEPTION_POINTERS* pException) { time_t t = time(0); char szDmupName[MAX_PATH]; tm* ptm = localtime(&t); sprintf_s(szDmupName, "%04d_%02d_%02d_%02d_%02d_%02d.dmp", ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec); CreateDumpFile(szDmupName, pException); FatalAppExit(-1, szDmupName); return EXCEPTION_EXECUTE_HANDLER; } #endif void CloseXButton() { #if ARK_PLATFORM == PLATFORM_WIN HWND hWnd = GetConsoleWindow(); if(hWnd) { HMENU hMenu = GetSystemMenu(hWnd, FALSE); EnableMenuItem(hMenu, SC_CLOSE, MF_DISABLED | MF_BYCOMMAND); } #endif } void InitDaemon() { #if ARK_PLATFORM == PLATFORM_UNIX daemon(1, 0); // ignore signals signal(SIGINT, SIG_IGN); signal(SIGHUP, SIG_IGN); signal(SIGQUIT, SIG_IGN); signal(SIGPIPE, SIG_IGN); signal(SIGTTOU, SIG_IGN); signal(SIGTTIN, SIG_IGN); signal(SIGTERM, SIG_IGN); #endif } void EchoArkLogo() { #if ARK_PLATFORM == PLATFORM_WIN SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); #endif std::cout << " _ _ ____ _ _ _ " << std::endl; std::cout << " / \\ _ __| | __ / ___|| |_ _ _ __| (_) ___ " << std::endl; std::cout << " / _ \\ | '__| |/ / \\___ \\| __| | | |/ _` | |/ _ \\ " << std::endl; std::cout << " / ___ \\| | | < ___) | |_| |_| | (_| | | (_) |" << std::endl; std::cout << " /_/ \\_\\_| |_|\\_\\ |____/ \\__|\\__,_|\\__,_|_|\\___/ " << std::endl; std::cout << std::endl; std::cout << "COPYRIGHT (c) 2013-2018 Ark Studio" << std::endl; std::cout << "All RIGHTS RESERVED." << std::endl; std::cout << "HTTPS://ARKGAME.NET" << std::endl; std::cout << "********************************************" << std::endl; #if ARK_PLATFORM == PLATFORM_WIN SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); #endif } void Usage() { std::cout << "Ark PluginLoader usage:" << std::endl; std::cout << "./PluginLoader [options]" << std::endl; std::cout << "Option:" << std::endl; std::cout << "\t" << "-d, Run as daemon, just take effect in Linux" << std::endl; std::cout << "\t" << "-x, Remove close button, just take effect in Windows" << std::endl; std::cout << "\t" << "cfg=plugin.xml, plugin configuration files" << std::endl; std::cout << "\t" << "app_id=1, set application's id" << std::endl; std::cout << "\t" << "app_name=GameServer, set application's name" << std::endl; std::cout << "i.e. ./PluginLoader -d -x cfg=plugin.xml app_id=1 app_name=my_test" << std::endl; } void ThreadFunc() { while(!bExitApp) { std::this_thread::sleep_for(std::chrono::milliseconds(1000)); std::string s; std::cin >> s; std::transform(s.begin(), s.end(), s.begin(), ::tolower); if(s == "exit") { bExitApp = true; } else if(s == "help") { Usage(); } } } void CreateBackThread() { gBackThread = std::thread(std::bind(&ThreadFunc)); //std::cout << "CreateBackThread, thread ID = " << gThread.get_id() << std::endl; } struct ApplicationConfig { bool deamon = true; //run as deamon, Linux bool xbutton = true; //close X button in windows std::string plugin_file = "Plugin.xml"; //config file int app_id = 0; //app id std::string app_name = ""; //app name }; #if ARK_PLATFORM == PLATFORM_UNIX extern char** environ; struct environ_guard { public: ~environ_guard() { if(env_buf) { delete[] env_buf; env_buf = nullptr; } if(environ) { delete[] environ; environ = nullptr; } } char* env_buf; char** environ; }; environ_guard g_new_environ_guard{ nullptr, nullptr }; int realloc_environ() { int var_count = 0; int env_size = 0; { char** ep = environ; while(*ep) { env_size += std::strlen(*ep) + 1; ++var_count; ++ep; } } char* new_env_buf = new char[env_size]; std::memcpy((void *)new_env_buf, (void *)*environ, env_size); char** new_env = new char*[var_count + 1]; { int var = 0; int offset = 0; char** ep = environ; while(*ep) { new_env[var++] = (new_env_buf + offset); offset += std::strlen(*ep) + 1; ++ep; } } new_env[var_count] = 0; // RAII to prevent memory leak g_new_environ_guard = environ_guard{ new_env_buf, new_env }; environ = new_env; return env_size; } void setproctitle(const char* title, int argc, char** argv) { int argv_size = 0; for(int i = 0; i < argc; ++i) { int len = std::strlen(argv[i]); std::memset(argv[i], 0, len); argv_size += len; } int to_be_copied = std::strlen(title); if(argv_size <= to_be_copied) { int env_size = realloc_environ(); if(env_size < to_be_copied) { to_be_copied = env_size; } } std::strncpy(argv[0], title, to_be_copied); *(argv[0] + to_be_copied) = 0; } #endif bool ProcArgList(int argc, char* argv[]) { //Echo logo EchoArkLogo(); //Analyse arg list ApplicationConfig config; for(int i = 0; i < argc; ++i) { std::string arg = argv[i]; if(arg == "-d") { config.deamon = true; } else if(arg == "-x") { config.xbutton = true; } else if(arg.find("cfg") != std::string::npos) { size_t pos = arg.find("="); if(pos != std::string::npos) { config.plugin_file = arg.substr(pos + 1, arg.length() - pos - 1); } } else if(arg.find("app_id") != std::string::npos) { size_t pos = arg.find("="); if(pos != std::string::npos) { config.app_id = ARK_LEXICAL_CAST<int>(arg.substr(pos + 1, arg.length() - pos - 1)); } } else if(arg.find("app_name") != std::string::npos) { size_t pos = arg.find("="); if(pos != std::string::npos) { config.app_name = arg.substr(pos + 1, arg.length() - pos - 1); } } } if(config.deamon) { #if ARK_PLATFORM == PLATFORM_UNIX //Run as a daemon process signal(SIGPIPE, SIG_IGN); signal(SIGCHLD, SIG_IGN); #endif } if(config.xbutton) { #if ARK_PLATFORM == PLATFORM_WIN SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ApplicationCrashHandler); CloseXButton(); #endif } //暂时还从plugin.xml中获取app id,不做强制要求 //如果要做多开,则需要自己处理 //if(config.app_id == 0) //{ // std::cout << "parameter app_id is invalid, please check." << std::endl; // return false; //} //暂时app name也可以不用传参 //if(config.app_name.empty()) //{ // std::cout << "parameter app_name is invalid, please check." << std::endl; // return false; //} //Set plugin file AFCPluginManager::GetInstancePtr()->SetConfigName(config.plugin_file); AFCPluginManager::GetInstancePtr()->SetAppID(config.app_id); std::string process_name = "[" + config.app_name + ":" + ARK_TO_STRING(config.app_id) + "]"; //Set process name #if ARK_PLATFORM == PLATFORM_WIN SetConsoleTitle(process_name.c_str()); #elif ARK_PLATFORM == PLATFORM_UNIX setproctitle(process_name.c_str(), argc, argv); #endif //Create back thread, for some cmd CreateBackThread(); return true; } void MainLoop() { #if ARK_PLATFORM == PLATFORM_WIN __try { AFCPluginManager::GetInstancePtr()->Update(); } __except(ApplicationCrashHandler(GetExceptionInformation())) { } #else AFCPluginManager::GetInstancePtr()->Update(); #endif } int main(int argc, char* argv[]) { //arg list //-d, Run as daemon, just take effect in Linux //-x, Remove close button, just take effect in Windows //cfg=plugin.xml, plugin configuration files //app_id=1, set application's id //app_name=GameServer, set application's name if(!ProcArgList(argc, argv)) { std::cout << "Application parameter is invalid, please check it..." << std::endl; Usage(); return -1; } AFCPluginManager::GetInstancePtr()->Init(); AFCPluginManager::GetInstancePtr()->PostInit(); AFCPluginManager::GetInstancePtr()->CheckConfig(); AFCPluginManager::GetInstancePtr()->PreUpdate(); while(!bExitApp) //DEBUG版本崩溃,RELEASE不崩 { while(true) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); if(bExitApp) { break; } MainLoop(); } } AFCPluginManager::GetInstancePtr()->PreShut(); AFCPluginManager::GetInstancePtr()->Shut(); AFCPluginManager::GetInstancePtr()->ReleaseInstance(); gBackThread.join(); return 0; }<|endoftext|>
<commit_before>/* Copyright (c) 2014 Quanta Research Cambridge, Inc * * 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 <assert.h> #include <fcntl.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/uio.h> #include <unistd.h> #include <stdio.h> #include <sys/mman.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <sys/ioctl.h> #include <sys/time.h> #include "P4TopIndication.h" #include "P4TopRequest.h" #include "GeneratedTypes.h" #include "utils.h" #ifndef le32 #define le32 int32_t #endif #ifndef u32 #define u32 u_int32_t #endif #ifndef u16 #define u16 u_int16_t #endif #ifndef s32 #define s32 int32_t #endif #define DATA_WIDTH 128 struct pcap_file_header { u32 magic; u16 version_major; u16 version_minor; s32 thiszone; /* gmt to local correction */ u32 sigfigs; /* accuracy of timL1 cache bytes userspaceestamps */ u32 snaplen; /* max length saved portion of each pkt */ u32 linktype; /* data link type (LINKTYPE_*) */ } __attribute__((packed)); struct pcap_pkthdr_ts { le32 hts_sec; le32 hts_usec; } __attribute__((packed)); struct pcap_pkthdr { struct pcap_pkthdr_ts ts; /* time stamp */ le32 caplen; /* length of portion present */ le32 length; /* length this packet (off wire) */ } __attribute__((packed)); void mem_copy(const void *buff, int length); static P4TopRequestProxy *device = 0; class P4TopIndication : public P4TopIndicationWrapper { public: virtual void sonic_read_version_resp(uint32_t a) { fprintf(stderr, "version %08x\n", a); } virtual void matchTableResponse(uint32_t key, uint32_t value) { fprintf(stderr, "\nkey = %u value = %u\n", key, value); } P4TopIndication(unsigned int id) : P4TopIndicationWrapper(id) {} }; void mem_copy(const void *buff, int packet_size) { int i, sop, eop; uint64_t data[2]; int numBeats; numBeats = packet_size / 8; // 16 bytes per beat for 128-bit datawidth; if (packet_size % 8) numBeats++; PRINT_INFO("nBeats=%d, packetSize=%d\n", numBeats, packet_size); for (i=0; i<numBeats; i++) { data[i%2] = *(static_cast<const uint64_t *>(buff) + i); sop = (i/2 == 0); eop = (i/2 == (numBeats-1)/2); if (i%2) { device->writePacketData(data, sop, eop); PRINT_INFO("%016lx %016lx %d %d\n", data[1], data[0], sop, eop); } // last beat, padding with zero if ((numBeats%2!=0) && (i==numBeats-1)) { sop = (i/2 == 0) ? 1 : 0; eop = 1; data[1] = 0; device->writePacketData(data, sop, eop); PRINT_INFO("%016lx %016lx %d %d\n", data[1], data[0], sop, eop); } } } /** * Send packet on quick_tx device * @param qtx pointer to a quick_tx structure * @param buffer full packet data starting at the ETH frame * @param length length of packet (must be over 0) * @return length of packet if it was successfully queued, QTX_E_EXIT if a critical error occurred * and close needs to be called */ static inline int quick_tx_send_packet(const void* buffer, int length) { assert(buffer); assert(length > 0); #ifdef EXTRA_DEBUG printf("[quick_tx] Copying data from %p buffer, length = %d\n", (buffer, length); #endif mem_copy(buffer, length); return length; } bool read_pcap_file(char* filename, void** buffer, long *length) { FILE *infile; long length_read; infile = fopen(filename, "r"); if(infile == NULL) { printf("File does not exist!\n"); return false; } fseek(infile, 0L, SEEK_END); *length = ftell(infile); fseek(infile, 0L, SEEK_SET); *buffer = (char*)calloc(*length, sizeof(char)); /* memory error */ if(*buffer == NULL) { printf("Could not allocate %ld bytes of memory!\n", *length); return false; } length_read = fread(*buffer, sizeof(char), *length, infile); *length = length_read; fclose(infile); return true; } int main(int argc, char **argv) { void *buffer; long length; struct pcap_pkthdr* pcap_hdr; int i; int loops = 1; P4TopIndication echoIndication(IfcNames_P4TopIndicationH2S); device = new P4TopRequestProxy(IfcNames_P4TopRequestS2H); device->sonic_read_version(); device->matchTableRequest(10, 15, 1); device->matchTableRequest(10, 0, 0); fprintf(stderr, "Attempts to read pcap file %s\n", argv[1]); if (!read_pcap_file(argv[1], &buffer, &length)) { perror("Failed to read file!"); exit(-1); } for (i = 0; i < loops; i++) { void* offset = static_cast<char *>(buffer) + sizeof(struct pcap_file_header); while(offset < static_cast<char *>(buffer) + length) { pcap_hdr = (struct pcap_pkthdr*) offset; offset = static_cast<char *>(offset) + sizeof(struct pcap_pkthdr); if ((quick_tx_send_packet((const void*)offset, pcap_hdr->caplen)) < 0) { printf("An error occurred while trying to send a packet\n"); exit(-1); } offset = static_cast<char *>(offset) + pcap_hdr->caplen; } } while(1) sleep(1); return 0; } <commit_msg>added while(1);<commit_after>/* Copyright (c) 2014 Quanta Research Cambridge, Inc * * 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 <assert.h> #include <fcntl.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/uio.h> #include <unistd.h> #include <stdio.h> #include <sys/mman.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <sys/ioctl.h> #include <sys/time.h> #include "P4TopIndication.h" #include "P4TopRequest.h" #include "GeneratedTypes.h" #include "utils.h" #ifndef le32 #define le32 int32_t #endif #ifndef u32 #define u32 u_int32_t #endif #ifndef u16 #define u16 u_int16_t #endif #ifndef s32 #define s32 int32_t #endif #define DATA_WIDTH 128 struct pcap_file_header { u32 magic; u16 version_major; u16 version_minor; s32 thiszone; /* gmt to local correction */ u32 sigfigs; /* accuracy of timL1 cache bytes userspaceestamps */ u32 snaplen; /* max length saved portion of each pkt */ u32 linktype; /* data link type (LINKTYPE_*) */ } __attribute__((packed)); struct pcap_pkthdr_ts { le32 hts_sec; le32 hts_usec; } __attribute__((packed)); struct pcap_pkthdr { struct pcap_pkthdr_ts ts; /* time stamp */ le32 caplen; /* length of portion present */ le32 length; /* length this packet (off wire) */ } __attribute__((packed)); void mem_copy(const void *buff, int length); static P4TopRequestProxy *device = 0; class P4TopIndication : public P4TopIndicationWrapper { public: virtual void sonic_read_version_resp(uint32_t a) { fprintf(stderr, "version %08x\n", a); } virtual void matchTableResponse(uint32_t key, uint32_t value) { fprintf(stderr, "\nkey = %u value = %u\n", key, value); } P4TopIndication(unsigned int id) : P4TopIndicationWrapper(id) {} }; void mem_copy(const void *buff, int packet_size) { int i, sop, eop; uint64_t data[2]; int numBeats; numBeats = packet_size / 8; // 16 bytes per beat for 128-bit datawidth; if (packet_size % 8) numBeats++; PRINT_INFO("nBeats=%d, packetSize=%d\n", numBeats, packet_size); for (i=0; i<numBeats; i++) { data[i%2] = *(static_cast<const uint64_t *>(buff) + i); sop = (i/2 == 0); eop = (i/2 == (numBeats-1)/2); if (i%2) { device->writePacketData(data, sop, eop); PRINT_INFO("%016lx %016lx %d %d\n", data[1], data[0], sop, eop); } // last beat, padding with zero if ((numBeats%2!=0) && (i==numBeats-1)) { sop = (i/2 == 0) ? 1 : 0; eop = 1; data[1] = 0; device->writePacketData(data, sop, eop); PRINT_INFO("%016lx %016lx %d %d\n", data[1], data[0], sop, eop); } } } /** * Send packet on quick_tx device * @param qtx pointer to a quick_tx structure * @param buffer full packet data starting at the ETH frame * @param length length of packet (must be over 0) * @return length of packet if it was successfully queued, QTX_E_EXIT if a critical error occurred * and close needs to be called */ static inline int quick_tx_send_packet(const void* buffer, int length) { assert(buffer); assert(length > 0); #ifdef EXTRA_DEBUG printf("[quick_tx] Copying data from %p buffer, length = %d\n", (buffer, length); #endif mem_copy(buffer, length); return length; } bool read_pcap_file(char* filename, void** buffer, long *length) { FILE *infile; long length_read; infile = fopen(filename, "r"); if(infile == NULL) { printf("File does not exist!\n"); return false; } fseek(infile, 0L, SEEK_END); *length = ftell(infile); fseek(infile, 0L, SEEK_SET); *buffer = (char*)calloc(*length, sizeof(char)); /* memory error */ if(*buffer == NULL) { printf("Could not allocate %ld bytes of memory!\n", *length); return false; } length_read = fread(*buffer, sizeof(char), *length, infile); *length = length_read; fclose(infile); return true; } int main(int argc, char **argv) { void *buffer; long length; struct pcap_pkthdr* pcap_hdr; int i; int loops = 1; P4TopIndication echoIndication(IfcNames_P4TopIndicationH2S); device = new P4TopRequestProxy(IfcNames_P4TopRequestS2H); device->sonic_read_version(); device->matchTableRequest(10, 15, 1); device->matchTableRequest(10, 0, 0); while(1); fprintf(stderr, "Attempts to read pcap file %s\n", argv[1]); if (!read_pcap_file(argv[1], &buffer, &length)) { perror("Failed to read file!"); exit(-1); } for (i = 0; i < loops; i++) { void* offset = static_cast<char *>(buffer) + sizeof(struct pcap_file_header); while(offset < static_cast<char *>(buffer) + length) { pcap_hdr = (struct pcap_pkthdr*) offset; offset = static_cast<char *>(offset) + sizeof(struct pcap_pkthdr); if ((quick_tx_send_packet((const void*)offset, pcap_hdr->caplen)) < 0) { printf("An error occurred while trying to send a packet\n"); exit(-1); } offset = static_cast<char *>(offset) + pcap_hdr->caplen; } } while(1) sleep(1); return 0; } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ ///////////////////////////////////////////////////////////// // // AliAnalysisTaskSE for the reconstruction of heavy flavor // decays, using the class AliAnalysisVertexingHF. // // Author: A.Dainese, andrea.dainese@lnl.infn.it ///////////////////////////////////////////////////////////// #include <TROOT.h> #include <TSystem.h> #include <TClonesArray.h> #include "AliVEvent.h" #include "AliAODEvent.h" #include "AliESDEvent.h" #include "AliAnalysisVertexingHF.h" #include "AliAnalysisTaskSE.h" #include "AliAnalysisTaskSEVertexingHF.h" ClassImp(AliAnalysisTaskSEVertexingHF) //________________________________________________________________________ AliAnalysisTaskSEVertexingHF::AliAnalysisTaskSEVertexingHF(): AliAnalysisTaskSE(), fVHF(0), fVerticesHFTClArr(0), fD0toKpiTClArr(0), fJPSItoEleTClArr(0), fCharm3ProngTClArr(0), fCharm4ProngTClArr(0), fDstarTClArr(0), fLikeSign2ProngTClArr(0), fLikeSign3ProngTClArr(0) { // Default constructor } //________________________________________________________________________ AliAnalysisTaskSEVertexingHF::AliAnalysisTaskSEVertexingHF(const char *name): AliAnalysisTaskSE(name), fVHF(0), fVerticesHFTClArr(0), fD0toKpiTClArr(0), fJPSItoEleTClArr(0), fCharm3ProngTClArr(0), fCharm4ProngTClArr(0), fDstarTClArr(0), fLikeSign2ProngTClArr(0), fLikeSign3ProngTClArr(0) { // Default constructor } //________________________________________________________________________ AliAnalysisTaskSEVertexingHF::~AliAnalysisTaskSEVertexingHF() { // Destructor } //________________________________________________________________________ void AliAnalysisTaskSEVertexingHF::Init() { // Initialization // Instanciates vHF and loads its parameters if(fDebug > 1) printf("AnalysisTaskSEVertexingHF::Init() \n"); if(gROOT->LoadMacro("ConfigVertexingHF.C")) { printf("AnalysisTaskSEVertexingHF::Init() \n Using $ALICE_ROOT/PWG3/vertexingHF/ConfigVertexingHF.C\n"); gROOT->LoadMacro("$ALICE_ROOT/PWG3/vertexingHF/ConfigVertexingHF.C"); } fVHF = (AliAnalysisVertexingHF*)gROOT->ProcessLine("ConfigVertexingHF()"); fVHF->PrintStatus(); return; } //________________________________________________________________________ void AliAnalysisTaskSEVertexingHF::UserCreateOutputObjects() { // Create the output container // if(fDebug > 1) printf("AnalysisTaskSEVertexingHF::UserCreateOutPutData() \n"); if(!fVHF) { printf("AnalysisTaskSEVertexingHF::UserCreateOutPutData() \n ERROR! no fvHF!\n"); return; } fVerticesHFTClArr = new TClonesArray("AliAODVertex", 0); fVerticesHFTClArr->SetName("VerticesHF"); AddAODBranch("TClonesArray", &fVerticesHFTClArr); if(fVHF->GetD0toKpi()) { fD0toKpiTClArr = new TClonesArray("AliAODRecoDecayHF2Prong", 0); fD0toKpiTClArr->SetName("D0toKpi"); AddAODBranch("TClonesArray", &fD0toKpiTClArr); } if(fVHF->GetJPSItoEle()) { fJPSItoEleTClArr = new TClonesArray("AliAODRecoDecayHF2Prong", 0); fJPSItoEleTClArr->SetName("JPSItoEle"); AddAODBranch("TClonesArray", &fJPSItoEleTClArr); } if(fVHF->Get3Prong()) { fCharm3ProngTClArr = new TClonesArray("AliAODRecoDecayHF3Prong", 0); fCharm3ProngTClArr->SetName("Charm3Prong"); AddAODBranch("TClonesArray", &fCharm3ProngTClArr); } if(fVHF->Get4Prong()) { fCharm4ProngTClArr = new TClonesArray("AliAODRecoDecayHF4Prong", 0); fCharm4ProngTClArr->SetName("Charm4Prong"); AddAODBranch("TClonesArray", &fCharm4ProngTClArr); } if(fVHF->GetDstar()) { fDstarTClArr = new TClonesArray("AliAODRecoCascadeHF", 0); fDstarTClArr->SetName("Dstar"); AddAODBranch("TClonesArray", &fDstarTClArr); } if(fVHF->GetLikeSign()) { fLikeSign2ProngTClArr = new TClonesArray("AliAODRecoDecayHF2Prong", 0); fLikeSign2ProngTClArr->SetName("LikeSign2Prong"); AddAODBranch("TClonesArray", &fLikeSign2ProngTClArr); } if(fVHF->GetLikeSign() && fVHF->Get3Prong()) { fLikeSign3ProngTClArr = new TClonesArray("AliAODRecoDecayHF3Prong", 0); fLikeSign3ProngTClArr->SetName("LikeSign3Prong"); AddAODBranch("TClonesArray", &fLikeSign3ProngTClArr); } return; } //________________________________________________________________________ void AliAnalysisTaskSEVertexingHF::UserExec(Option_t */*option*/) { // Execute analysis for current event: // heavy flavor vertexing AliVEvent *event = dynamic_cast<AliVEvent*> (InputEvent()); // heavy flavor vertexing fVHF->FindCandidates(event, fVerticesHFTClArr, fD0toKpiTClArr, fJPSItoEleTClArr, fCharm3ProngTClArr, fCharm4ProngTClArr, fDstarTClArr, fLikeSign2ProngTClArr, fLikeSign3ProngTClArr); return; } //________________________________________________________________________ void AliAnalysisTaskSEVertexingHF::Terminate(Option_t */*option*/) { // Terminate analysis // if(fDebug > 1) printf("AnalysisTaskSEVertexingHF: Terminate() \n"); } <commit_msg>Possibility to create AOD+AODVertexingHF in the same train, starting from ESD (A. Gheata)<commit_after>/************************************************************************** * Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ ///////////////////////////////////////////////////////////// // // AliAnalysisTaskSE for the reconstruction of heavy flavor // decays, using the class AliAnalysisVertexingHF. // // Author: A.Dainese, andrea.dainese@lnl.infn.it ///////////////////////////////////////////////////////////// #include <TROOT.h> #include <TSystem.h> #include <TClonesArray.h> #include "AliVEvent.h" #include "AliAODEvent.h" #include "AliESDEvent.h" #include "AliAnalysisVertexingHF.h" #include "AliAnalysisTaskSE.h" #include "AliAnalysisTaskSEVertexingHF.h" ClassImp(AliAnalysisTaskSEVertexingHF) //________________________________________________________________________ AliAnalysisTaskSEVertexingHF::AliAnalysisTaskSEVertexingHF(): AliAnalysisTaskSE(), fVHF(0), fVerticesHFTClArr(0), fD0toKpiTClArr(0), fJPSItoEleTClArr(0), fCharm3ProngTClArr(0), fCharm4ProngTClArr(0), fDstarTClArr(0), fLikeSign2ProngTClArr(0), fLikeSign3ProngTClArr(0) { // Default constructor } //________________________________________________________________________ AliAnalysisTaskSEVertexingHF::AliAnalysisTaskSEVertexingHF(const char *name): AliAnalysisTaskSE(name), fVHF(0), fVerticesHFTClArr(0), fD0toKpiTClArr(0), fJPSItoEleTClArr(0), fCharm3ProngTClArr(0), fCharm4ProngTClArr(0), fDstarTClArr(0), fLikeSign2ProngTClArr(0), fLikeSign3ProngTClArr(0) { // Default constructor } //________________________________________________________________________ AliAnalysisTaskSEVertexingHF::~AliAnalysisTaskSEVertexingHF() { // Destructor } //________________________________________________________________________ void AliAnalysisTaskSEVertexingHF::Init() { // Initialization // Instanciates vHF and loads its parameters if(fDebug > 1) printf("AnalysisTaskSEVertexingHF::Init() \n"); if(gROOT->LoadMacro("ConfigVertexingHF.C")) { printf("AnalysisTaskSEVertexingHF::Init() \n Using $ALICE_ROOT/PWG3/vertexingHF/ConfigVertexingHF.C\n"); gROOT->LoadMacro("$ALICE_ROOT/PWG3/vertexingHF/ConfigVertexingHF.C"); } fVHF = (AliAnalysisVertexingHF*)gROOT->ProcessLine("ConfigVertexingHF()"); fVHF->PrintStatus(); return; } //________________________________________________________________________ void AliAnalysisTaskSEVertexingHF::UserCreateOutputObjects() { // Create the output container // if(fDebug > 1) printf("AnalysisTaskSEVertexingHF::UserCreateOutPutData() \n"); // Support both the case when the AOD + deltaAOD are produced in an ESD // analysis or if the deltaAOD is produced on an analysis on AOD's. (A.G. 27/04/09) if (!AODEvent()) { Fatal("UserCreateOutputObjects", "This task needs an AOD handler"); return; } TString filename = "AliAOD.VertexingHF.root"; if (!IsStandardAOD()) filename = ""; if(!fVHF) { printf("AnalysisTaskSEVertexingHF::UserCreateOutPutData() \n ERROR! no fvHF!\n"); return; } fVerticesHFTClArr = new TClonesArray("AliAODVertex", 0); fVerticesHFTClArr->SetName("VerticesHF"); AddAODBranch("TClonesArray", &fVerticesHFTClArr, filename); if(fVHF->GetD0toKpi()) { fD0toKpiTClArr = new TClonesArray("AliAODRecoDecayHF2Prong", 0); fD0toKpiTClArr->SetName("D0toKpi"); AddAODBranch("TClonesArray", &fD0toKpiTClArr, filename); } if(fVHF->GetJPSItoEle()) { fJPSItoEleTClArr = new TClonesArray("AliAODRecoDecayHF2Prong", 0); fJPSItoEleTClArr->SetName("JPSItoEle"); AddAODBranch("TClonesArray", &fJPSItoEleTClArr, filename); } if(fVHF->Get3Prong()) { fCharm3ProngTClArr = new TClonesArray("AliAODRecoDecayHF3Prong", 0); fCharm3ProngTClArr->SetName("Charm3Prong"); AddAODBranch("TClonesArray", &fCharm3ProngTClArr, filename); } if(fVHF->Get4Prong()) { fCharm4ProngTClArr = new TClonesArray("AliAODRecoDecayHF4Prong", 0); fCharm4ProngTClArr->SetName("Charm4Prong"); AddAODBranch("TClonesArray", &fCharm4ProngTClArr, filename); } if(fVHF->GetDstar()) { fDstarTClArr = new TClonesArray("AliAODRecoCascadeHF", 0); fDstarTClArr->SetName("Dstar"); AddAODBranch("TClonesArray", &fDstarTClArr, filename); } if(fVHF->GetLikeSign()) { fLikeSign2ProngTClArr = new TClonesArray("AliAODRecoDecayHF2Prong", 0); fLikeSign2ProngTClArr->SetName("LikeSign2Prong"); AddAODBranch("TClonesArray", &fLikeSign2ProngTClArr, filename); } if(fVHF->GetLikeSign() && fVHF->Get3Prong()) { fLikeSign3ProngTClArr = new TClonesArray("AliAODRecoDecayHF3Prong", 0); fLikeSign3ProngTClArr->SetName("LikeSign3Prong"); AddAODBranch("TClonesArray", &fLikeSign3ProngTClArr, filename); } return; } //________________________________________________________________________ void AliAnalysisTaskSEVertexingHF::UserExec(Option_t */*option*/) { // Execute analysis for current event: // heavy flavor vertexing AliVEvent *event = dynamic_cast<AliVEvent*> (InputEvent()); // In case there is an AOD handler writing a standard AOD, use the AOD // event in memory rather than the input (ESD) event. (A.G. 27/04/09) if (AODEvent() && IsStandardAOD()) event = dynamic_cast<AliVEvent*> (AODEvent()); // heavy flavor vertexing fVHF->FindCandidates(event, fVerticesHFTClArr, fD0toKpiTClArr, fJPSItoEleTClArr, fCharm3ProngTClArr, fCharm4ProngTClArr, fDstarTClArr, fLikeSign2ProngTClArr, fLikeSign3ProngTClArr); return; } //________________________________________________________________________ void AliAnalysisTaskSEVertexingHF::Terminate(Option_t */*option*/) { // Terminate analysis // if(fDebug > 1) printf("AnalysisTaskSEVertexingHF: Terminate() \n"); } <|endoftext|>
<commit_before>/** \file new_journal_alert.cc * \brief Detects new journal issues for subscribed users. * \author Dr. Johannes Ruscheinski */ /* Copyright (C) 2016, Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <sstream> #include <vector> #include <cstdlib> #include <cstring> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include "Compiler.h" #include "DbConnection.h" #include "EmailSender.h" #include "ExecUtil.h" #include "FileUtil.h" #include "HtmlUtil.h" #include "MiscUtil.h" #include "Solr.h" #include "StringUtil.h" #include "UrlUtil.h" #include "util.h" #include "VuFind.h" void Usage() { std::cerr << "Usage: " << ::progname << " [--verbose] [solr_host_and_port]\n"; std::cerr << " Sends out notification emails for journal subscribers.\n"; std::cerr << " Should \"solr_host_and_port\" be missing \"localhost:8080\" will be used.\n"; std::exit(EXIT_FAILURE); } struct SerialControlNumberAndLastIssueDate { std::string serial_control_number_; std::string last_issue_date_; bool changed_; public: SerialControlNumberAndLastIssueDate(const std::string &serial_control_number, const std::string &last_issue_date) : serial_control_number_(serial_control_number), last_issue_date_(last_issue_date), changed_(false) { } inline void setLastIssueDate(const std::string &new_last_issue_date) { last_issue_date_ = new_last_issue_date; changed_ = true; } inline bool changed() const { return changed_; } }; struct NewIssueInfo { std::string control_number_; std::string title_; std::string last_issue_date_; public: NewIssueInfo(const std::string &control_number, const std::string &title) : control_number_(control_number), title_(title) { } }; /** \return True if new issues were found, false o/w. */ bool ExtractNewIssueInfos(const std::string &json_document, std::vector<NewIssueInfo> * const new_issue_infos, std::string * const max_last_issue_date) { std::stringstream input(json_document, std::ios_base::in); boost::property_tree::ptree property_tree; boost::property_tree::json_parser::read_json(input, property_tree); bool found_at_least_one_new_issue(false); for (const auto &document : property_tree.get_child("response.docs.")) { const auto &id(document.second.get<std::string>("id")); const auto &title(document.second.get<std::string>("title")); new_issue_infos->emplace_back(id, title); const auto &recording_date(document.second.get<std::string>("recording_date")); if (recording_date > *max_last_issue_date) { *max_last_issue_date = recording_date; found_at_least_one_new_issue = true; } } return found_at_least_one_new_issue; } bool GetNewIssues(const std::string &solr_host_and_port, const std::string &serial_control_number, std::string last_issue_date, std::vector<NewIssueInfo> * const new_issue_infos, std::string * const max_last_issue_date) { if (not StringUtil::EndsWith(last_issue_date, "Z")) last_issue_date += "T00:00:00Z"; // Solr does not support the short form of the ISO 8601 date formats. const std::string QUERY("superior_ppn:" + serial_control_number + " AND recording_date:{" + last_issue_date + " TO *}"); std::string json_result; if (unlikely(not Solr::Query(QUERY, "id,title,author,recording_date", &json_result, solr_host_and_port, /* timeout = */ 5, Solr::JSON))) Error("Solr query failed or timed-out: \"" + QUERY + "\"."); return ExtractNewIssueInfos(json_result, new_issue_infos, max_last_issue_date); } void SendNotificationEmail(const std::string &firstname, const std::string &lastname, const std::string &email, const std::string &vufind_host, const std::vector<NewIssueInfo> &new_issue_infos) { const std::string EMAIL_TEMPLATE_PATH("/var/lib/tuelib/subscriptions_email.template"); std::string email_template; if (unlikely(not FileUtil::ReadString(EMAIL_TEMPLATE_PATH, &email_template))) Error("can't load email template \"" + EMAIL_TEMPLATE_PATH + "\"!"); // Process the email template: std::map<std::string, std::vector<std::string>> names_to_values_map; names_to_values_map["firstname"] = std::vector<std::string>{ firstname }; names_to_values_map["lastname"] = std::vector<std::string>{ lastname }; std::vector<std::string> urls, titles; for (const auto &new_issue_info : new_issue_infos) { urls.emplace_back("https://" + vufind_host + "/Record/" + new_issue_info.control_number_); titles.emplace_back(HtmlUtil::HtmlEscape(new_issue_info.title_)); } names_to_values_map["url"] = urls; names_to_values_map["title"] = titles; std::istringstream input(email_template); std::ostringstream email_contents; MiscUtil::ExpandTemplate(input, email_contents, names_to_values_map); if (unlikely(not EmailSender::SendEmail("notifications@ixtheo.de", email, "Ixtheo Subscriptions", email_contents.str(), EmailSender::DO_NOT_SET_PRIORITY, EmailSender::HTML))) Error("failed to send a notification email to \"" + email + "\"!"); } /** \return If "host_and_port" has a colon, the part before the colon else all of "host_and_port". */ std::string GetHostname() { std::string hostname; if (unlikely(not ExecUtil::ExecSubcommandAndCaptureStdout("/bin/hostname --fqdn", &hostname) or hostname.empty())) Error("failed to execute /bin/hostname or got an empty hostname!"); return hostname; } void ProcessSingleUser(const bool verbose, DbConnection * const db_connection, const std::string &user_id, const std::string &solr_host_and_port, std::vector<SerialControlNumberAndLastIssueDate> &control_numbers_and_last_issue_dates) { const std::string SELECT_USER_ATTRIBUTES("SELECT * FROM user WHERE id=" + user_id); if (unlikely(not db_connection->query(SELECT_USER_ATTRIBUTES))) Error("Select failed: " + SELECT_USER_ATTRIBUTES + " (" + db_connection->getLastErrorMessage() + ")"); DbResultSet result_set(db_connection->getLastResultSet()); if (result_set.empty()) Error("found no user attributes in table \"user\" for ID \"" + user_id + "\"!"); if (result_set.size() > 1) Error("found multiple user attribute sets in table \"user\" for ID \"" + user_id + "\"!"); const DbRow row(result_set.getNextRow()); const std::string username(row["username"]); if (verbose) std::cerr << "Found " << control_numbers_and_last_issue_dates.size() << " subscriptions for \"" << username << ".\n"; const std::string firstname(row["firstname"]); const std::string lastname(row["lastname"]); const std::string email(row["email"]); // Collect the dates for new issues. std::vector<NewIssueInfo> new_issue_infos; for (auto &control_number_and_last_issue_date : control_numbers_and_last_issue_dates) { std::string max_last_issue_date(control_number_and_last_issue_date.last_issue_date_); if (GetNewIssues(solr_host_and_port, control_number_and_last_issue_date.serial_control_number_, control_number_and_last_issue_date.last_issue_date_, &new_issue_infos, &max_last_issue_date)) control_number_and_last_issue_date.setLastIssueDate(max_last_issue_date); } if (verbose) std::cerr << "Found " << new_issue_infos.size() << " new issues for " << " \"" << username << "\".\n"; if (not new_issue_infos.empty()) SendNotificationEmail(firstname, lastname, email, GetHostname(), new_issue_infos); // Update the database with the new last issue dates. for (const auto &control_number_and_last_issue_date : control_numbers_and_last_issue_dates) { if (not control_number_and_last_issue_date.changed()) continue; const std::string REPLACE_STMT("REPLACE INTO ixtheo_journal_subscriptions SET id=" + user_id + ",last_issue_date='" + control_number_and_last_issue_date.last_issue_date_ + "',journal_control_number=" + control_number_and_last_issue_date.serial_control_number_); if (unlikely(not db_connection->query(REPLACE_STMT))) Error("Replace failed: " + REPLACE_STMT + " (" + db_connection->getLastErrorMessage() + ")"); } } void ProcessSubscriptions(const bool verbose, DbConnection * const db_connection, const std::string &solr_host_and_port) { const std::string SELECT_IDS_STMT("SELECT DISTINCT id FROM ixtheo_journal_subscriptions"); if (unlikely(not db_connection->query(SELECT_IDS_STMT))) Error("Select failed: " + SELECT_IDS_STMT + " (" + db_connection->getLastErrorMessage() + ")"); unsigned subscription_count(0); DbResultSet id_result_set(db_connection->getLastResultSet()); const unsigned user_count(id_result_set.size()); while (const DbRow id_row = id_result_set.getNextRow()) { const std::string user_id(id_row["id"]); const std::string SELECT_SUBSCRIPTION_INFO("SELECT journal_control_number,last_issue_date FROM " "ixtheo_journal_subscriptions WHERE id=" + user_id); if (unlikely(not db_connection->query(SELECT_SUBSCRIPTION_INFO))) Error("Select failed: " + SELECT_SUBSCRIPTION_INFO + " (" + db_connection->getLastErrorMessage() + ")"); DbResultSet result_set(db_connection->getLastResultSet()); std::vector<SerialControlNumberAndLastIssueDate> control_numbers_and_last_issue_dates; while (const DbRow row = result_set.getNextRow()) { control_numbers_and_last_issue_dates.emplace_back(SerialControlNumberAndLastIssueDate( row["journal_control_number"], row["last_issue_date"])); ++subscription_count; } ProcessSingleUser(verbose, db_connection, user_id, solr_host_and_port, control_numbers_and_last_issue_dates); } if (verbose) std::cout << "Processed " << user_count << " users and " << subscription_count << " subscriptions.\n"; } int main(int argc, char **argv) { progname = argv[0]; if (argc > 3) Usage(); bool verbose(false); std::string solr_host_and_port("localhost:8080"); if (argc == 3) { if (std::strcmp("--verbose", argv[1]) != 0) Usage(); verbose = true; solr_host_and_port = argv[2]; } else if (argc == 2) { if (std::strcmp("--verbose", argv[1]) == 0) verbose = true; else solr_host_and_port = argv[1]; } try { std::string mysql_url; VuFind::GetMysqlURL(&mysql_url); DbConnection db_connection(mysql_url); ProcessSubscriptions(verbose, &db_connection, solr_host_and_port); } catch (const std::exception &x) { Error("caught exception: " + std::string(x.what())); } } <commit_msg>We now also provide the journal title.<commit_after>/** \file new_journal_alert.cc * \brief Detects new journal issues for subscribed users. * \author Dr. Johannes Ruscheinski */ /* Copyright (C) 2016, Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <sstream> #include <vector> #include <cstdlib> #include <cstring> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include "Compiler.h" #include "DbConnection.h" #include "EmailSender.h" #include "ExecUtil.h" #include "FileUtil.h" #include "HtmlUtil.h" #include "MiscUtil.h" #include "Solr.h" #include "StringUtil.h" #include "UrlUtil.h" #include "util.h" #include "VuFind.h" void Usage() { std::cerr << "Usage: " << ::progname << " [--verbose] [solr_host_and_port]\n"; std::cerr << " Sends out notification emails for journal subscribers.\n"; std::cerr << " Should \"solr_host_and_port\" be missing \"localhost:8080\" will be used.\n"; std::exit(EXIT_FAILURE); } struct SerialControlNumberAndLastIssueDate { std::string serial_control_number_; std::string last_issue_date_; bool changed_; public: SerialControlNumberAndLastIssueDate(const std::string &serial_control_number, const std::string &last_issue_date) : serial_control_number_(serial_control_number), last_issue_date_(last_issue_date), changed_(false) { } inline void setLastIssueDate(const std::string &new_last_issue_date) { last_issue_date_ = new_last_issue_date; changed_ = true; } inline bool changed() const { return changed_; } }; struct NewIssueInfo { std::string control_number_; std::string journal_title_; std::string issue_title_; std::string last_issue_date_; public: NewIssueInfo(const std::string &control_number, const std::string &journal_title, const std::string &issue_title) : control_number_(control_number), journal_title_(journal_title), issue_title_(issue_title) { } }; /** \return True if new issues were found, false o/w. */ bool ExtractNewIssueInfos(const std::string &json_document, std::vector<NewIssueInfo> * const new_issue_infos, std::string * const max_last_issue_date) { std::stringstream input(json_document, std::ios_base::in); boost::property_tree::ptree property_tree; boost::property_tree::json_parser::read_json(input, property_tree); bool found_at_least_one_new_issue(false); for (const auto &document : property_tree.get_child("response.docs.")) { const auto &id(document.second.get<std::string>("id")); const auto &issue_title(document.second.get<std::string>("issue_title")); const std::string journal_title(document.second.get<std::string>("journal_issue/0", "*No Journal Title*")); new_issue_infos->emplace_back(id, journal_title, issue_title); const auto &recording_date(document.second.get<std::string>("recording_date")); if (recording_date > *max_last_issue_date) { *max_last_issue_date = recording_date; found_at_least_one_new_issue = true; } } return found_at_least_one_new_issue; } bool GetNewIssues(const std::string &solr_host_and_port, const std::string &serial_control_number, std::string last_issue_date, std::vector<NewIssueInfo> * const new_issue_infos, std::string * const max_last_issue_date) { if (not StringUtil::EndsWith(last_issue_date, "Z")) last_issue_date += "T00:00:00Z"; // Solr does not support the short form of the ISO 8601 date formats. const std::string QUERY("superior_ppn:" + serial_control_number + " AND recording_date:{" + last_issue_date + " TO *}"); std::string json_result; if (unlikely(not Solr::Query(QUERY, "id,title,author,recording_date", &json_result, solr_host_and_port, /* timeout = */ 5, Solr::JSON))) Error("Solr query failed or timed-out: \"" + QUERY + "\"."); return ExtractNewIssueInfos(json_result, new_issue_infos, max_last_issue_date); } void SendNotificationEmail(const std::string &firstname, const std::string &lastname, const std::string &email, const std::string &vufind_host, const std::vector<NewIssueInfo> &new_issue_infos) { const std::string EMAIL_TEMPLATE_PATH("/var/lib/tuelib/subscriptions_email.template"); std::string email_template; if (unlikely(not FileUtil::ReadString(EMAIL_TEMPLATE_PATH, &email_template))) Error("can't load email template \"" + EMAIL_TEMPLATE_PATH + "\"!"); // Process the email template: std::map<std::string, std::vector<std::string>> names_to_values_map; names_to_values_map["firstname"] = std::vector<std::string>{ firstname }; names_to_values_map["lastname"] = std::vector<std::string>{ lastname }; std::vector<std::string> urls, journal_titles, issue_titles; for (const auto &new_issue_info : new_issue_infos) { urls.emplace_back("https://" + vufind_host + "/Record/" + new_issue_info.control_number_); journal_titles.emplace_back(new_issue_info.journal_title_); issue_titles.emplace_back(HtmlUtil::HtmlEscape(new_issue_info.issue_title_)); } names_to_values_map["url"] = urls; names_to_values_map["journal_title"] = journal_titles; names_to_values_map["issue_title"] = issue_titles; std::istringstream input(email_template); std::ostringstream email_contents; MiscUtil::ExpandTemplate(input, email_contents, names_to_values_map); if (unlikely(not EmailSender::SendEmail("notifications@ixtheo.de", email, "Ixtheo Subscriptions", email_contents.str(), EmailSender::DO_NOT_SET_PRIORITY, EmailSender::HTML))) Error("failed to send a notification email to \"" + email + "\"!"); } /** \return If "host_and_port" has a colon, the part before the colon else all of "host_and_port". */ std::string GetHostname() { std::string hostname; if (unlikely(not ExecUtil::ExecSubcommandAndCaptureStdout("/bin/hostname --fqdn", &hostname) or hostname.empty())) Error("failed to execute /bin/hostname or got an empty hostname!"); return hostname; } void ProcessSingleUser(const bool verbose, DbConnection * const db_connection, const std::string &user_id, const std::string &solr_host_and_port, std::vector<SerialControlNumberAndLastIssueDate> &control_numbers_and_last_issue_dates) { const std::string SELECT_USER_ATTRIBUTES("SELECT * FROM user WHERE id=" + user_id); if (unlikely(not db_connection->query(SELECT_USER_ATTRIBUTES))) Error("Select failed: " + SELECT_USER_ATTRIBUTES + " (" + db_connection->getLastErrorMessage() + ")"); DbResultSet result_set(db_connection->getLastResultSet()); if (result_set.empty()) Error("found no user attributes in table \"user\" for ID \"" + user_id + "\"!"); if (result_set.size() > 1) Error("found multiple user attribute sets in table \"user\" for ID \"" + user_id + "\"!"); const DbRow row(result_set.getNextRow()); const std::string username(row["username"]); if (verbose) std::cerr << "Found " << control_numbers_and_last_issue_dates.size() << " subscriptions for \"" << username << ".\n"; const std::string firstname(row["firstname"]); const std::string lastname(row["lastname"]); const std::string email(row["email"]); // Collect the dates for new issues. std::vector<NewIssueInfo> new_issue_infos; for (auto &control_number_and_last_issue_date : control_numbers_and_last_issue_dates) { std::string max_last_issue_date(control_number_and_last_issue_date.last_issue_date_); if (GetNewIssues(solr_host_and_port, control_number_and_last_issue_date.serial_control_number_, control_number_and_last_issue_date.last_issue_date_, &new_issue_infos, &max_last_issue_date)) control_number_and_last_issue_date.setLastIssueDate(max_last_issue_date); } if (verbose) std::cerr << "Found " << new_issue_infos.size() << " new issues for " << " \"" << username << "\".\n"; if (not new_issue_infos.empty()) SendNotificationEmail(firstname, lastname, email, GetHostname(), new_issue_infos); // Update the database with the new last issue dates. for (const auto &control_number_and_last_issue_date : control_numbers_and_last_issue_dates) { if (not control_number_and_last_issue_date.changed()) continue; const std::string REPLACE_STMT("REPLACE INTO ixtheo_journal_subscriptions SET id=" + user_id + ",last_issue_date='" + control_number_and_last_issue_date.last_issue_date_ + "',journal_control_number=" + control_number_and_last_issue_date.serial_control_number_); if (unlikely(not db_connection->query(REPLACE_STMT))) Error("Replace failed: " + REPLACE_STMT + " (" + db_connection->getLastErrorMessage() + ")"); } } void ProcessSubscriptions(const bool verbose, DbConnection * const db_connection, const std::string &solr_host_and_port) { const std::string SELECT_IDS_STMT("SELECT DISTINCT id FROM ixtheo_journal_subscriptions"); if (unlikely(not db_connection->query(SELECT_IDS_STMT))) Error("Select failed: " + SELECT_IDS_STMT + " (" + db_connection->getLastErrorMessage() + ")"); unsigned subscription_count(0); DbResultSet id_result_set(db_connection->getLastResultSet()); const unsigned user_count(id_result_set.size()); while (const DbRow id_row = id_result_set.getNextRow()) { const std::string user_id(id_row["id"]); const std::string SELECT_SUBSCRIPTION_INFO("SELECT journal_control_number,last_issue_date FROM " "ixtheo_journal_subscriptions WHERE id=" + user_id); if (unlikely(not db_connection->query(SELECT_SUBSCRIPTION_INFO))) Error("Select failed: " + SELECT_SUBSCRIPTION_INFO + " (" + db_connection->getLastErrorMessage() + ")"); DbResultSet result_set(db_connection->getLastResultSet()); std::vector<SerialControlNumberAndLastIssueDate> control_numbers_and_last_issue_dates; while (const DbRow row = result_set.getNextRow()) { control_numbers_and_last_issue_dates.emplace_back(SerialControlNumberAndLastIssueDate( row["journal_control_number"], row["last_issue_date"])); ++subscription_count; } ProcessSingleUser(verbose, db_connection, user_id, solr_host_and_port, control_numbers_and_last_issue_dates); } if (verbose) std::cout << "Processed " << user_count << " users and " << subscription_count << " subscriptions.\n"; } int main(int argc, char **argv) { progname = argv[0]; if (argc > 3) Usage(); bool verbose(false); std::string solr_host_and_port("localhost:8080"); if (argc == 3) { if (std::strcmp("--verbose", argv[1]) != 0) Usage(); verbose = true; solr_host_and_port = argv[2]; } else if (argc == 2) { if (std::strcmp("--verbose", argv[1]) == 0) verbose = true; else solr_host_and_port = argv[1]; } try { std::string mysql_url; VuFind::GetMysqlURL(&mysql_url); DbConnection db_connection(mysql_url); ProcessSubscriptions(verbose, &db_connection, solr_host_and_port); } catch (const std::exception &x) { Error("caught exception: " + std::string(x.what())); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ViewShellBase.hxx,v $ * * $Revision: 1.14 $ * * last change: $Author: hr $ $Date: 2005-09-23 14:59:28 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SD_VIEW_SHELL_BASE_HXX #define SD_VIEW_SHELL_BASE_HXX #ifndef SD_VIEW_SHELL_HXX #include "ViewShell.hxx" #endif #ifndef SD_GLOB_HXX #include "glob.hxx" #endif #ifndef _SFXVIEWSH_HXX #include <sfx2/viewsh.hxx> #endif #ifndef _VIEWFAC_HXX #include <sfx2/viewfac.hxx> #endif #include <memory> class SdDrawDocument; class SfxRequest; namespace sd { namespace tools { class EventMultiplexer; } } namespace sd { class DrawDocShell; class FormShellManager; class PaneManager; class PrintManager; class UpdateLockManager; class ViewShell; class ViewShellManager; /** SfxViewShell descendant that the stacked Draw/Impress shells are based on. <p>The "base" part of the name does not mean that this is a base class of some class hierarchy. It rather is the base of the stacked shells.</p> <p>This class starts as a new and relatively small class. Over time as much code as possible should be moved from the stacked shells to this class.</p> */ class ViewShellBase : public SfxViewShell { public: TYPEINFO(); SFX_DECL_VIEWFACTORY(ViewShellBase); SFX_DECL_INTERFACE(SD_IF_SDVIEWSHELLBASE); /** This constructor is used by the view factory of the SFX macros. Note that LateInit() has to be called after the constructor terminates and before doing anything else. */ ViewShellBase ( SfxViewFrame *pFrame, SfxViewShell* pOldShell, ViewShell::ShellType eDefaultSubShell = ViewShell::ST_NONE); virtual ~ViewShellBase (void); /** This method is part of the object construction. It HAS to be called after the constructor has created a new object. */ virtual void LateInit (void); ViewShellManager& GetViewShellManager (void) const; /** Return the main view shell stacked on the called ViewShellBase object. This is usually the view shell displayed in the center pane. */ ViewShell* GetMainViewShell (void) const; PaneManager& GetPaneManager (void); /** When given a view frame this static method returns the corresponding sd::ViewShellBase object. @return When the SfxViewShell of the given frame is not a ViewShellBase object then NULL is returned. */ static ViewShellBase* GetViewShellBase (SfxViewFrame* pFrame); DrawDocShell* GetDocShell (void) const; SdDrawDocument* GetDocument (void) const; /** Callback function for retrieving item values related to menu entries. */ void GetMenuState (SfxItemSet& rSet); /** Callback function for general slot calls. At the moment these are slots for switching the pane docking windows on and off. */ virtual void Execute (SfxRequest& rRequest); /** Callback function for retrieving item values related to certain slots. This is the companion of Execute() and handles the slots concerned with showing the pane docking windows. */ virtual void GetState (SfxItemSet& rSet); /** Make sure that the given controller is known and used by the frame. @param pController The new controller. Usually that of the main view shell. */ void UpdateController (SfxBaseController* pController); SvBorder GetBorder (bool bOuterResize); virtual void InnerResizePixel (const Point& rOrigin, const Size& rSize); virtual void OuterResizePixel (const Point& rOrigin, const Size& rSize); /** This call is forwarded to the main sub-shell. */ virtual ErrCode DoVerb (long nVerb); /// Forwarded to the print manager. virtual SfxPrinter* GetPrinter (BOOL bCreate = FALSE); /// Forwarded to the print manager. virtual USHORT SetPrinter ( SfxPrinter* pNewPrinter, USHORT nDiffFlags = SFX_PRINTER_ALL); /// Forwarded to the print manager. virtual PrintDialog* CreatePrintDialog (::Window *pParent); /// Forwarded to the print manager. virtual SfxTabPage* CreatePrintOptionsPage ( ::Window *pParent, const SfxItemSet &rOptions); /// Forwarded to the print manager. virtual USHORT Print (SfxProgress& rProgress, PrintDialog* pDialog); /// Forwarded to the print manager. virtual ErrCode DoPrint ( SfxPrinter *pPrinter, PrintDialog *pPrintDialog, BOOL bSilent); /// Forwarded to the print manager. USHORT SetPrinterOptDlg ( SfxPrinter* pNewPrinter, USHORT nDiffFlags = SFX_PRINTER_ALL, BOOL _bShowDialog = TRUE); virtual void PreparePrint (PrintDialog* pPrintDialog); /// Forward methods to main sub shell. virtual void WriteUserDataSequence ( ::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue >&, sal_Bool bBrowse = sal_False); /** Pass the given properties to the main view shell. After that we ensure that the right view shell type is displayed in the center pane. */ virtual void ReadUserDataSequence ( const ::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue >&, sal_Bool bBrowse = sal_False); virtual void UIActivating( SfxInPlaceClient* ); virtual void UIDeactivated( SfxInPlaceClient* ); virtual void Activate (BOOL IsMDIActivate); virtual void Deactivate (BOOL IsMDIActivate); virtual void SetZoomFactor ( const Fraction &rZoomX, const Fraction &rZoomY); virtual USHORT PrepareClose (BOOL bUI = TRUE, BOOL bForBrowsing = FALSE); virtual void WriteUserData (String&, BOOL bBrowse = FALSE); virtual void ReadUserData (const String&, BOOL bBrowse = FALSE); virtual SdrView* GetDrawView (void) const; virtual void AdjustPosSizePixel (const Point &rOfs, const Size &rSize); /** Arrange GUI elements of the pane which shows the given view shell. @return The returned border contains the controls placed by the method. */ SvBorder ArrangeGUIElements (const Point& rOrigin, const Size& rSize); /** When <TRUE/> is given, then the mouse shape is set to hour glass (or whatever the busy shape looks like on the system.) */ void SetBusyState (bool bBusy); /** Call this method when the controls of this view shell or the embedded sub shell need to be rearranged. This is necessary e.g. when the border has been modified (UpdateBorder() calls this method). This method is like ResizePixel() with no arguments. */ void Rearrange (void); /** Update the border that is set with SfxViewShell::SetBorderPixel(). This is done by adding the border used by the ViewShellBase itself with the border used by the main view shell. @param bForce if true the borders are also updated if old border and new border are same. */ void UpdateBorder ( bool bForce = false ); /** With this method the UI controls can be turned on or off. It is used by the FuSlideShow to hide the UI controls while showing a non-full-screen or in-window presentation in the center pane. */ void ShowUIControls (bool bVisible); /** this method starts the presentation by executing the slot SID_PRESENTATION asynchronous */ void StartPresentation(); /** this methods ends the presentation by executing the slot SID_PRESENTATION_END asynchronous */ void StopPresentation(); /** Return an event multiplexer. It is a single class that forwards events from various sources. This method must not be called before LateInit() has terminated. */ tools::EventMultiplexer& GetEventMultiplexer (void); /* returns the complete area of the current view relative to the frame window */ inline const Rectangle& getClientRectangle() const; UpdateLockManager& GetUpdateLockManager (void) const; protected: osl::Mutex maMutex; /** The view tab bar is the control for switching between different views in one pane. */ ::std::auto_ptr<ViewTabBar> mpViewTabBar; virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType); private: class Implementation; ::std::auto_ptr<Implementation> mpImpl; ::std::auto_ptr<ViewShellManager> mpViewShellManager; ::std::auto_ptr<PaneManager> mpPaneManager; DrawDocShell* mpDocShell; SdDrawDocument* mpDocument; /// The print manager is responsible for printing documents. ::std::auto_ptr<PrintManager> mpPrintManager; ::std::auto_ptr<FormShellManager> mpFormShellManager; ::std::auto_ptr<tools::EventMultiplexer> mpEventMultiplexer; // contains the complete area of the current view relative to the frame window Rectangle maClientArea; ::std::auto_ptr<UpdateLockManager> mpUpdateLockManager; /** Common code of OuterResizePixel() and InnerResizePixel(). */ void ResizePixel ( const Point& rOrigin, const Size& rSize, bool bOuterResize); /** Determine from the properties of the document shell the initial type of the view shell in the center pane. We use this method to avoid starting with the wrong type. When ReadUserDataSequence() is called we check that the right type is active and change again if that is not the case because something went wrong. */ ViewShell::ShellType GetInitialViewShellType (void); /** Wait for the ViewTabBar to become visible so that its correct height can calculated and the border can be updated. */ DECL_LINK(WindowEventHandler,VclWindowEvent*); }; inline const Rectangle& ViewShellBase::getClientRectangle() const { return maClientArea; } } // end of namespace sd #endif <commit_msg>INTEGRATION: CWS viewswitch (1.14.62); FILE MERGED 2006/02/02 09:54:23 af 1.14.62.3: #i61191# Moved ViewTabBar, ArrangeGUIElements(), and Resize() to ViewShellBaseImplementation. 2005/11/29 14:35:32 af 1.14.62.2: #i57552# Removed UpdateController(). Added GetController(). 2005/11/17 14:11:09 af 1.14.62.1: #i57551# Added access to ToolBarManager and FormShellManager.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ViewShellBase.hxx,v $ * * $Revision: 1.15 $ * * last change: $Author: obo $ $Date: 2006-03-21 17:28:51 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SD_VIEW_SHELL_BASE_HXX #define SD_VIEW_SHELL_BASE_HXX #ifndef SD_VIEW_SHELL_HXX #include "ViewShell.hxx" #endif #ifndef SD_GLOB_HXX #include "glob.hxx" #endif #ifndef _SFXVIEWSH_HXX #include <sfx2/viewsh.hxx> #endif #ifndef _VIEWFAC_HXX #include <sfx2/viewfac.hxx> #endif #include <memory> class SdDrawDocument; class SfxRequest; namespace sd { namespace tools { class EventMultiplexer; } } namespace sd { class DrawController; class DrawDocShell; class FormShellManager; class PaneManager; class PrintManager; class ToolBarManager; class UpdateLockManager; class ViewShell; class ViewShellManager; /** SfxViewShell descendant that the stacked Draw/Impress shells are based on. <p>The "base" part of the name does not mean that this is a base class of some class hierarchy. It rather is the base of the stacked shells.</p> <p>This class starts as a new and relatively small class. Over time as much code as possible should be moved from the stacked shells to this class.</p> */ class ViewShellBase : public SfxViewShell { public: TYPEINFO(); SFX_DECL_VIEWFACTORY(ViewShellBase); SFX_DECL_INTERFACE(SD_IF_SDVIEWSHELLBASE); /** This constructor is used by the view factory of the SFX macros. Note that LateInit() has to be called after the constructor terminates and before doing anything else. */ ViewShellBase ( SfxViewFrame *pFrame, SfxViewShell* pOldShell, ViewShell::ShellType eDefaultSubShell = ViewShell::ST_NONE); virtual ~ViewShellBase (void); /** This method is part of the object construction. It HAS to be called after the constructor has created a new object. */ virtual void LateInit (void); ViewShellManager& GetViewShellManager (void) const; /** Return the main view shell stacked on the called ViewShellBase object. This is usually the view shell displayed in the center pane. */ ViewShell* GetMainViewShell (void) const; PaneManager& GetPaneManager (void); /** When given a view frame this static method returns the corresponding sd::ViewShellBase object. @return When the SfxViewShell of the given frame is not a ViewShellBase object then NULL is returned. */ static ViewShellBase* GetViewShellBase (SfxViewFrame* pFrame); DrawDocShell* GetDocShell (void) const; SdDrawDocument* GetDocument (void) const; /** Callback function for retrieving item values related to menu entries. */ void GetMenuState (SfxItemSet& rSet); /** Callback function for general slot calls. At the moment these are slots for switching the pane docking windows on and off. */ virtual void Execute (SfxRequest& rRequest); /** Callback function for retrieving item values related to certain slots. This is the companion of Execute() and handles the slots concerned with showing the pane docking windows. */ virtual void GetState (SfxItemSet& rSet); SvBorder GetBorder (bool bOuterResize); virtual void InnerResizePixel (const Point& rOrigin, const Size& rSize); virtual void OuterResizePixel (const Point& rOrigin, const Size& rSize); /** This call is forwarded to the main sub-shell. */ virtual ErrCode DoVerb (long nVerb); /// Forwarded to the print manager. virtual SfxPrinter* GetPrinter (BOOL bCreate = FALSE); /// Forwarded to the print manager. virtual USHORT SetPrinter ( SfxPrinter* pNewPrinter, USHORT nDiffFlags = SFX_PRINTER_ALL); /// Forwarded to the print manager. virtual PrintDialog* CreatePrintDialog (::Window *pParent); /// Forwarded to the print manager. virtual SfxTabPage* CreatePrintOptionsPage ( ::Window *pParent, const SfxItemSet &rOptions); /// Forwarded to the print manager. virtual USHORT Print (SfxProgress& rProgress, PrintDialog* pDialog); /// Forwarded to the print manager. virtual ErrCode DoPrint ( SfxPrinter *pPrinter, PrintDialog *pPrintDialog, BOOL bSilent); /// Forwarded to the print manager. USHORT SetPrinterOptDlg ( SfxPrinter* pNewPrinter, USHORT nDiffFlags = SFX_PRINTER_ALL, BOOL _bShowDialog = TRUE); virtual void PreparePrint (PrintDialog* pPrintDialog); /// Forward methods to main sub shell. virtual void WriteUserDataSequence ( ::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue >&, sal_Bool bBrowse = sal_False); /** Pass the given properties to the main view shell. After that we ensure that the right view shell type is displayed in the center pane. */ virtual void ReadUserDataSequence ( const ::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue >&, sal_Bool bBrowse = sal_False); virtual void UIActivating( SfxInPlaceClient* ); virtual void UIDeactivated( SfxInPlaceClient* ); virtual void Activate (BOOL IsMDIActivate); virtual void Deactivate (BOOL IsMDIActivate); virtual void SetZoomFactor ( const Fraction &rZoomX, const Fraction &rZoomY); virtual USHORT PrepareClose (BOOL bUI = TRUE, BOOL bForBrowsing = FALSE); virtual void WriteUserData (String&, BOOL bBrowse = FALSE); virtual void ReadUserData (const String&, BOOL bBrowse = FALSE); virtual SdrView* GetDrawView (void) const; virtual void AdjustPosSizePixel (const Point &rOfs, const Size &rSize); /** When <TRUE/> is given, then the mouse shape is set to hour glass (or whatever the busy shape looks like on the system.) */ void SetBusyState (bool bBusy); /** Call this method when the controls of this view shell or the embedded sub shell need to be rearranged. This is necessary e.g. when the border has been modified (UpdateBorder() calls this method). This method is like ResizePixel() with no arguments. */ void Rearrange (void); /** Update the border that is set with SfxViewShell::SetBorderPixel(). This is done by adding the border used by the ViewShellBase itself with the border used by the main view shell. @param bForce if true the borders are also updated if old border and new border are same. */ void UpdateBorder ( bool bForce = false ); /** With this method the UI controls can be turned on or off. It is used by the FuSlideShow to hide the UI controls while showing a non-full-screen or in-window presentation in the center pane. */ void ShowUIControls (bool bVisible); /** this method starts the presentation by executing the slot SID_PRESENTATION asynchronous */ void StartPresentation(); /** this methods ends the presentation by executing the slot SID_PRESENTATION_END asynchronous */ void StopPresentation(); /** Return an event multiplexer. It is a single class that forwards events from various sources. This method must not be called before LateInit() has terminated. */ tools::EventMultiplexer& GetEventMultiplexer (void); /** returns the complete area of the current view relative to the frame window */ const Rectangle& getClientRectangle() const; UpdateLockManager& GetUpdateLockManager (void) const; ToolBarManager& GetToolBarManager (void) const; FormShellManager& GetFormShellManager (void) const; DrawController& GetDrawController (void) const; protected: osl::Mutex maMutex; /** Factory method for creating the ViewTabBar member that allows derived classes to have no ViewTabBar. @return When the ViewTabBar is supported then a new instance of that class is returned. Otherwise it returns <NULL/>. */ virtual ViewTabBar* CreateViewTabBar (void); virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType); private: class Implementation; ::std::auto_ptr<Implementation> mpImpl; ::std::auto_ptr<ViewShellManager> mpViewShellManager; ::std::auto_ptr<PaneManager> mpPaneManager; DrawDocShell* mpDocShell; SdDrawDocument* mpDocument; /// The print manager is responsible for printing documents. ::std::auto_ptr<PrintManager> mpPrintManager; ::std::auto_ptr<FormShellManager> mpFormShellManager; ::std::auto_ptr<tools::EventMultiplexer> mpEventMultiplexer; ::std::auto_ptr<UpdateLockManager> mpUpdateLockManager; /** Determine from the properties of the document shell the initial type of the view shell in the center pane. We use this method to avoid starting with the wrong type. When ReadUserDataSequence() is called we check that the right type is active and change again if that is not the case because something went wrong. */ ViewShell::ShellType GetInitialViewShellType (void); /** Wait for the ViewTabBar to become visible so that its correct height can calculated and the border can be updated. */ DECL_LINK(WindowEventHandler,VclWindowEvent*); }; } // end of namespace sd #endif <|endoftext|>
<commit_before>/* * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by the * Free Software Foundation; either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "MapMgr.h" #include "Chat.h" #include "DatabaseEnv.h" #include "GridDefines.h" #include "Group.h" #include "InstanceSaveMgr.h" #include "InstanceScript.h" #include "LFGMgr.h" #include "Language.h" #include "Log.h" #include "MapInstanced.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Opcodes.h" #include "Player.h" #include "ScriptMgr.h" #include "Transport.h" #include "World.h" #include "WorldPacket.h" MapMgr::MapMgr() { i_timer[3].SetInterval(sWorld->getIntConfig(CONFIG_INTERVAL_MAPUPDATE)); mapUpdateStep = 0; _nextInstanceId = 0; } MapMgr::~MapMgr() { } MapMgr* MapMgr::instance() { static MapMgr instance; return &instance; } void MapMgr::Initialize() { int num_threads(sWorld->getIntConfig(CONFIG_NUMTHREADS)); // Start mtmaps if needed if (num_threads > 0) m_updater.activate(num_threads); } void MapMgr::InitializeVisibilityDistanceInfo() { for (MapMapType::iterator iter = i_maps.begin(); iter != i_maps.end(); ++iter) (*iter).second->InitVisibilityDistance(); } Map* MapMgr::CreateBaseMap(uint32 id) { Map* map = FindBaseMap(id); if (map == nullptr) { std::lock_guard<std::mutex> guard(Lock); map = FindBaseMap(id); if (map == nullptr) // pussywizard: check again after acquiring mutex { MapEntry const* entry = sMapStore.LookupEntry(id); ASSERT(entry); if (entry->Instanceable()) map = new MapInstanced(id); else { map = new Map(id, 0, REGULAR_DIFFICULTY); map->LoadRespawnTimes(); map->LoadCorpseData(); } i_maps[id] = map; } } ASSERT(map); return map; } Map* MapMgr::FindBaseNonInstanceMap(uint32 mapId) const { Map* map = FindBaseMap(mapId); if (map && map->Instanceable()) return nullptr; return map; } Map* MapMgr::CreateMap(uint32 id, Player* player) { Map* m = CreateBaseMap(id); if (m && m->Instanceable()) m = ((MapInstanced*)m)->CreateInstanceForPlayer(id, player); return m; } Map* MapMgr::FindMap(uint32 mapid, uint32 instanceId) const { Map* map = FindBaseMap(mapid); if (!map) return nullptr; if (!map->Instanceable()) return instanceId == 0 ? map : nullptr; return ((MapInstanced*)map)->FindInstanceMap(instanceId); } Map::EnterState MapMgr::PlayerCannotEnter(uint32 mapid, Player* player, bool loginCheck) { MapEntry const* entry = sMapStore.LookupEntry(mapid); if (!entry) return Map::CANNOT_ENTER_NO_ENTRY; if (!entry->IsDungeon()) return Map::CAN_ENTER; InstanceTemplate const* instance = sObjectMgr->GetInstanceTemplate(mapid); if (!instance) return Map::CANNOT_ENTER_UNINSTANCED_DUNGEON; Difficulty targetDifficulty, requestedDifficulty; targetDifficulty = requestedDifficulty = player->GetDifficulty(entry->IsRaid()); // Get the highest available difficulty if current setting is higher than the instance allows MapDifficulty const* mapDiff = GetDownscaledMapDifficultyData(entry->MapID, targetDifficulty); if (!mapDiff) { player->SendTransferAborted(mapid, TRANSFER_ABORT_DIFFICULTY, requestedDifficulty); return Map::CANNOT_ENTER_DIFFICULTY_UNAVAILABLE; } //Bypass checks for GMs if (player->IsGameMaster()) return Map::CAN_ENTER; char const* mapName = entry->name[player->GetSession()->GetSessionDbcLocale()]; if (!sScriptMgr->CanEnterMap(player, entry, instance, mapDiff, loginCheck)) return Map::CANNOT_ENTER_UNSPECIFIED_REASON; Group* group = player->GetGroup(); if (entry->IsRaid()) { // can only enter in a raid group if ((!group || !group->isRaidGroup()) && !sWorld->getBoolConfig(CONFIG_INSTANCE_IGNORE_RAID)) { // probably there must be special opcode, because client has this string constant in GlobalStrings.lua // TODO: this is not a good place to send the message player->GetSession()->SendAreaTriggerMessage(player->GetSession()->GetAcoreString(LANG_INSTANCE_RAID_GROUP_ONLY), mapName); LOG_DEBUG("maps", "MAP: Player '{}' must be in a raid group to enter instance '{}'", player->GetName(), mapName); return Map::CANNOT_ENTER_NOT_IN_RAID; } } // xinef: dont allow LFG Group to enter other instance that is selected if (group) if (group->isLFGGroup()) if (!sLFGMgr->inLfgDungeonMap(group->GetGUID(), mapid, targetDifficulty)) { player->SendTransferAborted(mapid, TRANSFER_ABORT_MAP_NOT_ALLOWED); return Map::CANNOT_ENTER_UNSPECIFIED_REASON; } if (!player->IsAlive()) { if (player->HasCorpse()) { // let enter in ghost mode in instance that connected to inner instance with corpse uint32 corpseMap = player->GetCorpseLocation().GetMapId(); do { if (corpseMap == mapid) break; InstanceTemplate const* corpseInstance = sObjectMgr->GetInstanceTemplate(corpseMap); corpseMap = corpseInstance ? corpseInstance->Parent : 0; } while (corpseMap); if (!corpseMap) { WorldPacket data(SMSG_CORPSE_NOT_IN_INSTANCE, 0); player->GetSession()->SendPacket(&data); LOG_DEBUG("maps", "MAP: Player '{}' does not have a corpse in instance '{}' and cannot enter.", player->GetName(), mapName); return Map::CANNOT_ENTER_CORPSE_IN_DIFFERENT_INSTANCE; } LOG_DEBUG("maps", "MAP: Player '{}' has corpse in instance '{}' and can enter.", player->GetName(), mapName); } else { LOG_DEBUG("maps", "Map::PlayerCannotEnter - player '{}' is dead but does not have a corpse!", player->GetName()); } } // if map exists - check for being full, etc. if (!loginCheck) // for login this is done by the calling function { uint32 destInstId = sInstanceSaveMgr->PlayerGetDestinationInstanceId(player, mapid, targetDifficulty); if (destInstId) if (Map* boundMap = sMapMgr->FindMap(mapid, destInstId)) if (Map::EnterState denyReason = boundMap->CannotEnter(player, loginCheck)) return denyReason; } // players are only allowed to enter 5 instances per hour if (entry->IsDungeon() && (!group || !group->isLFGGroup() || !group->IsLfgRandomInstance())) { uint32 instaceIdToCheck = 0; if (InstanceSave* save = sInstanceSaveMgr->PlayerGetInstanceSave(player->GetGUID(), mapid, player->GetDifficulty(entry->IsRaid()))) instaceIdToCheck = save->GetInstanceId(); // instaceIdToCheck can be 0 if save not found - means no bind so the instance is new if (!player->CheckInstanceCount(instaceIdToCheck) && !player->isDead()) { player->SendTransferAborted(mapid, TRANSFER_ABORT_TOO_MANY_INSTANCES); return Map::CANNOT_ENTER_TOO_MANY_INSTANCES; } } //Other requirements return player->Satisfy(sObjectMgr->GetAccessRequirement(mapid, targetDifficulty), mapid, true) ? Map::CAN_ENTER : Map::CANNOT_ENTER_UNSPECIFIED_REASON; } void MapMgr::Update(uint32 diff) { for (uint8 i = 0; i < 4; ++i) i_timer[i].Update(diff); // pussywizard: lfg compatibles update, schedule before maps so it is processed from the very beginning //if (mapUpdateStep == 0) { if (m_updater.activated()) { m_updater.schedule_lfg_update(diff); } else { sLFGMgr->Update(diff, 1); } } MapMapType::iterator iter = i_maps.begin(); for (; iter != i_maps.end(); ++iter) { bool full = mapUpdateStep < 3 && ((mapUpdateStep == 0 && !iter->second->IsBattlegroundOrArena() && !iter->second->IsDungeon()) || (mapUpdateStep == 1 && iter->second->IsBattlegroundOrArena()) || (mapUpdateStep == 2 && iter->second->IsDungeon())); if (m_updater.activated()) m_updater.schedule_update(*iter->second, uint32(full ? i_timer[mapUpdateStep].GetCurrent() : 0), diff); else iter->second->Update(uint32(full ? i_timer[mapUpdateStep].GetCurrent() : 0), diff); } if (m_updater.activated()) m_updater.wait(); if (mapUpdateStep < 3) { for (iter = i_maps.begin(); iter != i_maps.end(); ++iter) { bool full = ((mapUpdateStep == 0 && !iter->second->IsBattlegroundOrArena() && !iter->second->IsDungeon()) || (mapUpdateStep == 1 && iter->second->IsBattlegroundOrArena()) || (mapUpdateStep == 2 && iter->second->IsDungeon())); if (full) iter->second->DelayedUpdate(uint32(i_timer[mapUpdateStep].GetCurrent())); } i_timer[mapUpdateStep].SetCurrent(0); ++mapUpdateStep; } if (mapUpdateStep == 3 && i_timer[3].Passed()) { mapUpdateStep = 0; i_timer[3].SetCurrent(0); } } void MapMgr::DoDelayedMovesAndRemoves() { } bool MapMgr::ExistMapAndVMap(uint32 mapid, float x, float y) { GridCoord p = Acore::ComputeGridCoord(x, y); int gx = 63 - p.x_coord; int gy = 63 - p.y_coord; return Map::ExistMap(mapid, gx, gy) && Map::ExistVMap(mapid, gx, gy); } bool MapMgr::IsValidMAP(uint32 mapid, bool startUp) { MapEntry const* mEntry = sMapStore.LookupEntry(mapid); if (startUp) { return mEntry != nullptr; } else { return mEntry && (!mEntry->IsDungeon() || sObjectMgr->GetInstanceTemplate(mapid)); } // TODO: add check for battleground template } void MapMgr::UnloadAll() { for (MapMapType::iterator iter = i_maps.begin(); iter != i_maps.end();) { iter->second->UnloadAll(); delete iter->second; i_maps.erase(iter++); } if (m_updater.activated()) m_updater.deactivate(); } void MapMgr::GetNumInstances(uint32& dungeons, uint32& battlegrounds, uint32& arenas) { for (MapMapType::iterator itr = i_maps.begin(); itr != i_maps.end(); ++itr) { Map* map = itr->second; if (!map->Instanceable()) continue; MapInstanced::InstancedMaps& maps = ((MapInstanced*)map)->GetInstancedMaps(); for (MapInstanced::InstancedMaps::iterator mitr = maps.begin(); mitr != maps.end(); ++mitr) { if (mitr->second->IsDungeon()) dungeons++; else if (mitr->second->IsBattleground()) battlegrounds++; else if (mitr->second->IsBattleArena()) arenas++; } } } void MapMgr::GetNumPlayersInInstances(uint32& dungeons, uint32& battlegrounds, uint32& arenas, uint32& spectators) { for (MapMapType::iterator itr = i_maps.begin(); itr != i_maps.end(); ++itr) { Map* map = itr->second; if (!map->Instanceable()) continue; MapInstanced::InstancedMaps& maps = ((MapInstanced*)map)->GetInstancedMaps(); for (MapInstanced::InstancedMaps::iterator mitr = maps.begin(); mitr != maps.end(); ++mitr) { if (mitr->second->IsDungeon()) dungeons += ((InstanceMap*)mitr->second)->GetPlayers().getSize(); else if (mitr->second->IsBattleground()) battlegrounds += ((InstanceMap*)mitr->second)->GetPlayers().getSize(); else if (mitr->second->IsBattleArena()) { uint32 spect = 0; if (BattlegroundMap* bgmap = mitr->second->ToBattlegroundMap()) if (Battleground* bg = bgmap->GetBG()) spect = bg->GetSpectators().size(); arenas += ((InstanceMap*)mitr->second)->GetPlayers().getSize() - spect; spectators += spect; } } } } void MapMgr::InitInstanceIds() { _nextInstanceId = 1; QueryResult result = CharacterDatabase.Query("SELECT MAX(id) FROM instance"); if (result) { uint32 maxId = (*result)[0].Get<uint32>(); _instanceIds.resize(maxId + 1); } } void MapMgr::RegisterInstanceId(uint32 instanceId) { // Allocation was done in InitInstanceIds() _instanceIds[instanceId] = true; // Instances are pulled in ascending order from db and _nextInstanceId is initialized with 1, // so if the instance id is used, increment if (_nextInstanceId == instanceId) ++_nextInstanceId; } uint32 MapMgr::GenerateInstanceId() { uint32 newInstanceId = _nextInstanceId; // find the lowest available id starting from the current _nextInstanceId while (_nextInstanceId < 0xFFFFFFFF && ++_nextInstanceId < _instanceIds.size() && _instanceIds[_nextInstanceId]); if (_nextInstanceId == 0xFFFFFFFF) { LOG_ERROR("server.worldserver", "Instance ID overflow!! Can't continue, shutting down server. "); World::StopNow(ERROR_EXIT_CODE); } return newInstanceId; } <commit_msg>fix(Core/Maps): Dead players should not be allowed to enter dungeon if exceeded max number of instances. Thx to @DepTypes (#10831)<commit_after>/* * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by the * Free Software Foundation; either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "MapMgr.h" #include "Chat.h" #include "DatabaseEnv.h" #include "GridDefines.h" #include "Group.h" #include "InstanceSaveMgr.h" #include "InstanceScript.h" #include "LFGMgr.h" #include "Language.h" #include "Log.h" #include "MapInstanced.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Opcodes.h" #include "Player.h" #include "ScriptMgr.h" #include "Transport.h" #include "World.h" #include "WorldPacket.h" MapMgr::MapMgr() { i_timer[3].SetInterval(sWorld->getIntConfig(CONFIG_INTERVAL_MAPUPDATE)); mapUpdateStep = 0; _nextInstanceId = 0; } MapMgr::~MapMgr() { } MapMgr* MapMgr::instance() { static MapMgr instance; return &instance; } void MapMgr::Initialize() { int num_threads(sWorld->getIntConfig(CONFIG_NUMTHREADS)); // Start mtmaps if needed if (num_threads > 0) m_updater.activate(num_threads); } void MapMgr::InitializeVisibilityDistanceInfo() { for (MapMapType::iterator iter = i_maps.begin(); iter != i_maps.end(); ++iter) (*iter).second->InitVisibilityDistance(); } Map* MapMgr::CreateBaseMap(uint32 id) { Map* map = FindBaseMap(id); if (map == nullptr) { std::lock_guard<std::mutex> guard(Lock); map = FindBaseMap(id); if (map == nullptr) // pussywizard: check again after acquiring mutex { MapEntry const* entry = sMapStore.LookupEntry(id); ASSERT(entry); if (entry->Instanceable()) map = new MapInstanced(id); else { map = new Map(id, 0, REGULAR_DIFFICULTY); map->LoadRespawnTimes(); map->LoadCorpseData(); } i_maps[id] = map; } } ASSERT(map); return map; } Map* MapMgr::FindBaseNonInstanceMap(uint32 mapId) const { Map* map = FindBaseMap(mapId); if (map && map->Instanceable()) return nullptr; return map; } Map* MapMgr::CreateMap(uint32 id, Player* player) { Map* m = CreateBaseMap(id); if (m && m->Instanceable()) m = ((MapInstanced*)m)->CreateInstanceForPlayer(id, player); return m; } Map* MapMgr::FindMap(uint32 mapid, uint32 instanceId) const { Map* map = FindBaseMap(mapid); if (!map) return nullptr; if (!map->Instanceable()) return instanceId == 0 ? map : nullptr; return ((MapInstanced*)map)->FindInstanceMap(instanceId); } Map::EnterState MapMgr::PlayerCannotEnter(uint32 mapid, Player* player, bool loginCheck) { MapEntry const* entry = sMapStore.LookupEntry(mapid); if (!entry) return Map::CANNOT_ENTER_NO_ENTRY; if (!entry->IsDungeon()) return Map::CAN_ENTER; InstanceTemplate const* instance = sObjectMgr->GetInstanceTemplate(mapid); if (!instance) return Map::CANNOT_ENTER_UNINSTANCED_DUNGEON; Difficulty targetDifficulty, requestedDifficulty; targetDifficulty = requestedDifficulty = player->GetDifficulty(entry->IsRaid()); // Get the highest available difficulty if current setting is higher than the instance allows MapDifficulty const* mapDiff = GetDownscaledMapDifficultyData(entry->MapID, targetDifficulty); if (!mapDiff) { player->SendTransferAborted(mapid, TRANSFER_ABORT_DIFFICULTY, requestedDifficulty); return Map::CANNOT_ENTER_DIFFICULTY_UNAVAILABLE; } //Bypass checks for GMs if (player->IsGameMaster()) return Map::CAN_ENTER; char const* mapName = entry->name[player->GetSession()->GetSessionDbcLocale()]; if (!sScriptMgr->CanEnterMap(player, entry, instance, mapDiff, loginCheck)) return Map::CANNOT_ENTER_UNSPECIFIED_REASON; Group* group = player->GetGroup(); if (entry->IsRaid()) { // can only enter in a raid group if ((!group || !group->isRaidGroup()) && !sWorld->getBoolConfig(CONFIG_INSTANCE_IGNORE_RAID)) { // probably there must be special opcode, because client has this string constant in GlobalStrings.lua // TODO: this is not a good place to send the message player->GetSession()->SendAreaTriggerMessage(player->GetSession()->GetAcoreString(LANG_INSTANCE_RAID_GROUP_ONLY), mapName); LOG_DEBUG("maps", "MAP: Player '{}' must be in a raid group to enter instance '{}'", player->GetName(), mapName); return Map::CANNOT_ENTER_NOT_IN_RAID; } } // xinef: dont allow LFG Group to enter other instance that is selected if (group) if (group->isLFGGroup()) if (!sLFGMgr->inLfgDungeonMap(group->GetGUID(), mapid, targetDifficulty)) { player->SendTransferAborted(mapid, TRANSFER_ABORT_MAP_NOT_ALLOWED); return Map::CANNOT_ENTER_UNSPECIFIED_REASON; } if (!player->IsAlive()) { if (player->HasCorpse()) { // let enter in ghost mode in instance that connected to inner instance with corpse uint32 corpseMap = player->GetCorpseLocation().GetMapId(); do { if (corpseMap == mapid) break; InstanceTemplate const* corpseInstance = sObjectMgr->GetInstanceTemplate(corpseMap); corpseMap = corpseInstance ? corpseInstance->Parent : 0; } while (corpseMap); if (!corpseMap) { WorldPacket data(SMSG_CORPSE_NOT_IN_INSTANCE, 0); player->GetSession()->SendPacket(&data); LOG_DEBUG("maps", "MAP: Player '{}' does not have a corpse in instance '{}' and cannot enter.", player->GetName(), mapName); return Map::CANNOT_ENTER_CORPSE_IN_DIFFERENT_INSTANCE; } LOG_DEBUG("maps", "MAP: Player '{}' has corpse in instance '{}' and can enter.", player->GetName(), mapName); } else { LOG_DEBUG("maps", "Map::PlayerCannotEnter - player '{}' is dead but does not have a corpse!", player->GetName()); } } // if map exists - check for being full, etc. if (!loginCheck) // for login this is done by the calling function { uint32 destInstId = sInstanceSaveMgr->PlayerGetDestinationInstanceId(player, mapid, targetDifficulty); if (destInstId) if (Map* boundMap = sMapMgr->FindMap(mapid, destInstId)) if (Map::EnterState denyReason = boundMap->CannotEnter(player, loginCheck)) return denyReason; } // players are only allowed to enter 5 instances per hour if (entry->IsDungeon() && (!group || !group->isLFGGroup() || !group->IsLfgRandomInstance())) { uint32 instaceIdToCheck = 0; if (InstanceSave* save = sInstanceSaveMgr->PlayerGetInstanceSave(player->GetGUID(), mapid, player->GetDifficulty(entry->IsRaid()))) instaceIdToCheck = save->GetInstanceId(); // instaceIdToCheck can be 0 if save not found - means no bind so the instance is new if (!player->CheckInstanceCount(instaceIdToCheck)) { player->SendTransferAborted(mapid, TRANSFER_ABORT_TOO_MANY_INSTANCES); return Map::CANNOT_ENTER_TOO_MANY_INSTANCES; } } //Other requirements return player->Satisfy(sObjectMgr->GetAccessRequirement(mapid, targetDifficulty), mapid, true) ? Map::CAN_ENTER : Map::CANNOT_ENTER_UNSPECIFIED_REASON; } void MapMgr::Update(uint32 diff) { for (uint8 i = 0; i < 4; ++i) i_timer[i].Update(diff); // pussywizard: lfg compatibles update, schedule before maps so it is processed from the very beginning //if (mapUpdateStep == 0) { if (m_updater.activated()) { m_updater.schedule_lfg_update(diff); } else { sLFGMgr->Update(diff, 1); } } MapMapType::iterator iter = i_maps.begin(); for (; iter != i_maps.end(); ++iter) { bool full = mapUpdateStep < 3 && ((mapUpdateStep == 0 && !iter->second->IsBattlegroundOrArena() && !iter->second->IsDungeon()) || (mapUpdateStep == 1 && iter->second->IsBattlegroundOrArena()) || (mapUpdateStep == 2 && iter->second->IsDungeon())); if (m_updater.activated()) m_updater.schedule_update(*iter->second, uint32(full ? i_timer[mapUpdateStep].GetCurrent() : 0), diff); else iter->second->Update(uint32(full ? i_timer[mapUpdateStep].GetCurrent() : 0), diff); } if (m_updater.activated()) m_updater.wait(); if (mapUpdateStep < 3) { for (iter = i_maps.begin(); iter != i_maps.end(); ++iter) { bool full = ((mapUpdateStep == 0 && !iter->second->IsBattlegroundOrArena() && !iter->second->IsDungeon()) || (mapUpdateStep == 1 && iter->second->IsBattlegroundOrArena()) || (mapUpdateStep == 2 && iter->second->IsDungeon())); if (full) iter->second->DelayedUpdate(uint32(i_timer[mapUpdateStep].GetCurrent())); } i_timer[mapUpdateStep].SetCurrent(0); ++mapUpdateStep; } if (mapUpdateStep == 3 && i_timer[3].Passed()) { mapUpdateStep = 0; i_timer[3].SetCurrent(0); } } void MapMgr::DoDelayedMovesAndRemoves() { } bool MapMgr::ExistMapAndVMap(uint32 mapid, float x, float y) { GridCoord p = Acore::ComputeGridCoord(x, y); int gx = 63 - p.x_coord; int gy = 63 - p.y_coord; return Map::ExistMap(mapid, gx, gy) && Map::ExistVMap(mapid, gx, gy); } bool MapMgr::IsValidMAP(uint32 mapid, bool startUp) { MapEntry const* mEntry = sMapStore.LookupEntry(mapid); if (startUp) { return mEntry != nullptr; } else { return mEntry && (!mEntry->IsDungeon() || sObjectMgr->GetInstanceTemplate(mapid)); } // TODO: add check for battleground template } void MapMgr::UnloadAll() { for (MapMapType::iterator iter = i_maps.begin(); iter != i_maps.end();) { iter->second->UnloadAll(); delete iter->second; i_maps.erase(iter++); } if (m_updater.activated()) m_updater.deactivate(); } void MapMgr::GetNumInstances(uint32& dungeons, uint32& battlegrounds, uint32& arenas) { for (MapMapType::iterator itr = i_maps.begin(); itr != i_maps.end(); ++itr) { Map* map = itr->second; if (!map->Instanceable()) continue; MapInstanced::InstancedMaps& maps = ((MapInstanced*)map)->GetInstancedMaps(); for (MapInstanced::InstancedMaps::iterator mitr = maps.begin(); mitr != maps.end(); ++mitr) { if (mitr->second->IsDungeon()) dungeons++; else if (mitr->second->IsBattleground()) battlegrounds++; else if (mitr->second->IsBattleArena()) arenas++; } } } void MapMgr::GetNumPlayersInInstances(uint32& dungeons, uint32& battlegrounds, uint32& arenas, uint32& spectators) { for (MapMapType::iterator itr = i_maps.begin(); itr != i_maps.end(); ++itr) { Map* map = itr->second; if (!map->Instanceable()) continue; MapInstanced::InstancedMaps& maps = ((MapInstanced*)map)->GetInstancedMaps(); for (MapInstanced::InstancedMaps::iterator mitr = maps.begin(); mitr != maps.end(); ++mitr) { if (mitr->second->IsDungeon()) dungeons += ((InstanceMap*)mitr->second)->GetPlayers().getSize(); else if (mitr->second->IsBattleground()) battlegrounds += ((InstanceMap*)mitr->second)->GetPlayers().getSize(); else if (mitr->second->IsBattleArena()) { uint32 spect = 0; if (BattlegroundMap* bgmap = mitr->second->ToBattlegroundMap()) if (Battleground* bg = bgmap->GetBG()) spect = bg->GetSpectators().size(); arenas += ((InstanceMap*)mitr->second)->GetPlayers().getSize() - spect; spectators += spect; } } } } void MapMgr::InitInstanceIds() { _nextInstanceId = 1; QueryResult result = CharacterDatabase.Query("SELECT MAX(id) FROM instance"); if (result) { uint32 maxId = (*result)[0].Get<uint32>(); _instanceIds.resize(maxId + 1); } } void MapMgr::RegisterInstanceId(uint32 instanceId) { // Allocation was done in InitInstanceIds() _instanceIds[instanceId] = true; // Instances are pulled in ascending order from db and _nextInstanceId is initialized with 1, // so if the instance id is used, increment if (_nextInstanceId == instanceId) ++_nextInstanceId; } uint32 MapMgr::GenerateInstanceId() { uint32 newInstanceId = _nextInstanceId; // find the lowest available id starting from the current _nextInstanceId while (_nextInstanceId < 0xFFFFFFFF && ++_nextInstanceId < _instanceIds.size() && _instanceIds[_nextInstanceId]); if (_nextInstanceId == 0xFFFFFFFF) { LOG_ERROR("server.worldserver", "Instance ID overflow!! Can't continue, shutting down server. "); World::StopNow(ERROR_EXIT_CODE); } return newInstanceId; } <|endoftext|>
<commit_before>// // audio-thread.cpp // ndnrtc // // Copyright 2013 Regents of the University of California // For licensing details see the LICENSE file. // // Author: Peter Gusev // #include "ndnrtc-namespace.h" #include "audio-thread.h" #include "segmentizer.h" using namespace ndnrtc::new_api; using namespace webrtc; using namespace boost; //****************************************************************************** #pragma mark - public int AudioThread::init(const AudioThreadSettings& settings) { settings_ = new AudioThreadSettings(); *settings_ = settings; int res = MediaThread::init(settings); if (RESULT_FAIL(res)) return res; rtpPacketPrefix_ = Name(threadPrefix_); rtpPacketPrefix_.append(Name(NameComponents::NameComponentStreamFramesDelta)); rtcpPacketPrefix_ = rtpPacketPrefix_; return res; } int AudioThread::publishPacket(PacketData &packetData, PrefixMetaInfo prefixMeta) { Name packetPrefix(rtpPacketPrefix_); packetPrefix.append(NdnRtcUtils::componentFromInt(packetNo_)); NdnRtcNamespace::appendDataKind(packetPrefix, false); prefixMeta.totalSegmentsNum_ = Segmentizer::getSegmentsNum(packetData.getLength(), segSizeNoHeader_); // no fec for audio prefixMeta.paritySegmentsNum_ = 0; prefixMeta.playbackNo_ = packetNo_; return MediaThread::publishPacket(packetData, packetPrefix, packetNo_, prefixMeta, NdnRtcUtils::unixTimestamp()); } void AudioThread::onDeliverRtpFrame(unsigned int len, unsigned char *data) { // in order to avoid situations when interest arrives simultaneously // with the data being added to the PIT/cache, we synchronize with // face on this level NdnRtcUtils::performOnBackgroundThread([this, data, len](){ publishRTPAudioPacket(len, data); }); } void AudioThread::onDeliverRtcpFrame(unsigned int len, unsigned char *data) { // in order to avoid situations when interest arrives simultaneously // with the data being added to the PIT/cache, we synchronize with // face on this level NdnRtcUtils::performOnBackgroundThread([this, data, len](){ publishRTCPAudioPacket(len, data); }); } int AudioThread::publishRTPAudioPacket(unsigned int len, unsigned char *data) { NdnAudioData::AudioPacket packet = {false, len, data}; if ((adata_.getLength() + packet.getLength()) > segSizeNoHeader_) { // update packet rate meter NdnRtcUtils::frequencyMeterTick(packetRateMeter_); // publish adata and flush publishPacket(adata_); adata_.clear(); packetNo_++; } adata_.addPacket(packet); return 0; } int AudioThread::publishRTCPAudioPacket(unsigned int len, unsigned char *data) { NdnAudioData::AudioPacket packet = (NdnAudioData::AudioPacket){true, len, data}; if ((adata_.getLength() + packet.getLength()) > segSizeNoHeader_) { NdnRtcUtils::frequencyMeterTick(packetRateMeter_); // publish adata and flush publishPacket(adata_); adata_.clear(); packetNo_++; } adata_.addPacket(packet); return 0; } <commit_msg>fixed deadlocking when publishing audio<commit_after>// // audio-thread.cpp // ndnrtc // // Copyright 2013 Regents of the University of California // For licensing details see the LICENSE file. // // Author: Peter Gusev // #include "ndnrtc-namespace.h" #include "audio-thread.h" #include "segmentizer.h" using namespace ndnrtc::new_api; using namespace webrtc; using namespace boost; //****************************************************************************** #pragma mark - public int AudioThread::init(const AudioThreadSettings& settings) { settings_ = new AudioThreadSettings(); *settings_ = settings; int res = MediaThread::init(settings); if (RESULT_FAIL(res)) return res; rtpPacketPrefix_ = Name(threadPrefix_); rtpPacketPrefix_.append(Name(NameComponents::NameComponentStreamFramesDelta)); rtcpPacketPrefix_ = rtpPacketPrefix_; return res; } int AudioThread::publishPacket(PacketData &packetData, PrefixMetaInfo prefixMeta) { Name packetPrefix(rtpPacketPrefix_); packetPrefix.append(NdnRtcUtils::componentFromInt(packetNo_)); NdnRtcNamespace::appendDataKind(packetPrefix, false); prefixMeta.totalSegmentsNum_ = Segmentizer::getSegmentsNum(packetData.getLength(), segSizeNoHeader_); // no fec for audio prefixMeta.paritySegmentsNum_ = 0; prefixMeta.playbackNo_ = packetNo_; return MediaThread::publishPacket(packetData, packetPrefix, packetNo_, prefixMeta, NdnRtcUtils::unixTimestamp()); } void AudioThread::onDeliverRtpFrame(unsigned int len, unsigned char *data) { // in order to avoid situations when interest arrives simultaneously // with the data being added to the PIT/cache, we synchronize with // face on this level NdnRtcUtils::dispatchOnBackgroundThread([this, data, len](){ publishRTPAudioPacket(len, data); }); } void AudioThread::onDeliverRtcpFrame(unsigned int len, unsigned char *data) { // in order to avoid situations when interest arrives simultaneously // with the data being added to the PIT/cache, we synchronize with // face on this level NdnRtcUtils::dispatchOnBackgroundThread([this, data, len](){ publishRTCPAudioPacket(len, data); }); } int AudioThread::publishRTPAudioPacket(unsigned int len, unsigned char *data) { NdnAudioData::AudioPacket packet = {false, len, data}; if ((adata_.getLength() + packet.getLength()) > segSizeNoHeader_) { // update packet rate meter NdnRtcUtils::frequencyMeterTick(packetRateMeter_); // publish adata and flush publishPacket(adata_); adata_.clear(); packetNo_++; } adata_.addPacket(packet); return 0; } int AudioThread::publishRTCPAudioPacket(unsigned int len, unsigned char *data) { NdnAudioData::AudioPacket packet = (NdnAudioData::AudioPacket){true, len, data}; if ((adata_.getLength() + packet.getLength()) > segSizeNoHeader_) { NdnRtcUtils::frequencyMeterTick(packetRateMeter_); // publish adata and flush publishPacket(adata_); adata_.clear(); packetNo_++; } adata_.addPacket(packet); return 0; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* * This file is part of the libetonyek project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <algorithm> #include <cmath> #include <deque> #include <boost/math/constants/constants.hpp> #include <libetonyek/KEYPresentationInterface.h> #include "KEYOutput.h" #include "KEYPath.h" #include "KEYShape.h" #include "KEYText.h" #include "KEYTransformation.h" #include "KEYTypes.h" namespace m = boost::math::double_constants; using std::deque; namespace libetonyek { KEYShape::KEYShape() : geometry() , style() , path() , text() { } namespace { class ShapeObject : public KEYObject { public: ShapeObject(const KEYShapePtr_t &shape); virtual ~ShapeObject(); private: virtual void draw(const KEYOutput &output); private: const KEYShapePtr_t m_shape; }; ShapeObject::ShapeObject(const KEYShapePtr_t &shape) : m_shape(shape) { } ShapeObject::~ShapeObject() { } void ShapeObject::draw(const KEYOutput &output) { if (bool(m_shape) && bool(m_shape->path)) { // TODO: make style const KEYTransformation tr = bool(m_shape->geometry) ? makeTransformation(*m_shape->geometry) : KEYTransformation(); KEYOutput newOutput(output, tr, m_shape->style); const KEYPath path = *m_shape->path * newOutput.getTransformation(); KEYPresentationInterface *const painter = output.getPainter(); painter->setStyle(WPXPropertyList(), WPXPropertyListVector()); painter->drawPath(path.toWPG()); if (bool(m_shape->text)) makeObject(m_shape->text)->draw(newOutput); } } } KEYObjectPtr_t makeObject(const KEYShapePtr_t &shape) { const KEYObjectPtr_t object(new ShapeObject(shape)); return object; } namespace { struct Point { double x; double y; Point(); Point(double x_, double y_); }; Point::Point() : x(0) , y(0) { } Point::Point(const double x_, const double y_) : x(x_) , y(y_) { } bool approxEqual(const Point &left, const Point &right, const double eps = KEY_EPSILON) { using libetonyek::approxEqual; return approxEqual(left.x, right.x, eps) && approxEqual(left.y, right.y, eps); } bool operator==(const Point &left, const Point &right) { return approxEqual(left, right); } bool operator!=(const Point &left, const Point &right) { return !(left == right); } } namespace { using namespace transformations; deque<Point> rotatePoint(const Point &point, const unsigned n) { deque<Point> points; const double angle = m::two_pi / n; points.push_back(point); for (unsigned i = 1; i < n; ++i) { Point pt(point); const KEYTransformation rot(rotate(i * angle)); rot(pt.x, pt.y); points.push_back(pt); } return points; } deque<Point> drawArrowHalf(const double headWidth, const double stemThickness) { // user space canvas: [0:1] x [0:1] deque<Point> points; points.push_back(Point(0, stemThickness)); points.push_back(Point(1 - headWidth, stemThickness)); points.push_back(Point(1 - headWidth, 1)); points.push_back(Point(1, 0)); return points; } KEYPathPtr_t makePolyLine(const deque<Point> inputPoints, bool close = true) { KEYPathPtr_t path; // need at least 2 points to make a polyline if (inputPoints.size() < 2) return path; // remove multiple points deque<Point> points; std::unique_copy(inputPoints.begin(), inputPoints.end(), back_inserter(points)); // close path if the first and last points are equal if (points.front() == points.back()) { points.pop_back(); close = true; } // ... but there must be at least 3 points to make a closed path if (points.size() < 3) close = false; // need at least 2 points to make a polyline if (points.size() < 2) return path; path.reset(new KEYPath()); deque<Point>::const_iterator it = points.begin(); path->appendMoveTo(it->x, it->y); ++it; for (; it != points.end(); ++it) path->appendLineTo(it->x, it->y); if (close) path->appendClose(); return path; } struct TransformPoint { TransformPoint(const KEYTransformation &tr) : m_tr(tr) { } void operator()(Point &point) const { m_tr(point.x, point.y); } private: const KEYTransformation &m_tr; }; void transform(deque<Point> &points, const KEYTransformation &tr) { for_each(points.begin(), points.end(), TransformPoint(tr)); } } KEYPathPtr_t makePolygonPath(const KEYSize &size, const unsigned edges) { // user space canvas: [-1:1] x [-1:1] deque<Point> points = rotatePoint(Point(0, -1), edges); // FIXME: the shape should probably be scaled to whole width/height. // Check. transform(points, translate(1, 1) * scale(0.5, 0.5) * scale(size.width, size.height)); const KEYPathPtr_t path = makePolyLine(points); return path; } KEYPathPtr_t makeRoundedRectanglePath(const KEYSize &size, const double radius) { // TODO: implement me (void) size; (void) radius; return KEYPathPtr_t(); } KEYPathPtr_t makeArrowPath(const KEYSize &size, const double headWidth, const double stemThickness) { deque<Point> points = drawArrowHalf(headWidth / size.width, stemThickness); // mirror around the x axis deque<Point> mirroredPoints = points; transform(mirroredPoints, flip(false, true)); // join the two point sets copy(mirroredPoints.rbegin(), mirroredPoints.rend(), back_inserter(points)); // transform and create path transform(points, translate(0, 1) * scale(1, 0.5) * scale(size.width, size.height)); const KEYPathPtr_t path = makePolyLine(points); return path; } KEYPathPtr_t makeDoubleArrowPath(const KEYSize &size, const double headWidth, const double stemThickness) { deque<Point> points = drawArrowHalf(2 * headWidth / size.width, stemThickness); { // mirror around the y axis deque<Point> mirroredPoints = points; transform(mirroredPoints, flip(true, false)); copy(mirroredPoints.begin(), mirroredPoints.end(), front_inserter(points)); } { // mirror around the x axis deque<Point> mirroredPoints = points; transform(mirroredPoints, flip(false, true)); copy(mirroredPoints.rbegin(), mirroredPoints.rend(), back_inserter(points)); } transform(points, translate(1, 1) * scale(0.5, 0.5) * scale(size.width, size.height)); const KEYPathPtr_t path = makePolyLine(points); return path; } KEYPathPtr_t makeStarPath(const KEYSize &size, const unsigned points, const double innerRadius) { // user space canvas: [-1:1] x [-1:1] // create outer points const deque<Point> outerPoints = rotatePoint(Point(0, -1), points); // create inner points const double angle = m::two_pi / points; deque<Point> innerPoints(outerPoints); transform(innerPoints, rotate(angle / 2) * scale(innerRadius, innerRadius)); // merge them together deque<Point> pathPoints; assert(outerPoints.size() == innerPoints.size()); for (deque<Point>::const_iterator itO = outerPoints.begin(), itI = innerPoints.begin(); (itO != outerPoints.end()) && (itI != innerPoints.end()); ++itO, ++itI) { pathPoints.push_back(*itO); pathPoints.push_back(*itI); } // create the path transform(pathPoints, translate(1, 1) * scale(0.5, 0.5) * scale(size.width, size.height)); const KEYPathPtr_t path = makePolyLine(pathPoints); return path; } KEYPathPtr_t makeConnectionPath(const KEYSize &size, const double middleX, const double middleY) { // TODO: implement me (void) size; (void) middleX; (void) middleY; return KEYPathPtr_t(); } KEYPathPtr_t makeCalloutPath(const KEYSize &size, const double radius, const double tailSize, const double tailX, const double tailY) { // TODO: implement me (void) size; (void) radius; (void) tailSize; (void) tailX; (void) tailY; return KEYPathPtr_t(); } KEYPathPtr_t makeQuoteBubblePath(const KEYSize &size, const double radius, const double tailSize, const double tailX, const double tailY) { // TODO: implement me (void) size; (void) radius; (void) tailSize; (void) tailX; (void) tailY; return KEYPathPtr_t(); } } /* vim:set shiftwidth=2 softtabstop=2 expandtab: */ <commit_msg>fix drawing of double-ended arrow<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* * This file is part of the libetonyek project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <algorithm> #include <cmath> #include <deque> #include <boost/math/constants/constants.hpp> #include <libetonyek/KEYPresentationInterface.h> #include "KEYOutput.h" #include "KEYPath.h" #include "KEYShape.h" #include "KEYText.h" #include "KEYTransformation.h" #include "KEYTypes.h" namespace m = boost::math::double_constants; using std::deque; namespace libetonyek { KEYShape::KEYShape() : geometry() , style() , path() , text() { } namespace { class ShapeObject : public KEYObject { public: ShapeObject(const KEYShapePtr_t &shape); virtual ~ShapeObject(); private: virtual void draw(const KEYOutput &output); private: const KEYShapePtr_t m_shape; }; ShapeObject::ShapeObject(const KEYShapePtr_t &shape) : m_shape(shape) { } ShapeObject::~ShapeObject() { } void ShapeObject::draw(const KEYOutput &output) { if (bool(m_shape) && bool(m_shape->path)) { // TODO: make style const KEYTransformation tr = bool(m_shape->geometry) ? makeTransformation(*m_shape->geometry) : KEYTransformation(); KEYOutput newOutput(output, tr, m_shape->style); const KEYPath path = *m_shape->path * newOutput.getTransformation(); KEYPresentationInterface *const painter = output.getPainter(); painter->setStyle(WPXPropertyList(), WPXPropertyListVector()); painter->drawPath(path.toWPG()); if (bool(m_shape->text)) makeObject(m_shape->text)->draw(newOutput); } } } KEYObjectPtr_t makeObject(const KEYShapePtr_t &shape) { const KEYObjectPtr_t object(new ShapeObject(shape)); return object; } namespace { struct Point { double x; double y; Point(); Point(double x_, double y_); }; Point::Point() : x(0) , y(0) { } Point::Point(const double x_, const double y_) : x(x_) , y(y_) { } bool approxEqual(const Point &left, const Point &right, const double eps = KEY_EPSILON) { using libetonyek::approxEqual; return approxEqual(left.x, right.x, eps) && approxEqual(left.y, right.y, eps); } bool operator==(const Point &left, const Point &right) { return approxEqual(left, right); } bool operator!=(const Point &left, const Point &right) { return !(left == right); } } namespace { using namespace transformations; deque<Point> rotatePoint(const Point &point, const unsigned n) { deque<Point> points; const double angle = m::two_pi / n; points.push_back(point); for (unsigned i = 1; i < n; ++i) { Point pt(point); const KEYTransformation rot(rotate(i * angle)); rot(pt.x, pt.y); points.push_back(pt); } return points; } deque<Point> drawArrowHalf(const double headWidth, const double stemThickness) { // user space canvas: [0:1] x [0:1] deque<Point> points; points.push_back(Point(0, stemThickness)); points.push_back(Point(1 - headWidth, stemThickness)); points.push_back(Point(1 - headWidth, 1)); points.push_back(Point(1, 0)); return points; } KEYPathPtr_t makePolyLine(const deque<Point> inputPoints, bool close = true) { KEYPathPtr_t path; // need at least 2 points to make a polyline if (inputPoints.size() < 2) return path; // remove multiple points deque<Point> points; std::unique_copy(inputPoints.begin(), inputPoints.end(), back_inserter(points)); // close path if the first and last points are equal if (points.front() == points.back()) { points.pop_back(); close = true; } // ... but there must be at least 3 points to make a closed path if (points.size() < 3) close = false; // need at least 2 points to make a polyline if (points.size() < 2) return path; path.reset(new KEYPath()); deque<Point>::const_iterator it = points.begin(); path->appendMoveTo(it->x, it->y); ++it; for (; it != points.end(); ++it) path->appendLineTo(it->x, it->y); if (close) path->appendClose(); return path; } struct TransformPoint { TransformPoint(const KEYTransformation &tr) : m_tr(tr) { } void operator()(Point &point) const { m_tr(point.x, point.y); } private: const KEYTransformation &m_tr; }; void transform(deque<Point> &points, const KEYTransformation &tr) { for_each(points.begin(), points.end(), TransformPoint(tr)); } } KEYPathPtr_t makePolygonPath(const KEYSize &size, const unsigned edges) { // user space canvas: [-1:1] x [-1:1] deque<Point> points = rotatePoint(Point(0, -1), edges); // FIXME: the shape should probably be scaled to whole width/height. // Check. transform(points, translate(1, 1) * scale(0.5, 0.5) * scale(size.width, size.height)); const KEYPathPtr_t path = makePolyLine(points); return path; } KEYPathPtr_t makeRoundedRectanglePath(const KEYSize &size, const double radius) { // TODO: implement me (void) size; (void) radius; return KEYPathPtr_t(); } KEYPathPtr_t makeArrowPath(const KEYSize &size, const double headWidth, const double stemThickness) { deque<Point> points = drawArrowHalf(headWidth / size.width, stemThickness); // mirror around the x axis deque<Point> mirroredPoints = points; transform(mirroredPoints, flip(false, true)); // join the two point sets copy(mirroredPoints.rbegin(), mirroredPoints.rend(), back_inserter(points)); // transform and create path transform(points, translate(0, 1) * scale(1, 0.5) * scale(size.width, size.height)); const KEYPathPtr_t path = makePolyLine(points); return path; } KEYPathPtr_t makeDoubleArrowPath(const KEYSize &size, const double headWidth, const double stemThickness) { deque<Point> points = drawArrowHalf(2 * headWidth / size.width, 1 - 2 * stemThickness); { // mirror around the y axis deque<Point> mirroredPoints = points; transform(mirroredPoints, flip(true, false)); copy(mirroredPoints.begin(), mirroredPoints.end(), front_inserter(points)); } { // mirror around the x axis deque<Point> mirroredPoints = points; transform(mirroredPoints, flip(false, true)); copy(mirroredPoints.rbegin(), mirroredPoints.rend(), back_inserter(points)); } transform(points, translate(1, 1) * scale(0.5, 0.5) * scale(size.width, size.height)); const KEYPathPtr_t path = makePolyLine(points); return path; } KEYPathPtr_t makeStarPath(const KEYSize &size, const unsigned points, const double innerRadius) { // user space canvas: [-1:1] x [-1:1] // create outer points const deque<Point> outerPoints = rotatePoint(Point(0, -1), points); // create inner points const double angle = m::two_pi / points; deque<Point> innerPoints(outerPoints); transform(innerPoints, rotate(angle / 2) * scale(innerRadius, innerRadius)); // merge them together deque<Point> pathPoints; assert(outerPoints.size() == innerPoints.size()); for (deque<Point>::const_iterator itO = outerPoints.begin(), itI = innerPoints.begin(); (itO != outerPoints.end()) && (itI != innerPoints.end()); ++itO, ++itI) { pathPoints.push_back(*itO); pathPoints.push_back(*itI); } // create the path transform(pathPoints, translate(1, 1) * scale(0.5, 0.5) * scale(size.width, size.height)); const KEYPathPtr_t path = makePolyLine(pathPoints); return path; } KEYPathPtr_t makeConnectionPath(const KEYSize &size, const double middleX, const double middleY) { // TODO: implement me (void) size; (void) middleX; (void) middleY; return KEYPathPtr_t(); } KEYPathPtr_t makeCalloutPath(const KEYSize &size, const double radius, const double tailSize, const double tailX, const double tailY) { // TODO: implement me (void) size; (void) radius; (void) tailSize; (void) tailX; (void) tailY; return KEYPathPtr_t(); } KEYPathPtr_t makeQuoteBubblePath(const KEYSize &size, const double radius, const double tailSize, const double tailX, const double tailY) { // TODO: implement me (void) size; (void) radius; (void) tailSize; (void) tailX; (void) tailY; return KEYPathPtr_t(); } } /* vim:set shiftwidth=2 softtabstop=2 expandtab: */ <|endoftext|>
<commit_before>#include <iostream> #include <cmath> #include <iomanip> using namespace std; int main() { string sstrana, suhlopricka; double strana, uhlopricka; cout << "Slyšel jsem, že neumíš spočítat obvod obdelníku." << endl; cout << "No, docela vostuda!" << endl; cout << "" << endl; cout << "Stranu změřit umíš? Tak ukaž: "; cin >> sstrana; strana = strtod(sstrana.c_str(), NULL); // Y U No Throw Exception? cout << "A co úhlopříčku? Zkus to: "; cin >> suhlopricka; uhlopricka = strtod(suhlopricka.c_str(), NULL); // Y U No Throw Exception? if (uhlopricka > 0 && strana > 0) { cout << "Deme počítat." << endl; double vysledek = (2 * strana + 2 * pow(abs (pow(strana, 2) - pow(uhlopricka, 2)), 0.5)); cout << "Výsledek je: "; cout << fixed << setprecision(2) << vysledek << endl; return (2 * strana + 2 * pow(abs (pow(strana, 2) - pow(uhlopricka, 2)), 0.5)); } else { cout << "Člověče, už jsi viděl obdelník s nulovou nebo zápornou stranou či úhlopříčkou?" << endl; cout << "Vzpamatuj se!" << endl; return -1; } } <commit_msg>Po vypoctu vrat 1<commit_after>#include <iostream> #include <cmath> #include <iomanip> using namespace std; int main() { string sstrana, suhlopricka; double strana, uhlopricka; cout << "Slyšel jsem, že neumíš spočítat obvod obdelníku." << endl; cout << "No, docela vostuda!" << endl; cout << "" << endl; cout << "Stranu změřit umíš? Tak ukaž: "; cin >> sstrana; strana = strtod(sstrana.c_str(), NULL); // Y U No Throw Exception? cout << "A co úhlopříčku? Zkus to: "; cin >> suhlopricka; uhlopricka = strtod(suhlopricka.c_str(), NULL); // Y U No Throw Exception? if (uhlopricka > 0 && strana > 0) { cout << "Deme počítat." << endl; double vysledek = (2 * strana + 2 * pow(abs (pow(strana, 2) - pow(uhlopricka, 2)), 0.5)); cout << "Výsledek je: "; cout << fixed << setprecision(2) << vysledek << endl; return 1; } else { cout << "Člověče, už jsi viděl obdelník s nulovou nebo zápornou stranou či úhlopříčkou?" << endl; cout << "Vzpamatuj se!" << endl; return -1; } } <|endoftext|>
<commit_before>Bool_t ConfigPhiLeadingPb( AliRsnMiniAnalysisTask *task, Bool_t isMC = kFALSE, Bool_t isPP = kFALSE, Double_t nSigmaPart1TPC = -1, Double_t nSigmaPart2TPC = -1, Double_t nSigmaPart1TOF = -1, Double_t nSigmaPart2TOF = -1 ) { // -- Values ------------------------------------------------------------------------------------ /* invariant mass */ Int_t imID = task->CreateValue(AliRsnMiniValue::kInvMass, kFALSE); /* transv. momentum */ Int_t ptID = task->CreateValue(AliRsnMiniValue::kPt, kFALSE); /* angel to leading */ Int_t alID = task->CreateValue(AliRsnMiniValue::kAngleLeading, kFALSE); /* pt of leading */ Int_t ptlID = task->CreateValue(AliRsnMiniValue::kLeadingPt, kFALSE); /* multiplicity */ Int_t multID = task->CreateValue(AliRsnMiniValue::kMult,kFALSE); /* delta eta */ Int_t detaID = task->CreateValue(AliRsnMiniValue::kDeltaEta, kFALSE); // Cuts TString scheme; AliRsnCutSet *cutSetKaon = new AliRsnCutSet("kaonCutSet", AliRsnTarget::kDaughter); AliRsnCutTrackQuality *trkQualityCut = new AliRsnCutTrackQuality("trackQualityCut"); trkQualityCut->SetDefaults2011(kTRUE, kTRUE); cutSetKaon->AddCut(trkQualityCut); if (!scheme.IsNull()) scheme += "&"; scheme += trkQualityCut->GetName(); if (nSigmaPart1TPC >= 0) { AliRsnCutPIDNSigma *cutKTPC = new AliRsnCutPIDNSigma("cutNSigmaTPCK", AliPID::kKaon, AliRsnCutPIDNSigma::kTPC); cutKTPC->SinglePIDRange(nSigmaPart1TPC); cutSetKaon->AddCut(cutKTPC); if (!scheme.IsNull()) scheme += "&"; scheme += cutKTPC->GetName(); } cutSetKaon->SetCutScheme(scheme.Data()); Int_t iTrackCutK = task->AddTrackCuts(cutSetKaon); // Defining output objects const Int_t dims = 6; Int_t useIM[dims] = {1, 1, 0, 0, isMC, isMC}; TString name[dims] = {"Unlike", "Mixing", "LikePP", "LikeMM", "True", "Mother"}; TString comp[dims] = {"PAIR", "MIX", "PAIR", "PAIR", "TRUE", "MOTHER"}; TString output[dims] = {"SPARSE", "SPARSE", "SPARSE", "SPARSE", "SPARSE", "SPARSE"}; Char_t charge1[dims] = {'+', '+', '+', '-', '+', '+'}; Char_t charge2[dims] = {'-', '-', '+', '-', '-', '-'}; Int_t pdgCode[dims] = {333, 333, 333, 333, 333, 333}; Double_t motherMass[dims] = {1.019461, 1.019461, 1.019461, 1.019461, 1.019461, 1.019461}; for (Int_t i = 0; i < dims; i++) { if (!useIM[i]) continue; AliRsnMiniOutput *out = task->CreateOutput(name[i].Data(), output[i].Data(), comp[i].Data()); out->SetCutID(0, iTrackCutK); out->SetCutID(1, iTrackCutK); out->SetDaughter(0, AliRsnDaughter::kKaon); out->SetDaughter(1, AliRsnDaughter::kKaon); out->SetCharge(0, charge1[i]); out->SetCharge(1, charge2[i]); out->SetMotherPDG(pdgCode[i]); out->SetMotherMass(motherMass[i]); out->AddAxis(imID, 95, 0.985, 1.08; out->AddAxis(ptID, 8, 2., 10.); if(!isPP ) out->AddAxis(multID,10,0.,100.); else out->AddAxis(multID, 10, 0., 100.); out->AddAxis(alID, 36, -0.5 * TMath::Pi(), 1.5 * TMath::Pi()); out->AddAxis(ptlID, 26, 4., 30.); out->AddAxis(detaID, 16, -1.6, 1.6); } return kTRUE; } <commit_msg>fix config phi Pb<commit_after>Bool_t ConfigPhiLeadingPb( AliRsnMiniAnalysisTask *task, Bool_t isMC = kFALSE, Bool_t isPP = kFALSE, Double_t nSigmaPart1TPC = -1, Double_t nSigmaPart2TPC = -1, Double_t nSigmaPart1TOF = -1, Double_t nSigmaPart2TOF = -1 ) { // -- Values ------------------------------------------------------------------------------------ /* invariant mass */ Int_t imID = task->CreateValue(AliRsnMiniValue::kInvMass, kFALSE); /* transv. momentum */ Int_t ptID = task->CreateValue(AliRsnMiniValue::kPt, kFALSE); /* angel to leading */ Int_t alID = task->CreateValue(AliRsnMiniValue::kAngleLeading, kFALSE); /* pt of leading */ Int_t ptlID = task->CreateValue(AliRsnMiniValue::kLeadingPt, kFALSE); /* multiplicity */ Int_t multID = task->CreateValue(AliRsnMiniValue::kMult,kFALSE); /* delta eta */ Int_t detaID = task->CreateValue(AliRsnMiniValue::kDeltaEta, kFALSE); // Cuts TString scheme; AliRsnCutSet *cutSetKaon = new AliRsnCutSet("kaonCutSet", AliRsnTarget::kDaughter); AliRsnCutTrackQuality *trkQualityCut = new AliRsnCutTrackQuality("trackQualityCut"); trkQualityCut->SetDefaults2011(kTRUE, kTRUE); cutSetKaon->AddCut(trkQualityCut); if (!scheme.IsNull()) scheme += "&"; scheme += trkQualityCut->GetName(); if (nSigmaPart1TPC >= 0) { AliRsnCutPIDNSigma *cutKTPC = new AliRsnCutPIDNSigma("cutNSigmaTPCK", AliPID::kKaon, AliRsnCutPIDNSigma::kTPC); cutKTPC->SinglePIDRange(nSigmaPart1TPC); cutSetKaon->AddCut(cutKTPC); if (!scheme.IsNull()) scheme += "&"; scheme += cutKTPC->GetName(); } cutSetKaon->SetCutScheme(scheme.Data()); Int_t iTrackCutK = task->AddTrackCuts(cutSetKaon); // Defining output objects const Int_t dims = 6; Int_t useIM[dims] = {1, 1, 0, 0, isMC, isMC}; TString name[dims] = {"Unlike", "Mixing", "LikePP", "LikeMM", "True", "Mother"}; TString comp[dims] = {"PAIR", "MIX", "PAIR", "PAIR", "TRUE", "MOTHER"}; TString output[dims] = {"SPARSE", "SPARSE", "SPARSE", "SPARSE", "SPARSE", "SPARSE"}; Char_t charge1[dims] = {'+', '+', '+', '-', '+', '+'}; Char_t charge2[dims] = {'-', '-', '+', '-', '-', '-'}; Int_t pdgCode[dims] = {333, 333, 333, 333, 333, 333}; Double_t motherMass[dims] = {1.019461, 1.019461, 1.019461, 1.019461, 1.019461, 1.019461}; for (Int_t i = 0; i < dims; i++) { if (!useIM[i]) continue; AliRsnMiniOutput *out = task->CreateOutput(name[i].Data(), output[i].Data(), comp[i].Data()); out->SetCutID(0, iTrackCutK); out->SetCutID(1, iTrackCutK); out->SetDaughter(0, AliRsnDaughter::kKaon); out->SetDaughter(1, AliRsnDaughter::kKaon); out->SetCharge(0, charge1[i]); out->SetCharge(1, charge2[i]); out->SetMotherPDG(pdgCode[i]); out->SetMotherMass(motherMass[i]); out->AddAxis(imID, 95, 0.985, 1.08); out->AddAxis(ptID, 8, 2., 10.); if(!isPP ) out->AddAxis(multID,10,0.,100.); else out->AddAxis(multID, 10, 0., 100.); out->AddAxis(alID, 36, -0.5 * TMath::Pi(), 1.5 * TMath::Pi()); out->AddAxis(ptlID, 26, 4., 30.); out->AddAxis(detaID, 16, -1.6, 1.6); } return kTRUE; } <|endoftext|>
<commit_before>// Copyright (c) 2012 Intel Corp // Copyright (c) 2012 The Chromium Authors // // 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 co // pies 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 al // l copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM // PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES // S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS // OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH // ETHER 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 "content/nw/src/shell_browser_main_parts.h" #include "base/bind.h" #include "base/command_line.h" #include "base/message_loop/message_loop.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_restrictions.h" #include "base/values.h" #include "chrome/common/chrome_switches.h" #include "content/nw/src/api/app/app.h" #include "content/nw/src/api/dispatcher_host.h" #include "content/nw/src/breakpad_linux.h" #include "content/nw/src/browser/printing/print_job_manager.h" #include "content/nw/src/browser/shell_devtools_delegate.h" #include "content/nw/src/common/shell_switches.h" #include "content/nw/src/nw_package.h" #include "content/nw/src/nw_shell.h" #include "content/nw/src/shell_browser_context.h" #include "content/public/common/content_switches.h" #include "content/public/common/main_function_params.h" #include "grit/net_resources.h" #include "net/base/net_module.h" #include "net/proxy/proxy_resolver_v8.h" #include "ui/base/ime/input_method_initializer.h" #include "ui/base/resource/resource_bundle.h" #if !defined(OS_WIN) #include <sys/resource.h> #endif #if defined(TOOLKIT_GTK) #include "content/nw/src/browser/printing/print_dialog_gtk.h" #endif #if defined(USE_AURA) #include "ui/aura/env.h" #include "ui/gfx/screen.h" #include "ui/views/test/desktop_test_views_delegate.h" #include "ui/views/widget/desktop_aura/desktop_screen.h" #endif // defined(USE_AURA) #if defined(OS_LINUX) #include "chrome/browser/ui/libgtk2ui/gtk2_ui.h" #include "ui/aura/window.h" #include "ui/base/ime/input_method_initializer.h" #include "ui/native_theme/native_theme_aura.h" #include "ui/views/linux_ui/linux_ui.h" #endif using base::MessageLoop; namespace { #if !defined(OS_WIN) // Sets the file descriptor soft limit to |max_descriptors| or the OS hard // limit, whichever is lower. void SetFileDescriptorLimit(unsigned int max_descriptors) { struct rlimit limits; if (getrlimit(RLIMIT_NOFILE, &limits) == 0) { unsigned int new_limit = max_descriptors; if (limits.rlim_max > 0 && limits.rlim_max < max_descriptors) { new_limit = limits.rlim_max; } limits.rlim_cur = new_limit; if (setrlimit(RLIMIT_NOFILE, &limits) != 0) { PLOG(INFO) << "Failed to set file descriptor limit"; } } else { PLOG(INFO) << "Failed to get file descriptor limit"; } } #endif base::StringPiece PlatformResourceProvider(int key) { if (key == IDR_DIR_HEADER_HTML) { base::StringPiece html_data = ui::ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_DIR_HEADER_HTML); return html_data; } return base::StringPiece(); } } // namespace namespace content { ShellBrowserMainParts::ShellBrowserMainParts( const MainFunctionParams& parameters) : BrowserMainParts(), parameters_(parameters), run_message_loop_(true), devtools_delegate_(NULL), notify_result_(ProcessSingleton::PROCESS_NONE) { #if defined(ENABLE_PRINTING) // Must be created after the NotificationService. print_job_manager_.reset(new printing::PrintJobManager); #endif } ShellBrowserMainParts::~ShellBrowserMainParts() { } #if !defined(OS_MACOSX) void ShellBrowserMainParts::PreMainMessageLoopStart() { } #endif void ShellBrowserMainParts::PreMainMessageLoopRun() { #if !defined(OS_MACOSX) Init(); #endif if (parameters_.ui_task) { parameters_.ui_task->Run(); delete parameters_.ui_task; run_message_loop_ = false; } } bool ShellBrowserMainParts::MainMessageLoopRun(int* result_code) { return !run_message_loop_; } void ShellBrowserMainParts::PostMainMessageLoopRun() { if (devtools_delegate_) devtools_delegate_->Stop(); if (notify_result_ == ProcessSingleton::PROCESS_NONE) process_singleton_->Cleanup(); browser_context_.reset(); off_the_record_browser_context_.reset(); } void ShellBrowserMainParts::PostMainMessageLoopStart() { #if defined(TOOLKIT_GTK) printing::PrintingContextLinux::SetCreatePrintDialogFunction( &PrintDialogGtk::CreatePrintDialog); #endif } int ShellBrowserMainParts::PreCreateThreads() { net::ProxyResolverV8::EnsureIsolateCreated(); #if defined(USE_AURA) gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, views::CreateDesktopScreen()); #endif base::ThreadRestrictions::ScopedAllowIO allow_io; package_.reset(new nw::Package()); return 0; } void ShellBrowserMainParts::PostDestroyThreads() { #if defined(USE_AURA) aura::Env::DeleteInstance(); delete views::ViewsDelegate::views_delegate; #endif } void ShellBrowserMainParts::ToolkitInitialized() { #if defined(USE_AURA) aura::Env::CreateInstance(true); DCHECK(!views::ViewsDelegate::views_delegate); new views::DesktopTestViewsDelegate; #endif #if defined(OS_LINUX) views::LinuxUI::instance()->Initialize(); #endif } void ShellBrowserMainParts::Init() { //this will be reset to false before entering the message loop base::ThreadRestrictions::SetIOAllowed(true); CommandLine& command_line = *CommandLine::ForCurrentProcess(); browser_context_.reset(new ShellBrowserContext(false, package())); browser_context_->PreMainMessageLoopRun(); off_the_record_browser_context_.reset( new ShellBrowserContext(true, package())); process_singleton_.reset(new ProcessSingleton(browser_context_->GetPath(), base::Bind(&ShellBrowserMainParts::ProcessSingletonNotificationCallback, base::Unretained(this)))); notify_result_ = process_singleton_->NotifyOtherProcessOrCreate(); // Quit if the other existing instance want to handle it. if (notify_result_ == ProcessSingleton::PROCESS_NOTIFIED) { MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure()); return; } net::NetModule::SetResourceProvider(PlatformResourceProvider); int port = 0; // See if the user specified a port on the command line (useful for // automation). If not, use an ephemeral port by specifying 0. if (command_line.HasSwitch(switches::kRemoteDebuggingPort)) { int temp_port; std::string port_str = command_line.GetSwitchValueASCII(switches::kRemoteDebuggingPort); if (base::StringToInt(port_str, &temp_port) && temp_port > 0 && temp_port < 65535) { port = temp_port; } else { DLOG(WARNING) << "Invalid http debugger port number " << temp_port; } } devtools_delegate_ = new ShellDevToolsDelegate(browser_context_.get(), port); Shell::Create(browser_context_.get(), package()->GetStartupURL(), NULL, MSG_ROUTING_NONE, NULL); } bool ShellBrowserMainParts::ProcessSingletonNotificationCallback( const CommandLine& command_line, const base::FilePath& current_directory) { // Don't reuse current instance if 'single-instance' is specified to false. bool single_instance; if (package_->root()->GetBoolean(switches::kmSingleInstance, &single_instance) && !single_instance) return false; #if defined(OS_WIN) std::string cmd = base::UTF16ToUTF8(command_line.GetCommandLineString()); #else std::string cmd = command_line.GetCommandLineString(); #endif static const char* const kSwitchNames[] = { switches::kNoSandbox, switches::kProcessPerTab, switches::kEnableExperimentalWebPlatformFeatures, // switches::kEnableCssShaders, switches::kAllowFileAccessFromFiles, }; for (size_t i = 0; i < arraysize(kSwitchNames); ++i) { ReplaceSubstringsAfterOffset(&cmd, 0, std::string(" --") + kSwitchNames[i], ""); } #if 0 nwapi::App::EmitOpenEvent(UTF16ToUTF8(cmd)); #else nwapi::App::EmitOpenEvent(cmd); #endif return true; } printing::PrintJobManager* ShellBrowserMainParts::print_job_manager() { // TODO(abarth): DCHECK(CalledOnValidThread()); // http://code.google.com/p/chromium/issues/detail?id=6828 // print_job_manager_ is initialized in the constructor and destroyed in the // destructor, so it should always be valid. DCHECK(print_job_manager_.get()); return print_job_manager_.get(); } void ShellBrowserMainParts::PreEarlyInitialization() { #if !defined(OS_WIN) // see chrome_browser_main_posix.cc CommandLine& command_line = *CommandLine::ForCurrentProcess(); const std::string fd_limit_string = command_line.GetSwitchValueASCII("file-descriptor-limit"); int fd_limit = 0; if (!fd_limit_string.empty()) { base::StringToInt(fd_limit_string, &fd_limit); } #if defined(OS_MACOSX) // We use quite a few file descriptors for our IPC, and the default limit on // the Mac is low (256), so bump it up if there is no explicit override. if (fd_limit == 0) { fd_limit = 1024; } #endif // OS_MACOSX if (fd_limit > 0) SetFileDescriptorLimit(fd_limit); #endif // !OS_WIN #if defined(OS_LINUX) views::LinuxUI* gtk2_ui = BuildGtk2UI(); // gtk2_ui->SetNativeThemeOverride(base::Bind(&GetNativeThemeForWindow)); views::LinuxUI::SetInstance(gtk2_ui); // ui::InitializeInputMethodForTesting(); #endif } } // namespace content <commit_msg>Set default port of devtools to 9222<commit_after>// Copyright (c) 2012 Intel Corp // Copyright (c) 2012 The Chromium Authors // // 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 co // pies 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 al // l copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM // PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES // S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS // OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH // ETHER 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 "content/nw/src/shell_browser_main_parts.h" #include "base/bind.h" #include "base/command_line.h" #include "base/message_loop/message_loop.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_restrictions.h" #include "base/values.h" #include "chrome/common/chrome_switches.h" #include "content/nw/src/api/app/app.h" #include "content/nw/src/api/dispatcher_host.h" #include "content/nw/src/breakpad_linux.h" #include "content/nw/src/browser/printing/print_job_manager.h" #include "content/nw/src/browser/shell_devtools_delegate.h" #include "content/nw/src/common/shell_switches.h" #include "content/nw/src/nw_package.h" #include "content/nw/src/nw_shell.h" #include "content/nw/src/shell_browser_context.h" #include "content/public/common/content_switches.h" #include "content/public/common/main_function_params.h" #include "grit/net_resources.h" #include "net/base/net_module.h" #include "net/proxy/proxy_resolver_v8.h" #include "ui/base/ime/input_method_initializer.h" #include "ui/base/resource/resource_bundle.h" #if !defined(OS_WIN) #include <sys/resource.h> #endif #if defined(TOOLKIT_GTK) #include "content/nw/src/browser/printing/print_dialog_gtk.h" #endif #if defined(USE_AURA) #include "ui/aura/env.h" #include "ui/gfx/screen.h" #include "ui/views/test/desktop_test_views_delegate.h" #include "ui/views/widget/desktop_aura/desktop_screen.h" #endif // defined(USE_AURA) #if defined(OS_LINUX) #include "chrome/browser/ui/libgtk2ui/gtk2_ui.h" #include "ui/aura/window.h" #include "ui/base/ime/input_method_initializer.h" #include "ui/native_theme/native_theme_aura.h" #include "ui/views/linux_ui/linux_ui.h" #endif using base::MessageLoop; namespace { #if !defined(OS_WIN) // Sets the file descriptor soft limit to |max_descriptors| or the OS hard // limit, whichever is lower. void SetFileDescriptorLimit(unsigned int max_descriptors) { struct rlimit limits; if (getrlimit(RLIMIT_NOFILE, &limits) == 0) { unsigned int new_limit = max_descriptors; if (limits.rlim_max > 0 && limits.rlim_max < max_descriptors) { new_limit = limits.rlim_max; } limits.rlim_cur = new_limit; if (setrlimit(RLIMIT_NOFILE, &limits) != 0) { PLOG(INFO) << "Failed to set file descriptor limit"; } } else { PLOG(INFO) << "Failed to get file descriptor limit"; } } #endif base::StringPiece PlatformResourceProvider(int key) { if (key == IDR_DIR_HEADER_HTML) { base::StringPiece html_data = ui::ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_DIR_HEADER_HTML); return html_data; } return base::StringPiece(); } } // namespace namespace content { ShellBrowserMainParts::ShellBrowserMainParts( const MainFunctionParams& parameters) : BrowserMainParts(), parameters_(parameters), run_message_loop_(true), devtools_delegate_(NULL), notify_result_(ProcessSingleton::PROCESS_NONE) { #if defined(ENABLE_PRINTING) // Must be created after the NotificationService. print_job_manager_.reset(new printing::PrintJobManager); #endif } ShellBrowserMainParts::~ShellBrowserMainParts() { } #if !defined(OS_MACOSX) void ShellBrowserMainParts::PreMainMessageLoopStart() { } #endif void ShellBrowserMainParts::PreMainMessageLoopRun() { #if !defined(OS_MACOSX) Init(); #endif if (parameters_.ui_task) { parameters_.ui_task->Run(); delete parameters_.ui_task; run_message_loop_ = false; } } bool ShellBrowserMainParts::MainMessageLoopRun(int* result_code) { return !run_message_loop_; } void ShellBrowserMainParts::PostMainMessageLoopRun() { if (devtools_delegate_) devtools_delegate_->Stop(); if (notify_result_ == ProcessSingleton::PROCESS_NONE) process_singleton_->Cleanup(); browser_context_.reset(); off_the_record_browser_context_.reset(); } void ShellBrowserMainParts::PostMainMessageLoopStart() { #if defined(TOOLKIT_GTK) printing::PrintingContextLinux::SetCreatePrintDialogFunction( &PrintDialogGtk::CreatePrintDialog); #endif } int ShellBrowserMainParts::PreCreateThreads() { net::ProxyResolverV8::EnsureIsolateCreated(); #if defined(USE_AURA) gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, views::CreateDesktopScreen()); #endif base::ThreadRestrictions::ScopedAllowIO allow_io; package_.reset(new nw::Package()); return 0; } void ShellBrowserMainParts::PostDestroyThreads() { #if defined(USE_AURA) aura::Env::DeleteInstance(); delete views::ViewsDelegate::views_delegate; #endif } void ShellBrowserMainParts::ToolkitInitialized() { #if defined(USE_AURA) aura::Env::CreateInstance(true); DCHECK(!views::ViewsDelegate::views_delegate); new views::DesktopTestViewsDelegate; #endif #if defined(OS_LINUX) views::LinuxUI::instance()->Initialize(); #endif } void ShellBrowserMainParts::Init() { //this will be reset to false before entering the message loop base::ThreadRestrictions::SetIOAllowed(true); CommandLine& command_line = *CommandLine::ForCurrentProcess(); browser_context_.reset(new ShellBrowserContext(false, package())); browser_context_->PreMainMessageLoopRun(); off_the_record_browser_context_.reset( new ShellBrowserContext(true, package())); process_singleton_.reset(new ProcessSingleton(browser_context_->GetPath(), base::Bind(&ShellBrowserMainParts::ProcessSingletonNotificationCallback, base::Unretained(this)))); notify_result_ = process_singleton_->NotifyOtherProcessOrCreate(); // Quit if the other existing instance want to handle it. if (notify_result_ == ProcessSingleton::PROCESS_NOTIFIED) { MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure()); return; } net::NetModule::SetResourceProvider(PlatformResourceProvider); // FIXME: This is a workaround to fix #2206 by setting default port to non-zero. // The real fix would be enabling chrome-devtools:// schema. int port = 9222; // See if the user specified a port on the command line (useful for // automation). If not, use an ephemeral port by specifying 0. if (command_line.HasSwitch(switches::kRemoteDebuggingPort)) { int temp_port; std::string port_str = command_line.GetSwitchValueASCII(switches::kRemoteDebuggingPort); // FIXME: should revert to `temp_port > 0` when chrome-devtools:// is enabled if (base::StringToInt(port_str, &temp_port) && temp_port >= 0 && temp_port < 65535) { port = temp_port; } else { DLOG(WARNING) << "Invalid http debugger port number " << temp_port; } } devtools_delegate_ = new ShellDevToolsDelegate(browser_context_.get(), port); Shell::Create(browser_context_.get(), package()->GetStartupURL(), NULL, MSG_ROUTING_NONE, NULL); } bool ShellBrowserMainParts::ProcessSingletonNotificationCallback( const CommandLine& command_line, const base::FilePath& current_directory) { // Don't reuse current instance if 'single-instance' is specified to false. bool single_instance; if (package_->root()->GetBoolean(switches::kmSingleInstance, &single_instance) && !single_instance) return false; #if defined(OS_WIN) std::string cmd = base::UTF16ToUTF8(command_line.GetCommandLineString()); #else std::string cmd = command_line.GetCommandLineString(); #endif static const char* const kSwitchNames[] = { switches::kNoSandbox, switches::kProcessPerTab, switches::kEnableExperimentalWebPlatformFeatures, // switches::kEnableCssShaders, switches::kAllowFileAccessFromFiles, }; for (size_t i = 0; i < arraysize(kSwitchNames); ++i) { ReplaceSubstringsAfterOffset(&cmd, 0, std::string(" --") + kSwitchNames[i], ""); } #if 0 nwapi::App::EmitOpenEvent(UTF16ToUTF8(cmd)); #else nwapi::App::EmitOpenEvent(cmd); #endif return true; } printing::PrintJobManager* ShellBrowserMainParts::print_job_manager() { // TODO(abarth): DCHECK(CalledOnValidThread()); // http://code.google.com/p/chromium/issues/detail?id=6828 // print_job_manager_ is initialized in the constructor and destroyed in the // destructor, so it should always be valid. DCHECK(print_job_manager_.get()); return print_job_manager_.get(); } void ShellBrowserMainParts::PreEarlyInitialization() { #if !defined(OS_WIN) // see chrome_browser_main_posix.cc CommandLine& command_line = *CommandLine::ForCurrentProcess(); const std::string fd_limit_string = command_line.GetSwitchValueASCII("file-descriptor-limit"); int fd_limit = 0; if (!fd_limit_string.empty()) { base::StringToInt(fd_limit_string, &fd_limit); } #if defined(OS_MACOSX) // We use quite a few file descriptors for our IPC, and the default limit on // the Mac is low (256), so bump it up if there is no explicit override. if (fd_limit == 0) { fd_limit = 1024; } #endif // OS_MACOSX if (fd_limit > 0) SetFileDescriptorLimit(fd_limit); #endif // !OS_WIN #if defined(OS_LINUX) views::LinuxUI* gtk2_ui = BuildGtk2UI(); // gtk2_ui->SetNativeThemeOverride(base::Bind(&GetNativeThemeForWindow)); views::LinuxUI::SetInstance(gtk2_ui); // ui::InitializeInputMethodForTesting(); #endif } } // namespace content <|endoftext|>
<commit_before>// $Id$ //************************************************************************** //* This file is property of and copyright by the ALICE HLT Project * //* ALICE Experiment at CERN, All rights reserved. * //* * //* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no> * //* for The ALICE HLT Project. * //* * //* Permission to use, copy, modify and distribute this software and its * //* documentation strictly for non-commercial purposes is hereby granted * //* without fee, provided that the above copyright notice appears in all * //* copies and that both the copyright notice and this permission notice * //* appear in the supporting documentation. The authors make no claims * //* about the suitability of this software for any purpose. It is * //* provided "as is" without express or implied warranty. * //************************************************************************** /// @file AliHLTGlobalHistoComponent.cxx /// @author Matthias Richter /// @date 2010-09-16 /// @brief A histogramming component for global ESD properties based /// on the AliHLTTTreeProcessor #include "AliHLTGlobalHistoComponent.h" #include "AliESDEvent.h" #include "TTree.h" #include "TString.h" #include "TObjString.h" #include "TObjArray.h" #include <cassert> /** ROOT macro for the implementation of ROOT specific class methods */ ClassImp(AliHLTGlobalHistoComponent) AliHLTGlobalHistoComponent::AliHLTGlobalHistoComponent() : AliHLTTTreeProcessor() , fEvent(0) , fNofTracks(0) , fVertexX(-99) , fVertexY(-99) , fVertexZ(-99) , fTrackVariables() { // see header file for class documentation // or // refer to README to build package // or // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt } AliHLTGlobalHistoComponent::~AliHLTGlobalHistoComponent() { // see header file for class documentation fTrackVariables.Reset(); } void AliHLTGlobalHistoComponent::GetInputDataTypes(AliHLTComponentDataTypeList& list) { // see header file for class documentation list.push_back(kAliHLTAllDataTypes); } TTree* AliHLTGlobalHistoComponent::CreateTree(int /*argc*/, const char** /*argv*/) { // create the tree and branches int iResult=0; TTree* pTree=new TTree("ESDproperties", "HLT ESD properties"); if (!pTree) return NULL; const char* trackVariableNames = { "Track_pt " "Track_phi " "Track_eta " "Track_p " "Track_theta " "Track_Nclusters " "Track_status " "Track_charge " "Track_DCAr " "Track_DCAz " "Track_dEdx " }; int maxTrackCount=20000; // FIXME: make configurable if ((iResult=fTrackVariables.Init(maxTrackCount, trackVariableNames))<0) { HLTError("failed to initialize internal structure for track properties"); } if (iResult>=0) { pTree->Branch("event", &fEvent, "event/I"); pTree->Branch("trackcount", &fNofTracks, "trackcount/I"); pTree->Branch("vertexX", &fVertexX, "vertexX/F"); pTree->Branch("vertexY", &fVertexY, "vertexY/F"); pTree->Branch("vertexZ", &fVertexZ, "vertexZ/F"); for (int i=0; i<fTrackVariables.Variables(); i++) { TString specifier=fTrackVariables.GetKey(i); float* pArray=fTrackVariables.GetArray(specifier); specifier+="[trackcount]/f"; specifier+="[vertexX]/f"; pTree->Branch(fTrackVariables.GetKey(i), pArray, specifier.Data()); } } else { delete pTree; pTree=NULL; } return pTree; } void AliHLTGlobalHistoComponent::FillHistogramDefinitions() { /// default histogram definitions } int AliHLTGlobalHistoComponent::FillTree(TTree* pTree, const AliHLTComponentEventData& /*evtData*/, AliHLTComponentTriggerData& /*trigData*/ ) { /// fill the tree from the ESD int iResult=0; if (!IsDataEvent()) return 0; ResetVariables(); // fetch ESD from input stream const TObject* obj = GetFirstInputObject(kAliHLTAllDataTypes, "AliESDEvent"); AliESDEvent* esd = dynamic_cast<AliESDEvent*>(const_cast<TObject*>(obj)); esd->GetStdContent(); // fill track variables fNofTracks=esd->GetNumberOfTracks(); fVertexX = esd->GetPrimaryVertexTracks()->GetX(); fVertexY = esd->GetPrimaryVertexTracks()->GetY(); fVertexZ = esd->GetPrimaryVertexTracks()->GetZ(); for (int i=0; i<fNofTracks; i++) { AliESDtrack *esdTrack = esd->GetTrack(i); if (!esdTrack) continue; Float_t DCAr, DCAz = -99; esdTrack->GetImpactParametersTPC(DCAr, DCAz); fTrackVariables.Fill("Track_pt" , esdTrack->Pt() ); fTrackVariables.Fill("Track_phi" , esdTrack->Phi()*TMath::RadToDeg() ); fTrackVariables.Fill("Track_eta" , esdTrack->Theta() ); fTrackVariables.Fill("Track_p" , esdTrack->P() ); fTrackVariables.Fill("Track_theta" , esdTrack->Theta()*TMath::RadToDeg() ); fTrackVariables.Fill("Track_Nclusters" , esdTrack->GetTPCNcls() ); fTrackVariables.Fill("Track_status" , esdTrack->GetStatus() ); fTrackVariables.Fill("Track_charge" , esdTrack->Charge() ); fTrackVariables.Fill("Track_DCAr" , DCAr ); fTrackVariables.Fill("Track_DCAz" , DCAz ); fTrackVariables.Fill("Track_dEdx" , esdTrack->GetTPCsignal() ); } HLTInfo("added parameters for %d tracks", fNofTracks); if (iResult<0) { // fill an empty event ResetVariables(); } fEvent++; pTree->Fill(); return iResult; } int AliHLTGlobalHistoComponent::ResetVariables() { /// reset all filling variables fNofTracks=0; fTrackVariables.ResetCount(); return 0; } AliHLTComponentDataType AliHLTGlobalHistoComponent::GetOriginDataType() const { // get the origin of the output data return kAliHLTVoidDataType; } // AliHLTUInt32_t AliHLTGlobalHistoComponent::GetDataSpec() const; // { // // get specifications of the output data // return 0; // } AliHLTGlobalHistoComponent::AliHLTGlobalHistoVariables::AliHLTGlobalHistoVariables() : fCapacity(0) , fArrays() , fCount() , fKeys() { /// default constructor } AliHLTGlobalHistoComponent::AliHLTGlobalHistoVariables::~AliHLTGlobalHistoVariables() { /// destructor Reset(); } int AliHLTGlobalHistoComponent::AliHLTGlobalHistoVariables::Init(int capacity, const char* names) { /// init the arrays int iResult=0; TString initializer(names); TObjArray* pTokens=initializer.Tokenize(" "); fCapacity=capacity; if (pTokens) { int entries=pTokens->GetEntriesFast(); fArrays.resize(entries); fCount.resize(entries); for (int i=0; i<entries; i++) { fKeys[pTokens->At(i)->GetName()]=i; fArrays[i]=new float[fCapacity]; } delete pTokens; } assert(fArrays.size()==fCount.size()); assert(fArrays.size()==fKeys.size()); if (fArrays.size()!=fCount.size() || fArrays.size()!=fKeys.size()) { return -EFAULT; } ResetCount(); return iResult; } int AliHLTGlobalHistoComponent::AliHLTGlobalHistoVariables::Reset() { /// reset the arrays for (vector<float*>::iterator element=fArrays.begin(); element!=fArrays.end(); element++) { delete *element; } fArrays.clear(); fCount.clear(); fKeys.clear(); return 0; } int AliHLTGlobalHistoComponent::AliHLTGlobalHistoVariables::ResetCount() { /// reset the fill counts for (vector<int>::iterator element=fCount.begin(); element!=fCount.end(); element++) { *element=0; } return 0; } int AliHLTGlobalHistoComponent::AliHLTGlobalHistoVariables::Fill(unsigned index, float value) { /// fill variable at index assert(fArrays.size()==fCount.size()); if (index>=fArrays.size() || index>=fCount.size()) return -ENOENT; if (fCount[index]>=fCapacity) return -ENOSPC; (fArrays[index])[fCount[index]++]=value; return fCount[index]; } int AliHLTGlobalHistoComponent::AliHLTGlobalHistoVariables::Fill(const char* key, float value) { /// fill variable at key int index=FindKey(key); if (index<0) return -ENOENT; return Fill(index, value); } float* AliHLTGlobalHistoComponent::AliHLTGlobalHistoVariables::GetArray(const char* key) { /// get array at key int index=FindKey(key); if (index<0) return NULL; assert((unsigned)index<fArrays.size()); if ((unsigned)index>=fArrays.size()) return NULL; return fArrays[index]; } int AliHLTGlobalHistoComponent::AliHLTGlobalHistoVariables::FindKey(const char* key) const { /// fill variable at key map<string, int>::const_iterator element=fKeys.find(key); if (element==fKeys.end()) return -ENOENT; return element->second; } const char* AliHLTGlobalHistoComponent::AliHLTGlobalHistoVariables::GetKey(int index) const { /// fill variable at key for (map<string, int>::const_iterator element=fKeys.begin(); element!=fKeys.end(); element++) { if (element->second==index) return element->first.c_str(); } return NULL; } <commit_msg>- bug fix<commit_after>// $Id$ //************************************************************************** //* This file is property of and copyright by the ALICE HLT Project * //* ALICE Experiment at CERN, All rights reserved. * //* * //* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no> * //* for The ALICE HLT Project. * //* * //* Permission to use, copy, modify and distribute this software and its * //* documentation strictly for non-commercial purposes is hereby granted * //* without fee, provided that the above copyright notice appears in all * //* copies and that both the copyright notice and this permission notice * //* appear in the supporting documentation. The authors make no claims * //* about the suitability of this software for any purpose. It is * //* provided "as is" without express or implied warranty. * //************************************************************************** /// @file AliHLTGlobalHistoComponent.cxx /// @author Matthias Richter /// @date 2010-09-16 /// @brief A histogramming component for global ESD properties based /// on the AliHLTTTreeProcessor #include "AliHLTGlobalHistoComponent.h" #include "AliESDEvent.h" #include "TTree.h" #include "TString.h" #include "TObjString.h" #include "TObjArray.h" #include <cassert> /** ROOT macro for the implementation of ROOT specific class methods */ ClassImp(AliHLTGlobalHistoComponent) AliHLTGlobalHistoComponent::AliHLTGlobalHistoComponent() : AliHLTTTreeProcessor() , fEvent(0) , fNofTracks(0) , fVertexX(-99) , fVertexY(-99) , fVertexZ(-99) , fTrackVariables() { // see header file for class documentation // or // refer to README to build package // or // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt } AliHLTGlobalHistoComponent::~AliHLTGlobalHistoComponent() { // see header file for class documentation fTrackVariables.Reset(); } void AliHLTGlobalHistoComponent::GetInputDataTypes(AliHLTComponentDataTypeList& list) { // see header file for class documentation list.push_back(kAliHLTAllDataTypes); } TTree* AliHLTGlobalHistoComponent::CreateTree(int /*argc*/, const char** /*argv*/) { // create the tree and branches int iResult=0; TTree* pTree=new TTree("ESDproperties", "HLT ESD properties"); if (!pTree) return NULL; const char* trackVariableNames = { "Track_pt " "Track_phi " "Track_eta " "Track_p " "Track_theta " "Track_Nclusters " "Track_status " "Track_charge " "Track_DCAr " "Track_DCAz " "Track_dEdx " }; int maxTrackCount=20000; // FIXME: make configurable if ((iResult=fTrackVariables.Init(maxTrackCount, trackVariableNames))<0) { HLTError("failed to initialize internal structure for track properties"); } if (iResult>=0) { pTree->Branch("event", &fEvent, "event/I"); pTree->Branch("trackcount", &fNofTracks, "trackcount/I"); pTree->Branch("vertexX", &fVertexX, "vertexX/F"); pTree->Branch("vertexY", &fVertexY, "vertexY/F"); pTree->Branch("vertexZ", &fVertexZ, "vertexZ/F"); for (int i=0; i<fTrackVariables.Variables(); i++) { TString specifier=fTrackVariables.GetKey(i); float* pArray=fTrackVariables.GetArray(specifier); specifier+="[trackcount]/f"; pTree->Branch(fTrackVariables.GetKey(i), pArray, specifier.Data()); } } else { delete pTree; pTree=NULL; } return pTree; } void AliHLTGlobalHistoComponent::FillHistogramDefinitions() { /// default histogram definitions } int AliHLTGlobalHistoComponent::FillTree(TTree* pTree, const AliHLTComponentEventData& /*evtData*/, AliHLTComponentTriggerData& /*trigData*/ ) { /// fill the tree from the ESD int iResult=0; if (!IsDataEvent()) return 0; ResetVariables(); // fetch ESD from input stream const TObject* obj = GetFirstInputObject(kAliHLTAllDataTypes, "AliESDEvent"); AliESDEvent* esd = dynamic_cast<AliESDEvent*>(const_cast<TObject*>(obj)); esd->GetStdContent(); // fill track variables fNofTracks=esd->GetNumberOfTracks(); fVertexX = esd->GetPrimaryVertexTracks()->GetX(); fVertexY = esd->GetPrimaryVertexTracks()->GetY(); fVertexZ = esd->GetPrimaryVertexTracks()->GetZ(); for (int i=0; i<fNofTracks; i++) { AliESDtrack *esdTrack = esd->GetTrack(i); if (!esdTrack) continue; Float_t DCAr, DCAz = -99; esdTrack->GetImpactParametersTPC(DCAr, DCAz); fTrackVariables.Fill("Track_pt" , esdTrack->Pt() ); fTrackVariables.Fill("Track_phi" , esdTrack->Phi()*TMath::RadToDeg() ); fTrackVariables.Fill("Track_eta" , esdTrack->Theta() ); fTrackVariables.Fill("Track_p" , esdTrack->P() ); fTrackVariables.Fill("Track_theta" , esdTrack->Theta()*TMath::RadToDeg() ); fTrackVariables.Fill("Track_Nclusters" , esdTrack->GetTPCNcls() ); fTrackVariables.Fill("Track_status" , esdTrack->GetStatus() ); fTrackVariables.Fill("Track_charge" , esdTrack->Charge() ); fTrackVariables.Fill("Track_DCAr" , DCAr ); fTrackVariables.Fill("Track_DCAz" , DCAz ); fTrackVariables.Fill("Track_dEdx" , esdTrack->GetTPCsignal() ); } HLTInfo("added parameters for %d tracks", fNofTracks); if (iResult<0) { // fill an empty event ResetVariables(); } fEvent++; pTree->Fill(); return iResult; } int AliHLTGlobalHistoComponent::ResetVariables() { /// reset all filling variables fNofTracks=0; fTrackVariables.ResetCount(); return 0; } AliHLTComponentDataType AliHLTGlobalHistoComponent::GetOriginDataType() const { // get the origin of the output data return kAliHLTVoidDataType; } // AliHLTUInt32_t AliHLTGlobalHistoComponent::GetDataSpec() const; // { // // get specifications of the output data // return 0; // } AliHLTGlobalHistoComponent::AliHLTGlobalHistoVariables::AliHLTGlobalHistoVariables() : fCapacity(0) , fArrays() , fCount() , fKeys() { /// default constructor } AliHLTGlobalHistoComponent::AliHLTGlobalHistoVariables::~AliHLTGlobalHistoVariables() { /// destructor Reset(); } int AliHLTGlobalHistoComponent::AliHLTGlobalHistoVariables::Init(int capacity, const char* names) { /// init the arrays int iResult=0; TString initializer(names); TObjArray* pTokens=initializer.Tokenize(" "); fCapacity=capacity; if (pTokens) { int entries=pTokens->GetEntriesFast(); fArrays.resize(entries); fCount.resize(entries); for (int i=0; i<entries; i++) { fKeys[pTokens->At(i)->GetName()]=i; fArrays[i]=new float[fCapacity]; } delete pTokens; } assert(fArrays.size()==fCount.size()); assert(fArrays.size()==fKeys.size()); if (fArrays.size()!=fCount.size() || fArrays.size()!=fKeys.size()) { return -EFAULT; } ResetCount(); return iResult; } int AliHLTGlobalHistoComponent::AliHLTGlobalHistoVariables::Reset() { /// reset the arrays for (vector<float*>::iterator element=fArrays.begin(); element!=fArrays.end(); element++) { delete *element; } fArrays.clear(); fCount.clear(); fKeys.clear(); return 0; } int AliHLTGlobalHistoComponent::AliHLTGlobalHistoVariables::ResetCount() { /// reset the fill counts for (vector<int>::iterator element=fCount.begin(); element!=fCount.end(); element++) { *element=0; } return 0; } int AliHLTGlobalHistoComponent::AliHLTGlobalHistoVariables::Fill(unsigned index, float value) { /// fill variable at index assert(fArrays.size()==fCount.size()); if (index>=fArrays.size() || index>=fCount.size()) return -ENOENT; if (fCount[index]>=fCapacity) return -ENOSPC; (fArrays[index])[fCount[index]++]=value; return fCount[index]; } int AliHLTGlobalHistoComponent::AliHLTGlobalHistoVariables::Fill(const char* key, float value) { /// fill variable at key int index=FindKey(key); if (index<0) return -ENOENT; return Fill(index, value); } float* AliHLTGlobalHistoComponent::AliHLTGlobalHistoVariables::GetArray(const char* key) { /// get array at key int index=FindKey(key); if (index<0) return NULL; assert((unsigned)index<fArrays.size()); if ((unsigned)index>=fArrays.size()) return NULL; return fArrays[index]; } int AliHLTGlobalHistoComponent::AliHLTGlobalHistoVariables::FindKey(const char* key) const { /// fill variable at key map<string, int>::const_iterator element=fKeys.find(key); if (element==fKeys.end()) return -ENOENT; return element->second; } const char* AliHLTGlobalHistoComponent::AliHLTGlobalHistoVariables::GetKey(int index) const { /// fill variable at key for (map<string, int>::const_iterator element=fKeys.begin(); element!=fKeys.end(); element++) { if (element->second==index) return element->first.c_str(); } return NULL; } <|endoftext|>
<commit_before>#include "base_impl.h" #include "converter.h" #include "serial.h" namespace contourpy { SerialContourGenerator::SerialContourGenerator( const CoordinateArray& x, const CoordinateArray& y, const CoordinateArray& z, const MaskArray& mask, bool corner_mask, LineType line_type, FillType fill_type, bool quad_as_tri, ZInterp z_interp, index_t x_chunk_size, index_t y_chunk_size) : BaseContourGenerator(x, y, z, mask, corner_mask, line_type, fill_type, quad_as_tri, z_interp, x_chunk_size, y_chunk_size) {} void SerialContourGenerator::export_filled( const ChunkLocal& local, std::vector<py::list>& return_lists) { assert(local.total_point_count > 0); switch (get_fill_type()) { case FillType::OuterCode: case FillType::OuterOffset: { assert(!has_direct_points() && !has_direct_line_offsets()); auto outer_count = local.line_count - local.hole_count; for (decltype(outer_count) i = 0; i < outer_count; ++i) { auto outer_start = local.outer_offsets.start[i]; auto outer_end = local.outer_offsets.start[i+1]; auto point_start = local.line_offsets.start[outer_start]; auto point_end = local.line_offsets.start[outer_end]; auto point_count = point_end - point_start; assert(point_count > 2); return_lists[0].append(Converter::convert_points( point_count, local.points.start + 2*point_start)); if (get_fill_type() == FillType::OuterCode) return_lists[1].append(Converter::convert_codes( point_count, outer_end - outer_start + 1, local.line_offsets.start + outer_start, point_start)); else return_lists[1].append(Converter::convert_offsets( outer_end - outer_start + 1, local.line_offsets.start + outer_start, point_start)); } break; } case FillType::ChunkCombinedCode: case FillType::ChunkCombinedCodeOffset: { assert(has_direct_points() && !has_direct_line_offsets()); // return_lists[0][local_chunk] already contains combined points. // If ChunkCombinedCodeOffset. return_lists[2][local.chunk] already contains outer // offsets. return_lists[1][local.chunk] = Converter::convert_codes( local.total_point_count, local.line_count + 1, local.line_offsets.start, 0); break; } case FillType::ChunkCombinedOffset: case FillType::ChunkCombinedOffsetOffset: assert(has_direct_points() && has_direct_line_offsets()); if (get_fill_type() == FillType::ChunkCombinedOffsetOffset) { assert(has_direct_outer_offsets()); } // return_lists[0][local_chunk] already contains combined points. // return_lists[1][local.chunk] already contains line offsets. // If ChunkCombinedOffsetOffset, return_lists[2][local.chunk] already contains // outer offsets. break; } } void SerialContourGenerator::export_lines( const ChunkLocal& local, std::vector<py::list>& return_lists) { assert(local.total_point_count > 0); switch (get_line_type()) { case LineType::Separate: case LineType::SeparateCode: { assert(!has_direct_points() && !has_direct_line_offsets()); bool separate_code = (get_line_type() == LineType::SeparateCode); for (decltype(local.line_count) i = 0; i < local.line_count; ++i) { auto point_start = local.line_offsets.start[i]; auto point_end = local.line_offsets.start[i+1]; auto point_count = point_end - point_start; assert(point_count > 1); return_lists[0].append(Converter::convert_points( point_count, local.points.start + 2*point_start)); if (separate_code) { return_lists[1].append( Converter::convert_codes_check_closed_single( point_count, local.points.start + 2*point_start)); } } break; } case LineType::ChunkCombinedCode: { assert(has_direct_points() && !has_direct_line_offsets()); // return_lists[0][local.chunk] already contains points. return_lists[1][local.chunk] = Converter::convert_codes_check_closed( local.total_point_count, local.line_count + 1, local.line_offsets.start, local.points.start); break; } case LineType::ChunkCombinedOffset: assert(has_direct_points() && has_direct_line_offsets()); // return_lists[0][local.chunk] already contains points. // return_lists[1][local.chunk] already contains line offsets. break; } } void SerialContourGenerator::march(std::vector<py::list>& return_lists) { // Stage 1: Initialise cache z-levels and starting locations for whole domain. init_cache_levels_and_starts(); // Stage 2: Trace contours. auto n_chunks = get_n_chunks(); ChunkLocal local; for (index_t chunk = 0; chunk < n_chunks; ++chunk) { get_chunk_limits(chunk, local); march_chunk(local, return_lists); local.clear(); } } } // namespace contourpy <commit_msg>Init cache by chunk if more than 1 chunk (#155)<commit_after>#include "base_impl.h" #include "converter.h" #include "serial.h" namespace contourpy { SerialContourGenerator::SerialContourGenerator( const CoordinateArray& x, const CoordinateArray& y, const CoordinateArray& z, const MaskArray& mask, bool corner_mask, LineType line_type, FillType fill_type, bool quad_as_tri, ZInterp z_interp, index_t x_chunk_size, index_t y_chunk_size) : BaseContourGenerator(x, y, z, mask, corner_mask, line_type, fill_type, quad_as_tri, z_interp, x_chunk_size, y_chunk_size) {} void SerialContourGenerator::export_filled( const ChunkLocal& local, std::vector<py::list>& return_lists) { assert(local.total_point_count > 0); switch (get_fill_type()) { case FillType::OuterCode: case FillType::OuterOffset: { assert(!has_direct_points() && !has_direct_line_offsets()); auto outer_count = local.line_count - local.hole_count; for (decltype(outer_count) i = 0; i < outer_count; ++i) { auto outer_start = local.outer_offsets.start[i]; auto outer_end = local.outer_offsets.start[i+1]; auto point_start = local.line_offsets.start[outer_start]; auto point_end = local.line_offsets.start[outer_end]; auto point_count = point_end - point_start; assert(point_count > 2); return_lists[0].append(Converter::convert_points( point_count, local.points.start + 2*point_start)); if (get_fill_type() == FillType::OuterCode) return_lists[1].append(Converter::convert_codes( point_count, outer_end - outer_start + 1, local.line_offsets.start + outer_start, point_start)); else return_lists[1].append(Converter::convert_offsets( outer_end - outer_start + 1, local.line_offsets.start + outer_start, point_start)); } break; } case FillType::ChunkCombinedCode: case FillType::ChunkCombinedCodeOffset: { assert(has_direct_points() && !has_direct_line_offsets()); // return_lists[0][local_chunk] already contains combined points. // If ChunkCombinedCodeOffset. return_lists[2][local.chunk] already contains outer // offsets. return_lists[1][local.chunk] = Converter::convert_codes( local.total_point_count, local.line_count + 1, local.line_offsets.start, 0); break; } case FillType::ChunkCombinedOffset: case FillType::ChunkCombinedOffsetOffset: assert(has_direct_points() && has_direct_line_offsets()); if (get_fill_type() == FillType::ChunkCombinedOffsetOffset) { assert(has_direct_outer_offsets()); } // return_lists[0][local_chunk] already contains combined points. // return_lists[1][local.chunk] already contains line offsets. // If ChunkCombinedOffsetOffset, return_lists[2][local.chunk] already contains // outer offsets. break; } } void SerialContourGenerator::export_lines( const ChunkLocal& local, std::vector<py::list>& return_lists) { assert(local.total_point_count > 0); switch (get_line_type()) { case LineType::Separate: case LineType::SeparateCode: { assert(!has_direct_points() && !has_direct_line_offsets()); bool separate_code = (get_line_type() == LineType::SeparateCode); for (decltype(local.line_count) i = 0; i < local.line_count; ++i) { auto point_start = local.line_offsets.start[i]; auto point_end = local.line_offsets.start[i+1]; auto point_count = point_end - point_start; assert(point_count > 1); return_lists[0].append(Converter::convert_points( point_count, local.points.start + 2*point_start)); if (separate_code) { return_lists[1].append( Converter::convert_codes_check_closed_single( point_count, local.points.start + 2*point_start)); } } break; } case LineType::ChunkCombinedCode: { assert(has_direct_points() && !has_direct_line_offsets()); // return_lists[0][local.chunk] already contains points. return_lists[1][local.chunk] = Converter::convert_codes_check_closed( local.total_point_count, local.line_count + 1, local.line_offsets.start, local.points.start); break; } case LineType::ChunkCombinedOffset: assert(has_direct_points() && has_direct_line_offsets()); // return_lists[0][local.chunk] already contains points. // return_lists[1][local.chunk] already contains line offsets. break; } } void SerialContourGenerator::march(std::vector<py::list>& return_lists) { auto n_chunks = get_n_chunks(); bool single_chunk = (n_chunks == 1); if (single_chunk) { // Stage 1: If single chunk, initialise cache z-levels and starting locations for whole // domain. init_cache_levels_and_starts(); } // Stage 2: Trace contours. ChunkLocal local; for (index_t chunk = 0; chunk < n_chunks; ++chunk) { get_chunk_limits(chunk, local); if (!single_chunk) init_cache_levels_and_starts(&local); march_chunk(local, return_lists); local.clear(); } } } // namespace contourpy <|endoftext|>
<commit_before>// This file is part of xsonrpc, an XML/JSON RPC library. // Copyright (C) 2015 Erik Johansson <erik@ejohansson.se // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by the // Free Software Foundation; either version 2.1 of the License, or (at your // option) any later version. // // This library is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License // for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this library; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "server.h" #include <microhttpd.h> #include <tinyxml2.h> #include <vector> namespace { const char TEXT_XML[] = "text/xml"; const size_t MAX_REQUEST_SIZE = 16 * 1024; struct HttpError { unsigned int StatusCode; }; struct ConnectionInfo { std::vector<char> Buffer; tinyxml2::XMLPrinter Printer; }; } // namespace namespace xsonrpc { Server::Server(unsigned short port, std::string uri) : myUri(std::move(uri)) { myDaemon = MHD_start_daemon( MHD_USE_EPOLL_LINUX_ONLY, port, NULL, NULL, &Server::AccessHandlerCallback, this, MHD_OPTION_NOTIFY_COMPLETED, &Server::RequestCompletedCallback, this, MHD_OPTION_END); if (!myDaemon) { throw std::runtime_error("server: could not start HTTP daemon"); } } Server::~Server() { MHD_stop_daemon(myDaemon); } void Server::Run() { if (MHD_run(myDaemon) != MHD_YES) { throw std::runtime_error("server: could not run HTTP daemon"); } } int Server::GetFileDescriptor() { auto info = MHD_get_daemon_info( myDaemon, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY); if (!info || info->listen_fd == -1) { throw std::runtime_error("server: could not get file descriptor"); } return info->listen_fd; } void Server::OnReadableFileDescriptor() { if (MHD_run(myDaemon) != MHD_YES) { throw std::runtime_error("server: invalid call to run daemon"); } } void Server::HandleRequest(MHD_Connection* connection, void* connectionCls) { auto info = static_cast<ConnectionInfo*>(connectionCls); try { tinyxml2::XMLDocument document; auto error = document.Parse(info->Buffer.data(), info->Buffer.size()); if (error == tinyxml2::XML_CAN_NOT_CONVERT_TEXT) { throw InvalidCharacterFault(); } else if (error != tinyxml2::XML_NO_ERROR) { throw NotWellFormedFault(); } info->Buffer.clear(); Request request{document.RootElement()}; document.Clear(); auto response = myDispatcher.Invoke( request.GetMethodName(), request.GetParameters()); response.Print(info->Printer); } catch (const Fault& ex) { Response(ex).Print(info->Printer); } auto response = MHD_create_response_from_buffer( info->Printer.CStrSize() - 1, const_cast<char*>(info->Printer.CStr()), MHD_RESPMEM_PERSISTENT); MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, TEXT_XML); MHD_add_response_header(response, MHD_HTTP_HEADER_SERVER, "xsonrpc/" XSONRPC_VERSION); MHD_queue_response(connection, MHD_HTTP_OK, response); MHD_destroy_response(response); } int Server::AccessHandlerCallback( void* cls, MHD_Connection* connection, const char* url, const char* method, const char* version, const char* uploadData, size_t* uploadDataSize, void** connectionCls) { return static_cast<Server*>(cls)->AccessHandler( connection, url, method, version, uploadData, uploadDataSize, connectionCls); } int Server::AccessHandler( MHD_Connection* connection, const char* url, const char* method, const char* /*version*/, const char* uploadData, size_t* uploadDataSize, void** connectionCls) { try { if (*connectionCls != NULL) { if (*uploadDataSize == 0) { HandleRequest(connection, *connectionCls); return MHD_YES; } ConnectionInfo* info = static_cast<ConnectionInfo*>(*connectionCls); if (info->Buffer.size() + *uploadDataSize > MAX_REQUEST_SIZE) { *uploadDataSize = 0; throw HttpError{MHD_HTTP_BAD_REQUEST}; } info->Buffer.insert(info->Buffer.end(), uploadData, uploadData + *uploadDataSize); *uploadDataSize = 0; return MHD_YES; } if (strcmp(method, "POST") != 0) { throw HttpError{MHD_HTTP_METHOD_NOT_ALLOWED}; } if (url != myUri) { throw HttpError{MHD_HTTP_NOT_FOUND}; } *connectionCls = new ConnectionInfo; return MHD_YES; } catch (const HttpError& httpError) { auto response = MHD_create_response_from_data(0, nullptr, false, false); MHD_queue_response(connection, httpError.StatusCode, response); MHD_destroy_response(response); return MHD_YES; } catch (...) { auto response = MHD_create_response_from_data(0, nullptr, false, false); MHD_queue_response(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, response); MHD_destroy_response(response); return MHD_YES; } } void Server::RequestCompletedCallback( void* cls, MHD_Connection* connection, void** connectionCls, int requestTerminationCode) { static_cast<Server*>(cls)->OnRequestCompleted( connection, connectionCls, requestTerminationCode); } void Server::OnRequestCompleted( MHD_Connection* /*connection*/, void** connectionCls, int /*requestTerminationCode*/) { delete static_cast<ConnectionInfo*>(*connectionCls); } } // namespace xsonrpc <commit_msg>server: support older microhttpd versions<commit_after>// This file is part of xsonrpc, an XML/JSON RPC library. // Copyright (C) 2015 Erik Johansson <erik@ejohansson.se // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by the // Free Software Foundation; either version 2.1 of the License, or (at your // option) any later version. // // This library is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License // for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this library; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "server.h" #include <microhttpd.h> #include <sys/socket.h> #include <tinyxml2.h> #include <vector> namespace { const char TEXT_XML[] = "text/xml"; const size_t MAX_REQUEST_SIZE = 16 * 1024; struct HttpError { unsigned int StatusCode; }; struct ConnectionInfo { std::vector<char> Buffer; tinyxml2::XMLPrinter Printer; }; } // namespace namespace xsonrpc { Server::Server(unsigned short port, std::string uri) : myUri(std::move(uri)) { myDaemon = MHD_start_daemon( #if MHD_VERSION >= 0x00093100 MHD_USE_EPOLL_LINUX_ONLY, #else MHD_NO_FLAG, #endif port, NULL, NULL, &Server::AccessHandlerCallback, this, MHD_OPTION_NOTIFY_COMPLETED, &Server::RequestCompletedCallback, this, MHD_OPTION_END); if (!myDaemon) { throw std::runtime_error("server: could not start HTTP daemon"); } } Server::~Server() { MHD_stop_daemon(myDaemon); } void Server::Run() { if (MHD_run(myDaemon) != MHD_YES) { throw std::runtime_error("server: could not run HTTP daemon"); } } int Server::GetFileDescriptor() { #if MHD_VERSION >= 0x00093100 auto info = MHD_get_daemon_info( myDaemon, MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY); if (!info || info->listen_fd == -1) { throw std::runtime_error("server: could not get file descriptor"); } return info->listen_fd; #else throw std::runtime_error("server: could not get file descriptor"); #endif } void Server::OnReadableFileDescriptor() { if (MHD_run(myDaemon) != MHD_YES) { throw std::runtime_error("server: invalid call to run daemon"); } } void Server::HandleRequest(MHD_Connection* connection, void* connectionCls) { auto info = static_cast<ConnectionInfo*>(connectionCls); try { tinyxml2::XMLDocument document; auto error = document.Parse(info->Buffer.data(), info->Buffer.size()); if (error == tinyxml2::XML_CAN_NOT_CONVERT_TEXT) { throw InvalidCharacterFault(); } else if (error != tinyxml2::XML_NO_ERROR) { throw NotWellFormedFault(); } info->Buffer.clear(); Request request{document.RootElement()}; document.Clear(); auto response = myDispatcher.Invoke( request.GetMethodName(), request.GetParameters()); response.Print(info->Printer); } catch (const Fault& ex) { Response(ex).Print(info->Printer); } #if MHD_VERSION >= 0x00090500 auto response = MHD_create_response_from_buffer( info->Printer.CStrSize() - 1, const_cast<char*>(info->Printer.CStr()), MHD_RESPMEM_PERSISTENT); #else auto response = MHD_create_response_from_data( info->Printer.CStrSize() - 1, const_cast<char*>(info->Printer.CStr()), false, false); #endif MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, TEXT_XML); MHD_add_response_header(response, MHD_HTTP_HEADER_SERVER, "xsonrpc/" XSONRPC_VERSION); MHD_queue_response(connection, MHD_HTTP_OK, response); MHD_destroy_response(response); } int Server::AccessHandlerCallback( void* cls, MHD_Connection* connection, const char* url, const char* method, const char* version, const char* uploadData, size_t* uploadDataSize, void** connectionCls) { return static_cast<Server*>(cls)->AccessHandler( connection, url, method, version, uploadData, uploadDataSize, connectionCls); } int Server::AccessHandler( MHD_Connection* connection, const char* url, const char* method, const char* /*version*/, const char* uploadData, size_t* uploadDataSize, void** connectionCls) { try { if (*connectionCls != NULL) { if (*uploadDataSize == 0) { HandleRequest(connection, *connectionCls); return MHD_YES; } ConnectionInfo* info = static_cast<ConnectionInfo*>(*connectionCls); if (info->Buffer.size() + *uploadDataSize > MAX_REQUEST_SIZE) { *uploadDataSize = 0; throw HttpError{MHD_HTTP_BAD_REQUEST}; } info->Buffer.insert(info->Buffer.end(), uploadData, uploadData + *uploadDataSize); *uploadDataSize = 0; return MHD_YES; } if (strcmp(method, "POST") != 0) { throw HttpError{MHD_HTTP_METHOD_NOT_ALLOWED}; } if (url != myUri) { throw HttpError{MHD_HTTP_NOT_FOUND}; } *connectionCls = new ConnectionInfo; return MHD_YES; } catch (const HttpError& httpError) { auto response = MHD_create_response_from_data(0, nullptr, false, false); MHD_queue_response(connection, httpError.StatusCode, response); MHD_destroy_response(response); return MHD_YES; } catch (...) { auto response = MHD_create_response_from_data(0, nullptr, false, false); MHD_queue_response(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, response); MHD_destroy_response(response); return MHD_YES; } } void Server::RequestCompletedCallback( void* cls, MHD_Connection* connection, void** connectionCls, int requestTerminationCode) { static_cast<Server*>(cls)->OnRequestCompleted( connection, connectionCls, requestTerminationCode); } void Server::OnRequestCompleted( MHD_Connection* /*connection*/, void** connectionCls, int /*requestTerminationCode*/) { delete static_cast<ConnectionInfo*>(*connectionCls); } } // namespace xsonrpc <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Build Suite. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "preferences.h" #include "buildoptions.h" #include "hostosinfo.h" #include "profile.h" #include "settings.h" namespace qbs { /*! * \class Preferences * \brief The \c Preferences class gives access to all general qbs preferences. * If a non-empty \c profileName is given, the profile's preferences take precedence over global * ones. Otherwise, the global preferences are used. */ Preferences::Preferences(Settings *settings, const QString &profileName) : m_settings(settings), m_profile(profileName) { } /*! * \brief Returns true <=> colored output should be used for printing messages. * This is only relevant for command-line frontends. */ bool Preferences::useColoredOutput() const { return getPreference(QLatin1String("useColoredOutput"), true).toBool(); } /*! * \brief Returns the number of parallel jobs to use for building. * Uses a sensible default value if there is no such setting. */ int Preferences::jobs() const { return getPreference(QLatin1String("jobs"), BuildOptions::defaultMaxJobCount()).toInt(); } /*! * \brief Returns the shell to use for the "qbs shell" command. * This is only relevant for command-line frontends. */ QString Preferences::shell() const { return getPreference(QLatin1String("shell")).toString(); } /*! * \brief Returns the default build directory used by Qbs if none is specified. */ QString Preferences::defaultBuildDirectory() const { return getPreference(QLatin1String("defaultBuildDirectory")).toString(); } /*! * \brief Returns the list of paths where qbs looks for module definitions and such. * If there is no such setting, they will be looked up at \c{baseDir}/share/qbs. */ QStringList Preferences::searchPaths(const QString &baseDir) const { const QStringList searchPaths = pathList(QLatin1String("qbsSearchPaths"), baseDir + QLatin1String("/share/qbs")); // TODO: Remove in 1.2. const QStringList deprecatedSearchPaths = getPreference(QLatin1String("qbsPath")).toString() .split(Internal::HostOsInfo::pathListSeparator(), QString::SkipEmptyParts); if (!deprecatedSearchPaths.isEmpty()) { qDebug("Warning: preferences.qbsPath is deprecated, " "use preferences.qbsSearchPaths instead."); } return deprecatedSearchPaths + searchPaths; } /*! * \brief Returns the list of paths where qbs looks for plugins. * If there is no such setting, they will be looked up at \c{baseDir}/qbs/plugins. */ QStringList Preferences::pluginPaths(const QString &baseDir) const { return pathList(QLatin1String("pluginsPath"), baseDir + QLatin1String("/qbs/plugins")); } QVariant Preferences::getPreference(const QString &key, const QVariant &defaultValue) const { const QString fullKey = QLatin1String("preferences.") + key; if (!m_profile.isEmpty()) { const QVariant value = Profile(m_profile, m_settings).value(fullKey); if (value.isValid()) return value; } return m_settings->value(fullKey, defaultValue); } QStringList Preferences::pathList(const QString &key, const QString &defaultValue) const { QStringList paths = getPreference(key).toString().split( Internal::HostOsInfo::pathListSeparator(), QString::SkipEmptyParts); paths << defaultValue; return paths; } } // namespace qbs <commit_msg>remove deprecated qbsPath preferences key<commit_after>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Build Suite. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "preferences.h" #include "buildoptions.h" #include "hostosinfo.h" #include "profile.h" #include "settings.h" namespace qbs { /*! * \class Preferences * \brief The \c Preferences class gives access to all general qbs preferences. * If a non-empty \c profileName is given, the profile's preferences take precedence over global * ones. Otherwise, the global preferences are used. */ Preferences::Preferences(Settings *settings, const QString &profileName) : m_settings(settings), m_profile(profileName) { } /*! * \brief Returns true <=> colored output should be used for printing messages. * This is only relevant for command-line frontends. */ bool Preferences::useColoredOutput() const { return getPreference(QLatin1String("useColoredOutput"), true).toBool(); } /*! * \brief Returns the number of parallel jobs to use for building. * Uses a sensible default value if there is no such setting. */ int Preferences::jobs() const { return getPreference(QLatin1String("jobs"), BuildOptions::defaultMaxJobCount()).toInt(); } /*! * \brief Returns the shell to use for the "qbs shell" command. * This is only relevant for command-line frontends. */ QString Preferences::shell() const { return getPreference(QLatin1String("shell")).toString(); } /*! * \brief Returns the default build directory used by Qbs if none is specified. */ QString Preferences::defaultBuildDirectory() const { return getPreference(QLatin1String("defaultBuildDirectory")).toString(); } /*! * \brief Returns the list of paths where qbs looks for module definitions and such. * If there is no such setting, they will be looked up at \c{baseDir}/share/qbs. */ QStringList Preferences::searchPaths(const QString &baseDir) const { return pathList(QLatin1String("qbsSearchPaths"), baseDir + QLatin1String("/share/qbs")); } /*! * \brief Returns the list of paths where qbs looks for plugins. * If there is no such setting, they will be looked up at \c{baseDir}/qbs/plugins. */ QStringList Preferences::pluginPaths(const QString &baseDir) const { return pathList(QLatin1String("pluginsPath"), baseDir + QLatin1String("/qbs/plugins")); } QVariant Preferences::getPreference(const QString &key, const QVariant &defaultValue) const { const QString fullKey = QLatin1String("preferences.") + key; if (!m_profile.isEmpty()) { const QVariant value = Profile(m_profile, m_settings).value(fullKey); if (value.isValid()) return value; } return m_settings->value(fullKey, defaultValue); } QStringList Preferences::pathList(const QString &key, const QString &defaultValue) const { QStringList paths = getPreference(key).toString().split( Internal::HostOsInfo::pathListSeparator(), QString::SkipEmptyParts); paths << defaultValue; return paths; } } // namespace qbs <|endoftext|>
<commit_before>// Copyright 20Tab S.r.l. #include "PyCommandlet.h" #include "UEPyModule.h" #include "Regex.h" UPyCommandlet::UPyCommandlet(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { LogToConsole = 1; } int32 UPyCommandlet::Main(const FString& CommandLine) { FScopePythonGIL gil; TArray<FString> Tokens, Switches; TMap<FString, FString> Params; ParseCommandLine(*CommandLine, Tokens, Switches, Params); FString Filepath = Tokens[0]; if (!FPaths::FileExists(*Filepath)) { UE_LOG(LogPython, Error, TEXT("Python file could not be found: %s"), *Filepath); return -1; } FString RegexString = FString::Printf(TEXT("(?<=%s).*"), *(Filepath.Replace(TEXT("\\"), TEXT("\\\\")))); const FRegexPattern myPattern(RegexString); FRegexMatcher myMatcher(myPattern, *CommandLine); myMatcher.FindNext(); #if ENGINE_MINOR_VERSION >= 18 FString PyCommandLine = myMatcher.GetCaptureGroup(0).TrimStart().TrimEnd(); #else FString PyCommandLine = myMatcher.GetCaptureGroup(0).Trim().TrimTrailing(); #endif TArray<FString> PyArgv; PyArgv.Add(FString()); bool escaped = false; for (int i = 0; i < PyCommandLine.Len(); i++) { if (PyCommandLine[i] == ' ') { PyArgv.Add(FString()); continue; } else if (PyCommandLine[i] == '\"' && !escaped) { i++; while (i < PyCommandLine.Len() && !(PyCommandLine[i] == '"')) { PyArgv[PyArgv.Num() - 1].AppendChar(PyCommandLine[i]); i++; if (i == PyCommandLine.Len()) { PyArgv[PyArgv.Num() - 1].InsertAt(0, "\""); } } } else { if (PyCommandLine[i] == '\\') escaped = true; else escaped = false; PyArgv[PyArgv.Num() - 1].AppendChar(PyCommandLine[i]); } } PyArgv.Insert(Filepath, 0); #if PY_MAJOR_VERSION >= 3 wchar_t **argv = (wchar_t **)malloc(PyArgv.Num() * sizeof(void*)); #else char **argv = (char **)malloc(PyArgv.Num() * sizeof(void*)); #endif for (int i = 0; i < PyArgv.Num(); i++) { #if PY_MAJOR_VERSION >= 3 argv[i] = (wchar_t*)malloc(PyArgv[i].Len() + 1); #if defined(UNREAL_ENGINE_PYTHON_ON_MAC) || defined(UNREAL_ENGINE_PYTHON_ON_LINUX) wcsncpy(argv[i], *PyArgv[i].ReplaceEscapedCharWithChar(), PyArgv[i].Len() + 1); #else wcscpy_s(argv[i], PyArgv[i].Len() + 1, *PyArgv[i].ReplaceEscapedCharWithChar()); #endif #else argv[i] = (char*)malloc(PyArgv[i].Len() + 1); #if defined(UNREAL_ENGINE_PYTHON_ON_MAC) || defined(UNREAL_ENGINE_PYTHON_ON_LINUX) strncpy(argv[i], TCHAR_TO_UTF8(*PyArgv[i].ReplaceEscapedCharWithChar()), PyArgv[i].Len() + 1); #else strcpy_s(argv[i], PyArgv[i].Len() + 1, TCHAR_TO_UTF8(*PyArgv[i].ReplaceEscapedCharWithChar())); #endif #endif } PySys_SetArgv(PyArgv.Num(), argv); Py_BEGIN_ALLOW_THREADS; FUnrealEnginePythonModule &PythonModule = FModuleManager::GetModuleChecked<FUnrealEnginePythonModule>("UnrealEnginePython"); PythonModule.BrutalFinalize = true; PythonModule.RunFile(TCHAR_TO_UTF8(*Filepath)); Py_END_ALLOW_THREADS; return 0; } <commit_msg>fixed transactions in commandlets<commit_after>// Copyright 20Tab S.r.l. #include "PyCommandlet.h" #include "UEPyModule.h" #if WITH_EDITOR #include "Editor.h" #endif #include "Regex.h" UPyCommandlet::UPyCommandlet(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { LogToConsole = 1; } int32 UPyCommandlet::Main(const FString& CommandLine) { FScopePythonGIL gil; #if WITH_EDITOR // this allows commandlet's to use factories GEditor->Trans = GEditor->CreateTrans(); #endif TArray<FString> Tokens, Switches; TMap<FString, FString> Params; ParseCommandLine(*CommandLine, Tokens, Switches, Params); FString Filepath = Tokens[0]; if (!FPaths::FileExists(*Filepath)) { UE_LOG(LogPython, Error, TEXT("Python file could not be found: %s"), *Filepath); return -1; } FString RegexString = FString::Printf(TEXT("(?<=%s).*"), *(Filepath.Replace(TEXT("\\"), TEXT("\\\\")))); const FRegexPattern myPattern(RegexString); FRegexMatcher myMatcher(myPattern, *CommandLine); myMatcher.FindNext(); #if ENGINE_MINOR_VERSION >= 18 FString PyCommandLine = myMatcher.GetCaptureGroup(0).TrimStart().TrimEnd(); #else FString PyCommandLine = myMatcher.GetCaptureGroup(0).Trim().TrimTrailing(); #endif TArray<FString> PyArgv; PyArgv.Add(FString()); bool escaped = false; for (int i = 0; i < PyCommandLine.Len(); i++) { if (PyCommandLine[i] == ' ') { PyArgv.Add(FString()); continue; } else if (PyCommandLine[i] == '\"' && !escaped) { i++; while (i < PyCommandLine.Len() && !(PyCommandLine[i] == '"')) { PyArgv[PyArgv.Num() - 1].AppendChar(PyCommandLine[i]); i++; if (i == PyCommandLine.Len()) { PyArgv[PyArgv.Num() - 1].InsertAt(0, "\""); } } } else { if (PyCommandLine[i] == '\\') escaped = true; else escaped = false; PyArgv[PyArgv.Num() - 1].AppendChar(PyCommandLine[i]); } } PyArgv.Insert(Filepath, 0); #if PY_MAJOR_VERSION >= 3 wchar_t **argv = (wchar_t **)malloc(PyArgv.Num() * sizeof(void*)); #else char **argv = (char **)malloc(PyArgv.Num() * sizeof(void*)); #endif for (int i = 0; i < PyArgv.Num(); i++) { #if PY_MAJOR_VERSION >= 3 argv[i] = (wchar_t*)malloc(PyArgv[i].Len() + 1); #if defined(UNREAL_ENGINE_PYTHON_ON_MAC) || defined(UNREAL_ENGINE_PYTHON_ON_LINUX) wcsncpy(argv[i], *PyArgv[i].ReplaceEscapedCharWithChar(), PyArgv[i].Len() + 1); #else wcscpy_s(argv[i], PyArgv[i].Len() + 1, *PyArgv[i].ReplaceEscapedCharWithChar()); #endif #else argv[i] = (char*)malloc(PyArgv[i].Len() + 1); #if defined(UNREAL_ENGINE_PYTHON_ON_MAC) || defined(UNREAL_ENGINE_PYTHON_ON_LINUX) strncpy(argv[i], TCHAR_TO_UTF8(*PyArgv[i].ReplaceEscapedCharWithChar()), PyArgv[i].Len() + 1); #else strcpy_s(argv[i], PyArgv[i].Len() + 1, TCHAR_TO_UTF8(*PyArgv[i].ReplaceEscapedCharWithChar())); #endif #endif } PySys_SetArgv(PyArgv.Num(), argv); Py_BEGIN_ALLOW_THREADS; FUnrealEnginePythonModule &PythonModule = FModuleManager::GetModuleChecked<FUnrealEnginePythonModule>("UnrealEnginePython"); PythonModule.BrutalFinalize = true; PythonModule.RunFile(TCHAR_TO_UTF8(*Filepath)); Py_END_ALLOW_THREADS; return 0; } <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <sys/resource.h> #include <asm/errno.h> #include <sys/socket.h> #include <sys/time.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <malloc.h> #include <string.h> #include <utility> #include <map> #include <sys/types.h> #include <netdb.h> #include <string.h> #include <unistd.h> #include <assert.h> #include <linux/netfilter.h> #include <tins/tins.h> #include "HostMapping.h" #include "AITF_packet.h" #include "AITF_connect_state.h" #include "numbers.h" #define TLONG 30 using namespace Tins; using namespace std; extern HostMapping hosts; extern bool is_shadow; map<AITF_identity, AITF_connect_state> ostate_table; map<AITF_identity, AITF_connect_state> istate_table; vector<RRFilter> block_rules; typedef enum{ ENFORCE, REQUEST, VERIFY, CORRECT, BLOCK, CEASE } AITF_type; typedef struct thread_data{ IP::address_type addr; char buff[1500]; ssize_t size; } thread_data; uint64_t generateNonce(){ return generate_key(); } int block_verdict(RREntry r, IP::address_type addr){ struct timeval start_time; gettimeofday(&start_time, NULL); int verdict; int bypass = start_time.tv_sec; for (int i = 0; i < block_rules.size(); i++){ if (bypass > block_rules.at(i).ttl()){ continue; } verdict = block_rules.at(i).match(r, addr); if (verdict == 1){ return NF_ACCEPT; } if (verdict == 0){ return NF_DROP; } } return NF_ACCEPT; } void send_AITF_message(AITF_packet pack, IP::address_type addr){ cout << "SENDING PACKET: DEST: " << addr.to_string(); cout << pack.to_string(); uint8_t* data = (uint8_t*)malloc(pack.packet_size()); pack.serialize(data, pack.packet_size()); int status, sd, len, s, r; struct addrinfo hints; struct addrinfo *servinfo, *p; // will point to the results const char *url, *port; port = "11467"; url = addr.to_string().c_str(); memset(&hints, 0 , sizeof(hints)); // make sure the stuct is empty hints.ai_family = AF_INET; // only IPv4 hints.ai_socktype = SOCK_DGRAM; // Use a UDP connection // getaddrinfo() - fills out an address structure for us with the destination server's info if((status = getaddrinfo(url, port, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status)); return; } // loop through all results and connect to the first one we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("client: socket"); continue; } if((connect(sd, servinfo->ai_addr, servinfo->ai_addrlen)) < 0) { close(sd); perror("client: connect"); continue; } break; } if (p == NULL) { fprintf(stderr, "client: failed to connect\n"); return; } freeaddrinfo(servinfo); s = send(sd, data, pack.packet_size(), 0); close(sd); return; } uint64_t generateRandomValue(IP::address_type addr, int x){ return hash_for_destination(addr, x - 1); } void AITF_escalation(AITF_packet pack){ cout << endl << pack.to_string() << endl; uint64_t nonce1 = generateNonce(); ostate_table[pack.identity()].set_nonce1(nonce1); AITF_packet request = AITF_packet((uint8_t)REQUEST, nonce1, (uint64_t)0, ostate_table[pack.identity()].currentRoute()+1, pack.identity()); ostate_table[pack.identity()].set_currentRoute(request.pointer()); cout << endl << request.to_string() << endl; if (request.identity().filters().size() > request.pointer()){ send_AITF_message(request, request.identity().filters()[request.pointer()].address()); }else{ ostate_table.erase(request.identity()); } return; } void AITF_enforce(AITF_packet pack, IP::address_type addr){ cout << "Host enabled " << hosts.isEnabledHost(addr) << " " << addr << endl; if (hosts.isEnabledHost(addr)){ struct timeval start_time; gettimeofday(&start_time, NULL); int bypass = start_time.tv_sec; if (ostate_table.count(pack.identity()) && ostate_table[pack.identity()].ttl() >= bypass){ ostate_table[pack.identity()].set_ttl(bypass+TLONG-TLONG/6); AITF_escalation(pack); }else{ AITF_connect_state cstate(0,0,0); ostate_table.insert(std::make_pair(pack.identity(), cstate)); uint64_t nonce1 = generateNonce(); ostate_table[pack.identity()].set_nonce1(nonce1); ostate_table[pack.identity()].set_ttl(bypass+TLONG-TLONG/6); ostate_table[pack.identity()].set_currentRoute(1); if (is_shadow){ RRFilter block = pack.identity().filters().at(0); cout << endl << "INSTALLING SHADOW TEMP BLOCK: " << block.to_string() << endl; struct timeval start_time; gettimeofday(&start_time, NULL); block.set_ttl(start_time.tv_sec + TLONG/6); block_rules.push_back(block); } AITF_packet request = AITF_packet((uint8_t)REQUEST, nonce1, (uint64_t)0, (uint32_t)1, pack.identity().filters(), pack.identity().victim(), pack.identity().size()); if (request.identity().filters().size() >= 2){ send_AITF_message(request, request.identity().filters()[1].address()); }else{ ostate_table.erase(request.identity()); } } } return; } void AITF_request(AITF_packet pack){ vector<NetworkInterface> ip_addrs = NetworkInterface::all(); IP::address_type addr; int x; int y; for (x = ip_addrs.size()-1; x >= 0; x--){ if (ip_addrs[x].addresses().ip_addr == pack.identity().filters()[pack.pointer()].address()){ addr = ip_addrs[x].addresses().ip_addr; break; } } RRFilter rent = pack.identity().filters()[pack.pointer()]; //Check the random numbers if (generateRandomValue(pack.identity().victim(),1) == rent.random_number_1() || generateRandomValue(pack.identity().victim(),1) == rent.random_number_2()){ // SEND VERIFY AITF_connect_state cstate(0,0,0); istate_table[pack.identity()] = cstate; // SET NONCE2 uint64_t nonce2 = generateNonce(); istate_table[pack.identity()].set_nonce2(nonce2); AITF_packet verify((uint8_t)VERIFY, pack.nonce1(), nonce2, pack.pointer(), pack.identity()); send_AITF_message(verify, verify.identity().victim()); }else{ vector<RRFilter> nfilter = pack.identity().filters(); // SEND CORRECT uint64_t r1 = generateRandomValue(pack.identity().victim(), 1); uint64_t r2 = generateRandomValue(pack.identity().victim(), 2); AITF_packet correct = AITF_packet((uint8_t)CORRECT, pack.nonce1(), (uint64_t)0, pack.pointer(), r1, r2, pack.identity()); send_AITF_message(correct, correct.identity().victim()); } return; } void AITF_verify(AITF_packet pack){ struct timeval start_time; gettimeofday(&start_time, NULL); int bypass = start_time.tv_sec; if (ostate_table.count(pack.identity()) && ostate_table[pack.identity()].ttl() >= bypass){ ostate_table[pack.identity()].set_ttl(bypass+TLONG-TLONG/6); AITF_connect_state cstate = ostate_table.at(pack.identity()); if (cstate.nonce1() == pack.nonce1()){ AITF_packet block((uint8_t)BLOCK, (uint64_t)0, pack.nonce2(), pack.pointer(), pack.identity()); send_AITF_message(block, pack.identity().filters()[pack.pointer()].address()); } } return; } void AITF_correct(AITF_packet pack){ struct timeval start_time; gettimeofday(&start_time, NULL); int bypass = start_time.tv_sec; if (ostate_table.count(pack.identity()) && ostate_table[pack.identity()].ttl() >= bypass){ ostate_table[pack.identity()].set_ttl(bypass+TLONG-TLONG/6); AITF_connect_state cstate = ostate_table.at(pack.identity()); if (cstate.nonce1() == pack.nonce1()){ vector<RRFilter> rent = pack.identity().filters(); rent[pack.pointer()].set_random_number_1(pack.crn1()); rent[pack.pointer()].set_random_number_2(pack.crn2()); rent[pack.pointer()].set_match_type(2); AITF_packet enforce = AITF_packet((uint8_t)ENFORCE, (uint64_t)0, (uint64_t)0, pack.pointer(), rent, pack.identity().victim(), rent.size()); ostate_table.erase(pack.identity()); ostate_table[enforce.identity()] = cstate; ostate_table[enforce.identity()].set_ttl(bypass+TLONG-TLONG/6); ostate_table[enforce.identity()].set_currentRoute(pack.pointer()); cout << endl << "ENFORCE: " << enforce.to_string() << endl; AITF_enforce(enforce, pack.identity().victim()); } } return; } void AITF_block(AITF_packet pack){ if (istate_table.count(pack.identity())){ AITF_connect_state cstate = istate_table.at(pack.identity()); if (cstate.nonce2() == pack.nonce2()){ vector<RRFilter> rent = pack.identity().filters(); RRFilter block = rent.at(pack.pointer()-1); if (block.match_type() == 1) { block.set_address(pack.identity().victim()); } cout << endl << "INSTALLING BLOCK: " << block.to_string() << endl; struct timeval start_time; gettimeofday(&start_time, NULL); block.set_ttl(start_time.tv_sec + TLONG); block_rules.push_back(block); istate_table.erase(pack.identity()); } } return; } void AITF_cease(AITF_packet pack){ // NEVER CEASE! MARCH FORWARDS! return; } void AITF_action(thread_data* data){ AITF_packet apacket = AITF_packet((uint8_t*)data->buff, data->size); cout << apacket.to_string(); switch(apacket.packet_type()) { case 0: AITF_enforce(apacket, data->addr); break; case 1: AITF_request(apacket); break; case 2: AITF_verify(apacket); break; case 3: AITF_correct(apacket); break; case 4: AITF_block(apacket); break; case 5: default: AITF_cease(apacket); } free(data); } void AITF_daemon(void* data){ int portNumber = 11467; struct sockaddr_in serv_addr, client_addr; int fd = 0; int fdlisten = 0; int fdconn = 0; int out = 0; unsigned int client = sizeof(client_addr); // Establish the socket that will be used for listening fd = socket(AF_INET, SOCK_DGRAM, 0); printf("Socket: %d\n", fd); // Do a bind of that socket serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(portNumber); serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); bind( fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); // Set up to listen listen( fd, 10); fdlisten = fd; ssize_t tsdata; thread_data* buff; while(1) { buff = (thread_data*) malloc(sizeof(thread_data)); tsdata = recvfrom(fdlisten, buff->buff, 1500, 0, (struct sockaddr *)&client_addr, &client); if (tsdata > 0){ uint32_t conn_addr = client_addr.sin_addr.s_addr; buff->addr = IP::address_type(conn_addr); buff->size = tsdata; //pthread_t helper; //pthread_create(&helper, NULL, (void*(*)(void*))AITF_action, buff); AITF_action(buff); }else{ free(buff); } } } int intializeAITF(void* filtertable){ int aitf_thread = 0; pthread_t helper; pthread_create(&helper, NULL, (void*(*)(void*))AITF_daemon, filtertable); }<commit_msg>more print statements<commit_after>#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <sys/resource.h> #include <asm/errno.h> #include <sys/socket.h> #include <sys/time.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <malloc.h> #include <string.h> #include <utility> #include <map> #include <sys/types.h> #include <netdb.h> #include <string.h> #include <unistd.h> #include <assert.h> #include <linux/netfilter.h> #include <tins/tins.h> #include "HostMapping.h" #include "AITF_packet.h" #include "AITF_connect_state.h" #include "numbers.h" #define TLONG 30 using namespace Tins; using namespace std; extern HostMapping hosts; extern bool is_shadow; map<AITF_identity, AITF_connect_state> ostate_table; map<AITF_identity, AITF_connect_state> istate_table; vector<RRFilter> block_rules; typedef enum{ ENFORCE, REQUEST, VERIFY, CORRECT, BLOCK, CEASE } AITF_type; typedef struct thread_data{ IP::address_type addr; char buff[1500]; ssize_t size; } thread_data; uint64_t generateNonce(){ return generate_key(); } int block_verdict(RREntry r, IP::address_type addr){ struct timeval start_time; gettimeofday(&start_time, NULL); int verdict; int bypass = start_time.tv_sec; for (int i = 0; i < block_rules.size(); i++){ if (bypass > block_rules.at(i).ttl()){ continue; } cout << "ADDR: " << r.address() << " DADDR: " << addr; cout << " B RULE: " << block_rules.at(i).to_string() << endl; verdict = block_rules.at(i).match(r, addr); if (verdict == 1){ return NF_ACCEPT; } if (verdict == 0){ return NF_DROP; } } return NF_ACCEPT; } void send_AITF_message(AITF_packet pack, IP::address_type addr){ cout << "SENDING PACKET: DEST: " << addr.to_string(); cout << pack.to_string(); uint8_t* data = (uint8_t*)malloc(pack.packet_size()); pack.serialize(data, pack.packet_size()); int status, sd, len, s, r; struct addrinfo hints; struct addrinfo *servinfo, *p; // will point to the results const char *url, *port; port = "11467"; url = addr.to_string().c_str(); memset(&hints, 0 , sizeof(hints)); // make sure the stuct is empty hints.ai_family = AF_INET; // only IPv4 hints.ai_socktype = SOCK_DGRAM; // Use a UDP connection // getaddrinfo() - fills out an address structure for us with the destination server's info if((status = getaddrinfo(url, port, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status)); return; } // loop through all results and connect to the first one we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("client: socket"); continue; } if((connect(sd, servinfo->ai_addr, servinfo->ai_addrlen)) < 0) { close(sd); perror("client: connect"); continue; } break; } if (p == NULL) { fprintf(stderr, "client: failed to connect\n"); return; } freeaddrinfo(servinfo); s = send(sd, data, pack.packet_size(), 0); close(sd); return; } uint64_t generateRandomValue(IP::address_type addr, int x){ return hash_for_destination(addr, x - 1); } void AITF_escalation(AITF_packet pack){ cout << endl << pack.to_string() << endl; uint64_t nonce1 = generateNonce(); ostate_table[pack.identity()].set_nonce1(nonce1); AITF_packet request = AITF_packet((uint8_t)REQUEST, nonce1, (uint64_t)0, ostate_table[pack.identity()].currentRoute()+1, pack.identity()); ostate_table[pack.identity()].set_currentRoute(request.pointer()); cout << endl << request.to_string() << endl; if (request.identity().filters().size() > request.pointer()){ send_AITF_message(request, request.identity().filters()[request.pointer()].address()); }else{ ostate_table.erase(request.identity()); } return; } void AITF_enforce(AITF_packet pack, IP::address_type addr){ cout << "Host enabled " << hosts.isEnabledHost(addr) << " " << addr << endl; if (hosts.isEnabledHost(addr)){ struct timeval start_time; gettimeofday(&start_time, NULL); int bypass = start_time.tv_sec; if (ostate_table.count(pack.identity()) && ostate_table[pack.identity()].ttl() >= bypass){ ostate_table[pack.identity()].set_ttl(bypass+TLONG-TLONG/6); AITF_escalation(pack); }else{ AITF_connect_state cstate(0,0,0); ostate_table.insert(std::make_pair(pack.identity(), cstate)); uint64_t nonce1 = generateNonce(); ostate_table[pack.identity()].set_nonce1(nonce1); ostate_table[pack.identity()].set_ttl(bypass+TLONG-TLONG/6); ostate_table[pack.identity()].set_currentRoute(1); if (is_shadow){ RRFilter block = pack.identity().filters().at(0); cout << endl << "INSTALLING SHADOW TEMP BLOCK: " << block.to_string() << endl; struct timeval start_time; gettimeofday(&start_time, NULL); block.set_ttl(start_time.tv_sec + TLONG/6); block_rules.push_back(block); } AITF_packet request = AITF_packet((uint8_t)REQUEST, nonce1, (uint64_t)0, (uint32_t)1, pack.identity().filters(), pack.identity().victim(), pack.identity().size()); if (request.identity().filters().size() >= 2){ send_AITF_message(request, request.identity().filters()[1].address()); }else{ ostate_table.erase(request.identity()); } } } return; } void AITF_request(AITF_packet pack){ vector<NetworkInterface> ip_addrs = NetworkInterface::all(); IP::address_type addr; int x; int y; for (x = ip_addrs.size()-1; x >= 0; x--){ if (ip_addrs[x].addresses().ip_addr == pack.identity().filters()[pack.pointer()].address()){ addr = ip_addrs[x].addresses().ip_addr; break; } } RRFilter rent = pack.identity().filters()[pack.pointer()]; //Check the random numbers if (generateRandomValue(pack.identity().victim(),1) == rent.random_number_1() || generateRandomValue(pack.identity().victim(),1) == rent.random_number_2()){ // SEND VERIFY AITF_connect_state cstate(0,0,0); istate_table[pack.identity()] = cstate; // SET NONCE2 uint64_t nonce2 = generateNonce(); istate_table[pack.identity()].set_nonce2(nonce2); AITF_packet verify((uint8_t)VERIFY, pack.nonce1(), nonce2, pack.pointer(), pack.identity()); send_AITF_message(verify, verify.identity().victim()); }else{ vector<RRFilter> nfilter = pack.identity().filters(); // SEND CORRECT uint64_t r1 = generateRandomValue(pack.identity().victim(), 1); uint64_t r2 = generateRandomValue(pack.identity().victim(), 2); AITF_packet correct = AITF_packet((uint8_t)CORRECT, pack.nonce1(), (uint64_t)0, pack.pointer(), r1, r2, pack.identity()); send_AITF_message(correct, correct.identity().victim()); } return; } void AITF_verify(AITF_packet pack){ struct timeval start_time; gettimeofday(&start_time, NULL); int bypass = start_time.tv_sec; if (ostate_table.count(pack.identity()) && ostate_table[pack.identity()].ttl() >= bypass){ ostate_table[pack.identity()].set_ttl(bypass+TLONG-TLONG/6); AITF_connect_state cstate = ostate_table.at(pack.identity()); if (cstate.nonce1() == pack.nonce1()){ AITF_packet block((uint8_t)BLOCK, (uint64_t)0, pack.nonce2(), pack.pointer(), pack.identity()); send_AITF_message(block, pack.identity().filters()[pack.pointer()].address()); } } return; } void AITF_correct(AITF_packet pack){ struct timeval start_time; gettimeofday(&start_time, NULL); int bypass = start_time.tv_sec; if (ostate_table.count(pack.identity()) && ostate_table[pack.identity()].ttl() >= bypass){ ostate_table[pack.identity()].set_ttl(bypass+TLONG-TLONG/6); AITF_connect_state cstate = ostate_table.at(pack.identity()); if (cstate.nonce1() == pack.nonce1()){ vector<RRFilter> rent = pack.identity().filters(); rent[pack.pointer()].set_random_number_1(pack.crn1()); rent[pack.pointer()].set_random_number_2(pack.crn2()); rent[pack.pointer()].set_match_type(2); AITF_packet enforce = AITF_packet((uint8_t)ENFORCE, (uint64_t)0, (uint64_t)0, pack.pointer(), rent, pack.identity().victim(), rent.size()); ostate_table.erase(pack.identity()); ostate_table[enforce.identity()] = cstate; ostate_table[enforce.identity()].set_ttl(bypass+TLONG-TLONG/6); ostate_table[enforce.identity()].set_currentRoute(pack.pointer()); cout << endl << "ENFORCE: " << enforce.to_string() << endl; AITF_enforce(enforce, pack.identity().victim()); } } return; } void AITF_block(AITF_packet pack){ if (istate_table.count(pack.identity())){ AITF_connect_state cstate = istate_table.at(pack.identity()); if (cstate.nonce2() == pack.nonce2()){ vector<RRFilter> rent = pack.identity().filters(); RRFilter block = rent.at(pack.pointer()-1); if (block.match_type() == 1) { block.set_address(pack.identity().victim()); } cout << endl << "INSTALLING BLOCK: " << block.to_string() << endl; struct timeval start_time; gettimeofday(&start_time, NULL); block.set_ttl(start_time.tv_sec + TLONG); block_rules.push_back(block); istate_table.erase(pack.identity()); } } return; } void AITF_cease(AITF_packet pack){ // NEVER CEASE! MARCH FORWARDS! return; } void AITF_action(thread_data* data){ AITF_packet apacket = AITF_packet((uint8_t*)data->buff, data->size); cout << apacket.to_string(); switch(apacket.packet_type()) { case 0: AITF_enforce(apacket, data->addr); break; case 1: AITF_request(apacket); break; case 2: AITF_verify(apacket); break; case 3: AITF_correct(apacket); break; case 4: AITF_block(apacket); break; case 5: default: AITF_cease(apacket); } free(data); } void AITF_daemon(void* data){ int portNumber = 11467; struct sockaddr_in serv_addr, client_addr; int fd = 0; int fdlisten = 0; int fdconn = 0; int out = 0; unsigned int client = sizeof(client_addr); // Establish the socket that will be used for listening fd = socket(AF_INET, SOCK_DGRAM, 0); printf("Socket: %d\n", fd); // Do a bind of that socket serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(portNumber); serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); bind( fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); // Set up to listen listen( fd, 10); fdlisten = fd; ssize_t tsdata; thread_data* buff; while(1) { buff = (thread_data*) malloc(sizeof(thread_data)); tsdata = recvfrom(fdlisten, buff->buff, 1500, 0, (struct sockaddr *)&client_addr, &client); if (tsdata > 0){ uint32_t conn_addr = client_addr.sin_addr.s_addr; buff->addr = IP::address_type(conn_addr); buff->size = tsdata; //pthread_t helper; //pthread_create(&helper, NULL, (void*(*)(void*))AITF_action, buff); AITF_action(buff); }else{ free(buff); } } } int intializeAITF(void* filtertable){ int aitf_thread = 0; pthread_t helper; pthread_create(&helper, NULL, (void*(*)(void*))AITF_daemon, filtertable); }<|endoftext|>
<commit_before>// -*- Mode:C++ -*- /**************************************************************************************************/ /* */ /* Copyright (C) 2014 University of Hull */ /* */ /**************************************************************************************************/ /* */ /* module : field/test/adapter_single.cpp */ /* project : */ /* description: */ /* */ /**************************************************************************************************/ // includes, system //#include <> // includes, project #include <field/adapter/single.hpp> #include <shared.hpp> // internal unnamed namespace namespace { // types, internal (class, enum, struct, union, typedef) // variables, internal // functions, internal } // namespace { #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> #include <boost/test/test_case_template.hpp> BOOST_AUTO_TEST_CASE_TEMPLATE(adapter_single_get, T, field::test::single_types) { using namespace field; test::container_single<T> c; adapter::single<T> const f(c, "f", std::bind(&test::container_single<T>::cb_get, &c), std::bind(&test::container_single<T>::cb_set, &c, std::placeholders::_1)); BOOST_CHECK(T() == f.get()); } BOOST_AUTO_TEST_CASE_TEMPLATE(adapter_single_set, T, field::test::single_types) { using namespace field; test::container_single<T> c; adapter::single<T> f(c, "f", std::bind(&test::container_single<T>::cb_get, &c), std::bind(&test::container_single<T>::cb_set, &c, std::placeholders::_1)); BOOST_CHECK(T() == f.set(T())); } BOOST_AUTO_TEST_CASE_TEMPLATE(adapter_single_op_convert, T, field::test::single_types) { using namespace field; test::container_single<T> c; adapter::single<T> const f(c, "f", std::bind(&test::container_single<T>::cb_get, &c), std::bind(&test::container_single<T>::cb_set, &c, std::placeholders::_1)); BOOST_CHECK(T() == static_cast<T const&>(f)); BOOST_CHECK(T() == static_cast<T>(f)); } BOOST_AUTO_TEST_CASE_TEMPLATE(adapter_single_op_assign, T, field::test::single_types) { using namespace field; test::container_single<T> c; adapter::single<T> f(c, "f", std::bind(&test::container_single<T>::cb_get, &c), std::bind(&test::container_single<T>::cb_set, &c, std::placeholders::_1)); BOOST_CHECK(T() == static_cast<T>(f = T())); } <commit_msg>fixed: compile errors<commit_after>// -*- Mode:C++ -*- /**************************************************************************************************/ /* */ /* Copyright (C) 2014 University of Hull */ /* */ /**************************************************************************************************/ /* */ /* module : field/test/adapter_single.cpp */ /* project : */ /* description: */ /* */ /**************************************************************************************************/ // includes, system //#include <> // includes, project #include <field/adapter/single.hpp> #include <shared.hpp> // internal unnamed namespace namespace { // types, internal (class, enum, struct, union, typedef) // variables, internal // functions, internal } // namespace { #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> #include <boost/test/test_case_template.hpp> BOOST_AUTO_TEST_CASE_TEMPLATE(adapter_single_get, T, field::test::single_types) { using namespace field; test::container_single<T> c; adapter::single<T> const f(c, "f", std::bind(&test::container_single<T>::cb_get, &c), std::bind(&test::container_single<T>::cb_set, &c, std::placeholders::_1)); BOOST_CHECK(T() == f.get()); } BOOST_AUTO_TEST_CASE_TEMPLATE(adapter_single_set, T, field::test::single_types) { using namespace field; test::container_single<T> c; adapter::single<T> f(c, "f", std::bind(&test::container_single<T>::cb_get, &c), std::bind(&test::container_single<T>::cb_set, &c, std::placeholders::_1)); BOOST_CHECK(T() == f.set(T())); } BOOST_AUTO_TEST_CASE_TEMPLATE(adapter_single_op_convert, T, field::test::single_types) { using namespace field; test::container_single<T> c; adapter::single<T> const f(c, "f", std::bind(&test::container_single<T>::cb_get, &c), std::bind(&test::container_single<T>::cb_set, &c, std::placeholders::_1)); BOOST_CHECK(T() == static_cast<T const&>(f)); // BOOST_CHECK(T() == static_cast<T>(f)); } BOOST_AUTO_TEST_CASE_TEMPLATE(adapter_single_op_assign, T, field::test::single_types) { using namespace field; test::container_single<T> c; adapter::single<T> f(c, "f", std::bind(&test::container_single<T>::cb_get, &c), std::bind(&test::container_single<T>::cb_set, &c, std::placeholders::_1)); BOOST_CHECK(T() == static_cast<T const&>(f = T())); } <|endoftext|>
<commit_before>// // Copyright (c) 2011 Kim Walisch, <kim.walisch@gmail.com>. // All rights reserved. // // This file is part of primesieve. // Visit: http://primesieve.googlecode.com // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of the author nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. #include "SieveOfEratosthenes.h" #include "PreSieve.h" #include "EratSmall.h" #include "EratMedium.h" #include "EratBig.h" #include "defs.h" #include "imath.h" #include <stdexcept> #include <cstdlib> #include <cassert> const uint32_t SieveOfEratosthenes::bitValues_[32] = { 7, 11, 13, 17, 19, 23, 29, 31, /* sieve_[i+0] */ 37, 41, 43, 47, 49, 53, 59, 61, /* sieve_[i+1] */ 67, 71, 73, 77, 79, 83, 89, 91, /* sieve_[i+2] */ 97, 101, 103, 107, 109, 113, 119, 121 /* sieve_[i+3] */ }; /** * @param startNumber Sieve the primes within the interval [startNumber, stopNumber]. * @param stopNumber ... * @param sieveSize A sieve size in kilobytes. * @param preSieveLimit Multiples of small primes <= preSieveLimit are pre-sieved * to speed up the sieve of Eratosthenes. * * @pre sieveSize >= 1 && <= 8192 * @pre preSieveLimit >= 13 && <= 23 */ SieveOfEratosthenes::SieveOfEratosthenes(uint64_t startNumber, uint64_t stopNumber, uint32_t sieveSize, uint32_t preSieveLimit) : startNumber_(startNumber), stopNumber_(stopNumber), sqrtStop_(isqrt(stopNumber)), sieve_(NULL), sieveSize_(sieveSize * 1024), isFirstSegment_(true), preSieve_(preSieveLimit), eratSmall_(NULL), eratMedium_(NULL), eratBig_(NULL) { if (startNumber_ < 7 || startNumber_ > stopNumber_) throw std::logic_error( "SieveOfEratosthenes: startNumber must be >= 7 && <= stopNumber."); // it makes no sense to use very small sieve sizes as a sieve // size of the CPU's L1 or L2 cache size performs best if (sieveSize_ < 1024) throw std::invalid_argument( "SieveOfEratosthenes: sieveSize must be >= 1 kilobyte."); if (sieveSize_ > UINT32_MAX / NUMBERS_PER_BYTE) throw std::overflow_error( "SieveOfEratosthenes: sieveSize must be <= 2^32 / 30."); segmentLow_ = startNumber_ - this->getByteRemainder(startNumber_); assert(segmentLow_ % NUMBERS_PER_BYTE == 0); // '+ 1' is a correction for primes of type i*30 + 31 segmentHigh_ = segmentLow_ + sieveSize_ * NUMBERS_PER_BYTE + 1; this->initEratAlgorithms(); // allocate the sieve of Eratosthenes array sieve_ = new uint8_t[sieveSize_]; } SieveOfEratosthenes::~SieveOfEratosthenes() { delete eratSmall_; delete eratMedium_; delete eratBig_; delete[] sieve_; } uint32_t SieveOfEratosthenes::getPreSieveLimit() const { return preSieve_.getLimit(); } uint32_t SieveOfEratosthenes::getByteRemainder(uint64_t n) const { uint32_t remainder = static_cast<uint32_t> (n % NUMBERS_PER_BYTE); // correction for primes of type i*30 + 31 if (remainder <= 1) remainder += NUMBERS_PER_BYTE; return remainder; } void SieveOfEratosthenes::initEratAlgorithms() { try { if (sqrtStop_ > preSieve_.getLimit()) { eratSmall_ = new EratSmall(*this); if (sqrtStop_ > eratSmall_->getLimit()) { eratMedium_ = new EratMedium(*this); if (sqrtStop_ > eratMedium_->getLimit()) eratBig_ = new EratBig(*this); } } } catch (...) { delete eratSmall_; delete eratMedium_; delete eratBig_; throw; } } /** * Pre-sieve multiples of small primes <= preSieve_.getLimit() to * speed up the sieve of Eratosthenes. */ void SieveOfEratosthenes::preSieve() { preSieve_.doIt(sieve_, sieveSize_, segmentLow_); if (isFirstSegment_) { isFirstSegment_ = false; // correct preSieve_.doIt() for numbers <= 23 if (startNumber_ <= preSieve_.getLimit()) sieve_[0] = 0xff; uint32_t startRemainder = this->getByteRemainder(startNumber_); // unset the bits corresponding to numbers < startNumber_ for (int i = 0; bitValues_[i] < startRemainder; i++) sieve_[0] &= ~(1 << i); } } /** * Cross-off the multiples within the current segment. */ void SieveOfEratosthenes::crossOffMultiples() { if (eratSmall_ != NULL) { // process the sieving primes with many multiples per segment eratSmall_->sieve(sieve_, sieveSize_); if (eratMedium_ != NULL) { // process the sieving primes with a few multiples per segment eratMedium_->sieve(sieve_, sieveSize_); if (eratBig_ != NULL) // process the sieving primes having at most // one multiple per segment eratBig_->sieve(sieve_); } } } /** * Implementation of the segmented sieve of Eratosthenes, * sieve(uint32_t) must be called consecutively for all primes * (> getPreSieveLimit()) up to sqrt(stopNumber) in order to sieve * the primes within the interval [startNumber, stopNumber]. */ void SieveOfEratosthenes::sieve(uint32_t prime) { assert(prime > this->getPreSieveLimit()); assert(prime <= this->getSquareRoot()); assert(eratSmall_ != NULL); uint64_t primeSquared = isquare<uint64_t>(prime); // The following while loop segments the sieve of Eratosthenes, // it is entered if all primes <= sqrt(segmentHigh_) required to // sieve the next segment have been added to one of the three // erat(Small|Medium|Big)_ objects. // Each loop iteration sieves the primes within the interval // [segmentLow_+7, segmentLow_ + (sieveSize_*30+1)]. while (segmentHigh_ < primeSquared) { this->preSieve(); this->crossOffMultiples(); this->analyseSieve(sieve_, sieveSize_); segmentLow_ += sieveSize_ * NUMBERS_PER_BYTE; segmentHigh_ += sieveSize_ * NUMBERS_PER_BYTE; } // prime is added to eratSmall_ if it has many multiples per // segment, to eratMedium_ if it has a few multiples per segment // and to eratBig_ if it has at most one multiple per segment. if (prime > eratSmall_->getLimit()) if (prime > eratMedium_->getLimit()) eratBig_->addSievingPrime(prime); else eratMedium_->addSievingPrime(prime); else eratSmall_->addSievingPrime(prime); } /** * Sieve the last segments remaining after that sieve(uint32_t) has * been called for all primes up to sqrt(stopNumber). */ void SieveOfEratosthenes::finish() { assert(segmentLow_ < stopNumber_); // sieve all segments left except the last one while (segmentHigh_ < stopNumber_) { this->preSieve(); this->crossOffMultiples(); this->analyseSieve(sieve_, sieveSize_); segmentLow_ += sieveSize_ * NUMBERS_PER_BYTE; segmentHigh_ += sieveSize_ * NUMBERS_PER_BYTE; } uint32_t stopRemainder = this->getByteRemainder(stopNumber_); // calculate the sieve size of the last segment sieveSize_ = static_cast<uint32_t> ((stopNumber_ - stopRemainder) - segmentLow_) / NUMBERS_PER_BYTE + 1; // sieve the last segment this->preSieve(); this->crossOffMultiples(); // unset the bits corresponding to numbers > stopNumber_ for (int i = 0; i < 8; i++) { if (bitValues_[i] > stopRemainder) sieve_[sieveSize_ - 1] &= ~(1 << i); } this->analyseSieve(sieve_, sieveSize_); } <commit_msg>improved code readability<commit_after>// // Copyright (c) 2011 Kim Walisch, <kim.walisch@gmail.com>. // All rights reserved. // // This file is part of primesieve. // Visit: http://primesieve.googlecode.com // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of the author nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. #include "SieveOfEratosthenes.h" #include "PreSieve.h" #include "EratSmall.h" #include "EratMedium.h" #include "EratBig.h" #include "defs.h" #include "imath.h" #include <stdexcept> #include <cstdlib> #include <cassert> const uint32_t SieveOfEratosthenes::bitValues_[32] = { 7, 11, 13, 17, 19, 23, 29, 31, /* sieve_[i+0] */ 37, 41, 43, 47, 49, 53, 59, 61, /* sieve_[i+1] */ 67, 71, 73, 77, 79, 83, 89, 91, /* sieve_[i+2] */ 97, 101, 103, 107, 109, 113, 119, 121 /* sieve_[i+3] */ }; /** * @param startNumber Sieve the primes within the interval [startNumber, stopNumber]. * @param stopNumber ... * @param sieveSize A sieve size in kilobytes. * @param preSieveLimit Multiples of small primes <= preSieveLimit are pre-sieved * to speed up the sieve of Eratosthenes. * * @pre sieveSize >= 1 && <= 8192 * @pre preSieveLimit >= 13 && <= 23 */ SieveOfEratosthenes::SieveOfEratosthenes(uint64_t startNumber, uint64_t stopNumber, uint32_t sieveSize, uint32_t preSieveLimit) : startNumber_(startNumber), stopNumber_(stopNumber), sqrtStop_(isqrt(stopNumber)), sieve_(NULL), sieveSize_(sieveSize * 1024), isFirstSegment_(true), preSieve_(preSieveLimit), eratSmall_(NULL), eratMedium_(NULL), eratBig_(NULL) { if (startNumber_ < 7 || startNumber_ > stopNumber_) throw std::logic_error( "SieveOfEratosthenes: startNumber must be >= 7 && <= stopNumber."); // it makes no sense to use very small sieve sizes as a sieve // size of the CPU's L1 or L2 cache size performs best if (sieveSize_ < 1024) throw std::invalid_argument( "SieveOfEratosthenes: sieveSize must be >= 1 kilobyte."); segmentLow_ = startNumber_ - this->getByteRemainder(startNumber_); // '+ 1' is a correction for primes of type i*30 + 31 segmentHigh_ = segmentLow_ + sieveSize_ * NUMBERS_PER_BYTE + 1; this->initEratAlgorithms(); // allocate the sieve of Eratosthenes array sieve_ = new uint8_t[sieveSize_]; } SieveOfEratosthenes::~SieveOfEratosthenes() { delete eratSmall_; delete eratMedium_; delete eratBig_; delete[] sieve_; } uint32_t SieveOfEratosthenes::getPreSieveLimit() const { return preSieve_.getLimit(); } uint32_t SieveOfEratosthenes::getByteRemainder(uint64_t n) const { uint32_t remainder = static_cast<uint32_t> (n % NUMBERS_PER_BYTE); // correction for primes of type i*30 + 31 if (remainder <= 1) remainder += NUMBERS_PER_BYTE; return remainder; } void SieveOfEratosthenes::initEratAlgorithms() { try { if (sqrtStop_ > preSieve_.getLimit()) { eratSmall_ = new EratSmall(*this); if (sqrtStop_ > eratSmall_->getLimit()) { eratMedium_ = new EratMedium(*this); if (sqrtStop_ > eratMedium_->getLimit()) eratBig_ = new EratBig(*this); } } } catch (...) { delete eratSmall_; delete eratMedium_; delete eratBig_; throw; } } /** * Pre-sieve multiples of small primes <= preSieve_.getLimit() * to speed up the sieve of Eratosthenes. */ void SieveOfEratosthenes::preSieve() { preSieve_.doIt(sieve_, sieveSize_, segmentLow_); if (isFirstSegment_) { isFirstSegment_ = false; // correct preSieve_.doIt() for numbers <= 23 if (startNumber_ <= preSieve_.getLimit()) sieve_[0] = 0xff; uint32_t startRemainder = this->getByteRemainder(startNumber_); // unset the bits corresponding to numbers < startNumber_ for (int i = 0; bitValues_[i] < startRemainder; i++) sieve_[0] &= ~(1 << i); } } /** * Cross-off the multiples within the current segment i.e. * [segmentLow_+7, segmentHigh_]. */ void SieveOfEratosthenes::crossOffMultiples() { if (eratSmall_ != NULL) { // process the sieving primes with many multiples per segment eratSmall_->sieve(sieve_, sieveSize_); if (eratMedium_ != NULL) { // process the sieving primes with a few multiples per segment eratMedium_->sieve(sieve_, sieveSize_); if (eratBig_ != NULL) // process the sieving primes having at most // one multiple per segment eratBig_->sieve(sieve_); } } } /** * Implementation of the segmented sieve of Eratosthenes. * sieve(uint32_t) must be called consecutively for all primes * (> getPreSieveLimit()) up to sqrt(stopNumber) in order to sieve * the primes within the interval [startNumber, stopNumber]. */ void SieveOfEratosthenes::sieve(uint32_t prime) { assert(prime > this->getPreSieveLimit()); assert(prime <= this->getSquareRoot()); assert(sieveSize_ <= UINT32_MAX / NUMBERS_PER_BYTE); assert(eratSmall_ != NULL); uint64_t primeSquared = isquare<uint64_t>(prime); // The following while loop segments the sieve of Eratosthenes, // it is entered if all primes <= sqrt(segmentHigh_) required to // sieve the next segment have been added to one of the three // erat(Small|Medium|Big)_ objects. // Each loop iteration sieves the primes within the interval // [segmentLow_+7, segmentHigh_]. while (segmentHigh_ < primeSquared) { this->preSieve(); this->crossOffMultiples(); this->analyseSieve(sieve_, sieveSize_); segmentLow_ += sieveSize_ * NUMBERS_PER_BYTE; segmentHigh_ += sieveSize_ * NUMBERS_PER_BYTE; } // prime is added to eratSmall_ if it has many multiples per // segment, to eratMedium_ if it has a few multiples per segment // and to eratBig_ if it has at most one multiple per segment. if (prime > eratSmall_->getLimit()) if (prime > eratMedium_->getLimit()) eratBig_->addSievingPrime(prime); else eratMedium_->addSievingPrime(prime); else eratSmall_->addSievingPrime(prime); } /** * Sieve the last segments remaining after that sieve(uint32_t) * has been called for all primes up to sqrt(stopNumber). */ void SieveOfEratosthenes::finish() { assert(segmentLow_ < stopNumber_); // sieve all segments left except the last one while (segmentHigh_ < stopNumber_) { this->preSieve(); this->crossOffMultiples(); this->analyseSieve(sieve_, sieveSize_); segmentLow_ += sieveSize_ * NUMBERS_PER_BYTE; segmentHigh_ += sieveSize_ * NUMBERS_PER_BYTE; } uint32_t stopRemainder = this->getByteRemainder(stopNumber_); // calculate the sieve size of the last segment sieveSize_ = static_cast<uint32_t> ((stopNumber_ - stopRemainder) - segmentLow_) / NUMBERS_PER_BYTE + 1; // sieve the last segment this->preSieve(); this->crossOffMultiples(); // unset the bits corresponding to numbers > stopNumber_ for (int i = 0; i < 8; i++) { if (bitValues_[i] > stopRemainder) sieve_[sieveSize_ - 1] &= ~(1 << i); } this->analyseSieve(sieve_, sieveSize_); } <|endoftext|>
<commit_before>/******************************************************************************* Copyright (c) 2012-2016 Alex Zhondin <lexxmark.dev@gmail.com> Copyright (c) 2015-2019 Alexandra Cherdantseva <neluhus.vagus@gmail.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *******************************************************************************/ #include "PropertyDelegateFactory.h" #include "Utils/PropertyDelegateMisc.h" #include "Utils/PropertyDelegatePropertySet.h" #include "Utils/PropertyDelegateGeoCoord.h" #include "Utils/PropertyDelegateGeoPoint.h" #include "Core/PropertyDelegateBool.h" #include "Core/PropertyDelegateInt.h" #include "Core/PropertyDelegateUInt.h" #include "Core/PropertyDelegateDouble.h" #include "Core/PropertyDelegateFloat.h" #include "Core/PropertyDelegateEnum.h" #include "Core/PropertyDelegateEnumFlags.h" #include "Core/PropertyDelegateQString.h" #include "Core/PropertyDelegateQPoint.h" #include "Core/PropertyDelegateQPointF.h" #include "Core/PropertyDelegateQSize.h" #include "Core/PropertyDelegateQSizeF.h" #include "Core/PropertyDelegateQRect.h" #include "Core/PropertyDelegateQRectF.h" #include "GUI/PropertyDelegateQColor.h" #include "GUI/PropertyDelegateQPen.h" #include "GUI/PropertyDelegateQBrush.h" #include "GUI/PropertyDelegateQFont.h" #include "GUI/PropertyDelegateButton.h" #include "QtnProperty/PropertyQKeySequence.h" #include "QtnProperty/PropertyInt64.h" #include "QtnProperty/PropertyUInt64.h" #include "QtnProperty/MultiProperty.h" #include <QDebug> QtnPropertyDelegateFactory::QtnPropertyDelegateFactory( QtnPropertyDelegateFactory *superFactory) { setSuperFactory(superFactory); } void QtnPropertyDelegateFactory::setSuperFactory( QtnPropertyDelegateFactory *superFactory) { Q_ASSERT(m_superFactory != this); m_superFactory = superFactory; } QtnPropertyDelegate *QtnPropertyDelegateFactory::createDelegate( QtnPropertyBase &owner) { auto factory = this; while (factory) { auto result = factory->createDelegateInternal(owner); if (result) { result->setFactory(this); result->init(); return result; } factory = factory->m_superFactory; } auto delegateInfo = owner.delegateInfo(); QByteArray delegateName; if (delegateInfo) delegateName = delegateInfo->name; // create delegate stub if (delegateName.isEmpty()) { qWarning() << "Cannot find default delegate for property" << owner.name(); qWarning() << "Did you forget to register default delegate for " << owner.metaObject()->className() << "type?"; } else { qWarning() << "Cannot find delegate with name" << delegateName << "for property" << owner.name(); qWarning() << "Did you forget to register" << delegateName << "delegate for" << owner.metaObject()->className() << "type?"; } return qtnCreateDelegateError(owner, QString("Delegate <%1> unknown") .arg(QString::fromLatin1(delegateName))); } QtnPropertyDelegate *QtnPropertyDelegateFactory::createDelegateInternal( QtnPropertyBase &owner) { const QMetaObject *metaObject = owner.metaObject(); CreateFunction createFunction = nullptr; while (metaObject && !createFunction) { // try to find delegate factory by class name auto it = m_createItems.find(metaObject); if (it != m_createItems.end()) { // try to find delegate factory by name const CreateItem &createItem = it.value(); auto delegateInfo = owner.delegateInfo(); QByteArray delegateName; if (delegateInfo) delegateName = delegateInfo->name; if (delegateName.isEmpty()) { createFunction = createItem.defaultCreateFunction; } else { auto jt = createItem.createFunctions.find(delegateName); if (jt != createItem.createFunctions.end()) createFunction = jt.value(); } } metaObject = metaObject->superClass(); } if (!createFunction) return nullptr; return createFunction(owner); } bool QtnPropertyDelegateFactory::registerDelegateDefault( const QMetaObject *propertyMetaObject, const CreateFunction &createFunction, const QByteArray &delegateName) { Q_ASSERT(propertyMetaObject); Q_ASSERT(createFunction); // find or create creation record CreateItem &createItem = m_createItems[propertyMetaObject]; // register default create function createItem.defaultCreateFunction = createFunction; if (!delegateName.isEmpty()) { return registerDelegate( propertyMetaObject, createFunction, delegateName); } return true; } bool QtnPropertyDelegateFactory::registerDelegate( const QMetaObject *propertyMetaObject, const CreateFunction &createFunction, const QByteArray &delegateName) { Q_ASSERT(propertyMetaObject); Q_ASSERT(createFunction); Q_ASSERT(!delegateName.isEmpty()); // find or create creation record CreateItem &createItem = m_createItems[propertyMetaObject]; // register create function createItem.createFunctions[delegateName] = createFunction; return true; } bool QtnPropertyDelegateFactory::unregisterDelegate( const QMetaObject *propertyMetaObject) { Q_ASSERT(propertyMetaObject); auto it = m_createItems.find(propertyMetaObject); if (it == m_createItems.end()) return false; m_createItems.erase(it); return true; } bool QtnPropertyDelegateFactory::unregisterDelegate( const QMetaObject *propertyMetaObject, const QByteArray &delegateName) { Q_ASSERT(propertyMetaObject); Q_ASSERT(!delegateName.isEmpty()); auto it = m_createItems.find(propertyMetaObject); if (it == m_createItems.end()) return false; auto &createFunctions = it->createFunctions; auto it2 = createFunctions.find(delegateName); if (it2 == createFunctions.end()) return false; createFunctions.erase(it2); return true; } void QtnPropertyDelegateFactory::registerDefaultDelegates( QtnPropertyDelegateFactory &factory) { QtnPropertyDelegatePropertySet::Register(factory); QtnPropertyDelegateBoolCheck::Register(factory); QtnPropertyDelegateBoolCombobox::Register(factory); QtnPropertyDelegateInt::Register(factory); QtnPropertyDelegateUInt::Register(factory); QtnPropertyDelegateInt64::Register(factory); QtnPropertyDelegateUInt64::Register(factory); QtnPropertyDelegateDouble::Register(factory); QtnPropertyDelegateFloat::Register(factory); QtnPropertyDelegateEnum::Register(factory); QtnPropertyDelegateEnumFlags::Register(factory); QtnPropertyDelegateQString::Register(factory); QtnPropertyDelegateQStringFile::Register(factory); QtnPropertyDelegateQStringList::Register(factory); QtnPropertyDelegateQStringCallback::Register(factory); QtnPropertyDelegateQPoint::Register(factory); QtnPropertyDelegateQPointF::Register(factory); QtnPropertyDelegateQSize::Register(factory); QtnPropertyDelegateQSizeF::Register(factory); QtnPropertyDelegateQRect::Register(factory); QtnPropertyDelegateQRectF::Register(factory); QtnPropertyDelegateGeoCoord::Register(factory); QtnPropertyDelegateGeoPoint::Register(factory); QtnPropertyDelegateQColor::Register(factory); QtnPropertyDelegateQColorSolid::Register(factory); QtnPropertyDelegateQFont::Register(factory); QtnPropertyDelegateButton::Register(factory); QtnPropertyDelegateButtonLink::Register(factory); QtnPropertyDelegateQPenStyle::Register(factory); QtnPropertyDelegateQPen::Register(factory); QtnPropertyDelegateQBrushStyle::Register(factory); QtnPropertyDelegateQKeySequence::Register(factory); QtnMultiPropertyDelegate::Register(factory); } static QScopedPointer<QtnPropertyDelegateFactory> _staticInstance; QtnPropertyDelegateFactory &QtnPropertyDelegateFactory::staticInstance() { if (!_staticInstance) { _staticInstance.reset(new QtnPropertyDelegateFactory); registerDefaultDelegates(*_staticInstance.data()); } return *_staticInstance.data(); } void QtnPropertyDelegateFactory::resetDefaultInstance( QtnPropertyDelegateFactory *factory) { if (_staticInstance) { auto currentFactory = factory; while (currentFactory) { if (currentFactory == _staticInstance.data()) { _staticInstance.take(); break; } currentFactory = currentFactory->superFactory(); } } _staticInstance.reset(factory); } <commit_msg>fix uninitialized member<commit_after>/******************************************************************************* Copyright (c) 2012-2016 Alex Zhondin <lexxmark.dev@gmail.com> Copyright (c) 2015-2019 Alexandra Cherdantseva <neluhus.vagus@gmail.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *******************************************************************************/ #include "PropertyDelegateFactory.h" #include "Utils/PropertyDelegateMisc.h" #include "Utils/PropertyDelegatePropertySet.h" #include "Utils/PropertyDelegateGeoCoord.h" #include "Utils/PropertyDelegateGeoPoint.h" #include "Core/PropertyDelegateBool.h" #include "Core/PropertyDelegateInt.h" #include "Core/PropertyDelegateUInt.h" #include "Core/PropertyDelegateDouble.h" #include "Core/PropertyDelegateFloat.h" #include "Core/PropertyDelegateEnum.h" #include "Core/PropertyDelegateEnumFlags.h" #include "Core/PropertyDelegateQString.h" #include "Core/PropertyDelegateQPoint.h" #include "Core/PropertyDelegateQPointF.h" #include "Core/PropertyDelegateQSize.h" #include "Core/PropertyDelegateQSizeF.h" #include "Core/PropertyDelegateQRect.h" #include "Core/PropertyDelegateQRectF.h" #include "GUI/PropertyDelegateQColor.h" #include "GUI/PropertyDelegateQPen.h" #include "GUI/PropertyDelegateQBrush.h" #include "GUI/PropertyDelegateQFont.h" #include "GUI/PropertyDelegateButton.h" #include "QtnProperty/PropertyQKeySequence.h" #include "QtnProperty/PropertyInt64.h" #include "QtnProperty/PropertyUInt64.h" #include "QtnProperty/MultiProperty.h" #include <QDebug> QtnPropertyDelegateFactory::QtnPropertyDelegateFactory( QtnPropertyDelegateFactory *superFactory) : m_superFactory(nullptr) { setSuperFactory(superFactory); } void QtnPropertyDelegateFactory::setSuperFactory( QtnPropertyDelegateFactory *superFactory) { Q_ASSERT(m_superFactory != this); m_superFactory = superFactory; } QtnPropertyDelegate *QtnPropertyDelegateFactory::createDelegate( QtnPropertyBase &owner) { auto factory = this; while (factory) { auto result = factory->createDelegateInternal(owner); if (result) { result->setFactory(this); result->init(); return result; } factory = factory->m_superFactory; } auto delegateInfo = owner.delegateInfo(); QByteArray delegateName; if (delegateInfo) delegateName = delegateInfo->name; // create delegate stub if (delegateName.isEmpty()) { qWarning() << "Cannot find default delegate for property" << owner.name(); qWarning() << "Did you forget to register default delegate for " << owner.metaObject()->className() << "type?"; } else { qWarning() << "Cannot find delegate with name" << delegateName << "for property" << owner.name(); qWarning() << "Did you forget to register" << delegateName << "delegate for" << owner.metaObject()->className() << "type?"; } return qtnCreateDelegateError(owner, QString("Delegate <%1> unknown") .arg(QString::fromLatin1(delegateName))); } QtnPropertyDelegate *QtnPropertyDelegateFactory::createDelegateInternal( QtnPropertyBase &owner) { const QMetaObject *metaObject = owner.metaObject(); CreateFunction createFunction = nullptr; while (metaObject && !createFunction) { // try to find delegate factory by class name auto it = m_createItems.find(metaObject); if (it != m_createItems.end()) { // try to find delegate factory by name const CreateItem &createItem = it.value(); auto delegateInfo = owner.delegateInfo(); QByteArray delegateName; if (delegateInfo) delegateName = delegateInfo->name; if (delegateName.isEmpty()) { createFunction = createItem.defaultCreateFunction; } else { auto jt = createItem.createFunctions.find(delegateName); if (jt != createItem.createFunctions.end()) createFunction = jt.value(); } } metaObject = metaObject->superClass(); } if (!createFunction) return nullptr; return createFunction(owner); } bool QtnPropertyDelegateFactory::registerDelegateDefault( const QMetaObject *propertyMetaObject, const CreateFunction &createFunction, const QByteArray &delegateName) { Q_ASSERT(propertyMetaObject); Q_ASSERT(createFunction); // find or create creation record CreateItem &createItem = m_createItems[propertyMetaObject]; // register default create function createItem.defaultCreateFunction = createFunction; if (!delegateName.isEmpty()) { return registerDelegate( propertyMetaObject, createFunction, delegateName); } return true; } bool QtnPropertyDelegateFactory::registerDelegate( const QMetaObject *propertyMetaObject, const CreateFunction &createFunction, const QByteArray &delegateName) { Q_ASSERT(propertyMetaObject); Q_ASSERT(createFunction); Q_ASSERT(!delegateName.isEmpty()); // find or create creation record CreateItem &createItem = m_createItems[propertyMetaObject]; // register create function createItem.createFunctions[delegateName] = createFunction; return true; } bool QtnPropertyDelegateFactory::unregisterDelegate( const QMetaObject *propertyMetaObject) { Q_ASSERT(propertyMetaObject); auto it = m_createItems.find(propertyMetaObject); if (it == m_createItems.end()) return false; m_createItems.erase(it); return true; } bool QtnPropertyDelegateFactory::unregisterDelegate( const QMetaObject *propertyMetaObject, const QByteArray &delegateName) { Q_ASSERT(propertyMetaObject); Q_ASSERT(!delegateName.isEmpty()); auto it = m_createItems.find(propertyMetaObject); if (it == m_createItems.end()) return false; auto &createFunctions = it->createFunctions; auto it2 = createFunctions.find(delegateName); if (it2 == createFunctions.end()) return false; createFunctions.erase(it2); return true; } void QtnPropertyDelegateFactory::registerDefaultDelegates( QtnPropertyDelegateFactory &factory) { QtnPropertyDelegatePropertySet::Register(factory); QtnPropertyDelegateBoolCheck::Register(factory); QtnPropertyDelegateBoolCombobox::Register(factory); QtnPropertyDelegateInt::Register(factory); QtnPropertyDelegateUInt::Register(factory); QtnPropertyDelegateInt64::Register(factory); QtnPropertyDelegateUInt64::Register(factory); QtnPropertyDelegateDouble::Register(factory); QtnPropertyDelegateFloat::Register(factory); QtnPropertyDelegateEnum::Register(factory); QtnPropertyDelegateEnumFlags::Register(factory); QtnPropertyDelegateQString::Register(factory); QtnPropertyDelegateQStringFile::Register(factory); QtnPropertyDelegateQStringList::Register(factory); QtnPropertyDelegateQStringCallback::Register(factory); QtnPropertyDelegateQPoint::Register(factory); QtnPropertyDelegateQPointF::Register(factory); QtnPropertyDelegateQSize::Register(factory); QtnPropertyDelegateQSizeF::Register(factory); QtnPropertyDelegateQRect::Register(factory); QtnPropertyDelegateQRectF::Register(factory); QtnPropertyDelegateGeoCoord::Register(factory); QtnPropertyDelegateGeoPoint::Register(factory); QtnPropertyDelegateQColor::Register(factory); QtnPropertyDelegateQColorSolid::Register(factory); QtnPropertyDelegateQFont::Register(factory); QtnPropertyDelegateButton::Register(factory); QtnPropertyDelegateButtonLink::Register(factory); QtnPropertyDelegateQPenStyle::Register(factory); QtnPropertyDelegateQPen::Register(factory); QtnPropertyDelegateQBrushStyle::Register(factory); QtnPropertyDelegateQKeySequence::Register(factory); QtnMultiPropertyDelegate::Register(factory); } static QScopedPointer<QtnPropertyDelegateFactory> _staticInstance; QtnPropertyDelegateFactory &QtnPropertyDelegateFactory::staticInstance() { if (!_staticInstance) { _staticInstance.reset(new QtnPropertyDelegateFactory); registerDefaultDelegates(*_staticInstance.data()); } return *_staticInstance.data(); } void QtnPropertyDelegateFactory::resetDefaultInstance( QtnPropertyDelegateFactory *factory) { if (_staticInstance) { auto currentFactory = factory; while (currentFactory) { if (currentFactory == _staticInstance.data()) { _staticInstance.take(); break; } currentFactory = currentFactory->superFactory(); } } _staticInstance.reset(factory); } <|endoftext|>
<commit_before>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2014 Preferred Networks and Nippon Telegraph and Telephone Corporation. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License version 2.1 as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #ifndef JUBATUS_CORE_CLASSIFIER_NEAREST_NEIGHBOR_CLASSIFIER_HPP_ #define JUBATUS_CORE_CLASSIFIER_NEAREST_NEIGHBOR_CLASSIFIER_HPP_ #include <stdint.h> #include <map> #include <string> #include <vector> #include "jubatus/util/math/random.h" #include "jubatus/util/data/unordered_map.h" #include "jubatus/util/concurrent/lock.h" #include "jubatus/util/concurrent/mutex.h" #include "../common/type.hpp" #include "../nearest_neighbor/nearest_neighbor_base.hpp" #include "../unlearner/unlearner_base.hpp" #include "classifier_type.hpp" #include "classifier_base.hpp" namespace jubatus { namespace core { namespace classifier { class nearest_neighbor_classifier : public classifier_base { public: nearest_neighbor_classifier( jubatus::util::lang::shared_ptr<nearest_neighbor::nearest_neighbor_base> nearest_neighbor_engine, size_t k, float alpha); void train(const common::sfv_t& fv, const std::string& label); void set_label_unlearner( jubatus::util::lang::shared_ptr<unlearner::unlearner_base> label_unlearner); std::string classify(const common::sfv_t& fv) const; void classify_with_scores(const common::sfv_t& fv, classify_result& scores) const; bool delete_label(const std::string& label); void clear(); std::vector<std::string> get_labels() const; bool set_label(const std::string& label); std::string name() const; void get_status(std::map<std::string, std::string>& status) const; void pack(framework::packer& pk) const; void unpack(msgpack::object o); framework::mixable* get_mixable(); private: jubatus::util::lang::shared_ptr<nearest_neighbor::nearest_neighbor_base> nearest_neighbor_engine_; typedef jubatus::util::data::unordered_map<std::string, size_t> labels_t; labels_t labels_; size_t k_; float alpha_; jubatus::util::concurrent::mutex unlearner_mutex_; jubatus::util::lang::shared_ptr<unlearner::unlearner_base> unlearner_; jubatus::util::concurrent::mutex rand_mutex_; jubatus::util::math::random::mtrand rand_; mutable jubatus::util::concurrent::mutex label_mutex_; class unlearning_callback; void unlearn_id(const std::string& id); void decrement_label_counter(const std::string& label); void regenerate_label_counter(); }; } // namespace classifier } // namespace core } // namespace jubatus #endif // JUBATUS_CORE_CLASSIFIER_NEAREST_NEIGHBOR_CLASSIFIER_HPP_ <commit_msg>Add commnet about labels_<commit_after>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2014 Preferred Networks and Nippon Telegraph and Telephone Corporation. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License version 2.1 as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #ifndef JUBATUS_CORE_CLASSIFIER_NEAREST_NEIGHBOR_CLASSIFIER_HPP_ #define JUBATUS_CORE_CLASSIFIER_NEAREST_NEIGHBOR_CLASSIFIER_HPP_ #include <stdint.h> #include <map> #include <string> #include <vector> #include "jubatus/util/math/random.h" #include "jubatus/util/data/unordered_map.h" #include "jubatus/util/concurrent/lock.h" #include "jubatus/util/concurrent/mutex.h" #include "../common/type.hpp" #include "../nearest_neighbor/nearest_neighbor_base.hpp" #include "../unlearner/unlearner_base.hpp" #include "classifier_type.hpp" #include "classifier_base.hpp" namespace jubatus { namespace core { namespace classifier { class nearest_neighbor_classifier : public classifier_base { public: nearest_neighbor_classifier( jubatus::util::lang::shared_ptr<nearest_neighbor::nearest_neighbor_base> nearest_neighbor_engine, size_t k, float alpha); void train(const common::sfv_t& fv, const std::string& label); void set_label_unlearner( jubatus::util::lang::shared_ptr<unlearner::unlearner_base> label_unlearner); std::string classify(const common::sfv_t& fv) const; void classify_with_scores(const common::sfv_t& fv, classify_result& scores) const; bool delete_label(const std::string& label); void clear(); std::vector<std::string> get_labels() const; bool set_label(const std::string& label); std::string name() const; void get_status(std::map<std::string, std::string>& status) const; void pack(framework::packer& pk) const; void unpack(msgpack::object o); framework::mixable* get_mixable(); private: jubatus::util::lang::shared_ptr<nearest_neighbor::nearest_neighbor_base> nearest_neighbor_engine_; typedef jubatus::util::data::unordered_map<std::string, size_t> labels_t; // A map from label to number of records that belongs to the label. labels_t labels_; size_t k_; float alpha_; jubatus::util::concurrent::mutex unlearner_mutex_; jubatus::util::lang::shared_ptr<unlearner::unlearner_base> unlearner_; jubatus::util::concurrent::mutex rand_mutex_; jubatus::util::math::random::mtrand rand_; mutable jubatus::util::concurrent::mutex label_mutex_; class unlearning_callback; void unlearn_id(const std::string& id); void decrement_label_counter(const std::string& label); void regenerate_label_counter(); }; } // namespace classifier } // namespace core } // namespace jubatus #endif // JUBATUS_CORE_CLASSIFIER_NEAREST_NEIGHBOR_CLASSIFIER_HPP_ <|endoftext|>
<commit_before>/**************************************************************************** This file is part of the QtMediaHub project on http://www.qtmediahub.com Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).* All rights reserved. Contact: Girish Ramakrishnan girish@forwardbias.in Contact: Nokia Corporation donald.carr@nokia.com Contact: Nokia Corporation johannes.zellner@nokia.com You may use this file under the terms of the BSD license as follows: 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 Nokia Corporation and its Subsidiary(-ies) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ****************************************************************************/ #include "declarativeview.h" #include <QQuickItem> #include <QDeclarativeEngine> #include <QDebug> #include "globalsettings.h" DeclarativeView::DeclarativeView(GlobalSettings *settings, QWindow *parent) : QQuickView(parent), m_settings(settings), m_glViewport(false), m_frameCount(0), m_timeSigma(0), m_fps(0) { setResizeMode(QQuickView::SizeRootObjectToView); m_drivenFPS = m_settings->isEnabled(GlobalSettings::DrivenFPS); m_overlayMode = m_settings->isEnabled(GlobalSettings::OverlayMode); // TODO // if (Config::isEnabled("vsync-anim", false)) // setVSyncAnimations(true); connect(this, SIGNAL(statusChanged(QQuickView::Status)), this, SLOT(handleStatusChanged(QQuickView::Status))); } void DeclarativeView::setSource(const QUrl &url) { m_url = url; QMetaObject::invokeMethod(this, "handleSourceChanged", Qt::QueuedConnection); } void DeclarativeView::handleSourceChanged() { QQuickView::setSource(m_url); } void DeclarativeView::handleStatusChanged(QQuickView::Status status) { //Dodgy work around for gnome focus issues? if (status == QQuickView::Ready) { requestActivateWindow(); } } QObject *DeclarativeView::focusItem() const { return static_cast<QObject*>(activeFocusItem()); } int DeclarativeView::fps() const { return m_fps; } void DeclarativeView::addImportPath(const QString &path) { engine()->addImportPath(path); } <commit_msg>Work around scenegraph mac specific oddity<commit_after>/**************************************************************************** This file is part of the QtMediaHub project on http://www.qtmediahub.com Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).* All rights reserved. Contact: Girish Ramakrishnan girish@forwardbias.in Contact: Nokia Corporation donald.carr@nokia.com Contact: Nokia Corporation johannes.zellner@nokia.com You may use this file under the terms of the BSD license as follows: 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 Nokia Corporation and its Subsidiary(-ies) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ****************************************************************************/ #include "declarativeview.h" #include <QQuickItem> #include <QDeclarativeEngine> #include <QDebug> #include "globalsettings.h" DeclarativeView::DeclarativeView(GlobalSettings *settings, QWindow *parent) : QQuickView(parent), m_settings(settings), m_glViewport(false), m_frameCount(0), m_timeSigma(0), m_fps(0) { setResizeMode(QQuickView::SizeRootObjectToView); m_drivenFPS = m_settings->isEnabled(GlobalSettings::DrivenFPS); m_overlayMode = m_settings->isEnabled(GlobalSettings::OverlayMode); // TODO // if (Config::isEnabled("vsync-anim", false)) // setVSyncAnimations(true); connect(this, SIGNAL(statusChanged(QQuickView::Status)), this, SLOT(handleStatusChanged(QQuickView::Status))); } void DeclarativeView::setSource(const QUrl &url) { m_url = url; // This staggering is breaking SG usage on mac for some reason // QMetaObject::invokeMethod(this, "handleSourceChanged", Qt::QueuedConnection); QQuickView::setSource(url); } void DeclarativeView::handleSourceChanged() { QQuickView::setSource(m_url); } void DeclarativeView::handleStatusChanged(QQuickView::Status status) { //Dodgy work around for gnome focus issues? if (status == QQuickView::Ready) { requestActivateWindow(); } } QObject *DeclarativeView::focusItem() const { return static_cast<QObject*>(activeFocusItem()); } int DeclarativeView::fps() const { return m_fps; } void DeclarativeView::addImportPath(const QString &path) { engine()->addImportPath(path); } <|endoftext|>
<commit_before> /* * File: lambdaout.cc * Author: mayfalk * * Created on May 20, 2011, 12:21 PM */ #include <stdlib.h> #include "lambdaout.h" #include <math.h> #include <list> #include <boost/lexical_cast.hpp> #include <iostream> #include <fstream> void CalcLambdaOut::Initialize(QMTopology *top, Property *options) { _options = options; if (options->exists("options.lambda_params.lambda_method")) { if (options->get("options.lambda_params.lambda_method").as<string > () == "constant") { //_lambda_method = &CalcLambdaOut::const_lambda; if (options->exists("options.lambda_params.lambdaout")) { cout << "Thank you for choosing the constant lambda method"<<endl; _lambda_const = options->get("options.lambda_params.lambdaout").as<double>(); cout << "Using a constant lambda outer of " << _lambda_const << endl; } else { _lambda_const = 0.0; cout << "Warning: no lambda outer sphere defined, using lambdaout=0." << endl; } } else if (options->get("options.lambda_params.lambda_method").as<string > () == "spheres") { //_lambda_method = &CalcLambdaOut::spheres_lambda; cout << "Thank you for choosing the spheres lambda method"<<endl; if (options->exists("options.lambda_params.pekar")) { _pekar = options->get("options.lambda_params.pekar").as<double>(); cout << "Using a Pekar factor of " << _pekar << endl; } else { _pekar = 0.05; cout << "Warning: no Pekar factor defined, using pekar =0.05" << endl; } } else if (options->get("options.lambda_params.lambda_method").as<string > () == "dielectric") { //_lambda_method = &CalcLambdaOut::dielectric_lambda; cout << "Thank you for choosing the dielectric lambda method"<<endl; if (options->exists("options.lambda_params.pekar")) { _pekar = options->get("options.lambda_params.pekar").as<double>(); cout << "Using a Pekar factor of " << _pekar << endl; } else { _pekar = 0.05; cout << "Warning: no Pekar factor defined, using pekar =0.05" << endl; } } else throw std::runtime_error("Error in CalcLambdaOut::Initialize : no such lambda method, should be constant, spheres or dielectric"); } else throw std::runtime_error("Error in CalcLambdaOut::Initialize : no lambda method specified, should be constant, spheres or dielectric"); } bool CalcLambdaOut::EvaluateFrame(QMTopology *top) { if (_options->get("options.lambda_params.lambda_method").as<string > () == "constant") { const_lambda(top); } else if (_options->get("options.lambda_params.lambda_method").as<string > () == "spheres") { spheres_lambda(top); } else if (_options->get("options.lambda_params.lambda_method").as<string > () == "dielectric") { dielectric_lambda(top); } return true; } void CalcLambdaOut::const_lambda(QMTopology *top) { QMNBList& nblist=top->nblist(); for (QMNBList::iterator ipair = nblist.begin(); ipair != nblist.end(); ++ipair) { QMPair *pair = *ipair; QMCrgUnit *crg1 = pair->Crg1(); QMCrgUnit *crg2 = pair->Crg2(); double lambda = _lambda_const; pair->setLambdaOuter(lambda); cout << "lambda out [eV] for pair " << crg1->getId() << " and " << crg2->getId() << " is " << lambda << "\n"; } } void CalcLambdaOut::spheres_lambda(QMTopology *top) { QMNBList& nblist=top->nblist(); for (QMNBList::iterator ipair = nblist.begin(); ipair != nblist.end(); ++ipair) { QMPair *pair = *ipair; QMCrgUnit *crg1 = pair->Crg1(); QMCrgUnit *crg2 = pair->Crg2(); double R_one = crg1->getType()->getOptions()->get("R_lambda").as<double>(); double R_two = crg2->getType()->getOptions()->get("R_lambda").as<double>(); double distance = pair->dist(); double e = 1.602176487e-19; double epsilon_zero = 8.85418782e-12; double nanometer = 1.0e-09; double lambda = _pekar * e / (4.0 * M_PI * epsilon_zero)*(1.0 / (2.0 * R_one * nanometer) + 1.0 / (2.0 * R_two * nanometer) - 1.0 / (distance * nanometer)); pair->setLambdaOuter(lambda); cout << "lambda out [eV] for pair " << crg1->getId() << " and " << crg2->getId() << " is " << lambda << "\n"; } } void CalcLambdaOut::dielectric_lambda(QMTopology *top) { QMNBList& nblist=top->nblist(); for (QMNBList::iterator ipair = nblist.begin(); ipair != nblist.end(); ++ipair) { QMPair *pair = *ipair; QMCrgUnit *crg1 = pair->Crg1(); QMCrgUnit *crg2 = pair->Crg2(); double lambda = 0.0; //IS THIS THE RIGHT PLACE TO DEFINE LCHARGES AND WITH TOP NOT ATOP??? vector<QMCrgUnit *> lcharges = top->CrgUnits(); Topology atop; atop.setBox(top->getBox()); //Add the beads of charge units i and j to the atop Molecule *molcrg1 = top->AddAtomisticBeads(crg1, &atop); Molecule *molcrg2 = top->AddAtomisticBeads(crg2, &atop); //Add the rest of the beads to atop for (vector<QMCrgUnit *>::iterator itl = lcharges.begin(); itl != lcharges.end(); itl++) { if (crg1->getId() == (*itl)->getId()) continue; if (crg2->getId() == (*itl)->getId()) continue; top->AddAtomisticBeads(*itl, &atop); } //Loop over all beads exterior to crgunits i and j vec diff; for (BeadContainer::iterator ibead = atop.Beads().begin(); ibead != atop.Beads().end(); ++ibead) { Bead *bk = *ibead; //bk->getUserData<QMCrgUnit>->getId() if (bk->getMolecule()->getUserData<QMCrgUnit>()->getId() == crg1->getId()) continue; if (bk->getMolecule()->getUserData<QMCrgUnit>()->getId() == crg2->getId()) continue; double D = 0.0; //Get shortest distance to crgunit i diff = top->BCShortestConnection(crg1->GetCom(), bk->getMolecule()->getUserData<QMCrgUnit>()->GetCom()); //Loop over all bead of crgunit i for (int bi = 0; bi < molcrg1->BeadCount(); ++bi) { Bead *beadi = molcrg1->getBead(bi); //Compute deltaQ double charge_of_bead_i_charged = crg1->getType()->GetCrgUnit().getChargesCrged()->mpls[bi]; double charge_of_bead_i_neutral = crg1->getType()->GetCrgUnit().getChargesNeutr()->mpls[bi]; double delta_Q = charge_of_bead_i_neutral - charge_of_bead_i_neutral; vec r_v = bk->getPos()-(beadi->getPos() + diff); double r = abs(r_v); double r3 = r * r*r; double nanometer = 1.0e-09; double nanometer3 = 1.0e-27; D = D + delta_Q / (4.0 * M_PI * r3 * nanometer3) * r_v.getX() * nanometer; } //Get shortest distance to crgunit j diff = top->BCShortestConnection(crg2->GetCom(), bk->getMolecule()->getUserData<QMCrgUnit>()->GetCom()); //Loop over all bead of crgunit j for (int bj = 0; bj < molcrg2->BeadCount(); ++bj) { Bead *beadj = molcrg2->getBead(bj); //Compute deltaQ double charge_of_bead_j_charged = crg2->getType()->GetCrgUnit().getChargesCrged()->mpls[bj]; double charge_of_bead_j_neutral = crg2->getType()->GetCrgUnit().getChargesNeutr()->mpls[bj]; double delta_Q = charge_of_bead_j_neutral - charge_of_bead_j_neutral; vec r_v = bk->getPos()-(beadj->getPos() + diff); double nanometer = 1.0e-09; double nanometer3 = 1.0e-27; double r = abs(r_v); double r3 = r * r*r; D = D + delta_Q / (4.0 * M_PI * r3 * nanometer3) * r_v.getX() * nanometer; } double epsilon_zero = 8.85418782e-12; lambda = lambda + D * D * _pekar * atop.BeadCount() / (2.0 * epsilon_zero * atop.BoxVolume()); } pair->setLambdaOuter(lambda); cout << "lambda out [eV] for pair " << crg1->getId() << " and " << crg2->getId() << " is " << lambda << "\n"; } } <commit_msg>lambdaout runs, but the smaller values deviate from MATLAB results :-(<commit_after> /* * File: lambdaout.cc * Author: mayfalk * * Created on May 20, 2011, 12:21 PM */ #include <stdlib.h> #include "lambdaout.h" #include <math.h> #include <list> #include <boost/lexical_cast.hpp> #include <iostream> #include <fstream> void CalcLambdaOut::Initialize(QMTopology *top, Property *options) { _options = options; if (options->exists("options.lambda_params.lambda_method")) { if (options->get("options.lambda_params.lambda_method").as<string > () == "constant") { //_lambda_method = &CalcLambdaOut::const_lambda; if (options->exists("options.lambda_params.lambdaout")) { cout << "Thank you for choosing the constant lambda method"<<endl; _lambda_const = options->get("options.lambda_params.lambdaout").as<double>(); cout << "Using a constant lambda outer of " << _lambda_const << endl; } else { _lambda_const = 0.0; cout << "Warning: no lambda outer sphere defined, using lambdaout=0." << endl; } } else if (options->get("options.lambda_params.lambda_method").as<string > () == "spheres") { //_lambda_method = &CalcLambdaOut::spheres_lambda; cout << "Thank you for choosing the spheres lambda method"<<endl; if (options->exists("options.lambda_params.pekar")) { _pekar = options->get("options.lambda_params.pekar").as<double>(); cout << "Using a Pekar factor of " << _pekar << endl; } else { _pekar = 0.05; cout << "Warning: no Pekar factor defined, using pekar =0.05" << endl; } } else if (options->get("options.lambda_params.lambda_method").as<string > () == "dielectric") { //_lambda_method = &CalcLambdaOut::dielectric_lambda; cout << "Thank you for choosing the dielectric lambda method"<<endl; if (options->exists("options.lambda_params.pekar")) { _pekar = options->get("options.lambda_params.pekar").as<double>(); cout << "Using a Pekar factor of " << _pekar << endl; } else { _pekar = 0.05; cout << "Warning: no Pekar factor defined, using pekar =0.05" << endl; } } else throw std::runtime_error("Error in CalcLambdaOut::Initialize : no such lambda method, should be constant, spheres or dielectric"); } else throw std::runtime_error("Error in CalcLambdaOut::Initialize : no lambda method specified, should be constant, spheres or dielectric"); } bool CalcLambdaOut::EvaluateFrame(QMTopology *top) { if (_options->get("options.lambda_params.lambda_method").as<string > () == "constant") { const_lambda(top); } else if (_options->get("options.lambda_params.lambda_method").as<string > () == "spheres") { spheres_lambda(top); } else if (_options->get("options.lambda_params.lambda_method").as<string > () == "dielectric") { dielectric_lambda(top); } return true; } void CalcLambdaOut::const_lambda(QMTopology *top) { QMNBList& nblist=top->nblist(); for (QMNBList::iterator ipair = nblist.begin(); ipair != nblist.end(); ++ipair) { QMPair *pair = *ipair; QMCrgUnit *crg1 = pair->Crg1(); QMCrgUnit *crg2 = pair->Crg2(); double lambda = _lambda_const; pair->setLambdaOuter(lambda); cout << "lambda out [eV] for pair " << crg1->getId() << " and " << crg2->getId() << " is " << lambda << "\n"; } } void CalcLambdaOut::spheres_lambda(QMTopology *top) { QMNBList& nblist=top->nblist(); for (QMNBList::iterator ipair = nblist.begin(); ipair != nblist.end(); ++ipair) { QMPair *pair = *ipair; QMCrgUnit *crg1 = pair->Crg1(); QMCrgUnit *crg2 = pair->Crg2(); double R_one = crg1->getType()->getOptions()->get("R_lambda").as<double>(); double R_two = crg2->getType()->getOptions()->get("R_lambda").as<double>(); double distance = pair->dist(); double e = 1.602176487e-19; double epsilon_zero = 8.85418782e-12; double nanometer = 1.0e-09; double lambda = _pekar * e / (4.0 * M_PI * epsilon_zero)*(1.0 / (2.0 * R_one * nanometer) + 1.0 / (2.0 * R_two * nanometer) - 1.0 / (distance * nanometer)); pair->setLambdaOuter(lambda); cout << "lambda out [eV] for pair " << crg1->getId() << " and " << crg2->getId() << " at distance "<< distance << " is " << lambda << "\n"; } } void CalcLambdaOut::dielectric_lambda(QMTopology *top) { QMNBList& nblist=top->nblist(); for (QMNBList::iterator ipair = nblist.begin(); ipair != nblist.end(); ++ipair) { QMPair *pair = *ipair; double distance = pair->dist(); QMCrgUnit *crg1 = pair->Crg1(); QMCrgUnit *crg2 = pair->Crg2(); double lambda = 0.0; vector<QMCrgUnit *> lcharges = top->CrgUnits(); Topology atop; atop.setBox(top->getBox()); //Add the beads of charge units i and j to the atop Molecule *molcrg1 = top->AddAtomisticBeads(crg1, &atop); Molecule *molcrg2 = top->AddAtomisticBeads(crg2, &atop); //Add the rest of the beads to atop for (vector<QMCrgUnit *>::iterator itl = lcharges.begin(); itl != lcharges.end(); itl++) { if (crg1->getId() == (*itl)->getId()) continue; if (crg2->getId() == (*itl)->getId()) continue; top->AddAtomisticBeads(*itl, &atop); } //Loop over all beads exterior to crgunits i and j for (BeadContainer::iterator ibead = atop.Beads().begin(); ibead != atop.Beads().end(); ++ibead) { Bead *bk = *ibead; if (bk->getMolecule()->getUserData<QMCrgUnit>()->getId() == crg1->getId()) continue; if (bk->getMolecule()->getUserData<QMCrgUnit>()->getId() == crg2->getId()) continue; //cout << "chosen bead number:" << bk->getMolecule()->getUserData<QMCrgUnit>()->getId() << endl; double Dx = 0.0; double Dy = 0.0; double Dz = 0.0; double nanometer = 1.0e-09; double nanometer3 = 1.0e-27; double elementary_charge = 1.60217646e-19; double epsilon_zero = 8.85418782e-12; vec bcs, diff , dist; //Get shortest distance to crgunit i TOP OR ATOP??? //diff = top->BCShortestConnection(crg1->GetCom(), bk->getMolecule()->getUserData<QMCrgUnit>()->GetCom()); bcs = atop.BCShortestConnection(crg1->GetCom(), bk->getMolecule()->getUserData<QMCrgUnit>()->GetCom()); dist = bk->getMolecule()->getUserData<QMCrgUnit>()->GetCom() - crg1->GetCom(); diff = bcs - dist; //Loop over all bead of crgunit i for (int bi = 0; bi < molcrg1->BeadCount(); ++bi) { Bead *beadi = molcrg1->getBead(bi); //Compute deltaQ double charge_of_bead_i_charged = crg1->getType()->GetCrgUnit().getChargesCrged()->mpls[bi]; double charge_of_bead_i_neutral = crg1->getType()->GetCrgUnit().getChargesNeutr()->mpls[bi]; double delta_Q = charge_of_bead_i_charged - charge_of_bead_i_neutral; vec r_v = bk->getPos()-(beadi->getPos() + diff); double r = abs(r_v); double r3 = r * r * r; //cout << "delta Q:" << delta_Q << "|r3: " <<r3 << "|r_v.getX "<<r_v.getX()<<endl; Dx = Dx + elementary_charge * delta_Q / (4.0 * M_PI * r3 * nanometer3) * r_v.getX() * nanometer; Dy = Dy + elementary_charge * delta_Q / (4.0 * M_PI * r3 * nanometer3) * r_v.getY() * nanometer; Dz = Dz + elementary_charge * delta_Q / (4.0 * M_PI * r3 * nanometer3) * r_v.getZ() * nanometer; } //cout << "D due to mol i:"<<D<<endl; //Get shortest distance to crgunit j TOP OR ATOP??? //diff = top->BCShortestConnection(crg2->GetCom(), bk->getMolecule()->getUserData<QMCrgUnit>()->GetCom()); bcs = atop.BCShortestConnection(crg2->GetCom(), bk->getMolecule()->getUserData<QMCrgUnit>()->GetCom()); dist = bk->getMolecule()->getUserData<QMCrgUnit>()->GetCom() - crg2->GetCom(); diff = bcs - dist; //Loop over all bead of crgunit j for (int bj = 0; bj < molcrg2->BeadCount(); ++bj) { Bead *beadj = molcrg2->getBead(bj); //Compute deltaQ double charge_of_bead_j_charged = crg2->getType()->GetCrgUnit().getChargesCrged()->mpls[bj]; double charge_of_bead_j_neutral = crg2->getType()->GetCrgUnit().getChargesNeutr()->mpls[bj]; double delta_Q = charge_of_bead_j_neutral - charge_of_bead_j_charged; vec r_v = bk->getPos()-(beadj->getPos() + diff); double r = abs(r_v); double r3 = r * r * r; // cout << "delta Q:" << delta_Q << "|r3: " <<r3 << "|r_v.getX "<<r_v.getX()<<endl; Dx = Dx + elementary_charge * delta_Q / (4.0 * M_PI * r3 * nanometer3) * r_v.getX() * nanometer; Dy = Dy + elementary_charge * delta_Q / (4.0 * M_PI * r3 * nanometer3) * r_v.getY() * nanometer; Dz = Dz + elementary_charge * delta_Q / (4.0 * M_PI * r3 * nanometer3) * r_v.getZ() * nanometer; } //cout << "Dx :"<<Dx<<endl; cout << "Dy :"<<Dy<<endl; cout << "Dz :"<<Dz<<endl; //cout << "box volume:"<<atop.BoxVolume()<< " and beads:"<<atop.BeadCount()<<endl; lambda = lambda + (Dx*Dx+Dy*Dy+Dz*Dz) * _pekar * atop.BoxVolume()*nanometer3/atop.BeadCount() * 1/(2.0 * epsilon_zero * elementary_charge); } pair->setLambdaOuter(lambda); cout << "lambda out [eV] for pair " << crg1->getId() << " and " << crg2->getId() <<" at distance "<< distance << " is " << lambda << "\n"; } } <|endoftext|>
<commit_before>#pragma once #include "detect_type.hpp" #include "lubee/meta/enable_if.hpp" #include "lubee/none.hpp" #include "argholder.hpp" #include <utility> namespace spi { using none_t = lubee::none_t; const static none_t none; template <class... Ts> auto construct(Ts&&... ts) { return ArgHolder<decltype(ts)...>(std::forward<Ts>(ts)...); } template <class P> using IsRP = std::integral_constant<bool, std::is_reference<P>{} || std::is_pointer<P>{}>; namespace opt_tmp { template <class T> struct alignas(alignof(T)) Buffer { uint8_t _data[sizeof(T)]; Buffer() = default; template <class T2> Buffer(T2&& t) { new(ptr()) T(std::forward<T2>(t)); } T* ptr() noexcept { // Debug時は中身が有効かチェック #ifdef DEBUG #endif return reinterpret_cast<T*>(_data); } const T* ptr() const noexcept { // Debug時は中身が有効かチェック #ifdef DEBUG #endif return reinterpret_cast<const T*>(_data); } T& get() noexcept { return *ptr(); } const T& get() const noexcept { return *ptr(); } template <class... Ts> void ctor(Ts&&... ts) { new(ptr()) T(std::forward<Ts>(ts)...); } void dtor() noexcept { ptr()->~T(); } #define NOEXCEPT_WHEN_RAW(t) noexcept(noexcept(IsRP<t>{})) template <class T2> Buffer& operator = (T2&& t) NOEXCEPT_WHEN_RAW(T2) { get() = std::forward<T2>(t); return *this; } #undef NOEXCEPT_WHEN_RAW template <class Ar, class T2> friend void serialize(Ar&, Buffer<T2>&); }; template <class T> struct Buffer<T&> { T* _data; Buffer() = default; Buffer(T& t) noexcept: _data(&t) {} T* ptr() noexcept { return _data; } const T* ptr() const noexcept { return _data; } T& get() noexcept { return *ptr(); } const T& get() const noexcept { return *ptr(); } void ctor() noexcept {} void ctor(T& t) noexcept{ _data = &t; } void dtor() noexcept {} Buffer& operator = (T& t) noexcept { _data = &t; return *this; } template <class Ar, class T2> friend void serialize(Ar&, opt_tmp::Buffer<T2&>&); }; template <class T> struct Buffer<T*> { T* _data; Buffer() = default; Buffer(T* t) noexcept: _data(t) {} T* ptr() noexcept { return _data; } const T* ptr() const noexcept { return _data; } T*& get() noexcept { return _data; } T* const& get() const noexcept { return _data; } void ctor() noexcept {} void ctor(T* t) noexcept { _data = t; } void dtor() noexcept {} Buffer& operator = (T* t) noexcept { _data = t; return *this; } template <class Ar, class T2> friend void serialize(Ar&, opt_tmp::Buffer<T2*>&); }; } template <class T> class Optional { private: using value_t = T; constexpr static bool Is_RP = IsRP<T>{}; using Buffer = opt_tmp::Buffer<T>; Buffer _buffer; bool _bInit; void _force_release() noexcept { _buffer.dtor(); _bInit = false; } void _release() noexcept { if(_bInit) _force_release(); } value_t&& _takeOut() && noexcept { return std::move(get()); } const value_t& _takeOut() const& noexcept { return get(); } public: const static struct _AsInitialized{} AsInitialized; //! コンストラクタは呼ばないが初期化された物として扱う /*! ユーザーが自分でコンストラクタを呼ばないとエラーになる */ Optional(_AsInitialized) noexcept: _bInit(true) {} template <class T2, ENABLE_IF(!(is_optional<std::decay_t<T2>>{}))> Optional(T2&& v) noexcept(noexcept(!IsRP<T2>{})): _buffer(std::forward<T2>(v)), _bInit(true) {} template <class T2, ENABLE_IF((is_optional<std::decay_t<T2>>{}))> Optional(T2&& v) noexcept(noexcept(!IsRP<T2>{})) : _bInit(v._bInit) { if(_bInit) _buffer.ctor(std::forward<T2>(v)._takeOut()); } //! デフォルト初期化: 中身は無効  Optional() noexcept: _bInit(false) {} //! none_tを渡して初期化するとデフォルトと同じ挙動 Optional(none_t) noexcept: Optional() {} ~Optional() { _release(); } decltype(auto) get() & noexcept { return _buffer.get(); } decltype(auto) get() const& noexcept { return _buffer.get(); } decltype(auto) get() && noexcept { return std::move(_buffer.get()); } decltype(auto) operator * () & noexcept { return get(); } decltype(auto) operator * () const& noexcept { return get(); } decltype(auto) operator * () && noexcept { return std::move(get()); } explicit operator bool () const noexcept { return _bInit; } decltype(auto) operator -> () noexcept { return _buffer.ptr(); } decltype(auto) operator -> () const noexcept { return _buffer.ptr(); } bool operator == (const Optional& t) const noexcept { const bool b = _bInit; if(b == t._bInit) { if(b) return get() == t.get(); return true; } return false; } bool operator != (const Optional& t) const noexcept { return !(this->operator == (t)); } Optional& operator = (none_t) noexcept { _release(); return *this; } template <class T2> bool construct(std::true_type, T2&& t) { _buffer.ctor(std::forward<T2>(t)); return true; } template <class T2> bool construct(std::false_type, T2&&) { _buffer.ctor(); return false; } template < class T2, ENABLE_IF(!(is_optional<std::decay_t<T2>>{})) > Optional& operator = (T2&& t) { if(!_bInit) { _bInit = true; using CanConstruct = std::is_constructible<value_t, decltype(std::forward<T2>(t))>; if(construct(CanConstruct{}, std::forward<T2>(t))) return *this; } _buffer = std::forward<T2>(t); return *this; } template <class... Ts> Optional& operator = (ArgHolder<Ts...>&& ah) { if(_bInit) _release(); const auto fn = [&buff = _buffer](auto&&... ts) { buff.ctor(std::forward<decltype(ts)>(ts)...); }; ah.inorder(fn); _bInit = true; return *this; } template <class T2, ENABLE_IF((is_optional<std::decay_t<T2>>{}))> Optional& operator = (T2&& t) noexcept(Is_RP) { if(!t) _release(); else { _bInit = true; _buffer = std::forward<T2>(t).get(); } return *this; } template <class Ar, class T2> friend void serialize(Ar&, Optional<T2>&); }; template <class T> const typename Optional<T>::_AsInitialized Optional<T>::AsInitialized{}; } <commit_msg>Optional: move元のフラグクリアし忘れ<commit_after>#pragma once #include "detect_type.hpp" #include "lubee/meta/enable_if.hpp" #include "lubee/none.hpp" #include "argholder.hpp" #include <utility> namespace spi { using none_t = lubee::none_t; const static none_t none; template <class... Ts> auto construct(Ts&&... ts) { return ArgHolder<decltype(ts)...>(std::forward<Ts>(ts)...); } template <class P> using IsRP = std::integral_constant<bool, std::is_reference<P>{} || std::is_pointer<P>{}>; namespace opt_tmp { template <class T> struct alignas(alignof(T)) Buffer { uint8_t _data[sizeof(T)]; Buffer() = default; template <class T2> Buffer(T2&& t) { new(ptr()) T(std::forward<T2>(t)); } T* ptr() noexcept { // Debug時は中身が有効かチェック #ifdef DEBUG #endif return reinterpret_cast<T*>(_data); } const T* ptr() const noexcept { // Debug時は中身が有効かチェック #ifdef DEBUG #endif return reinterpret_cast<const T*>(_data); } T& get() noexcept { return *ptr(); } const T& get() const noexcept { return *ptr(); } template <class... Ts> void ctor(Ts&&... ts) { new(ptr()) T(std::forward<Ts>(ts)...); } void dtor() noexcept { ptr()->~T(); } #define NOEXCEPT_WHEN_RAW(t) noexcept(noexcept(IsRP<t>{})) template <class T2> Buffer& operator = (T2&& t) NOEXCEPT_WHEN_RAW(T2) { get() = std::forward<T2>(t); return *this; } #undef NOEXCEPT_WHEN_RAW template <class Ar, class T2> friend void serialize(Ar&, Buffer<T2>&); }; template <class T> struct Buffer<T&> { T* _data; Buffer() = default; Buffer(T& t) noexcept: _data(&t) {} T* ptr() noexcept { return _data; } const T* ptr() const noexcept { return _data; } T& get() noexcept { return *ptr(); } const T& get() const noexcept { return *ptr(); } void ctor() noexcept {} void ctor(T& t) noexcept{ _data = &t; } void dtor() noexcept {} Buffer& operator = (T& t) noexcept { _data = &t; return *this; } template <class Ar, class T2> friend void serialize(Ar&, opt_tmp::Buffer<T2&>&); }; template <class T> struct Buffer<T*> { T* _data; Buffer() = default; Buffer(T* t) noexcept: _data(t) {} T* ptr() noexcept { return _data; } const T* ptr() const noexcept { return _data; } T*& get() noexcept { return _data; } T* const& get() const noexcept { return _data; } void ctor() noexcept {} void ctor(T* t) noexcept { _data = t; } void dtor() noexcept {} Buffer& operator = (T* t) noexcept { _data = t; return *this; } template <class Ar, class T2> friend void serialize(Ar&, opt_tmp::Buffer<T2*>&); }; } template <class T> class Optional { private: using value_t = T; constexpr static bool Is_RP = IsRP<T>{}; using Buffer = opt_tmp::Buffer<T>; Buffer _buffer; bool _bInit; void _force_release() noexcept { _buffer.dtor(); _bInit = false; } void _release() noexcept { if(_bInit) _force_release(); } value_t&& _takeOut() && noexcept { return std::move(get()); } const value_t& _takeOut() const& noexcept { return get(); } public: const static struct _AsInitialized{} AsInitialized; //! コンストラクタは呼ばないが初期化された物として扱う /*! ユーザーが自分でコンストラクタを呼ばないとエラーになる */ Optional(_AsInitialized) noexcept: _bInit(true) {} template <class T2, ENABLE_IF(!(is_optional<std::decay_t<T2>>{}))> Optional(T2&& v) noexcept(noexcept(!IsRP<T2>{})): _buffer(std::forward<T2>(v)), _bInit(true) {} template <class T2, ENABLE_IF((is_optional<std::decay_t<T2>>{}))> Optional(T2&& v) noexcept(noexcept(!IsRP<T2>{})) : _bInit(v._bInit) { if(_bInit) { _buffer.ctor(std::forward<T2>(v)._takeOut()); v._bInit = false; } } //! デフォルト初期化: 中身は無効  Optional() noexcept: _bInit(false) {} //! none_tを渡して初期化するとデフォルトと同じ挙動 Optional(none_t) noexcept: Optional() {} ~Optional() { _release(); } decltype(auto) get() & noexcept { return _buffer.get(); } decltype(auto) get() const& noexcept { return _buffer.get(); } decltype(auto) get() && noexcept { return std::move(_buffer.get()); } decltype(auto) operator * () & noexcept { return get(); } decltype(auto) operator * () const& noexcept { return get(); } decltype(auto) operator * () && noexcept { return std::move(get()); } explicit operator bool () const noexcept { return _bInit; } decltype(auto) operator -> () noexcept { return _buffer.ptr(); } decltype(auto) operator -> () const noexcept { return _buffer.ptr(); } bool operator == (const Optional& t) const noexcept { const bool b = _bInit; if(b == t._bInit) { if(b) return get() == t.get(); return true; } return false; } bool operator != (const Optional& t) const noexcept { return !(this->operator == (t)); } Optional& operator = (none_t) noexcept { _release(); return *this; } template <class T2> bool construct(std::true_type, T2&& t) { _buffer.ctor(std::forward<T2>(t)); return true; } template <class T2> bool construct(std::false_type, T2&&) { _buffer.ctor(); return false; } template < class T2, ENABLE_IF(!(is_optional<std::decay_t<T2>>{})) > Optional& operator = (T2&& t) { if(!_bInit) { _bInit = true; using CanConstruct = std::is_constructible<value_t, decltype(std::forward<T2>(t))>; if(construct(CanConstruct{}, std::forward<T2>(t))) return *this; } _buffer = std::forward<T2>(t); return *this; } template <class... Ts> Optional& operator = (ArgHolder<Ts...>&& ah) { if(_bInit) _release(); const auto fn = [&buff = _buffer](auto&&... ts) { buff.ctor(std::forward<decltype(ts)>(ts)...); }; ah.inorder(fn); _bInit = true; return *this; } template <class T2, ENABLE_IF((is_optional<std::decay_t<T2>>{}))> Optional& operator = (T2&& t) noexcept(Is_RP) { if(!t) _release(); else { _bInit = true; _buffer = std::forward<T2>(t).get(); } return *this; } template <class Ar, class T2> friend void serialize(Ar&, Optional<T2>&); }; template <class T> const typename Optional<T>::_AsInitialized Optional<T>::AsInitialized{}; } <|endoftext|>
<commit_before>/* * Copyright (C) 2010-2011 Dmitry Marakasov * * This file is part of glosm. * * glosm 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. * * glosm 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 glosm. If not, see <http://www.gnu.org/licenses/>. */ #include <glosm/TileManager.hh> #include <glosm/Viewer.hh> #include <glosm/Geometry.hh> #include <glosm/GeometryDatasource.hh> #include <glosm/Tile.hh> #include <glosm/Exception.hh> #if defined(__APPLE__) # include <OpenGL/gl.h> #else # include <GL/gl.h> #endif #include <cassert> TileManager::TileId::TileId(int lev, int xx, int yy) : level(lev), x(xx), y(yy) { } bool TileManager::TileId::operator<(const TileId& other) const { if (level < other.level) return true; if (level > other.level) return false; if (x < other.x) return true; if (x > other.x) return false; return y < other.y; } TileManager::TileManager(const Projection projection): projection_(projection) { int errn; if ((errn = pthread_mutex_init(&tiles_mutex_, 0)) != 0) throw SystemError(errn) << "pthread_mutex_init failed"; if ((errn = pthread_mutex_init(&queue_mutex_, 0)) != 0) { pthread_mutex_destroy(&tiles_mutex_); throw SystemError(errn) << "pthread_mutex_init failed"; } if ((errn = pthread_cond_init(&queue_cond_, 0)) != 0) { pthread_mutex_destroy(&tiles_mutex_); pthread_mutex_destroy(&queue_mutex_); throw SystemError(errn) << "pthread_cond_init failed"; } if ((errn = pthread_create(&loading_thread_, NULL, LoadingThreadFuncWrapper, (void*)this)) != 0) { pthread_mutex_destroy(&tiles_mutex_); pthread_mutex_destroy(&queue_mutex_); pthread_cond_destroy(&queue_cond_); throw SystemError(errn) << "pthread_create failed"; } target_level_ = 0; generation_ = 0; thread_die_flag_ = false; } TileManager::~TileManager() { thread_die_flag_ = true; pthread_cond_signal(&queue_cond_); pthread_join(loading_thread_, NULL); pthread_cond_destroy(&queue_cond_); pthread_mutex_destroy(&queue_mutex_); pthread_mutex_destroy(&tiles_mutex_); for (TilesMap::iterator i = tiles_.begin(); i != tiles_.end(); ++i) delete i->second.tile; } int TileManager::LoadTile(const TileId& id, const BBoxi& bbox, int flags) { int ret = 0; if (flags & SYNC) { Tile* tile = SpawnTile(bbox); /* TODO: we may call tile->BindBuffers here */ tiles_.insert(std::make_pair(id, TileData(tile, generation_))); } else { bool added = false; pthread_mutex_lock(&queue_mutex_); if (loading_.find(id) == loading_.end()) { added = true; queue_.push_back(TileTask(id, bbox)); } ret = queue_.size(); pthread_mutex_unlock(&queue_mutex_); if (added) pthread_cond_signal(&queue_cond_); } return ret; } /* * recursive quadtree processing */ bool TileManager::LoadTiles(const BBoxi& bbox, int flags, int level, int x, int y) { if (level == target_level_) { TilesMap::iterator thistile = tiles_.find(TileId(level, x, y)); if (thistile != tiles_.end()) { thistile->second.generation = generation_; return true; /* tile already loaded */ } BBoxi bbox = BBoxi::ForGeoTile(level, x, y); /* since we expect tile loading to be longer than * on frame rendering time, limit queue length * TODO: this should be user-settable or depend on * # of threads. */ if (LoadTile(TileId(level, x, y), BBoxi::ForGeoTile(level, x, y), flags) >= 2) return false; /* no deeper recursion */ return true; } /* children */ for (int d = 0; d < 4; ++d) { int xx = x * 2 + d % 2; int yy = y * 2 + d / 2; if (BBoxi::ForGeoTile(level + 1, xx, yy).Intersects(bbox)) { if (!LoadTiles(bbox, flags, level + 1, xx, yy)) return false; } } return true; } /* * loading queue - related */ void TileManager::LoadingThreadFunc() { pthread_mutex_lock(&queue_mutex_); while (!thread_die_flag_) { /* found nothing, sleep */ if (queue_.empty()) { pthread_cond_wait(&queue_cond_, &queue_mutex_); continue; } /* take a task from the queue */ TileTask task = queue_.front(); queue_.pop_front(); /* mark it as loading */ std::pair<LoadingSet::iterator, bool> pair = loading_.insert(task.id); assert(pair.second); pthread_mutex_unlock(&queue_mutex_); /* load tile */ Tile* tile = SpawnTile(task.bbox); pthread_mutex_lock(&tiles_mutex_); tiles_.insert(std::make_pair(task.id, TileData(tile, generation_))); pthread_mutex_unlock(&tiles_mutex_); pthread_mutex_lock(&queue_mutex_); loading_.erase(pair.first); } pthread_mutex_unlock(&queue_mutex_); } void* TileManager::LoadingThreadFuncWrapper(void* arg) { static_cast<TileManager*>(arg)->LoadingThreadFunc(); return NULL; } /* * protected interface */ void TileManager::Render(const Viewer& viewer) { pthread_mutex_lock(&tiles_mutex_); /* and render them */ for (TilesMap::iterator i = tiles_.begin(); i != tiles_.end(); ++i) { if (i->second.generation != generation_) continue; glMatrixMode(GL_MODELVIEW); glPushMatrix(); /* prepare modelview matrix for the tile: position * it in the right place given that viewer is always * at (0, 0, 0) */ Vector3f offset = projection_.Project(i->second.tile->GetReference(), Vector2i(viewer.GetPos(projection_))) + projection_.Project(Vector2i(viewer.GetPos(projection_)), viewer.GetPos(projection_)); glTranslatef(offset.x, offset.y, offset.z); /* same for rotation */ Vector3i ref = i->second.tile->GetReference(); Vector3i pos = viewer.GetPos(projection_); /* normal at tile's reference point */ Vector3d refnormal = ( (Vector3d)projection_.Project(Vector3i(ref.x, ref.y, std::numeric_limits<osmint_t>::max()), pos) - (Vector3d)projection_.Project(Vector3i(ref.x, ref.y, 0), pos) ).Normalized(); /* normal at reference point projected to equator */ Vector3d refeqnormal = ( (Vector3d)projection_.Project(Vector3i(ref.x, 0, std::numeric_limits<osmint_t>::max()), pos) - (Vector3d)projection_.Project(Vector3i(ref.x, 0, 0), pos) ).Normalized(); /* normal at north pole */ Vector3d polenormal = ( (Vector3d)projection_.Project(Vector3i(ref.x, 900000000, std::numeric_limits<osmint_t>::max()), pos) - (Vector3d)projection_.Project(Vector3i(ref.x, 900000000, 0), pos) ).Normalized(); /* XXX: IsValid() check basically detects * MercatorProjection and does no rotation for it. * While is's ok for now, this may need more generic * approach in future */ if (polenormal.IsValid()) { Vector3d side = refnormal.CrossProduct(polenormal).Normalized(); glRotatef((double)((osmlong_t)ref.y - (osmlong_t)pos.y) / 10000000.0, side.x, side.y, side.z); glRotatef((double)((osmlong_t)ref.x - (osmlong_t)pos.x) / 10000000.0, polenormal.x, polenormal.y, polenormal.z); } i->second.tile->Render(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); } pthread_mutex_unlock(&tiles_mutex_); } /* * public interface */ void TileManager::SetTargetLevel(int level) { target_level_ = level; } void TileManager::RequestVisible(const BBoxi& bbox, int flags) { if (!flags & SYNC) { pthread_mutex_lock(&queue_mutex_); queue_.clear(); pthread_mutex_unlock(&queue_mutex_); } pthread_mutex_lock(&tiles_mutex_); if (flags & BLOB) LoadTile(TileId(0, 0, 0), bbox, flags); else LoadTiles(bbox, flags); pthread_mutex_unlock(&tiles_mutex_); } void TileManager::GarbageCollect() { /* TODO: may put deletable tiles into list and delete after * unlocking mutex for less contention */ pthread_mutex_lock(&tiles_mutex_); for (TilesMap::iterator i = tiles_.begin(); i != tiles_.end(); ) { if (i->second.generation != generation_) { delete i->second.tile; TilesMap::iterator tmp = i++; tiles_.erase(tmp); } else { i++; } } generation_++; pthread_mutex_unlock(&tiles_mutex_); } <commit_msg>Fix generation bumping<commit_after>/* * Copyright (C) 2010-2011 Dmitry Marakasov * * This file is part of glosm. * * glosm 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. * * glosm 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 glosm. If not, see <http://www.gnu.org/licenses/>. */ #include <glosm/TileManager.hh> #include <glosm/Viewer.hh> #include <glosm/Geometry.hh> #include <glosm/GeometryDatasource.hh> #include <glosm/Tile.hh> #include <glosm/Exception.hh> #if defined(__APPLE__) # include <OpenGL/gl.h> #else # include <GL/gl.h> #endif #include <cassert> TileManager::TileId::TileId(int lev, int xx, int yy) : level(lev), x(xx), y(yy) { } bool TileManager::TileId::operator<(const TileId& other) const { if (level < other.level) return true; if (level > other.level) return false; if (x < other.x) return true; if (x > other.x) return false; return y < other.y; } TileManager::TileManager(const Projection projection): projection_(projection) { int errn; if ((errn = pthread_mutex_init(&tiles_mutex_, 0)) != 0) throw SystemError(errn) << "pthread_mutex_init failed"; if ((errn = pthread_mutex_init(&queue_mutex_, 0)) != 0) { pthread_mutex_destroy(&tiles_mutex_); throw SystemError(errn) << "pthread_mutex_init failed"; } if ((errn = pthread_cond_init(&queue_cond_, 0)) != 0) { pthread_mutex_destroy(&tiles_mutex_); pthread_mutex_destroy(&queue_mutex_); throw SystemError(errn) << "pthread_cond_init failed"; } if ((errn = pthread_create(&loading_thread_, NULL, LoadingThreadFuncWrapper, (void*)this)) != 0) { pthread_mutex_destroy(&tiles_mutex_); pthread_mutex_destroy(&queue_mutex_); pthread_cond_destroy(&queue_cond_); throw SystemError(errn) << "pthread_create failed"; } target_level_ = 0; generation_ = 0; thread_die_flag_ = false; } TileManager::~TileManager() { thread_die_flag_ = true; pthread_cond_signal(&queue_cond_); pthread_join(loading_thread_, NULL); pthread_cond_destroy(&queue_cond_); pthread_mutex_destroy(&queue_mutex_); pthread_mutex_destroy(&tiles_mutex_); for (TilesMap::iterator i = tiles_.begin(); i != tiles_.end(); ++i) delete i->second.tile; } int TileManager::LoadTile(const TileId& id, const BBoxi& bbox, int flags) { int ret = 0; if (flags & SYNC) { Tile* tile = SpawnTile(bbox); /* TODO: we may call tile->BindBuffers here */ tiles_.insert(std::make_pair(id, TileData(tile, generation_))); } else { bool added = false; pthread_mutex_lock(&queue_mutex_); /* don't needlessly enqueue more tiles that we can process in a frame time*/ /* TODO: this should be user-settable, as we don't necessarily do GC/loading * every frame */ if (loading_.find(id) == loading_.end() && queue.size() < 2) { added = true; queue_.push_back(TileTask(id, bbox)); } ret = queue_.size(); pthread_mutex_unlock(&queue_mutex_); if (added) pthread_cond_signal(&queue_cond_); } return ret; } /* * recursive quadtree processing */ bool TileManager::LoadTiles(const BBoxi& bbox, int flags, int level, int x, int y) { if (level == target_level_) { TilesMap::iterator thistile = tiles_.find(TileId(level, x, y)); if (thistile != tiles_.end()) { thistile->second.generation = generation_; return true; /* tile already loaded */ } BBoxi bbox = BBoxi::ForGeoTile(level, x, y); LoadTile(TileId(level, x, y), BBoxi::ForGeoTile(level, x, y), flags); /* no deeper recursion */ return true; } /* children */ for (int d = 0; d < 4; ++d) { int xx = x * 2 + d % 2; int yy = y * 2 + d / 2; if (BBoxi::ForGeoTile(level + 1, xx, yy).Intersects(bbox)) { if (!LoadTiles(bbox, flags, level + 1, xx, yy)) return false; } } return true; } /* * loading queue - related */ void TileManager::LoadingThreadFunc() { pthread_mutex_lock(&queue_mutex_); while (!thread_die_flag_) { /* found nothing, sleep */ if (queue_.empty()) { pthread_cond_wait(&queue_cond_, &queue_mutex_); continue; } /* take a task from the queue */ TileTask task = queue_.front(); queue_.pop_front(); /* mark it as loading */ std::pair<LoadingSet::iterator, bool> pair = loading_.insert(task.id); assert(pair.second); pthread_mutex_unlock(&queue_mutex_); /* load tile */ Tile* tile = SpawnTile(task.bbox); pthread_mutex_lock(&tiles_mutex_); tiles_.insert(std::make_pair(task.id, TileData(tile, generation_))); pthread_mutex_unlock(&tiles_mutex_); pthread_mutex_lock(&queue_mutex_); loading_.erase(pair.first); } pthread_mutex_unlock(&queue_mutex_); } void* TileManager::LoadingThreadFuncWrapper(void* arg) { static_cast<TileManager*>(arg)->LoadingThreadFunc(); return NULL; } /* * protected interface */ void TileManager::Render(const Viewer& viewer) { pthread_mutex_lock(&tiles_mutex_); /* and render them */ for (TilesMap::iterator i = tiles_.begin(); i != tiles_.end(); ++i) { if (i->second.generation != generation_) continue; glMatrixMode(GL_MODELVIEW); glPushMatrix(); /* prepare modelview matrix for the tile: position * it in the right place given that viewer is always * at (0, 0, 0) */ Vector3f offset = projection_.Project(i->second.tile->GetReference(), Vector2i(viewer.GetPos(projection_))) + projection_.Project(Vector2i(viewer.GetPos(projection_)), viewer.GetPos(projection_)); glTranslatef(offset.x, offset.y, offset.z); /* same for rotation */ Vector3i ref = i->second.tile->GetReference(); Vector3i pos = viewer.GetPos(projection_); /* normal at tile's reference point */ Vector3d refnormal = ( (Vector3d)projection_.Project(Vector3i(ref.x, ref.y, std::numeric_limits<osmint_t>::max()), pos) - (Vector3d)projection_.Project(Vector3i(ref.x, ref.y, 0), pos) ).Normalized(); /* normal at reference point projected to equator */ Vector3d refeqnormal = ( (Vector3d)projection_.Project(Vector3i(ref.x, 0, std::numeric_limits<osmint_t>::max()), pos) - (Vector3d)projection_.Project(Vector3i(ref.x, 0, 0), pos) ).Normalized(); /* normal at north pole */ Vector3d polenormal = ( (Vector3d)projection_.Project(Vector3i(ref.x, 900000000, std::numeric_limits<osmint_t>::max()), pos) - (Vector3d)projection_.Project(Vector3i(ref.x, 900000000, 0), pos) ).Normalized(); /* XXX: IsValid() check basically detects * MercatorProjection and does no rotation for it. * While is's ok for now, this may need more generic * approach in future */ if (polenormal.IsValid()) { Vector3d side = refnormal.CrossProduct(polenormal).Normalized(); glRotatef((double)((osmlong_t)ref.y - (osmlong_t)pos.y) / 10000000.0, side.x, side.y, side.z); glRotatef((double)((osmlong_t)ref.x - (osmlong_t)pos.x) / 10000000.0, polenormal.x, polenormal.y, polenormal.z); } i->second.tile->Render(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); } pthread_mutex_unlock(&tiles_mutex_); } /* * public interface */ void TileManager::SetTargetLevel(int level) { target_level_ = level; } void TileManager::RequestVisible(const BBoxi& bbox, int flags) { if (!flags & SYNC) { pthread_mutex_lock(&queue_mutex_); queue_.clear(); pthread_mutex_unlock(&queue_mutex_); } pthread_mutex_lock(&tiles_mutex_); if (flags & BLOB) LoadTile(TileId(0, 0, 0), bbox, flags); else LoadTiles(bbox, flags); pthread_mutex_unlock(&tiles_mutex_); } void TileManager::GarbageCollect() { /* TODO: may put deletable tiles into list and delete after * unlocking mutex for less contention */ pthread_mutex_lock(&tiles_mutex_); for (TilesMap::iterator i = tiles_.begin(); i != tiles_.end(); ) { if (i->second.generation != generation_) { delete i->second.tile; TilesMap::iterator tmp = i++; tiles_.erase(tmp); } else { i++; } } generation_++; pthread_mutex_unlock(&tiles_mutex_); } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include "rasterlite_featureset.hpp" // mapnik #include <mapnik/debug.hpp> #include <mapnik/image_data.hpp> #include <mapnik/image_util.hpp> #include <mapnik/query.hpp> #include <mapnik/raster.hpp> #include <mapnik/feature.hpp> #include <mapnik/feature_factory.hpp> #include <cstring> using mapnik::coord2d; using mapnik::box2d; using mapnik::feature_ptr; using mapnik::geometry_type; using mapnik::query; using mapnik::feature_factory; rasterlite_featureset::rasterlite_featureset(void* dataset, rasterlite_query q) : dataset_(dataset), gquery_(q), first_(true), ctx_(std::make_shared<mapnik::context_type>()) { rasterliteSetBackgroundColor(dataset_, 255, 0, 255); rasterliteSetTransparentColor(dataset_, 255, 0, 255); } rasterlite_featureset::~rasterlite_featureset() { MAPNIK_LOG_DEBUG(rasterlite) << "rasterlite_featureset: Closing"; rasterliteClose(dataset_); } feature_ptr rasterlite_featureset::next() { if (first_) { first_ = false; MAPNIK_LOG_DEBUG(gdal) << "rasterlite_featureset: Next feature in Dataset=" << &dataset_; return mapnik::util::apply_visitor(query_dispatch(*this), gquery_); } return feature_ptr(); } feature_ptr rasterlite_featureset::get_feature(mapnik::query const& q) { MAPNIK_LOG_DEBUG(rasterlite) << "rasterlite_featureset: Running get_feature"; feature_ptr feature(feature_factory::create(ctx_,1)); double x0, y0, x1, y1; rasterliteGetExtent (dataset_, &x0, &y0, &x1, &y1); box2d<double> raster_extent(x0, y0, x1, y1); box2d<double> intersect = raster_extent.intersect(q.get_bbox()); const int width = static_cast<int>(std::get<0>(q.resolution()) * intersect.width() + 0.5); const int height = static_cast<int>(std::get<0>(q.resolution()) * intersect.height() + 0.5); const double pixel_size = (intersect.width() >= intersect.height()) ? (intersect.width() / (double) width) : (intersect.height() / (double) height); MAPNIK_LOG_DEBUG(rasterlite) << "rasterlite_featureset: Raster extent=" << raster_extent; MAPNIK_LOG_DEBUG(rasterlite) << "rasterlite_featureset: View extent=" << q.get_bbox(); MAPNIK_LOG_DEBUG(rasterlite) << "rasterlite_featureset: Intersect extent=" << intersect; MAPNIK_LOG_DEBUG(rasterlite) << "rasterlite_featureset: Query resolution=" << std::get<0>(q.resolution()) << "," << std::get<1>(q.resolution()); MAPNIK_LOG_DEBUG(rasterlite) << "rasterlite_featureset: Size=" << width << " " << height; MAPNIK_LOG_DEBUG(rasterlite) << "rasterlite_featureset: Pixel Size=" << pixel_size; if (width > 0 && height > 0) { int size = 0; void* raster = 0; if (rasterliteGetRawImageByRect(dataset_, intersect.minx(), intersect.miny(), intersect.maxx(), intersect.maxy(), pixel_size, width, height, GAIA_RGBA_ARRAY, &raster, &size) == RASTERLITE_OK) { if (size > 0) { mapnik::image_data_rgba8 image(width,height); unsigned char* raster_data = static_cast<unsigned char*>(raster); unsigned char* image_data = image.getBytes(); std::memcpy(image_data, raster_data, size); feature->set_raster(std::make_shared<mapnik::raster>(intersect, std::move(image), 1.0)); MAPNIK_LOG_DEBUG(rasterlite) << "rasterlite_featureset: Done"; } else { MAPNIK_LOG_DEBUG(rasterlite) << "Rasterlite Plugin: Error " << rasterliteGetLastError (dataset_); } } return feature; } return feature_ptr(); } feature_ptr rasterlite_featureset::get_feature_at_point(mapnik::coord2d const& pt) { return feature_ptr(); } <commit_msg>enable rasterlite error again, accidentally disabled in 62dbfea<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include "rasterlite_featureset.hpp" // mapnik #include <mapnik/debug.hpp> #include <mapnik/image_data.hpp> #include <mapnik/image_util.hpp> #include <mapnik/query.hpp> #include <mapnik/raster.hpp> #include <mapnik/feature.hpp> #include <mapnik/feature_factory.hpp> #include <cstring> using mapnik::coord2d; using mapnik::box2d; using mapnik::feature_ptr; using mapnik::geometry_type; using mapnik::query; using mapnik::feature_factory; rasterlite_featureset::rasterlite_featureset(void* dataset, rasterlite_query q) : dataset_(dataset), gquery_(q), first_(true), ctx_(std::make_shared<mapnik::context_type>()) { rasterliteSetBackgroundColor(dataset_, 255, 0, 255); rasterliteSetTransparentColor(dataset_, 255, 0, 255); } rasterlite_featureset::~rasterlite_featureset() { MAPNIK_LOG_DEBUG(rasterlite) << "rasterlite_featureset: Closing"; rasterliteClose(dataset_); } feature_ptr rasterlite_featureset::next() { if (first_) { first_ = false; MAPNIK_LOG_DEBUG(gdal) << "rasterlite_featureset: Next feature in Dataset=" << &dataset_; return mapnik::util::apply_visitor(query_dispatch(*this), gquery_); } return feature_ptr(); } feature_ptr rasterlite_featureset::get_feature(mapnik::query const& q) { MAPNIK_LOG_DEBUG(rasterlite) << "rasterlite_featureset: Running get_feature"; feature_ptr feature(feature_factory::create(ctx_,1)); double x0, y0, x1, y1; rasterliteGetExtent (dataset_, &x0, &y0, &x1, &y1); box2d<double> raster_extent(x0, y0, x1, y1); box2d<double> intersect = raster_extent.intersect(q.get_bbox()); const int width = static_cast<int>(std::get<0>(q.resolution()) * intersect.width() + 0.5); const int height = static_cast<int>(std::get<0>(q.resolution()) * intersect.height() + 0.5); const double pixel_size = (intersect.width() >= intersect.height()) ? (intersect.width() / (double) width) : (intersect.height() / (double) height); MAPNIK_LOG_DEBUG(rasterlite) << "rasterlite_featureset: Raster extent=" << raster_extent; MAPNIK_LOG_DEBUG(rasterlite) << "rasterlite_featureset: View extent=" << q.get_bbox(); MAPNIK_LOG_DEBUG(rasterlite) << "rasterlite_featureset: Intersect extent=" << intersect; MAPNIK_LOG_DEBUG(rasterlite) << "rasterlite_featureset: Query resolution=" << std::get<0>(q.resolution()) << "," << std::get<1>(q.resolution()); MAPNIK_LOG_DEBUG(rasterlite) << "rasterlite_featureset: Size=" << width << " " << height; MAPNIK_LOG_DEBUG(rasterlite) << "rasterlite_featureset: Pixel Size=" << pixel_size; if (width > 0 && height > 0) { int size = 0; void* raster = 0; if (rasterliteGetRawImageByRect(dataset_, intersect.minx(), intersect.miny(), intersect.maxx(), intersect.maxy(), pixel_size, width, height, GAIA_RGBA_ARRAY, &raster, &size) == RASTERLITE_OK) { if (size > 0) { mapnik::image_data_rgba8 image(width,height); unsigned char* raster_data = static_cast<unsigned char*>(raster); unsigned char* image_data = image.getBytes(); std::memcpy(image_data, raster_data, size); feature->set_raster(std::make_shared<mapnik::raster>(intersect, std::move(image), 1.0)); MAPNIK_LOG_DEBUG(rasterlite) << "rasterlite_featureset: Done"; } else { MAPNIK_LOG_ERROR(rasterlite) << "Rasterlite Plugin: Error " << rasterliteGetLastError (dataset_); } } return feature; } return feature_ptr(); } feature_ptr rasterlite_featureset::get_feature_at_point(mapnik::coord2d const& pt) { return feature_ptr(); } <|endoftext|>
<commit_before>/* kopeteaccountmanager.cpp - Kopete Account Manager Copyright (c) 2002 by Martijn Klingens <klingens@kde.org> Copyright (c) 2003 by Olivier Goffart <ogoffart@tiscalinet.be> Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include "kopeteaccountmanager.h" #include <qapplication.h> #include <qstylesheet.h> #include <qdom.h> #include <qfile.h> #include <kdebug.h> #include <ksavefile.h> #include <kstandarddirs.h> #include "kopeteaway.h" #include "kopeteprotocol.h" #include "pluginloader.h" #include "kopeteaccount.h" KopeteAccountManager* KopeteAccountManager::s_manager = 0L; KopeteAccountManager* KopeteAccountManager::manager() { if( !s_manager ) s_manager = new KopeteAccountManager; return s_manager; } KopeteAccountManager::KopeteAccountManager() : QObject( qApp, "KopeteAccountManager" ) { } KopeteAccountManager::~KopeteAccountManager() { s_manager = 0L; } void KopeteAccountManager::connectAll() { for(KopeteAccount *i=m_accounts.first() ; i; i=m_accounts.next() ) { i->connect(); } //------ OBSOLETE QPtrList<KopetePlugin> plugins = LibraryLoader::pluginLoader()->plugins(); for( KopetePlugin *p = plugins.first() ; p ; p = plugins.next() ) { KopeteProtocol *proto = dynamic_cast<KopeteProtocol*>( p ); if( !proto ) continue; if( !proto->isConnected() ) { kdDebug(14010) << "KopeteAccountManager::connectAll: " << "Connecting plugin: " << proto->pluginId() << endl; proto->connect(); } } } void KopeteAccountManager::disconnectAll() { for(KopeteAccount *i=m_accounts.first() ; i; i=m_accounts.next() ) { i->disconnect(); } //------ OBSOLETE QPtrList<KopetePlugin> plugins = LibraryLoader::pluginLoader()->plugins(); for( KopetePlugin *p = plugins.first() ; p ; p = plugins.next() ) { KopeteProtocol *proto = dynamic_cast<KopeteProtocol*>( p ); if( !proto ) continue; if( proto->isConnected() ) { kdDebug(14010) << "KopeteAccountManager::disconnectAll: " << "Disonnecting plugin: " << proto->pluginId() << endl; proto->disconnect(); } } } void KopeteAccountManager::setAwayAll() { KopeteAway::setGlobalAway( true ); for(KopeteAccount *i=m_accounts.first() ; i; i=m_accounts.next() ) { if(i->isConnected() && !i->isAway()) i->setAway(true); } //------ OBSOLETE QPtrList<KopetePlugin> plugins = LibraryLoader::pluginLoader()->plugins(); for( KopetePlugin *p = plugins.first() ; p ; p = plugins.next() ) { KopeteProtocol *proto = dynamic_cast<KopeteProtocol*>( p ); if( !proto ) continue; if( proto->isConnected() && !proto->isAway() ) { kdDebug(14010) << "KopeteAccountManager::setAwayAll: " << "Setting plugin to away: " << proto->pluginId() << endl; proto->setAway(); } } } void KopeteAccountManager::setAvailableAll() { KopeteAway::setGlobalAway( false ); for(KopeteAccount *i=m_accounts.first() ; i; i=m_accounts.next() ) { if(i->isConnected() && i->isAway()) i->setAway(false); } //------ OBSOLETE QPtrList<KopetePlugin> plugins = LibraryLoader::pluginLoader()->plugins(); for( KopetePlugin *p = plugins.first() ; p ; p = plugins.next() ) { KopeteProtocol *proto = dynamic_cast<KopeteProtocol*>( p ); if( !proto ) continue; if( proto->isConnected() && proto->isAway() ) { kdDebug(14010) << "KopeteAccountManager::setAvailableAll: " << "Setting plugin to available: " << proto->pluginId() << endl; proto->setAvailable(); } } } void KopeteAccountManager::registerAccount(KopeteAccount *i) { m_accounts.append( i ); } const QPtrList<KopeteAccount>& KopeteAccountManager::accounts() const { return m_accounts; } QDict<KopeteAccount> KopeteAccountManager::accounts(const KopeteProtocol *p) { QDict<KopeteAccount> dict; for(KopeteAccount *i=m_accounts.first() ; i; i=m_accounts.next() ) { if(i->protocol() == p) dict.insert(i->accountId() , i); } return dict; } KopeteAccount* KopeteAccountManager::findAccount(const QString& protocolId, const QString& accountId) { for(KopeteAccount *i=m_accounts.first() ; i; i=m_accounts.next() ) { if( i->protocol()->pluginId() == protocolId && i->accountId() == accountId ) return i; } return 0L; } void KopeteAccountManager::unregisterAccount( KopeteAccount *account ) { m_accounts.remove( account ); } void KopeteAccountManager::save() { QString fileName = locateLocal( "appdata", QString::fromLatin1( "accounts.xml" ) ); KSaveFile file( fileName ); if( file.status() == 0 ) { QTextStream *stream = file.textStream(); stream->setEncoding( QTextStream::UnicodeUTF8 ); QString xml = QString::fromLatin1("<?xml version=\"1.0\"?>\n" "<!DOCTYPE kopete-accounts>\n" "<kopete-accounts version=\"1.0\">\n" ); for(KopeteAccount *i=m_accounts.first() ; i; i=m_accounts.next() ) { xml += i->toXML(); } xml += QString::fromLatin1( "</kopete-accounts>\n" ); *stream << xml; if ( !file.close() ) { kdDebug(14010) << "KopeteAccountManager::save: ERROR: failed to write accounts, error code is: " << file.status() << endl; } } else { kdWarning(14010) << "KopeteAccountManager::save: ERROR: Couldn't open accounts file " << fileName << " accounts not saved." << endl; } } void KopeteAccountManager::load() { QString filename = locateLocal( "appdata", QString::fromLatin1( "accounts.xml" ) ); if( filename.isEmpty() ) return ; kdDebug(14010) << k_funcinfo <<endl; m_accountList = QDomDocument( QString::fromLatin1( "kopete-accounts" ) ); QFile file( filename ); file.open( IO_ReadOnly ); m_accountList.setContent( &file ); file.close(); connect( LibraryLoader::pluginLoader(), SIGNAL( pluginLoaded(KopetePlugin*) ), this, SLOT( loadProtocol(KopetePlugin*) ) ); } void KopeteAccountManager::loadProtocol( KopetePlugin *plu ) { KopeteProtocol* protocol=dynamic_cast<KopeteProtocol*>(plu); if(!protocol) return; kdDebug(14010) << k_funcinfo <<endl; QDomNode node = m_accountList.documentElement().firstChild(); while( !node.isNull() ) { QDomElement element = node.toElement(); if( !element.isNull() ) { if( element.tagName() == QString::fromLatin1("account") ) { QString accountId = element.attribute( QString::fromLatin1("account-id"), QString::null ); QString protocolId = element.attribute( QString::fromLatin1("protocol-id"), QString::null ); if( protocolId == protocol->pluginId() ) { KopeteAccount *account = protocol->createNewAccount(accountId); QDomNode accountNode = node.firstChild(); if (account && !account->fromXML( accountNode ) ) { delete account; account = 0L; } } } else { kdWarning(14010) << k_funcinfo << "Unknown element '" << element.tagName() << "' in contact list!" << endl; } } node = node.nextSibling(); } } void KopeteAccountManager::autoConnect() { for(KopeteAccount *i=m_accounts.first() ; i; i=m_accounts.next() ) { if(i->autoLogin()) i->connect(); } } #include "kopeteaccountmanager.moc" // vim: set noet ts=4 sts=4 sw=4: <commit_msg><commit_after>/* kopeteaccountmanager.cpp - Kopete Account Manager Copyright (c) 2002 by Martijn Klingens <klingens@kde.org> Copyright (c) 2003 by Olivier Goffart <ogoffart@tiscalinet.be> Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include "kopeteaccountmanager.h" #include <qapplication.h> #include <qstylesheet.h> #include <qdom.h> #include <qfile.h> #include <kdebug.h> #include <ksavefile.h> #include <kstandarddirs.h> #include "kopeteaway.h" #include "kopeteprotocol.h" #include "pluginloader.h" #include "kopeteaccount.h" KopeteAccountManager* KopeteAccountManager::s_manager = 0L; KopeteAccountManager* KopeteAccountManager::manager() { if( !s_manager ) s_manager = new KopeteAccountManager; return s_manager; } KopeteAccountManager::KopeteAccountManager() : QObject( qApp, "KopeteAccountManager" ) { } KopeteAccountManager::~KopeteAccountManager() { s_manager = 0L; } void KopeteAccountManager::connectAll() { for(KopeteAccount *i=m_accounts.first() ; i; i=m_accounts.next() ) { i->connect(); } //------ OBSOLETE QPtrList<KopetePlugin> plugins = LibraryLoader::pluginLoader()->plugins(); for( KopetePlugin *p = plugins.first() ; p ; p = plugins.next() ) { KopeteProtocol *proto = dynamic_cast<KopeteProtocol*>( p ); if( !proto ) continue; if( !proto->isConnected() ) { kdDebug(14010) << "KopeteAccountManager::connectAll: " << "Connecting plugin: " << proto->pluginId() << endl; proto->connect(); } } } void KopeteAccountManager::disconnectAll() { for(KopeteAccount *i=m_accounts.first() ; i; i=m_accounts.next() ) { i->disconnect(); } //------ OBSOLETE QPtrList<KopetePlugin> plugins = LibraryLoader::pluginLoader()->plugins(); for( KopetePlugin *p = plugins.first() ; p ; p = plugins.next() ) { KopeteProtocol *proto = dynamic_cast<KopeteProtocol*>( p ); if( !proto ) continue; if( proto->isConnected() ) { kdDebug(14010) << "KopeteAccountManager::disconnectAll: " << "Disonnecting plugin: " << proto->pluginId() << endl; proto->disconnect(); } } } void KopeteAccountManager::setAwayAll() { KopeteAway::setGlobalAway( true ); for(KopeteAccount *i=m_accounts.first() ; i; i=m_accounts.next() ) { if(i->isConnected() && !i->isAway()) i->setAway(true); } //------ OBSOLETE QPtrList<KopetePlugin> plugins = LibraryLoader::pluginLoader()->plugins(); for( KopetePlugin *p = plugins.first() ; p ; p = plugins.next() ) { KopeteProtocol *proto = dynamic_cast<KopeteProtocol*>( p ); if( !proto ) continue; if( proto->isConnected() && !proto->isAway() ) { kdDebug(14010) << "KopeteAccountManager::setAwayAll: " << "Setting plugin to away: " << proto->pluginId() << endl; proto->setAway(); } } } void KopeteAccountManager::setAvailableAll() { KopeteAway::setGlobalAway( false ); for(KopeteAccount *i=m_accounts.first() ; i; i=m_accounts.next() ) { if(i->isConnected() && i->isAway()) i->setAway(false); } //------ OBSOLETE QPtrList<KopetePlugin> plugins = LibraryLoader::pluginLoader()->plugins(); for( KopetePlugin *p = plugins.first() ; p ; p = plugins.next() ) { KopeteProtocol *proto = dynamic_cast<KopeteProtocol*>( p ); if( !proto ) continue; if( proto->isConnected() && proto->isAway() ) { kdDebug(14010) << "KopeteAccountManager::setAvailableAll: " << "Setting plugin to available: " << proto->pluginId() << endl; proto->setAvailable(); } } } void KopeteAccountManager::registerAccount(KopeteAccount *i) { /* Anti-Crash: Valid account pointer? */ if ( !i ) return; /* No, we dont allow accounts without id */ if ( !(i->accountId()).isNull() ) { /* Lets check if account exists already in protocol namespace */ for ( KopeteAccount *acc = m_accounts.first() ; acc ; acc = m_accounts.next() ) { if( ( i->protocol() == acc->protocol() ) && ( i->accountId() == acc->accountId() ) ) { /* Duplicate!! */ return; } } /* Ok seems sane */ m_accounts.append( i ); } } const QPtrList<KopeteAccount>& KopeteAccountManager::accounts() const { return m_accounts; } QDict<KopeteAccount> KopeteAccountManager::accounts(const KopeteProtocol *p) { QDict<KopeteAccount> dict; for(KopeteAccount *i=m_accounts.first() ; i; i=m_accounts.next() ) { if( (i->protocol() == p) && !(i->accountId().isNull()) ) dict.insert(i->accountId() , i); } return dict; } KopeteAccount* KopeteAccountManager::findAccount(const QString& protocolId, const QString& accountId) { for(KopeteAccount *i=m_accounts.first() ; i; i=m_accounts.next() ) { if( i->protocol()->pluginId() == protocolId && i->accountId() == accountId ) return i; } return 0L; } void KopeteAccountManager::unregisterAccount( KopeteAccount *account ) { m_accounts.remove( account ); } void KopeteAccountManager::save() { QString fileName = locateLocal( "appdata", QString::fromLatin1( "accounts.xml" ) ); KSaveFile file( fileName ); if( file.status() == 0 ) { QTextStream *stream = file.textStream(); stream->setEncoding( QTextStream::UnicodeUTF8 ); QString xml = QString::fromLatin1("<?xml version=\"1.0\"?>\n" "<!DOCTYPE kopete-accounts>\n" "<kopete-accounts version=\"1.0\">\n" ); for(KopeteAccount *i=m_accounts.first() ; i; i=m_accounts.next() ) { xml += i->toXML(); } xml += QString::fromLatin1( "</kopete-accounts>\n" ); *stream << xml; if ( !file.close() ) { kdDebug(14010) << "KopeteAccountManager::save: ERROR: failed to write accounts, error code is: " << file.status() << endl; } } else { kdWarning(14010) << "KopeteAccountManager::save: ERROR: Couldn't open accounts file " << fileName << " accounts not saved." << endl; } } void KopeteAccountManager::load() { QString filename = locateLocal( "appdata", QString::fromLatin1( "accounts.xml" ) ); if( filename.isEmpty() ) return ; kdDebug(14010) << k_funcinfo <<endl; m_accountList = QDomDocument( QString::fromLatin1( "kopete-accounts" ) ); QFile file( filename ); file.open( IO_ReadOnly ); m_accountList.setContent( &file ); file.close(); connect( LibraryLoader::pluginLoader(), SIGNAL( pluginLoaded(KopetePlugin*) ), this, SLOT( loadProtocol(KopetePlugin*) ) ); } void KopeteAccountManager::loadProtocol( KopetePlugin *plu ) { KopeteProtocol* protocol=dynamic_cast<KopeteProtocol*>(plu); if(!protocol) return; kdDebug(14010) << k_funcinfo <<endl; QDomNode node = m_accountList.documentElement().firstChild(); while( !node.isNull() ) { QDomElement element = node.toElement(); if( !element.isNull() ) { if( element.tagName() == QString::fromLatin1("account") ) { QString accountId = element.attribute( QString::fromLatin1("account-id"), QString::null ); QString protocolId = element.attribute( QString::fromLatin1("protocol-id"), QString::null ); if( (protocolId == protocol->pluginId()) ) { if ( !accountId.isEmpty() ) { kdWarning(14010) << k_funcinfo << "Creating account for " << accountId << endl; KopeteAccount *account = protocol->createNewAccount(accountId); QDomNode accountNode = node.firstChild(); if (account && !account->fromXML( accountNode ) ) { delete account; account = 0L; } } else { kdWarning(14010) << k_funcinfo << "Account with emtpy id!" << endl; } } else { kdWarning(14010) << k_funcinfo << "This account belong to another protocol!" << endl; } } else { kdWarning(14010) << k_funcinfo << "Unknown element '" << element.tagName() << "' in contact list!" << endl; } } node = node.nextSibling(); } } void KopeteAccountManager::autoConnect() { for(KopeteAccount *i=m_accounts.first() ; i; i=m_accounts.next() ) { if(i->autoLogin()) i->connect(); } } #include "kopeteaccountmanager.moc" // vim: set noet ts=4 sts=4 sw=4: <|endoftext|>
<commit_before>/* * Copyright 2009-2019 The VOTCA Development Team * (http://www.votca.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 "../statefilters/DeltaQ_filter.h" #include "../statefilters/Density_filter.h" #include "../statefilters/Localisation_filter.h" #include "../statefilters/OscillatorStrength_filter.h" #include "../statefilters/Overlap_filter.h" #include <votca/xtp/filterfactory.h> namespace votca { namespace xtp { void FilterFactory::RegisterAll(void) { Filter().Register<DeltaQ_filter>("chargeTransfer"); Filter().Register<Density_filter>("density"); Filter().Register<Localisation_filter>("localisation"); Filter().Register<OscillatorStrength_filter>("oscillatorstrength"); Filter().Register<Overlap_filter>("overlap"); } } // namespace xtp } // namespace votca <commit_msg>renamed register filter<commit_after>/* * Copyright 2009-2019 The VOTCA Development Team * (http://www.votca.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 "../statefilters/DeltaQ_filter.h" #include "../statefilters/Density_filter.h" #include "../statefilters/Localisation_filter.h" #include "../statefilters/OscillatorStrength_filter.h" #include "../statefilters/Overlap_filter.h" #include <votca/xtp/filterfactory.h> namespace votca { namespace xtp { void FilterFactory::RegisterAll(void) { Filter().Register<DeltaQ_filter>("chargetransfer"); Filter().Register<Density_filter>("density"); Filter().Register<Localisation_filter>("localisation"); Filter().Register<OscillatorStrength_filter>("oscillatorstrength"); Filter().Register<Overlap_filter>("overlap"); } } // namespace xtp } // namespace votca <|endoftext|>
<commit_before>#include "Atm_encoder.hpp" #include <limits.h> const char Atm_encoder::_enc_states[16] = {0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0}; Atm_encoder& Atm_encoder::begin( int pin1, int pin2, int divider /* = 4 */ ) { // clang-format off const static STATE_TYPE state_table[] PROGMEM = { /* ON_ENTER ON_LOOP ON_EXIT EVT_UP EVT_DOWN ELSE */ /* IDLE */ -1, ACT_SAMPLE, -1, UP, DOWN, -1, /* UP */ ACT_UP, -1, -1, -1, -1, IDLE, /* DOWN */ ACT_DOWN, -1, -1, -1, -1, IDLE, }; // clang-format on MACHINE::begin( state_table, ELSE ); _pin1 = pin1; _pin2 = pin2; _divider = divider; pinMode( _pin1, INPUT ); pinMode( _pin2, INPUT ); digitalWrite( _pin1, HIGH ); // Is this needed? digitalWrite( _pin2, HIGH ); _min = INT_MIN; _max = INT_MAX; _value = 0; return *this; } Atm_encoder& Atm_encoder::range( int min, int max, bool wrap /* = false */ ) { _min = min; _max = max; _wrap = wrap; if ( _value < _min || _value > _max ) { _value = min; } return *this; } Atm_encoder& Atm_encoder::set( int value ) { _value = value; return *this; } Atm_encoder& Atm_encoder::onUp( Machine& machine, int event /* = 0 */ ) { _onup.set( &machine, event ); return *this; } Atm_encoder& Atm_encoder::onUp( TinyMachine& machine, int event /* = 0 */ ) { _onup.set( &machine, event ); return *this; } Atm_encoder& Atm_encoder::onUp( atm_cb_t callback, int idx /* = 0 */ ) { _onup.set( callback, idx ); return *this; } #ifndef TINYMACHINE Atm_encoder& Atm_encoder::onUp( const char* label, int event /* = 0 */ ) { _onup.set( label, event ); return *this; } #endif Atm_encoder& Atm_encoder::onDown( Machine& machine, int event /* = 0 */ ) { _ondown.set( &machine, event ); return *this; } Atm_encoder& Atm_encoder::onDown( TinyMachine& machine, int event /* = 0 */ ) { _ondown.set( &machine, event ); return *this; } Atm_encoder& Atm_encoder::onDown( atm_cb_t callback, int idx /* = 0 */ ) { _ondown.set( callback, idx ); return *this; } #ifndef TINYMACHINE Atm_encoder& Atm_encoder::onDown( const char* label, int event /* = 0 */ ) { _ondown.set( label, event ); return *this; } #endif int Atm_encoder::state( void ) { return _value; } int Atm_encoder::event( int id ) { switch ( id ) { case EVT_UP: return _enc_direction == +1 && ( _enc_counter % _divider == 0 ); case EVT_DOWN: return _enc_direction == -1 && ( _enc_counter % _divider == 0 ); } return 0; } bool Atm_encoder::count( int direction ) { if ( (long)_value + direction > _max ) { if ( _wrap ) { _value = _min; } else { return false; } } else if ( (long)_value + direction < _min ) { if ( _wrap ) { _value = _max; } else { return false; } } else { _value += direction; } return true; } void Atm_encoder::action( int id ) { switch ( id ) { case ACT_SAMPLE: _enc_bits = ( ( _enc_bits << 2 ) | ( digitalRead( _pin1 ) << 1 ) | ( digitalRead( _pin2 ) ) ) & 0x0f; if ( ( _enc_direction = _enc_states[_enc_bits] ) != 0 ) { if ( ++_enc_counter % _divider == 0 ) if ( !count( _enc_direction ) ) { _enc_direction = 0; } } return; case ACT_UP: _onup.push( FACTORY ); return; case ACT_DOWN: _ondown.push( FACTORY ); return; } } Atm_encoder& Atm_encoder::trace( Stream& stream ) { #ifndef TINYMACHINE Machine::setTrace( &stream, atm_serial_debug::trace, "EVT_UP\0EVT_DOWN\0ELSE\0IDLE\0UP\0DOWN" ); #endif return *this; } <commit_msg>Fixed braces<commit_after>#include "Atm_encoder.hpp" #include <limits.h> const char Atm_encoder::_enc_states[16] = {0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0}; Atm_encoder& Atm_encoder::begin( int pin1, int pin2, int divider /* = 4 */ ) { // clang-format off const static STATE_TYPE state_table[] PROGMEM = { /* ON_ENTER ON_LOOP ON_EXIT EVT_UP EVT_DOWN ELSE */ /* IDLE */ -1, ACT_SAMPLE, -1, UP, DOWN, -1, /* UP */ ACT_UP, -1, -1, -1, -1, IDLE, /* DOWN */ ACT_DOWN, -1, -1, -1, -1, IDLE, }; // clang-format on MACHINE::begin( state_table, ELSE ); _pin1 = pin1; _pin2 = pin2; _divider = divider; pinMode( _pin1, INPUT ); pinMode( _pin2, INPUT ); digitalWrite( _pin1, HIGH ); // Is this needed? digitalWrite( _pin2, HIGH ); _min = INT_MIN; _max = INT_MAX; _value = 0; return *this; } Atm_encoder& Atm_encoder::range( int min, int max, bool wrap /* = false */ ) { _min = min; _max = max; _wrap = wrap; if ( _value < _min || _value > _max ) { _value = min; } return *this; } Atm_encoder& Atm_encoder::set( int value ) { _value = value; return *this; } Atm_encoder& Atm_encoder::onUp( Machine& machine, int event /* = 0 */ ) { _onup.set( &machine, event ); return *this; } Atm_encoder& Atm_encoder::onUp( TinyMachine& machine, int event /* = 0 */ ) { _onup.set( &machine, event ); return *this; } Atm_encoder& Atm_encoder::onUp( atm_cb_t callback, int idx /* = 0 */ ) { _onup.set( callback, idx ); return *this; } #ifndef TINYMACHINE Atm_encoder& Atm_encoder::onUp( const char* label, int event /* = 0 */ ) { _onup.set( label, event ); return *this; } #endif Atm_encoder& Atm_encoder::onDown( Machine& machine, int event /* = 0 */ ) { _ondown.set( &machine, event ); return *this; } Atm_encoder& Atm_encoder::onDown( TinyMachine& machine, int event /* = 0 */ ) { _ondown.set( &machine, event ); return *this; } Atm_encoder& Atm_encoder::onDown( atm_cb_t callback, int idx /* = 0 */ ) { _ondown.set( callback, idx ); return *this; } #ifndef TINYMACHINE Atm_encoder& Atm_encoder::onDown( const char* label, int event /* = 0 */ ) { _ondown.set( label, event ); return *this; } #endif int Atm_encoder::state( void ) { return _value; } int Atm_encoder::event( int id ) { switch ( id ) { case EVT_UP: return _enc_direction == +1 && ( _enc_counter % _divider == 0 ); case EVT_DOWN: return _enc_direction == -1 && ( _enc_counter % _divider == 0 ); } return 0; } bool Atm_encoder::count( int direction ) { if ( (long)_value + direction > _max ) { if ( _wrap ) { _value = _min; } else { return false; } } else if ( (long)_value + direction < _min ) { if ( _wrap ) { _value = _max; } else { return false; } } else { _value += direction; } return true; } void Atm_encoder::action( int id ) { switch ( id ) { case ACT_SAMPLE: _enc_bits = ( ( _enc_bits << 2 ) | ( digitalRead( _pin1 ) << 1 ) | ( digitalRead( _pin2 ) ) ) & 0x0f; if ( ( _enc_direction = _enc_states[_enc_bits] ) != 0 ) { if ( ++_enc_counter % _divider == 0 ) { if ( !count( _enc_direction ) ) { _enc_direction = 0; } } } return; case ACT_UP: _onup.push( FACTORY ); return; case ACT_DOWN: _ondown.push( FACTORY ); return; } } Atm_encoder& Atm_encoder::trace( Stream& stream ) { #ifndef TINYMACHINE Machine::setTrace( &stream, atm_serial_debug::trace, "EVT_UP\0EVT_DOWN\0ELSE\0IDLE\0UP\0DOWN" ); #endif return *this; } <|endoftext|>
<commit_before>/* ** Author(s): ** - Laurent LEC <llec@aldebaran-robotics.com> ** ** Copyright (C) 2012 Aldebaran Robotics */ #include <iostream> #include <istream> #include <sstream> #include <qimessaging/object.hpp> #include <qimessaging/session.hpp> qi::Session session; std::map<const std::string, qi::Object *> services; typedef std::vector<std::string> command; /**************** * SERVICE * ****************/ static void cmd_service(const command &cmd, command::const_iterator &it) { if (it == cmd.end()) { std::cerr << "service: not enough parameters" << std::endl; return; } std::vector<qi::ServiceInfo> servs = session.services(); for (unsigned int i = 0; i < servs.size(); ++i) { if (servs[i].name() == *it) { std::cout << servs[i].name() << std::endl << " id: " << servs[i].serviceId() << std::endl << " machine: " << servs[i].machineId() << std::endl << " process: " << servs[i].processId() << std::endl << " endpoints:" << std::endl; for (std::vector<std::string>::const_iterator it2 = servs[i].endpoints().begin(); it2 != servs[i].endpoints().end(); it2++) { std::cout << " " << *it2 << std::endl; } std::cout << " methods:" << std::endl; qi::Object *obj = session.service(*it); if (obj) { services[*it] = obj; qi::MetaObject &mobj = obj->metaObject(); for (std::vector<qi::MetaMethod>::const_iterator it2 = mobj.methods().begin(); it2 != mobj.methods().end(); ++it2) { std::cout << " " << (*it2).sigreturn() << " " << (*it2).signature() << std::endl; } } else { std::cerr << "service: could not get object" << std::endl; } } } } /**************** * SERVICES * ****************/ static void cmd_services(const command &cmd, command::const_iterator &QI_UNUSED(it)) { bool enum_all = false; if (std::find(cmd.begin(), cmd.end(), "-v") != cmd.end()) enum_all = true; std::vector<qi::ServiceInfo> servs = session.services(); for (unsigned int i = 0; i < servs.size(); ++i) { std::cout << "[" << servs[i].serviceId() << "] " << servs[i].name() << std::endl; if (enum_all) { command ncmd; command::const_iterator it; ncmd.push_back(servs[i].name()); it = ncmd.begin(); cmd_service(ncmd, it); std::cout << std::endl; } } } /**************** * SESSION * ****************/ static void cmd_session(const command &cmd, command::const_iterator &it) { if (it == cmd.end()) { std::cerr << "session: not enough parameters" << std::endl; return; } if (*it == "connect") { ++it; if (it == cmd.end()) { std::cerr << "session connect: not enough parameters" << std::endl; return; } else { session.connect(*it); session.waitForConnected(); } } else if (*it == "services") { ++it; std::vector<qi::ServiceInfo> servs = session.services(); for (unsigned int i = 0; i < servs.size(); ++i) { std::cout << "[" << servs[i].serviceId() << "] " << servs[i].name() << std::endl; } } else { std::cerr << "unexpected token: " << *it << std::endl; } } static void execute(const command &cmd) { command::const_iterator it = cmd.begin(); if (it == cmd.end()) { return; } if (*it == "session") { cmd_session(cmd, ++it); } else if (*it == "service") { cmd_service(cmd, ++it); } else if (*it == "services") { cmd_services(cmd, ++it); } else { std::cerr << "unexpected token: " << *it << std::endl; } } static void from_stdin() { char line[8192]; std::cout << "% "; while (std::cin.getline(line, sizeof(line))) { std::stringstream ssin(line, std::stringstream::in); command cmd; std::string input; while (ssin >> input) { cmd.push_back(input); } execute(cmd); std::cout << "% "; } } static void from_argv(int argc, char *argv[]) { command cmd; session.connect(argv[1]); session.waitForConnected(); for (int i = 2; i < argc; ++i) { cmd.push_back(argv[i]); } execute(cmd); } static void usage(char *argv0) { std::cout << "Usage: " << argv0 << " [ADDRESS CMD]" << std::endl; std::cout << " connect ADDRESS" << std::endl << " services [-v]" << std::endl << " service SERVICE" << std::endl; } int main(int argc, char *argv[]) { if (argc == 2 && (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0)) { usage(argv[0]); return (0); } if (argc == 1) { from_stdin(); } else { from_argv(argc, argv); } session.disconnect(); return (0); } <commit_msg>Events: support them in qicli.<commit_after>/* ** Author(s): ** - Laurent LEC <llec@aldebaran-robotics.com> ** ** Copyright (C) 2012 Aldebaran Robotics */ #include <iostream> #include <istream> #include <sstream> #include <qimessaging/object.hpp> #include <qimessaging/session.hpp> qi::Session session; std::map<const std::string, qi::Object *> services; typedef std::vector<std::string> command; /**************** * SERVICE * ****************/ static void cmd_service(const command &cmd, command::const_iterator &it) { if (it == cmd.end()) { std::cerr << "service: not enough parameters" << std::endl; return; } std::vector<qi::ServiceInfo> servs = session.services(); for (unsigned int i = 0; i < servs.size(); ++i) { if (servs[i].name() == *it) { std::cout << servs[i].name() << std::endl << " id: " << servs[i].serviceId() << std::endl << " machine: " << servs[i].machineId() << std::endl << " process: " << servs[i].processId() << std::endl << " endpoints:" << std::endl; for (std::vector<std::string>::const_iterator it2 = servs[i].endpoints().begin(); it2 != servs[i].endpoints().end(); it2++) { std::cout << " " << *it2 << std::endl; } std::cout << " methods:" << std::endl; qi::Object *obj = session.service(*it); if (obj) { services[*it] = obj; qi::MetaObject &mobj = obj->metaObject(); for (std::vector<qi::MetaMethod>::const_iterator it2 = mobj.methods().begin(); it2 != mobj.methods().end(); ++it2) { std::cout << " " << (*it2).sigreturn() << " " << (*it2).signature() << std::endl; } std::cout << " events:" << std::endl; for (std::vector<qi::MetaEvent>::const_iterator it2 = mobj.events().begin(); it2 != mobj.events().end(); ++it2) { std::cout << " " << it2->signature() << std::endl; } } else { std::cerr << "service: could not get object" << std::endl; } } } } /**************** * SERVICES * ****************/ static void cmd_services(const command &cmd, command::const_iterator &QI_UNUSED(it)) { bool enum_all = false; if (std::find(cmd.begin(), cmd.end(), "-v") != cmd.end()) enum_all = true; std::vector<qi::ServiceInfo> servs = session.services(); for (unsigned int i = 0; i < servs.size(); ++i) { std::cout << "[" << servs[i].serviceId() << "] " << servs[i].name() << std::endl; if (enum_all) { command ncmd; command::const_iterator it; ncmd.push_back(servs[i].name()); it = ncmd.begin(); cmd_service(ncmd, it); std::cout << std::endl; } } } /**************** * SESSION * ****************/ static void cmd_session(const command &cmd, command::const_iterator &it) { if (it == cmd.end()) { std::cerr << "session: not enough parameters" << std::endl; return; } if (*it == "connect") { ++it; if (it == cmd.end()) { std::cerr << "session connect: not enough parameters" << std::endl; return; } else { session.connect(*it); session.waitForConnected(); } } else if (*it == "services") { ++it; std::vector<qi::ServiceInfo> servs = session.services(); for (unsigned int i = 0; i < servs.size(); ++i) { std::cout << "[" << servs[i].serviceId() << "] " << servs[i].name() << std::endl; } } else { std::cerr << "unexpected token: " << *it << std::endl; } } static void execute(const command &cmd) { command::const_iterator it = cmd.begin(); if (it == cmd.end()) { return; } if (*it == "session") { cmd_session(cmd, ++it); } else if (*it == "service") { cmd_service(cmd, ++it); } else if (*it == "services") { cmd_services(cmd, ++it); } else { std::cerr << "unexpected token: " << *it << std::endl; } } static void from_stdin() { char line[8192]; std::cout << "% "; while (std::cin.getline(line, sizeof(line))) { std::stringstream ssin(line, std::stringstream::in); command cmd; std::string input; while (ssin >> input) { cmd.push_back(input); } execute(cmd); std::cout << "% "; } } static void from_argv(int argc, char *argv[]) { command cmd; session.connect(argv[1]); session.waitForConnected(); for (int i = 2; i < argc; ++i) { cmd.push_back(argv[i]); } execute(cmd); } static void usage(char *argv0) { std::cout << "Usage: " << argv0 << " [ADDRESS CMD]" << std::endl; std::cout << " connect ADDRESS" << std::endl << " services [-v]" << std::endl << " service SERVICE" << std::endl; } int main(int argc, char *argv[]) { if (argc == 2 && (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0)) { usage(argv[0]); return (0); } if (argc == 1) { from_stdin(); } else { from_argv(argc, argv); } session.disconnect(); return (0); } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2012-2014 Jun Wu <quark@zju.edu.cn> // // 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 "strconv.h" #include <cstdio> namespace conv = lrun::strconv; using std::string; double conv::to_double(const string& str) { double v = 0; sscanf(str.c_str(), "%lg", &v); return v; } long conv::to_long(const string& str) { long v = 0; sscanf(str.c_str(), "%ld", &v); return v; } long long conv::to_longlong(const string& str) { long long v = 0; sscanf(str.c_str(), "%lld", &v); return v; } bool conv::to_bool(const string& str) { if (str.empty()) return false; switch (str.c_str()[0]) { case '1': case 't': case 'T': case 'e': case 'E': return true; default: return false; } } string conv::from_double(double value, int precision) { char buf[1024]; char format[16]; snprintf(format, sizeof format, "%%.%df", precision); snprintf(buf, sizeof buf, format, value); return buf; } string conv::from_long(long value) { char buf[32]; snprintf(buf, sizeof buf, "%ld", value); return buf; } string conv::from_longlong(long long value) { char buf[32]; snprintf(buf, sizeof buf, "%lld", value); return buf; } <commit_msg>Remove some magic numbers from strconv<commit_after>//////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2012-2014 Jun Wu <quark@zju.edu.cn> // // 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 "strconv.h" #include <cstdio> namespace conv = lrun::strconv; using std::string; double conv::to_double(const string& str) { double v = 0; sscanf(str.c_str(), "%lg", &v); return v; } long conv::to_long(const string& str) { long v = 0; sscanf(str.c_str(), "%ld", &v); return v; } long long conv::to_longlong(const string& str) { long long v = 0; sscanf(str.c_str(), "%lld", &v); return v; } bool conv::to_bool(const string& str) { if (str.empty()) return false; switch (str.c_str()[0]) { case '1': case 't': case 'T': case 'e': case 'E': return true; default: return false; } } string conv::from_double(double value, int precision) { char buf[1024]; char format[16]; snprintf(format, sizeof format, "%%.%df", precision); snprintf(buf, sizeof buf, format, value); return buf; } string conv::from_long(long value) { char buf[sizeof(long) * 3 + 1]; snprintf(buf, sizeof buf, "%ld", value); return buf; } string conv::from_longlong(long long value) { char buf[sizeof(long long) * 3 + 1]; snprintf(buf, sizeof buf, "%lld", value); return buf; } <|endoftext|>
<commit_before>#include "stream.h" Stream::Stream(QObject *parent) : VolumeObject(parent) { m_volumeWritable = false; m_hasVolume = false; } Stream::~Stream() { } QString Stream::name() const { return m_name; } Client *Stream::client() const { qDebug() <<"client"; return context()->clients().data().value(m_clientIndex, nullptr); } <commit_msg>debug--<commit_after>#include "stream.h" Stream::Stream(QObject *parent) : VolumeObject(parent) { m_volumeWritable = false; m_hasVolume = false; } Stream::~Stream() { } QString Stream::name() const { return m_name; } Client *Stream::client() const { return context()->clients().data().value(m_clientIndex, nullptr); } <|endoftext|>
<commit_before>#ifndef SAVE_STATE_H # define SAVE_STATE_H # pragma once struct statebuf { void* sp; void* label; }; #if defined(__GNUC__) inline bool __attribute__((always_inline)) savestate(statebuf& ssb) noexcept { bool r; #if defined(i386) || defined(__i386) || defined(__i386__) asm volatile ( "movl %%esp, %0\n\t" // store sp "movl $1f, %1\n\t" // store label "movb $0, %2\n\t" // return false "jmp 2f\n\t" "1:movb $1, %2\n\t" // return true "2:" : "=m" (ssb.sp), "=m" (ssb.label), "=r" (r) : : "memory" ); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) asm volatile ( "movq %%rsp, %0\n\t" // store sp "movq $1f, %1\n\t" // store label "movb $0, %2\n\t" // return false "jmp 2f\n\t" "1:movb $1, %2\n\t" // return true "2:" : "=m" (ssb.sp), "=m" (ssb.label), "=r" (r) : : "memory" ); #elif defined(__arm__) asm volatile ( "str sp, %0\n\t" "b 2f\n\t" "2:" : "=m" (ssb.sp), "=m" (ssb.label), "=r" (r) : : "memory" ); #endif return r; } #elif defined(_MSC_VER) __forceinline bool savestate(statebuf& ssb) noexcept { bool r; __asm { push ebp mov ebx, ssb mov [ebx]ssb.sp, esp mov [ebx]ssb.label, offset _1f mov r, 0x0 jmp _2f _1f: pop ebp mov r, 0x1 _2f: } return r; } #else # error "unsupported compiler" #endif #if defined(__GNUC__) #if defined(i386) || defined(__i386) || defined(__i386__) #define restorestate(SSB) \ asm volatile ( \ "movl %0, %%esp\n\t" \ "jmp *%1" \ : \ : "m" (SSB.sp), "m" (SSB.label)\ ); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) #define restorestate(SSB) \ asm volatile ( \ "movq %0, %%rsp\n\t" \ "jmp *%1" \ : \ : "m" (SSB.sp), "m" (SSB.label)\ ); #elif defined(__arm__) #define restorestate(SSB) \ asm volatile ( \ "ldr sp, %0\n\t" \ : \ : "m" (SSB.sp), "m" (SSB.label)\ ); #else # error "unsupported architecture" #endif #elif defined(_MSC_VER) #define restorestate(SSB) \ __asm mov ebx, this \ __asm add ebx, [SSB] \ __asm mov esp, [ebx]SSB.sp\ __asm jmp [ebx]SSB.label #else # error "unsupported compiler" #endif #endif // SAVE_STATE_H <commit_msg>some fixes<commit_after>#ifndef SAVE_STATE_H # define SAVE_STATE_H # pragma once struct statebuf { void* sp; void* label; }; #if defined(__GNUC__) inline bool __attribute__((always_inline)) savestate(statebuf& ssb) noexcept { bool r; #if defined(i386) || defined(__i386) || defined(__i386__) asm volatile ( "movl %%esp, %0\n\t" // store sp "movl $1f, %1\n\t" // store label "movb $0, %2\n\t" // return false "jmp 2f\n\t" "1:movb $1, %2\n\t" // return true "2:" : "=m" (ssb.sp), "=m" (ssb.label), "=r" (r) : : "memory" ); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) asm volatile ( "movq %%rsp, %0\n\t" // store sp "movq $1f, %1\n\t" // store label "movb $0, %2\n\t" // return false "jmp 2f\n\t" "1:movb $1, %2\n\t" // return true "2:" : "=m" (ssb.sp), "=m" (ssb.label), "=r" (r) : : "memory" ); #elif defined(__arm__) asm volatile ( "push {r0}\n\t" // push r0 "str sp, %0\n\t" // store sp "ldr r0, $1f\n\t" // load label into r0 "str r0, %1\n\t" // store r0 into label "mov %2, $0\n\t" // store 0 into result "b 2f\n\t" "1:pop {r0}\n\t" "2:" : "=m" (ssb.sp), "=m" (ssb.label), "=r" (r) : : "memory" ); #endif return r; } #elif defined(_MSC_VER) __forceinline bool savestate(statebuf& ssb) noexcept { bool r; __asm { push ebp mov ebx, ssb mov [ebx]ssb.sp, esp mov [ebx]ssb.label, offset _1f mov r, 0x0 jmp _2f _1f: pop ebp mov r, 0x1 _2f: } return r; } #else # error "unsupported compiler" #endif #if defined(__GNUC__) #if defined(i386) || defined(__i386) || defined(__i386__) #define restorestate(SSB) \ asm volatile ( \ "movl %0, %%esp\n\t" \ "jmp *%1" \ : \ : "m" (SSB.sp), "m" (SSB.label)\ ); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) #define restorestate(SSB) \ asm volatile ( \ "movq %0, %%rsp\n\t" \ "jmp *%1" \ : \ : "m" (SSB.sp), "m" (SSB.label)\ ); #elif defined(__arm__) #define restorestate(SSB) \ asm volatile ( \ "ldr sp, %0\n\t" \ : \ : "m" (SSB.sp), "m" (SSB.label)\ ); #else # error "unsupported architecture" #endif #elif defined(_MSC_VER) #define restorestate(SSB) \ __asm mov ebx, this \ __asm add ebx, [SSB] \ __asm mov esp, [ebx]SSB.sp\ __asm jmp [ebx]SSB.label #else # error "unsupported compiler" #endif #endif // SAVE_STATE_H <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ /// \file string.cpp //------------------------------------------------------------------------------ /// \brief Implementation of general purpose functions for string processing //------------------------------------------------------------------------------ // Copyright (c) 2010 Serge Aleynikov <saleyn@gmail.com> // Created: 2010-05-06 //------------------------------------------------------------------------------ /* ***** BEGIN LICENSE BLOCK ***** This file is part of the utxx open-source project. Copyright (C) 2010 Serge Aleynikov <saleyn@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ***** END LICENSE BLOCK ***** */ #include <utxx/string.hpp> #include <utxx/print_opts.hpp> namespace utxx { std::string to_bin_string(const char* a_buf, size_t a_sz, bool a_hex, bool a_readable, bool a_eol) { std::stringstream out; const char* begin = a_buf, *end = a_buf + a_sz; print_opts opts = a_hex ? (a_readable ? print_opts::printable_or_hex : print_opts::hex) : (a_readable ? print_opts::printable_or_dec : print_opts::dec); output(out, begin, end, opts, ",", "", "\"", "<<", ">>"); if (a_eol) out << std::endl; return out.str(); } bool wildcard_match(const char* a_input, const char* a_pattern) { // Pattern match a_input against a_pattern, and exit // at the end of the input string for (const char* ip = nullptr, *pp = nullptr; *a_input;) if (*a_pattern == '*') { if (!*++a_pattern) return true; // Reached '*' at the end of pattern pp = a_pattern; // Store matching state right after '*' ip = a_input; } else if ((*a_pattern == *a_input) || (*a_pattern == '?')) { a_pattern++; // Continue successful input match a_input++; } else if (pp) { a_pattern = pp; // Match failed - restore state of pattern after '*' a_input = ++ip; // Advance the input on every match failure } else return false; // Match failed before the first '*' is found // Skip trailing '*' in the pattern, since they don't affect the outcome: while (*a_pattern == '*') a_pattern++; // This point is reached only when the a_input string was fully // exhaused. If at this point the a_pattern is exhaused too ('\0'), // there's a match, otherwise pattern match is incomplete. return !*a_pattern; } } // namespace utxx <commit_msg>Update string.cpp<commit_after>//------------------------------------------------------------------------------ /// \file string.cpp //------------------------------------------------------------------------------ /// \brief Implementation of general purpose functions for string processing //------------------------------------------------------------------------------ // Copyright (c) 2010 Serge Aleynikov <saleyn@gmail.com> // Created: 2010-05-06 //------------------------------------------------------------------------------ /* ***** BEGIN LICENSE BLOCK ***** This file is part of the utxx open-source project. Copyright (C) 2010 Serge Aleynikov <saleyn@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ***** END LICENSE BLOCK ***** */ #include <utxx/string.hpp> #include <utxx/print_opts.hpp> namespace utxx { std::string to_bin_string(const char* a_buf, size_t a_sz, bool a_hex, bool a_readable, bool a_eol) { std::stringstream out; const char* begin = a_buf, *end = a_buf + a_sz; print_opts opts = a_hex ? (a_readable ? print_opts::printable_or_hex : print_opts::hex) : (a_readable ? print_opts::printable_or_dec : print_opts::dec); output(out, begin, end, opts, ",", "", "\"", "<<", ">>"); if (a_eol) out << std::endl; return out.str(); } bool wildcard_match(const char* a_input, const char* a_pattern) { // Pattern match a_input against a_pattern, and exit // at the end of the input string for (const char* ip = nullptr, *pp = nullptr; *a_input;) if (*a_pattern == '*') { if (!*++a_pattern) return true; // Reached '*' at the end of the pattern pp = a_pattern; // Store matching state right after '*' ip = a_input; } else if ((*a_pattern == *a_input) || (*a_pattern == '?')) { a_pattern++; // Continue successful input match a_input++; } else if (pp) { a_pattern = pp; // Match failed - restore state of pattern after '*' a_input = ++ip; // Advance the input on every match failure } else return false; // Match failed before the first '*' is found in the pattern // Skip trailing '*' in the pattern, since they don't affect the outcome: while (*a_pattern == '*') a_pattern++; // This point is reached only when the a_input string was fully // exhaused. If at this point the a_pattern is exhaused too ('\0'), // there's a match, otherwise pattern match is incomplete. return !*a_pattern; } } // namespace utxx <|endoftext|>
<commit_before>#include <test/mcmc/mock_hmc.hpp> #include <stan/mcmc/hmc/base_hmc.hpp> #include <boost/random/additive_combine.hpp> #include <gtest/gtest.h> #include <test/models/utility.hpp> typedef boost::ecuyer1988 rng_t; namespace stan { namespace mcmc { class mock_hmc: public base_hmc<mock_model, ps_point, mock_hamiltonian, mock_integrator, rng_t> { public: mock_hmc(mock_model& m, rng_t& rng, std::ostream* o, std::ostream* e) : base_hmc<mock_model,ps_point,mock_hamiltonian,mock_integrator,rng_t> (m, rng, o, e) { this->_name = "Mock HMC"; } sample transition(sample& init_sample) { this->seed(init_sample.cont_params(), init_sample.disc_params()); return sample(this->_z.q, this->_z.r, - this->_hamiltonian.V(this->_z), 0); } void write_sampler_param_names(std::ostream& o) {}; void write_sampler_params(std::ostream& o) {}; void get_sampler_param_names(std::vector<std::string>& names) {}; void get_sampler_params(std::vector<double>& values) {}; }; } } TEST(McmcBaseHMC, point_construction) { rng_t base_rng(0); std::vector<double> q(5, 1.0); std::vector<int> r(2, 2); stan::mcmc::mock_model model(q.size()); stan::mcmc::mock_hmc sampler(model, base_rng, &std::cout, &std::cerr); EXPECT_EQ(static_cast<size_t>(q.size()), sampler.z().q.size()); EXPECT_EQ(static_cast<int>(q.size()), sampler.z().g.size()); } TEST(McmcBaseHMC, seed) { rng_t base_rng(0); std::vector<double> q(5, 1.0); std::vector<int> r; stan::mcmc::mock_model model(q.size()); stan::mcmc::mock_hmc sampler(model, base_rng, &std::cout, &std::cerr); std::vector<double> q_seed(q.size(), -1.0); sampler.seed(q_seed, r); for (std::vector<double>::size_type i = 0; i < q.size(); ++i) EXPECT_EQ(q_seed.at(i), sampler.z().q.at(i)); } TEST(McmcBaseHMC, set_nominal_stepsize) { rng_t base_rng(0); std::vector<double> q(5, 1.0); std::vector<int> r(2, 2); stan::mcmc::mock_model model(q.size()); stan::mcmc::mock_hmc sampler(model, base_rng, &std::cout, &std::cerr); double old_epsilon = 1.0; sampler.set_nominal_stepsize(old_epsilon); EXPECT_EQ(old_epsilon, sampler.get_nominal_stepsize()); sampler.set_nominal_stepsize(-0.1); EXPECT_EQ(old_epsilon, sampler.get_nominal_stepsize()); } TEST(McmcBaseHMC, set_stepsize_jitter) { rng_t base_rng(0); std::vector<double> q(5, 1.0); std::vector<int> r(2, 2); stan::mcmc::mock_model model(q.size()); stan::mcmc::mock_hmc sampler(model, base_rng, &std::cout, &std::cerr); double old_jitter = 0.1; sampler.set_stepsize_jitter(old_jitter); EXPECT_EQ(old_jitter, sampler.get_stepsize_jitter()); sampler.set_nominal_stepsize(-0.1); EXPECT_EQ(old_jitter, sampler.get_stepsize_jitter()); } TEST(McmcBaseHMC, init_stepsize) { std::vector<std::string> model_path; model_path.push_back("src"); model_path.push_back("test"); model_path.push_back("mcmc"); model_path.push_back("models"); model_path.push_back("improper"); std::string command = convert_model_path(model_path); command += " sample output file=" + convert_model_path(model_path) + ".csv"; run_command_output out; out = run_command(command); EXPECT_FALSE(out.hasError); EXPECT_EQ("Posterior is improper. Please check your model.", out.output.erase(out.output.length()-1).substr(out.output.rfind('\n')).erase(0, 1) ); } <commit_msg>fixed test so it's windows safe<commit_after>#include <test/mcmc/mock_hmc.hpp> #include <stan/mcmc/hmc/base_hmc.hpp> #include <boost/random/additive_combine.hpp> #include <boost/algorithm/string/split.hpp> #include <gtest/gtest.h> #include <test/models/utility.hpp> typedef boost::ecuyer1988 rng_t; namespace stan { namespace mcmc { class mock_hmc: public base_hmc<mock_model, ps_point, mock_hamiltonian, mock_integrator, rng_t> { public: mock_hmc(mock_model& m, rng_t& rng, std::ostream* o, std::ostream* e) : base_hmc<mock_model,ps_point,mock_hamiltonian,mock_integrator,rng_t> (m, rng, o, e) { this->_name = "Mock HMC"; } sample transition(sample& init_sample) { this->seed(init_sample.cont_params(), init_sample.disc_params()); return sample(this->_z.q, this->_z.r, - this->_hamiltonian.V(this->_z), 0); } void write_sampler_param_names(std::ostream& o) {}; void write_sampler_params(std::ostream& o) {}; void get_sampler_param_names(std::vector<std::string>& names) {}; void get_sampler_params(std::vector<double>& values) {}; }; } } TEST(McmcBaseHMC, point_construction) { rng_t base_rng(0); std::vector<double> q(5, 1.0); std::vector<int> r(2, 2); stan::mcmc::mock_model model(q.size()); stan::mcmc::mock_hmc sampler(model, base_rng, &std::cout, &std::cerr); EXPECT_EQ(static_cast<size_t>(q.size()), sampler.z().q.size()); EXPECT_EQ(static_cast<int>(q.size()), sampler.z().g.size()); } TEST(McmcBaseHMC, seed) { rng_t base_rng(0); std::vector<double> q(5, 1.0); std::vector<int> r; stan::mcmc::mock_model model(q.size()); stan::mcmc::mock_hmc sampler(model, base_rng, &std::cout, &std::cerr); std::vector<double> q_seed(q.size(), -1.0); sampler.seed(q_seed, r); for (std::vector<double>::size_type i = 0; i < q.size(); ++i) EXPECT_EQ(q_seed.at(i), sampler.z().q.at(i)); } TEST(McmcBaseHMC, set_nominal_stepsize) { rng_t base_rng(0); std::vector<double> q(5, 1.0); std::vector<int> r(2, 2); stan::mcmc::mock_model model(q.size()); stan::mcmc::mock_hmc sampler(model, base_rng, &std::cout, &std::cerr); double old_epsilon = 1.0; sampler.set_nominal_stepsize(old_epsilon); EXPECT_EQ(old_epsilon, sampler.get_nominal_stepsize()); sampler.set_nominal_stepsize(-0.1); EXPECT_EQ(old_epsilon, sampler.get_nominal_stepsize()); } TEST(McmcBaseHMC, set_stepsize_jitter) { rng_t base_rng(0); std::vector<double> q(5, 1.0); std::vector<int> r(2, 2); stan::mcmc::mock_model model(q.size()); stan::mcmc::mock_hmc sampler(model, base_rng, &std::cout, &std::cerr); double old_jitter = 0.1; sampler.set_stepsize_jitter(old_jitter); EXPECT_EQ(old_jitter, sampler.get_stepsize_jitter()); sampler.set_nominal_stepsize(-0.1); EXPECT_EQ(old_jitter, sampler.get_stepsize_jitter()); } <|endoftext|>
<commit_before>// The MIT License (MIT) // // Copyright (c) 2013-2014 Sound Metrics Corporation. All Rights Reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "SlidingWindowFrameAssembler.h" #include "frame_stream.h" #include <boost/asio/buffer.hpp> #include <myboost/scoped_guard.h> namespace Aris { namespace Network { using namespace boost; using namespace boost::asio; namespace { SlidingWindowFrameAssembler::Metrics operator+(const SlidingWindowFrameAssembler::Metrics &a, const SlidingWindowFrameAssembler::Metrics &b) { auto m = a; m.uniqueFrameIndexCount += b.uniqueFrameIndexCount; m.finishedFrameCount += b.finishedFrameCount; m.completeFrameCount += b.completeFrameCount; m.skippedFrameCount += b.skippedFrameCount; m.totalExpectedFrameSize += b.totalExpectedFrameSize; m.totalReceivedFrameSize += b.totalReceivedFrameSize; m.totalPacketsReceived += b.totalPacketsReceived; m.totalPacketsAccepted += b.totalPacketsAccepted; m.totalPacketsIgnored += b.totalPacketsIgnored; m.invalidPacketCount += b.invalidPacketCount; return m; } } SlidingWindowFrameAssembler::SlidingWindowFrameAssembler( boost::function<void(int, int)> sendAck, boost::function<void(FrameBuilder &)> onFrameFinished) : sendAck(sendAck), onFrameFinished(onFrameFinished), currentFrameIndex(-1), lastFinishedFrameIndex(-1), expectedDataOffset(0) { Metrics emptyMetrics = {}; metrics = emptyMetrics; } void SlidingWindowFrameAssembler::ProcessPacket(const_buffer data) { bool acceptedPacket = false, invalidPacket = false; uint32_t skippedFrameCount = 0; scoped_guard updateMetrics([&]() { Metrics update = {}; update.skippedFrameCount = skippedFrameCount; update.totalPacketsReceived = 1; update.totalPacketsAccepted = acceptedPacket ? 1 : 0; update.totalPacketsIgnored = acceptedPacket ? 0 : 1; update.invalidPacketCount = invalidPacket ? 1 : 0; UpdateMetrics(update); }); recursive_mutex::scoped_lock lock(stateGuard); frame_stream::FramePart framePart; if (!framePart.ParseFromArray(buffer_cast<const uint8_t *>(data), buffer_size(data))) { invalidPacket = true; // TODO log return; } const int incomingFrameIndex = framePart.frame_index(); const int incomingDataOffset = framePart.data_offset(); if (incomingFrameIndex > currentFrameIndex) { // sender moved on to the next frame Flush(); skippedFrameCount = incomingFrameIndex - currentFrameIndex - 1; currentFrameIndex = incomingFrameIndex; expectedDataOffset = 0; } else if (incomingFrameIndex <= lastFinishedFrameIndex) { return; // duplicate packet from finished frame } if (!currentFrame) { if (incomingDataOffset == 0) { currentFrame = std::unique_ptr<FrameBuilder>(new FrameBuilder( incomingFrameIndex, buffer(framePart.header().c_str(), framePart.header().size()), buffer(framePart.data().c_str(), framePart.data().size()), framePart.total_data_size())); expectedDataOffset = framePart.data().size(); acceptedPacket = true; } else { // Ack will go out asking for the first part of the frame to be resent. } } else { if (incomingDataOffset == expectedDataOffset) { currentFrame->AppendFrameData( incomingDataOffset, buffer(framePart.data().c_str(), framePart.data().size())); expectedDataOffset += framePart.data().size(); acceptedPacket = true; } else { // Missed a part. } } // NOTE: we're always acking each packet for now; this should change when we // develop strategies for retrying packets. sendAck(incomingFrameIndex, expectedDataOffset); if (expectedDataOffset == framePart.total_data_size()) Flush(); } void SlidingWindowFrameAssembler::Flush() { recursive_mutex::scoped_lock lock(stateGuard); if (currentFrame) { std::unique_ptr<FrameBuilder> frame; frame.swap(currentFrame); assert(!currentFrame); UpdateMetrics(GetMetricsForFinishedFrame(*frame)); lastFinishedFrameIndex = frame->FrameIndex(); onFrameFinished(*frame); } } SlidingWindowFrameAssembler::Metrics SlidingWindowFrameAssembler::GetMetrics() { recursive_mutex::scoped_lock lock(metricsGuard); return metrics; } void SlidingWindowFrameAssembler::UpdateMetrics(const Metrics &update) { recursive_mutex::scoped_lock lock(metricsGuard); metrics = metrics + update; } /* static */ SlidingWindowFrameAssembler::Metrics SlidingWindowFrameAssembler::GetMetricsForFinishedFrame( const FrameBuilder &frame) { Metrics metrics = {}; metrics.uniqueFrameIndexCount = 1; metrics.finishedFrameCount = 1; metrics.completeFrameCount = frame.IsComplete() ? 1 : 0; metrics.totalExpectedFrameSize = frame.ExpectedSize(); metrics.totalReceivedFrameSize = frame.BytesReceived(); return metrics; } } } <commit_msg>Fixes #30--reference to myboost.<commit_after>// The MIT License (MIT) // // Copyright (c) 2013-2014 Sound Metrics Corporation. All Rights Reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "SlidingWindowFrameAssembler.h" #include "frame_stream.h" #include <boost/asio/buffer.hpp> #include <boost/function.hpp> namespace { // Execute the lambda expression at the end of the scope. class scoped_guard : boost::noncopyable { boost::function<void()> lambda; public: scoped_guard(boost::function<void()> action) : lambda(action) { } ~scoped_guard() { try { lambda(); } catch (...) { // Ignore. } } }; } namespace Aris { namespace Network { using namespace boost; using namespace boost::asio; namespace { SlidingWindowFrameAssembler::Metrics operator+(const SlidingWindowFrameAssembler::Metrics &a, const SlidingWindowFrameAssembler::Metrics &b) { auto m = a; m.uniqueFrameIndexCount += b.uniqueFrameIndexCount; m.finishedFrameCount += b.finishedFrameCount; m.completeFrameCount += b.completeFrameCount; m.skippedFrameCount += b.skippedFrameCount; m.totalExpectedFrameSize += b.totalExpectedFrameSize; m.totalReceivedFrameSize += b.totalReceivedFrameSize; m.totalPacketsReceived += b.totalPacketsReceived; m.totalPacketsAccepted += b.totalPacketsAccepted; m.totalPacketsIgnored += b.totalPacketsIgnored; m.invalidPacketCount += b.invalidPacketCount; return m; } } SlidingWindowFrameAssembler::SlidingWindowFrameAssembler( boost::function<void(int, int)> sendAck, boost::function<void(FrameBuilder &)> onFrameFinished) : sendAck(sendAck), onFrameFinished(onFrameFinished), currentFrameIndex(-1), lastFinishedFrameIndex(-1), expectedDataOffset(0) { Metrics emptyMetrics = {}; metrics = emptyMetrics; } void SlidingWindowFrameAssembler::ProcessPacket(const_buffer data) { bool acceptedPacket = false, invalidPacket = false; uint32_t skippedFrameCount = 0; scoped_guard updateMetrics([&]() { Metrics update = {}; update.skippedFrameCount = skippedFrameCount; update.totalPacketsReceived = 1; update.totalPacketsAccepted = acceptedPacket ? 1 : 0; update.totalPacketsIgnored = acceptedPacket ? 0 : 1; update.invalidPacketCount = invalidPacket ? 1 : 0; UpdateMetrics(update); }); recursive_mutex::scoped_lock lock(stateGuard); frame_stream::FramePart framePart; if (!framePart.ParseFromArray(buffer_cast<const uint8_t *>(data), buffer_size(data))) { invalidPacket = true; // TODO log return; } const int incomingFrameIndex = framePart.frame_index(); const int incomingDataOffset = framePart.data_offset(); if (incomingFrameIndex > currentFrameIndex) { // sender moved on to the next frame Flush(); skippedFrameCount = incomingFrameIndex - currentFrameIndex - 1; currentFrameIndex = incomingFrameIndex; expectedDataOffset = 0; } else if (incomingFrameIndex <= lastFinishedFrameIndex) { return; // duplicate packet from finished frame } if (!currentFrame) { if (incomingDataOffset == 0) { currentFrame = std::unique_ptr<FrameBuilder>(new FrameBuilder( incomingFrameIndex, buffer(framePart.header().c_str(), framePart.header().size()), buffer(framePart.data().c_str(), framePart.data().size()), framePart.total_data_size())); expectedDataOffset = framePart.data().size(); acceptedPacket = true; } else { // Ack will go out asking for the first part of the frame to be resent. } } else { if (incomingDataOffset == expectedDataOffset) { currentFrame->AppendFrameData( incomingDataOffset, buffer(framePart.data().c_str(), framePart.data().size())); expectedDataOffset += framePart.data().size(); acceptedPacket = true; } else { // Missed a part. } } // NOTE: we're always acking each packet for now; this should change when we // develop strategies for retrying packets. sendAck(incomingFrameIndex, expectedDataOffset); if (expectedDataOffset == framePart.total_data_size()) Flush(); } void SlidingWindowFrameAssembler::Flush() { recursive_mutex::scoped_lock lock(stateGuard); if (currentFrame) { std::unique_ptr<FrameBuilder> frame; frame.swap(currentFrame); assert(!currentFrame); UpdateMetrics(GetMetricsForFinishedFrame(*frame)); lastFinishedFrameIndex = frame->FrameIndex(); onFrameFinished(*frame); } } SlidingWindowFrameAssembler::Metrics SlidingWindowFrameAssembler::GetMetrics() { recursive_mutex::scoped_lock lock(metricsGuard); return metrics; } void SlidingWindowFrameAssembler::UpdateMetrics(const Metrics &update) { recursive_mutex::scoped_lock lock(metricsGuard); metrics = metrics + update; } /* static */ SlidingWindowFrameAssembler::Metrics SlidingWindowFrameAssembler::GetMetricsForFinishedFrame( const FrameBuilder &frame) { Metrics metrics = {}; metrics.uniqueFrameIndexCount = 1; metrics.finishedFrameCount = 1; metrics.completeFrameCount = frame.IsComplete() ? 1 : 0; metrics.totalExpectedFrameSize = frame.ExpectedSize(); metrics.totalReceivedFrameSize = frame.BytesReceived(); return metrics; } } } <|endoftext|>
<commit_before>/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Copyright (C) 2017, James R. Barlow (https://github.com/jbarlow83/) */ /* * Convert Python types <-> QPDFObjectHandle types */ #include <vector> #include <map> #include <qpdf/Constants.h> #include <qpdf/Types.h> #include <qpdf/DLL.h> #include <qpdf/QPDFExc.hh> #include <qpdf/QPDFObjGen.hh> #include <qpdf/PointerHolder.hh> #include <qpdf/Buffer.hh> #include <qpdf/QPDFObjectHandle.hh> #include <qpdf/QPDF.hh> #include <qpdf/QPDFWriter.hh> #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include "pikepdf.h" std::map<std::string, QPDFObjectHandle> dict_builder(py::dict dict) { std::map<std::string, QPDFObjectHandle> result; for (auto item: dict) { std::string key = item.first.cast<std::string>(); auto value = objecthandle_encode(item.second); result[key] = value; } return result; } std::vector<QPDFObjectHandle> array_builder(py::iterable iter) { std::vector<QPDFObjectHandle> result; int narg = 0; for (auto item: iter) { narg++; auto value = objecthandle_encode(item); result.push_back(value); } return result; } QPDFObjectHandle objecthandle_encode(py::handle handle) { if (handle.is_none()) return QPDFObjectHandle::newNull(); // Ensure that when we return QPDFObjectHandle/pikepdf.Object to the Py // environment, that we can recover it try { auto as_qobj = handle.cast<QPDFObjectHandle>(); return as_qobj; } catch (py::cast_error) {} // Special-case booleans since pybind11 coerces nonzero integers to boolean if (py::isinstance<py::bool_>(handle)) { bool as_bool = handle.cast<bool>(); return QPDFObjectHandle::newBool(as_bool); } try { auto as_int = handle.cast<long long>(); return QPDFObjectHandle::newInteger(as_int); } catch (py::cast_error) {} try { auto as_double = handle.cast<double>(); return QPDFObjectHandle::newReal(as_double); } catch (py::cast_error) {} py::object obj = py::reinterpret_borrow<py::object>(handle); if (py::isinstance<py::bytes>(obj)) { auto py_bytes = py::bytes(obj); return QPDFObjectHandle::newString(static_cast<std::string>(py_bytes)); } else if (py::isinstance<py::str>(obj)) { // Convert all Py strings to UTF-16, big endian, byte order marks, which // is what PDF uses internally. Big endian is used independent of // platform endian. auto py_str = py::str(obj); std::string utf16 = py::reinterpret_steal<py::bytes>( PyUnicode_AsEncodedString(py_str.ptr(), "utf-16be", "strict")); if (utf16.size() == 0) return QPDFObjectHandle::newString(""); // Put the utf-16be string in a regular std::string... that is what // QPDF wants std::string utf16_encoded = std::string("\xfe\xff") + utf16; return QPDFObjectHandle::newString(utf16_encoded); } if (py::hasattr(obj, "__iter__")) { //py::print(py::repr(obj)); bool is_mapping = false; // PyMapping_Check is unreliable in Py3 if (py::hasattr(obj, "keys")) is_mapping = true; bool is_sequence = PySequence_Check(obj.ptr()); if (is_mapping) { return QPDFObjectHandle::newDictionary(dict_builder(obj)); } else if (is_sequence) { return QPDFObjectHandle::newArray(array_builder(obj)); } } if (obj.is(py::object())) { return QPDFObjectHandle::newNull(); } throw py::cast_error(std::string("don't know how to encode value") + std::string(py::repr(obj))); } py::object decimal_from_pdfobject(QPDFObjectHandle& h) { auto decimal_constructor = py::module::import("decimal").attr("Decimal"); if (h.getTypeCode() == QPDFObject::object_type_e::ot_integer) { auto value = h.getIntValue(); return decimal_constructor(py::cast(value)); } else if (h.getTypeCode() == QPDFObject::object_type_e::ot_real) { auto value = h.getRealValue(); return decimal_constructor(py::cast(value)); } throw py::type_error("object has no Decimal() representation"); } py::object objecthandle_decode(QPDFObjectHandle& h) { py::object obj = py::none(); switch (h.getTypeCode()) { case QPDFObject::object_type_e::ot_null: return py::none(); case QPDFObject::object_type_e::ot_integer: obj = py::cast(h.getIntValue()); break; case QPDFObject::object_type_e::ot_boolean: obj = py::cast(h.getBoolValue()); break; case QPDFObject::object_type_e::ot_real: obj = decimal_from_pdfobject(h); break; case QPDFObject::object_type_e::ot_name: break; case QPDFObject::object_type_e::ot_string: obj = py::bytes(h.getStringValue()); break; case QPDFObject::object_type_e::ot_operator: break; case QPDFObject::object_type_e::ot_inlineimage: break; case QPDFObject::object_type_e::ot_array: { py::list lst; for (auto item: h.getArrayAsVector()) { lst.append(objecthandle_decode(item)); } obj = lst; } break; case QPDFObject::object_type_e::ot_dictionary: break; case QPDFObject::object_type_e::ot_stream: break; default: break; } if (obj.is_none()) throw py::type_error("not decodable"); return obj; }<commit_msg>Unicode: use ASCII representation when possible<commit_after>/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Copyright (C) 2017, James R. Barlow (https://github.com/jbarlow83/) */ /* * Convert Python types <-> QPDFObjectHandle types */ #include <vector> #include <map> #include <qpdf/Constants.h> #include <qpdf/Types.h> #include <qpdf/DLL.h> #include <qpdf/QPDFExc.hh> #include <qpdf/QPDFObjGen.hh> #include <qpdf/PointerHolder.hh> #include <qpdf/Buffer.hh> #include <qpdf/QPDFObjectHandle.hh> #include <qpdf/QPDF.hh> #include <qpdf/QPDFWriter.hh> #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include "pikepdf.h" std::map<std::string, QPDFObjectHandle> dict_builder(py::dict dict) { std::map<std::string, QPDFObjectHandle> result; for (auto item: dict) { std::string key = item.first.cast<std::string>(); auto value = objecthandle_encode(item.second); result[key] = value; } return result; } std::vector<QPDFObjectHandle> array_builder(py::iterable iter) { std::vector<QPDFObjectHandle> result; int narg = 0; for (auto item: iter) { narg++; auto value = objecthandle_encode(item); result.push_back(value); } return result; } QPDFObjectHandle objecthandle_encode(py::handle handle) { if (handle.is_none()) return QPDFObjectHandle::newNull(); // Ensure that when we return QPDFObjectHandle/pikepdf.Object to the Py // environment, that we can recover it try { auto as_qobj = handle.cast<QPDFObjectHandle>(); return as_qobj; } catch (py::cast_error) {} // Special-case booleans since pybind11 coerces nonzero integers to boolean if (py::isinstance<py::bool_>(handle)) { bool as_bool = handle.cast<bool>(); return QPDFObjectHandle::newBool(as_bool); } try { auto as_int = handle.cast<long long>(); return QPDFObjectHandle::newInteger(as_int); } catch (py::cast_error) {} try { auto as_double = handle.cast<double>(); return QPDFObjectHandle::newReal(as_double); } catch (py::cast_error) {} py::object obj = py::reinterpret_borrow<py::object>(handle); if (py::isinstance<py::bytes>(obj)) { auto py_bytes = py::bytes(obj); return QPDFObjectHandle::newString(static_cast<std::string>(py_bytes)); } else if (py::isinstance<py::str>(obj)) { // Convert all Py strings to UTF-16, big endian, byte order marks, which // is what PDF uses internally. Big endian is used independent of // platform endian. auto py_str = py::str(obj); py::object ascii = py::reinterpret_steal<py::object>( PyUnicode_AsEncodedString(py_str.ptr(), "ascii", nullptr)); if (ascii) return QPDFObjectHandle::newString(py::bytes(ascii)); PyErr_Clear(); // Or else we crash std::string utf16 = py::reinterpret_steal<py::bytes>( PyUnicode_AsEncodedString(py_str.ptr(), "utf-16be", nullptr)); if (utf16.size() == 0) return QPDFObjectHandle::newString(""); // Put the utf-16be string in a regular std::string... that is what // QPDF wants std::string utf16_encoded = std::string("\xfe\xff") + utf16; return QPDFObjectHandle::newString(utf16_encoded); } if (py::hasattr(obj, "__iter__")) { //py::print(py::repr(obj)); bool is_mapping = false; // PyMapping_Check is unreliable in Py3 if (py::hasattr(obj, "keys")) is_mapping = true; bool is_sequence = PySequence_Check(obj.ptr()); if (is_mapping) { return QPDFObjectHandle::newDictionary(dict_builder(obj)); } else if (is_sequence) { return QPDFObjectHandle::newArray(array_builder(obj)); } } if (obj.is(py::object())) { return QPDFObjectHandle::newNull(); } throw py::cast_error(std::string("don't know how to encode value") + std::string(py::repr(obj))); } py::object decimal_from_pdfobject(QPDFObjectHandle& h) { auto decimal_constructor = py::module::import("decimal").attr("Decimal"); if (h.getTypeCode() == QPDFObject::object_type_e::ot_integer) { auto value = h.getIntValue(); return decimal_constructor(py::cast(value)); } else if (h.getTypeCode() == QPDFObject::object_type_e::ot_real) { auto value = h.getRealValue(); return decimal_constructor(py::cast(value)); } throw py::type_error("object has no Decimal() representation"); } py::object objecthandle_decode(QPDFObjectHandle& h) { py::object obj = py::none(); switch (h.getTypeCode()) { case QPDFObject::object_type_e::ot_null: return py::none(); case QPDFObject::object_type_e::ot_integer: obj = py::cast(h.getIntValue()); break; case QPDFObject::object_type_e::ot_boolean: obj = py::cast(h.getBoolValue()); break; case QPDFObject::object_type_e::ot_real: obj = decimal_from_pdfobject(h); break; case QPDFObject::object_type_e::ot_name: break; case QPDFObject::object_type_e::ot_string: obj = py::bytes(h.getStringValue()); break; case QPDFObject::object_type_e::ot_operator: break; case QPDFObject::object_type_e::ot_inlineimage: break; case QPDFObject::object_type_e::ot_array: { py::list lst; for (auto item: h.getArrayAsVector()) { lst.append(objecthandle_decode(item)); } obj = lst; } break; case QPDFObject::object_type_e::ot_dictionary: break; case QPDFObject::object_type_e::ot_stream: break; default: break; } if (obj.is_none()) throw py::type_error("not decodable"); return obj; }<|endoftext|>
<commit_before> // Include #include "nui.h" #include "nglThread.h" #include "nglThreadChecker.h" /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // nglThread class. // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class nglThreadPrivate { friend class nglThread; public: // Start static inline void Start(nglThread * pThread) { if(pThread) { bool deleted = false; NGL_ASSERT(pThread->mpData); pThread->mpData->mpDeleted = &deleted; nglThread::ID ThreadID = pThread->GetID(); nglString ThreadName = pThread->GetName(); // register the thread by the nglThreadChecker nglThreadChecker::RegisterThread(ThreadID, ThreadName); // Call main thread method (which often contains a loop inside) pThread->OnStart(); // warn the nglThreadChecker that the thread stoped nglThreadChecker::UnregisterThread(ThreadID); // Now, the thread is closed pThread->mState = nglThread::Closed; if (!deleted) { if (pThread->GetAutoDelete()) { delete pThread; } else { pThread->mpData->mpDeleted = NULL; } } } // // IMPORTANT: no need to call 'ExitThread' which is "C" coding style. // in C++, you just have to return, that's all. // See MSDN for details. //ExitThread(0); } // Get inline nglThread::ID GetThreadID() const { return mThreadID; } void SetDeleted() { *mpDeleted = true; } nglThreadPrivate() { mpDeleted = NULL; mThread = NULL; mThreadID = NULL; } ~nglThreadPrivate() { if (mpDeleted) *mpDeleted = true; } private: // Data HANDLE mThread; DWORD mThreadID; bool* mpDeleted; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Static function /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static DWORD WINAPI start_thread(void *arg) { nglThreadPrivate::Start( (nglThread*)arg ); return 0; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Constructor /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Constructor of nglThread class // nglThread::nglThread(Priority priority) { mpData = new nglThreadPrivate(); mState = Stopped; mPriority = priority; mAutoDelete = false; } nglThread::nglThread(const nglString& rName, Priority priority) { mName = rName; mpData = new nglThreadPrivate(); mState = Stopped; mPriority = priority; mAutoDelete = false; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Destructor /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Destructor of nglThread class // nglThread::~nglThread() { NGL_OUT(_T("nglThread::~nglThread() [this=0x%x '%ls']\n"), this, GetName().GetChars()); CloseHandle(mpData->mThread); delete mpData; mpData = NULL; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Start /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Start a paused thread // bool nglThread::Start() { DWORD res = 0; // Maybe release the previous thread instance ? if (mpData->mThread && mState==Closed) { CloseHandle(mpData->mThread); mpData->mThread = NULL; mpData->mThreadID = 0; } // If the thread is not created, do it if(mpData->mThread==NULL) { // Create the thread mpData->mThread = CreateThread(NULL, 0, start_thread, this, 0, & mpData->mThreadID); if(!mpData->mThread) return false; // Add it in global list nglAddThreadInGlobalList(this); // Set its priority SetPriority(mPriority); } // Status mState = Running; return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Join /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Wait until the thread is stopped // bool nglThread::Join() { if (mState == Closed) return true; // If the thread is not running, return false if (!mpData->mThread || mState == Stopped) return false; // We wait the end of the thread if (WAIT_FAILED == WaitForSingleObject(mpData->mThread, INFINITE)) return false; // Status mState = Closed; // Remove thread from list nglDelThreadFromGlobalList(this); return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // OnStart /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // void nglThread::OnStart() { // Do nothing by default mpData->mThread = NULL; mpData->mThreadID = NULL; ExitThread(0); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // IsCurrent /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // bool nglThread::IsCurrent() const { return GetCurrentThread() == mpData->mThread; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // GetState /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // nglThread::State nglThread::GetState() const { return mState; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // GetPriority /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // nglThread::Priority nglThread::GetPriority() const { return mPriority; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // SetPriority /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Set thread priority // bool nglThread::SetPriority(Priority priority) { static const int priorityTable[] = { THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_BELOW_NORMAL, THREAD_PRIORITY_NORMAL, THREAD_PRIORITY_ABOVE_NORMAL, THREAD_PRIORITY_HIGHEST, THREAD_PRIORITY_TIME_CRITICAL }; return SetThreadPriority(mpData->mThread, priorityTable[priority]) == TRUE; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // GetCurThread /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Return current active thread // nglThread* nglThread::GetCurThread() { return nglGetThreadFromGlobalList( ::GetCurrentThreadId() ); } nglThread::ID nglThread::GetCurThreadID() { return ::GetCurrentThreadId(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Sleep /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Sleep (seconds) // void nglThread::Sleep(uint32 secs) { ::Sleep(secs * 1000); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // MsSleep /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Sleep (milliseconds) // void nglThread::MsSleep(uint32 msecs) { ::Sleep(msecs); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // USleep /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Sleep (microseconds) // void nglThread::USleep(uint32 usecs) { ::Sleep(usecs/1000); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // GetID /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Return thread ID // nglThread::ID nglThread::GetID() const { return mpData->GetThreadID(); } <commit_msg>fixed win32 crash : comments on ngl_out call<commit_after> // Include #include "nui.h" #include "nglThread.h" #include "nglThreadChecker.h" /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // nglThread class. // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class nglThreadPrivate { friend class nglThread; public: // Start static inline void Start(nglThread * pThread) { if(pThread) { bool deleted = false; NGL_ASSERT(pThread->mpData); pThread->mpData->mpDeleted = &deleted; nglThread::ID ThreadID = pThread->GetID(); nglString ThreadName = pThread->GetName(); // register the thread by the nglThreadChecker nglThreadChecker::RegisterThread(ThreadID, ThreadName); // Call main thread method (which often contains a loop inside) pThread->OnStart(); // warn the nglThreadChecker that the thread stoped nglThreadChecker::UnregisterThread(ThreadID); // Now, the thread is closed pThread->mState = nglThread::Closed; if (!deleted) { if (pThread->GetAutoDelete()) { delete pThread; } else { pThread->mpData->mpDeleted = NULL; } } } // // IMPORTANT: no need to call 'ExitThread' which is "C" coding style. // in C++, you just have to return, that's all. // See MSDN for details. //ExitThread(0); } // Get inline nglThread::ID GetThreadID() const { return mThreadID; } void SetDeleted() { *mpDeleted = true; } nglThreadPrivate() { mpDeleted = NULL; mThread = NULL; mThreadID = NULL; } ~nglThreadPrivate() { if (mpDeleted) *mpDeleted = true; } private: // Data HANDLE mThread; DWORD mThreadID; bool* mpDeleted; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Static function /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static DWORD WINAPI start_thread(void *arg) { nglThreadPrivate::Start( (nglThread*)arg ); return 0; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Constructor /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Constructor of nglThread class // nglThread::nglThread(Priority priority) { mpData = new nglThreadPrivate(); mState = Stopped; mPriority = priority; mAutoDelete = false; } nglThread::nglThread(const nglString& rName, Priority priority) { mName = rName; mpData = new nglThreadPrivate(); mState = Stopped; mPriority = priority; mAutoDelete = false; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Destructor /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Destructor of nglThread class // nglThread::~nglThread() { // NGL_OUT(_T("nglThread::~nglThread() [this=0x%x '%ls']\n"), this, GetName().GetChars()); CloseHandle(mpData->mThread); delete mpData; mpData = NULL; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Start /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Start a paused thread // bool nglThread::Start() { DWORD res = 0; // Maybe release the previous thread instance ? if (mpData->mThread && mState==Closed) { CloseHandle(mpData->mThread); mpData->mThread = NULL; mpData->mThreadID = 0; } // If the thread is not created, do it if(mpData->mThread==NULL) { // Create the thread mpData->mThread = CreateThread(NULL, 0, start_thread, this, 0, & mpData->mThreadID); if(!mpData->mThread) return false; // Add it in global list nglAddThreadInGlobalList(this); // Set its priority SetPriority(mPriority); } // Status mState = Running; return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Join /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Wait until the thread is stopped // bool nglThread::Join() { if (mState == Closed) return true; // If the thread is not running, return false if (!mpData->mThread || mState == Stopped) return false; // We wait the end of the thread if (WAIT_FAILED == WaitForSingleObject(mpData->mThread, INFINITE)) return false; // Status mState = Closed; // Remove thread from list nglDelThreadFromGlobalList(this); return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // OnStart /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // void nglThread::OnStart() { // Do nothing by default mpData->mThread = NULL; mpData->mThreadID = NULL; ExitThread(0); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // IsCurrent /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // bool nglThread::IsCurrent() const { return GetCurrentThread() == mpData->mThread; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // GetState /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // nglThread::State nglThread::GetState() const { return mState; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // GetPriority /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // nglThread::Priority nglThread::GetPriority() const { return mPriority; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // SetPriority /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Set thread priority // bool nglThread::SetPriority(Priority priority) { static const int priorityTable[] = { THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_BELOW_NORMAL, THREAD_PRIORITY_NORMAL, THREAD_PRIORITY_ABOVE_NORMAL, THREAD_PRIORITY_HIGHEST, THREAD_PRIORITY_TIME_CRITICAL }; return SetThreadPriority(mpData->mThread, priorityTable[priority]) == TRUE; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // GetCurThread /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Return current active thread // nglThread* nglThread::GetCurThread() { return nglGetThreadFromGlobalList( ::GetCurrentThreadId() ); } nglThread::ID nglThread::GetCurThreadID() { return ::GetCurrentThreadId(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Sleep /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Sleep (seconds) // void nglThread::Sleep(uint32 secs) { ::Sleep(secs * 1000); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // MsSleep /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Sleep (milliseconds) // void nglThread::MsSleep(uint32 msecs) { ::Sleep(msecs); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // USleep /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Sleep (microseconds) // void nglThread::USleep(uint32 usecs) { ::Sleep(usecs/1000); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // GetID /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Return thread ID // nglThread::ID nglThread::GetID() const { return mpData->GetThreadID(); } <|endoftext|>
<commit_before>// Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved // Please see LICENSE.md in repository root for license information // https://github.com/AtomicGameEngine/AtomicGameEngine #include "AtomicEditor.h" #include <Atomic/IO/FileSystem.h> #include "../AEEditor.h" #include "../Project/AEProject.h" #include "../Project/ProjectUtils.h" #include "License/AELicenseSystem.h" #include "BuildSystem.h" #include "BuildWindows.h" namespace AtomicEditor { BuildWindows::BuildWindows(Context * context) : BuildBase(context) { } BuildWindows::~BuildWindows() { } void BuildWindows::Initialize() { Editor* editor = GetSubsystem<Editor>(); Project* project = editor->GetProject(); FileSystem* fileSystem = GetSubsystem<FileSystem>(); #ifdef ATOMIC_PLATFORM_WINDOWS String bundleResources = fileSystem->GetProgramDir(); #else String bundleResources = fileSystem->GetAppBundleResourceFolder(); #endif String projectResources = project->GetResourcePath(); String coreDataFolder = bundleResources + "CoreData/"; AddResourceDir(coreDataFolder); AddResourceDir(projectResources); BuildResourceEntries(); } void BuildWindows::Build(const String& buildPath) { buildPath_ = buildPath + "/Windows-Build"; Initialize(); BuildSystem* buildSystem = GetSubsystem<BuildSystem>(); // BEGIN LICENSE MANAGEMENT LicenseSystem *licenseSystem = GetSubsystem<LicenseSystem>(); if (licenseSystem->IsStandardLicense()) { if (containsMDL_) { buildSystem->BuildComplete(AE_PLATFORM_WINDOWS, buildPath_, false, true); return; } } // END LICENSE MANAGEMENT FileSystem* fileSystem = GetSubsystem<FileSystem>(); if (fileSystem->DirExists(buildPath_)) fileSystem->RemoveDir(buildPath_, true); #ifdef ATOMIC_PLATFORM_WINDOWS String buildSourceDir = fileSystem->GetProgramDir(); #else String buildSourceDir = fileSystem->GetAppBundleResourceFolder(); #endif buildSourceDir += "Deployment/Win64"; fileSystem->CreateDir(buildPath_); fileSystem->CreateDir(buildPath_ + "/AtomicPlayer_Resources"); String resourcePackagePath = buildPath_ + "/AtomicPlayer_Resources/AtomicResources.pak"; GenerateResourcePackage(resourcePackagePath); fileSystem->Copy(buildSourceDir + "/AtomicPlayer.exe", buildPath_ + "/AtomicPlayer.exe"); buildSystem->BuildComplete(AE_PLATFORM_WINDOWS, buildPath_); } } <commit_msg>Copy D3DCompiler on Windows deployment<commit_after>// Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved // Please see LICENSE.md in repository root for license information // https://github.com/AtomicGameEngine/AtomicGameEngine #include "AtomicEditor.h" #include <Atomic/IO/FileSystem.h> #include "../AEEditor.h" #include "../Project/AEProject.h" #include "../Project/ProjectUtils.h" #include "License/AELicenseSystem.h" #include "BuildSystem.h" #include "BuildWindows.h" namespace AtomicEditor { BuildWindows::BuildWindows(Context * context) : BuildBase(context) { } BuildWindows::~BuildWindows() { } void BuildWindows::Initialize() { Editor* editor = GetSubsystem<Editor>(); Project* project = editor->GetProject(); FileSystem* fileSystem = GetSubsystem<FileSystem>(); #ifdef ATOMIC_PLATFORM_WINDOWS String bundleResources = fileSystem->GetProgramDir(); #else String bundleResources = fileSystem->GetAppBundleResourceFolder(); #endif String projectResources = project->GetResourcePath(); String coreDataFolder = bundleResources + "CoreData/"; AddResourceDir(coreDataFolder); AddResourceDir(projectResources); BuildResourceEntries(); } void BuildWindows::Build(const String& buildPath) { buildPath_ = buildPath + "/Windows-Build"; Initialize(); BuildSystem* buildSystem = GetSubsystem<BuildSystem>(); // BEGIN LICENSE MANAGEMENT LicenseSystem *licenseSystem = GetSubsystem<LicenseSystem>(); if (licenseSystem->IsStandardLicense()) { if (containsMDL_) { buildSystem->BuildComplete(AE_PLATFORM_WINDOWS, buildPath_, false, true); return; } } // END LICENSE MANAGEMENT FileSystem* fileSystem = GetSubsystem<FileSystem>(); if (fileSystem->DirExists(buildPath_)) fileSystem->RemoveDir(buildPath_, true); #ifdef ATOMIC_PLATFORM_WINDOWS String buildSourceDir = fileSystem->GetProgramDir(); #else String buildSourceDir = fileSystem->GetAppBundleResourceFolder(); #endif buildSourceDir += "Deployment/Win64"; fileSystem->CreateDir(buildPath_); fileSystem->CreateDir(buildPath_ + "/AtomicPlayer_Resources"); String resourcePackagePath = buildPath_ + "/AtomicPlayer_Resources/AtomicResources.pak"; GenerateResourcePackage(resourcePackagePath); fileSystem->Copy(buildSourceDir + "/AtomicPlayer.exe", buildPath_ + "/AtomicPlayer.exe"); fileSystem->Copy(buildSourceDir + "/D3DCompiler_47.dll", buildPath_ + "/D3DCompiler_47.dll"); buildSystem->BuildComplete(AE_PLATFORM_WINDOWS, buildPath_); } } <|endoftext|>
<commit_before><commit_msg>chore(tests): add stub for string formatter<commit_after>#include <blackhole/formatter/string.hpp> namespace blackhole { namespace testing { } // namespace testing } // namespace blackhole <|endoftext|>
<commit_before>// Copyright 2019 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <errno.h> #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include "src/main/tools/process-tools.h" int TerminateAndWaitForAll(pid_t pid) { kill(-pid, SIGKILL); int res; while ((res = waitpid(-1, nullptr, WNOHANG)) > 0) { // Got one child; try again. } if (res == -1) { // The fast path got all children, so there is nothing else to do. return 0; } // Cope with children that may have escaped the process group or that // did not exit quickly enough. FILE *f = fopen("/proc/thread-self/children", "r"); if (f == nullptr) { // Oh oh. This feature may be disabled, in which case there is // nothing we can do. Stop early and let any stale children be // reparented to init. return 0; } setbuf(f, nullptr); int child_pid; while ((waitpid(-1, nullptr, WNOHANG) != -1 || errno != ECHILD) && (rewind(f), 1 == fscanf(f, "%d", &child_pid))) { kill(child_pid, SIGKILL); usleep(100); } fclose(f); return 0; } <commit_msg>fix(#14135): error: use of undeclared identifier SIGKILL on FreeBSD 13.0<commit_after>// Copyright 2019 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <errno.h> #include <signal.h> #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include "src/main/tools/process-tools.h" int TerminateAndWaitForAll(pid_t pid) { kill(-pid, SIGKILL); int res; while ((res = waitpid(-1, nullptr, WNOHANG)) > 0) { // Got one child; try again. } if (res == -1) { // The fast path got all children, so there is nothing else to do. return 0; } // Cope with children that may have escaped the process group or that // did not exit quickly enough. FILE *f = fopen("/proc/thread-self/children", "r"); if (f == nullptr) { // Oh oh. This feature may be disabled, in which case there is // nothing we can do. Stop early and let any stale children be // reparented to init. return 0; } setbuf(f, nullptr); int child_pid; while ((waitpid(-1, nullptr, WNOHANG) != -1 || errno != ECHILD) && (rewind(f), 1 == fscanf(f, "%d", &child_pid))) { kill(child_pid, SIGKILL); usleep(100); } fclose(f); return 0; } <|endoftext|>
<commit_before>/* This file is part of Strigi Desktop Search * * Copyright (C) 2007 Jos van den Oever <jos@vandenoever.info> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "combinedindexmanager.h" #include "indexreader.h" #include "indexeddocument.h" #include "analyzerconfiguration.h" #include "diranalyzer.h" #include "strigiconfig.h" #include "query.h" #include <algorithm> #include <cstdio> #include <cstdarg> #include <cstring> #include <string> #include "stgdirent.h" //dirent replacement (includes native if available) using namespace std; using namespace Strigi; map<char, string> options; vector<string> dirs; void parseArguments(int argc, char** argv) { // parse arguments int i = 1; while (++i < argc) { const char* arg = argv[i]; size_t len = strlen(arg); if (len == 0) continue; if (*arg == '-' && len > 1) { char option = arg[1]; if (len > 2) { arg += 2; } else if (i+1 < argc) { arg = argv[++i]; } else { arg = ""; } options[option].assign(arg); } else { dirs.push_back(arg); } } } /* * Help function for printing to stderr: fprintf(stderr, */ int pe(const char *format, ...) { va_list arg; int done; va_start(arg, format); done = vfprintf(stderr, format, arg); va_end(arg); return done; } /** * This is the main for implementing a command line program that can create * and query indexes. **/ int usage(int argc, char** argv) { pe("%s:\n", argv[0]); pe(" Program for creating and querying indices.\n"); pe(" This program is not meant for talking to the strigi daemon.\n\n"); pe("usage:\n"); pe(" %s create [-j num] -t backend -d indexdir files/dirs\n"); pe(" %s get -t backend -d indexdir files\n"); pe(" %s listFiles -t backend -d indexdir\n"); pe(" %s listFields -t backend -d indexdir\n"); pe(" %s update [-j num] -t backend -d indexdir files/dirs\n"); return 1; } void checkIndexdirIsEmpty(const char* dir) { DIR* d = opendir(dir); if (!d) return; struct dirent* de = readdir(d); while (de) { if (strcmp(de->d_name, "..") && strcmp(de->d_name, ".")) { fprintf(stderr, "Directory %s is not empty.\n", dir); exit(1); } de = readdir(d); } closedir(d); } void printBackends(const string& msg, const vector<string> backends) { pe(msg.c_str()); pe(" Choose one from "); for (uint j=0; j<backends.size()-1; ++j) { pe("'%s', ", backends[j].c_str()); } pe("'%s'.\n", backends[backends.size()-1].c_str()); } void printIndexedDocument (IndexedDocument indexedDoc) { printf ("\t- mimetype: %s\n", indexedDoc.mimetype.c_str()); printf ("\t- sha1: %s\n", indexedDoc.sha1.c_str()); printf ("\t- size: %lld\n", indexedDoc.size); const time_t mtime = (const time_t) indexedDoc.mtime; printf ("\t- mtime: %s", ctime (&mtime)); set<string> processedProperties; for (multimap<string,string>::iterator iter = indexedDoc.properties.begin(); iter != indexedDoc.properties.end(); iter++) { // iter over all document properties set<string>::iterator match = processedProperties.find(iter->first); if (match != processedProperties.end()) continue; processedProperties.insert (iter->first); multimap<string,string>::iterator it; bool first = true; for (it = indexedDoc.properties.lower_bound(iter->first); it != indexedDoc.properties.upper_bound(iter->first); it++) { // shows all properties with the same key together if (first) { printf ("\t- %s:\t%s\n", it->first.c_str(), it->second.c_str()); first = false; } else printf ("\t\t%s\n", it->second.c_str()); } } } IndexManager* getIndexManager(string& backend, const string& indexdir) { // check arguments: backend const vector<string>& backends = CombinedIndexManager::backEnds(); // if there is only one backend, the backend does not have to be specified if (backend.size() == 0) { if (backends.size() == 1) { backend = backends[0]; } else { printBackends("Specify a backend.", backends); return 0; } } vector<string>::const_iterator b = find(backends.begin(), backends.end(), backend); if (b == backends.end()) { printBackends("Invalid index type.", backends); return 0; } return CombinedIndexManager::factories()[backend](indexdir.c_str()); } int create(int argc, char** argv) { // parse arguments parseArguments(argc, argv); string backend = options['t']; string indexdir = options['d']; int nthreads = atoi(options['j'].c_str()); if (nthreads < 1) nthreads = 2; // check arguments: indexdir if (indexdir.length() == 0) { pe("Provide a dir to write the index to with -d.\n"); return usage(argc, argv); } // check that the dir does not yet exist checkIndexdirIsEmpty(indexdir.c_str()); // check arguments: dirs if (dirs.size() == 0) { pe("'%s' '%s'\n", backend.c_str(), indexdir.c_str()); pe("Provide directories to index.\n"); return usage(argc, argv); } IndexManager* manager = getIndexManager(backend, indexdir); if (manager == 0) { return usage(argc, argv); } IndexWriter* writer = manager->indexWriter(); AnalyzerConfiguration config; DirAnalyzer* analyzer = new DirAnalyzer(*writer, &config); vector<string>::const_iterator j; for (j = dirs.begin(); j != dirs.end(); ++j) { analyzer->analyzeDir(j->c_str(), nthreads); } delete analyzer; delete manager; return 0; } int update(int argc, char** argv) { return 0; } int listFiles(int argc, char** argv) { // parse arguments parseArguments(argc, argv); string backend = options['t']; string indexdir = options['d']; // check arguments: indexdir if (indexdir.length() == 0) { pe("Provide the directory with the index.\n"); return usage(argc, argv); } // create an index manager IndexManager* manager = getIndexManager(backend, indexdir); if (manager == 0) { return usage(argc, argv); } IndexReader* reader = manager->indexReader(); map<string, time_t> files = reader->files(-1); map<string, time_t>::const_iterator i; for (i=files.begin(); i!=files.end(); ++i) { printf("%s\n", i->first.c_str()); } delete manager; return 0; } int get(int argc, char** argv) { // parse arguments parseArguments(argc, argv); string backend = options['t']; string indexdir = options['d']; // check arguments: indexdir if (indexdir.length() == 0) { pe("Provide the directory with the index.\n"); return usage(argc, argv); } // check arguments: dirs if (dirs.size() == 0) { pe("'%s' '%s'\n", backend.c_str(), indexdir.c_str()); pe("Provide directories to index.\n"); return usage(argc, argv); } // create an index manager IndexManager* manager = getIndexManager(backend, indexdir); if (manager == 0) { return usage(argc, argv); } IndexReader* reader = manager->indexReader(); QueryParser parser; for (vector<string>::iterator iter = dirs.begin(); iter != dirs.end(); iter++) { Query query = parser.buildQuery( "system.location:'"+ *iter + "'", 10, 0); vector<IndexedDocument> matches = reader->query( query); if (matches.size() == 0) printf ("%s: is not indexed\n", iter->c_str()); else { printf ("Informations associated to %s:\n", iter->c_str()); for (vector<IndexedDocument>::iterator it = matches.begin(); it != matches.end(); it++) { printIndexedDocument(*it); } } } delete manager; return 0; } int listFields(int argc, char** argv) { // parse arguments parseArguments(argc, argv); string backend = options['t']; string indexdir = options['d']; // check arguments: indexdir if (indexdir.length() == 0) { pe("Provide the directory with the index.\n"); return usage(argc, argv); } // create an index manager IndexManager* manager = getIndexManager(backend, indexdir); if (manager == 0) { return usage(argc, argv); } IndexReader* reader = manager->indexReader(); vector<string> fields = reader->fieldNames(); vector<string>::const_iterator i; for (i=fields.begin(); i!=fields.end(); ++i) { printf("%s\n", i->c_str()); } delete manager; return 0; } int main(int argc, char** argv) { if (argc < 2) { return usage(argc, argv); } const char* cmd = argv[1]; if (!strcmp(cmd,"create")) { return create(argc, argv); } else if (!strcmp(cmd,"update")) { return update(argc, argv); } else if (!strcmp(cmd,"listFiles")) { return listFiles(argc, argv); } else if (!strcmp(cmd,"listFields")) { return listFields(argc, argv); } else if (!strcmp(cmd,"get")) { return get(argc, argv); } else { return usage(argc, argv); } return 0; } <commit_msg>if you use time functions it's a good idea to include time.h ...<commit_after>/* This file is part of Strigi Desktop Search * * Copyright (C) 2007 Jos van den Oever <jos@vandenoever.info> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "combinedindexmanager.h" #include "indexreader.h" #include "indexeddocument.h" #include "analyzerconfiguration.h" #include "diranalyzer.h" #include "strigiconfig.h" #include "query.h" #include <algorithm> #include <cstdio> #include <cstdarg> #include <cstring> #include <string> #include <time.h> #include "stgdirent.h" //dirent replacement (includes native if available) using namespace std; using namespace Strigi; map<char, string> options; vector<string> dirs; void parseArguments(int argc, char** argv) { // parse arguments int i = 1; while (++i < argc) { const char* arg = argv[i]; size_t len = strlen(arg); if (len == 0) continue; if (*arg == '-' && len > 1) { char option = arg[1]; if (len > 2) { arg += 2; } else if (i+1 < argc) { arg = argv[++i]; } else { arg = ""; } options[option].assign(arg); } else { dirs.push_back(arg); } } } /* * Help function for printing to stderr: fprintf(stderr, */ int pe(const char *format, ...) { va_list arg; int done; va_start(arg, format); done = vfprintf(stderr, format, arg); va_end(arg); return done; } /** * This is the main for implementing a command line program that can create * and query indexes. **/ int usage(int argc, char** argv) { pe("%s:\n", argv[0]); pe(" Program for creating and querying indices.\n"); pe(" This program is not meant for talking to the strigi daemon.\n\n"); pe("usage:\n"); pe(" %s create [-j num] -t backend -d indexdir files/dirs\n"); pe(" %s get -t backend -d indexdir files\n"); pe(" %s listFiles -t backend -d indexdir\n"); pe(" %s listFields -t backend -d indexdir\n"); pe(" %s update [-j num] -t backend -d indexdir files/dirs\n"); return 1; } void checkIndexdirIsEmpty(const char* dir) { DIR* d = opendir(dir); if (!d) return; struct dirent* de = readdir(d); while (de) { if (strcmp(de->d_name, "..") && strcmp(de->d_name, ".")) { fprintf(stderr, "Directory %s is not empty.\n", dir); exit(1); } de = readdir(d); } closedir(d); } void printBackends(const string& msg, const vector<string> backends) { pe(msg.c_str()); pe(" Choose one from "); for (uint j=0; j<backends.size()-1; ++j) { pe("'%s', ", backends[j].c_str()); } pe("'%s'.\n", backends[backends.size()-1].c_str()); } void printIndexedDocument (IndexedDocument indexedDoc) { printf ("\t- mimetype: %s\n", indexedDoc.mimetype.c_str()); printf ("\t- sha1: %s\n", indexedDoc.sha1.c_str()); printf ("\t- size: %lld\n", indexedDoc.size); const time_t mtime = (const time_t) indexedDoc.mtime; printf ("\t- mtime: %s", ctime (&mtime)); set<string> processedProperties; for (multimap<string,string>::iterator iter = indexedDoc.properties.begin(); iter != indexedDoc.properties.end(); iter++) { // iter over all document properties set<string>::iterator match = processedProperties.find(iter->first); if (match != processedProperties.end()) continue; processedProperties.insert (iter->first); multimap<string,string>::iterator it; bool first = true; for (it = indexedDoc.properties.lower_bound(iter->first); it != indexedDoc.properties.upper_bound(iter->first); it++) { // shows all properties with the same key together if (first) { printf ("\t- %s:\t%s\n", it->first.c_str(), it->second.c_str()); first = false; } else printf ("\t\t%s\n", it->second.c_str()); } } } IndexManager* getIndexManager(string& backend, const string& indexdir) { // check arguments: backend const vector<string>& backends = CombinedIndexManager::backEnds(); // if there is only one backend, the backend does not have to be specified if (backend.size() == 0) { if (backends.size() == 1) { backend = backends[0]; } else { printBackends("Specify a backend.", backends); return 0; } } vector<string>::const_iterator b = find(backends.begin(), backends.end(), backend); if (b == backends.end()) { printBackends("Invalid index type.", backends); return 0; } return CombinedIndexManager::factories()[backend](indexdir.c_str()); } int create(int argc, char** argv) { // parse arguments parseArguments(argc, argv); string backend = options['t']; string indexdir = options['d']; int nthreads = atoi(options['j'].c_str()); if (nthreads < 1) nthreads = 2; // check arguments: indexdir if (indexdir.length() == 0) { pe("Provide a dir to write the index to with -d.\n"); return usage(argc, argv); } // check that the dir does not yet exist checkIndexdirIsEmpty(indexdir.c_str()); // check arguments: dirs if (dirs.size() == 0) { pe("'%s' '%s'\n", backend.c_str(), indexdir.c_str()); pe("Provide directories to index.\n"); return usage(argc, argv); } IndexManager* manager = getIndexManager(backend, indexdir); if (manager == 0) { return usage(argc, argv); } IndexWriter* writer = manager->indexWriter(); AnalyzerConfiguration config; DirAnalyzer* analyzer = new DirAnalyzer(*writer, &config); vector<string>::const_iterator j; for (j = dirs.begin(); j != dirs.end(); ++j) { analyzer->analyzeDir(j->c_str(), nthreads); } delete analyzer; delete manager; return 0; } int update(int argc, char** argv) { return 0; } int listFiles(int argc, char** argv) { // parse arguments parseArguments(argc, argv); string backend = options['t']; string indexdir = options['d']; // check arguments: indexdir if (indexdir.length() == 0) { pe("Provide the directory with the index.\n"); return usage(argc, argv); } // create an index manager IndexManager* manager = getIndexManager(backend, indexdir); if (manager == 0) { return usage(argc, argv); } IndexReader* reader = manager->indexReader(); map<string, time_t> files = reader->files(-1); map<string, time_t>::const_iterator i; for (i=files.begin(); i!=files.end(); ++i) { printf("%s\n", i->first.c_str()); } delete manager; return 0; } int get(int argc, char** argv) { // parse arguments parseArguments(argc, argv); string backend = options['t']; string indexdir = options['d']; // check arguments: indexdir if (indexdir.length() == 0) { pe("Provide the directory with the index.\n"); return usage(argc, argv); } // check arguments: dirs if (dirs.size() == 0) { pe("'%s' '%s'\n", backend.c_str(), indexdir.c_str()); pe("Provide directories to index.\n"); return usage(argc, argv); } // create an index manager IndexManager* manager = getIndexManager(backend, indexdir); if (manager == 0) { return usage(argc, argv); } IndexReader* reader = manager->indexReader(); QueryParser parser; for (vector<string>::iterator iter = dirs.begin(); iter != dirs.end(); iter++) { Query query = parser.buildQuery( "system.location:'"+ *iter + "'", 10, 0); vector<IndexedDocument> matches = reader->query( query); if (matches.size() == 0) printf ("%s: is not indexed\n", iter->c_str()); else { printf ("Informations associated to %s:\n", iter->c_str()); for (vector<IndexedDocument>::iterator it = matches.begin(); it != matches.end(); it++) { printIndexedDocument(*it); } } } delete manager; return 0; } int listFields(int argc, char** argv) { // parse arguments parseArguments(argc, argv); string backend = options['t']; string indexdir = options['d']; // check arguments: indexdir if (indexdir.length() == 0) { pe("Provide the directory with the index.\n"); return usage(argc, argv); } // create an index manager IndexManager* manager = getIndexManager(backend, indexdir); if (manager == 0) { return usage(argc, argv); } IndexReader* reader = manager->indexReader(); vector<string> fields = reader->fieldNames(); vector<string>::const_iterator i; for (i=fields.begin(); i!=fields.end(); ++i) { printf("%s\n", i->c_str()); } delete manager; return 0; } int main(int argc, char** argv) { if (argc < 2) { return usage(argc, argv); } const char* cmd = argv[1]; if (!strcmp(cmd,"create")) { return create(argc, argv); } else if (!strcmp(cmd,"update")) { return update(argc, argv); } else if (!strcmp(cmd,"listFiles")) { return listFiles(argc, argv); } else if (!strcmp(cmd,"listFields")) { return listFields(argc, argv); } else if (!strcmp(cmd,"get")) { return get(argc, argv); } else { return usage(argc, argv); } return 0; } <|endoftext|>
<commit_before><commit_msg><commit_after><|endoftext|>
<commit_before>#include<iostream> extern "C"{ #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xresource.h> #include <X11/extensions/XTest.h> } #include "network.h" using namespace std; class MDisplay { Display* disp; // uint32_t SIGN_X = 1; public: MDisplay(); void mouse_move(uint32_t arg); void mouse_press(void); void mouse_release(void); }; MDisplay::MDisplay(){ disp = XOpenDisplay(":0"); } void MDisplay::mouse_move(uint32_t arg) { } void MDisplay::mouse_press() { } void MDisplay::mouse_release() { } void dispatch_message(MDisplay display, Message* msg){ // switch(msg->cmd){ // case Messages::M_MOVE: // } // this won't work; needs constexpr if (msg->cmd == Messages::M_MOVE){ display.mouse_move(msg->arg); } else if(msg->cmd == Messages::M_PRESS1) { display.mouse_press(); } else if(msg->cmd == Messages::M_RELEASE1) { display.mouse_release(); } } void dispatch_messages(MDisplay display, int sock){ Recieved* rcv = get_data(sock); Message** messages = Message::from_recieved(rcv); int i = 0; while(messages[i]) { dispatch_message(display, messages[i]); i++; } } int main(int argc, char** argv) { // Display* display = XOpenDisplay(":0"); // int ev_br, er_br, maj_v, min_v; // int socket; // if (XTestQueryExtension(display, &ev_br, &er_br, &maj_v, &min_v)) { // cout << "XTestQuery is supported" << endl; // } // /* XTestFakeMotionEvent(display, screen_number, x, y, delay); */ // // XTestFakeMotionEvent(display, -1, 1, 1, CurrentTime); // // XWarpPointer(display, None, 0, 0, 0, 0, 0, 100, 100); // XTestFakeButtonEvent(display, 1, True, CurrentTime); // XFlush(display); // XTestFakeButtonEvent(display, 1, False, CurrentTime); // XFlush(display); // socket = open_listening_socket(); // Recieved* rcv; // cout << "-" << endl; // rcv = get_data(socket); // cout << "-" << endl; // cout.write(rcv->data, max(rcv->count, 512)); // cout.flush(); Messages::initialize(); cout << "Hello World" << endl; // unsigned int i = 0; char txt[] = {0,1,0,0,0,0, 0,1,0,0,0,0}; cout<<"sizeof input data "<<sizeof txt<<endl; // cout<<txt<<endl; // i=*(uint16_t*)txt; // cout<<i<<endl; Recieved rcvd = Recieved(); rcvd.data = txt; rcvd.count = sizeof txt; Message** messages = Message::from_recieved(&rcvd); int i=0; cout<<(1<<1)<<endl; while(messages[i]){ cout<<"spam!"<<endl; i++; } delete messages; cout<<"bye"<<endl; } <commit_msg>added event loop to remote<commit_after>#include<iostream> #include<cstring> extern "C"{ #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xresource.h> #include <X11/extensions/XTest.h> } #include "network.h" using namespace std; class MDisplay { Display* disp; // uint32_t SIGN_X = 1; public: MDisplay(); void mouse_move(int x, int y); void mouse_press(int btn); void mouse_release(int btn); }; MDisplay::MDisplay(){ // int ev_br, er_br, maj_v, min_v; // die(!XTestQueryExtension(disp, &ev_br, &er_br, &maj_v, &min_v)) disp = XOpenDisplay(":0"); } void MDisplay::mouse_move(int x, int y) { XWarpPointer(disp, None, 0, 0, 0, 0, 0, x, y); } void MDisplay::mouse_press(int btn) { XTestFakeButtonEvent(disp, btn, True, CurrentTime); } void MDisplay::mouse_release(int btn) { XTestFakeButtonEvent(disp, btn, False, CurrentTime); } void dispatch_message(MDisplay display, Message* msg){ // switch(msg->cmd){ // case Messages::M_MOVE: // } // this won't work; needs constexpr if (msg->cmd == Messages::M_MOVE){ display.mouse_move(msg->arg1, msg->arg2); } else if(msg->cmd == Messages::M_PRESS1) { display.mouse_press(msg->arg1); } else if(msg->cmd == Messages::M_RELEASE1) { display.mouse_release(msg->arg1); } } void dispatch_messages(MDisplay display, int sock){ Recieved* rcv = get_data(sock); Message** messages = Message::from_recieved(rcv); int i = 0; while(messages[i]) { dispatch_message(display, messages[i]); i++; } } int test(){ // Display* display = XOpenDisplay(":0"); // int ev_br, er_br, maj_v, min_v; // int socket; // if (XTestQueryExtension(display, &ev_br, &er_br, &maj_v, &min_v)) { // cout << "XTestQuery is supported" << endl; // } // /* XTestFakeMotionEvent(display, screen_number, x, y, delay); */ // // XTestFakeMotionEvent(display, -1, 1, 1, CurrentTime); // // XWarpPointer(display, None, 0, 0, 0, 0, 0, 100, 100); // XTestFakeButtonEvent(display, 1, True, CurrentTime); // XFlush(display); // XTestFakeButtonEvent(display, 1, False, CurrentTime); // XFlush(display); // socket = open_listening_socket(); // Recieved* rcv; // cout << "-" << endl; // rcv = get_data(socket); // cout << "-" << endl; // cout.write(rcv->data, max(rcv->count, 512)); // cout.flush(); Messages::initialize(); cout << "Hello World" << endl; // uint16_t uns = 3; // uns <<= 15; // cout << uns << endl; // cout << (int16_t)uns << endl; // unsigned int i = 0; char txt[] = {0,1, 255,255, 0,0, 0,0, 0,255, 128,0}; cout<<"sizeof input data "<<sizeof txt<<endl; // cout<<txt<<endl; // i=*(uint16_t*)txt; // cout<<i<<endl; Recieved rcvd = Recieved(); rcvd.data = txt; rcvd.count = sizeof txt; Message** messages = Message::from_recieved(&rcvd); int i=0; while(messages[i]){ cout << "msg:" << messages[i]->arg1 << ";" << messages[i]->arg2 << ";" << endl; i++; } delete messages; cout<<"bye"<<endl; return 0; } int main(int argc, char** argv) { if (strcmp(argv[0], "tests")) { return test(); } Messages::initialize(); MDisplay display = MDisplay(); int socket; socket = open_listening_socket(); Recieved* rcv; while((rcv = get_data(socket))){ Message** messages = Message::from_recieved(rcv); for(int i; messages[i]; i++){ dispatch_message(display, messages[i]); } } } <|endoftext|>
<commit_before>// ----------------------------------------------------------------------------- // // MIT License // // Copyright (c) 2016 Alberto Sola // // 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 "taskdb.hpp" // ----------------------------------------------------------------------------- TaskDB::TaskDB(){ initialize(); } // ----------------------------------------------------------------------------- TaskDB::TaskDB(const std::string & name){ initialize(); set_name(name); } // ----------------------------------------------------------------------------- void TaskDB::initialize(){ /* Initialize the ID count, and set an empty task (ID: 0). */ Task task; last_id = 0; // Start ID count task.set_id(last_id); add_task(task); // Empty Task - 0 } // ----------------------------------------------------------------------------- void TaskDB::set_name(const std::string & name){ /* Set the TaskDB file name. */ db_file_name = name; } // ----------------------------------------------------------------------------- // TODO: return error code void TaskDB::read(){ /* Read the TaskDB file. */ std::ifstream file(db_file_name, std::ofstream::in ); std::string line; Task task; unsigned int id = 0; if( file.is_open() ){ std::getline(file,line); while(!file.eof()){ task.load_from_str(line); id = task.get_id(); task_list.insert(std::make_pair(id,task)); if(id > last_id) last_id = id; std::getline(file,line); } } if(last_id > 1 || id == 1) last_id += 1; file.close(); } // ----------------------------------------------------------------------------- void TaskDB::save() const{ /* Save all tasks. */ std::ofstream file(db_file_name, std::ofstream::out | std::ofstream::trunc); for( auto & task : task_list ) file << task.second.to_str() << std::endl; file.close(); } // ----------------------------------------------------------------------------- void TaskDB::add_task( Task & task ){ /* Add a new task. */ task.set_id(last_id); task_list.insert(std::make_pair(last_id, task)); last_id += 1; } // ----------------------------------------------------------------------------- void TaskDB::update_task(const Task & task){ std::map<unsigned int,Task>::iterator it = task_list.find(task.get_id()); // TODO: Return value if( it != task_list.end() ) (*it).second = task; } // ----------------------------------------------------------------------------- const Task & TaskDB::get_task( unsigned int id ) const{ /* Get a task by its ID. */ std::map<unsigned int,Task>::const_iterator it = task_list.find(id); if( it != task_list.end() ) return (*it).second; else return (*task_list.find(0)).second; } // ----------------------------------------------------------------------------- void TaskDB::delete_task(unsigned int id){ /* Delete a task by its ID. */ task_list.erase(id); } // ----------------------------------------------------------------------------- bool TaskDB::finish_task(unsigned int id){ /* Finish/Starts a task by its ID. */ std::map<unsigned int,Task>::iterator it = task_list.find(id); bool old_status = false; if( it != task_list.end() ) old_status = (*it).second.finish(); return old_status; } // ----------------------------------------------------------------------------- bool TaskDB::finish_task(unsigned int id, bool status){ std::map<unsigned int,Task>::iterator it = task_list.find(id); bool old_status = false; if( it != task_list.end() ) old_status = (*it).second.finish(status); return old_status; } // ----------------------------------------------------------------------------- void TaskDB::get_task_list(std::vector<Task> & tasks) const{ /* Get all tasks. */ std::map<unsigned int, Task>::const_iterator start = task_list.cbegin(); std::map<unsigned int, Task>::const_iterator end = task_list.cend(); start++; // Skip ID:0 for(auto & t = start; t != end; t++ ) tasks.push_back((*t).second); } // ----------------------------------------------------------------------------- void TaskDB::get_task_list(std::vector<Task> & tasks, const std::string & tag) const{ std::map<unsigned int, Task>::const_iterator start = task_list.cbegin(); std::map<unsigned int, Task>::const_iterator end = task_list.cend(); start++; // Skip ID:0 for(auto & t = start; t != end; t++ ) if((*t).second.get_tag() == tag) tasks.push_back((*t).second); } // ----------------------------------------------------------------------------- <commit_msg>Bug fixed when empty.<commit_after>// ----------------------------------------------------------------------------- // // MIT License // // Copyright (c) 2016 Alberto Sola // // 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 "taskdb.hpp" // ----------------------------------------------------------------------------- TaskDB::TaskDB(){ initialize(); } // ----------------------------------------------------------------------------- TaskDB::TaskDB(const std::string & name){ initialize(); set_name(name); } // ----------------------------------------------------------------------------- void TaskDB::initialize(){ /* Initialize the ID count, and set an empty task (ID: 0). */ Task task; last_id = 0; // Start ID count task.set_id(last_id); add_task(task); // Empty Task - 0 } // ----------------------------------------------------------------------------- void TaskDB::set_name(const std::string & name){ /* Set the TaskDB file name. */ db_file_name = name; } // ----------------------------------------------------------------------------- void TaskDB::add_tag(const std::string & tag){ std::map<std::string,int>::iterator it = tag_list.find(tag); if(it != tag_list.end()) (*it).second += 1; else tag_list.insert(std::make_pair(tag,1)); } // ----------------------------------------------------------------------------- void TaskDB::del_tag(const std::string & tag){ std::map<std::string,int>::iterator it = tag_list.find(tag); if(it != tag_list.end()){ (*it).second -= 1; if((*it).second == 0) tag_list.erase(tag); } } // ----------------------------------------------------------------------------- // TODO: return error code void TaskDB::read(){ /* Read the TaskDB file. */ std::ifstream file(db_file_name, std::ofstream::in ); std::string line; Task task; unsigned int id = 0; // Clear current data task_list.clear(); tag_list.clear(); // Check if the DB is open if( file.is_open() ){ // Get each line and parse it std::getline(file,line); while(!file.eof()){ task.load_from_str(line); id = task.get_id(); // Add task task_list.insert(std::make_pair(id,task)); // Add tag add_tag(task.get_tag()); if(id > last_id) last_id = id; // Get next line std::getline(file,line); } } if(last_id > 1 || id == 1) last_id += 1; file.close(); } // ----------------------------------------------------------------------------- void TaskDB::save() const{ /* Save all tasks. */ std::ofstream file(db_file_name, std::ofstream::out | std::ofstream::trunc); for( auto & task : task_list ) file << task.second.to_str() << std::endl; file.close(); } // ----------------------------------------------------------------------------- void TaskDB::add_task( Task & task ){ /* Add a new task. */ task.set_id(last_id); task_list.insert(std::make_pair(last_id, task)); add_tag(task.get_tag()); last_id += 1; } // ----------------------------------------------------------------------------- void TaskDB::update_task(const Task & task){ std::map<unsigned int,Task>::iterator it = task_list.find(task.get_id()); // TODO: Return value if( it != task_list.end() ){ del_tag((*it).second.get_tag()); add_tag(task.get_tag()); (*it).second = task; } } // ----------------------------------------------------------------------------- const Task & TaskDB::get_task( unsigned int id ) const{ /* Get a task by its ID. */ std::map<unsigned int,Task>::const_iterator it = task_list.find(id); if( it != task_list.end() ) return (*it).second; else return (*task_list.find(0)).second; } // ----------------------------------------------------------------------------- void TaskDB::delete_task(unsigned int id){ /* Delete a task by its ID. */ Task task = get_task(id); del_tag(task.get_tag()); task_list.erase(id); } // ----------------------------------------------------------------------------- bool TaskDB::finish_task(unsigned int id){ /* Finish/Starts a task by its ID. */ std::map<unsigned int,Task>::iterator it = task_list.find(id); bool old_status = false; if( it != task_list.end() ) old_status = (*it).second.finish(); return old_status; } // ----------------------------------------------------------------------------- bool TaskDB::finish_task(unsigned int id, bool status){ std::map<unsigned int,Task>::iterator it = task_list.find(id); bool old_status = false; if( it != task_list.end() ) old_status = (*it).second.finish(status); return old_status; } // ----------------------------------------------------------------------------- void TaskDB::get_task_list(std::vector<Task> & tasks) const{ /* Get all tasks. */ std::map<unsigned int, Task>::const_iterator start = task_list.cbegin(); std::map<unsigned int, Task>::const_iterator end = task_list.cend(); // Check if empty if(start != end){ start++; for(auto & t = start; t != end; t++ ) tasks.push_back((*t).second); } } // ----------------------------------------------------------------------------- void TaskDB::get_task_list(std::vector<Task> & tasks, const std::string & tag) const{ std::map<unsigned int, Task>::const_iterator start = task_list.cbegin(); std::map<unsigned int, Task>::const_iterator end = task_list.cend(); start++; // Skip ID:0 for(auto & t = start; t != end; t++ ) if((*t).second.get_tag() == tag) tasks.push_back((*t).second); } // ----------------------------------------------------------------------------- <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2014 PX4 Development Team. 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. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file mavlink_orb_subscription.cpp * uORB subscription implementation. * * @author Anton Babushkin <anton.babushkin@me.com> */ #include <unistd.h> #include <stdlib.h> #include <string.h> #include <uORB/uORB.h> #include <stdio.h> #include "mavlink_orb_subscription.h" MavlinkOrbSubscription::MavlinkOrbSubscription(const orb_id_t topic) : _fd(orb_subscribe(_topic)), _published(false), _topic(topic), next(nullptr) { } MavlinkOrbSubscription::~MavlinkOrbSubscription() { close(_fd); } orb_id_t MavlinkOrbSubscription::get_topic() const { return _topic; } bool MavlinkOrbSubscription::update(uint64_t *time, void* data) { // TODO this is NOT atomic operation, we can get data newer than time // if topic was published between orb_stat and orb_copy calls. uint64_t time_topic; if (orb_stat(_fd, &time_topic)) { /* error getting last topic publication time */ time_topic = 0; } if (orb_copy(_topic, _fd, data)) { /* error copying topic data */ memset(data, 0, _topic->o_size); return false; } else { /* data copied successfully */ _published = true; if (time_topic != *time) { *time = time_topic; return true; } else { return false; } } } bool MavlinkOrbSubscription::update(void* data) { return !orb_copy(_topic, _fd, data); } bool MavlinkOrbSubscription::is_published() { if (_published) { return true; } bool updated; orb_check(_fd, &updated); if (updated) { _published = true; } return _published; } <commit_msg>Hotfix: Only orb_copy items in mavlink app if the timestamp changed<commit_after>/**************************************************************************** * * Copyright (c) 2014 PX4 Development Team. 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. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file mavlink_orb_subscription.cpp * uORB subscription implementation. * * @author Anton Babushkin <anton.babushkin@me.com> */ #include <unistd.h> #include <stdlib.h> #include <string.h> #include <uORB/uORB.h> #include <stdio.h> #include <systemlib/err.h> #include "mavlink_orb_subscription.h" MavlinkOrbSubscription::MavlinkOrbSubscription(const orb_id_t topic) : _fd(orb_subscribe(_topic)), _published(false), _topic(topic), next(nullptr) { } MavlinkOrbSubscription::~MavlinkOrbSubscription() { close(_fd); } orb_id_t MavlinkOrbSubscription::get_topic() const { return _topic; } bool MavlinkOrbSubscription::update(uint64_t *time, void* data) { // TODO this is NOT atomic operation, we can get data newer than time // if topic was published between orb_stat and orb_copy calls. uint64_t time_topic; if (orb_stat(_fd, &time_topic)) { /* error getting last topic publication time */ time_topic = 0; } if (time_topic != *time) { if (orb_copy(_topic, _fd, data)) { /* error copying topic data */ memset(data, 0, _topic->o_size); //warnx("err copy, fd: %d, obj: %s, size: %d", _fd, _topic->o_name, _topic->o_size); return false; } else { /* data copied successfully */ _published = true; *time = time_topic; return true; } } else { return false; } } bool MavlinkOrbSubscription::update(void* data) { return !orb_copy(_topic, _fd, data); } bool MavlinkOrbSubscription::is_published() { if (_published) { return true; } bool updated; orb_check(_fd, &updated); if (updated) { _published = true; } return _published; } <|endoftext|>
<commit_before>#include <babylon/engines/asset_container.h> #include <babylon/actions/abstract_action_manager.h> #include <babylon/animations/animation.h> #include <babylon/animations/animation_group.h> #include <babylon/audio/sound.h> #include <babylon/audio/sound_track.h> #include <babylon/bones/skeleton.h> #include <babylon/cameras/camera.h> #include <babylon/engines/iscene_serializable_component.h> #include <babylon/engines/scene.h> #include <babylon/lights/light.h> #include <babylon/materials/material.h> #include <babylon/materials/multi_material.h> #include <babylon/materials/textures/texture.h> #include <babylon/meshes/abstract_mesh.h> #include <babylon/meshes/geometry.h> #include <babylon/meshes/mesh.h> #include <babylon/meshes/transform_node.h> #include <babylon/morph/morph_target_manager.h> #include <babylon/probes/reflection_probe.h> namespace BABYLON { AssetContainer::AssetContainer(Scene* iScene) : scene{iScene}, _wasAddedToScene{false} { scene->onDisposeObservable.add([this](Scene* /*scene*/, EventState & /*es*/) -> void { if (!_wasAddedToScene) { dispose(); } }); } AssetContainer::~AssetContainer() = default; void AssetContainer::addAllToScene() { _wasAddedToScene = true; for (const auto& o : cameras) { scene->addCamera(o); } for (const auto& o : lights) { scene->addLight(o); } for (const auto& o : meshes) { scene->addMesh(o); } for (const auto& o : skeletons) { scene->addSkeleton(o); } for (const auto& o : animations) { scene->addAnimation(o); } for (const auto& o : animationGroups) { scene->addAnimationGroup(o); } for (const auto& o : multiMaterials) { scene->addMultiMaterial(o); } for (const auto& o : materials) { scene->addMaterial(o); } for (const auto& o : morphTargetManagers) { scene->addMorphTargetManager(o); } for (const auto& o : geometries) { scene->addGeometry(o); } for (const auto& o : transformNodes) { scene->addTransformNode(o); } for (const auto& o : actionManagers) { scene->addActionManager(o); } for (const auto& o : textures) { scene->addTexture(o); } for (const auto& o : reflectionProbes) { scene->addReflectionProbe(o); } if (environmentTexture()) { scene->environmentTexture = environmentTexture(); } for (const auto& component : scene->_serializableComponents) { component->addFromContainer(*this); } } void AssetContainer::removeAllFromScene() { _wasAddedToScene = false; for (const auto& o : cameras) { scene->removeCamera(o); } for (const auto& o : lights) { scene->removeLight(o); } for (const auto& o : meshes) { scene->removeMesh(o); } for (const auto& o : skeletons) { scene->removeSkeleton(o); } for (const auto& o : animations) { scene->removeAnimation(o); } for (const auto& o : animationGroups) { scene->removeAnimationGroup(o); } for (const auto& o : multiMaterials) { scene->removeMultiMaterial(o); } for (const auto& o : materials) { scene->removeMaterial(o); } for (const auto& o : morphTargetManagers) { scene->removeMorphTargetManager(o); } for (const auto& o : geometries) { scene->removeGeometry(o); } for (const auto& o : transformNodes) { scene->removeTransformNode(o); } for (const auto& o : actionManagers) { scene->removeActionManager(o); } for (const auto& o : textures) { scene->removeTexture(o); } for (const auto& o : reflectionProbes) { scene->removeReflectionProbe(o); } if (environmentTexture() == scene->environmentTexture()) { scene->environmentTexture = nullptr; } for (const auto& component : scene->_serializableComponents) { component->removeFromContainer(*this); } } void AssetContainer::dispose() { for (const auto& o : cameras) { o->dispose(); } cameras.clear(); for (const auto& o : lights) { o->dispose(); } lights.clear(); for (const auto& o : meshes) { scene->removeMesh(o); } meshes.clear(); for (const auto& o : skeletons) { o->dispose(); } skeletons.clear(); for (const auto& o : animationGroups) { o->dispose(); } animationGroups.clear(); for (const auto& o : multiMaterials) { o->dispose(); } multiMaterials.clear(); for (const auto& o : materials) { o->dispose(); } materials.clear(); for (const auto& o : geometries) { o->dispose(); } geometries.clear(); for (const auto& o : transformNodes) { o->dispose(); } transformNodes.clear(); for (const auto& o : actionManagers) { o->dispose(); } actionManagers.clear(); for (const auto& o : textures) { o->dispose(); } textures.clear(); for (const auto& o : reflectionProbes) { o->dispose(); } reflectionProbes.clear(); if (environmentTexture()) { environmentTexture()->dispose(); environmentTexture = nullptr; } for (const auto& component : scene->_serializableComponents) { component->removeFromContainer(*this, true); } } MeshPtr AssetContainer::createRootMesh() { auto rootMesh = Mesh::New("assetContainerRootMesh", scene); for (const auto& m : meshes) { if (!m->parent) { rootMesh->addChild(*m); } } meshes.insert(meshes.begin(), rootMesh); return rootMesh; } } // end of namespace BABYLON <commit_msg>Const correctness<commit_after>#include <babylon/engines/asset_container.h> #include <babylon/actions/abstract_action_manager.h> #include <babylon/animations/animation.h> #include <babylon/animations/animation_group.h> #include <babylon/audio/sound.h> #include <babylon/audio/sound_track.h> #include <babylon/bones/skeleton.h> #include <babylon/cameras/camera.h> #include <babylon/engines/iscene_serializable_component.h> #include <babylon/engines/scene.h> #include <babylon/lights/light.h> #include <babylon/materials/material.h> #include <babylon/materials/multi_material.h> #include <babylon/materials/textures/texture.h> #include <babylon/meshes/abstract_mesh.h> #include <babylon/meshes/geometry.h> #include <babylon/meshes/mesh.h> #include <babylon/meshes/transform_node.h> #include <babylon/morph/morph_target_manager.h> #include <babylon/probes/reflection_probe.h> namespace BABYLON { AssetContainer::AssetContainer(Scene* iScene) : scene{iScene}, _wasAddedToScene{false} { scene->onDisposeObservable.add([this](Scene* /*scene*/, EventState & /*es*/) -> void { if (!_wasAddedToScene) { dispose(); } }); } AssetContainer::~AssetContainer() = default; void AssetContainer::addAllToScene() { _wasAddedToScene = true; for (const auto& o : cameras) { scene->addCamera(o); } for (const auto& o : lights) { scene->addLight(o); } for (const auto& o : meshes) { scene->addMesh(o); } for (const auto& o : skeletons) { scene->addSkeleton(o); } for (const auto& o : animations) { scene->addAnimation(o); } for (const auto& o : animationGroups) { scene->addAnimationGroup(o); } for (const auto& o : multiMaterials) { scene->addMultiMaterial(o); } for (const auto& o : materials) { scene->addMaterial(o); } for (const auto& o : morphTargetManagers) { scene->addMorphTargetManager(o); } for (const auto& o : geometries) { scene->addGeometry(o); } for (const auto& o : transformNodes) { scene->addTransformNode(o); } for (const auto& o : actionManagers) { scene->addActionManager(o); } for (const auto& o : textures) { scene->addTexture(o); } for (const auto& o : reflectionProbes) { scene->addReflectionProbe(o); } if (environmentTexture()) { scene->environmentTexture = environmentTexture(); } for (const auto& component : scene->_serializableComponents) { component->addFromContainer(*this); } } void AssetContainer::removeAllFromScene() { _wasAddedToScene = false; for (const auto& o : cameras) { scene->removeCamera(o); } for (const auto& o : lights) { scene->removeLight(o); } for (const auto& o : meshes) { scene->removeMesh(o); } for (const auto& o : skeletons) { scene->removeSkeleton(o); } for (const auto& o : animations) { scene->removeAnimation(o); } for (const auto& o : animationGroups) { scene->removeAnimationGroup(o); } for (const auto& o : multiMaterials) { scene->removeMultiMaterial(o); } for (const auto& o : materials) { scene->removeMaterial(o); } for (const auto& o : morphTargetManagers) { scene->removeMorphTargetManager(o); } for (const auto& o : geometries) { scene->removeGeometry(o); } for (const auto& o : transformNodes) { scene->removeTransformNode(o); } for (const auto& o : actionManagers) { scene->removeActionManager(o); } for (const auto& o : textures) { scene->removeTexture(o); } for (const auto& o : reflectionProbes) { scene->removeReflectionProbe(o); } if (environmentTexture() == scene->environmentTexture()) { scene->environmentTexture = nullptr; } for (const auto& component : scene->_serializableComponents) { component->removeFromContainer(*this); } } void AssetContainer::dispose() { for (const auto& o : cameras) { o->dispose(); } cameras.clear(); for (const auto& o : lights) { o->dispose(); } lights.clear(); for (const auto& o : meshes) { scene->removeMesh(o); } meshes.clear(); for (const auto& o : skeletons) { o->dispose(); } skeletons.clear(); for (const auto& o : animationGroups) { o->dispose(); } animationGroups.clear(); for (const auto& o : multiMaterials) { o->dispose(); } multiMaterials.clear(); for (const auto& o : materials) { o->dispose(); } materials.clear(); for (const auto& o : geometries) { o->dispose(); } geometries.clear(); for (const auto& o : transformNodes) { o->dispose(); } transformNodes.clear(); for (const auto& o : actionManagers) { o->dispose(); } actionManagers.clear(); for (const auto& o : textures) { o->dispose(); } textures.clear(); for (const auto& o : reflectionProbes) { o->dispose(); } reflectionProbes.clear(); if (environmentTexture()) { environmentTexture()->dispose(); environmentTexture = nullptr; } for (const auto& component : scene->_serializableComponents) { component->removeFromContainer(*this, true); } } MeshPtr AssetContainer::createRootMesh() { const auto rootMesh = Mesh::New("assetContainerRootMesh", scene); for (const auto& m : meshes) { if (!m->parent) { rootMesh->addChild(*m); } } meshes.insert(meshes.begin(), rootMesh); return rootMesh; } } // end of namespace BABYLON <|endoftext|>
<commit_before>/* * Copyright 2013 Gustaf Räntilä * * 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 LIBQ_PROMISE_DEFER_HPP #define LIBQ_PROMISE_DEFER_HPP namespace q { namespace detail { template< typename... T > class defer : public std::enable_shared_from_this< defer< T... > > { public: typedef ::q::arguments< T... > arguments_type; typedef std::tuple< T... > tuple_type; typedef expect< tuple_type > expect_type; typedef detail::promise_state_data< tuple_type, false > state_data_type; typedef detail::promise_state< tuple_type, false > state_type; typedef promise< tuple_type > promise_type; typedef shared_promise< tuple_type > shared_promise_type; void set_expect( expect_type&& exp ) { if ( exp.has_exception( ) ) set_exception( exp.exception( ) ); else set_value( exp.consume( ) ); } /** * Sets the expected value based on an expect< tuple< expect< > > > */ void set_inner_expect( ::q::expect< std::tuple< > >&& exp ) { if ( exp.has_exception( ) ) { set_value( ::q::refuse< void >( exp.exception( ) ) ); } else { set_value( ::q::fulfill< void >( ) ); } } /** * Sets the expected value based on an expect< tuple< expect< _T > > > */ template< typename _T > typename std::enable_if< sizeof...( T ) == 1 and ::q::is_argument_same_or_convertible< ::q::arguments< _T >, arguments_type >::value >::type set_inner_expect( ::q::expect< std::tuple< _T > >&& exp ) { if ( exp.has_exception( ) ) { set_value( ::q::refuse< _T >( exp.exception( ) ) ); } else { auto tuple = exp.consume( ); auto inner_value = std::move( std::get< 0 >( tuple ) ); set_value( ::q::fulfill< _T >( std::move( inner_value ) ) ); } } inline void set_value( tuple_type&& tuple ) { auto value = ::q::fulfill< tuple_type >( std::move( tuple ) ); promise_.set_value( std::move( value ) ); signal_->done( ); } inline void set_value( const tuple_type& tuple ) { auto value = ::q::fulfill< tuple_type >( tuple ); promise_.set_value( std::move( value ) ); signal_->done( ); } template< typename... Args > typename std::enable_if< ( q::arguments< Args... >::size::value != 1 || !q::is_tuple< typename std::decay< Args >::type... >::value ) && ::q::is_argument_same_or_convertible< q::arguments< Args... >, q::arguments< T... > >::value >::type set_value( Args&&... args ) { set_value( std::make_tuple( std::forward< Args >( args )... ) ); } /** * Sets an exception to this defer, the exception can be any kind of * value, but should preferably be either a @c q::exception or a * @c std::exception_ptr. */ template< typename E > typename std::enable_if< !std::is_same< typename q::remove_cv_ref< E >::type, std::exception_ptr >::value >::type set_exception( E&& e ) { set_exception( std::make_exception_ptr( std::forward< E >( e ) ) ); } void set_exception( const std::exception_ptr& e ) { promise_.set_value( ::q::refuse< tuple_type >( e ) ); signal_->done( ); } void set_current_exception( ) { auto e = std::current_exception( ); promise_.set_value( ::q::refuse< tuple_type >( e ) ); signal_->done( ); } /** * fn( args... ), set_value( void ) */ template< typename Fn, typename... Args > typename std::enable_if< sizeof...( T ) == 0 && Q_RESULT_OF_AS_ARGUMENT( Fn )::size::value == 0 && Q_ARGUMENTS_ARE_CONVERTIBLE_FROM( Fn, Args... )::value >::type set_by_fun( Fn&& fn, Args&&... args ) { try { ::q::call_with_args( std::forward< Fn >( fn ), std::forward< Args >( args )... ); set_value( std::tuple< >( ) ); } catch ( ... ) { set_current_exception( ); } } /** * set_value( fn( args... ) ) */ template< typename Fn, typename... Args > typename std::enable_if< ( sizeof...( T ) > 0 ) && Q_RESULT_OF_AS_ARGUMENT( Fn )::template equals< ::q::arguments< T... > >::value && Q_ARGUMENTS_ARE_CONVERTIBLE_FROM( Fn, Args... )::value >::type set_by_fun( Fn&& fn, Args&&... args ) { try { set_value( ::q::call_with_args( std::forward< Fn >( fn ), std::forward< Args >( args )... ) ); } catch ( ... ) { set_current_exception( ); } } /** * fn( tuple< args >... ), set_value( void ) */ template< typename Fn, typename Args > typename std::enable_if< sizeof...( T ) == 0 && Q_RESULT_OF_AS_ARGUMENT( Fn )::size::value == 0 && ::q::is_tuple< Args >::value && ::q::tuple_arguments< Args >::template is_convertible_to< Q_ARGUMENTS_OF( Fn ) >::value >::type set_by_fun( Fn&& fn, Args&& args ) { try { ::q::call_with_args_by_tuple( std::forward< Fn >( fn ), std::forward< Args >( args ) ); set_value( std::tuple< >( ) ); } catch ( ... ) { set_current_exception( ); } } /** * set_value( fn( tuple< args >... ) ) */ template< typename Fn, typename Args > typename std::enable_if< ( sizeof...( T ) > 0 ) && Q_RESULT_OF_AS_ARGUMENT( Fn )::template equals< ::q::arguments< T... > >::value && ::q::is_tuple< Args >::value && ::q::tuple_arguments< Args >::template is_convertible_to< Q_ARGUMENTS_OF( Fn ) >::value >::type set_by_fun( Fn&& fn, Args&& args ) { try { set_value( ::q::call_with_args_by_tuple( std::forward< Fn >( fn ), std::forward< Args >( args ) ) ); } catch ( ... ) { set_current_exception( ); } } /** * Sets the promise (i.e. value or exception) by a function. * * inner promise = fn( args... ) */ template< typename Fn, typename... Args > typename std::enable_if< Q_ARITY_OF( Fn ) == sizeof...( Args ) && ( Q_ARITY_OF( Fn ) != 1 || Q_ARGUMENTS_ARE_CONVERTIBLE_FROM( Fn, Args... )::value ) && ::q::is_promise< Q_RESULT_OF( Fn ) >::value >::type set_by_fun( Fn&& fn, Args&&... args ) { try { satisfy( ::q::call_with_args( std::forward< Fn >( fn ), std::forward< Args >( args )... ) ); } catch ( ... ) { set_exception( std::make_exception_ptr( broken_promise_exception( std::current_exception( ) ) ) ); } } /** * inner promise = fn( tuple< args >... ) */ template< typename Fn, typename Args > typename std::enable_if< is_tuple< Args >::value && tuple_arguments< Args >::template is_convertible_to< Q_ARGUMENTS_OF( Fn ) >::value && ::q::is_promise< Q_RESULT_OF( Fn ) >::value >::type set_by_fun( Fn&& fn, Args&& args ) { try { satisfy( ::q::call_with_args_by_tuple( std::forward< Fn >( fn ), std::forward< Args >( args ) ) ); } catch ( ... ) { set_exception( std::make_exception_ptr( broken_promise_exception( std::current_exception( ) ) ) ); } } void satisfy( promise_type&& promise ) { auto _this = this->shared_from_this( ); promise .then( [ _this ]( tuple_type&& tuple ) { _this->set_value( std::move( tuple ) ); } ) .fail( [ _this ]( std::exception_ptr&& e ) { _this->set_exception( std::move( e ) ); } ); } void satisfy( shared_promise_type promise ) { auto _this = this->shared_from_this( ); promise .then( [ _this ]( const tuple_type& tuple ) { _this->set_value( tuple ); } ) .fail( [ _this ]( std::exception_ptr&& e ) { _this->set_exception( std::move( e ) ); } ); } /* void satisfy( const shared_promise_type& promise ) { promise_ = std::move( promise.privatize( ) ); signal_->done( ); } */ // Moves the promise out of the defer promise_type get_promise( ) { return std::move( deferred_ ); } template< typename Promise > typename std::enable_if< Promise::shared_type::value && std::is_same< tuple_type, typename Promise::tuple_type >::value, Promise >::type get_suitable_promise( ) { return get_promise( ).share( ); } template< typename Promise > typename std::enable_if< !Promise::shared_type::value && std::is_same< tuple_type, typename Promise::tuple_type >::value, Promise >::type get_suitable_promise( ) { return get_promise( ); } static std::shared_ptr< defer< T... > > construct( const queue_ptr& queue ) { typedef typename state_data_type::future_type future_type; std::promise< expect_type > std_promise; future_type future = std_promise.get_future( ); state_data_type state_data( std::move( future ) ); state_type state( std::move( state_data ) ); auto signal = state.signal( ); promise_type q_promise( std::move( state ), queue ); return ::q::make_shared_using_constructor< defer< T... > >( std::move( std_promise ), std::move( signal ), std::move( q_promise ) ); } protected: defer( ) = delete; defer( std::promise< expect_type >&& promise, promise_signal_ptr&& signal, promise_type&& deferred ) : promise_( std::move( promise ) ) , signal_( std::move( signal ) ) , deferred_( std::move( deferred ) ) { } private: std::promise< expect_type > promise_; promise_signal_ptr signal_; promise_type deferred_; }; template< typename... T > class defer< std::tuple< T... > > : public defer< T... > { }; } // namespace detail } // namespace q #endif // LIBQ_PROMISE_DEFER_HPP <commit_msg>Reference compile issue in defer::set_value<commit_after>/* * Copyright 2013 Gustaf Räntilä * * 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 LIBQ_PROMISE_DEFER_HPP #define LIBQ_PROMISE_DEFER_HPP namespace q { namespace detail { template< typename... T > class defer : public std::enable_shared_from_this< defer< T... > > { public: typedef ::q::arguments< T... > arguments_type; typedef std::tuple< T... > tuple_type; typedef expect< tuple_type > expect_type; typedef detail::promise_state_data< tuple_type, false > state_data_type; typedef detail::promise_state< tuple_type, false > state_type; typedef promise< tuple_type > promise_type; typedef shared_promise< tuple_type > shared_promise_type; void set_expect( expect_type&& exp ) { if ( exp.has_exception( ) ) set_exception( exp.exception( ) ); else set_value( exp.consume( ) ); } /** * Sets the expected value based on an expect< tuple< expect< > > > */ void set_inner_expect( ::q::expect< std::tuple< > >&& exp ) { if ( exp.has_exception( ) ) { set_value( ::q::refuse< void >( exp.exception( ) ) ); } else { set_value( ::q::fulfill< void >( ) ); } } /** * Sets the expected value based on an expect< tuple< expect< _T > > > */ template< typename _T > typename std::enable_if< sizeof...( T ) == 1 and ::q::is_argument_same_or_convertible< ::q::arguments< _T >, arguments_type >::value >::type set_inner_expect( ::q::expect< std::tuple< _T > >&& exp ) { if ( exp.has_exception( ) ) { set_value( ::q::refuse< _T >( exp.exception( ) ) ); } else { auto tuple = exp.consume( ); auto inner_value = std::move( std::get< 0 >( tuple ) ); set_value( ::q::fulfill< _T >( std::move( inner_value ) ) ); } } inline void set_value( tuple_type&& tuple ) { auto value = ::q::fulfill< tuple_type >( std::move( tuple ) ); promise_.set_value( std::move( value ) ); signal_->done( ); } inline void set_value( const tuple_type& tuple ) { auto value = ::q::fulfill< tuple_type >( tuple_type( tuple ) ); promise_.set_value( std::move( value ) ); signal_->done( ); } template< typename... Args > typename std::enable_if< ( q::arguments< Args... >::size::value != 1 || !q::is_tuple< typename std::decay< Args >::type... >::value ) && ::q::is_argument_same_or_convertible< q::arguments< Args... >, q::arguments< T... > >::value >::type set_value( Args&&... args ) { set_value( std::make_tuple( std::forward< Args >( args )... ) ); } /** * Sets an exception to this defer, the exception can be any kind of * value, but should preferably be either a @c q::exception or a * @c std::exception_ptr. */ template< typename E > typename std::enable_if< !std::is_same< typename q::remove_cv_ref< E >::type, std::exception_ptr >::value >::type set_exception( E&& e ) { set_exception( std::make_exception_ptr( std::forward< E >( e ) ) ); } void set_exception( const std::exception_ptr& e ) { promise_.set_value( ::q::refuse< tuple_type >( e ) ); signal_->done( ); } void set_current_exception( ) { auto e = std::current_exception( ); promise_.set_value( ::q::refuse< tuple_type >( e ) ); signal_->done( ); } /** * fn( args... ), set_value( void ) */ template< typename Fn, typename... Args > typename std::enable_if< sizeof...( T ) == 0 && Q_RESULT_OF_AS_ARGUMENT( Fn )::size::value == 0 && Q_ARGUMENTS_ARE_CONVERTIBLE_FROM( Fn, Args... )::value >::type set_by_fun( Fn&& fn, Args&&... args ) { try { ::q::call_with_args( std::forward< Fn >( fn ), std::forward< Args >( args )... ); set_value( std::tuple< >( ) ); } catch ( ... ) { set_current_exception( ); } } /** * set_value( fn( args... ) ) */ template< typename Fn, typename... Args > typename std::enable_if< ( sizeof...( T ) > 0 ) && Q_RESULT_OF_AS_ARGUMENT( Fn )::template equals< ::q::arguments< T... > >::value && Q_ARGUMENTS_ARE_CONVERTIBLE_FROM( Fn, Args... )::value >::type set_by_fun( Fn&& fn, Args&&... args ) { try { set_value( ::q::call_with_args( std::forward< Fn >( fn ), std::forward< Args >( args )... ) ); } catch ( ... ) { set_current_exception( ); } } /** * fn( tuple< args >... ), set_value( void ) */ template< typename Fn, typename Args > typename std::enable_if< sizeof...( T ) == 0 && Q_RESULT_OF_AS_ARGUMENT( Fn )::size::value == 0 && ::q::is_tuple< Args >::value && ::q::tuple_arguments< Args >::template is_convertible_to< Q_ARGUMENTS_OF( Fn ) >::value >::type set_by_fun( Fn&& fn, Args&& args ) { try { ::q::call_with_args_by_tuple( std::forward< Fn >( fn ), std::forward< Args >( args ) ); set_value( std::tuple< >( ) ); } catch ( ... ) { set_current_exception( ); } } /** * set_value( fn( tuple< args >... ) ) */ template< typename Fn, typename Args > typename std::enable_if< ( sizeof...( T ) > 0 ) && Q_RESULT_OF_AS_ARGUMENT( Fn )::template equals< ::q::arguments< T... > >::value && ::q::is_tuple< Args >::value && ::q::tuple_arguments< Args >::template is_convertible_to< Q_ARGUMENTS_OF( Fn ) >::value >::type set_by_fun( Fn&& fn, Args&& args ) { try { set_value( ::q::call_with_args_by_tuple( std::forward< Fn >( fn ), std::forward< Args >( args ) ) ); } catch ( ... ) { set_current_exception( ); } } /** * Sets the promise (i.e. value or exception) by a function. * * inner promise = fn( args... ) */ template< typename Fn, typename... Args > typename std::enable_if< Q_ARITY_OF( Fn ) == sizeof...( Args ) && ( Q_ARITY_OF( Fn ) != 1 || Q_ARGUMENTS_ARE_CONVERTIBLE_FROM( Fn, Args... )::value ) && ::q::is_promise< Q_RESULT_OF( Fn ) >::value >::type set_by_fun( Fn&& fn, Args&&... args ) { try { satisfy( ::q::call_with_args( std::forward< Fn >( fn ), std::forward< Args >( args )... ) ); } catch ( ... ) { set_exception( std::make_exception_ptr( broken_promise_exception( std::current_exception( ) ) ) ); } } /** * inner promise = fn( tuple< args >... ) */ template< typename Fn, typename Args > typename std::enable_if< is_tuple< Args >::value && tuple_arguments< Args >::template is_convertible_to< Q_ARGUMENTS_OF( Fn ) >::value && ::q::is_promise< Q_RESULT_OF( Fn ) >::value >::type set_by_fun( Fn&& fn, Args&& args ) { try { satisfy( ::q::call_with_args_by_tuple( std::forward< Fn >( fn ), std::forward< Args >( args ) ) ); } catch ( ... ) { set_exception( std::make_exception_ptr( broken_promise_exception( std::current_exception( ) ) ) ); } } void satisfy( promise_type&& promise ) { auto _this = this->shared_from_this( ); promise .then( [ _this ]( tuple_type&& tuple ) { _this->set_value( std::move( tuple ) ); } ) .fail( [ _this ]( std::exception_ptr&& e ) { _this->set_exception( std::move( e ) ); } ); } void satisfy( shared_promise_type promise ) { auto _this = this->shared_from_this( ); promise .then( [ _this ]( const tuple_type& tuple ) { _this->set_value( tuple ); } ) .fail( [ _this ]( std::exception_ptr&& e ) { _this->set_exception( std::move( e ) ); } ); } /* void satisfy( const shared_promise_type& promise ) { promise_ = std::move( promise.privatize( ) ); signal_->done( ); } */ // Moves the promise out of the defer promise_type get_promise( ) { return std::move( deferred_ ); } template< typename Promise > typename std::enable_if< Promise::shared_type::value && std::is_same< tuple_type, typename Promise::tuple_type >::value, Promise >::type get_suitable_promise( ) { return get_promise( ).share( ); } template< typename Promise > typename std::enable_if< !Promise::shared_type::value && std::is_same< tuple_type, typename Promise::tuple_type >::value, Promise >::type get_suitable_promise( ) { return get_promise( ); } static std::shared_ptr< defer< T... > > construct( const queue_ptr& queue ) { typedef typename state_data_type::future_type future_type; std::promise< expect_type > std_promise; future_type future = std_promise.get_future( ); state_data_type state_data( std::move( future ) ); state_type state( std::move( state_data ) ); auto signal = state.signal( ); promise_type q_promise( std::move( state ), queue ); return ::q::make_shared_using_constructor< defer< T... > >( std::move( std_promise ), std::move( signal ), std::move( q_promise ) ); } protected: defer( ) = delete; defer( std::promise< expect_type >&& promise, promise_signal_ptr&& signal, promise_type&& deferred ) : promise_( std::move( promise ) ) , signal_( std::move( signal ) ) , deferred_( std::move( deferred ) ) { } private: std::promise< expect_type > promise_; promise_signal_ptr signal_; promise_type deferred_; }; template< typename... T > class defer< std::tuple< T... > > : public defer< T... > { }; } // namespace detail } // namespace q #endif // LIBQ_PROMISE_DEFER_HPP <|endoftext|>
<commit_before>/* * The MIT License (MIT) * * Copyright (c) <2017> <Felix Retsch> * * 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. */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE utf8_checker_tests #include <boost/test/unit_test.hpp> #include "utf8_checker.h" static const int invalid_message_size = 9; static const uint8_t invalid_message[invalid_message_size][4] = {{0xC0,0x00,0x00,0x00}, //invalid start {0xF6,0x00,0x00,0x00}, //invalid start {0x80,0x00,0x00,0x00}, //invalid start {0xC2,0x80,0x80,0x00}, //invalid continuation {0xE0,0x60,0x80,0x00}, //invalid continuation {0xE0,0x9F,0x80,0x00}, //reserved zone {0xED,0xA0,0x80,0x00}, //reserved zone {0xF0,0x8F,0x80,0x80}, //reserved zone {0xF4,0x90,0x80,0x80}}; //reserved zone static const char valid_message[] = "Hello-µ@ßöäüàá-UTF-8!!"; static const uint8_t valid_message_long[] = {0xF1,0x80,0x80,0x80,0xF2,0xA0,0xA0,0xA0}; struct F { F () { cjet_init_checker(&c); } ~F() { } struct cjet_utf8_checker c; }; /** * @brief tests the utf8 checker with a message of length 0 */ BOOST_AUTO_TEST_CASE(test_message_zero_length) { F f; char zero = '\0'; int ret = cjet_is_text_valid(&f.c, &zero, 0, true); BOOST_CHECK_MESSAGE(ret == true, "Message should be valid!"); } /** * @brief tests the utf8 checker with a valid message */ BOOST_AUTO_TEST_CASE(test_valid_message) { F f; int ret = cjet_is_text_valid(&f.c, valid_message, sizeof(valid_message), true); BOOST_CHECK_MESSAGE(ret == true, "Message should be valid!"); } /** * @brief tests the utf8 checker with a fragmented valid message * * The message is fragmented after an utf8 character, considering that * an utf8 character may consists of more than one byte. */ BOOST_AUTO_TEST_CASE(test_valid_message_fragmented_on_codepoints) { F f; int ret = cjet_is_text_valid(&f.c, valid_message, 15, false); BOOST_CHECK_MESSAGE(ret == true, "Message should be valid!"); ret = cjet_is_text_valid(&f.c, valid_message + 15, sizeof(valid_message) - 15, true); BOOST_CHECK_MESSAGE(ret == true, "Message should be valid!"); } /** * @brief tests the utf8 checker with a fragmented valid message * * The message is fragmented after each byte. Hence some utf8 characters * are fragmented, too. */ BOOST_AUTO_TEST_CASE(test_valid_message_fragmented_between_letters) { F f; int ret; for (unsigned int i = 0; i < sizeof(valid_message) - 1; i++) { ret = cjet_is_text_valid(&f.c, valid_message + i, 1, false); BOOST_CHECK_MESSAGE(ret == true, "Message should be valid!"); } ret = cjet_is_text_valid(&f.c, valid_message + sizeof(valid_message) - 1, 1, true); BOOST_CHECK_MESSAGE(ret == true, "Message should be valid!"); } /** * @brief tests the utf8 checker with a valid message * * The message consists of two 4 byte utf8 characters */ BOOST_AUTO_TEST_CASE(test_valid_message_long) { F f; int ret = cjet_is_byte_sequence_valid(&f.c, valid_message_long, sizeof(valid_message_long), true); BOOST_CHECK_MESSAGE(ret == true, "Message should be valid!"); } /** * @brief tests the utf8 checker with a fragmented valid message * * The message consists of two 4 byte utf8 characters and is fragmented * between them. */ BOOST_AUTO_TEST_CASE(test_valid_message_fragmented_on_codepoints_long) { F f; int ret = cjet_is_byte_sequence_valid(&f.c, valid_message_long, 4, false); BOOST_CHECK_MESSAGE(ret == true, "Message should be valid!"); ret = cjet_is_byte_sequence_valid(&f.c, valid_message_long + 4, sizeof(valid_message_long) - 4, true); BOOST_CHECK_MESSAGE(ret == true, "Message should be valid!"); } /** * @brief tests the utf8 checker with a fragmented valid message * * The message consists of two 4 byte utf8 characters. The message * is fragmented after each byte. */ BOOST_AUTO_TEST_CASE(test_valid_message_fragmented_between_letters_long) { F f; int ret; for (unsigned int i = 0; i < sizeof(valid_message_long) - 1; i++) { ret = cjet_is_byte_sequence_valid(&f.c, valid_message_long + i, 1, false); BOOST_CHECK_MESSAGE(ret == true, "Message should be valid!"); } ret = cjet_is_byte_sequence_valid(&f.c, valid_message_long + sizeof(valid_message_long) - 1, 1, true); BOOST_CHECK_MESSAGE(ret == true, "Message should be valid!"); } /** * @brief tests the utf8 checker with a invalid message */ BOOST_AUTO_TEST_CASE(test_invalid_message) { int ret; for (unsigned int i = 0; i < invalid_message_size; i++) { F f; ret = cjet_is_byte_sequence_valid(&f.c, invalid_message[i], sizeof(invalid_message[i]), true); BOOST_CHECK_MESSAGE(ret == false, "Message should be invalid!"); } } /** * @brief tests the utf8 checker with a fragmented invalid message * * The message is fragmented after an utf8 character, considering that * an utf8 character may consists of more than one byte. */ BOOST_AUTO_TEST_CASE(test_invalid_message_fragmented_on_codepoints) { F f; int ret = cjet_is_byte_sequence_valid(&f.c, valid_message_long, sizeof(valid_message_long), false); BOOST_CHECK_MESSAGE(ret == 1, "Message should be valid!"); ret = cjet_is_byte_sequence_valid(&f.c, invalid_message[1], sizeof(invalid_message[1]), true); BOOST_CHECK_MESSAGE(ret == false, "Message should be invalid!"); } /** * @brief tests the utf8 checker with a fragmented invalid message * * The message is fragmented after each byte. Hence some utf8 characters * are fragmented, too. */ BOOST_AUTO_TEST_CASE(test_invalid_message_fragmented_between_letters) { int ret; bool invalid = false; for (unsigned int i = 0; i < invalid_message_size; i++) { F f; for (unsigned int j = 0; j < sizeof(invalid_message[i]) - 1; j++) { ret = cjet_is_byte_sequence_valid(&f.c, &invalid_message[i][j], 1, false); if (ret < 1) { invalid = true; break; } } if (!invalid) { ret = cjet_is_byte_sequence_valid(&f.c, &invalid_message[i][sizeof(invalid_message[i]) - 1], 1, true); } BOOST_CHECK_MESSAGE(ret == false, "Message should be invalid!"); } } /** * @brief tests the utf8 checkers is_complete flag * * An incomplete valid utf8 byte is checked with and without is_complete set. */ BOOST_AUTO_TEST_CASE(test_is_complete_flag) { F f; uint8_t test_msg = 0xC2; int ret = cjet_is_byte_sequence_valid(&f.c, &test_msg, 1, false); BOOST_CHECK_MESSAGE(ret == true, "Message should be valid!"); cjet_init_checker(&f.c); ret = cjet_is_byte_sequence_valid(&f.c, &test_msg, 1, true); BOOST_CHECK_MESSAGE(ret == false, "Message should be invalid!"); } <commit_msg>Change auto_testcase to fixture_testcase<commit_after>/* * The MIT License (MIT) * * Copyright (c) <2017> <Felix Retsch> * * 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. */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE utf8_checker_tests #include <boost/test/unit_test.hpp> #include "utf8_checker.h" static const int invalid_message_size = 9; static const uint8_t invalid_message[invalid_message_size][4] = {{0xC0,0x00,0x00,0x00}, //invalid start {0xF6,0x00,0x00,0x00}, //invalid start {0x80,0x00,0x00,0x00}, //invalid start {0xC2,0x80,0x80,0x00}, //invalid continuation {0xE0,0x60,0x80,0x00}, //invalid continuation {0xE0,0x9F,0x80,0x00}, //reserved zone {0xED,0xA0,0x80,0x00}, //reserved zone {0xF0,0x8F,0x80,0x80}, //reserved zone {0xF4,0x90,0x80,0x80}}; //reserved zone static const char valid_message[] = "Hello-µ@ßöäüàá-UTF-8!!"; static const uint8_t valid_message_long[] = {0xF1,0x80,0x80,0x80,0xF2,0xA0,0xA0,0xA0}; struct F { F () { cjet_init_checker(&c); } ~F() { } struct cjet_utf8_checker c; }; /** * @brief tests the utf8 checker with a message of length 0 */ BOOST_FIXTURE_TEST_CASE(test_message_zero_length, F) { char zero = '\0'; int ret = cjet_is_text_valid(&c, &zero, 0, true); BOOST_CHECK_MESSAGE(ret == true, "Message should be valid!"); } /** * @brief tests the utf8 checker with a valid message */ BOOST_FIXTURE_TEST_CASE(test_valid_message, F) { int ret = cjet_is_text_valid(&c, valid_message, sizeof(valid_message), true); BOOST_CHECK_MESSAGE(ret == true, "Message should be valid!"); } /** * @brief tests the utf8 checker with a fragmented valid message * * The message is fragmented after an utf8 character, considering that * an utf8 character may consists of more than one byte. */ BOOST_FIXTURE_TEST_CASE(test_valid_message_fragmented_on_codepoints, F) { int ret = cjet_is_text_valid(&c, valid_message, 15, false); BOOST_CHECK_MESSAGE(ret == true, "Message should be valid!"); ret = cjet_is_text_valid(&c, valid_message + 15, sizeof(valid_message) - 15, true); BOOST_CHECK_MESSAGE(ret == true, "Message should be valid!"); } /** * @brief tests the utf8 checker with a fragmented valid message * * The message is fragmented after each byte. Hence some utf8 characters * are fragmented, too. */ BOOST_FIXTURE_TEST_CASE(test_valid_message_fragmented_between_letters, F) { int ret; for (unsigned int i = 0; i < sizeof(valid_message) - 1; i++) { ret = cjet_is_text_valid(&c, valid_message + i, 1, false); BOOST_CHECK_MESSAGE(ret == true, "Message should be valid!"); } ret = cjet_is_text_valid(&c, valid_message + sizeof(valid_message) - 1, 1, true); BOOST_CHECK_MESSAGE(ret == true, "Message should be valid!"); } /** * @brief tests the utf8 checker with a valid message * * The message consists of two 4 byte utf8 characters */ BOOST_FIXTURE_TEST_CASE(test_valid_message_long, F) { int ret = cjet_is_byte_sequence_valid(&c, valid_message_long, sizeof(valid_message_long), true); BOOST_CHECK_MESSAGE(ret == true, "Message should be valid!"); } /** * @brief tests the utf8 checker with a fragmented valid message * * The message consists of two 4 byte utf8 characters and is fragmented * between them. */ BOOST_FIXTURE_TEST_CASE(test_valid_message_fragmented_on_codepoints_long, F) { int ret = cjet_is_byte_sequence_valid(&c, valid_message_long, 4, false); BOOST_CHECK_MESSAGE(ret == true, "Message should be valid!"); ret = cjet_is_byte_sequence_valid(&c, valid_message_long + 4, sizeof(valid_message_long) - 4, true); BOOST_CHECK_MESSAGE(ret == true, "Message should be valid!"); } /** * @brief tests the utf8 checker with a fragmented valid message * * The message consists of two 4 byte utf8 characters. The message * is fragmented after each byte. */ BOOST_FIXTURE_TEST_CASE(test_valid_message_fragmented_between_letters_long, F) { int ret; for (unsigned int i = 0; i < sizeof(valid_message_long) - 1; i++) { ret = cjet_is_byte_sequence_valid(&c, valid_message_long + i, 1, false); BOOST_CHECK_MESSAGE(ret == true, "Message should be valid!"); } ret = cjet_is_byte_sequence_valid(&c, valid_message_long + sizeof(valid_message_long) - 1, 1, true); BOOST_CHECK_MESSAGE(ret == true, "Message should be valid!"); } /** * @brief tests the utf8 checker with a invalid message */ BOOST_FIXTURE_TEST_CASE(test_invalid_message, F) { for (unsigned int i = 0; i < invalid_message_size; i++) { cjet_init_checker(&c); int ret = cjet_is_byte_sequence_valid(&c, invalid_message[i], sizeof(invalid_message[i]), true); BOOST_CHECK_MESSAGE(ret == false, "Message should be invalid!"); } } /** * @brief tests the utf8 checker with a fragmented invalid message * * The message is fragmented after an utf8 character, considering that * an utf8 character may consists of more than one byte. */ BOOST_FIXTURE_TEST_CASE(test_invalid_message_fragmented_on_codepoints, F) { int ret = cjet_is_byte_sequence_valid(&c, valid_message_long, sizeof(valid_message_long), false); BOOST_CHECK_MESSAGE(ret == 1, "Message should be valid!"); ret = cjet_is_byte_sequence_valid(&c, invalid_message[1], sizeof(invalid_message[1]), true); BOOST_CHECK_MESSAGE(ret == false, "Message should be invalid!"); } /** * @brief tests the utf8 checker with a fragmented invalid message * * The message is fragmented after each byte. Hence some utf8 characters * are fragmented, too. */ BOOST_FIXTURE_TEST_CASE(test_invalid_message_fragmented_between_letters, F) { int ret; bool invalid = false; for (unsigned int i = 0; i < invalid_message_size; i++) { cjet_init_checker(&c); for (unsigned int j = 0; j < sizeof(invalid_message[i]) - 1; j++) { ret = cjet_is_byte_sequence_valid(&c, &invalid_message[i][j], 1, false); if (ret < 1) { invalid = true; break; } } if (!invalid) { ret = cjet_is_byte_sequence_valid(&c, &invalid_message[i][sizeof(invalid_message[i]) - 1], 1, true); } BOOST_CHECK_MESSAGE(ret == false, "Message should be invalid!"); } } /** * @brief tests the utf8 checkers is_complete flag * * An incomplete valid utf8 byte is checked with and without is_complete set. */ BOOST_FIXTURE_TEST_CASE(test_is_complete_flag, F) { uint8_t test_msg = 0xC2; int ret = cjet_is_byte_sequence_valid(&c, &test_msg, 1, false); BOOST_CHECK_MESSAGE(ret == true, "Message should be valid!"); cjet_init_checker(&c); ret = cjet_is_byte_sequence_valid(&c, &test_msg, 1, true); BOOST_CHECK_MESSAGE(ret == false, "Message should be invalid!"); } <|endoftext|>
<commit_before>// Copyright (c) 2012-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // SYSCOIN #include <primitives/transaction.h> #include <script/standard.h> #include <test/util/setup_common.h> #include <stdint.h> #include <boost/test/unit_test.hpp> // amounts 0.00000001 .. 0.00100000 #define NUM_MULTIPLES_UNIT 100000 // amounts 0.01 .. 100.00 #define NUM_MULTIPLES_CENT 10000 // amounts 1 .. 10000 #define NUM_MULTIPLES_1SYS 10000 // amounts 50 .. 21000000 #define NUM_MULTIPLES_50SYS 420000 BOOST_FIXTURE_TEST_SUITE(compress_tests, BasicTestingSetup) bool static TestEncode(uint64_t in) { return in == DecompressAmount(CompressAmount(in)); } bool static TestDecode(uint64_t in) { return in == CompressAmount(DecompressAmount(in)); } bool static TestPair(uint64_t dec, uint64_t enc) { return CompressAmount(dec) == enc && DecompressAmount(enc) == dec; } BOOST_AUTO_TEST_CASE(compress_amounts) { BOOST_CHECK(TestPair( 0, 0x0)); BOOST_CHECK(TestPair( 1, 0x1)); BOOST_CHECK(TestPair( CENT, 0x7)); BOOST_CHECK(TestPair( COIN, 0x9)); BOOST_CHECK(TestPair( 50*COIN, 0x32)); BOOST_CHECK(TestPair(21000000*COIN, 0x1406f40)); // SYSCOIN auto compressed = CompressAmount(888000000*COIN); BOOST_CHECK_EQUAL(888000000*COIN, (int64_t)DecompressAmount(compressed)); // max amount that can be compressed without unsigned integer overflow its a bit above 2 quintillion range compressed = CompressAmount((2^64)/9); BOOST_CHECK_EQUAL((2^64)/9, (int64_t)DecompressAmount(compressed)); for (uint64_t i = 1; i <= NUM_MULTIPLES_UNIT; i++) BOOST_CHECK(TestEncode(i)); for (uint64_t i = 1; i <= NUM_MULTIPLES_CENT; i++) BOOST_CHECK(TestEncode(i * CENT)); for (uint64_t i = 1; i <= NUM_MULTIPLES_1SYS; i++) BOOST_CHECK(TestEncode(i * COIN)); for (uint64_t i = 1; i <= NUM_MULTIPLES_50SYS; i++) BOOST_CHECK(TestEncode(i * 50 * COIN)); for (uint64_t i = 0; i < 100000; i++) BOOST_CHECK(TestDecode(i)); } BOOST_AUTO_TEST_CASE(compress_script_to_ckey_id) { // case CKeyID CKey key; key.MakeNewKey(true); CPubKey pubkey = key.GetPubKey(); CScript script = CScript() << OP_DUP << OP_HASH160 << ToByteVector(pubkey.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG; BOOST_CHECK_EQUAL(script.size(), 25U); std::vector<unsigned char> out; bool done = CompressScript(script, out); BOOST_CHECK_EQUAL(done, true); // Check compressed script BOOST_CHECK_EQUAL(out.size(), 21U); BOOST_CHECK_EQUAL(out[0], 0x00); BOOST_CHECK_EQUAL(memcmp(&out[1], &script[3], 20), 0); // compare the 20 relevant chars of the CKeyId in the script } BOOST_AUTO_TEST_CASE(compress_script_to_cscript_id) { // case CScriptID CScript script, redeemScript; script << OP_HASH160 << ToByteVector(CScriptID(redeemScript)) << OP_EQUAL; BOOST_CHECK_EQUAL(script.size(), 23U); std::vector<unsigned char> out; bool done = CompressScript(script, out); BOOST_CHECK_EQUAL(done, true); // Check compressed script BOOST_CHECK_EQUAL(out.size(), 21U); BOOST_CHECK_EQUAL(out[0], 0x01); BOOST_CHECK_EQUAL(memcmp(&out[1], &script[2], 20), 0); // compare the 20 relevant chars of the CScriptId in the script } BOOST_AUTO_TEST_CASE(compress_script_to_compressed_pubkey_id) { CKey key; key.MakeNewKey(true); // case compressed PubKeyID CScript script = CScript() << ToByteVector(key.GetPubKey()) << OP_CHECKSIG; // COMPRESSED_PUBLIC_KEY_SIZE (33) BOOST_CHECK_EQUAL(script.size(), 35U); std::vector<unsigned char> out; bool done = CompressScript(script, out); BOOST_CHECK_EQUAL(done, true); // Check compressed script BOOST_CHECK_EQUAL(out.size(), 33U); BOOST_CHECK_EQUAL(memcmp(&out[0], &script[1], 1), 0); BOOST_CHECK_EQUAL(memcmp(&out[1], &script[2], 32), 0); // compare the 32 chars of the compressed CPubKey } BOOST_AUTO_TEST_CASE(compress_script_to_uncompressed_pubkey_id) { CKey key; key.MakeNewKey(false); // case uncompressed PubKeyID CScript script = CScript() << ToByteVector(key.GetPubKey()) << OP_CHECKSIG; // PUBLIC_KEY_SIZE (65) BOOST_CHECK_EQUAL(script.size(), 67U); // 1 char code + 65 char pubkey + OP_CHECKSIG std::vector<unsigned char> out; bool done = CompressScript(script, out); BOOST_CHECK_EQUAL(done, true); // Check compressed script BOOST_CHECK_EQUAL(out.size(), 33U); BOOST_CHECK_EQUAL(memcmp(&out[1], &script[2], 32), 0); // first 32 chars of CPubKey are copied into out[1:] BOOST_CHECK_EQUAL(out[0], 0x04 | (script[65] & 0x01)); // least significant bit (lsb) of last char of pubkey is mapped into out[0] } BOOST_AUTO_TEST_SUITE_END() <commit_msg>fix test<commit_after>// Copyright (c) 2012-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // SYSCOIN #include <primitives/transaction.h> #include <script/standard.h> #include <test/util/setup_common.h> #include <stdint.h> #include <boost/test/unit_test.hpp> // amounts 0.00000001 .. 0.00100000 #define NUM_MULTIPLES_UNIT 100000 // amounts 0.01 .. 100.00 #define NUM_MULTIPLES_CENT 10000 // amounts 1 .. 10000 #define NUM_MULTIPLES_1SYS 10000 // amounts 50 .. 21000000 #define NUM_MULTIPLES_50SYS 420000 BOOST_FIXTURE_TEST_SUITE(compress_tests, BasicTestingSetup) bool static TestEncode(uint64_t in) { return in == DecompressAmount(CompressAmount(in)); } bool static TestDecode(uint64_t in) { return in == CompressAmount(DecompressAmount(in)); } bool static TestPair(uint64_t dec, uint64_t enc) { return CompressAmount(dec) == enc && DecompressAmount(enc) == dec; } BOOST_AUTO_TEST_CASE(compress_amounts) { BOOST_CHECK(TestPair( 0, 0x0)); BOOST_CHECK(TestPair( 1, 0x1)); BOOST_CHECK(TestPair( CENT, 0x7)); BOOST_CHECK(TestPair( COIN, 0x9)); BOOST_CHECK(TestPair( 50*COIN, 0x32)); BOOST_CHECK(TestPair(21000000*COIN, 0x1406f40)); // SYSCOIN auto compressed = CompressAmount(888000000*COIN); BOOST_CHECK_EQUAL(888000000*COIN, (int64_t)DecompressAmount(compressed)); // max amount that can be compressed without unsigned integer overflow its a bit above 2 quintillion range compressed = CompressAmount((0x2^64)/9); BOOST_CHECK_EQUAL((0x2^64)/9, (int64_t)DecompressAmount(compressed)); for (uint64_t i = 1; i <= NUM_MULTIPLES_UNIT; i++) BOOST_CHECK(TestEncode(i)); for (uint64_t i = 1; i <= NUM_MULTIPLES_CENT; i++) BOOST_CHECK(TestEncode(i * CENT)); for (uint64_t i = 1; i <= NUM_MULTIPLES_1SYS; i++) BOOST_CHECK(TestEncode(i * COIN)); for (uint64_t i = 1; i <= NUM_MULTIPLES_50SYS; i++) BOOST_CHECK(TestEncode(i * 50 * COIN)); for (uint64_t i = 0; i < 100000; i++) BOOST_CHECK(TestDecode(i)); } BOOST_AUTO_TEST_CASE(compress_script_to_ckey_id) { // case CKeyID CKey key; key.MakeNewKey(true); CPubKey pubkey = key.GetPubKey(); CScript script = CScript() << OP_DUP << OP_HASH160 << ToByteVector(pubkey.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG; BOOST_CHECK_EQUAL(script.size(), 25U); std::vector<unsigned char> out; bool done = CompressScript(script, out); BOOST_CHECK_EQUAL(done, true); // Check compressed script BOOST_CHECK_EQUAL(out.size(), 21U); BOOST_CHECK_EQUAL(out[0], 0x00); BOOST_CHECK_EQUAL(memcmp(&out[1], &script[3], 20), 0); // compare the 20 relevant chars of the CKeyId in the script } BOOST_AUTO_TEST_CASE(compress_script_to_cscript_id) { // case CScriptID CScript script, redeemScript; script << OP_HASH160 << ToByteVector(CScriptID(redeemScript)) << OP_EQUAL; BOOST_CHECK_EQUAL(script.size(), 23U); std::vector<unsigned char> out; bool done = CompressScript(script, out); BOOST_CHECK_EQUAL(done, true); // Check compressed script BOOST_CHECK_EQUAL(out.size(), 21U); BOOST_CHECK_EQUAL(out[0], 0x01); BOOST_CHECK_EQUAL(memcmp(&out[1], &script[2], 20), 0); // compare the 20 relevant chars of the CScriptId in the script } BOOST_AUTO_TEST_CASE(compress_script_to_compressed_pubkey_id) { CKey key; key.MakeNewKey(true); // case compressed PubKeyID CScript script = CScript() << ToByteVector(key.GetPubKey()) << OP_CHECKSIG; // COMPRESSED_PUBLIC_KEY_SIZE (33) BOOST_CHECK_EQUAL(script.size(), 35U); std::vector<unsigned char> out; bool done = CompressScript(script, out); BOOST_CHECK_EQUAL(done, true); // Check compressed script BOOST_CHECK_EQUAL(out.size(), 33U); BOOST_CHECK_EQUAL(memcmp(&out[0], &script[1], 1), 0); BOOST_CHECK_EQUAL(memcmp(&out[1], &script[2], 32), 0); // compare the 32 chars of the compressed CPubKey } BOOST_AUTO_TEST_CASE(compress_script_to_uncompressed_pubkey_id) { CKey key; key.MakeNewKey(false); // case uncompressed PubKeyID CScript script = CScript() << ToByteVector(key.GetPubKey()) << OP_CHECKSIG; // PUBLIC_KEY_SIZE (65) BOOST_CHECK_EQUAL(script.size(), 67U); // 1 char code + 65 char pubkey + OP_CHECKSIG std::vector<unsigned char> out; bool done = CompressScript(script, out); BOOST_CHECK_EQUAL(done, true); // Check compressed script BOOST_CHECK_EQUAL(out.size(), 33U); BOOST_CHECK_EQUAL(memcmp(&out[1], &script[2], 32), 0); // first 32 chars of CPubKey are copied into out[1:] BOOST_CHECK_EQUAL(out[0], 0x04 | (script[65] & 0x01)); // least significant bit (lsb) of last char of pubkey is mapped into out[0] } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>#include "portability_analyser.h" #include "log.h" #include "types.h" namespace bpftrace { namespace ast { PortabilityAnalyser::PortabilityAnalyser(Node *root, std::ostream &out) : root_(root), out_(out) { } int PortabilityAnalyser::analyse() { Visit(*root_); std::string errors = err_.str(); if (!errors.empty()) { out_ << errors; return 1; } return 0; } void PortabilityAnalyser::visit(PositionalParameter &param) { // Positional params are only known at runtime. Currently, codegen directly // embeds positional params into the bytecode but that does not work for AOT. // // In theory we could allow positional params for AOT and just embed the // values into the bytecode but there's really no point to that as: // // * that would mislead the user into thinking there's positional param // support // * the user can just hard code the values into their script LOG(ERROR, param.loc, err_) << "AOT does not yet support positional parameters"; } void PortabilityAnalyser::visit(Builtin &builtin) { // `struct task_struct` is unstable across kernel versions and configurations. // This makes it inherently unportable. We must block it until we support // field access relocations. if (builtin.ident == "curtask") { LOG(ERROR, builtin.loc, err_) << "AOT does not yet support accessing `curtask`"; } } void PortabilityAnalyser::visit(Call &call) { if (call.vargs) { for (Expression *expr : *call.vargs) Visit(*expr); } // kaddr() and uaddr() both resolve symbols -> address during codegen and // embeds the values into the bytecode. For AOT to support kaddr()/uaddr(), // the addresses must be resolved at runtime and fixed up during load time. // // cgroupid can vary across systems just like how a process does not // necessarily share the same PID across multiple systems. cgroupid() is also // resolved during codegen and the value embedded into the bytecode. For AOT // to support cgroupid(), the cgroupid must be resolved at runtime and fixed // up during load time. if (call.func == "kaddr" || call.func == "uaddr" || call.func == "cgroupid") { LOG(ERROR, call.loc, err_) << "AOT does not yet support " << call.func << "()"; } } void PortabilityAnalyser::visit(Cast &cast) { Visit(*cast.expr); // The goal here is to block arbitrary field accesses but still allow `args` // access. `args` for tracepoint is fairly stable and should be considered // portable. `args` for k[ret]funcs are type checked by the kernel and may // also be considered stable. For AOT to fully support field accesses, we // need to relocate field access at runtime. LOG(ERROR, cast.loc, err_) << "AOT does not yet support struct casts"; } void PortabilityAnalyser::visit(AttachPoint &ap) { auto type = probetype(ap.provider); // USDT probes require analyzing a USDT enabled binary for precise offsets // and argument information. This analyzing is currently done during codegen // and offsets and type information is embedded into the bytecode. For AOT // support, this analyzing must be done during runtime and fixed up during // load time. if (type == ProbeType::usdt) { LOG(ERROR, ap.loc, err_) << "AOT does not yet support USDT probes"; } // While userspace watchpoint probes are technically portable from codegen // point of view, they require a PID or path via cmdline to resolve address. // watchpoint probes are also API-unstable and need a further change // (see https://github.com/iovisor/bpftrace/issues/1683). // // So disable for now and re-evalulate at another point. else if (type == ProbeType::watchpoint || type == ProbeType::asyncwatchpoint) { LOG(ERROR, ap.loc, err_) << "AOT does not yet support watchpoint probes"; } } Pass CreatePortabilityPass() { auto fn = [](Node &n, PassContext &__attribute__((unused))) { PortabilityAnalyser analyser{ &n }; if (analyser.analyse()) return PassResult::Error(""); return PassResult::Success(); }; return Pass("PortabilityAnalyser", fn); } } // namespace ast } // namespace bpftrace <commit_msg>aot: Add magic env var for knowing when a feature was disabled<commit_after>#include "portability_analyser.h" #include <cstdlib> #include "log.h" #include "types.h" namespace bpftrace { namespace ast { PortabilityAnalyser::PortabilityAnalyser(Node *root, std::ostream &out) : root_(root), out_(out) { } int PortabilityAnalyser::analyse() { Visit(*root_); std::string errors = err_.str(); if (!errors.empty()) { out_ << errors; return 1; } return 0; } void PortabilityAnalyser::visit(PositionalParameter &param) { // Positional params are only known at runtime. Currently, codegen directly // embeds positional params into the bytecode but that does not work for AOT. // // In theory we could allow positional params for AOT and just embed the // values into the bytecode but there's really no point to that as: // // * that would mislead the user into thinking there's positional param // support // * the user can just hard code the values into their script LOG(ERROR, param.loc, err_) << "AOT does not yet support positional parameters"; } void PortabilityAnalyser::visit(Builtin &builtin) { // `struct task_struct` is unstable across kernel versions and configurations. // This makes it inherently unportable. We must block it until we support // field access relocations. if (builtin.ident == "curtask") { LOG(ERROR, builtin.loc, err_) << "AOT does not yet support accessing `curtask`"; } } void PortabilityAnalyser::visit(Call &call) { if (call.vargs) { for (Expression *expr : *call.vargs) Visit(*expr); } // kaddr() and uaddr() both resolve symbols -> address during codegen and // embeds the values into the bytecode. For AOT to support kaddr()/uaddr(), // the addresses must be resolved at runtime and fixed up during load time. // // cgroupid can vary across systems just like how a process does not // necessarily share the same PID across multiple systems. cgroupid() is also // resolved during codegen and the value embedded into the bytecode. For AOT // to support cgroupid(), the cgroupid must be resolved at runtime and fixed // up during load time. if (call.func == "kaddr" || call.func == "uaddr" || call.func == "cgroupid") { LOG(ERROR, call.loc, err_) << "AOT does not yet support " << call.func << "()"; } } void PortabilityAnalyser::visit(Cast &cast) { Visit(*cast.expr); // The goal here is to block arbitrary field accesses but still allow `args` // access. `args` for tracepoint is fairly stable and should be considered // portable. `args` for k[ret]funcs are type checked by the kernel and may // also be considered stable. For AOT to fully support field accesses, we // need to relocate field access at runtime. LOG(ERROR, cast.loc, err_) << "AOT does not yet support struct casts"; } void PortabilityAnalyser::visit(AttachPoint &ap) { auto type = probetype(ap.provider); // USDT probes require analyzing a USDT enabled binary for precise offsets // and argument information. This analyzing is currently done during codegen // and offsets and type information is embedded into the bytecode. For AOT // support, this analyzing must be done during runtime and fixed up during // load time. if (type == ProbeType::usdt) { LOG(ERROR, ap.loc, err_) << "AOT does not yet support USDT probes"; } // While userspace watchpoint probes are technically portable from codegen // point of view, they require a PID or path via cmdline to resolve address. // watchpoint probes are also API-unstable and need a further change // (see https://github.com/iovisor/bpftrace/issues/1683). // // So disable for now and re-evalulate at another point. else if (type == ProbeType::watchpoint || type == ProbeType::asyncwatchpoint) { LOG(ERROR, ap.loc, err_) << "AOT does not yet support watchpoint probes"; } } Pass CreatePortabilityPass() { auto fn = [](Node &n, PassContext &__attribute__((unused))) { PortabilityAnalyser analyser{ &n }; if (analyser.analyse()) { // Used by runtime test framework to know when to skip an AOT test if (std::getenv("__BPFTRACE_NOTIFY_AOT_PORTABILITY_DISABLED")) std::cout << "__BPFTRACE_NOTIFY_AOT_PORTABILITY_DISABLED" << std::endl; return PassResult::Error(""); } return PassResult::Success(); }; return Pass("PortabilityAnalyser", fn); } } // namespace ast } // namespace bpftrace <|endoftext|>
<commit_before>/* * Copyright 2011 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. */ // Author: morlovich@google.com (Maksim Orlovich) #include "net/instaweb/util/public/shared_mem_lock_manager.h" #include <cstddef> #include "base/logging.h" #include "base/scoped_ptr.h" #include "net/instaweb/util/public/abstract_mutex.h" #include "net/instaweb/util/public/abstract_shared_mem.h" #include "net/instaweb/util/public/basictypes.h" #include "net/instaweb/util/public/hasher.h" #include "net/instaweb/util/public/message_handler.h" #include "net/instaweb/util/public/string.h" #include "net/instaweb/util/public/string_util.h" #include "net/instaweb/util/public/scheduler.h" #include "net/instaweb/util/public/scheduler_based_abstract_lock.h" #include "net/instaweb/util/public/timer.h" namespace net_instaweb { namespace SharedMemLockData { // Memory structure: // // Bucket 0: // Slot 0 // lock name hash (64-bit) // acquire timestamp (64-bit) // Slot 1 // ... // Slot 15 // Mutex // (pad to 64-byte alignment) // Bucket 1: // .. // Bucket 63: // .. // // Each key is statically assigned to a bucket based on its hash. // When we're trying to lock or unlock the given named lock, we lock // the corresponding bucket. // // Whenever a lock is held, some slot in the corresponding bucket has its hash // and the time of acquisition. When a slot is free (or unlocked), its timestamp // is set to kNotAcquired. // // Very old locks can be stolen by new clients, in which case the timestamp gets // updated. This serves multiple purposes: // 1) It means only one extra process will grab it for each timeout period, // as all others will see the new timestamp. // 2) It makes it possible for the last grabber to be the one to unlock the // lock, as we check the grabber's acquisition timestamp versus the lock's. // // A further issue is what happens when a bucket is overflowed. In that case, // however, we simply state that lock acquisition failed. This is because the // purpose of this service is to limit the load on the system, and the table // getting filled suggests it's under heavy load as it is, in which case // blocking further operations is desirable. // const size_t kBuckets = 64; // assumed to be <= 256 const size_t kSlotsPerBucket = 32; struct Slot { uint64 hash; int64 acquired_at_ms; // kNotAcquired if free. }; const int64 kNotAcquired = 0; struct Bucket { Slot slots[kSlotsPerBucket]; char mutex_base[1]; }; inline size_t Align64(size_t in) { return (in + 63) & ~63; } inline size_t BucketSize(size_t lock_size) { return Align64(offsetof(Bucket, mutex_base) + lock_size); } inline size_t SegmentSize(size_t lock_size) { return kBuckets * BucketSize(lock_size); } } // namespace SharedMemLockData namespace Data = SharedMemLockData; class SharedMemLock : public SchedulerBasedAbstractLock { public: virtual ~SharedMemLock() { Unlock(); } virtual bool TryLock() { return TryLockImpl(false, 0); } virtual bool TryLockStealOld(int64 timeout_ms) { return TryLockImpl(true, timeout_ms); } virtual void Unlock() { if (acquisition_time_ == Data::kNotAcquired) { return; } // Protect the bucket. scoped_ptr<AbstractMutex> lock(AttachMutex()); ScopedMutex hold_lock(lock.get()); // Search for this lock. // note: we permit empty slots in the middle, and start search at different // positions depending on the hash to increase chance of quick hit. // TODO(morlovich): Consider remembering which bucket we locked to avoid // the search. (Could potentially be made lock-free, too). size_t base = hash_ % Data::kSlotsPerBucket; for (size_t offset = 0; offset < Data::kSlotsPerBucket; ++offset) { size_t s = (base + offset) % Data::kSlotsPerBucket; Data::Slot& slot = bucket_->slots[s]; if (slot.hash == hash_ && slot.acquired_at_ms == acquisition_time_) { slot.acquired_at_ms = Data::kNotAcquired; break; } } acquisition_time_ = Data::kNotAcquired; } virtual GoogleString name() { return name_; } virtual bool Held() { return (acquisition_time_ != Data::kNotAcquired); } protected: virtual Scheduler* scheduler() const { return manager_->scheduler_; } private: friend class SharedMemLockManager; // ctor should only be called by CreateNamedLock below. SharedMemLock(SharedMemLockManager* manager, const StringPiece& name) : manager_(manager), name_(name.data(), name.size()), acquisition_time_(Data::kNotAcquired) { size_t bucket_num; GetHashAndBucket(name_, &hash_, &bucket_num); bucket_ = manager_->Bucket(bucket_num); } // Compute hash and bucket used to store the lock for a given lock name. void GetHashAndBucket(const StringPiece& name, uint64* hash_out, size_t* bucket_out) { GoogleString raw_hash = manager_->hasher_->RawHash(name); // We use separate hash bits to determine the hash and the bucket. *bucket_out = static_cast<unsigned char>(raw_hash[8]) % Data::kBuckets; uint64 hash = 0; for (int c = 0; c < 8; ++c) { hash = (hash << 8) | static_cast<unsigned char>(raw_hash[c]); } *hash_out = hash; } AbstractMutex* AttachMutex() const { return manager_->seg_->AttachToSharedMutex( manager_->MutexOffset(bucket_)); } bool TryLockImpl(bool steal, int64 steal_timeout_ms) { // Protect the bucket. scoped_ptr<AbstractMutex> lock(AttachMutex()); ScopedMutex hold_lock(lock.get()); int64 now_ms = manager_->scheduler_->timer()->NowMs(); if (now_ms == Data::kNotAcquired) { ++now_ms; } // Search for existing lock or empty slot. We need to check everything // for existing lock, of course. size_t empty_slot = Data::kSlotsPerBucket; size_t base = hash_ % Data::kSlotsPerBucket; for (size_t offset = 0; offset < Data::kSlotsPerBucket; ++offset) { size_t s = (base + offset) % Data::kSlotsPerBucket; Data::Slot& slot = bucket_->slots[s]; if (slot.hash == hash_) { if (slot.acquired_at_ms == Data::kNotAcquired || (steal && ((now_ms - slot.acquired_at_ms) >= steal_timeout_ms))) { // Stealing lock, or re-using a free slot we ourselves unlocked. // // We know we don't have an actual locked entry with our key elsewhere // because: // 1) After our last unlock of it no one else has ever locked it (or // our key would have been overwritten), so if we ever performed an // another lock operation we would have done it with this slot in // present state. // // 2) We always chose the first candidate. DoLockSlot(s, now_ms); return true; } else { // Not permitted to steal or not stale enough to steal. return false; } } else if (slot.acquired_at_ms == Data::kNotAcquired) { if (empty_slot == Data::kSlotsPerBucket) { empty_slot = s; } } } if (empty_slot != Data::kSlotsPerBucket) { DoLockSlot(empty_slot, now_ms); return true; } manager_->handler_->Message(kInfo, "Overflowed bucket trying to grab lock."); return false; } // Writes out our ID and current timestamp into the slot, and marks the // fact of our acquisition. void DoLockSlot(size_t s, int64 now_ms) { Data::Slot& slot = bucket_->slots[s]; slot.hash = hash_; slot.acquired_at_ms = now_ms; acquisition_time_ = now_ms; } SharedMemLockManager* manager_; GoogleString name_; uint64 hash_; // Time at which we acquired the lock... int64 acquisition_time_; // base pointer for the bucket we are in. Data::Bucket* bucket_; DISALLOW_COPY_AND_ASSIGN(SharedMemLock); }; SharedMemLockManager::SharedMemLockManager( AbstractSharedMem* shm, const GoogleString& path, Scheduler* scheduler, Hasher* hasher, MessageHandler* handler) : shm_runtime_(shm), path_(path), scheduler_(scheduler), hasher_(hasher), handler_(handler), lock_size_(shm->SharedMutexSize()) { CHECK_GE(hasher_->RawHashSizeInBytes(), 9) << "Need >= 9 byte hashes"; } SharedMemLockManager::~SharedMemLockManager() { } bool SharedMemLockManager::Initialize() { seg_.reset(shm_runtime_->CreateSegment(path_, Data::SegmentSize(lock_size_), handler_)); if (seg_.get() == NULL) { handler_->Message(kError, "Unable to create memory segment for locks."); return false; } // Create the mutexes for each bucket for (size_t bucket = 0; bucket < Data::kBuckets; ++bucket) { if (!seg_->InitializeSharedMutex(MutexOffset(Bucket(bucket)), handler_)) { handler_->Message(kError, "%s", StrCat("Unable to create lock service mutex #", Integer64ToString(bucket)).c_str()); return false; } } return true; } bool SharedMemLockManager::Attach() { size_t size = Data::SegmentSize(shm_runtime_->SharedMutexSize()); seg_.reset(shm_runtime_->AttachToSegment(path_, size, handler_)); if (seg_.get() == NULL) { handler_->Message(kWarning, "Unable to attach to lock service SHM segment"); return false; } return true; } void SharedMemLockManager::GlobalCleanup( AbstractSharedMem* shm, const GoogleString& path, MessageHandler* handler) { shm->DestroySegment(path, handler); } NamedLock* SharedMemLockManager::CreateNamedLock(const StringPiece& name) { return new SharedMemLock(this, name); } Data::Bucket* SharedMemLockManager::Bucket(size_t bucket) { return reinterpret_cast<Data::Bucket*>( const_cast<char*>(seg_->Base()) + bucket * Data::BucketSize(lock_size_)); } size_t SharedMemLockManager::MutexOffset(SharedMemLockData::Bucket* bucket) { return &bucket->mutex_base[0] - seg_->Base(); } } // namespace net_instaweb <commit_msg>Bump the number of buckets here; load testing suggests the current setting is insufficient.<commit_after>/* * Copyright 2011 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. */ // Author: morlovich@google.com (Maksim Orlovich) #include "net/instaweb/util/public/shared_mem_lock_manager.h" #include <cstddef> #include "base/logging.h" #include "base/scoped_ptr.h" #include "net/instaweb/util/public/abstract_mutex.h" #include "net/instaweb/util/public/abstract_shared_mem.h" #include "net/instaweb/util/public/basictypes.h" #include "net/instaweb/util/public/hasher.h" #include "net/instaweb/util/public/message_handler.h" #include "net/instaweb/util/public/string.h" #include "net/instaweb/util/public/string_util.h" #include "net/instaweb/util/public/scheduler.h" #include "net/instaweb/util/public/scheduler_based_abstract_lock.h" #include "net/instaweb/util/public/timer.h" namespace net_instaweb { namespace SharedMemLockData { // Memory structure: // // Bucket 0: // Slot 0 // lock name hash (64-bit) // acquire timestamp (64-bit) // Slot 1 // ... // Slot kSlotsPerBucket - 1 // Mutex // (pad to 64-byte alignment) // Bucket 1: // .. // Bucket kBuckets - 1: // .. // // Each key is statically assigned to a bucket based on its hash. // When we're trying to lock or unlock the given named lock, we lock // the corresponding bucket. // // Whenever a lock is held, some slot in the corresponding bucket has its hash // and the time of acquisition. When a slot is free (or unlocked), its timestamp // is set to kNotAcquired. // // Very old locks can be stolen by new clients, in which case the timestamp gets // updated. This serves multiple purposes: // 1) It means only one extra process will grab it for each timeout period, // as all others will see the new timestamp. // 2) It makes it possible for the last grabber to be the one to unlock the // lock, as we check the grabber's acquisition timestamp versus the lock's. // // A further issue is what happens when a bucket is overflowed. In that case, // however, we simply state that lock acquisition failed. This is because the // purpose of this service is to limit the load on the system, and the table // getting filled suggests it's under heavy load as it is, in which case // blocking further operations is desirable. // const size_t kBuckets = 256; // assumed to be <= 256 const size_t kSlotsPerBucket = 32; struct Slot { uint64 hash; int64 acquired_at_ms; // kNotAcquired if free. }; const int64 kNotAcquired = 0; struct Bucket { Slot slots[kSlotsPerBucket]; char mutex_base[1]; }; inline size_t Align64(size_t in) { return (in + 63) & ~63; } inline size_t BucketSize(size_t lock_size) { return Align64(offsetof(Bucket, mutex_base) + lock_size); } inline size_t SegmentSize(size_t lock_size) { return kBuckets * BucketSize(lock_size); } } // namespace SharedMemLockData namespace Data = SharedMemLockData; class SharedMemLock : public SchedulerBasedAbstractLock { public: virtual ~SharedMemLock() { Unlock(); } virtual bool TryLock() { return TryLockImpl(false, 0); } virtual bool TryLockStealOld(int64 timeout_ms) { return TryLockImpl(true, timeout_ms); } virtual void Unlock() { if (acquisition_time_ == Data::kNotAcquired) { return; } // Protect the bucket. scoped_ptr<AbstractMutex> lock(AttachMutex()); ScopedMutex hold_lock(lock.get()); // Search for this lock. // note: we permit empty slots in the middle, and start search at different // positions depending on the hash to increase chance of quick hit. // TODO(morlovich): Consider remembering which bucket we locked to avoid // the search. (Could potentially be made lock-free, too). size_t base = hash_ % Data::kSlotsPerBucket; for (size_t offset = 0; offset < Data::kSlotsPerBucket; ++offset) { size_t s = (base + offset) % Data::kSlotsPerBucket; Data::Slot& slot = bucket_->slots[s]; if (slot.hash == hash_ && slot.acquired_at_ms == acquisition_time_) { slot.acquired_at_ms = Data::kNotAcquired; break; } } acquisition_time_ = Data::kNotAcquired; } virtual GoogleString name() { return name_; } virtual bool Held() { return (acquisition_time_ != Data::kNotAcquired); } protected: virtual Scheduler* scheduler() const { return manager_->scheduler_; } private: friend class SharedMemLockManager; // ctor should only be called by CreateNamedLock below. SharedMemLock(SharedMemLockManager* manager, const StringPiece& name) : manager_(manager), name_(name.data(), name.size()), acquisition_time_(Data::kNotAcquired) { size_t bucket_num; GetHashAndBucket(name_, &hash_, &bucket_num); bucket_ = manager_->Bucket(bucket_num); } // Compute hash and bucket used to store the lock for a given lock name. void GetHashAndBucket(const StringPiece& name, uint64* hash_out, size_t* bucket_out) { GoogleString raw_hash = manager_->hasher_->RawHash(name); // We use separate hash bits to determine the hash and the bucket. *bucket_out = static_cast<unsigned char>(raw_hash[8]) % Data::kBuckets; uint64 hash = 0; for (int c = 0; c < 8; ++c) { hash = (hash << 8) | static_cast<unsigned char>(raw_hash[c]); } *hash_out = hash; } AbstractMutex* AttachMutex() const { return manager_->seg_->AttachToSharedMutex( manager_->MutexOffset(bucket_)); } bool TryLockImpl(bool steal, int64 steal_timeout_ms) { // Protect the bucket. scoped_ptr<AbstractMutex> lock(AttachMutex()); ScopedMutex hold_lock(lock.get()); int64 now_ms = manager_->scheduler_->timer()->NowMs(); if (now_ms == Data::kNotAcquired) { ++now_ms; } // Search for existing lock or empty slot. We need to check everything // for existing lock, of course. size_t empty_slot = Data::kSlotsPerBucket; size_t base = hash_ % Data::kSlotsPerBucket; for (size_t offset = 0; offset < Data::kSlotsPerBucket; ++offset) { size_t s = (base + offset) % Data::kSlotsPerBucket; Data::Slot& slot = bucket_->slots[s]; if (slot.hash == hash_) { if (slot.acquired_at_ms == Data::kNotAcquired || (steal && ((now_ms - slot.acquired_at_ms) >= steal_timeout_ms))) { // Stealing lock, or re-using a free slot we ourselves unlocked. // // We know we don't have an actual locked entry with our key elsewhere // because: // 1) After our last unlock of it no one else has ever locked it (or // our key would have been overwritten), so if we ever performed an // another lock operation we would have done it with this slot in // present state. // // 2) We always chose the first candidate. DoLockSlot(s, now_ms); return true; } else { // Not permitted to steal or not stale enough to steal. return false; } } else if (slot.acquired_at_ms == Data::kNotAcquired) { if (empty_slot == Data::kSlotsPerBucket) { empty_slot = s; } } } if (empty_slot != Data::kSlotsPerBucket) { DoLockSlot(empty_slot, now_ms); return true; } manager_->handler_->Message(kInfo, "Overflowed bucket trying to grab lock."); return false; } // Writes out our ID and current timestamp into the slot, and marks the // fact of our acquisition. void DoLockSlot(size_t s, int64 now_ms) { Data::Slot& slot = bucket_->slots[s]; slot.hash = hash_; slot.acquired_at_ms = now_ms; acquisition_time_ = now_ms; } SharedMemLockManager* manager_; GoogleString name_; uint64 hash_; // Time at which we acquired the lock... int64 acquisition_time_; // base pointer for the bucket we are in. Data::Bucket* bucket_; DISALLOW_COPY_AND_ASSIGN(SharedMemLock); }; SharedMemLockManager::SharedMemLockManager( AbstractSharedMem* shm, const GoogleString& path, Scheduler* scheduler, Hasher* hasher, MessageHandler* handler) : shm_runtime_(shm), path_(path), scheduler_(scheduler), hasher_(hasher), handler_(handler), lock_size_(shm->SharedMutexSize()) { CHECK_GE(hasher_->RawHashSizeInBytes(), 9) << "Need >= 9 byte hashes"; } SharedMemLockManager::~SharedMemLockManager() { } bool SharedMemLockManager::Initialize() { seg_.reset(shm_runtime_->CreateSegment(path_, Data::SegmentSize(lock_size_), handler_)); if (seg_.get() == NULL) { handler_->Message(kError, "Unable to create memory segment for locks."); return false; } // Create the mutexes for each bucket for (size_t bucket = 0; bucket < Data::kBuckets; ++bucket) { if (!seg_->InitializeSharedMutex(MutexOffset(Bucket(bucket)), handler_)) { handler_->Message(kError, "%s", StrCat("Unable to create lock service mutex #", Integer64ToString(bucket)).c_str()); return false; } } return true; } bool SharedMemLockManager::Attach() { size_t size = Data::SegmentSize(shm_runtime_->SharedMutexSize()); seg_.reset(shm_runtime_->AttachToSegment(path_, size, handler_)); if (seg_.get() == NULL) { handler_->Message(kWarning, "Unable to attach to lock service SHM segment"); return false; } return true; } void SharedMemLockManager::GlobalCleanup( AbstractSharedMem* shm, const GoogleString& path, MessageHandler* handler) { shm->DestroySegment(path, handler); } NamedLock* SharedMemLockManager::CreateNamedLock(const StringPiece& name) { return new SharedMemLock(this, name); } Data::Bucket* SharedMemLockManager::Bucket(size_t bucket) { return reinterpret_cast<Data::Bucket*>( const_cast<char*>(seg_->Base()) + bucket * Data::BucketSize(lock_size_)); } size_t SharedMemLockManager::MutexOffset(SharedMemLockData::Bucket* bucket) { return &bucket->mutex_base[0] - seg_->Base(); } } // namespace net_instaweb <|endoftext|>
<commit_before>#include "ghost/timing.h" #include "ghost/util.h" #include <map> #include <vector> #include <sstream> #include <iostream> #include <iomanip> #include <numeric> #include <algorithm> using namespace std; /** * @brief Region timing accumulator */ typedef struct { /** * @brief The runtimes of this region. */ vector<double> times; /** * @brief The last start time of this region. */ double start; /** * @brief User-defined callback function to compute a region's performance. */ ghost_compute_performance_func_t perfFunc; /** * @brief Argument to perfFunc. */ void *perfFuncArg; /** * @brief The unit of performance. */ const char *perfUnit; } ghost_timing_region_accu_t; static map<string,ghost_timing_region_accu_t> timings; void ghost_timing_tick(const char *tag) { double start = 0.; ghost_timing_wc(&start); timings[tag].start = start; } void ghost_timing_tock(const char *tag) { double end; ghost_timing_wc(&end); ghost_timing_region_accu_t *ti = &timings[string(tag)]; ti->times.push_back(end-ti->start); } void ghost_timing_set_perfFunc(const char *tag, ghost_compute_performance_func_t func, void *arg, const char *unit) { timings[tag].perfFunc = func; timings[tag].perfFuncArg = arg; timings[tag].perfUnit = unit; } ghost_error_t ghost_timing_region_create(ghost_timing_region_t ** ri, const char *tag) { ghost_timing_region_accu_t ti = timings[string(tag)]; if (!ti.times.size()) { ERROR_LOG("The region %s does not exist!",tag); return GHOST_ERR_INVALID_ARG; } ghost_error_t ret = GHOST_SUCCESS; GHOST_CALL_GOTO(ghost_malloc((void **)ri,sizeof(ghost_timing_region_t)),err,ret); (*ri)->nCalls = ti.times.size(); (*ri)->minTime = *min_element(ti.times.begin(),ti.times.end()); (*ri)->maxTime = *max_element(ti.times.begin(),ti.times.end()); (*ri)->accTime = accumulate(ti.times.begin(),ti.times.end(),0.); (*ri)->avgTime = (*ri)->accTime/(*ri)->nCalls; GHOST_CALL_GOTO(ghost_malloc((void **)(&((*ri)->times)),sizeof(double)*(*ri)->nCalls),err,ret); memcpy((*ri)->times,&ti.times[0],(*ri)->nCalls*sizeof(double)); goto out; err: ERROR_LOG("Freeing region info"); if (*ri) { free((*ri)->times); (*ri)->times = NULL; } free(*ri); (*ri) = NULL; out: return ret; } void ghost_timing_region_destroy(ghost_timing_region_t * ri) { if (ri) { free(ri->times); ri->times = NULL; } free(ri); } ghost_error_t ghost_timing_summarystring(char **str) { stringstream buffer; map<string,ghost_timing_region_accu_t>::iterator iter; size_t maxRegionLen = 0; size_t maxCallsLen = 0; size_t maxUnitLen = 0; stringstream tmp; for (iter = timings.begin(); iter != timings.end(); ++iter) { int regLen = 0; if (iter->second.perfUnit) { tmp << iter->first.length(); maxUnitLen = max(strlen(iter->second.perfUnit),maxUnitLen); regLen = strlen(iter->second.perfUnit); tmp.str(""); } tmp << regLen+iter->first.length(); maxRegionLen = max(regLen+iter->first.length(),maxRegionLen); tmp.str(""); tmp << iter->second.times.size(); maxCallsLen = max(maxCallsLen,tmp.str().length()); tmp.str(""); } if (maxCallsLen < 5) { maxCallsLen = 5; } buffer << left << setw(maxRegionLen+4) << "Region" << right << " | "; buffer << setw(maxCallsLen+3) << "Calls | "; buffer << " t_min | "; buffer << " t_max | "; buffer << " t_avg | "; buffer << " t_acc" << endl; buffer << string(maxRegionLen+maxCallsLen+7+4*11,'-') << endl; buffer.precision(2); for (iter = timings.begin(); iter != timings.end(); ++iter) { ghost_timing_region_t *region = NULL; ghost_timing_region_create(&region,iter->first.c_str()); if (region) { buffer << scientific << left << setw(maxRegionLen+4) << iter->first << " | " << right << setw(maxCallsLen) << region->nCalls << " | " << region->minTime << " | " << region->maxTime << " | " << region->avgTime << " | " << region->accTime << endl; ghost_timing_region_destroy(region); } } int printed = 0; buffer.precision(2); for (iter = timings.begin(); iter != timings.end(); ++iter) { ghost_compute_performance_func_t pf = iter->second.perfFunc; if (!pf) { continue; } if (!printed) { buffer << endl << endl << left << setw(maxRegionLen+4) << "Region" << right << " | "; buffer << setw(maxCallsLen+3) << "Calls | "; buffer << " P_max | "; buffer << " P_min | "; buffer << " P_avg | "; buffer << "P_skip10" << endl;; buffer << string(maxRegionLen+maxCallsLen+7+4*11,'-') << endl; } printed = 1; ghost_timing_region_t *region = NULL; ghost_timing_region_create(&region,iter->first.c_str()); if (region) { void *pfa = iter->second.perfFuncArg; double P_min = 0., P_max = 0., P_avg = 0., P_skip10 = 0.; int err = pf(&P_min,region->maxTime,pfa); if (err) { ERROR_LOG("Error in calling performance computation callback!"); } err = pf(&P_max,region->minTime,pfa); if (err) { ERROR_LOG("Error in calling performance computation callback!"); } err = pf(&P_avg,region->avgTime,pfa); if (err) { ERROR_LOG("Error in calling performance computation callback!"); } if (region->nCalls > 10) { err = pf(&P_skip10,accumulate(iter->second.times.begin()+10,iter->second.times.end(),0.)/(region->nCalls-10),pfa); if (err) { ERROR_LOG("Error in calling performance computation callback!"); } } buffer << scientific << left << setw(maxRegionLen-maxUnitLen+2) << iter->first << right << "(" << setw(maxUnitLen) << iter->second.perfUnit << ")" << " | " << setw(maxCallsLen) << region->nCalls << " | " << P_max << " | " << P_min << " | " << P_avg << " | " << P_skip10 << endl; ghost_timing_region_destroy(region); } } GHOST_CALL_RETURN(ghost_malloc((void **)str,buffer.str().length()+1)); strcpy(*str,buffer.str().c_str()); return GHOST_SUCCESS; } <commit_msg>there can be more than one performance functions per region now<commit_after>#include "ghost/timing.h" #include "ghost/util.h" #include <map> #include <vector> #include <sstream> #include <iostream> #include <iomanip> #include <numeric> #include <algorithm> using namespace std; typedef struct { /** * @brief User-defined callback function to compute a region's performance. */ ghost_compute_performance_func_t perfFunc; /** * @brief Argument to perfFunc. */ void *perfFuncArg; /** * @brief The unit of performance. */ const char *perfUnit; } ghost_timing_perfFunc_t; /** * @brief Region timing accumulator */ typedef struct { /** * @brief The runtimes of this region. */ vector<double> times; /** * @brief The last start time of this region. */ double start; vector<ghost_timing_perfFunc_t> perfFuncs; } ghost_timing_region_accu_t; static map<string,ghost_timing_region_accu_t> timings; void ghost_timing_tick(const char *tag) { double start = 0.; ghost_timing_wc(&start); timings[tag].start = start; } void ghost_timing_tock(const char *tag) { double end; ghost_timing_wc(&end); ghost_timing_region_accu_t *ti = &timings[string(tag)]; ti->times.push_back(end-ti->start); } void ghost_timing_set_perfFunc(const char *tag, ghost_compute_performance_func_t func, void *arg, const char *unit) { ghost_timing_perfFunc_t pf; pf.perfFunc = func; pf.perfFuncArg = arg; pf.perfUnit = unit; timings[tag].perfFuncs.push_back(pf); } ghost_error_t ghost_timing_region_create(ghost_timing_region_t ** ri, const char *tag) { ghost_timing_region_accu_t ti = timings[string(tag)]; if (!ti.times.size()) { ERROR_LOG("The region %s does not exist!",tag); return GHOST_ERR_INVALID_ARG; } ghost_error_t ret = GHOST_SUCCESS; GHOST_CALL_GOTO(ghost_malloc((void **)ri,sizeof(ghost_timing_region_t)),err,ret); (*ri)->nCalls = ti.times.size(); (*ri)->minTime = *min_element(ti.times.begin(),ti.times.end()); (*ri)->maxTime = *max_element(ti.times.begin(),ti.times.end()); (*ri)->accTime = accumulate(ti.times.begin(),ti.times.end(),0.); (*ri)->avgTime = (*ri)->accTime/(*ri)->nCalls; GHOST_CALL_GOTO(ghost_malloc((void **)(&((*ri)->times)),sizeof(double)*(*ri)->nCalls),err,ret); memcpy((*ri)->times,&ti.times[0],(*ri)->nCalls*sizeof(double)); goto out; err: ERROR_LOG("Freeing region info"); if (*ri) { free((*ri)->times); (*ri)->times = NULL; } free(*ri); (*ri) = NULL; out: return ret; } void ghost_timing_region_destroy(ghost_timing_region_t * ri) { if (ri) { free(ri->times); ri->times = NULL; } free(ri); } ghost_error_t ghost_timing_summarystring(char **str) { stringstream buffer; map<string,ghost_timing_region_accu_t>::iterator iter; vector<ghost_timing_perfFunc_t>::iterator pf_iter; size_t maxRegionLen = 0; size_t maxCallsLen = 0; size_t maxUnitLen = 0; stringstream tmp; for (iter = timings.begin(); iter != timings.end(); ++iter) { int regLen = 0; for (pf_iter = iter->second.perfFuncs.begin(); pf_iter != iter->second.perfFuncs.end(); ++pf_iter) { if (pf_iter->perfUnit) { tmp << iter->first.length(); maxUnitLen = max(strlen(pf_iter->perfUnit),maxUnitLen); regLen = strlen(pf_iter->perfUnit); tmp.str(""); } } tmp << regLen+iter->first.length(); maxRegionLen = max(regLen+iter->first.length(),maxRegionLen); tmp.str(""); tmp << iter->second.times.size(); maxCallsLen = max(maxCallsLen,tmp.str().length()); tmp.str(""); } if (maxCallsLen < 5) { maxCallsLen = 5; } buffer << left << setw(maxRegionLen+4) << "Region" << right << " | "; buffer << setw(maxCallsLen+3) << "Calls | "; buffer << " t_min | "; buffer << " t_max | "; buffer << " t_avg | "; buffer << " t_acc" << endl; buffer << string(maxRegionLen+maxCallsLen+7+4*11,'-') << endl; buffer.precision(2); for (iter = timings.begin(); iter != timings.end(); ++iter) { ghost_timing_region_t *region = NULL; ghost_timing_region_create(&region,iter->first.c_str()); if (region) { buffer << scientific << left << setw(maxRegionLen+4) << iter->first << " | " << right << setw(maxCallsLen) << region->nCalls << " | " << region->minTime << " | " << region->maxTime << " | " << region->avgTime << " | " << region->accTime << endl; ghost_timing_region_destroy(region); } } int printed = 0; buffer.precision(2); for (iter = timings.begin(); iter != timings.end(); ++iter) { if (!printed) { buffer << endl << endl << left << setw(maxRegionLen+4) << "Region" << right << " | "; buffer << setw(maxCallsLen+3) << "Calls | "; buffer << " P_max | "; buffer << " P_min | "; buffer << " P_avg | "; buffer << "P_skip10" << endl;; buffer << string(maxRegionLen+maxCallsLen+7+4*11,'-') << endl; } printed = 1; ghost_timing_region_t *region = NULL; ghost_timing_region_create(&region,iter->first.c_str()); if (region) { for (pf_iter = iter->second.perfFuncs.begin(); pf_iter != iter->second.perfFuncs.end(); ++pf_iter) { ghost_compute_performance_func_t pf = pf_iter->perfFunc; void *pfa = pf_iter->perfFuncArg; double P_min = 0., P_max = 0., P_avg = 0., P_skip10 = 0.; int err = pf(&P_min,region->maxTime,pfa); if (err) { ERROR_LOG("Error in calling performance computation callback!"); } err = pf(&P_max,region->minTime,pfa); if (err) { ERROR_LOG("Error in calling performance computation callback!"); } err = pf(&P_avg,region->avgTime,pfa); if (err) { ERROR_LOG("Error in calling performance computation callback!"); } if (region->nCalls > 10) { err = pf(&P_skip10,accumulate(iter->second.times.begin()+10,iter->second.times.end(),0.)/(region->nCalls-10),pfa); if (err) { ERROR_LOG("Error in calling performance computation callback!"); } } buffer << scientific << left << setw(maxRegionLen-maxUnitLen+2) << iter->first << right << "(" << setw(maxUnitLen) << pf_iter->perfUnit << ")" << " | " << setw(maxCallsLen) << region->nCalls << " | " << P_max << " | " << P_min << " | " << P_avg << " | " << P_skip10 << endl; } ghost_timing_region_destroy(region); } } GHOST_CALL_RETURN(ghost_malloc((void **)str,buffer.str().length()+1)); strcpy(*str,buffer.str().c_str()); return GHOST_SUCCESS; } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <fstream> #include <vector> using namespace std; int main(int argc, char **argv) { string in_string, var_name; vector <string> names; int ctr=1, next_comma=0, len=0, start=0, file_ctr=0; vector <string> files; ifstream infile2; string filename(argv[1]), new_filename; char num[4]; if (filename.find("#") != string::npos) { // if plotting multiple files while (file_ctr<10) { new_filename=filename; sprintf(num,"%d",file_ctr); new_filename.replace(new_filename.find("#"),1,num); infile2.open(new_filename.c_str()); if (!infile2.is_open()) break; infile2.close(); files.push_back(new_filename); file_ctr++; } } else { files.push_back(filename); } ifstream infile(files[0].c_str()); if (!infile.is_open()) { cerr << "Could not open file: " << files[0] << endl; exit(-1); } getline(infile, in_string, '\n'); cout << "set terminal postscript color \"Helvetica,12\"" << endl; if (argc >= 3) { cout << "set title \"" << argv[2] << "\" font \"Helvetica,12\"" << endl; } cout << "set output '" << files[0].substr(0,files[0].size()-4) << ".ps'" << endl; cout << "set lmargin 6" << endl; cout << "set rmargin 4" << endl; cout << "set tmargin 1" << endl; cout << "set bmargin 1" << endl; cout << "set datafile separator \",\"" << endl; cout << "set grid xtics ytics" << endl; cout << "set xtics font \"Helvetica,8\"" << endl; cout << "set ytics font \"Helvetica,8\"" << endl; cout << "set timestamp \"%d/%m/%y %H:%M\" 0,0 \"Helvetica,8\"" << endl; while(next_comma != string::npos) { next_comma=in_string.find_first_of(",",start); if (next_comma == string::npos) { var_name=in_string.substr(start); } else { len = next_comma-start; var_name=in_string.substr(start,len); } var_name.erase(0,var_name.find_first_not_of(" ")); names.push_back(var_name); start = next_comma+1; ctr++; } unsigned int num_names=names.size(); for (int i=1;i<num_names;i++) { if ( i <= num_names-3 && names[i].find("_X") != string::npos && names[i+1].find("_Y") != string::npos && names[i+2].find("_Z") != string::npos ) { // XYZ value if (argc >= 3) { cout << "set title \"" << argv[2] << "\\n" << names[i] << " vs. Time\" font \"Helvetica,12\"" << endl; } cout << "set multiplot" << endl; cout << "set size 1.0,0.3" << endl; if (files.size()==1) { // Single file cout << "set origin 0.0,0.66" << endl; cout << "set xlabel \"\"" << endl; cout << "set ylabel \"" << names[i] << "\" font \"Helvetica,10\"" << endl; cout << "set timestamp \"\"" << endl; cout << "plot \"" << files[0] << "\" using 1:" << i+1 << " with lines" << " title " << "\"" << names[i] << "\"" << endl; cout << "set origin 0.0,0.33" << endl; cout << "set title \"\"" << endl; cout << "set ylabel \"" << names[i+1] << "\" font \"Helvetica,10\"" << endl; cout << "plot \"" << files[0] << "\" using 1:" << i+2 << " with lines" << " title " << "\"" << names[i+1] << "\"" << endl; cout << "set origin 0.0,0.034" << endl; cout << "set xlabel \"Time (sec)\" font \"Helvetica,10\"" << endl; cout << "set ylabel \"" << names[i+2] << "\" font \"Helvetica,10\"" << endl; cout << "set timestamp \"%d/%m/%y %H:%M\" 0,0 \"Helvetica,8\"" << endl; cout << "plot \"" << files[0] << "\" using 1:" << i+3 << " with lines" << " title " << "\"" << names[i+2] << "\"" << endl; } else { // Multiple files, multiple plots per page // Plot 1 (top) X cout << "set origin 0.0,0.66" << endl; cout << "set xlabel \"\"" << endl; cout << "set ylabel \"" << names[i] << "\" font \"Helvetica,10\"" << endl; cout << "set timestamp \"\"" << endl; cout << "plot \"" << files[0] << "\" using 1:" << i+1 << " with lines" << " title " << "\"" << names[i] << "\",\\" << endl; for (int f=1;f<files.size()-2;f++){ cout << "\"" << files[f] << "\" using 1:" << i+1 << " with lines" << " title " << "\"" << names[i] << "\",\\" << endl; } cout << "\"" << files[files.size()-1] << "\" using 1:" << i+1 << " with lines" << " title " << "\"" << names[i] << "\"" << endl; // Plot 2 (middle) Y cout << "set origin 0.0,0.33" << endl; cout << "set title \"\"" << endl; cout << "set ylabel \"" << names[i+1] << "\" font \"Helvetica,10\"" << endl; cout << "plot \"" << files[0] << "\" using 1:" << i+2 << " with lines" << " title " << "\"" << names[i+1] << "\",\\" << endl; for (int f=1;f<files.size()-2;f++){ cout << "\"" << files[f] << "\" using 1:" << i+2 << " with lines" << " title " << "\"" << names[i+1] << "\",\\" << endl; } cout << "\"" << files[files.size()-1] << "\" using 1:" << i+2 << " with lines" << " title " << "\"" << names[i+1] << "\"" << endl; // Plot 3 (bottom) Z cout << "set origin 0.0,0.034" << endl; cout << "set xlabel \"Time (sec)\" font \"Helvetica,10\"" << endl; cout << "set ylabel \"" << names[i+2] << "\" font \"Helvetica,10\"" << endl; cout << "set timestamp \"%d/%m/%y %H:%M\" 0,0 \"Helvetica,8\"" << endl; cout << "plot \"" << files[0] << "\" using 1:" << i+3 << " with lines" << " title " << "\"" << names[i+2] << "\",\\" << endl; for (int f=1;f<files.size()-2;f++){ cout << "\"" << files[f] << "\" using 1:" << i+3 << " with lines" << " title " << "\"" << names[i+2] << "\",\\" << endl; } cout << "\"" << files[files.size()-1] << "\" using 1:" << i+3 << " with lines" << " title " << "\"" << names[i+2] << "\"" << endl; } i += 3; cout << "unset multiplot" << endl; cout << "set size -1.0,-1.0" << endl; cout << "set offset -0.0,-0.0" << endl; } else { // Straight single value to plot if (argc >= 3) { // title added cout << "set title \"" << argv[2] << "\\n" << names[i] << " vs. Time\" font \"Helvetica,12\"" << endl; } cout << "set xlabel \"Time (sec)\" font \"Helvetica,10\"" << endl; cout << "set ylabel \"" << names[i] << "\" font \"Helvetica,10\"" << endl; if (files.size()==1) { // Single file cout << "plot \"" << files[0] << "\" using 1:" << i+1 << " with lines" << " title " << "\"" << names[i] << "\"" << endl; } else { // Multiple files cout << "plot \"" << files[0] << "\" using 1:" << i+1 << " with lines" << " title " << "\"" << names[i] << "\",\\" << endl; for (int f=1;f<files.size()-2;f++){ cout << "\"" << files[f] << "\" using 1:" << i+1 << " with lines" << " title " << "\"" << names[i] << "\",\\" << endl; } cout << "\"" << files[files.size()-1] << "\" using 1:" << i+1 << " with lines" << " title " << "\"" << names[i] << "\"" << endl; } } } } <commit_msg>A few changes/fixes<commit_after>#include <iostream> #include <string> #include <fstream> #include <vector> using namespace std; int main(int argc, char **argv) { string in_string, var_name; vector <string> names; int ctr=1, next_comma=0, len=0, start=0, file_ctr=0; vector <string> files; ifstream infile2; string filename(argv[1]), new_filename; char num[4]; if (filename.find("#") != string::npos) { // if plotting multiple files while (file_ctr<10) { new_filename=filename; sprintf(num,"%d",file_ctr); new_filename.replace(new_filename.find("#"),1,num); infile2.open(new_filename.c_str()); if (!infile2.is_open()) break; infile2.close(); files.push_back(new_filename); file_ctr++; } } else { files.push_back(filename); } ifstream infile(files[0].c_str()); if (!infile.is_open()) { cerr << "Could not open file: " << files[0] << endl; exit(-1); } getline(infile, in_string, '\n'); cout << "set terminal postscript color \"Helvetica,12\"" << endl; if (argc >= 3) { cout << "set title \"" << argv[2] << "\" font \"Helvetica,12\"" << endl; } cout << "set output '" << files[0].substr(0,files[0].size()-4) << ".ps'" << endl; cout << "set lmargin 6" << endl; cout << "set rmargin 4" << endl; cout << "set tmargin 1" << endl; cout << "set bmargin 1" << endl; cout << "set datafile separator \",\"" << endl; cout << "set grid xtics ytics" << endl; cout << "set xtics font \"Helvetica,8\"" << endl; cout << "set ytics font \"Helvetica,8\"" << endl; cout << "set timestamp \"%d/%m/%y %H:%M\" 0,0 \"Helvetica,8\"" << endl; while(next_comma != string::npos) { next_comma=in_string.find_first_of(",",start); if (next_comma == string::npos) { var_name=in_string.substr(start); } else { len = next_comma-start; var_name=in_string.substr(start,len); } var_name.erase(0,var_name.find_first_not_of(" ")); names.push_back(var_name); start = next_comma+1; ctr++; } unsigned int num_names=names.size(); for (int i=1;i<num_names;i++) { if ( i <= num_names-3 && names[i].find("_X") != string::npos && names[i+1].find("_Y") != string::npos && names[i+2].find("_Z") != string::npos ) { // XYZ value if (argc >= 3) { cout << "set title \"" << argv[2] << "\\n" << names[i] << " vs. Time\" font \"Helvetica,12\"" << endl; } cout << "set multiplot" << endl; cout << "set size 1.0,0.3" << endl; if (files.size()==1) { // Single file cout << "set origin 0.0,0.66" << endl; cout << "set xlabel \"\"" << endl; cout << "set ylabel \"" << names[i] << "\" font \"Helvetica,10\"" << endl; cout << "set timestamp \"\"" << endl; cout << "plot \"" << files[0] << "\" using 1:" << i+1 << " with lines" << " title " << "\"" << names[i] << "\"" << endl; cout << "set origin 0.0,0.33" << endl; cout << "set title \"\"" << endl; cout << "set ylabel \"" << names[i+1] << "\" font \"Helvetica,10\"" << endl; cout << "plot \"" << files[0] << "\" using 1:" << i+2 << " with lines" << " title " << "\"" << names[i+1] << "\"" << endl; cout << "set origin 0.0,0.034" << endl; cout << "set xlabel \"Time (sec)\" font \"Helvetica,10\"" << endl; cout << "set ylabel \"" << names[i+2] << "\" font \"Helvetica,10\"" << endl; cout << "set timestamp \"%d/%m/%y %H:%M\" 0,0 \"Helvetica,8\"" << endl; cout << "plot \"" << files[0] << "\" using 1:" << i+3 << " with lines" << " title " << "\"" << names[i+2] << "\"" << endl; } else { // Multiple files, multiple plots per page // Plot 1 (top) X cout << "set origin 0.0,0.66" << endl; cout << "set xlabel \"\"" << endl; cout << "set ylabel \"" << names[i] << "\" font \"Helvetica,10\"" << endl; cout << "set timestamp \"\"" << endl; cout << "plot \"" << files[0] << "\" using 1:" << i+1 << " with lines" << " title " << "\"" << names[i] << ": 1" << "\",\\" << endl; for (int f=1;f<files.size()-2;f++){ cout << "\"" << files[f] << "\" using 1:" << i+1 << " with lines" << " title " << "\"" << names[i] << ": " << f+1 << "\",\\" << endl; } cout << "\"" << files[files.size()-1] << "\" using 1:" << i+1 << " with lines" << " title " << "\"" << names[i] << ": " << files.size() << "\"" << endl; // Plot 2 (middle) Y cout << "set origin 0.0,0.33" << endl; cout << "set title \"\"" << endl; cout << "set ylabel \"" << names[i+1] << "\" font \"Helvetica,10\"" << endl; cout << "plot \"" << files[0] << "\" using 1:" << i+2 << " with lines" << " title " << "\"" << names[i+1] << ": 1" << "\",\\" << endl; for (int f=1;f<files.size()-2;f++){ cout << "\"" << files[f] << "\" using 1:" << i+2 << " with lines" << " title " << "\"" << names[i+1] << ": " << f+1 << "\",\\" << endl; } cout << "\"" << files[files.size()-1] << "\" using 1:" << i+2 << " with lines" << " title " << "\"" << names[i+1] << ": " << files.size() << "\"" << endl; // Plot 3 (bottom) Z cout << "set origin 0.0,0.034" << endl; cout << "set xlabel \"Time (sec)\" font \"Helvetica,10\"" << endl; cout << "set ylabel \"" << names[i+2] << "\" font \"Helvetica,10\"" << endl; cout << "set timestamp \"%d/%m/%y %H:%M\" 0,0 \"Helvetica,8\"" << endl; cout << "plot \"" << files[0] << "\" using 1:" << i+3 << " with lines" << " title " << "\"" << names[i+2] << ": 1" << "\",\\" << endl; for (int f=1;f<files.size()-2;f++){ cout << "\"" << files[f] << "\" using 1:" << i+3 << " with lines" << " title " << "\"" << names[i+2] << ": " << f+1 << "\",\\" << endl; } cout << "\"" << files[files.size()-1] << "\" using 1:" << i+3 << " with lines" << " title " << "\"" << names[i+2] << ": " << files.size() << "\"" << endl; } i += 3; cout << "unset multiplot" << endl; cout << "set size 1.0,1.0" << endl; cout << "set offset 0.0,0.0" << endl; } else { // Straight single value to plot if (argc >= 3) { // title added cout << "set title \"" << argv[2] << "\\n" << names[i] << " vs. Time\" font \"Helvetica,12\"" << endl; } cout << "set xlabel \"Time (sec)\" font \"Helvetica,10\"" << endl; cout << "set ylabel \"" << names[i] << "\" font \"Helvetica,10\"" << endl; if (files.size()==1) { // Single file cout << "plot \"" << files[0] << "\" using 1:" << i+1 << " with lines" << " title " << "\"" << names[i] << "\"" << endl; } else { // Multiple files cout << "plot \"" << files[0] << "\" using 1:" << i+1 << " with lines" << " title " << "\"" << names[i] << ": 1" << "\",\\" << endl; for (int f=1;f<files.size()-2;f++){ cout << "\"" << files[f] << "\" using 1:" << i+1 << " with lines" << " title " << "\"" << names[i] << ": " << f+1 << "\",\\" << endl; } cout << "\"" << files[files.size()-1] << "\" using 1:" << i+1 << " with lines" << " title " << "\"" << names[i] << ": " << files.size() << "\"" << endl; } } } } <|endoftext|>
<commit_before>/* -*- C++ -*- */ /************************************************************************* * Copyright(c) 1995~2005 Masaharu Goto (cint@pcroot.cern.ch) * * For the licensing terms see the file COPYING * ************************************************************************/ #include <iostream> #include <fstream> using namespace std; #define TEST int main() { char *filename = "t1126.cxx"; char curr[200]; ifstream indat; indat.open(filename, ios_base::in); if(!indat.good()) { cerr << "File open problem" << endl; } #ifdef TEST long locate0 = 0; #else streampos locate0 = 0; #endif indat.seekg(locate0); locate0 = indat.tellg(); cout << "locate0 : " << locate0 << endl; indat.read(curr, 30); curr[30] = 0; cout << curr << endl; #ifdef TEST long locate1 = 0; #else streampos locate1 = 0; #endif locate1 = indat.tellg(); cout << "locate1 : " << locate1 << endl; #ifdef TEST long locate2 = 0; #else streampos locate2 = 0; #endif indat.seekg(0,ios_base::end); locate2 = indat.tellg(); cout << "locate2 : " << locate2 << endl; indat.close(); return 0; } <commit_msg>Fix usage of string constant.<commit_after>/* -*- C++ -*- */ /************************************************************************* * Copyright(c) 1995~2005 Masaharu Goto (cint@pcroot.cern.ch) * * For the licensing terms see the file COPYING * ************************************************************************/ #include <iostream> #include <fstream> using namespace std; #define TEST int main() { const char* filename = "t1126.cxx"; char curr[200]; ifstream indat; indat.open(filename, ios_base::in); if (!indat.good()) { cerr << "File open problem" << endl; } #ifdef TEST long locate0 = 0; #else // TEST streampos locate0 = 0; #endif // TEST indat.seekg(locate0); locate0 = indat.tellg(); cout << "locate0 : " << locate0 << endl; indat.read(curr, 30); curr[30] = 0; cout << curr << endl; #ifdef TEST long locate1 = 0; #else // TEST streampos locate1 = 0; #endif // TEST locate1 = indat.tellg(); cout << "locate1 : " << locate1 << endl; #ifdef TEST long locate2 = 0; #else // TEST streampos locate2 = 0; #endif // TEST indat.seekg(0, ios_base::end); locate2 = indat.tellg(); cout << "locate2 : " << locate2 << endl; indat.close(); return 0; } <|endoftext|>
<commit_before>#include <SDL.h> #include <stdexcept> #include <string> #include <sstream> #include <iostream> #include "window.h" #include "timer.h" int main(int argc, char** argv){ //Start our window try { Window::Init("Lesson 8"); } catch (const std::runtime_error &e){ std::cout << e.what() << std::endl; Window::Quit(); return -1; } //Our timer: Timer timer; //Textures to display a message and ticks elapsed SDL_Texture *msg = nullptr, *ticks = nullptr; //Color for the text SDL_Color white = { 255, 255, 255 }; //Rects for the text SDL_Rect msgBox, ticksBox; //Setup msg text msg = Window::RenderText("Ticks Elapsed: ", "../res/Lesson8/SourceSansPro-Regular.ttf", white, 30); //Setup msg dstRect msgBox.x = 0; msgBox.y = Window::Box().h / 2; //Query w & h from texture SDL_QueryTexture(msg, NULL, NULL, &msgBox.w, &msgBox.h); //Setup ticks message //We must use a stringstream to convert int to string std::stringstream ssTicks; ssTicks << timer.Ticks(); ticks = Window::RenderText(ssTicks.str(), "../res/Lesson8/SourceSansPro-Regular.ttf", white, 30); //clear the stream ssTicks.str(""); //Setup the ticks dstRect ticksBox.x = msgBox.w + 20; ticksBox.y = Window::Box().h / 2; SDL_QueryTexture(ticks, NULL, NULL, &ticksBox.w, &ticksBox.h); //Our event structure SDL_Event e; //For tracking if we want to quit bool quit = false; while (!quit){ //Event Polling while (SDL_PollEvent(&e)){ //If user closes he window if (e.type == SDL_QUIT) quit = true; //If user presses any key if (e.type == SDL_KEYDOWN){ switch (e.key.keysym.sym){ //Start/stop the timer case SDLK_s: //If timer was running, stop it if (timer.Started()) timer.Stop(); else timer.Start(); break; case SDLK_p: if (timer.Paused()) timer.Unpause(); else timer.Pause(); break; //For quitting, escape key case SDLK_ESCAPE: quit = true; break; default: break; } } } //LOGIC //If the timer is running, update the ticks message if (timer.Started() && !timer.Paused()){ //Update text ssTicks << timer.Ticks(); SDL_DestroyTexture(ticks); ticks = Window::RenderText(ssTicks.str(), "../res/Lesson8/SourceSansPro-Regular.ttf", white, 30); ssTicks.str(""); //Update w/h SDL_QueryTexture(ticks, NULL, NULL, &ticksBox.w, &ticksBox.h); } //RENDERING Window::Clear(); Window::Draw(msg, msgBox); Window::Draw(ticks, ticksBox); Window::Present(); } Window::Quit(); return 0; }<commit_msg>some formatting tweaks<commit_after>#include <SDL.h> #include <stdexcept> #include <string> #include <sstream> #include <iostream> #include "window.h" #include "timer.h" int main(int argc, char** argv){ //Start our window try { Window::Init("Lesson 8"); } catch (const std::runtime_error &e){ std::cout << e.what() << std::endl; Window::Quit(); return -1; } //Our timer: Timer timer; //Textures to display a message and ticks elapsed SDL_Texture *msg = nullptr, *ticks = nullptr; //Color for the text SDL_Color white = { 255, 255, 255 }; //Rects for the text SDL_Rect msgBox, ticksBox; //Setup msg text msg = Window::RenderText("Ticks Elapsed: ", "../res/Lesson8/SourceSansPro-Regular.ttf", white, 30); //Setup msg dstRect msgBox.x = 0; msgBox.y = Window::Box().h / 2; //Query w & h from texture SDL_QueryTexture(msg, NULL, NULL, &msgBox.w, &msgBox.h); //Setup ticks message //We must use a stringstream to convert int to string std::stringstream ssTicks; ssTicks << timer.Ticks(); ticks = Window::RenderText(ssTicks.str(), "../res/Lesson8/SourceSansPro-Regular.ttf", white, 30); //clear the stream ssTicks.str(""); //Setup the ticks dstRect ticksBox.x = msgBox.w + 20; ticksBox.y = Window::Box().h / 2; SDL_QueryTexture(ticks, NULL, NULL, &ticksBox.w, &ticksBox.h); //Our event structure SDL_Event e; //For tracking if we want to quit bool quit = false; while (!quit){ //Event Polling while (SDL_PollEvent(&e)){ //If user closes he window if (e.type == SDL_QUIT) quit = true; //If user presses any key if (e.type == SDL_KEYDOWN){ switch (e.key.keysym.sym){ //Start/stop the timer case SDLK_s: //If timer was running, stop it if (timer.Started()) timer.Stop(); else timer.Start(); break; case SDLK_p: if (timer.Paused()) timer.Unpause(); else timer.Pause(); break; //For quitting, escape key case SDLK_ESCAPE: quit = true; break; default: break; } } } //LOGIC //If the timer is running, update the ticks message if (timer.Started() && !timer.Paused()){ //Update text ssTicks << timer.Ticks(); SDL_DestroyTexture(ticks); ticks = Window::RenderText(ssTicks.str(), "../res/Lesson8/SourceSansPro-Regular.ttf", white, 30); ssTicks.str(""); //Update w/h SDL_QueryTexture(ticks, NULL, NULL, &ticksBox.w, &ticksBox.h); } //RENDERING Window::Clear(); Window::Draw(msg, msgBox); Window::Draw(ticks, ticksBox); Window::Present(); } Window::Quit(); return 0; }<|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ReportEngineJFree.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef REPORTDESIGN_API_REPORTENGINEJFREE_HXX #define REPORTDESIGN_API_REPORTENGINEJFREE_HXX #include <com/sun/star/report/XReportEngine.hpp> #include <cppuhelper/compbase2.hxx> #include <comphelper/broadcasthelper.hxx> #include <comphelper/uno3.hxx> #include <comphelper/types.hxx> #include <cppuhelper/propertysetmixin.hxx> #include <com/sun/star/uno/XComponentContext.hpp> #include <com/sun/star/sdbc/XRowSet.hpp> #include <comphelper/stl_types.hxx> #include <comphelper/implementationreference.hxx> #include <com/sun/star/lang/XServiceInfo.hpp> namespace reportdesign { typedef ::cppu::WeakComponentImplHelper2< com::sun::star::report::XReportEngine ,com::sun::star::lang::XServiceInfo> ReportEngineBase; typedef ::cppu::PropertySetMixin<com::sun::star::report::XReportEngine> ReportEnginePropertySet; class OReportEngineJFree : public comphelper::OMutexAndBroadcastHelper, public ReportEngineBase, public ReportEnginePropertySet { typedef ::std::multimap< ::rtl::OUString, ::com::sun::star::uno::Any , ::comphelper::UStringMixLess> TComponentMap; ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext; ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportDefinition > m_xReport; ::com::sun::star::uno::Reference< ::com::sun::star::task::XStatusIndicator> m_StatusIndicator; ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > m_xActiveConnection; private: OReportEngineJFree(const OReportEngineJFree&); OReportEngineJFree& operator=(const OReportEngineJFree&); template <typename T> void set( const ::rtl::OUString& _sProperty ,const T& _Value ,T& _member) { BoundListeners l; { ::osl::MutexGuard aGuard(m_aMutex); prepareSet(_sProperty, ::com::sun::star::uno::makeAny(_member), ::com::sun::star::uno::makeAny(_Value), &l); _member = _Value; } l.notify(); } /** transform the report defintion format into a jfree report format. * * \return The URL of the newly created file. */ ::rtl::OUString transform(); /** returns the file url for a new model * * \return The new file url. */ ::rtl::OUString getNewOutputName(); /** generates the order statement defined by the groups of the report * * \return the ORDER BY part */ ::rtl::OUString getOrderStatement() const; protected: // TODO: VirtualFunctionFinder: This is virtual function! // virtual ~OReportEngineJFree(); public: typedef ::comphelper::ImplementationReference< OReportEngineJFree ,::com::sun::star::report::XReportEngine,::com::sun::star::uno::XWeak > TReportEngine; OReportEngineJFree(const com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext >& context); DECLARE_XINTERFACE( ) // ::com::sun::star::lang::XServiceInfo virtual ::sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException); static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( ::com::sun::star::uno::RuntimeException ); static ::rtl::OUString getImplementationName_Static(void) throw( ::com::sun::star::uno::RuntimeException ); static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL create(::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > const & xContext); // com::sun::star::beans::XPropertySet virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XReportEngine // Attributes virtual ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportDefinition > SAL_CALL getReportDefinition() throw (::com::sun::star::uno::RuntimeException) ; virtual void SAL_CALL setReportDefinition( const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportDefinition >& _reportdefinition ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL getActiveConnection() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setActiveConnection( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _activeconnection ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::task::XStatusIndicator > SAL_CALL getStatusIndicator() throw (::com::sun::star::uno::RuntimeException) ; virtual void SAL_CALL setStatusIndicator( const ::com::sun::star::uno::Reference< ::com::sun::star::task::XStatusIndicator >& _statusindicator ) throw (::com::sun::star::uno::RuntimeException) ; // Methods virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > SAL_CALL createDocumentModel( ) throw (::com::sun::star::lang::DisposedException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException) ; virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > SAL_CALL createDocumentAlive( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& _frame ) throw (::com::sun::star::lang::DisposedException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException) ; virtual ::com::sun::star::util::URL SAL_CALL createDocument( ) throw (::com::sun::star::lang::DisposedException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException) ; virtual void SAL_CALL interrupt( ) throw (::com::sun::star::lang::DisposedException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException) ; // XComponent virtual void SAL_CALL dispose() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addEventListener(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener > & aListener) throw(::com::sun::star::uno::RuntimeException) { cppu::WeakComponentImplHelperBase::addEventListener(aListener); } virtual void SAL_CALL removeEventListener(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener > & aListener) throw(::com::sun::star::uno::RuntimeException) { cppu::WeakComponentImplHelperBase::removeEventListener(aListener); } }; } #endif //REPORTDESIGN_API_REPORTENGINEJFREE_HXX <commit_msg>INTEGRATION: CWS rptchart02 (1.3.4); FILE MERGED 2008/04/16 06:28:06 oj 1.3.4.2: RESYNC: (1.3-1.4); FILE MERGED 2008/04/03 06:35:18 oj 1.3.4.1: #i86343# remove unused code<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ReportEngineJFree.hxx,v $ * $Revision: 1.5 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef REPORTDESIGN_API_REPORTENGINEJFREE_HXX #define REPORTDESIGN_API_REPORTENGINEJFREE_HXX #include <com/sun/star/report/XReportEngine.hpp> #include <cppuhelper/compbase2.hxx> #include <comphelper/broadcasthelper.hxx> #include <comphelper/uno3.hxx> #include <comphelper/types.hxx> #include <cppuhelper/propertysetmixin.hxx> #include <com/sun/star/uno/XComponentContext.hpp> #include <com/sun/star/sdbc/XRowSet.hpp> #include <comphelper/stl_types.hxx> #include <comphelper/implementationreference.hxx> #include <com/sun/star/lang/XServiceInfo.hpp> namespace reportdesign { typedef ::cppu::WeakComponentImplHelper2< com::sun::star::report::XReportEngine ,com::sun::star::lang::XServiceInfo> ReportEngineBase; typedef ::cppu::PropertySetMixin<com::sun::star::report::XReportEngine> ReportEnginePropertySet; class OReportEngineJFree : public comphelper::OMutexAndBroadcastHelper, public ReportEngineBase, public ReportEnginePropertySet { typedef ::std::multimap< ::rtl::OUString, ::com::sun::star::uno::Any , ::comphelper::UStringMixLess> TComponentMap; ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext; ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportDefinition > m_xReport; ::com::sun::star::uno::Reference< ::com::sun::star::task::XStatusIndicator> m_StatusIndicator; ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > m_xActiveConnection; private: OReportEngineJFree(const OReportEngineJFree&); OReportEngineJFree& operator=(const OReportEngineJFree&); template <typename T> void set( const ::rtl::OUString& _sProperty ,const T& _Value ,T& _member) { BoundListeners l; { ::osl::MutexGuard aGuard(m_aMutex); prepareSet(_sProperty, ::com::sun::star::uno::makeAny(_member), ::com::sun::star::uno::makeAny(_Value), &l); _member = _Value; } l.notify(); } /** returns the file url for a new model * * \return The new file url. */ ::rtl::OUString getNewOutputName(); /** generates the order statement defined by the groups of the report * * \return the ORDER BY part */ ::rtl::OUString getOrderStatement() const; protected: // TODO: VirtualFunctionFinder: This is virtual function! // virtual ~OReportEngineJFree(); public: typedef ::comphelper::ImplementationReference< OReportEngineJFree ,::com::sun::star::report::XReportEngine,::com::sun::star::uno::XWeak > TReportEngine; OReportEngineJFree(const com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext >& context); DECLARE_XINTERFACE( ) // ::com::sun::star::lang::XServiceInfo virtual ::sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException); static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( ::com::sun::star::uno::RuntimeException ); static ::rtl::OUString getImplementationName_Static(void) throw( ::com::sun::star::uno::RuntimeException ); static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL create(::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > const & xContext); // com::sun::star::beans::XPropertySet virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XReportEngine // Attributes virtual ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportDefinition > SAL_CALL getReportDefinition() throw (::com::sun::star::uno::RuntimeException) ; virtual void SAL_CALL setReportDefinition( const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportDefinition >& _reportdefinition ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL getActiveConnection() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setActiveConnection( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _activeconnection ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::task::XStatusIndicator > SAL_CALL getStatusIndicator() throw (::com::sun::star::uno::RuntimeException) ; virtual void SAL_CALL setStatusIndicator( const ::com::sun::star::uno::Reference< ::com::sun::star::task::XStatusIndicator >& _statusindicator ) throw (::com::sun::star::uno::RuntimeException) ; // Methods virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > SAL_CALL createDocumentModel( ) throw (::com::sun::star::lang::DisposedException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException) ; virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > SAL_CALL createDocumentAlive( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& _frame ) throw (::com::sun::star::lang::DisposedException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException) ; virtual ::com::sun::star::util::URL SAL_CALL createDocument( ) throw (::com::sun::star::lang::DisposedException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException) ; virtual void SAL_CALL interrupt( ) throw (::com::sun::star::lang::DisposedException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException) ; // XComponent virtual void SAL_CALL dispose() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addEventListener(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener > & aListener) throw(::com::sun::star::uno::RuntimeException) { cppu::WeakComponentImplHelperBase::addEventListener(aListener); } virtual void SAL_CALL removeEventListener(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener > & aListener) throw(::com::sun::star::uno::RuntimeException) { cppu::WeakComponentImplHelperBase::removeEventListener(aListener); } }; } #endif //REPORTDESIGN_API_REPORTENGINEJFREE_HXX <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011-2013. // 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) //======================================================================= #include <iostream> #include "timing.hpp" using namespace eddic; timing_timer::timing_timer(timing_system& system, const std::string& name) : system(system), name(name) { //Nothing } timing_timer::~timing_timer(){ system.register_timing(name, timer.elapsed()); } bool is_aggregate(const std::string& name){ return name == "whole_optimizations" || name == "all_optimizations"; } void timing_system::display(){ std::cout << "Timers" << std::endl; typedef std::pair<std::string, double> timer; std::vector<timer> timers; for(auto& timing : timings){ timers.emplace_back(timing.first, timing.second); } std::sort(timers.begin(), timers.end(), [](const timer& lhs, const timer& rhs){ return lhs.second > rhs.second; }); double total = 0.0; for(auto& timing : timers){ if(!is_aggregate(timing.first)){ std::cout << " " << timing.first << ":" << timing.second << "ms" << std::endl; total += timing.second; } } std::cout << "Aggregate Timers" << std::endl; std::cout << " " << "Total:" << total << "ms" << std::endl; for(auto& timing : timers){ if(is_aggregate(timing.first)){ std::cout << " " << timing.first << ":" << timing.second << "ms" << std::endl; } } } void timing_system::register_timing(std::string name, double time){ timings[name] += time; } <commit_msg>Better printings<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011-2013. // 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) //======================================================================= #include <iostream> #include <iomanip> #include "timing.hpp" using namespace eddic; timing_timer::timing_timer(timing_system& system, const std::string& name) : system(system), name(name) { //Nothing } timing_timer::~timing_timer(){ system.register_timing(name, timer.elapsed()); } bool is_aggregate(const std::string& name){ return name == "whole_optimizations" || name == "all_optimizations"; } void timing_system::display(){ std::cout << "Timers" << std::endl; typedef std::pair<std::string, double> timer; std::vector<timer> timers; for(auto& timing : timings){ timers.emplace_back(timing.first, timing.second); } std::sort(timers.begin(), timers.end(), [](const timer& lhs, const timer& rhs){ return lhs.second > rhs.second; }); double total = 0.0; for(auto& timing : timers){ if(!is_aggregate(timing.first)){ total += timing.second; } } for(auto& timing : timers){ if(!is_aggregate(timing.first)){ size_t save_prec = std::cout.precision(); std::cout << " " << timing.first << ":" << timing.second << "ms (" << std::setprecision(2) << ((timing.second / total) * 100) << "%)"<< std::endl; std::cout.precision(save_prec); } } std::cout << "Aggregate Timers" << std::endl; std::cout << " " << "Total:" << total << "ms" << std::endl; for(auto& timing : timers){ if(is_aggregate(timing.first)){ std::cout << " " << timing.first << ":" << timing.second << "ms" << std::endl; } } } void timing_system::register_timing(std::string name, double time){ timings[name] += time; } <|endoftext|>
<commit_before>/* <one line to give the library's name and an idea of what it does.> Copyright (C) 2013 David Edmundson <davidedmundson@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "persondatatests.h" #include <persondata.h> #include <Nepomuk2/Vocabulary/NCO> #include <Nepomuk2/Vocabulary/PIMO> #include <Nepomuk2/StoreResourcesJob> #include <Nepomuk2/SimpleResource> #include <Nepomuk2/SimpleResourceGraph> #include <Soprano/Vocabulary/NAO> #include <qtest_kde.h> #include <QTest> using namespace Nepomuk2; using namespace Nepomuk2::Vocabulary; using namespace Soprano::Vocabulary; void PersonDataTests::initContact1() { Nepomuk2::SimpleResourceGraph graph; Nepomuk2::SimpleResource contact; contact.addType(NCO::PersonContact()); contact.addProperty(NAO::prefLabel(), "Contact 1"); contact.addProperty(NCO::fullname(), "Contact One"); Nepomuk2::SimpleResource email; email.addType(NCO::EmailAddress()); email.addProperty(NCO::emailAddress(), "contact1@example.com"); contact.addProperty(NCO::hasEmailAddress(), email); graph << contact << email; Nepomuk2::StoreResourcesJob *job = graph.save(); job->exec(); m_contact1Uri = job->mappings()[contact.uri()]; } void PersonDataTests::initPersonA() { //create contact 2 and contact 3 //both have a ground truth to person1 Nepomuk2::SimpleResourceGraph graph; Nepomuk2::SimpleResource contact2; { contact2.addType(NCO::PersonContact()); contact2.addProperty(NAO::prefLabel(), "Person A"); contact2.addProperty(NCO::fullname(), "Person A"); Nepomuk2::SimpleResource email; email.addType(NCO::EmailAddress()); email.addProperty(NCO::emailAddress(), "contact2@example.com"); contact2.addProperty(NCO::hasEmailAddress(), email); graph << contact2 << email; } Nepomuk2::SimpleResource contact3; { contact3.addType(NCO::PersonContact()); contact3.addProperty(NAO::prefLabel(), "Person A"); contact3.addProperty(NCO::fullname(), "Person A"); Nepomuk2::SimpleResource email; email.addType(NCO::EmailAddress()); email.addProperty(NCO::emailAddress(), "contact3@example.com"); contact3.addProperty(NCO::hasEmailAddress(), email); graph << contact3 << email; } Nepomuk2::SimpleResource personA; personA.addType(PIMO::Person()); personA.addProperty(PIMO::GroundingClosure(), contact2); personA.addProperty(PIMO::GroundingClosure(), contact3); graph << personA; Nepomuk2::StoreResourcesJob *job = graph.save(); job->exec(); m_contact2Uri = job->mappings()[contact2.uri()]; m_contact3Uri = job->mappings()[contact3.uri()]; m_personAUri = job->mappings()[personA.uri()]; } void PersonDataTests::contactProperties() { //create a simple contact with name + email QScopedPointer<PersonData> personData(new PersonData); personData->setUri(m_contact1Uri.toString()); QCOMPARE(personData->name(), QLatin1String("Contact One")); QCOMPARE(personData->emails(), QStringList() << QLatin1String("contact1@example.com")); } void PersonDataTests::personProperties() { PersonData personData; personData.setUri(m_personAUri.toString()); QCOMPARE(personData.name(), QLatin1String("Person A")); QCOMPARE(personData.emails(), QStringList() << QLatin1String("contact2@example.com") << QLatin1String("contact3@example.com")); } void PersonDataTests::personFromContactID() { PersonData personData; personData.setContactId(QLatin1String("contact2@example.com")); //This should load PersonA NOT Contact2 QCOMPARE(personData.uri(), m_personAUri.toString()); } void PersonDataTests::contactFromContactID() { PersonData personData; personData.setContactId(QLatin1String("contact1@example.com")); QCOMPARE(personData.uri(), m_contact1Uri.toString()); } QTEST_KDEMAIN(PersonDataTests, NoGUI) <commit_msg>Tidy test code<commit_after>/* <one line to give the library's name and an idea of what it does.> Copyright (C) 2013 David Edmundson <davidedmundson@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "persondatatests.h" #include <persondata.h> #include <Nepomuk2/Vocabulary/NCO> #include <Nepomuk2/Vocabulary/PIMO> #include <Nepomuk2/StoreResourcesJob> #include <Nepomuk2/SimpleResource> #include <Nepomuk2/SimpleResourceGraph> #include <Soprano/Vocabulary/NAO> #include <qtest_kde.h> #include <QTest> using namespace Nepomuk2; using namespace Nepomuk2::Vocabulary; using namespace Soprano::Vocabulary; void PersonDataTests::initContact1() { Nepomuk2::SimpleResourceGraph graph; Nepomuk2::SimpleResource contact; contact.addType(NCO::PersonContact()); contact.addProperty(NAO::prefLabel(), "Contact 1"); contact.addProperty(NCO::fullname(), "Contact One"); Nepomuk2::SimpleResource email; email.addType(NCO::EmailAddress()); email.addProperty(NCO::emailAddress(), "contact1@example.com"); contact.addProperty(NCO::hasEmailAddress(), email); graph << contact << email; Nepomuk2::StoreResourcesJob *job = graph.save(); job->exec(); m_contact1Uri = job->mappings()[contact.uri()]; } void PersonDataTests::initPersonA() { //create contact 2 and contact 3 //both have a ground truth to person1 Nepomuk2::SimpleResourceGraph graph; Nepomuk2::SimpleResource contact2; { contact2.addType(NCO::PersonContact()); contact2.addProperty(NAO::prefLabel(), "Person A"); contact2.addProperty(NCO::fullname(), "Person A"); Nepomuk2::SimpleResource email; email.addType(NCO::EmailAddress()); email.addProperty(NCO::emailAddress(), "contact2@example.com"); contact2.addProperty(NCO::hasEmailAddress(), email); graph << contact2 << email; } Nepomuk2::SimpleResource contact3; { contact3.addType(NCO::PersonContact()); contact3.addProperty(NAO::prefLabel(), "Person A"); contact3.addProperty(NCO::fullname(), "Person A"); Nepomuk2::SimpleResource email; email.addType(NCO::EmailAddress()); email.addProperty(NCO::emailAddress(), "contact3@example.com"); contact3.addProperty(NCO::hasEmailAddress(), email); graph << contact3 << email; } Nepomuk2::SimpleResource personA; personA.addType(PIMO::Person()); personA.addProperty(PIMO::GroundingClosure(), contact2); personA.addProperty(PIMO::GroundingClosure(), contact3); graph << personA; Nepomuk2::StoreResourcesJob *job = graph.save(); job->exec(); m_contact2Uri = job->mappings()[contact2.uri()]; m_contact3Uri = job->mappings()[contact3.uri()]; m_personAUri = job->mappings()[personA.uri()]; } void PersonDataTests::contactProperties() { //create a simple contact with name + email PersonData personData; personData.setUri(m_contact1Uri.toString()); QCOMPARE(personData.name(), QLatin1String("Contact One")); QCOMPARE(personData.emails(), QStringList() << QLatin1String("contact1@example.com")); } void PersonDataTests::personProperties() { PersonData personData; personData.setUri(m_personAUri.toString()); QCOMPARE(personData.name(), QLatin1String("Person A")); QCOMPARE(personData.emails(), QStringList() << QLatin1String("contact2@example.com") << QLatin1String("contact3@example.com")); } void PersonDataTests::personFromContactID() { PersonData personData; personData.setContactId(QLatin1String("contact2@example.com")); //This should load PersonA NOT Contact2 QCOMPARE(personData.uri(), m_personAUri.toString()); } void PersonDataTests::contactFromContactID() { PersonData personData; personData.setContactId(QLatin1String("contact1@example.com")); QCOMPARE(personData.uri(), m_contact1Uri.toString()); } QTEST_KDEMAIN(PersonDataTests, NoGUI) <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 2001, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.1 2002/02/01 22:22:10 peiyongz * Initial revision * * Revision 1.1 2001/05/16 15:25:38 tng * Schema: Add Base64 and HexBin. By Pei Yong Zhang. * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/util/HexBin.hpp> #include <xercesc/util/XMLUniDefs.hpp> #include <xercesc/util/XMLString.hpp> // --------------------------------------------------------------------------- // constants // --------------------------------------------------------------------------- static const int BASELENGTH = 255; // --------------------------------------------------------------------------- // class data member // --------------------------------------------------------------------------- bool HexBin::hexNumberTable[BASELENGTH]; bool HexBin::isInitialized = false; int HexBin::getDataLength(const XMLCh* const hexData) { if (!isArrayByteHex(hexData)) return -1; return XMLString::stringLen(hexData)/2; } bool HexBin::isArrayByteHex(const XMLCh* const hexData) { if ( !isInitialized ) init(); if (( hexData == 0 ) || ( *hexData == 0 )) // zero length return false; int strLen = XMLString::stringLen(hexData); if ( strLen%2 != 0 ) return false; for ( int i = 0; i < strLen; i++ ) if( !isHex(hexData[i]) ) return false; return true; } // ----------------------------------------------------------------------- // Helper methods // ----------------------------------------------------------------------- bool HexBin::isHex(const XMLCh& octect) { // sanity check to avoid out-of-bound index if (( octect >= BASELENGTH ) || ( octect < 0 )) return false; return (hexNumberTable[octect]); } void HexBin::init() { if ( isInitialized ) return; int i; for ( i = 0; i < BASELENGTH; i++ ) hexNumberTable[i] = false; for ( i = chDigit_9; i >= chDigit_0; i-- ) hexNumberTable[i] = true; for ( i = chLatin_F; i >= chLatin_A; i-- ) hexNumberTable[i] = true; for ( i = chLatin_f; i >= chLatin_a; i-- ) hexNumberTable[i] = true; isInitialized = true; } <commit_msg>Bug#7301: Redundant range-check in HexBin.cpp, patch from Martin Kalen<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 2001, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.2 2002/04/18 14:55:38 peiyongz * Bug#7301: Redundant range-check in HexBin.cpp, patch from Martin Kalen * * Revision 1.1.1.1 2002/02/01 22:22:10 peiyongz * sane_include * * Revision 1.1 2001/05/16 15:25:38 tng * Schema: Add Base64 and HexBin. By Pei Yong Zhang. * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/util/HexBin.hpp> #include <xercesc/util/XMLUniDefs.hpp> #include <xercesc/util/XMLString.hpp> // --------------------------------------------------------------------------- // constants // --------------------------------------------------------------------------- static const int BASELENGTH = 255; // --------------------------------------------------------------------------- // class data member // --------------------------------------------------------------------------- bool HexBin::hexNumberTable[BASELENGTH]; bool HexBin::isInitialized = false; int HexBin::getDataLength(const XMLCh* const hexData) { if (!isArrayByteHex(hexData)) return -1; return XMLString::stringLen(hexData)/2; } bool HexBin::isArrayByteHex(const XMLCh* const hexData) { if ( !isInitialized ) init(); if (( hexData == 0 ) || ( *hexData == 0 )) // zero length return false; int strLen = XMLString::stringLen(hexData); if ( strLen%2 != 0 ) return false; for ( int i = 0; i < strLen; i++ ) if( !isHex(hexData[i]) ) return false; return true; } // ----------------------------------------------------------------------- // Helper methods // ----------------------------------------------------------------------- bool HexBin::isHex(const XMLCh& octet) { // sanity check to avoid out-of-bound index if ( octet >= BASELENGTH ) return false; return (hexNumberTable[octet]); } void HexBin::init() { if ( isInitialized ) return; int i; for ( i = 0; i < BASELENGTH; i++ ) hexNumberTable[i] = false; for ( i = chDigit_9; i >= chDigit_0; i-- ) hexNumberTable[i] = true; for ( i = chLatin_F; i >= chLatin_A; i-- ) hexNumberTable[i] = true; for ( i = chLatin_f; i >= chLatin_a; i-- ) hexNumberTable[i] = true; isInitialized = true; } <|endoftext|>
<commit_before>/* -*- C++ -*- */ /************************************************************************* * Copyright(c) 1995~2005 Masaharu Goto (cint@pcroot.cern.ch) * * For the licensing terms see the file COPYING * ************************************************************************/ #if defined(interp) && defined(makecint) #pragma include "test.dll" #else #include "t1193.h" #endif namespace testscript0001 { class MyScript : public SystemScript { private : float mValue; public : MyScript() : SystemScript("MyScript", "MyObject") { System::Print("alive!"); // this causes "Warning: Automatic variable mValue is allocated mValue = 1.0f; // working version // this->mValue = 1.0f; } } MyObject; //MyScript MyObject2; } // -- script start -- namespace testscript0002 { class Noise : public EditorScript { public : Noise() : EditorScript("Noise", "NoiseObject") { const int Size = 513*513; unsigned short *Map = new unsigned short[Size]; for(int i=0; i<Size; i++) Map[i]=Math::rand()%1024; BeginTerrainPaint(); //[..(snipped)..] } }; Noise NoiseObject; }; int main() { return 0; } <commit_msg>Shorten test run time drastically. -- Paul Russo<commit_after>/* -*- C++ -*- */ /************************************************************************* * Copyright(c) 1995~2005 Masaharu Goto (cint@pcroot.cern.ch) * * For the licensing terms see the file COPYING * ************************************************************************/ #if defined(interp) && defined(makecint) #pragma include "test.dll" #else #include "t1193.h" #endif namespace testscript0001 { class MyScript : public SystemScript { private : float mValue; public : MyScript() : SystemScript("MyScript", "MyObject") { System::Print("alive!"); // this causes "Warning: Automatic variable mValue is allocated mValue = 1.0f; // working version // this->mValue = 1.0f; } } MyObject; //MyScript MyObject2; } // -- script start -- namespace testscript0002 { class Noise : public EditorScript { public : Noise() : EditorScript("Noise", "NoiseObject") { const int Size = 1; unsigned short *Map = new unsigned short[Size]; for(int i=0; i<Size; i++) Map[i]=Math::rand()%1024; BeginTerrainPaint(); //[..(snipped)..] } }; Noise NoiseObject; }; int main() { return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xmlMasterFields.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: kz $ $Date: 2008-03-05 18:04:14 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "precompiled_reportdesign.hxx" #ifndef RPT_XMLMASTERFIELDS_HXX #include "xmlMasterFields.hxx" #endif #ifndef RPT_XMLFILTER_HXX #include "xmlfilter.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmloff/xmlnmspe.hxx> #endif #ifndef _XMLOFF_NMSPMAP_HXX #include <xmloff/nmspmap.hxx> #endif #ifndef RPT_XMLENUMS_HXX #include "xmlEnums.hxx" #endif #include "xmlReport.hxx" #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif namespace rptxml { using namespace ::com::sun::star; using namespace ::com::sun::star::report; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::xml::sax; DBG_NAME( rpt_OXMLMasterFields ) OXMLMasterFields::OXMLMasterFields( ORptFilter& rImport, sal_uInt16 nPrfx, const ::rtl::OUString& rLName, const Reference< XAttributeList > & _xAttrList ,IMasterDetailFieds* _pReport ) : SvXMLImportContext( rImport, nPrfx, rLName) ,m_pReport(_pReport) { DBG_CTOR( rpt_OXMLMasterFields,NULL); const SvXMLNamespaceMap& rMap = rImport.GetNamespaceMap(); const SvXMLTokenMap& rTokenMap = rImport.GetSubDocumentElemTokenMap(); ::rtl::OUString sMasterField,sDetailField; const sal_Int16 nLength = (_xAttrList.is()) ? _xAttrList->getLength() : 0; for(sal_Int16 i = 0; i < nLength; ++i) { ::rtl::OUString sLocalName; const rtl::OUString sAttrName = _xAttrList->getNameByIndex( i ); const sal_uInt16 nPrefix = rMap.GetKeyByAttrName( sAttrName,&sLocalName ); const rtl::OUString sValue = _xAttrList->getValueByIndex( i ); switch( rTokenMap.Get( nPrefix, sLocalName ) ) { case XML_TOK_MASTER: sMasterField = sValue; break; case XML_TOK_SUB_DETAIL: sDetailField = sValue; break; default: break; } } if ( !sDetailField.getLength() ) sDetailField = sMasterField; m_pReport->addMasterDetailPair(::std::pair< ::rtl::OUString,::rtl::OUString >(sMasterField,sDetailField)); } // ----------------------------------------------------------------------------- OXMLMasterFields::~OXMLMasterFields() { DBG_DTOR( rpt_OXMLMasterFields,NULL); } // ----------------------------------------------------------------------------- SvXMLImportContext* OXMLMasterFields::CreateChildContext( sal_uInt16 _nPrefix, const ::rtl::OUString& _rLocalName, const Reference< XAttributeList > & xAttrList ) { SvXMLImportContext *pContext = 0; const SvXMLTokenMap& rTokenMap = static_cast<ORptFilter&>(GetImport()).GetSubDocumentElemTokenMap(); switch( rTokenMap.Get( _nPrefix, _rLocalName ) ) { case XML_TOK_MASTER_DETAIL_FIELD: { GetImport().GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP ); pContext = new OXMLMasterFields(static_cast<ORptFilter&>(GetImport()), _nPrefix, _rLocalName,xAttrList ,m_pReport); } break; default: break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), _nPrefix, _rLocalName ); return pContext; } //---------------------------------------------------------------------------- } // namespace rptxml // ----------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS changefileheader (1.5.8); FILE MERGED 2008/04/01 15:23:38 thb 1.5.8.3: #i85898# Stripping all external header guards 2008/04/01 12:33:11 thb 1.5.8.2: #i85898# Stripping all external header guards 2008/03/31 13:32:09 rt 1.5.8.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xmlMasterFields.cxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "precompiled_reportdesign.hxx" #include "xmlMasterFields.hxx" #include "xmlfilter.hxx" #include <xmloff/xmltoken.hxx> #include <xmloff/xmlnmspe.hxx> #include <xmloff/nmspmap.hxx> #include "xmlEnums.hxx" #include "xmlReport.hxx" #include <tools/debug.hxx> namespace rptxml { using namespace ::com::sun::star; using namespace ::com::sun::star::report; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::xml::sax; DBG_NAME( rpt_OXMLMasterFields ) OXMLMasterFields::OXMLMasterFields( ORptFilter& rImport, sal_uInt16 nPrfx, const ::rtl::OUString& rLName, const Reference< XAttributeList > & _xAttrList ,IMasterDetailFieds* _pReport ) : SvXMLImportContext( rImport, nPrfx, rLName) ,m_pReport(_pReport) { DBG_CTOR( rpt_OXMLMasterFields,NULL); const SvXMLNamespaceMap& rMap = rImport.GetNamespaceMap(); const SvXMLTokenMap& rTokenMap = rImport.GetSubDocumentElemTokenMap(); ::rtl::OUString sMasterField,sDetailField; const sal_Int16 nLength = (_xAttrList.is()) ? _xAttrList->getLength() : 0; for(sal_Int16 i = 0; i < nLength; ++i) { ::rtl::OUString sLocalName; const rtl::OUString sAttrName = _xAttrList->getNameByIndex( i ); const sal_uInt16 nPrefix = rMap.GetKeyByAttrName( sAttrName,&sLocalName ); const rtl::OUString sValue = _xAttrList->getValueByIndex( i ); switch( rTokenMap.Get( nPrefix, sLocalName ) ) { case XML_TOK_MASTER: sMasterField = sValue; break; case XML_TOK_SUB_DETAIL: sDetailField = sValue; break; default: break; } } if ( !sDetailField.getLength() ) sDetailField = sMasterField; m_pReport->addMasterDetailPair(::std::pair< ::rtl::OUString,::rtl::OUString >(sMasterField,sDetailField)); } // ----------------------------------------------------------------------------- OXMLMasterFields::~OXMLMasterFields() { DBG_DTOR( rpt_OXMLMasterFields,NULL); } // ----------------------------------------------------------------------------- SvXMLImportContext* OXMLMasterFields::CreateChildContext( sal_uInt16 _nPrefix, const ::rtl::OUString& _rLocalName, const Reference< XAttributeList > & xAttrList ) { SvXMLImportContext *pContext = 0; const SvXMLTokenMap& rTokenMap = static_cast<ORptFilter&>(GetImport()).GetSubDocumentElemTokenMap(); switch( rTokenMap.Get( _nPrefix, _rLocalName ) ) { case XML_TOK_MASTER_DETAIL_FIELD: { GetImport().GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP ); pContext = new OXMLMasterFields(static_cast<ORptFilter&>(GetImport()), _nPrefix, _rLocalName,xAttrList ,m_pReport); } break; default: break; } if( !pContext ) pContext = new SvXMLImportContext( GetImport(), _nPrefix, _rLocalName ); return pContext; } //---------------------------------------------------------------------------- } // namespace rptxml // ----------------------------------------------------------------------------- <|endoftext|>
<commit_before>/* Copyright 2012 Frederik Gladhorn <gladhorn@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "eventview.h" #include <qtextdocument.h> #include <qtextcursor.h> #include <qtextobject.h> #include <qtimer.h> #include <qscrollbar.h> #include <qsettings.h> #include <QPair> #include <QSortFilterProxyModel> #include <QStandardItemModel> #include <QStandardItem> #include <QMetaObject> #include <QMetaEnum> #include <qdebug.h> class EventsModel : public QStandardItemModel { public: enum Column { AccessibleRole = 0, RoleRole = 1, EventRole = 2, ActionRole = 3, EventTypeRole = Qt::UserRole, UrlRole, AppNameRole }; EventsModel(EventsWidget *view) : QStandardItemModel(view), m_view(view) { QHash<int, QByteArray> roles; roles[AccessibleRole] = "accessible"; roles[RoleRole] = "role"; roles[EventRole] = "event"; roles[EventTypeRole] = "eventType"; roles[UrlRole] = "url"; roles[AppNameRole] = "appName"; setRoleNames(roles); clearLog(); } ~EventsModel() {} QString roleLabel(Column c) const { switch (c) { case AccessibleRole: return QString("Accessible"); case RoleRole: return QString("Role"); case EventRole: return QString("Event"); case ActionRole: return QString("Action"); case EventTypeRole: case UrlRole: case AppNameRole: break; } return QString(); } void clearLog() { clear(); m_apps.clear(); setColumnCount(4); QStringList headerLabels; Q_FOREACH(Column c, QList<Column>() << AccessibleRole << RoleRole << EventRole << ActionRole) headerLabels << roleLabel(c); setHorizontalHeaderLabels(headerLabels); } struct LogItem { QStandardItem *appItem; bool isNewAppItem; LogItem(QStandardItem *appItem, bool isNewAppItem) : appItem(appItem), isNewAppItem(isNewAppItem) {} }; LogItem addLog(QList<QStandardItem*> item) { QString appName = item.first()->data(AppNameRole).toString(); QStandardItem *appItem = 0; QMap<QString, QStandardItem*>::ConstIterator it = m_apps.constFind(appName); bool isNewAppItem = it == m_apps.constEnd(); if (isNewAppItem) { m_apps[appName] = appItem = new QStandardItem(appName); invisibleRootItem()->appendRow(appItem); } else { appItem = it.value(); } appItem->appendRow(item); return LogItem(appItem, isNewAppItem); } private: EventsWidget *m_view; QMap<QString, QStandardItem*> m_apps; }; class EventsProxyModel : public QSortFilterProxyModel { public: EventsProxyModel(QWidget *parent = 0) : QSortFilterProxyModel(parent), m_types(EventsWidget::AllEvents) {} EventsWidget::EventTypes filter() const { return m_types; } QString accessibleFilter() const { return m_accessibleFilter; } QString roleFilter() const { return m_roleFilter; } void setFilter(EventsWidget::EventTypes types) { m_types = types; invalidateFilter(); } void setAccessibleFilter(const QString &filter) { m_accessibleFilter = filter; invalidateFilter(); } void setRoleFilter(const QString &filter) { m_roleFilter = filter; invalidateFilter(); } protected: virtual bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const { QModelIndex index = sourceModel()->index(source_row, 0, source_parent); if (!index.parent().isValid()) return true; if (!m_types.testFlag(EventsWidget::AllEvents)) { EventsWidget::EventType type = index.data(EventsModel::EventTypeRole).value<EventsWidget::EventType>(); if (!m_types.testFlag(type)) return false; } if (!m_accessibleFilter.isEmpty()) { QModelIndex index = sourceModel()->index(source_row, EventsModel::AccessibleRole, source_parent); QString accessibleName = index.data(Qt::DisplayRole).toString(); if (!accessibleName.contains(m_accessibleFilter, Qt::CaseInsensitive)) return false; } if (!m_roleFilter.isEmpty()) { QModelIndex index = sourceModel()->index(source_row, EventsModel::RoleRole, source_parent); QString roleName = index.data(Qt::DisplayRole).toString(); if (!roleName.contains(m_roleFilter, Qt::CaseInsensitive)) return false; } return true; } private: EventsWidget::EventTypes m_types; QString m_accessibleFilter; QString m_roleFilter; }; using namespace QAccessibleClient; QAccessible::UpdateHandler EventsWidget::m_originalAccessibilityUpdateHandler = 0; QObject *EventsWidget::m_textEditForAccessibilityUpdateHandler = 0; EventsWidget::EventsWidget(QAccessibleClient::Registry *registry, QWidget *parent) : QWidget(parent), m_registry(registry), m_model(new EventsModel(this)), m_proxyModel(new EventsProxyModel(this)) { m_ui.setupUi(this); m_ui.eventListView->setAccessibleName(QLatin1String("Events View")); m_ui.eventListView->setAccessibleDescription(QString("Displays all received events")); m_proxyModel->setSourceModel(m_model); m_ui.eventListView->setModel(m_proxyModel); connect(m_ui.accessibleFilterEdit, SIGNAL(textChanged(QString)), this, SLOT(accessibleFilterChanged())); connect(m_ui.roleFilterEdit, SIGNAL(textChanged(QString)), this, SLOT(roleFilterChanged())); QStandardItemModel *filerModel = new QStandardItemModel(); QStandardItem *firstFilterItem = new QStandardItem(QString("Event Filter")); firstFilterItem->setFlags(Qt::ItemIsEnabled); filerModel->appendRow(firstFilterItem); QVector< EventType > filterList; filterList << StateChanged << NameChanged << DescriptionChanged << Window << Focus << Document << Object << Text << Table << Others; for(int i = 0; i < filterList.count(); ++i) { EventType t = filterList[i]; QStandardItem* item = new QStandardItem(eventName(t)); item->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled); item->setData(QVariant::fromValue<EventType>(t), EventsModel::EventTypeRole); item->setData(Qt::Checked, Qt::CheckStateRole); filerModel->appendRow(QList<QStandardItem*>() << item); } m_ui.filterComboBox->setModel(filerModel); m_ui.clearButton->setFixedWidth(QFontMetrics(m_ui.clearButton->font()).boundingRect(m_ui.clearButton->text()).width() + 4); m_ui.clearButton->setFixedHeight(m_ui.filterComboBox->sizeHint().height()); connect(m_ui.clearButton, SIGNAL(clicked()), this, SLOT(clearLog())); connect(m_ui.filterComboBox->model(), SIGNAL(itemChanged(QStandardItem*)), this, SLOT(checkStateChanged())); connect(m_ui.eventListView, SIGNAL(activated(QModelIndex)), this, SLOT(eventActivated(QModelIndex))); // Collect multiple addLog calls and process them after 500 ms earliest. This // makes sure multiple calls to addLog will be compressed to one only one // view refresh what improves performance. m_pendingTimer.setInterval(500); connect(&m_pendingTimer, SIGNAL(timeout()), this, SLOT(processPending())); m_textEditForAccessibilityUpdateHandler = m_ui.eventListView; checkStateChanged(); // We need to wait for a11y to be active for this hack. QTimer::singleShot(500, this, SLOT(installUpdateHandler())); } void EventsWidget::installUpdateHandler() { m_originalAccessibilityUpdateHandler = QAccessible::installUpdateHandler(customUpdateHandler); if (!m_originalAccessibilityUpdateHandler) QTimer::singleShot(500, this, SLOT(installUpdateHandler())); } #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) void EventsWidget::customUpdateHandler(QAccessibleEvent *event) { QObject *object = event->object(); #else void EventsWidget::customUpdateHandler(QObject *object, int who, QAccessible::Event reason) { #endif if (object == m_textEditForAccessibilityUpdateHandler) return; //if (m_originalAccessibilityUpdateHandler) // m_originalAccessibilityUpdateHandler(object, who, reason); } QString EventsWidget::eventName(EventType eventType) const { QString s; switch (eventType) { case EventsWidget::Focus: s = QLatin1String("Focus"); break; case EventsWidget::StateChanged: s = QLatin1String("State"); break; case EventsWidget::NameChanged: s = QLatin1String("Name"); break; case EventsWidget::DescriptionChanged: s = QLatin1String("Description"); break; case EventsWidget::Window: s = QLatin1String("Window"); break; case EventsWidget::Document: s = QLatin1String("Document"); break; case EventsWidget::Object: s = QLatin1String("Object"); break; case EventsWidget::Text: s = QLatin1String("Text"); break; case EventsWidget::Table: s = QLatin1String("Table"); break; case EventsWidget::Others: s = QLatin1String("Others"); break; } return s; } void EventsWidget::loadSettings(QSettings &settings) { settings.beginGroup("events"); bool eventsFilterOk; EventTypes eventsFilter = EventTypes(settings.value("eventsFiler").toInt(&eventsFilterOk)); if (!eventsFilterOk) eventsFilter = AllEvents; QAbstractItemModel *model = m_ui.filterComboBox->model(); if (eventsFilter != m_proxyModel->filter()) { for (int i = 1; i < model->rowCount(); ++i) { QModelIndex index = model->index(i, 0); EventType type = model->data(index, EventsModel::EventTypeRole).value<EventType>(); if (eventsFilter.testFlag(type)) model->setData(index, Qt::Checked, Qt::CheckStateRole); else model->setData(index, Qt::Unchecked, Qt::CheckStateRole); } m_proxyModel->setFilter(eventsFilter); } settings.endGroup(); } void EventsWidget::saveSettings(QSettings &settings) { settings.beginGroup("events"); settings.setValue("eventsFiler", int(m_proxyModel->filter())); settings.endGroup(); } void EventsWidget::clearLog() { m_model->clearLog(); } void EventsWidget::processPending() { m_pendingTimer.stop(); QVector< QList<QStandardItem*> > pendingLogs = m_pendingLogs; m_pendingLogs.clear(); //bool wasMax = true;//m_ui.eventListView->verticalScrollBar()->value() - 10 >= m_ui.eventListView->verticalScrollBar()->maximum(); QStandardItem *lastItem = 0; QStandardItem *lastAppItem = 0; for(int i = 0; i < pendingLogs.count(); ++i) { QList<QStandardItem*> item = pendingLogs[i]; EventsModel::LogItem logItem = m_model->addLog(item); // Logic to scroll to the last added logItem of the last appItem that is expanded. // For appItem's not expanded the logItem is added but no scrolling will happen. if (lastItem && lastAppItem && lastAppItem != logItem.appItem) lastItem = 0; bool selected = lastItem; if (lastAppItem != logItem.appItem) { lastAppItem = logItem.appItem; QModelIndex index = m_proxyModel->mapFromSource(m_model->indexFromItem(logItem.appItem)); if (logItem.isNewAppItem) { m_ui.eventListView->setExpanded(index, true); selected = true; } else { selected = m_ui.eventListView->isExpanded(index); } } if (selected) lastItem = item.first(); } if (lastItem) { // scroll down to the lastItem. //m_ui.eventListView->verticalScrollBar()->setValue(m_ui.eventListView->verticalScrollBar()->maximum()); QModelIndex index = m_proxyModel->mapFromSource(m_model->indexFromItem(lastItem)); m_ui.eventListView->scrollTo(index, QAbstractItemView::PositionAtBottom); //m_ui.eventListView->scrollTo(index, QAbstractItemView::EnsureVisible); } } void EventsWidget::addLog(const QAccessibleClient::AccessibleObject &object, EventsWidget::EventType eventType, const QString &text) { if (!object.isValid()) return; // if (object.name() == m_ui.eventListView->accessibleName() && object.description() == m_ui.eventListView->accessibleDescription()) // return; QStandardItem *nameItem = new QStandardItem(object.name()); nameItem->setData(QVariant::fromValue<EventType>(eventType), EventsModel::EventTypeRole); nameItem->setData(m_registry->url(object).toString(), EventsModel::UrlRole); AccessibleObject app = object.application(); nameItem->setData(app.isValid() ? app.name() : QString(), EventsModel::AppNameRole); QStandardItem *roleItem = new QStandardItem(object.roleName()); QStandardItem *typeItem = new QStandardItem(eventName(eventType)); QStandardItem *textItem = new QStandardItem(text); m_pendingLogs.append(QList<QStandardItem*>() << nameItem << roleItem << typeItem << textItem); if (!m_pendingTimer.isActive()) { m_pendingTimer.start(); } } void EventsWidget::checkStateChanged() { EventTypes types; QStringList names; bool allEvents = true; QMetaEnum e = metaObject()->enumerator(metaObject()->indexOfEnumerator("EventType")); Q_ASSERT(e.isValid()); QAbstractItemModel *model = m_ui.filterComboBox->model(); for (int i = 1; i < model->rowCount(); ++i) { QModelIndex index = model->index(i, 0); bool checked = model->data(index, Qt::CheckStateRole).toBool(); if (checked) { EventType type = model->data(index, EventsModel::EventTypeRole).value<EventType>(); types |= type; names.append(QString::fromLatin1(e.valueToKey(type))); } else { allEvents = false; } } m_proxyModel->setFilter(types); } void EventsWidget::eventActivated(const QModelIndex &index) { Q_ASSERT(index.isValid()); EventsProxyModel *proxyModel = dynamic_cast<EventsProxyModel*>(m_ui.eventListView->model()); Q_ASSERT(proxyModel); QModelIndex firstIndex = proxyModel->index(index.row(), 0, index.parent()); QString s = proxyModel->data(firstIndex, EventsModel::UrlRole).toString(); QUrl url(s); if (!url.isValid()) { qWarning() << Q_FUNC_INFO << "Invalid url=" << s; return; } emit anchorClicked(url); } void EventsWidget::accessibleFilterChanged() { m_proxyModel->setAccessibleFilter(m_ui.accessibleFilterEdit->text()); } void EventsWidget::roleFilterChanged() { m_proxyModel->setRoleFilter(m_ui.roleFilterEdit->text()); } <commit_msg>Naming++ Column=>Role<commit_after>/* Copyright 2012 Frederik Gladhorn <gladhorn@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "eventview.h" #include <qtextdocument.h> #include <qtextcursor.h> #include <qtextobject.h> #include <qtimer.h> #include <qscrollbar.h> #include <qsettings.h> #include <QPair> #include <QSortFilterProxyModel> #include <QStandardItemModel> #include <QStandardItem> #include <QMetaObject> #include <QMetaEnum> #include <qdebug.h> class EventsModel : public QStandardItemModel { public: enum Role { AccessibleRole = 0, RoleRole = 1, EventRole = 2, ActionRole = 3, EventTypeRole = Qt::UserRole, UrlRole, AppNameRole }; EventsModel(EventsWidget *view) : QStandardItemModel(view), m_view(view) { QHash<int, QByteArray> roles; roles[AccessibleRole] = "accessible"; roles[RoleRole] = "role"; roles[EventRole] = "event"; roles[EventTypeRole] = "eventType"; roles[UrlRole] = "url"; roles[AppNameRole] = "appName"; setRoleNames(roles); clearLog(); } ~EventsModel() {} QString roleLabel(Role role) const { switch (role) { case AccessibleRole: return QString("Accessible"); case RoleRole: return QString("Role"); case EventRole: return QString("Event"); case ActionRole: return QString("Action"); case EventTypeRole: case UrlRole: case AppNameRole: break; } return QString(); } void clearLog() { clear(); m_apps.clear(); setColumnCount(4); QStringList headerLabels; Q_FOREACH(Role r, QList<Role>() << AccessibleRole << RoleRole << EventRole << ActionRole) headerLabels << roleLabel(r); setHorizontalHeaderLabels(headerLabels); } struct LogItem { QStandardItem *appItem; bool isNewAppItem; LogItem(QStandardItem *appItem, bool isNewAppItem) : appItem(appItem), isNewAppItem(isNewAppItem) {} }; LogItem addLog(QList<QStandardItem*> item) { QString appName = item.first()->data(AppNameRole).toString(); QStandardItem *appItem = 0; QMap<QString, QStandardItem*>::ConstIterator it = m_apps.constFind(appName); bool isNewAppItem = it == m_apps.constEnd(); if (isNewAppItem) { m_apps[appName] = appItem = new QStandardItem(appName); invisibleRootItem()->appendRow(appItem); } else { appItem = it.value(); } appItem->appendRow(item); return LogItem(appItem, isNewAppItem); } private: EventsWidget *m_view; QMap<QString, QStandardItem*> m_apps; }; class EventsProxyModel : public QSortFilterProxyModel { public: EventsProxyModel(QWidget *parent = 0) : QSortFilterProxyModel(parent), m_types(EventsWidget::AllEvents) {} EventsWidget::EventTypes filter() const { return m_types; } QString accessibleFilter() const { return m_accessibleFilter; } QString roleFilter() const { return m_roleFilter; } void setFilter(EventsWidget::EventTypes types) { m_types = types; invalidateFilter(); } void setAccessibleFilter(const QString &filter) { m_accessibleFilter = filter; invalidateFilter(); } void setRoleFilter(const QString &filter) { m_roleFilter = filter; invalidateFilter(); } protected: virtual bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const { QModelIndex index = sourceModel()->index(source_row, 0, source_parent); if (!index.parent().isValid()) return true; if (!m_types.testFlag(EventsWidget::AllEvents)) { EventsWidget::EventType type = index.data(EventsModel::EventTypeRole).value<EventsWidget::EventType>(); if (!m_types.testFlag(type)) return false; } if (!m_accessibleFilter.isEmpty()) { QModelIndex index = sourceModel()->index(source_row, EventsModel::AccessibleRole, source_parent); QString accessibleName = index.data(Qt::DisplayRole).toString(); if (!accessibleName.contains(m_accessibleFilter, Qt::CaseInsensitive)) return false; } if (!m_roleFilter.isEmpty()) { QModelIndex index = sourceModel()->index(source_row, EventsModel::RoleRole, source_parent); QString roleName = index.data(Qt::DisplayRole).toString(); if (!roleName.contains(m_roleFilter, Qt::CaseInsensitive)) return false; } return true; } private: EventsWidget::EventTypes m_types; QString m_accessibleFilter; QString m_roleFilter; }; using namespace QAccessibleClient; QAccessible::UpdateHandler EventsWidget::m_originalAccessibilityUpdateHandler = 0; QObject *EventsWidget::m_textEditForAccessibilityUpdateHandler = 0; EventsWidget::EventsWidget(QAccessibleClient::Registry *registry, QWidget *parent) : QWidget(parent), m_registry(registry), m_model(new EventsModel(this)), m_proxyModel(new EventsProxyModel(this)) { m_ui.setupUi(this); m_ui.eventListView->setAccessibleName(QLatin1String("Events View")); m_ui.eventListView->setAccessibleDescription(QString("Displays all received events")); m_proxyModel->setSourceModel(m_model); m_ui.eventListView->setModel(m_proxyModel); connect(m_ui.accessibleFilterEdit, SIGNAL(textChanged(QString)), this, SLOT(accessibleFilterChanged())); connect(m_ui.roleFilterEdit, SIGNAL(textChanged(QString)), this, SLOT(roleFilterChanged())); QStandardItemModel *filerModel = new QStandardItemModel(); QStandardItem *firstFilterItem = new QStandardItem(QString("Event Filter")); firstFilterItem->setFlags(Qt::ItemIsEnabled); filerModel->appendRow(firstFilterItem); QVector< EventType > filterList; filterList << StateChanged << NameChanged << DescriptionChanged << Window << Focus << Document << Object << Text << Table << Others; for(int i = 0; i < filterList.count(); ++i) { EventType t = filterList[i]; QStandardItem* item = new QStandardItem(eventName(t)); item->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled); item->setData(QVariant::fromValue<EventType>(t), EventsModel::EventTypeRole); item->setData(Qt::Checked, Qt::CheckStateRole); filerModel->appendRow(QList<QStandardItem*>() << item); } m_ui.filterComboBox->setModel(filerModel); m_ui.clearButton->setFixedWidth(QFontMetrics(m_ui.clearButton->font()).boundingRect(m_ui.clearButton->text()).width() + 4); m_ui.clearButton->setFixedHeight(m_ui.filterComboBox->sizeHint().height()); connect(m_ui.clearButton, SIGNAL(clicked()), this, SLOT(clearLog())); connect(m_ui.filterComboBox->model(), SIGNAL(itemChanged(QStandardItem*)), this, SLOT(checkStateChanged())); connect(m_ui.eventListView, SIGNAL(activated(QModelIndex)), this, SLOT(eventActivated(QModelIndex))); // Collect multiple addLog calls and process them after 500 ms earliest. This // makes sure multiple calls to addLog will be compressed to one only one // view refresh what improves performance. m_pendingTimer.setInterval(500); connect(&m_pendingTimer, SIGNAL(timeout()), this, SLOT(processPending())); m_textEditForAccessibilityUpdateHandler = m_ui.eventListView; checkStateChanged(); // We need to wait for a11y to be active for this hack. QTimer::singleShot(500, this, SLOT(installUpdateHandler())); } void EventsWidget::installUpdateHandler() { m_originalAccessibilityUpdateHandler = QAccessible::installUpdateHandler(customUpdateHandler); if (!m_originalAccessibilityUpdateHandler) QTimer::singleShot(500, this, SLOT(installUpdateHandler())); } #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) void EventsWidget::customUpdateHandler(QAccessibleEvent *event) { QObject *object = event->object(); #else void EventsWidget::customUpdateHandler(QObject *object, int who, QAccessible::Event reason) { #endif if (object == m_textEditForAccessibilityUpdateHandler) return; //if (m_originalAccessibilityUpdateHandler) // m_originalAccessibilityUpdateHandler(object, who, reason); } QString EventsWidget::eventName(EventType eventType) const { QString s; switch (eventType) { case EventsWidget::Focus: s = QLatin1String("Focus"); break; case EventsWidget::StateChanged: s = QLatin1String("State"); break; case EventsWidget::NameChanged: s = QLatin1String("Name"); break; case EventsWidget::DescriptionChanged: s = QLatin1String("Description"); break; case EventsWidget::Window: s = QLatin1String("Window"); break; case EventsWidget::Document: s = QLatin1String("Document"); break; case EventsWidget::Object: s = QLatin1String("Object"); break; case EventsWidget::Text: s = QLatin1String("Text"); break; case EventsWidget::Table: s = QLatin1String("Table"); break; case EventsWidget::Others: s = QLatin1String("Others"); break; } return s; } void EventsWidget::loadSettings(QSettings &settings) { settings.beginGroup("events"); bool eventsFilterOk; EventTypes eventsFilter = EventTypes(settings.value("eventsFiler").toInt(&eventsFilterOk)); if (!eventsFilterOk) eventsFilter = AllEvents; QAbstractItemModel *model = m_ui.filterComboBox->model(); if (eventsFilter != m_proxyModel->filter()) { for (int i = 1; i < model->rowCount(); ++i) { QModelIndex index = model->index(i, 0); EventType type = model->data(index, EventsModel::EventTypeRole).value<EventType>(); if (eventsFilter.testFlag(type)) model->setData(index, Qt::Checked, Qt::CheckStateRole); else model->setData(index, Qt::Unchecked, Qt::CheckStateRole); } m_proxyModel->setFilter(eventsFilter); } settings.endGroup(); } void EventsWidget::saveSettings(QSettings &settings) { settings.beginGroup("events"); settings.setValue("eventsFiler", int(m_proxyModel->filter())); settings.endGroup(); } void EventsWidget::clearLog() { m_model->clearLog(); } void EventsWidget::processPending() { m_pendingTimer.stop(); QVector< QList<QStandardItem*> > pendingLogs = m_pendingLogs; m_pendingLogs.clear(); //bool wasMax = true;//m_ui.eventListView->verticalScrollBar()->value() - 10 >= m_ui.eventListView->verticalScrollBar()->maximum(); QStandardItem *lastItem = 0; QStandardItem *lastAppItem = 0; for(int i = 0; i < pendingLogs.count(); ++i) { QList<QStandardItem*> item = pendingLogs[i]; EventsModel::LogItem logItem = m_model->addLog(item); // Logic to scroll to the last added logItem of the last appItem that is expanded. // For appItem's not expanded the logItem is added but no scrolling will happen. if (lastItem && lastAppItem && lastAppItem != logItem.appItem) lastItem = 0; bool selected = lastItem; if (lastAppItem != logItem.appItem) { lastAppItem = logItem.appItem; QModelIndex index = m_proxyModel->mapFromSource(m_model->indexFromItem(logItem.appItem)); if (logItem.isNewAppItem) { m_ui.eventListView->setExpanded(index, true); selected = true; } else { selected = m_ui.eventListView->isExpanded(index); } } if (selected) lastItem = item.first(); } if (lastItem) { // scroll down to the lastItem. //m_ui.eventListView->verticalScrollBar()->setValue(m_ui.eventListView->verticalScrollBar()->maximum()); QModelIndex index = m_proxyModel->mapFromSource(m_model->indexFromItem(lastItem)); m_ui.eventListView->scrollTo(index, QAbstractItemView::PositionAtBottom); //m_ui.eventListView->scrollTo(index, QAbstractItemView::EnsureVisible); } } void EventsWidget::addLog(const QAccessibleClient::AccessibleObject &object, EventsWidget::EventType eventType, const QString &text) { if (!object.isValid()) return; // if (object.name() == m_ui.eventListView->accessibleName() && object.description() == m_ui.eventListView->accessibleDescription()) // return; QStandardItem *nameItem = new QStandardItem(object.name()); nameItem->setData(QVariant::fromValue<EventType>(eventType), EventsModel::EventTypeRole); nameItem->setData(m_registry->url(object).toString(), EventsModel::UrlRole); AccessibleObject app = object.application(); nameItem->setData(app.isValid() ? app.name() : QString(), EventsModel::AppNameRole); QStandardItem *roleItem = new QStandardItem(object.roleName()); QStandardItem *typeItem = new QStandardItem(eventName(eventType)); QStandardItem *textItem = new QStandardItem(text); m_pendingLogs.append(QList<QStandardItem*>() << nameItem << roleItem << typeItem << textItem); if (!m_pendingTimer.isActive()) { m_pendingTimer.start(); } } void EventsWidget::checkStateChanged() { EventTypes types; QStringList names; bool allEvents = true; QMetaEnum e = metaObject()->enumerator(metaObject()->indexOfEnumerator("EventType")); Q_ASSERT(e.isValid()); QAbstractItemModel *model = m_ui.filterComboBox->model(); for (int i = 1; i < model->rowCount(); ++i) { QModelIndex index = model->index(i, 0); bool checked = model->data(index, Qt::CheckStateRole).toBool(); if (checked) { EventType type = model->data(index, EventsModel::EventTypeRole).value<EventType>(); types |= type; names.append(QString::fromLatin1(e.valueToKey(type))); } else { allEvents = false; } } m_proxyModel->setFilter(types); } void EventsWidget::eventActivated(const QModelIndex &index) { Q_ASSERT(index.isValid()); EventsProxyModel *proxyModel = dynamic_cast<EventsProxyModel*>(m_ui.eventListView->model()); Q_ASSERT(proxyModel); QModelIndex firstIndex = proxyModel->index(index.row(), 0, index.parent()); QString s = proxyModel->data(firstIndex, EventsModel::UrlRole).toString(); QUrl url(s); if (!url.isValid()) { qWarning() << Q_FUNC_INFO << "Invalid url=" << s; return; } emit anchorClicked(url); } void EventsWidget::accessibleFilterChanged() { m_proxyModel->setAccessibleFilter(m_ui.accessibleFilterEdit->text()); } void EventsWidget::roleFilterChanged() { m_proxyModel->setRoleFilter(m_ui.roleFilterEdit->text()); } <|endoftext|>
<commit_before>/** * @file * * @brief * * @copyright BSD License (see doc/COPYING or http://www.libelektra.org) */ #include <tests.hpp> #include <vector> #include <string> #include <stdexcept> TEST(meta, basic) { cout << "testing metainfo" << endl; Key test; succeed_if (test.hasMeta("mode") == false, "has meta?"); succeed_if (test.getMeta<mode_t>("mode") == 0, "not properly default constructed"); test.setMeta<mode_t>("mode", 0775); succeed_if (test.hasMeta("mode") == true, "has not meta even though set?"); succeed_if (test.getMeta<mode_t>("mode") == 0775, "not correct default mode for dir"); test.setMeta<int>("myint", 333); succeed_if (test.getMeta<int>("myint") == 333, "could not set other meta"); test.setMeta<double>("mydouble", 333.3); succeed_if (test.hasMeta("mydouble"), "no meta data even though it was just set"); succeed_if (test.getMeta<double>("mydouble") >= 333.2, "could not set other meta"); succeed_if (test.getMeta<double>("mydouble") <= 333.4, "could not set other meta"); test.delMeta("mydouble"); succeed_if (!test.hasMeta("mydouble"), "meta data there even though it was just deleted"); test.setMeta<std::string>("mystr", "str"); succeed_if (test.getMeta<std::string>("mystr") == "str", "could not set other meta"); const ckdb::Key *cmeta = test.getMeta<const ckdb::Key*>("mystr"); succeed_if (!strcmp(static_cast<const char*>(ckdb::keyValue(cmeta)), "str"), "could not set other meta"); const ckdb::Key *nmeta = test.getMeta<const ckdb::Key*>("not available"); succeed_if (nmeta == nullptr, "not available meta data did not give a null pointer"); const Key meta = test.getMeta<const Key>("mystr"); succeed_if (meta, "null key"); succeed_if (meta.getString() == "str", "could not get other meta"); const Key xmeta = test.getMeta<const Key>("not available"); succeed_if (!xmeta, "not a null key"); const char * str = test.getMeta<const char*>("mystr"); succeed_if (!strcmp(str, "str"), "could not get meta as c-string"); const char * nstr = test.getMeta<const char*>("not available"); succeed_if (nstr == nullptr, "did not get null pointer on not available meta data"); succeed_if (test.getMeta<int>("not available") == 0, "not default constructed"); succeed_if (test.getMeta<std::string>("not available") == "", "not default constructed"); test.setMeta<std::string>("wrong", "not an int"); try { succeed_if (test.hasMeta("wrong") == true, "meta is here"); test.getMeta<int>("wrong"); succeed_if (0, "exception did not raise"); } catch (KeyTypeConversion const& e) { succeed_if (1, "no such meta data"); } } TEST(meta, iter) { // clang-format on Key k ("user/metakey", KEY_META, "a", "meta", KEY_META, "b", "my", KEY_META, "c", "other", KEY_END); // clang-format off Key meta; //key = keyNew(0) succeed_if (meta, "key is a not null key"); Key end = static_cast<ckdb::Key*>(nullptr); // key = 0 succeed_if (!end, "key is a null key"); int count = 0; k.rewindMeta(); while ((meta = k.nextMeta())) count ++; succeed_if (count == 3, "Not the correct number of meta data"); k.setMeta("d", "more"); k.setMeta("e", "even more"); count = 0; k.rewindMeta(); while ((meta = k.nextMeta())) count ++; succeed_if (count == 5, "Not the correct number of meta data"); } TEST(test, copy) { cout << "testing copy meta" << std::endl; Key k ("user/metakey", KEY_META, "", "meta value", KEY_META, "a", "a meta value", KEY_META, "b", "b meta value", KEY_META, "c", "c meta value", KEY_END); Key c; c.copyMeta(k, "a"); succeed_if (k.getMeta<const ckdb::Key*>("a") == c.getMeta<const ckdb::Key*>("a"), "copy meta did not work"); c.copyMeta(k, ""); succeed_if (k.getMeta<const ckdb::Key*>("") == c.getMeta<const ckdb::Key*>(""), "copy meta did not work"); k.setMeta<int>("a", 420); succeed_if (k.getMeta<int>("a") == 420, "could not get value set before"); c.copyMeta(k, "a"); succeed_if (c.getMeta<int>("a") == 420, "could not get value copied before"); succeed_if (k.getMeta<const ckdb::Key*>("a") == c.getMeta<const ckdb::Key*>("a"), "copy meta did not work"); c.copyMeta(k, "a"); succeed_if (c.getMeta<int>("a") == 420, "could not get value copied before (again)"); succeed_if (k.getMeta<const ckdb::Key*>("a") == c.getMeta<const ckdb::Key*>("a"), "copy meta did not work (again)"); Key d; Key meta; k.rewindMeta(); while ((meta = k.nextMeta())) { d.copyMeta(k, meta.getName()); } succeed_if (d.getMeta<std::string>("a") == "420", "did not copy meta value in the loop"); succeed_if (d.getMeta<const ckdb::Key*>("a") == d.getMeta<const ckdb::Key*>("a"), "copy meta did not work in the loop"); succeed_if (d.getMeta<std::string>("") == "meta value", "did not copy meta value in the loop"); succeed_if (d.getMeta<const ckdb::Key*>("") == d.getMeta<const ckdb::Key*>(""), "copy meta did not work in the loop"); succeed_if (d.getMeta<std::string>("b") == "b meta value", "did not copy meta value in the loop"); succeed_if (d.getMeta<const ckdb::Key*>("b") == d.getMeta<const ckdb::Key*>("b"), "copy meta did not work in the loop"); succeed_if (d.getMeta<std::string>("c") == "c meta value", "did not copy meta value in the loop"); succeed_if (d.getMeta<const ckdb::Key*>("c") == d.getMeta<const ckdb::Key*>("c"), "copy meta did not work in the loop"); } TEST(meta, string) { Key k("user/anything", KEY_META, "", "meta value", KEY_META, "a", "a meta value", KEY_META, "b", "b meta value", KEY_META, "c", "c meta value", KEY_END); succeed_if (k.getMeta<string>("a") == "a meta value", "could not get meta value"); Key m = k.getMeta<const Key> ("a"); succeed_if (m, "could not get meta key"); succeed_if (m.getString() == "a meta value", "could not get meta string"); Key m1 = k.getMeta<const Key> ("x"); succeed_if (!m1, "got not existing meta key"); } TEST(meta, copyAll) { Key k ("user/metakey", KEY_META, "", "meta value", KEY_META, "a", "a meta value", KEY_META, "b", "b meta value", KEY_META, "c", "c meta value", KEY_META, "i", "420", KEY_END); Key c; c.copyAllMeta(k); succeed_if (c.getMeta<const ckdb::Key*>("a") == c.getMeta<const ckdb::Key*>("a"), "copy meta did not work"); succeed_if (c.getMeta<const ckdb::Key*>("") == c.getMeta<const ckdb::Key*>(""), "copy meta did not work"); succeed_if (c.getMeta<int>("i") == 420, "could not get value copied before"); succeed_if (c.getMeta<std::string>("i") == "420", "did not copy meta value in the loop"); succeed_if (c.getMeta<const ckdb::Key*>("a") == c.getMeta<const ckdb::Key*>("a"), "copy meta did not work"); Key d; d.copyAllMeta(k); succeed_if (d.getMeta<std::string>("i") == "420", "did not copy meta value in the loop"); succeed_if (d.getMeta<int>("i") == 420, "could not get value copied before"); succeed_if (k.getMeta<const ckdb::Key*>("a") == d.getMeta<const ckdb::Key*>("a"), "copy meta did not work in the loop"); succeed_if (d.getMeta<std::string>("") == "meta value", "did not copy meta value in the loop"); succeed_if (k.getMeta<const ckdb::Key*>("") == d.getMeta<const ckdb::Key*>(""), "copy meta did not work in the loop"); succeed_if (d.getMeta<std::string>("b") == "b meta value", "did not copy meta value in the loop"); succeed_if (k.getMeta<const ckdb::Key*>("b") == d.getMeta<const ckdb::Key*>("b"), "copy meta did not work in the loop"); succeed_if (d.getMeta<std::string>("c") == "c meta value", "did not copy meta value in the loop"); succeed_if (k.getMeta<const ckdb::Key*>("c") == d.getMeta<const ckdb::Key*>("c"), "copy meta did not work in the loop"); } <commit_msg>fix wrong on/off<commit_after>/** * @file * * @brief * * @copyright BSD License (see doc/COPYING or http://www.libelektra.org) */ #include <tests.hpp> #include <stdexcept> #include <string> #include <vector> TEST (meta, basic) { cout << "testing metainfo" << endl; Key test; succeed_if (test.hasMeta ("mode") == false, "has meta?"); succeed_if (test.getMeta<mode_t> ("mode") == 0, "not properly default constructed"); test.setMeta<mode_t> ("mode", 0775); succeed_if (test.hasMeta ("mode") == true, "has not meta even though set?"); succeed_if (test.getMeta<mode_t> ("mode") == 0775, "not correct default mode for dir"); test.setMeta<int> ("myint", 333); succeed_if (test.getMeta<int> ("myint") == 333, "could not set other meta"); test.setMeta<double> ("mydouble", 333.3); succeed_if (test.hasMeta ("mydouble"), "no meta data even though it was just set"); succeed_if (test.getMeta<double> ("mydouble") >= 333.2, "could not set other meta"); succeed_if (test.getMeta<double> ("mydouble") <= 333.4, "could not set other meta"); test.delMeta ("mydouble"); succeed_if (!test.hasMeta ("mydouble"), "meta data there even though it was just deleted"); test.setMeta<std::string> ("mystr", "str"); succeed_if (test.getMeta<std::string> ("mystr") == "str", "could not set other meta"); const ckdb::Key * cmeta = test.getMeta<const ckdb::Key *> ("mystr"); succeed_if (!strcmp (static_cast<const char *> (ckdb::keyValue (cmeta)), "str"), "could not set other meta"); const ckdb::Key * nmeta = test.getMeta<const ckdb::Key *> ("not available"); succeed_if (nmeta == nullptr, "not available meta data did not give a null pointer"); const Key meta = test.getMeta<const Key> ("mystr"); succeed_if (meta, "null key"); succeed_if (meta.getString () == "str", "could not get other meta"); const Key xmeta = test.getMeta<const Key> ("not available"); succeed_if (!xmeta, "not a null key"); const char * str = test.getMeta<const char *> ("mystr"); succeed_if (!strcmp (str, "str"), "could not get meta as c-string"); const char * nstr = test.getMeta<const char *> ("not available"); succeed_if (nstr == nullptr, "did not get null pointer on not available meta data"); succeed_if (test.getMeta<int> ("not available") == 0, "not default constructed"); succeed_if (test.getMeta<std::string> ("not available") == "", "not default constructed"); test.setMeta<std::string> ("wrong", "not an int"); try { succeed_if (test.hasMeta ("wrong") == true, "meta is here"); test.getMeta<int> ("wrong"); succeed_if (0, "exception did not raise"); } catch (KeyTypeConversion const & e) { succeed_if (1, "no such meta data"); } } TEST (meta, iter) { // clang-format off Key k ("user/metakey", KEY_META, "a", "meta", KEY_META, "b", "my", KEY_META, "c", "other", KEY_END); // clang-format on Key meta; // key = keyNew(0) succeed_if (meta, "key is a not null key"); Key end = static_cast<ckdb::Key *> (nullptr); // key = 0 succeed_if (!end, "key is a null key"); int count = 0; k.rewindMeta (); while ((meta = k.nextMeta ())) count++; succeed_if (count == 3, "Not the correct number of meta data"); k.setMeta ("d", "more"); k.setMeta ("e", "even more"); count = 0; k.rewindMeta (); while ((meta = k.nextMeta ())) count++; succeed_if (count == 5, "Not the correct number of meta data"); } TEST (test, copy) { cout << "testing copy meta" << std::endl; Key k ("user/metakey", KEY_META, "", "meta value", KEY_META, "a", "a meta value", KEY_META, "b", "b meta value", KEY_META, "c", "c meta value", KEY_END); Key c; c.copyMeta (k, "a"); succeed_if (k.getMeta<const ckdb::Key *> ("a") == c.getMeta<const ckdb::Key *> ("a"), "copy meta did not work"); c.copyMeta (k, ""); succeed_if (k.getMeta<const ckdb::Key *> ("") == c.getMeta<const ckdb::Key *> (""), "copy meta did not work"); k.setMeta<int> ("a", 420); succeed_if (k.getMeta<int> ("a") == 420, "could not get value set before"); c.copyMeta (k, "a"); succeed_if (c.getMeta<int> ("a") == 420, "could not get value copied before"); succeed_if (k.getMeta<const ckdb::Key *> ("a") == c.getMeta<const ckdb::Key *> ("a"), "copy meta did not work"); c.copyMeta (k, "a"); succeed_if (c.getMeta<int> ("a") == 420, "could not get value copied before (again)"); succeed_if (k.getMeta<const ckdb::Key *> ("a") == c.getMeta<const ckdb::Key *> ("a"), "copy meta did not work (again)"); Key d; Key meta; k.rewindMeta (); while ((meta = k.nextMeta ())) { d.copyMeta (k, meta.getName ()); } succeed_if (d.getMeta<std::string> ("a") == "420", "did not copy meta value in the loop"); succeed_if (d.getMeta<const ckdb::Key *> ("a") == d.getMeta<const ckdb::Key *> ("a"), "copy meta did not work in the loop"); succeed_if (d.getMeta<std::string> ("") == "meta value", "did not copy meta value in the loop"); succeed_if (d.getMeta<const ckdb::Key *> ("") == d.getMeta<const ckdb::Key *> (""), "copy meta did not work in the loop"); succeed_if (d.getMeta<std::string> ("b") == "b meta value", "did not copy meta value in the loop"); succeed_if (d.getMeta<const ckdb::Key *> ("b") == d.getMeta<const ckdb::Key *> ("b"), "copy meta did not work in the loop"); succeed_if (d.getMeta<std::string> ("c") == "c meta value", "did not copy meta value in the loop"); succeed_if (d.getMeta<const ckdb::Key *> ("c") == d.getMeta<const ckdb::Key *> ("c"), "copy meta did not work in the loop"); } TEST (meta, string) { Key k ("user/anything", KEY_META, "", "meta value", KEY_META, "a", "a meta value", KEY_META, "b", "b meta value", KEY_META, "c", "c meta value", KEY_END); succeed_if (k.getMeta<string> ("a") == "a meta value", "could not get meta value"); Key m = k.getMeta<const Key> ("a"); succeed_if (m, "could not get meta key"); succeed_if (m.getString () == "a meta value", "could not get meta string"); Key m1 = k.getMeta<const Key> ("x"); succeed_if (!m1, "got not existing meta key"); } TEST (meta, copyAll) { Key k ("user/metakey", KEY_META, "", "meta value", KEY_META, "a", "a meta value", KEY_META, "b", "b meta value", KEY_META, "c", "c meta value", KEY_META, "i", "420", KEY_END); Key c; c.copyAllMeta (k); succeed_if (c.getMeta<const ckdb::Key *> ("a") == c.getMeta<const ckdb::Key *> ("a"), "copy meta did not work"); succeed_if (c.getMeta<const ckdb::Key *> ("") == c.getMeta<const ckdb::Key *> (""), "copy meta did not work"); succeed_if (c.getMeta<int> ("i") == 420, "could not get value copied before"); succeed_if (c.getMeta<std::string> ("i") == "420", "did not copy meta value in the loop"); succeed_if (c.getMeta<const ckdb::Key *> ("a") == c.getMeta<const ckdb::Key *> ("a"), "copy meta did not work"); Key d; d.copyAllMeta (k); succeed_if (d.getMeta<std::string> ("i") == "420", "did not copy meta value in the loop"); succeed_if (d.getMeta<int> ("i") == 420, "could not get value copied before"); succeed_if (k.getMeta<const ckdb::Key *> ("a") == d.getMeta<const ckdb::Key *> ("a"), "copy meta did not work in the loop"); succeed_if (d.getMeta<std::string> ("") == "meta value", "did not copy meta value in the loop"); succeed_if (k.getMeta<const ckdb::Key *> ("") == d.getMeta<const ckdb::Key *> (""), "copy meta did not work in the loop"); succeed_if (d.getMeta<std::string> ("b") == "b meta value", "did not copy meta value in the loop"); succeed_if (k.getMeta<const ckdb::Key *> ("b") == d.getMeta<const ckdb::Key *> ("b"), "copy meta did not work in the loop"); succeed_if (d.getMeta<std::string> ("c") == "c meta value", "did not copy meta value in the loop"); succeed_if (k.getMeta<const ckdb::Key *> ("c") == d.getMeta<const ckdb::Key *> ("c"), "copy meta did not work in the loop"); } <|endoftext|>
<commit_before>// Copyright (C) 2014 Jérôme Leclercq // This file is part of the "Nazara Engine - Renderer module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Renderer/UberShaderPreprocessor.hpp> #include <Nazara/Core/ErrorFlags.hpp> #include <Nazara/Core/File.hpp> #include <Nazara/Renderer/OpenGL.hpp> #include <algorithm> #include <memory> #include <Nazara/Renderer/Debug.hpp> NzUberShaderInstance* NzUberShaderPreprocessor::Get(const NzParameterList& parameters) const { // Première étape, transformer les paramètres en un flag nzUInt32 flags = 0; for (auto it = m_flags.begin(); it != m_flags.end(); ++it) { if (parameters.HasParameter(it->first)) { bool value; if (parameters.GetBooleanParameter(it->first, &value) && value) flags |= it->second; } } // Le shader fait-il partie du cache ? auto shaderIt = m_cache.find(flags); // Si non, il nous faut le construire if (shaderIt == m_cache.end()) { try { NzErrorFlags errFlags(nzErrorFlag_Silent | nzErrorFlag_ThrowException); std::unique_ptr<NzShader> shader(new NzShader); shader->Create(); for (unsigned int i = 0; i <= nzShaderStage_Max; ++i) { const Shader& shaderStage = m_shaders[i]; if (shaderStage.present) { nzUInt32 stageFlags = 0; for (auto it = shaderStage.flags.begin(); it != shaderStage.flags.end(); ++it) { if (parameters.HasParameter(it->first)) { bool value; if (parameters.GetBooleanParameter(it->first, &value) && value) stageFlags |= it->second; } } auto stageIt = shaderStage.cache.find(stageFlags); if (stageIt == shaderStage.cache.end()) { NzShaderStage stage; stage.Create(static_cast<nzShaderStage>(i)); unsigned int glslVersion = NzOpenGL::GetGLSLVersion(); NzStringStream code; code << "#version " << glslVersion << "\n\n"; code << "#define GLSL_VERSION " << glslVersion << "\n\n"; code << "#define EARLY_FRAGMENT_TEST " << (glslVersion >= 420 || NzOpenGL::IsSupported(nzOpenGLExtension_Shader_ImageLoadStore)) << "\n\n"; for (auto it = shaderStage.flags.begin(); it != shaderStage.flags.end(); ++it) code << "#define " << it->first << ' ' << ((stageFlags & it->second) ? '1' : '0') << '\n'; code << "\n#line 1\n"; code << shaderStage.source; stage.SetSource(code); stage.Compile(); shader->AttachStage(static_cast<nzShaderStage>(i), stage); shaderStage.cache.emplace(flags, std::move(stage)); } else shader->AttachStage(static_cast<nzShaderStage>(i), stageIt->second); } } shader->Link(); auto pair = m_cache.emplace(flags, shader.get()); shader.release(); return &(pair.first)->second; } catch (const std::exception& e) { NzErrorFlags errFlags(nzErrorFlag_ThrowExceptionDisabled); NazaraError("Failed to build uber shader instance: " + NzError::GetLastError()); throw; } } else return &shaderIt->second; } void NzUberShaderPreprocessor::SetShader(nzShaderStage stage, const NzString& source, const NzString& flagString) { Shader& shader = m_shaders[stage]; shader.present = true; shader.source = source; std::vector<NzString> flags; flagString.Split(flags, ' '); for (NzString& flag : flags) { auto it = m_flags.find(flag); if (it == m_flags.end()) m_flags[flag] = 1U << m_flags.size(); auto it2 = shader.flags.find(flag); if (it2 == shader.flags.end()) shader.flags[flag] = 1U << shader.flags.size(); } } bool NzUberShaderPreprocessor::SetShaderFromFile(nzShaderStage stage, const NzString& filePath, const NzString& flags) { NzFile file(filePath); if (!file.Open(NzFile::ReadOnly | NzFile::Text)) { NazaraError("Failed to open \"" + filePath + '"'); return false; } unsigned int length = static_cast<unsigned int>(file.GetSize()); NzString source(length, '\0'); if (file.Read(&source[0], length) != length) { NazaraError("Failed to read program file"); return false; } file.Close(); SetShader(stage, source, flags); return true; } <commit_msg>Added UberShaderPreprocessor::IsSupported "implementation"<commit_after>// Copyright (C) 2014 Jérôme Leclercq // This file is part of the "Nazara Engine - Renderer module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Renderer/UberShaderPreprocessor.hpp> #include <Nazara/Core/ErrorFlags.hpp> #include <Nazara/Core/File.hpp> #include <Nazara/Renderer/OpenGL.hpp> #include <algorithm> #include <memory> #include <Nazara/Renderer/Debug.hpp> NzUberShaderInstance* NzUberShaderPreprocessor::Get(const NzParameterList& parameters) const { // Première étape, transformer les paramètres en un flag nzUInt32 flags = 0; for (auto it = m_flags.begin(); it != m_flags.end(); ++it) { if (parameters.HasParameter(it->first)) { bool value; if (parameters.GetBooleanParameter(it->first, &value) && value) flags |= it->second; } } // Le shader fait-il partie du cache ? auto shaderIt = m_cache.find(flags); // Si non, il nous faut le construire if (shaderIt == m_cache.end()) { try { NzErrorFlags errFlags(nzErrorFlag_Silent | nzErrorFlag_ThrowException); std::unique_ptr<NzShader> shader(new NzShader); shader->Create(); for (unsigned int i = 0; i <= nzShaderStage_Max; ++i) { const Shader& shaderStage = m_shaders[i]; if (shaderStage.present) { nzUInt32 stageFlags = 0; for (auto it = shaderStage.flags.begin(); it != shaderStage.flags.end(); ++it) { if (parameters.HasParameter(it->first)) { bool value; if (parameters.GetBooleanParameter(it->first, &value) && value) stageFlags |= it->second; } } auto stageIt = shaderStage.cache.find(stageFlags); if (stageIt == shaderStage.cache.end()) { NzShaderStage stage; stage.Create(static_cast<nzShaderStage>(i)); unsigned int glslVersion = NzOpenGL::GetGLSLVersion(); NzStringStream code; code << "#version " << glslVersion << "\n\n"; code << "#define GLSL_VERSION " << glslVersion << "\n\n"; code << "#define EARLY_FRAGMENT_TEST " << (glslVersion >= 420 || NzOpenGL::IsSupported(nzOpenGLExtension_Shader_ImageLoadStore)) << "\n\n"; for (auto it = shaderStage.flags.begin(); it != shaderStage.flags.end(); ++it) code << "#define " << it->first << ' ' << ((stageFlags & it->second) ? '1' : '0') << '\n'; code << "\n#line 1\n"; code << shaderStage.source; stage.SetSource(code); stage.Compile(); shader->AttachStage(static_cast<nzShaderStage>(i), stage); shaderStage.cache.emplace(flags, std::move(stage)); } else shader->AttachStage(static_cast<nzShaderStage>(i), stageIt->second); } } shader->Link(); auto pair = m_cache.emplace(flags, shader.get()); shader.release(); return &(pair.first)->second; // On retourne l'objet construit } catch (const std::exception& e) { NzErrorFlags errFlags(nzErrorFlag_ThrowExceptionDisabled); NazaraError("Failed to build uber shader instance: " + NzError::GetLastError()); throw; } } else return &shaderIt->second; } void NzUberShaderPreprocessor::SetShader(nzShaderStage stage, const NzString& source, const NzString& flagString) { Shader& shader = m_shaders[stage]; shader.present = true; shader.source = source; std::vector<NzString> flags; flagString.Split(flags, ' '); for (NzString& flag : flags) { auto it = m_flags.find(flag); if (it == m_flags.end()) m_flags[flag] = 1U << m_flags.size(); auto it2 = shader.flags.find(flag); if (it2 == shader.flags.end()) shader.flags[flag] = 1U << shader.flags.size(); } } bool NzUberShaderPreprocessor::SetShaderFromFile(nzShaderStage stage, const NzString& filePath, const NzString& flags) { NzFile file(filePath); if (!file.Open(NzFile::ReadOnly | NzFile::Text)) { NazaraError("Failed to open \"" + filePath + '"'); return false; } unsigned int length = static_cast<unsigned int>(file.GetSize()); NzString source(length, '\0'); if (file.Read(&source[0], length) != length) { NazaraError("Failed to read program file"); return false; } file.Close(); SetShader(stage, source, flags); return true; } bool NzUberShaderPreprocessor::IsSupported() { return true; // Forcément supporté } <|endoftext|>
<commit_before>/* The OpenTRV project licenses this file to you under the Apache Licence, Version 2.0 (the "Licence"); you may not use this file except in compliance with the Licence. You may obtain a copy of the Licence at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licence for the specific language governing permissions and limitations under the Licence. Author(s) / Copyright (s): Deniz Erbilgin 2017 */ #include <gtest/gtest.h> #include <stdio.h> #include <stdlib.h> #include <OTRadioLink.h> namespace OTFHT { uint8_t minuteCount = 0; static constexpr uint8_t heatCallPin = 0; // unused in unit tests. OTRadioLink::OTNullRadioLink rt; OTRadValve::BoilerCallForHeat<heatCallPin> b0; } // // Basic sanity/does it compile tests // TEST(FrameHandlerTest, OTSerialHandlerTest) // { // // TODO write test (need print object) // } TEST(FrameHandlerTest, OTRadioHandlerTest) { // Instantiate objects OTRadioLink::OTRadioHandler<decltype(OTFHT::rt), OTFHT::rt> rh; // message const uint8_t msgBuf[5] = {0,1,2,3,4}; const char decryptedBuf[] = "hello"; auto bufPtr = (const uint8_t * const) &decryptedBuf[1]; const auto result = rh.frameHandler(msgBuf, bufPtr, sizeof(decryptedBuf) - 1); EXPECT_FALSE(result); } TEST(FrameHandlerTest, OTBoilerHandlerTest) { // Instantiate objects OTRadioLink::OTBoilerHandler<decltype(OTFHT::b0), OTFHT::b0, OTFHT::minuteCount> bh; // message const uint8_t msgBuf[5] = {0,1,2,3,4}; const char decryptedBuf[] = "hello"; auto bufPtr = (const uint8_t * const) &decryptedBuf[1]; const auto result = bh.frameHandler(msgBuf, bufPtr, sizeof(decryptedBuf) - 1); EXPECT_TRUE(result); } // TEST(FrameHandlerTest, NullHandlerTest) // { // const char msg[] = "hello"; // EXPECT_FALSE(OTRadioLink::decodeAndHandleNullFrame((const uint8_t *)msg)); // } <commit_msg>more unit tests<commit_after>/* The OpenTRV project licenses this file to you under the Apache Licence, Version 2.0 (the "Licence"); you may not use this file except in compliance with the Licence. You may obtain a copy of the Licence at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licence for the specific language governing permissions and limitations under the Licence. Author(s) / Copyright (s): Deniz Erbilgin 2017 */ #include <gtest/gtest.h> #include <stdio.h> #include <stdlib.h> #include <OTRadioLink.h> namespace OTFHT { uint8_t minuteCount = 0; static constexpr uint8_t heatCallPin = 0; // unused in unit tests. OTRadioLink::OTNullRadioLink rt; OTRadValve::BoilerCallForHeat<heatCallPin> b0; class NULLSerialStream final : public Stream { public: static bool verbose; void begin(unsigned long) { } void begin(unsigned long, uint8_t); void end(); virtual size_t write(uint8_t c) override { if(verbose) { fprintf(stderr, "%c\n", (char) c); } return(0); } virtual size_t write(const uint8_t *buf, size_t size) override { size_t n = 0; while((size-- > 0) && (0 != write(*buf++))) { ++n; } return(n); } virtual int available() override { return(-1); } virtual int read() override { return(-1); } virtual int peek() override { return(-1); } virtual void flush() override { } }; bool NULLSerialStream::verbose = false; // Instantiate objects NULLSerialStream ss; } // Basic sanity/does it compile tests TEST(FrameHandlerTest, OTFrameDataTest) { // message // msg buf consists of { len | Message } const uint8_t msgBuf[6] = { 5, 0,1,2,3,4 }; const uint8_t nodeID[OTV0P2BASE::OpenTRV_Node_ID_Bytes] = {1, 2, 3, 4, 5, 6, 7, 8}; const uint8_t decrypted[] = "hello"; OTRadioLink::OTFrameData_T fd(&msgBuf[1]); EXPECT_EQ(sizeof(fd.senderNodeID), OTV0P2BASE::OpenTRV_Node_ID_Bytes); EXPECT_EQ(sizeof(fd.decryptedBody), OTRadioLink::ENC_BODY_SMALL_FIXED_PTEXT_MAX_SIZE); memcpy(fd.senderNodeID, nodeID, sizeof(nodeID)); memcpy(fd.decryptedBody, decrypted, sizeof(decrypted)); fd.decryptedBodyLen = sizeof(decrypted); EXPECT_EQ(5, fd.msg[-1]); EXPECT_EQ(sizeof(decrypted), fd.decryptedBodyLen); } // Minimum valid Frame TEST(FrameHandlerTest, OTSerialHandlerTestTrue) { OTFHT::NULLSerialStream::verbose = false; // Instantiate objects OTRadioLink::OTSerialHandler<decltype(OTFHT::ss), OTFHT::ss> sh; // message // msg buf consists of { len | Message } const uint8_t msgBuf[] = { 5, 0,1,2,3,4 }; const uint8_t nodeID[OTV0P2BASE::OpenTRV_Node_ID_Bytes] = {1, 2, 3, 4, 5, 6, 7, 8}; const uint8_t decrypted[] = { 'a', 0x10, '{', 'b', 'c'}; OTRadioLink::OTFrameData_T fd(&msgBuf[1]); memcpy(fd.senderNodeID, nodeID, sizeof(nodeID)); memcpy(fd.decryptedBody, decrypted, sizeof(decrypted)); fd.decryptedBodyLen = sizeof(decrypted); EXPECT_TRUE(sh.frameHandler(fd)); } // Invalid Frame TEST(FrameHandlerTest, OTSerialHandlerTestFalse) { OTFHT::NULLSerialStream::verbose = false; // Instantiate objects OTRadioLink::OTSerialHandler<decltype(OTFHT::ss), OTFHT::ss> sh; // message // msg buf consists of { len | Message } const uint8_t msgBuf[6] = { 5, 0,1,3,4,5 }; const uint8_t nodeID[OTV0P2BASE::OpenTRV_Node_ID_Bytes] = {1, 2, 3, 4, 5, 6, 7, 8}; OTRadioLink::OTFrameData_T fd(&msgBuf[1]); memcpy(fd.senderNodeID, nodeID, sizeof(nodeID)); // Case (0 != (db[1] & 0x10) const uint8_t decrypted0[] = { 'a', 0x1, '{', 'b', 'c', 'd'}; memcpy(fd.decryptedBody, decrypted0, sizeof(decrypted0)); fd.decryptedBodyLen = sizeof(decrypted0); EXPECT_FALSE(sh.frameHandler(fd)); // Case (dbLen > 3) const uint8_t decrypted1[] = { 'a', 0x10, '{', 'b', 'c', 'd'}; memcpy(fd.decryptedBody, decrypted1, sizeof(decrypted1)); fd.decryptedBodyLen = 3; EXPECT_FALSE(sh.frameHandler(fd)); // Case ('{' == db[2]) const uint8_t decrypted2[] = { 'a', 0x10, 's', 'b', 'c', 'd'}; memcpy(fd.decryptedBody, decrypted2, sizeof(decrypted2)); fd.decryptedBodyLen = sizeof(decrypted2); EXPECT_FALSE(sh.frameHandler(fd)); } // Minimum valid Frame TEST(FrameHandlerTest, OTRadioHandlerTestTrue) { // Instantiate objects OTRadioLink::OTRadioHandler<decltype(OTFHT::rt), OTFHT::rt> rh; // message // msg buf consists of { len | Message } const uint8_t msgBuf[] = { 5, 0,1,2,3,4 }; const uint8_t nodeID[OTV0P2BASE::OpenTRV_Node_ID_Bytes] = {1, 2, 3, 4, 5, 6, 7, 8}; const uint8_t decrypted[] = { 'a', 0x10, '{', 'b', 'c'}; OTRadioLink::OTFrameData_T fd(&msgBuf[1]); memcpy(fd.senderNodeID, nodeID, sizeof(nodeID)); memcpy(fd.decryptedBody, decrypted, sizeof(decrypted)); fd.decryptedBodyLen = sizeof(decrypted); EXPECT_TRUE(rh.frameHandler(fd)); } // Invalid Frame TEST(FrameHandlerTest, OTRadioHandlerTestFalse) { // Instantiate objects OTRadioLink::OTRadioHandler<decltype(OTFHT::rt), OTFHT::rt> rh; // message // msg buf consists of { len | Message } const uint8_t msgBuf[6] = { 5, 0,1,3,4,5 }; const uint8_t nodeID[OTV0P2BASE::OpenTRV_Node_ID_Bytes] = {1, 2, 3, 4, 5, 6, 7, 8}; // Case nullptr const uint8_t decryptedValid[] = { 'a', 0x10, '{', 'b', 'c'}; OTRadioLink::OTFrameData_T fd0(nullptr); memcpy(fd0.senderNodeID, nodeID, sizeof(nodeID)); memcpy(fd0.decryptedBody, decryptedValid, sizeof(decryptedValid)); fd0.decryptedBodyLen = sizeof(decryptedValid); EXPECT_FALSE(rh.frameHandler(fd0)); // Other cases OTRadioLink::OTFrameData_T fd1(&msgBuf[1]); memcpy(fd1.senderNodeID, nodeID, sizeof(nodeID)); // Case (0 != (db[1] & 0x10) const uint8_t decrypted0[] = { 'a', 0x1, '{', 'b', 'c', 'd'}; memcpy(fd1.decryptedBody, decrypted0, sizeof(decrypted0)); fd1.decryptedBodyLen = sizeof(decrypted0); EXPECT_FALSE(rh.frameHandler(fd1)); // Case (dbLen > 3) const uint8_t decrypted1[] = { 'a', 0x10, '{', 'b', 'c', 'd'}; memcpy(fd1.decryptedBody, decrypted1, sizeof(decrypted1)); fd1.decryptedBodyLen = 3; EXPECT_FALSE(rh.frameHandler(fd1)); // Case ('{' == db[2]) const uint8_t decrypted2[] = { 'a', 0x10, 's', 'b', 'c', 'd'}; memcpy(fd1.decryptedBody, decrypted2, sizeof(decrypted2)); fd1.decryptedBodyLen = sizeof(decrypted2); EXPECT_FALSE(rh.frameHandler(fd1)); } TEST(FrameHandlerTest, OTBoilerHandlerTest) { // Instantiate objects OTRadioLink::OTBoilerHandler<decltype(OTFHT::b0), OTFHT::b0, OTFHT::minuteCount> bh; // message // msg buf consists of { len | Message } const uint8_t msgBuf[6] = { 5, 0,1,2,3,4 }; const uint8_t nodeID[OTV0P2BASE::OpenTRV_Node_ID_Bytes] = {1, 2, 3, 4, 5, 6, 7, 8}; const uint8_t decrypted[] = "hello"; OTRadioLink::OTFrameData_T fd(&msgBuf[1]); memcpy(fd.senderNodeID, nodeID, sizeof(nodeID)); memcpy(fd.decryptedBody, decrypted, sizeof(decrypted)); fd.decryptedBodyLen = sizeof(decrypted); const auto result = bh.frameHandler(fd); EXPECT_TRUE(result); } // More detailed Tests <|endoftext|>
<commit_before>/* * Copyright (C) 2018 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. */ #include "src/profiling/memory/socket_listener.h" #include "perfetto/base/scoped_file.h" #include "src/base/test/test_task_runner.h" #include "src/ipc/test/test_socket.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace perfetto { namespace profiling { namespace { using ::testing::_; using ::testing::InvokeWithoutArgs; constexpr char kSocketName[] = TEST_SOCK_NAME("socket_listener_unittest"); class SocketListenerTest : public ::testing::Test { protected: void SetUp() override { DESTROY_TEST_SOCK(kSocketName); } void TearDown() override { DESTROY_TEST_SOCK(kSocketName); } }; class MockEventListener : public base::UnixSocket::EventListener { public: MOCK_METHOD2(OnConnect, void(base::UnixSocket*, bool)); }; TEST_F(SocketListenerTest, ReceiveRecord) { base::TestTaskRunner task_runner; auto callback_called = task_runner.CreateCheckpoint("callback.called"); auto connected = task_runner.CreateCheckpoint("connected"); auto callback_fn = [&callback_called](UnwindingRecord r) { ASSERT_EQ(r.size, 1u); ASSERT_EQ(r.data[0], '1'); ASSERT_FALSE(r.metadata.expired()); callback_called(); }; BookkeepingThread bookkeeping_thread; SocketListener listener(std::move(callback_fn), &bookkeeping_thread); ProcessSetSpec spec{}; spec.pids.emplace(getpid()); auto handle = listener.process_matcher().AwaitProcessSetSpec(std::move(spec)); MockEventListener client_listener; EXPECT_CALL(client_listener, OnConnect(_, _)) .WillOnce(InvokeWithoutArgs(connected)); std::unique_ptr<base::UnixSocket> recv_socket = base::UnixSocket::Listen(kSocketName, &listener, &task_runner); std::unique_ptr<base::UnixSocket> client_socket = base::UnixSocket::Connect(kSocketName, &client_listener, &task_runner); task_runner.RunUntilCheckpoint("connected"); uint64_t size = 1; base::ScopedFile fds[2] = { base::ScopedFile(base::OpenFile("/dev/null", O_RDONLY)), base::ScopedFile(base::OpenFile("/dev/null", O_RDONLY))}; int raw_fds[2] = {*fds[0], *fds[1]}; ASSERT_TRUE(client_socket->Send(&size, sizeof(size), raw_fds, base::ArraySize(raw_fds), base::UnixSocket::BlockingMode::kBlocking)); ASSERT_TRUE(client_socket->Send("1", 1, -1, base::UnixSocket::BlockingMode::kBlocking)); task_runner.RunUntilCheckpoint("callback.called"); } } // namespace } // namespace profiling } // namespace perfetto <commit_msg>Fix test failure on is_debug. am: 152255fcc7 am: 1989accbaa am: 95f6ed58a3<commit_after>/* * Copyright (C) 2018 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. */ #include "src/profiling/memory/socket_listener.h" #include "perfetto/base/scoped_file.h" #include "src/base/test/test_task_runner.h" #include "src/ipc/test/test_socket.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace perfetto { namespace profiling { namespace { using ::testing::_; using ::testing::InvokeWithoutArgs; constexpr char kSocketName[] = TEST_SOCK_NAME("socket_listener_unittest"); class SocketListenerTest : public ::testing::Test { protected: void SetUp() override { DESTROY_TEST_SOCK(kSocketName); } void TearDown() override { DESTROY_TEST_SOCK(kSocketName); } }; class MockEventListener : public base::UnixSocket::EventListener { public: MOCK_METHOD2(OnConnect, void(base::UnixSocket*, bool)); }; TEST_F(SocketListenerTest, ReceiveRecord) { base::TestTaskRunner task_runner; auto callback_called = task_runner.CreateCheckpoint("callback.called"); auto connected = task_runner.CreateCheckpoint("connected"); auto callback_fn = [&callback_called](UnwindingRecord r) { ASSERT_EQ(r.size, 1u); ASSERT_EQ(r.data[0], '1'); ASSERT_FALSE(r.metadata.expired()); callback_called(); }; BookkeepingThread bookkeeping_thread; SocketListener listener(std::move(callback_fn), &bookkeeping_thread); ProcessSetSpec spec{}; spec.pids.emplace(getpid()); spec.client_configuration.interval = 1; auto handle = listener.process_matcher().AwaitProcessSetSpec(std::move(spec)); MockEventListener client_listener; EXPECT_CALL(client_listener, OnConnect(_, _)) .WillOnce(InvokeWithoutArgs(connected)); std::unique_ptr<base::UnixSocket> recv_socket = base::UnixSocket::Listen(kSocketName, &listener, &task_runner); std::unique_ptr<base::UnixSocket> client_socket = base::UnixSocket::Connect(kSocketName, &client_listener, &task_runner); task_runner.RunUntilCheckpoint("connected"); uint64_t size = 1; base::ScopedFile fds[2] = { base::ScopedFile(base::OpenFile("/dev/null", O_RDONLY)), base::ScopedFile(base::OpenFile("/dev/null", O_RDONLY))}; int raw_fds[2] = {*fds[0], *fds[1]}; ASSERT_TRUE(client_socket->Send(&size, sizeof(size), raw_fds, base::ArraySize(raw_fds), base::UnixSocket::BlockingMode::kBlocking)); ASSERT_TRUE(client_socket->Send("1", 1, -1, base::UnixSocket::BlockingMode::kBlocking)); task_runner.RunUntilCheckpoint("callback.called"); } } // namespace } // namespace profiling } // namespace perfetto <|endoftext|>
<commit_before>/* * (C) Copyright 2015 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include <gst/gst.h> #include "loadConfig.hpp" #include <queue> #include <list> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/property_tree/json_parser.hpp> #define GST_CAT_DEFAULT kurento_load_config GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "KurentoLoadConfig" namespace kurento { static std::list<std::string> split (const std::string &s, char delim) { std::list<std::string> elems; std::stringstream ss (s); std::string item; while (std::getline (ss, item, delim) ) { elems.push_back (item); } return elems; } static void mergePropertyTrees (boost::property_tree::ptree &ptMerged, const boost::property_tree::ptree &rptSecond ) { // Keep track of keys and values (subtrees) in second property tree std::queue<std::string> qKeys; std::queue<boost::property_tree::ptree> qValues; qValues.push ( rptSecond ); // Iterate over second property tree while ( !qValues.empty() ) { // Setup keys and corresponding values boost::property_tree::ptree ptree = qValues.front(); qValues.pop(); std::string keychain; if ( !qKeys.empty() ) { keychain = qKeys.front(); qKeys.pop(); } BOOST_FOREACH ( const boost::property_tree::ptree::value_type & child, ptree ) { if ( child.second.size() == 0 ) { std::string s; if ( !keychain.empty() ) { s = keychain + "." + child.first.data(); } else { s = child.first.data(); } // Put into combined property tree ptMerged.put ( s, child.second.data() ); } else { // Put keys (identifiers of subtrees) and all of its parents (where present) // aside for later iteration. if ( !keychain.empty() ) { qKeys.push ( keychain + "." + child.first.data() ); } else { qKeys.push ( child.first.data() ); } // Put values (the subtrees) aside, too qValues.push ( child.second ); } } } } static void loadModulesConfigFromDir (boost::property_tree::ptree &config, const boost::filesystem::path &dir, const boost::filesystem::path &parentDir) { GST_INFO ("Looking for config files in %s", dir.string().c_str() ); if (!boost::filesystem::is_directory (dir) ) { GST_WARNING ("Unable to load config files from: %s, it is not a directory", dir.string().c_str() ); return; } boost::filesystem::directory_iterator end_itr; for ( boost::filesystem::directory_iterator itr ( dir ); itr != end_itr; ++itr ) { if (boost::filesystem::is_regular (*itr) ) { boost::filesystem::path extension = itr->path().extension(); boost::filesystem::path extension2 = itr->path().stem().extension(); std::string fileName = itr->path().filename().string(); if (extension.string() == ".json" && extension2.string() == ".conf") { boost::property_tree::ptree moduleConfig; boost::property_tree::read_json (itr->path().string(), moduleConfig); moduleConfig.add ("configPath", itr->path().parent_path().string() ); { boost::filesystem::path diffpath; boost::filesystem::path tmppath = itr->path().parent_path(); while (tmppath != parentDir) { diffpath = tmppath.stem() / diffpath; tmppath = tmppath.parent_path(); } tmppath = diffpath; boost::property_tree::ptree loadedConfig; std::string key = "modules"; for (auto it = tmppath.begin(); it != tmppath.end(); it ++) { key += "." + it->string(); } fileName = fileName.substr (0, fileName.size() - extension.string().size() ); fileName = fileName.substr (0, fileName.size() - extension2.string().size() ); key += "." + fileName; loadedConfig.put_child (key, moduleConfig); mergePropertyTrees (config, loadedConfig); } GST_INFO ("Loaded module config from: %s", itr->path().string().c_str() ); } } else if (boost::filesystem::is_directory (*itr) ) { loadModulesConfigFromDir (config, itr->path(), parentDir); } } } static void loadModulesConfig (boost::property_tree::ptree &config, const boost::filesystem::path &configFilePath, std::string modulesConfigPath) { std::list <std::string> locations; if (modulesConfigPath.empty() ) { boost::filesystem::path modulesConfigDir = configFilePath.parent_path() / "modules"; modulesConfigPath = modulesConfigDir.string(); } locations = split (modulesConfigPath, ':'); for (std::string location : locations) { boost::filesystem::path dir (location); loadModulesConfigFromDir (config, dir, dir); } } void loadConfig (boost::property_tree::ptree &config, const std::string &file_name, const std::string &modulesConfigPath) { boost::filesystem::path configFilePath (file_name); GST_INFO ("Reading configuration from: %s", file_name.c_str () ); try { boost::property_tree::read_json (file_name, config); } catch (boost::property_tree::ptree_error &e) { GST_ERROR ("Error reading configuration: %s", e.what() ); std::cerr << "Error reading configuration: " << e.what() << std::endl; exit (1); } loadModulesConfig (config, configFilePath, modulesConfigPath); config.add ("configPath", configFilePath.parent_path().string() ); GST_INFO ("Configuration loaded successfully"); std::ostringstream oss; boost::property_tree::write_json (oss, config, true); std::string jsonConfig = oss.str(); GST_DEBUG ("Effective loaded config:\n%s", jsonConfig.c_str() ); } } /* kurento */ static void init_debug (void) __attribute__ ( (constructor) ); static void init_debug (void) { GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); } <commit_msg>loadConfig.cpp: Add support config files in info, init an xml formats<commit_after>/* * (C) Copyright 2015 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include <gst/gst.h> #include "loadConfig.hpp" #include <queue> #include <list> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/info_parser.hpp> #include <boost/property_tree/ini_parser.hpp> #include <boost/property_tree/xml_parser.hpp> #define GST_CAT_DEFAULT kurento_load_config GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "KurentoLoadConfig" namespace kurento { static std::list<std::string> split (const std::string &s, char delim) { std::list<std::string> elems; std::stringstream ss (s); std::string item; while (std::getline (ss, item, delim) ) { elems.push_back (item); } return elems; } static void mergePropertyTrees (boost::property_tree::ptree &ptMerged, const boost::property_tree::ptree &rptSecond ) { // Keep track of keys and values (subtrees) in second property tree std::queue<std::string> qKeys; std::queue<boost::property_tree::ptree> qValues; qValues.push ( rptSecond ); // Iterate over second property tree while ( !qValues.empty() ) { // Setup keys and corresponding values boost::property_tree::ptree ptree = qValues.front(); qValues.pop(); std::string keychain; if ( !qKeys.empty() ) { keychain = qKeys.front(); qKeys.pop(); } BOOST_FOREACH ( const boost::property_tree::ptree::value_type & child, ptree ) { if ( child.second.size() == 0 ) { std::string s; if ( !keychain.empty() ) { s = keychain + "." + child.first.data(); } else { s = child.first.data(); } // Put into combined property tree ptMerged.put ( s, child.second.data() ); } else { // Put keys (identifiers of subtrees) and all of its parents (where present) // aside for later iteration. if ( !keychain.empty() ) { qKeys.push ( keychain + "." + child.first.data() ); } else { qKeys.push ( child.first.data() ); } // Put values (the subtrees) aside, too qValues.push ( child.second ); } } } } static void loadModulesConfigFromDir (boost::property_tree::ptree &config, const boost::filesystem::path &dir, const boost::filesystem::path &parentDir) { GST_INFO ("Looking for config files in %s", dir.string().c_str() ); if (!boost::filesystem::is_directory (dir) ) { GST_WARNING ("Unable to load config files from: %s, it is not a directory", dir.string().c_str() ); return; } boost::filesystem::directory_iterator end_itr; for ( boost::filesystem::directory_iterator itr ( dir ); itr != end_itr; ++itr ) { if (boost::filesystem::is_regular (*itr) ) { boost::filesystem::path extension = itr->path().extension(); boost::filesystem::path extension2 = itr->path().stem().extension(); std::string fileName = itr->path().filename().string(); if (extension2.string() == ".conf") { boost::property_tree::ptree moduleConfig; if (extension.string() == ".json") { boost::property_tree::read_json (itr->path().string(), moduleConfig); } else if (extension.string() == ".info") { boost::property_tree::read_info (itr->path().string(), moduleConfig); } else if (extension.string() == ".ini") { boost::property_tree::read_ini (itr->path().string(), moduleConfig); } else if (extension.string() == ".xml") { boost::property_tree::read_xml (itr->path().string(), moduleConfig); } else { continue; } moduleConfig.add ("configPath", itr->path().parent_path().string() ); { boost::filesystem::path diffpath; boost::filesystem::path tmppath = itr->path().parent_path(); while (tmppath != parentDir) { diffpath = tmppath.stem() / diffpath; tmppath = tmppath.parent_path(); } tmppath = diffpath; boost::property_tree::ptree loadedConfig; std::string key = "modules"; for (auto it = tmppath.begin(); it != tmppath.end(); it ++) { key += "." + it->string(); } fileName = fileName.substr (0, fileName.size() - extension.string().size() ); fileName = fileName.substr (0, fileName.size() - extension2.string().size() ); key += "." + fileName; loadedConfig.put_child (key, moduleConfig); mergePropertyTrees (config, loadedConfig); } GST_INFO ("Loaded module config from: %s", itr->path().string().c_str() ); } } else if (boost::filesystem::is_directory (*itr) ) { loadModulesConfigFromDir (config, itr->path(), parentDir); } } } static void loadModulesConfig (boost::property_tree::ptree &config, const boost::filesystem::path &configFilePath, std::string modulesConfigPath) { std::list <std::string> locations; if (modulesConfigPath.empty() ) { boost::filesystem::path modulesConfigDir = configFilePath.parent_path() / "modules"; modulesConfigPath = modulesConfigDir.string(); } locations = split (modulesConfigPath, ':'); for (std::string location : locations) { boost::filesystem::path dir (location); loadModulesConfigFromDir (config, dir, dir); } } void loadConfig (boost::property_tree::ptree &config, const std::string &file_name, const std::string &modulesConfigPath) { boost::filesystem::path configFilePath (file_name); GST_INFO ("Reading configuration from: %s", file_name.c_str () ); try { boost::property_tree::read_json (file_name, config); } catch (boost::property_tree::ptree_error &e) { GST_ERROR ("Error reading configuration: %s", e.what() ); std::cerr << "Error reading configuration: " << e.what() << std::endl; exit (1); } loadModulesConfig (config, configFilePath, modulesConfigPath); config.add ("configPath", configFilePath.parent_path().string() ); GST_INFO ("Configuration loaded successfully"); std::ostringstream oss; boost::property_tree::write_json (oss, config, true); std::string jsonConfig = oss.str(); GST_DEBUG ("Effective loaded config:\n%s", jsonConfig.c_str() ); } } /* kurento */ static void init_debug (void) __attribute__ ( (constructor) ); static void init_debug (void) { GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); } <|endoftext|>
<commit_before>/* * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "../sstable_test.hh" #include "sstables/sstables.hh" #include "mutation_reader.hh" #include "memtable-sstable.hh" #include <boost/accumulators/accumulators.hpp> #include <boost/accumulators/statistics.hpp> #include <boost/range/irange.hpp> using namespace sstables; class test_env { public: struct conf { unsigned partitions; unsigned key_size; unsigned num_columns; unsigned column_size; size_t buffer_size; sstring dir; }; private: sstring dir() { return _cfg.dir + "/" + to_sstring(engine().cpu_id()); } sstring random_string(unsigned size) { sstring str(sstring::initialized_later{}, size_t(size)); for (auto& b: str) { b = _distribution(_generator); } return str; } sstring random_key() { return random_string(_cfg.key_size); } sstring random_column() { return random_string(_cfg.column_size); } conf _cfg; schema_ptr s; std::default_random_engine _generator; std::uniform_int_distribution<char> _distribution; lw_shared_ptr<memtable> _mt; std::vector<shared_sstable> _sst; schema_ptr create_schema() { std::vector<schema::column> columns; for (unsigned i = 0; i < _cfg.num_columns; ++i) { columns.push_back(schema::column{ to_bytes(sprint("column%04d", i)), utf8_type }); } schema_builder builder(make_lw_shared(schema(generate_legacy_id("ks", "perf-test"), "ks", "perf-test", // partition key {{"name", utf8_type}}, // clustering key {}, // regular columns { columns }, // static columns {}, // regular column name type utf8_type, // comment "Perf tests" ))); return builder.build(schema_builder::compact_storage::no); } public: test_env(conf cfg) : _cfg(std::move(cfg)) , s(create_schema()) , _distribution('@', '~') , _mt(make_lw_shared<memtable>(s)) {} future<> stop() { return make_ready_future<>(); } future<> fill_memtable() { auto idx = boost::irange(0, int(_cfg.partitions)); return do_for_each(idx.begin(), idx.end(), [this] (auto iteration) { auto key = partition_key::from_deeply_exploded(*s, { this->random_key() }); auto mut = mutation(key, this->s); for (auto& cdef: this->s->regular_columns()) { mut.set_clustered_cell(clustering_key::make_empty(), cdef, atomic_cell::make_live(0, utf8_type->decompose(this->random_column()))); } this->_mt->apply(std::move(mut)); return make_ready_future<>(); }); } future<> load_sstables(unsigned iterations) { _sst.push_back(make_sstable(s, this->dir(), 0, sstable::version_types::ka, sstable::format_types::big)); return _sst.back()->load(); } using clk = std::chrono::steady_clock; static auto now() { return clk::now(); } // Mappers below future<double> flush_memtable(int idx) { auto start = test_env::now(); size_t partitions = _mt->partition_count(); return test_setup::create_empty_test_dir(dir()).then([this, idx] { auto sst = sstables::test::make_test_sstable(_cfg.buffer_size, s, dir(), idx, sstable::version_types::ka, sstable::format_types::big); return write_memtable_to_sstable(*_mt, sst).then([sst] {}); }).then([start, partitions] { auto end = test_env::now(); auto duration = std::chrono::duration<double>(end - start).count(); return partitions / duration; }); } future<double> read_all_indexes(int idx) { return do_with(test(_sst[0]), [] (auto& sst) { const auto start = test_env::now(); return sst.read_indexes().then([start] (const auto& indexes) { auto end = test_env::now(); auto duration = std::chrono::duration<double>(end - start).count(); return indexes.size() / duration; }); }); } future<double> read_sequential_partitions(int idx) { return do_with(_sst[0]->read_rows_flat(s), [this] (flat_mutation_reader& r) { auto start = test_env::now(); auto total = make_lw_shared<size_t>(0); auto done = make_lw_shared<bool>(false); return do_until([done] { return *done; }, [this, done, total, &r] { return read_mutation_from_flat_mutation_reader(s, r).then([this, done, total] (mutation_opt m) { if (!m) { *done = true; } else { auto row = m->partition().find_row(*s, clustering_key::make_empty()); if (!row || row->size() != _cfg.num_columns) { throw std::invalid_argument("Invalid sstable found. Maybe you ran write mode with different num_columns settings?"); } else { (*total)++; } } }); }).then([total, start] { auto end = test_env::now(); auto duration = std::chrono::duration<double>(end - start).count(); return *total / duration; }); }); } }; // The function func should carry on with the test, and return the number of partitions processed. // time_runs will then map reduce it, and return the aggregate partitions / sec for the whole system. template <typename Func> future<> time_runs(unsigned iterations, unsigned parallelism, distributed<test_env>& dt, Func func) { using namespace boost::accumulators; auto acc = make_lw_shared<accumulator_set<double, features<tag::mean, tag::error_of<tag::mean>>>>(); auto idx = boost::irange(0, int(iterations)); return do_for_each(idx.begin(), idx.end(), [parallelism, acc, &dt, func] (auto iter) { auto idx = boost::irange(0, int(parallelism)); return parallel_for_each(idx.begin(), idx.end(), [&dt, func, acc] (auto idx) { return dt.map_reduce(adder<double>(), func, std::move(idx)).then([acc] (double result) { auto& a = *acc; a(result); return make_ready_future<>(); }); }); }).then([acc, iterations, parallelism] { std::cout << sprint("%.2f", mean(*acc)) << " +- " << sprint("%.2f", error_of<tag::mean>(*acc)) << " partitions / sec (" << iterations << " runs, " << parallelism << " concurrent ops)\n"; }); } <commit_msg>tests:perf: make perf_sstable write mode work again<commit_after>/* * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "../sstable_test.hh" #include "sstables/sstables.hh" #include "mutation_reader.hh" #include "memtable-sstable.hh" #include <boost/accumulators/accumulators.hpp> #include <boost/accumulators/statistics.hpp> #include <boost/range/irange.hpp> using namespace sstables; class test_env { public: struct conf { unsigned partitions; unsigned key_size; unsigned num_columns; unsigned column_size; size_t buffer_size; sstring dir; }; private: sstring dir() { return _cfg.dir + "/" + to_sstring(engine().cpu_id()); } sstring random_string(unsigned size) { sstring str(sstring::initialized_later{}, size_t(size)); for (auto& b: str) { b = _distribution(_generator); } return str; } sstring random_key() { return random_string(_cfg.key_size); } sstring random_column() { return random_string(_cfg.column_size); } conf _cfg; schema_ptr s; std::default_random_engine _generator; std::uniform_int_distribution<char> _distribution; lw_shared_ptr<memtable> _mt; std::vector<shared_sstable> _sst; schema_ptr create_schema() { std::vector<schema::column> columns; for (unsigned i = 0; i < _cfg.num_columns; ++i) { columns.push_back(schema::column{ to_bytes(sprint("column%04d", i)), utf8_type }); } schema_builder builder(make_lw_shared(schema(generate_legacy_id("ks", "perf-test"), "ks", "perf-test", // partition key {{"name", utf8_type}}, // clustering key {}, // regular columns { columns }, // static columns {}, // regular column name type utf8_type, // comment "Perf tests" ))); return builder.build(schema_builder::compact_storage::no); } public: test_env(conf cfg) : _cfg(std::move(cfg)) , s(create_schema()) , _distribution('@', '~') , _mt(make_lw_shared<memtable>(s)) {} future<> stop() { return make_ready_future<>(); } future<> fill_memtable() { auto idx = boost::irange(0, int(_cfg.partitions)); return do_for_each(idx.begin(), idx.end(), [this] (auto iteration) { auto key = partition_key::from_deeply_exploded(*s, { this->random_key() }); auto mut = mutation(key, this->s); for (auto& cdef: this->s->regular_columns()) { mut.set_clustered_cell(clustering_key::make_empty(), cdef, atomic_cell::make_live(0, utf8_type->decompose(this->random_column()))); } this->_mt->apply(std::move(mut)); return make_ready_future<>(); }); } future<> load_sstables(unsigned iterations) { _sst.push_back(make_sstable(s, this->dir(), 0, sstable::version_types::ka, sstable::format_types::big)); return _sst.back()->load(); } using clk = std::chrono::steady_clock; static auto now() { return clk::now(); } // Mappers below future<double> flush_memtable(int idx) { return seastar::async([this, idx] { storage_service_for_tests ssft; size_t partitions = _mt->partition_count(); test_setup::create_empty_test_dir(dir()).get(); auto sst = sstables::test::make_test_sstable(_cfg.buffer_size, s, dir(), idx, sstable::version_types::ka, sstable::format_types::big); auto start = test_env::now(); write_memtable_to_sstable(*_mt, sst).get(); auto end = test_env::now(); _mt->revert_flushed_memory(); auto duration = std::chrono::duration<double>(end - start).count(); return partitions / duration; }); } future<double> read_all_indexes(int idx) { return do_with(test(_sst[0]), [] (auto& sst) { const auto start = test_env::now(); return sst.read_indexes().then([start] (const auto& indexes) { auto end = test_env::now(); auto duration = std::chrono::duration<double>(end - start).count(); return indexes.size() / duration; }); }); } future<double> read_sequential_partitions(int idx) { return do_with(_sst[0]->read_rows_flat(s), [this] (flat_mutation_reader& r) { auto start = test_env::now(); auto total = make_lw_shared<size_t>(0); auto done = make_lw_shared<bool>(false); return do_until([done] { return *done; }, [this, done, total, &r] { return read_mutation_from_flat_mutation_reader(s, r).then([this, done, total] (mutation_opt m) { if (!m) { *done = true; } else { auto row = m->partition().find_row(*s, clustering_key::make_empty()); if (!row || row->size() != _cfg.num_columns) { throw std::invalid_argument("Invalid sstable found. Maybe you ran write mode with different num_columns settings?"); } else { (*total)++; } } }); }).then([total, start] { auto end = test_env::now(); auto duration = std::chrono::duration<double>(end - start).count(); return *total / duration; }); }); } }; // The function func should carry on with the test, and return the number of partitions processed. // time_runs will then map reduce it, and return the aggregate partitions / sec for the whole system. template <typename Func> future<> time_runs(unsigned iterations, unsigned parallelism, distributed<test_env>& dt, Func func) { using namespace boost::accumulators; auto acc = make_lw_shared<accumulator_set<double, features<tag::mean, tag::error_of<tag::mean>>>>(); auto idx = boost::irange(0, int(iterations)); return do_for_each(idx.begin(), idx.end(), [parallelism, acc, &dt, func] (auto iter) { auto idx = boost::irange(0, int(parallelism)); return parallel_for_each(idx.begin(), idx.end(), [&dt, func, acc] (auto idx) { return dt.map_reduce(adder<double>(), func, std::move(idx)).then([acc] (double result) { auto& a = *acc; a(result); return make_ready_future<>(); }); }); }).then([acc, iterations, parallelism] { std::cout << sprint("%.2f", mean(*acc)) << " +- " << sprint("%.2f", error_of<tag::mean>(*acc)) << " partitions / sec (" << iterations << " runs, " << parallelism << " concurrent ops)\n"; }); } <|endoftext|>
<commit_before>/* ** repository: https://github.com/trumanzhao/luna ** trumanzhao, 2016/10/19, trumanzhao@foxmail.com */ #include <stdint.h> #include <string.h> #include <algorithm> #include <lua.hpp> #include "lz4.h" #include "lua_archiver.h" #include "var_int.h" enum class ar_type { nill, number, integer, string, string_idx, bool_true, bool_false, table_head, table_tail, count }; static const int small_int_max = UCHAR_MAX - (int)ar_type::count; static const int max_share_string = UCHAR_MAX; static const int max_table_depth = 16; static int normal_index(lua_State* L, int idx) { int top = lua_gettop(L); if (idx < 0 && -idx <= top) return idx + top + 1; return idx; } lua_archiver::lua_archiver(size_t size) { m_buffer_size = size; m_lz_threshold = size; } lua_archiver::lua_archiver(size_t size, size_t lz_size) { m_buffer_size = size; m_lz_threshold = lz_size; } lua_archiver::~lua_archiver() { free_buffer(); } void lua_archiver::set_buffer_size(size_t size) { m_buffer_size = size; free_buffer(); } void* lua_archiver::save(size_t* data_len, lua_State* L, int first, int last) { first = normal_index(L, first); last = normal_index(L, last); if (last < first || !alloc_buffer()) return nullptr; *m_ar_buffer = 'x'; m_begin = m_ar_buffer; m_end = m_ar_buffer + m_buffer_size; m_pos = m_begin + 1; m_table_depth = 0; m_shared_string.clear(); m_shared_strlen.clear(); for (int i = first; i <= last; i++) { if (!save_value(L, i)) return nullptr; } *data_len = (size_t)(m_pos - m_begin); if (*data_len >= m_lz_threshold && m_buffer_size < 1 + LZ4_COMPRESSBOUND(*data_len)) { *m_lz_buffer = 'z'; int len = LZ4_compress_default((const char*)m_begin + 1, (char*)m_lz_buffer + 1, (int)*data_len, (int)m_buffer_size - 1); if (len <= 0) return nullptr; *data_len = 1 + len; return m_lz_buffer; } return m_begin; } int lua_archiver::load(lua_State* L, const void* data, size_t data_len) { if (data_len == 0 || !alloc_buffer()) return 0; m_pos = (unsigned char*)data; m_end = (unsigned char*)data + data_len; if (*m_pos == 'z') { m_pos++; int len = LZ4_decompress_safe((const char*)m_pos, (char*)m_lz_buffer, (int)data_len - 1, (int)m_buffer_size); if (len <= 0) return 0; m_pos = m_lz_buffer; m_end = m_lz_buffer + len; } else { if (*m_pos != 'x') return 0; m_pos++; } m_shared_string.clear(); m_shared_strlen.clear(); int count = 0; int top = lua_gettop(L); while (m_pos < m_end) { if (!load_value(L)) { lua_settop(L, top); return 0; } count++; } return count; } bool lua_archiver::alloc_buffer() { if (m_ar_buffer == nullptr) { m_ar_buffer = new unsigned char[m_buffer_size]; } if (m_lz_buffer == nullptr) { m_lz_buffer = new unsigned char[m_buffer_size]; } return m_ar_buffer != nullptr && m_lz_buffer != nullptr; } void lua_archiver::free_buffer() { if (m_ar_buffer) { delete[] m_ar_buffer; m_ar_buffer = nullptr; } if (m_lz_buffer) { delete[] m_lz_buffer; m_lz_buffer = nullptr; } } bool lua_archiver::save_value(lua_State* L, int idx) { int type = lua_type(L, idx); switch (type) { case LUA_TNIL: return save_nill(); case LUA_TNUMBER: return lua_isinteger(L, idx) ? save_integer(lua_tointeger(L, idx)) : save_number(lua_tonumber(L, idx)); case LUA_TBOOLEAN: return save_bool(!!lua_toboolean(L, idx)); case LUA_TSTRING: return save_string(L, idx); case LUA_TTABLE: return save_table(L, idx); default: break; } return false; } bool lua_archiver::save_number(double v) { if (m_end - m_pos < sizeof(unsigned char) + sizeof(double)) return false; *m_pos++ = (unsigned char)ar_type::number; memcpy(m_pos, &v, sizeof(double)); m_pos += sizeof(double); return true; } bool lua_archiver::save_integer(int64_t v) { if (v >= 0 && v <= small_int_max) { if (m_end - m_pos < sizeof(unsigned char)) return false; *m_pos++ = (unsigned char)(v + (int)ar_type::count); return true; } if (v > small_int_max) { v -= small_int_max; } if (m_end - m_pos < sizeof(unsigned char)) return false; *m_pos++ = (unsigned char)ar_type::integer; size_t len = encode_s64(m_pos, (size_t)(m_end - m_pos), v); m_pos += len; return len > 0; } bool lua_archiver::save_bool(bool v) { if (m_end - m_pos < sizeof(unsigned char)) return false; *m_pos++ = (unsigned char)(v ? ar_type::bool_true : ar_type::bool_false); return true; } bool lua_archiver::save_nill() { if (m_end - m_pos < sizeof(unsigned char)) return false; *m_pos++ = (unsigned char)ar_type::nill; return true; } bool lua_archiver::save_table(lua_State* L, int idx) { if (m_end - m_pos < (ptrdiff_t)sizeof(unsigned char)) return false; if (++m_table_depth > max_table_depth) return false; *m_pos++ = (unsigned char)ar_type::table_head; idx = normal_index(L, idx); if (!lua_checkstack(L, 1)) return false; lua_pushnil(L); while (lua_next(L, idx)) { if (!save_value(L, -2) || !save_value(L, -1)) return false; lua_pop(L, 1); } --m_table_depth; if (m_end - m_pos < (ptrdiff_t)sizeof(unsigned char)) return false; *m_pos++ = (unsigned char)ar_type::table_tail; return true; } bool lua_archiver::save_string(lua_State* L, int idx) { size_t len = 0, encode_len = 0; const char* str = lua_tolstring(L, idx, &len); int shared = find_shared_str(str); if (shared >= 0) { if (m_end - m_pos < sizeof(unsigned char)) return false; *m_pos++ = (unsigned char)ar_type::string_idx; encode_len = encode_u64(m_pos, (size_t)(m_end - m_pos), shared); m_pos += encode_len; return encode_len > 0; } if (m_end - m_pos < sizeof(unsigned char)) return false; *m_pos++ = (unsigned char)ar_type::string; encode_len = encode_u64(m_pos, (size_t)(m_end - m_pos), len); if (encode_len == 0) return false; m_pos += encode_len; if (m_end - m_pos < (int)len) return false; memcpy(m_pos, str, len); m_pos += len; if (m_shared_string.size() < max_share_string) { m_shared_string.push_back(str); } return true; } int lua_archiver::find_shared_str(const char* str) { auto it = std::find(m_shared_string.begin(), m_shared_string.end(), str); if (it != m_shared_string.end()) return (int)(it - m_shared_string.begin()); return -1; } bool lua_archiver::load_value(lua_State* L) { if (!lua_checkstack(L, 1)) return false; if (m_end - m_pos < (ptrdiff_t)sizeof(unsigned char)) return false; int code = *m_pos++; if (code >= (int)ar_type::count) { lua_pushinteger(L, code - (int)ar_type::count); return true; } double number = 0; int64_t integer = 0; size_t decode_len = 0; uint64_t str_len = 0, str_idx = 0; switch ((ar_type)code) { case ar_type::nill: lua_pushnil(L); break; case ar_type::number: if (m_end - m_pos < (ptrdiff_t)sizeof(double)) return false; memcpy(&number, m_pos, sizeof(double)); m_pos += sizeof(double); lua_pushnumber(L, number); break; case ar_type::integer: decode_len = decode_s64(&integer, m_pos, (size_t)(m_end - m_pos)); if (decode_len == 0) return false; m_pos += decode_len; if (integer >= 0) { integer += small_int_max; } lua_pushinteger(L, integer); break; case ar_type::bool_true: lua_pushboolean(L, true); break; case ar_type::bool_false: lua_pushboolean(L, false); break; case ar_type::string: decode_len = decode_u64(&str_len, m_pos, (size_t)(m_end - m_pos)); if (decode_len == 0) return false; m_pos += decode_len; if (m_end - m_pos < (ptrdiff_t)str_len) return false; m_shared_string.push_back((char*)m_pos); m_shared_strlen.push_back((size_t)str_len); lua_pushlstring(L, (char*)m_pos, (size_t)str_len); m_pos += str_len; break; case ar_type::string_idx: decode_len = decode_u64(&str_idx, m_pos, (size_t)(m_end - m_pos)); if (decode_len == 0 || str_idx >= m_shared_string.size()) return false; m_pos += decode_len; lua_pushlstring(L, m_shared_string[(int)str_idx], m_shared_strlen[(int)str_idx]); break; case ar_type::table_head: lua_newtable(L); while (m_pos < m_end) { if (*m_pos == (unsigned char)ar_type::table_tail) { m_pos++; return true; } if (!load_value(L) || !load_value(L)) return false; lua_settable(L, -3); } return false; default: return false; } return true; } <commit_msg>修正数据压缩阀值判断问题<commit_after>/* ** repository: https://github.com/trumanzhao/luna ** trumanzhao, 2016/10/19, trumanzhao@foxmail.com */ #include <stdint.h> #include <string.h> #include <algorithm> #include <lua.hpp> #include "lz4.h" #include "lua_archiver.h" #include "var_int.h" enum class ar_type { nill, number, integer, string, string_idx, bool_true, bool_false, table_head, table_tail, count }; static const int small_int_max = UCHAR_MAX - (int)ar_type::count; static const int max_share_string = UCHAR_MAX; static const int max_table_depth = 16; static int normal_index(lua_State* L, int idx) { int top = lua_gettop(L); if (idx < 0 && -idx <= top) return idx + top + 1; return idx; } lua_archiver::lua_archiver(size_t size) { m_buffer_size = size; m_lz_threshold = size; } lua_archiver::lua_archiver(size_t size, size_t lz_size) { m_buffer_size = size; m_lz_threshold = lz_size; } lua_archiver::~lua_archiver() { free_buffer(); } void lua_archiver::set_buffer_size(size_t size) { m_buffer_size = size; free_buffer(); } void* lua_archiver::save(size_t* data_len, lua_State* L, int first, int last) { first = normal_index(L, first); last = normal_index(L, last); if (last < first || !alloc_buffer()) return nullptr; *m_ar_buffer = 'x'; m_begin = m_ar_buffer; m_end = m_ar_buffer + m_buffer_size; m_pos = m_begin + 1; m_table_depth = 0; m_shared_string.clear(); m_shared_strlen.clear(); for (int i = first; i <= last; i++) { if (!save_value(L, i)) return nullptr; } *data_len = (size_t)(m_pos - m_begin); if (*data_len >= m_lz_threshold) { int raw_len = ((int)*data_len) - 1; if (1 + LZ4_COMPRESSBOUND(raw_len) < m_buffer_size) { *m_lz_buffer = 'z'; int out_len = LZ4_compress_default((const char*)m_begin + 1, (char*)m_lz_buffer + 1, raw_len, (int)m_buffer_size - 1); if (out_len <= 0) return nullptr; *data_len = 1 + out_len; return m_lz_buffer; } } return m_begin; } int lua_archiver::load(lua_State* L, const void* data, size_t data_len) { if (data_len == 0 || !alloc_buffer()) return 0; m_pos = (unsigned char*)data; m_end = (unsigned char*)data + data_len; if (*m_pos == 'z') { m_pos++; int len = LZ4_decompress_safe((const char*)m_pos, (char*)m_lz_buffer, (int)data_len - 1, (int)m_buffer_size); if (len <= 0) return 0; m_pos = m_lz_buffer; m_end = m_lz_buffer + len; } else { if (*m_pos != 'x') return 0; m_pos++; } m_shared_string.clear(); m_shared_strlen.clear(); int count = 0; int top = lua_gettop(L); while (m_pos < m_end) { if (!load_value(L)) { lua_settop(L, top); return 0; } count++; } return count; } bool lua_archiver::alloc_buffer() { if (m_ar_buffer == nullptr) { m_ar_buffer = new unsigned char[m_buffer_size]; } if (m_lz_buffer == nullptr) { m_lz_buffer = new unsigned char[m_buffer_size]; } return m_ar_buffer != nullptr && m_lz_buffer != nullptr; } void lua_archiver::free_buffer() { if (m_ar_buffer) { delete[] m_ar_buffer; m_ar_buffer = nullptr; } if (m_lz_buffer) { delete[] m_lz_buffer; m_lz_buffer = nullptr; } } bool lua_archiver::save_value(lua_State* L, int idx) { int type = lua_type(L, idx); switch (type) { case LUA_TNIL: return save_nill(); case LUA_TNUMBER: return lua_isinteger(L, idx) ? save_integer(lua_tointeger(L, idx)) : save_number(lua_tonumber(L, idx)); case LUA_TBOOLEAN: return save_bool(!!lua_toboolean(L, idx)); case LUA_TSTRING: return save_string(L, idx); case LUA_TTABLE: return save_table(L, idx); default: break; } return false; } bool lua_archiver::save_number(double v) { if (m_end - m_pos < sizeof(unsigned char) + sizeof(double)) return false; *m_pos++ = (unsigned char)ar_type::number; memcpy(m_pos, &v, sizeof(double)); m_pos += sizeof(double); return true; } bool lua_archiver::save_integer(int64_t v) { if (v >= 0 && v <= small_int_max) { if (m_end - m_pos < sizeof(unsigned char)) return false; *m_pos++ = (unsigned char)(v + (int)ar_type::count); return true; } if (v > small_int_max) { v -= small_int_max; } if (m_end - m_pos < sizeof(unsigned char)) return false; *m_pos++ = (unsigned char)ar_type::integer; size_t len = encode_s64(m_pos, (size_t)(m_end - m_pos), v); m_pos += len; return len > 0; } bool lua_archiver::save_bool(bool v) { if (m_end - m_pos < sizeof(unsigned char)) return false; *m_pos++ = (unsigned char)(v ? ar_type::bool_true : ar_type::bool_false); return true; } bool lua_archiver::save_nill() { if (m_end - m_pos < sizeof(unsigned char)) return false; *m_pos++ = (unsigned char)ar_type::nill; return true; } bool lua_archiver::save_table(lua_State* L, int idx) { if (m_end - m_pos < (ptrdiff_t)sizeof(unsigned char)) return false; if (++m_table_depth > max_table_depth) return false; *m_pos++ = (unsigned char)ar_type::table_head; idx = normal_index(L, idx); if (!lua_checkstack(L, 1)) return false; lua_pushnil(L); while (lua_next(L, idx)) { if (!save_value(L, -2) || !save_value(L, -1)) return false; lua_pop(L, 1); } --m_table_depth; if (m_end - m_pos < (ptrdiff_t)sizeof(unsigned char)) return false; *m_pos++ = (unsigned char)ar_type::table_tail; return true; } bool lua_archiver::save_string(lua_State* L, int idx) { size_t len = 0, encode_len = 0; const char* str = lua_tolstring(L, idx, &len); int shared = find_shared_str(str); if (shared >= 0) { if (m_end - m_pos < sizeof(unsigned char)) return false; *m_pos++ = (unsigned char)ar_type::string_idx; encode_len = encode_u64(m_pos, (size_t)(m_end - m_pos), shared); m_pos += encode_len; return encode_len > 0; } if (m_end - m_pos < sizeof(unsigned char)) return false; *m_pos++ = (unsigned char)ar_type::string; encode_len = encode_u64(m_pos, (size_t)(m_end - m_pos), len); if (encode_len == 0) return false; m_pos += encode_len; if (m_end - m_pos < (int)len) return false; memcpy(m_pos, str, len); m_pos += len; if (m_shared_string.size() < max_share_string) { m_shared_string.push_back(str); } return true; } int lua_archiver::find_shared_str(const char* str) { auto it = std::find(m_shared_string.begin(), m_shared_string.end(), str); if (it != m_shared_string.end()) return (int)(it - m_shared_string.begin()); return -1; } bool lua_archiver::load_value(lua_State* L) { if (!lua_checkstack(L, 1)) return false; if (m_end - m_pos < (ptrdiff_t)sizeof(unsigned char)) return false; int code = *m_pos++; if (code >= (int)ar_type::count) { lua_pushinteger(L, code - (int)ar_type::count); return true; } double number = 0; int64_t integer = 0; size_t decode_len = 0; uint64_t str_len = 0, str_idx = 0; switch ((ar_type)code) { case ar_type::nill: lua_pushnil(L); break; case ar_type::number: if (m_end - m_pos < (ptrdiff_t)sizeof(double)) return false; memcpy(&number, m_pos, sizeof(double)); m_pos += sizeof(double); lua_pushnumber(L, number); break; case ar_type::integer: decode_len = decode_s64(&integer, m_pos, (size_t)(m_end - m_pos)); if (decode_len == 0) return false; m_pos += decode_len; if (integer >= 0) { integer += small_int_max; } lua_pushinteger(L, integer); break; case ar_type::bool_true: lua_pushboolean(L, true); break; case ar_type::bool_false: lua_pushboolean(L, false); break; case ar_type::string: decode_len = decode_u64(&str_len, m_pos, (size_t)(m_end - m_pos)); if (decode_len == 0) return false; m_pos += decode_len; if (m_end - m_pos < (ptrdiff_t)str_len) return false; m_shared_string.push_back((char*)m_pos); m_shared_strlen.push_back((size_t)str_len); lua_pushlstring(L, (char*)m_pos, (size_t)str_len); m_pos += str_len; break; case ar_type::string_idx: decode_len = decode_u64(&str_idx, m_pos, (size_t)(m_end - m_pos)); if (decode_len == 0 || str_idx >= m_shared_string.size()) return false; m_pos += decode_len; lua_pushlstring(L, m_shared_string[(int)str_idx], m_shared_strlen[(int)str_idx]); break; case ar_type::table_head: lua_newtable(L); while (m_pos < m_end) { if (*m_pos == (unsigned char)ar_type::table_tail) { m_pos++; return true; } if (!load_value(L) || !load_value(L)) return false; lua_settable(L, -3); } return false; default: return false; } return true; } <|endoftext|>
<commit_before>// Copyright (c) 2014, Baidu.com, Inc. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chunkserver_manager.h" #include <boost/bind.hpp> #include <gflags/gflags.h> #include <common/logging.h> #include "proto/status_code.pb.h" #include "nameserver/block_mapping.h" DECLARE_int32(keepalive_timeout); DECLARE_int32(chunkserver_max_pending_buffers); DECLARE_int32(recover_speed); namespace baidu { namespace bfs { ChunkServerManager::ChunkServerManager(ThreadPool* thread_pool, BlockMapping* block_mapping) : thread_pool_(thread_pool), block_mapping_(block_mapping), chunkserver_num_(0), next_chunkserver_id_(1) { thread_pool_->AddTask(boost::bind(&ChunkServerManager::DeadCheck, this)); } void ChunkServerManager::CleanChunkserver(ChunkServerInfo* cs, const std::string& reason) { MutexLock lock(&mu_); chunkserver_num_--; LOG(INFO, "Remove Chunkserver C%d %s %s, cs_num=%d", cs->id(), cs->address().c_str(), reason.c_str(), chunkserver_num_); int32_t id = cs->id(); std::set<int64_t> blocks; std::swap(blocks, chunkserver_block_map_[id]); chunkserver_block_map_.erase(id); cs->set_status(kCsCleaning); mu_.Unlock(); block_mapping_->DealWithDeadBlocks(id, blocks); mu_.Lock(); if (cs->is_dead()) { cs->set_status(kCsOffLine); } else { cs->set_status(kCsStandby); } } bool ChunkServerManager::RemoveChunkServer(const std::string& addr) { MutexLock lock(&mu_); std::map<std::string, int32_t>::iterator it = address_map_.find(addr); if (it == address_map_.end()) { return false; } ChunkServerInfo* cs_info = NULL; bool ret = GetChunkServerPtr(it->second, &cs_info); assert(ret); if (cs_info->status() == kCsActive) { cs_info->set_status(kCsWaitClean); boost::function<void ()> task = boost::bind(&ChunkServerManager::CleanChunkserver, this, cs_info, std::string("Dead")); thread_pool_->AddTask(task); } return true; } void ChunkServerManager::DeadCheck() { int32_t now_time = common::timer::now_time(); MutexLock lock(&mu_); std::map<int32_t, std::set<ChunkServerInfo*> >::iterator it = heartbeat_list_.begin(); while (it != heartbeat_list_.end() && it->first + FLAGS_keepalive_timeout <= now_time) { std::set<ChunkServerInfo*>::iterator node = it->second.begin(); while (node != it->second.end()) { ChunkServerInfo* cs = *node; it->second.erase(node++); LOG(INFO, "[DeadCheck] Chunkserver dead C%d %s, cs_num=%d", cs->id(), cs->address().c_str(), chunkserver_num_); cs->set_is_dead(true); if (cs->status() == kCsActive) { cs->set_status(kCsWaitClean); boost::function<void ()> task = boost::bind(&ChunkServerManager::CleanChunkserver, this, cs, std::string("Dead")); thread_pool_->AddTask(task); } else { LOG(INFO, "[DeadCheck] Chunkserver C%d %s is being clean", cs->id(), cs->address().c_str()); } } assert(it->second.empty()); heartbeat_list_.erase(it); it = heartbeat_list_.begin(); } int idle_time = 5; if (it != heartbeat_list_.end()) { idle_time = it->first + FLAGS_keepalive_timeout - now_time; // LOG(INFO, "it->first= %d, now_time= %d\n", it->first, now_time); if (idle_time > 5) { idle_time = 5; } } thread_pool_->DelayTask(idle_time * 1000, boost::bind(&ChunkServerManager::DeadCheck, this)); } void ChunkServerManager::IncChunkServerNum() { ++chunkserver_num_; } int32_t ChunkServerManager::GetChunkServerNum() { return chunkserver_num_; } void ChunkServerManager::HandleRegister(const RegisterRequest* request, RegisterResponse* response) { const std::string& address = request->chunkserver_addr(); StatusCode status = kOK; int cs_id = -1; MutexLock lock(&mu_); std::map<std::string, int32_t>::iterator it = address_map_.find(address); if (it == address_map_.end()) { cs_id = AddChunkServer(request->chunkserver_addr(), request->disk_quota()); assert(cs_id >= 0); response->set_chunkserver_id(cs_id); } else { cs_id = it->second; ChunkServerInfo* cs_info; bool ret = GetChunkServerPtr(cs_id, &cs_info); assert(ret); if (cs_info->status() == kCsWaitClean || cs_info->status() == kCsCleaning) { status = kNotOK; LOG(INFO, "Reconnect chunkserver C%d %s, cs_num=%d, internal cleaning", cs_id, address.c_str(), chunkserver_num_); } else { UpdateChunkServer(cs_id, request->disk_quota()); LOG(INFO, "Reconnect chunkserver C%d %s, cs_num=%d", cs_id, address.c_str(), chunkserver_num_); } } response->set_chunkserver_id(cs_id); response->set_status(status); } void ChunkServerManager::HandleHeartBeat(const HeartBeatRequest* request, HeartBeatResponse* response) { int32_t id = request->chunkserver_id(); const std::string& address = request->chunkserver_addr(); int cs_id = GetChunkserverId(address); if (id == -1 || cs_id != id) { //reconnect after DeadCheck() LOG(WARNING, "Unknown chunkserver %s with namespace version %ld", address.c_str(), request->namespace_version()); response->set_status(kUnknownCs); return; } response->set_status(kOK); MutexLock lock(&mu_); ChunkServerInfo* info = NULL; bool ret = GetChunkServerPtr(id, &info); assert(ret && info); if (!info->is_dead()) { assert(heartbeat_list_.find(info->last_heartbeat()) != heartbeat_list_.end()); heartbeat_list_[info->last_heartbeat()].erase(info); if (heartbeat_list_[info->last_heartbeat()].empty()) { heartbeat_list_.erase(info->last_heartbeat()); } } else { assert(heartbeat_list_.find(info->last_heartbeat()) == heartbeat_list_.end()); info->set_is_dead(false); } info->set_data_size(request->data_size()); info->set_block_num(request->block_num()); info->set_buffers(request->buffers()); int32_t now_time = common::timer::now_time(); heartbeat_list_[now_time].insert(info); info->set_last_heartbeat(now_time); } void ChunkServerManager::ListChunkServers(::google::protobuf::RepeatedPtrField<ChunkServerInfo>* chunkservers) { MutexLock lock(&mu_, "ListChunkServers", 1000); for (ServerMap::iterator it = chunkservers_.begin(); it != chunkservers_.end(); ++it) { ChunkServerInfo* src = it->second; ChunkServerInfo* dst = chunkservers->Add(); dst->CopyFrom(*src); } } bool ChunkServerManager::GetChunkServerChains(int num, std::vector<std::pair<int32_t,std::string> >* chains, const std::string& client_address) { MutexLock lock(&mu_); if (num > chunkserver_num_) { LOG(WARNING, "not enough alive chunkservers [%ld] for GetChunkServerChains [%d]\n", chunkserver_num_, num); return false; } //first take local cs of client std::map<std::string, int32_t>::iterator client_it = address_map_.lower_bound(client_address); if (client_it != address_map_.end()) { std::string tmp_address(client_it->first, 0, client_it->first.find_last_of(':')); if (tmp_address == client_address) { ChunkServerInfo* cs = NULL; if (GetChunkServerPtr(client_it->second, &cs)) { if (cs->data_size() < cs->disk_quota() && cs->buffers() < FLAGS_chunkserver_max_pending_buffers * 0.8) { chains->push_back(std::make_pair(cs->id(), cs->address())); if (--num == 0) { return true; } } } } } std::map<int32_t, std::set<ChunkServerInfo*> >::iterator it = heartbeat_list_.begin(); std::vector<std::pair<int64_t, ChunkServerInfo*> > loads; for (; it != heartbeat_list_.end(); ++it) { std::set<ChunkServerInfo*>& set = it->second; for (std::set<ChunkServerInfo*>::iterator sit = set.begin(); sit != set.end(); ++sit) { ChunkServerInfo* cs = *sit; if (cs->data_size() < cs->disk_quota() && cs->buffers() < FLAGS_chunkserver_max_pending_buffers * 0.8) { loads.push_back( std::make_pair(cs->data_size(), cs)); } else { LOG(INFO, "Alloc ignore: Chunkserver %s data %ld/%ld buffer %d", cs->address().c_str(), cs->data_size(), cs->disk_quota(), cs->buffers()); } } } if ((int)loads.size() < num) { LOG(WARNING, "Only %ld chunkserver of %ld is not over overladen, GetChunkServerChains(%d) rturne false", loads.size(), chunkserver_num_, num); return false; } std::sort(loads.begin(), loads.end()); // Add random factor int scope = loads.size() - (loads.size() % num); for (int32_t i = num; i < scope; i++) { int round = i / num + 1; int64_t base_load = loads[i % num].first; int ratio = (base_load + 1024) * 100 / (loads[i].first + 1024); if (rand() % 100 < (ratio / round)) { std::swap(loads[i % num], loads[i]); } } for (int i = 0; i < num; ++i) { ChunkServerInfo* cs = loads[i].second; chains->push_back(std::make_pair(cs->id(), cs->address())); } return true; } bool ChunkServerManager::UpdateChunkServer(int cs_id, int64_t quota) { mu_.AssertHeld(); ChunkServerInfo* info = NULL; if (!GetChunkServerPtr(cs_id, &info)) { return false; } info->set_disk_quota(quota); info->set_status(kCsActive); if (info->is_dead()) { int32_t now_time = common::timer::now_time(); heartbeat_list_[now_time].insert(info); info->set_last_heartbeat(now_time); info->set_is_dead(false); chunkserver_num_ ++; } return true; } int32_t ChunkServerManager::AddChunkServer(const std::string& address, int64_t quota) { mu_.AssertHeld(); ChunkServerInfo* info = new ChunkServerInfo; int32_t id = next_chunkserver_id_++; info->set_id(id); info->set_address(address); info->set_disk_quota(quota); info->set_status(kCsActive); LOG(INFO, "New ChunkServerInfo C%d %s %p", id, address.c_str(), info); chunkservers_[id] = info; address_map_[address] = id; int32_t now_time = common::timer::now_time(); heartbeat_list_[now_time].insert(info); info->set_last_heartbeat(now_time); ++chunkserver_num_; return id; } std::string ChunkServerManager::GetChunkServerAddr(int32_t id) { MutexLock lock(&mu_); ChunkServerInfo* cs = NULL; if (GetChunkServerPtr(id, &cs) && !cs->is_dead()) { return cs->address(); } return ""; } int32_t ChunkServerManager::GetChunkserverId(const std::string& addr) { MutexLock lock(&mu_); std::map<std::string, int32_t>::iterator it = address_map_.find(addr); if (it != address_map_.end()) { return it->second; } return -1; } void ChunkServerManager::AddBlock(int32_t id, int64_t block_id) { MutexLock lock(&mu_); chunkserver_block_map_[id].insert(block_id); } void ChunkServerManager::RemoveBlock(int32_t id, int64_t block_id) { MutexLock lock(&mu_); chunkserver_block_map_[id].erase(block_id); } void ChunkServerManager::PickRecoverBlocks(int cs_id, std::map<int64_t, std::string>* recover_blocks) { MutexLock lock(&mu_); ChunkServerInfo* cs = NULL; if (!GetChunkServerPtr(cs_id, &cs)) { return; } if (cs->buffers() > FLAGS_chunkserver_max_pending_buffers * 0.5) { return; } std::map<int64_t, int32_t> blocks; block_mapping_->PickRecoverBlocks(cs_id, FLAGS_recover_speed, &blocks); for (std::map<int64_t, int32_t>::iterator it = blocks.begin(); it != blocks.end(); ++it) { ChunkServerInfo* cs = NULL; if (!GetChunkServerPtr(it->second, &cs)) { LOG(WARNING, "PickRecoverBlocks for C%d can't find chunkserver C%d", cs_id, it->second); continue; } recover_blocks->insert(std::make_pair(it->first, cs->address())); } LOG(INFO, "C%d picked %lu blocks to recover", cs_id, recover_blocks->size()); } bool ChunkServerManager::GetChunkServerPtr(int32_t cs_id, ChunkServerInfo** cs) { mu_.AssertHeld(); ServerMap::iterator it = chunkservers_.find(cs_id); if (it == chunkservers_.end()) { return false; } if (cs) *cs = it->second; return true; } } // namespace bfs } // namespace baidu <commit_msg>Skip selected local chunkserver<commit_after>// Copyright (c) 2014, Baidu.com, Inc. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chunkserver_manager.h" #include <boost/bind.hpp> #include <gflags/gflags.h> #include <common/logging.h> #include "proto/status_code.pb.h" #include "nameserver/block_mapping.h" DECLARE_int32(keepalive_timeout); DECLARE_int32(chunkserver_max_pending_buffers); DECLARE_int32(recover_speed); namespace baidu { namespace bfs { ChunkServerManager::ChunkServerManager(ThreadPool* thread_pool, BlockMapping* block_mapping) : thread_pool_(thread_pool), block_mapping_(block_mapping), chunkserver_num_(0), next_chunkserver_id_(1) { thread_pool_->AddTask(boost::bind(&ChunkServerManager::DeadCheck, this)); } void ChunkServerManager::CleanChunkserver(ChunkServerInfo* cs, const std::string& reason) { MutexLock lock(&mu_); chunkserver_num_--; LOG(INFO, "Remove Chunkserver C%d %s %s, cs_num=%d", cs->id(), cs->address().c_str(), reason.c_str(), chunkserver_num_); int32_t id = cs->id(); std::set<int64_t> blocks; std::swap(blocks, chunkserver_block_map_[id]); chunkserver_block_map_.erase(id); cs->set_status(kCsCleaning); mu_.Unlock(); block_mapping_->DealWithDeadBlocks(id, blocks); mu_.Lock(); if (cs->is_dead()) { cs->set_status(kCsOffLine); } else { cs->set_status(kCsStandby); } } bool ChunkServerManager::RemoveChunkServer(const std::string& addr) { MutexLock lock(&mu_); std::map<std::string, int32_t>::iterator it = address_map_.find(addr); if (it == address_map_.end()) { return false; } ChunkServerInfo* cs_info = NULL; bool ret = GetChunkServerPtr(it->second, &cs_info); assert(ret); if (cs_info->status() == kCsActive) { cs_info->set_status(kCsWaitClean); boost::function<void ()> task = boost::bind(&ChunkServerManager::CleanChunkserver, this, cs_info, std::string("Dead")); thread_pool_->AddTask(task); } return true; } void ChunkServerManager::DeadCheck() { int32_t now_time = common::timer::now_time(); MutexLock lock(&mu_); std::map<int32_t, std::set<ChunkServerInfo*> >::iterator it = heartbeat_list_.begin(); while (it != heartbeat_list_.end() && it->first + FLAGS_keepalive_timeout <= now_time) { std::set<ChunkServerInfo*>::iterator node = it->second.begin(); while (node != it->second.end()) { ChunkServerInfo* cs = *node; it->second.erase(node++); LOG(INFO, "[DeadCheck] Chunkserver dead C%d %s, cs_num=%d", cs->id(), cs->address().c_str(), chunkserver_num_); cs->set_is_dead(true); if (cs->status() == kCsActive) { cs->set_status(kCsWaitClean); boost::function<void ()> task = boost::bind(&ChunkServerManager::CleanChunkserver, this, cs, std::string("Dead")); thread_pool_->AddTask(task); } else { LOG(INFO, "[DeadCheck] Chunkserver C%d %s is being clean", cs->id(), cs->address().c_str()); } } assert(it->second.empty()); heartbeat_list_.erase(it); it = heartbeat_list_.begin(); } int idle_time = 5; if (it != heartbeat_list_.end()) { idle_time = it->first + FLAGS_keepalive_timeout - now_time; // LOG(INFO, "it->first= %d, now_time= %d\n", it->first, now_time); if (idle_time > 5) { idle_time = 5; } } thread_pool_->DelayTask(idle_time * 1000, boost::bind(&ChunkServerManager::DeadCheck, this)); } void ChunkServerManager::IncChunkServerNum() { ++chunkserver_num_; } int32_t ChunkServerManager::GetChunkServerNum() { return chunkserver_num_; } void ChunkServerManager::HandleRegister(const RegisterRequest* request, RegisterResponse* response) { const std::string& address = request->chunkserver_addr(); StatusCode status = kOK; int cs_id = -1; MutexLock lock(&mu_); std::map<std::string, int32_t>::iterator it = address_map_.find(address); if (it == address_map_.end()) { cs_id = AddChunkServer(request->chunkserver_addr(), request->disk_quota()); assert(cs_id >= 0); response->set_chunkserver_id(cs_id); } else { cs_id = it->second; ChunkServerInfo* cs_info; bool ret = GetChunkServerPtr(cs_id, &cs_info); assert(ret); if (cs_info->status() == kCsWaitClean || cs_info->status() == kCsCleaning) { status = kNotOK; LOG(INFO, "Reconnect chunkserver C%d %s, cs_num=%d, internal cleaning", cs_id, address.c_str(), chunkserver_num_); } else { UpdateChunkServer(cs_id, request->disk_quota()); LOG(INFO, "Reconnect chunkserver C%d %s, cs_num=%d", cs_id, address.c_str(), chunkserver_num_); } } response->set_chunkserver_id(cs_id); response->set_status(status); } void ChunkServerManager::HandleHeartBeat(const HeartBeatRequest* request, HeartBeatResponse* response) { int32_t id = request->chunkserver_id(); const std::string& address = request->chunkserver_addr(); int cs_id = GetChunkserverId(address); if (id == -1 || cs_id != id) { //reconnect after DeadCheck() LOG(WARNING, "Unknown chunkserver %s with namespace version %ld", address.c_str(), request->namespace_version()); response->set_status(kUnknownCs); return; } response->set_status(kOK); MutexLock lock(&mu_); ChunkServerInfo* info = NULL; bool ret = GetChunkServerPtr(id, &info); assert(ret && info); if (!info->is_dead()) { assert(heartbeat_list_.find(info->last_heartbeat()) != heartbeat_list_.end()); heartbeat_list_[info->last_heartbeat()].erase(info); if (heartbeat_list_[info->last_heartbeat()].empty()) { heartbeat_list_.erase(info->last_heartbeat()); } } else { assert(heartbeat_list_.find(info->last_heartbeat()) == heartbeat_list_.end()); info->set_is_dead(false); } info->set_data_size(request->data_size()); info->set_block_num(request->block_num()); info->set_buffers(request->buffers()); int32_t now_time = common::timer::now_time(); heartbeat_list_[now_time].insert(info); info->set_last_heartbeat(now_time); } void ChunkServerManager::ListChunkServers(::google::protobuf::RepeatedPtrField<ChunkServerInfo>* chunkservers) { MutexLock lock(&mu_, "ListChunkServers", 1000); for (ServerMap::iterator it = chunkservers_.begin(); it != chunkservers_.end(); ++it) { ChunkServerInfo* src = it->second; ChunkServerInfo* dst = chunkservers->Add(); dst->CopyFrom(*src); } } bool ChunkServerManager::GetChunkServerChains(int num, std::vector<std::pair<int32_t,std::string> >* chains, const std::string& client_address) { MutexLock lock(&mu_); if (num > chunkserver_num_) { LOG(WARNING, "not enough alive chunkservers [%ld] for GetChunkServerChains [%d]\n", chunkserver_num_, num); return false; } //first take local cs of client std::map<std::string, int32_t>::iterator client_it = address_map_.lower_bound(client_address); if (client_it != address_map_.end()) { std::string tmp_address(client_it->first, 0, client_it->first.find_last_of(':')); if (tmp_address == client_address) { ChunkServerInfo* cs = NULL; if (GetChunkServerPtr(client_it->second, &cs)) { if (cs->data_size() < cs->disk_quota() && cs->buffers() < FLAGS_chunkserver_max_pending_buffers * 0.8) { chains->push_back(std::make_pair(cs->id(), cs->address())); if (--num == 0) { return true; } } } } } std::map<int32_t, std::set<ChunkServerInfo*> >::iterator it = heartbeat_list_.begin(); std::vector<std::pair<int64_t, ChunkServerInfo*> > loads; for (; it != heartbeat_list_.end(); ++it) { std::set<ChunkServerInfo*>& set = it->second; for (std::set<ChunkServerInfo*>::iterator sit = set.begin(); sit != set.end(); ++sit) { ChunkServerInfo* cs = *sit; if (!chains->empty() && cs->id() == (*(chains->begin())).first) { continue; } if (cs->data_size() < cs->disk_quota() && cs->buffers() < FLAGS_chunkserver_max_pending_buffers * 0.8) { loads.push_back( std::make_pair(cs->data_size(), cs)); } else { LOG(INFO, "Alloc ignore: Chunkserver %s data %ld/%ld buffer %d", cs->address().c_str(), cs->data_size(), cs->disk_quota(), cs->buffers()); } } } if ((int)loads.size() < num) { LOG(WARNING, "Only %ld chunkserver of %ld is not over overladen, GetChunkServerChains(%d) rturne false", loads.size(), chunkserver_num_, num); return false; } std::sort(loads.begin(), loads.end()); // Add random factor int scope = loads.size() - (loads.size() % num); for (int32_t i = num; i < scope; i++) { int round = i / num + 1; int64_t base_load = loads[i % num].first; int ratio = (base_load + 1024) * 100 / (loads[i].first + 1024); if (rand() % 100 < (ratio / round)) { std::swap(loads[i % num], loads[i]); } } for (int i = 0; i < num; ++i) { ChunkServerInfo* cs = loads[i].second; chains->push_back(std::make_pair(cs->id(), cs->address())); } return true; } bool ChunkServerManager::UpdateChunkServer(int cs_id, int64_t quota) { mu_.AssertHeld(); ChunkServerInfo* info = NULL; if (!GetChunkServerPtr(cs_id, &info)) { return false; } info->set_disk_quota(quota); info->set_status(kCsActive); if (info->is_dead()) { int32_t now_time = common::timer::now_time(); heartbeat_list_[now_time].insert(info); info->set_last_heartbeat(now_time); info->set_is_dead(false); chunkserver_num_ ++; } return true; } int32_t ChunkServerManager::AddChunkServer(const std::string& address, int64_t quota) { mu_.AssertHeld(); ChunkServerInfo* info = new ChunkServerInfo; int32_t id = next_chunkserver_id_++; info->set_id(id); info->set_address(address); info->set_disk_quota(quota); info->set_status(kCsActive); LOG(INFO, "New ChunkServerInfo C%d %s %p", id, address.c_str(), info); chunkservers_[id] = info; address_map_[address] = id; int32_t now_time = common::timer::now_time(); heartbeat_list_[now_time].insert(info); info->set_last_heartbeat(now_time); ++chunkserver_num_; return id; } std::string ChunkServerManager::GetChunkServerAddr(int32_t id) { MutexLock lock(&mu_); ChunkServerInfo* cs = NULL; if (GetChunkServerPtr(id, &cs) && !cs->is_dead()) { return cs->address(); } return ""; } int32_t ChunkServerManager::GetChunkserverId(const std::string& addr) { MutexLock lock(&mu_); std::map<std::string, int32_t>::iterator it = address_map_.find(addr); if (it != address_map_.end()) { return it->second; } return -1; } void ChunkServerManager::AddBlock(int32_t id, int64_t block_id) { MutexLock lock(&mu_); chunkserver_block_map_[id].insert(block_id); } void ChunkServerManager::RemoveBlock(int32_t id, int64_t block_id) { MutexLock lock(&mu_); chunkserver_block_map_[id].erase(block_id); } void ChunkServerManager::PickRecoverBlocks(int cs_id, std::map<int64_t, std::string>* recover_blocks) { MutexLock lock(&mu_); ChunkServerInfo* cs = NULL; if (!GetChunkServerPtr(cs_id, &cs)) { return; } if (cs->buffers() > FLAGS_chunkserver_max_pending_buffers * 0.5) { return; } std::map<int64_t, int32_t> blocks; block_mapping_->PickRecoverBlocks(cs_id, FLAGS_recover_speed, &blocks); for (std::map<int64_t, int32_t>::iterator it = blocks.begin(); it != blocks.end(); ++it) { ChunkServerInfo* cs = NULL; if (!GetChunkServerPtr(it->second, &cs)) { LOG(WARNING, "PickRecoverBlocks for C%d can't find chunkserver C%d", cs_id, it->second); continue; } recover_blocks->insert(std::make_pair(it->first, cs->address())); } LOG(INFO, "C%d picked %lu blocks to recover", cs_id, recover_blocks->size()); } bool ChunkServerManager::GetChunkServerPtr(int32_t cs_id, ChunkServerInfo** cs) { mu_.AssertHeld(); ServerMap::iterator it = chunkservers_.find(cs_id); if (it == chunkservers_.end()) { return false; } if (cs) *cs = it->second; return true; } } // namespace bfs } // namespace baidu <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /** * $Log$ * Revision 1.4 2000/01/12 19:11:49 aruna1 * XMLCh now defined to wchar_t * * Revision 1.3 1999/11/12 20:36:51 rahulj * Changed library name to xerces-c.lib. * * Revision 1.1.1.1 1999/11/09 01:07:31 twl * Initial checkin * * Revision 1.3 1999/11/08 20:45:22 rahul * Swat for adding in Product name and CVS comment log variable. * */ // --------------------------------------------------------------------------- // Define these away for this platform // --------------------------------------------------------------------------- #define PLATFORM_EXPORT #define PLATFORM_IMPORT // --------------------------------------------------------------------------- // Indicate that we do not support native bools // --------------------------------------------------------------------------- #define NO_NATIVE_BOOL // --------------------------------------------------------------------------- // Define our version of the XML character // --------------------------------------------------------------------------- //typedef unsigned short XMLCh; typedef wchar_t XMLCh; // --------------------------------------------------------------------------- // Define unsigned 16 and 32 bits integers // --------------------------------------------------------------------------- typedef unsigned short XMLUInt16; typedef unsigned int XMLUInt32; // --------------------------------------------------------------------------- // Force on the XML4C debug token if it was on in the build environment // --------------------------------------------------------------------------- #if 0 #define XML4C_DEBUG #endif // --------------------------------------------------------------------------- // Provide some common string ops that are different/notavail on CSet // --------------------------------------------------------------------------- inline char toupper(const char toUpper) { if ((toUpper >= 'a') && (toUpper <= 'z')) return char(toUpper - 0x20); return toUpper; } inline char tolower(const char toLower) { if ((toLower >= 'A') && (toLower <= 'Z')) return char(toLower + 0x20); return toLower; } int stricmp(const char* const str1, const char* const str2); int strnicmp(const char* const str1, const char* const str2, const unsigned int count); // --------------------------------------------------------------------------- // The name of the DLL that is built by the CSet C++ version of the system. // --------------------------------------------------------------------------- const char* const XML4C_DLLName = "libxerces-c"; <commit_msg>Added L"string" support for cset compiler<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /** * $Log$ * Revision 1.5 2000/01/14 02:28:16 aruna1 * Added L"string" support for cset compiler * * Revision 1.4 2000/01/12 19:11:49 aruna1 * XMLCh now defined to wchar_t * * Revision 1.3 1999/11/12 20:36:51 rahulj * Changed library name to xerces-c.lib. * * Revision 1.1.1.1 1999/11/09 01:07:31 twl * Initial checkin * * Revision 1.3 1999/11/08 20:45:22 rahul * Swat for adding in Product name and CVS comment log variable. * */ // --------------------------------------------------------------------------- // Define these away for this platform // --------------------------------------------------------------------------- #define PLATFORM_EXPORT #define PLATFORM_IMPORT // --------------------------------------------------------------------------- // Supports L"" prefixed constants. There are places // where it is advantageous to use the L"" where it supported, to avoid // unnecessary transcoding. xlC_r does support this, so we define this token. // If your compiler does not support it, don't define this. // --------------------------------------------------------------------------- #define XML_LSTRSUPPORT // --------------------------------------------------------------------------- // Indicate that we do not support native bools // --------------------------------------------------------------------------- #define NO_NATIVE_BOOL // --------------------------------------------------------------------------- // Define our version of the XML character // --------------------------------------------------------------------------- //typedef unsigned short XMLCh; typedef wchar_t XMLCh; // --------------------------------------------------------------------------- // Define unsigned 16 and 32 bits integers // --------------------------------------------------------------------------- typedef unsigned short XMLUInt16; typedef unsigned int XMLUInt32; // --------------------------------------------------------------------------- // Force on the XML4C debug token if it was on in the build environment // --------------------------------------------------------------------------- #if 0 #define XML4C_DEBUG #endif // --------------------------------------------------------------------------- // Provide some common string ops that are different/notavail on CSet // --------------------------------------------------------------------------- inline char toupper(const char toUpper) { if ((toUpper >= 'a') && (toUpper <= 'z')) return char(toUpper - 0x20); return toUpper; } inline char tolower(const char toLower) { if ((toLower >= 'A') && (toLower <= 'Z')) return char(toLower + 0x20); return toLower; } int stricmp(const char* const str1, const char* const str2); int strnicmp(const char* const str1, const char* const str2, const unsigned int count); // --------------------------------------------------------------------------- // The name of the DLL that is built by the CSet C++ version of the system. // --------------------------------------------------------------------------- const char* const XML4C_DLLName = "libxerces-c"; <|endoftext|>
<commit_before>// Copyright 2010-2014 Google // 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 <algorithm> #include <string> #include <vector> #include "base/integral_types.h" #include "base/logging.h" #include "base/stringprintf.h" #include "base/int_type.h" #include "base/int_type_indexed_vector.h" #include "base/hash.h" #include "constraint_solver/constraint_solver.h" #include "constraint_solver/constraint_solveri.h" #include "util/string_array.h" DEFINE_bool(cp_diffn_use_cumulative, false, "Diffn constraint adds redundant cumulative constraint"); namespace operations_research { // Diffn constraint, Non overlapping boxs. namespace { DEFINE_INT_TYPE(Box, int); class Diffn : public Constraint { public: Diffn(Solver* const solver, const std::vector<IntVar*>& x_vars, const std::vector<IntVar*>& y_vars, const std::vector<IntVar*>& x_size, const std::vector<IntVar*>& y_size) : Constraint(solver), x_(x_vars), y_(y_vars), dx_(x_size), dy_(y_size), size_(x_vars.size()), fail_stamp_(0) { CHECK_EQ(x_vars.size(), y_vars.size()); CHECK_EQ(x_vars.size(), x_size.size()); CHECK_EQ(x_vars.size(), y_size.size()); } virtual ~Diffn() {} virtual void Post() { Solver* const s = solver(); for (int i = 0; i < size_; ++i) { Demon* const demon = MakeConstraintDemon1( s, this, &Diffn::OnBoxRangeChange, "OnBoxRangeChange", i); x_[i]->WhenRange(demon); y_[i]->WhenRange(demon); dx_[i]->WhenRange(demon); dy_[i]->WhenRange(demon); } delayed_demon_ = MakeDelayedConstraintDemon0(s, this, &Diffn::PropagateAll, "PropagateAll"); if (FLAGS_cp_diffn_use_cumulative && AreAllBound(dx_) && AreAllBound(dy_) && IsArrayInRange(x_, 0LL, kint64max) && IsArrayInRange(y_, 0LL, kint64max)) { Constraint* ct1 = nullptr; Constraint* ct2 = nullptr; { // We can add redundant cumulative constraints. This is done // inside a c++ block to avoid leaking memory if adding the // constraints leads to a failure. A cumulative constraint is // a scheduling constraint that will perform finer energy // based reasoning to do more propagation. (see Solver::MakeCumulative). const int64 min_x = MinVarArray(x_); const int64 max_x = MaxVarArray(x_); const int64 max_size_x = MaxVarArray(dx_); const int64 min_y = MinVarArray(y_); const int64 max_y = MaxVarArray(y_); const int64 max_size_y = MaxVarArray(dy_); std::vector<int64> size_x; FillValues(dx_, &size_x); std::vector<int64> size_y; FillValues(dy_, &size_y); ct1 = MakeCumulativeConstraint(x_, size_x, size_y, max_size_y + max_y - min_y); ct2 = MakeCumulativeConstraint(y_, size_y, size_x, max_size_x + max_x - min_x); } s->AddConstraint(ct1); s->AddConstraint(ct2); } } virtual void InitialPropagate() { // All sizes should be > 0. for (int i = 0; i < size_; ++i) { dx_[i]->SetMin(1); dy_[i]->SetMin(1); } // Force propagation on all boxes. to_propagate_.clear(); for (int i = 0; i < size_; i++) { to_propagate_.insert(i); } PropagateAll(); } virtual std::string DebugString() const { return StringPrintf("Diffn(x = [%s], y = [%s], dx = [%s], dy = [%s]))", JoinDebugStringPtr(x_, ", ").c_str(), JoinDebugStringPtr(y_, ", ").c_str(), JoinDebugStringPtr(dx_, ", ").c_str(), JoinDebugStringPtr(dy_, ", ").c_str()); } virtual void Accept(ModelVisitor* const visitor) const { visitor->BeginVisitConstraint(ModelVisitor::kDisjunctive, this); visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kPositionXArgument, x_); visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kPositionYArgument, y_); visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kSizeXArgument, dx_); visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kSizeYArgument, dy_); visitor->EndVisitConstraint(ModelVisitor::kDisjunctive, this); } private: void PropagateAll() { for (const int box : to_propagate_) { FillNeighbors(box); FailWhenEnergyIsTooLarge(box); PushOverlappingBoxes(box); } to_propagate_.clear(); fail_stamp_ = solver()->fail_stamp(); } void OnBoxRangeChange(int box) { if (solver()->fail_stamp() > fail_stamp_ && !to_propagate_.empty()) { // We have failed in the last propagation and the to_propagate_ // was not cleared. fail_stamp_ = solver()->fail_stamp(); to_propagate_.clear(); } to_propagate_.insert(box); EnqueueDelayedDemon(delayed_demon_); } bool CanBoxedOverlap(int i, int j) const { if (AreBoxedDisjoingHorizontallyForSure(i, j) || AreBoxedDisjoingVerticallyForSure(i, j)) { return false; } return true; } bool AreBoxedDisjoingHorizontallyForSure(int i, int j) const { return (x_[i]->Min() >= x_[j]->Max() + dx_[j]->Max()) || (x_[j]->Min() >= x_[i]->Max() + dx_[i]->Max()); } bool AreBoxedDisjoingVerticallyForSure(int i, int j) const { return (y_[i]->Min() >= y_[j]->Max() + dy_[j]->Max()) || (y_[j]->Min() >= y_[i]->Max() + dy_[i]->Max()); } // Fill neighbors_ with all boxes that can overlap the given box. void FillNeighbors(int box) { // TODO(user): We could maintain a non reversible list of // neighbors and clean it after each failure. neighbors_.clear(); for (int other = 0; other < size_; ++other) { if (other != box && CanBoxedOverlap(other, box)) { neighbors_.push_back(other); } } } // Fails if the minimum area of the given box plus the area of its neighbors // (that must already be computed in neighbors_) is greater than the area of a // bounding box that necessarily contains all these boxes. void FailWhenEnergyIsTooLarge(int box) { int64 area_min_x = x_[box]->Min(); int64 area_max_x = x_[box]->Max() + dx_[box]->Max(); int64 area_min_y = y_[box]->Min(); int64 area_max_y = y_[box]->Max() + dy_[box]->Max(); int64 sum_of_areas = dx_[box]->Min() * dy_[box]->Min(); // TODO(user): Is there a better order, maybe sort by distance // with the current box. for (int i = 0; i < neighbors_.size(); ++i) { const int other = neighbors_[i]; // Update Bounding box. area_min_x = std::min(area_min_x, x_[other]->Min()); area_max_x = std::max(area_max_x, x_[other]->Max() + dx_[other]->Max()); area_min_y = std::min(area_min_y, y_[other]->Min()); area_max_y = std::max(area_max_y, y_[other]->Max() + dy_[other]->Max()); // Update sum of areas. sum_of_areas += dx_[other]->Min() * dy_[other]->Min(); const int64 bounding_area = (area_max_x - area_min_x) * (area_max_y - area_min_y); if (sum_of_areas > bounding_area) { solver()->Fail(); } } } // Changes the domain of all the neighbors of a given box (that must // already be computed in neighbors_) so that they can't overlap the // mandatory part of the given box. void PushOverlappingBoxes(int box) { for (int i = 0; i < neighbors_.size(); ++i) { PushOneBox(box, neighbors_[i]); } } // Changes the domain of the two given box by excluding the value that // make them overlap for sure. Note that this function is symmetric in // the sense that its argument can be swapped for the same result. void PushOneBox(int box, int other) { const int state = (x_[box]->Min() + dx_[box]->Min() <= x_[other]->Max()) + 2 * (x_[other]->Min() + dx_[other]->Min() <= x_[box]->Max()) + 4 * (y_[box]->Min() + dy_[box]->Min() <= y_[other]->Max()) + 8 * (y_[other]->Min() + dy_[other]->Min() <= y_[box]->Max()); // This is an "hack" to be able to easily test for none or for one // and only one of the conditions below. switch (state) { case 0: { solver()->Fail(); break; } case 1: { // We push other left (x increasing). x_[other]->SetMin(x_[box]->Min() + dx_[box]->Min()); x_[box]->SetMax(x_[other]->Max() - dx_[box]->Min()); dx_[box]->SetMax(x_[other]->Max() - x_[box]->Min()); break; } case 2: { // We push other right (x decreasing). x_[box]->SetMin(x_[other]->Min() + dx_[other]->Min()); x_[other]->SetMax(x_[box]->Max() - dx_[other]->Min()); dx_[other]->SetMax(x_[box]->Max() - x_[other]->Min()); break; } case 4: { // We push other up (y increasing). y_[other]->SetMin(y_[box]->Min() + dy_[box]->Min()); y_[box]->SetMax(y_[other]->Max() - dy_[box]->Min()); dy_[box]->SetMax(y_[other]->Max() - y_[box]->Min()); break; } case 8: { // We push other down (y decreasing). y_[box]->SetMin(y_[other]->Min() + dy_[other]->Min()); y_[other]->SetMax(y_[box]->Max() - dy_[other]->Min()); dy_[other]->SetMax(y_[box]->Max() - y_[other]->Min()); break; } default: { break; } } } Constraint* MakeCumulativeConstraint(const std::vector<IntVar*>& positions, const std::vector<int64>& sizes, const std::vector<int64>& demands, int64 capacity) { std::vector<IntervalVar*> intervals; solver()->MakeFixedDurationIntervalVarArray(positions, sizes, "interval", &intervals); return solver()->MakeCumulative(intervals, demands, capacity, "cumul"); } std::vector<IntVar*> x_; std::vector<IntVar*> y_; std::vector<IntVar*> dx_; std::vector<IntVar*> dy_; const int64 size_; Demon* delayed_demon_; hash_set<int> to_propagate_; std::vector<int> neighbors_; uint64 fail_stamp_; }; } // namespace Constraint* Solver::MakeNonOverlappingBoxesConstraint( const std::vector<IntVar*>& x_vars, const std::vector<IntVar*>& y_vars, const std::vector<IntVar*>& x_size, const std::vector<IntVar*>& y_size) { return RevAlloc(new Diffn(this, x_vars, y_vars, x_size, y_size)); } Constraint* Solver::MakeNonOverlappingBoxesConstraint( const std::vector<IntVar*>& x_vars, const std::vector<IntVar*>& y_vars, const std::vector<int64>& x_size, const std::vector<int64>& y_size) { std::vector<IntVar*> dx(x_size.size()); std::vector<IntVar*> dy(y_size.size()); for (int i = 0; i < x_size.size(); ++i) { dx[i] = MakeIntConst(x_size[i]); dy[i] = MakeIntConst(y_size[i]); } return RevAlloc(new Diffn(this, x_vars, y_vars, dx, dy)); } Constraint* Solver::MakeNonOverlappingBoxesConstraint( const std::vector<IntVar*>& x_vars, const std::vector<IntVar*>& y_vars, const std::vector<int>& x_size, const std::vector<int>& y_size) { std::vector<IntVar*> dx(x_size.size()); std::vector<IntVar*> dy(y_size.size()); for (int i = 0; i < x_size.size(); ++i) { dx[i] = MakeIntConst(x_size[i]); dy[i] = MakeIntConst(y_size[i]); } return RevAlloc(new Diffn(this, x_vars, y_vars, dx, dy)); } } // namespace operations_research <commit_msg>diffn now uses variable demand cumulative constraint<commit_after>// Copyright 2010-2014 Google // 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 <algorithm> #include <string> #include <vector> #include "base/integral_types.h" #include "base/logging.h" #include "base/stringprintf.h" #include "base/int_type.h" #include "base/int_type_indexed_vector.h" #include "base/hash.h" #include "constraint_solver/constraint_solver.h" #include "constraint_solver/constraint_solveri.h" #include "util/string_array.h" DEFINE_bool(cp_diffn_use_cumulative, true, "Diffn constraint adds redundant cumulative constraint"); namespace operations_research { // Diffn constraint, Non overlapping boxs. namespace { DEFINE_INT_TYPE(Box, int); class Diffn : public Constraint { public: Diffn(Solver* const solver, const std::vector<IntVar*>& x_vars, const std::vector<IntVar*>& y_vars, const std::vector<IntVar*>& x_size, const std::vector<IntVar*>& y_size) : Constraint(solver), x_(x_vars), y_(y_vars), dx_(x_size), dy_(y_size), size_(x_vars.size()), fail_stamp_(0) { CHECK_EQ(x_vars.size(), y_vars.size()); CHECK_EQ(x_vars.size(), x_size.size()); CHECK_EQ(x_vars.size(), y_size.size()); } virtual ~Diffn() {} virtual void Post() { Solver* const s = solver(); for (int i = 0; i < size_; ++i) { Demon* const demon = MakeConstraintDemon1( s, this, &Diffn::OnBoxRangeChange, "OnBoxRangeChange", i); x_[i]->WhenRange(demon); y_[i]->WhenRange(demon); dx_[i]->WhenRange(demon); dy_[i]->WhenRange(demon); } delayed_demon_ = MakeDelayedConstraintDemon0(s, this, &Diffn::PropagateAll, "PropagateAll"); if (FLAGS_cp_diffn_use_cumulative && IsArrayInRange(x_, 0LL, kint64max) && IsArrayInRange(y_, 0LL, kint64max)) { Constraint* ct1 = nullptr; Constraint* ct2 = nullptr; { // We can add redundant cumulative constraints. This is done // inside a c++ block to avoid leaking memory if adding the // constraints leads to a failure. A cumulative constraint is // a scheduling constraint that will perform finer energy // based reasoning to do more propagation. (see Solver::MakeCumulative). const int64 min_x = MinVarArray(x_); const int64 max_x = MaxVarArray(x_); const int64 max_size_x = MaxVarArray(dx_); const int64 min_y = MinVarArray(y_); const int64 max_y = MaxVarArray(y_); const int64 max_size_y = MaxVarArray(dy_); if (AreAllBound(dx_)) { std::vector<int64> size_x; FillValues(dx_, &size_x); ct1 = MakeCumulativeConstraint( x_, size_x, dy_, max_size_y + max_y - min_y); } if (AreAllBound(dy_)) { std::vector<int64> size_y; FillValues(dy_, &size_y); ct2 = MakeCumulativeConstraint( y_, size_y, dx_, max_size_x + max_x - min_x); } } if (ct1 != nullptr) { s->AddConstraint(ct1); } if (ct2 != nullptr) { s->AddConstraint(ct2); } } } virtual void InitialPropagate() { // All sizes should be > 0. for (int i = 0; i < size_; ++i) { dx_[i]->SetMin(1); dy_[i]->SetMin(1); } // Force propagation on all boxes. to_propagate_.clear(); for (int i = 0; i < size_; i++) { to_propagate_.insert(i); } PropagateAll(); } virtual std::string DebugString() const { return StringPrintf("Diffn(x = [%s], y = [%s], dx = [%s], dy = [%s]))", JoinDebugStringPtr(x_, ", ").c_str(), JoinDebugStringPtr(y_, ", ").c_str(), JoinDebugStringPtr(dx_, ", ").c_str(), JoinDebugStringPtr(dy_, ", ").c_str()); } virtual void Accept(ModelVisitor* const visitor) const { visitor->BeginVisitConstraint(ModelVisitor::kDisjunctive, this); visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kPositionXArgument, x_); visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kPositionYArgument, y_); visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kSizeXArgument, dx_); visitor->VisitIntegerVariableArrayArgument(ModelVisitor::kSizeYArgument, dy_); visitor->EndVisitConstraint(ModelVisitor::kDisjunctive, this); } private: void PropagateAll() { for (const int box : to_propagate_) { FillNeighbors(box); FailWhenEnergyIsTooLarge(box); PushOverlappingBoxes(box); } to_propagate_.clear(); fail_stamp_ = solver()->fail_stamp(); } void OnBoxRangeChange(int box) { if (solver()->fail_stamp() > fail_stamp_ && !to_propagate_.empty()) { // We have failed in the last propagation and the to_propagate_ // was not cleared. fail_stamp_ = solver()->fail_stamp(); to_propagate_.clear(); } to_propagate_.insert(box); EnqueueDelayedDemon(delayed_demon_); } bool CanBoxedOverlap(int i, int j) const { if (AreBoxedDisjoingHorizontallyForSure(i, j) || AreBoxedDisjoingVerticallyForSure(i, j)) { return false; } return true; } bool AreBoxedDisjoingHorizontallyForSure(int i, int j) const { return (x_[i]->Min() >= x_[j]->Max() + dx_[j]->Max()) || (x_[j]->Min() >= x_[i]->Max() + dx_[i]->Max()); } bool AreBoxedDisjoingVerticallyForSure(int i, int j) const { return (y_[i]->Min() >= y_[j]->Max() + dy_[j]->Max()) || (y_[j]->Min() >= y_[i]->Max() + dy_[i]->Max()); } // Fill neighbors_ with all boxes that can overlap the given box. void FillNeighbors(int box) { // TODO(user): We could maintain a non reversible list of // neighbors and clean it after each failure. neighbors_.clear(); for (int other = 0; other < size_; ++other) { if (other != box && CanBoxedOverlap(other, box)) { neighbors_.push_back(other); } } } // Fails if the minimum area of the given box plus the area of its neighbors // (that must already be computed in neighbors_) is greater than the area of a // bounding box that necessarily contains all these boxes. void FailWhenEnergyIsTooLarge(int box) { int64 area_min_x = x_[box]->Min(); int64 area_max_x = x_[box]->Max() + dx_[box]->Max(); int64 area_min_y = y_[box]->Min(); int64 area_max_y = y_[box]->Max() + dy_[box]->Max(); int64 sum_of_areas = dx_[box]->Min() * dy_[box]->Min(); // TODO(user): Is there a better order, maybe sort by distance // with the current box. for (int i = 0; i < neighbors_.size(); ++i) { const int other = neighbors_[i]; // Update Bounding box. area_min_x = std::min(area_min_x, x_[other]->Min()); area_max_x = std::max(area_max_x, x_[other]->Max() + dx_[other]->Max()); area_min_y = std::min(area_min_y, y_[other]->Min()); area_max_y = std::max(area_max_y, y_[other]->Max() + dy_[other]->Max()); // Update sum of areas. sum_of_areas += dx_[other]->Min() * dy_[other]->Min(); const int64 bounding_area = (area_max_x - area_min_x) * (area_max_y - area_min_y); if (sum_of_areas > bounding_area) { solver()->Fail(); } } } // Changes the domain of all the neighbors of a given box (that must // already be computed in neighbors_) so that they can't overlap the // mandatory part of the given box. void PushOverlappingBoxes(int box) { for (int i = 0; i < neighbors_.size(); ++i) { PushOneBox(box, neighbors_[i]); } } // Changes the domain of the two given box by excluding the value that // make them overlap for sure. Note that this function is symmetric in // the sense that its argument can be swapped for the same result. void PushOneBox(int box, int other) { const int state = (x_[box]->Min() + dx_[box]->Min() <= x_[other]->Max()) + 2 * (x_[other]->Min() + dx_[other]->Min() <= x_[box]->Max()) + 4 * (y_[box]->Min() + dy_[box]->Min() <= y_[other]->Max()) + 8 * (y_[other]->Min() + dy_[other]->Min() <= y_[box]->Max()); // This is an "hack" to be able to easily test for none or for one // and only one of the conditions below. switch (state) { case 0: { solver()->Fail(); break; } case 1: { // We push other left (x increasing). x_[other]->SetMin(x_[box]->Min() + dx_[box]->Min()); x_[box]->SetMax(x_[other]->Max() - dx_[box]->Min()); dx_[box]->SetMax(x_[other]->Max() - x_[box]->Min()); break; } case 2: { // We push other right (x decreasing). x_[box]->SetMin(x_[other]->Min() + dx_[other]->Min()); x_[other]->SetMax(x_[box]->Max() - dx_[other]->Min()); dx_[other]->SetMax(x_[box]->Max() - x_[other]->Min()); break; } case 4: { // We push other up (y increasing). y_[other]->SetMin(y_[box]->Min() + dy_[box]->Min()); y_[box]->SetMax(y_[other]->Max() - dy_[box]->Min()); dy_[box]->SetMax(y_[other]->Max() - y_[box]->Min()); break; } case 8: { // We push other down (y decreasing). y_[box]->SetMin(y_[other]->Min() + dy_[other]->Min()); y_[other]->SetMax(y_[box]->Max() - dy_[other]->Min()); dy_[other]->SetMax(y_[box]->Max() - y_[other]->Min()); break; } default: { break; } } } Constraint* MakeCumulativeConstraint(const std::vector<IntVar*>& positions, const std::vector<int64>& sizes, const std::vector<IntVar*>& demands, int64 capacity) { std::vector<IntervalVar*> intervals; solver()->MakeFixedDurationIntervalVarArray(positions, sizes, "interval", &intervals); return solver()->MakeCumulative(intervals, demands, capacity, "cumul"); } std::vector<IntVar*> x_; std::vector<IntVar*> y_; std::vector<IntVar*> dx_; std::vector<IntVar*> dy_; const int64 size_; Demon* delayed_demon_; hash_set<int> to_propagate_; std::vector<int> neighbors_; uint64 fail_stamp_; }; } // namespace Constraint* Solver::MakeNonOverlappingBoxesConstraint( const std::vector<IntVar*>& x_vars, const std::vector<IntVar*>& y_vars, const std::vector<IntVar*>& x_size, const std::vector<IntVar*>& y_size) { return RevAlloc(new Diffn(this, x_vars, y_vars, x_size, y_size)); } Constraint* Solver::MakeNonOverlappingBoxesConstraint( const std::vector<IntVar*>& x_vars, const std::vector<IntVar*>& y_vars, const std::vector<int64>& x_size, const std::vector<int64>& y_size) { std::vector<IntVar*> dx(x_size.size()); std::vector<IntVar*> dy(y_size.size()); for (int i = 0; i < x_size.size(); ++i) { dx[i] = MakeIntConst(x_size[i]); dy[i] = MakeIntConst(y_size[i]); } return RevAlloc(new Diffn(this, x_vars, y_vars, dx, dy)); } Constraint* Solver::MakeNonOverlappingBoxesConstraint( const std::vector<IntVar*>& x_vars, const std::vector<IntVar*>& y_vars, const std::vector<int>& x_size, const std::vector<int>& y_size) { std::vector<IntVar*> dx(x_size.size()); std::vector<IntVar*> dy(y_size.size()); for (int i = 0; i < x_size.size(); ++i) { dx[i] = MakeIntConst(x_size[i]); dy[i] = MakeIntConst(y_size[i]); } return RevAlloc(new Diffn(this, x_vars, y_vars, dx, dy)); } } // namespace operations_research <|endoftext|>