text
stringlengths
54
60.6k
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tpsort.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: vg $ $Date: 2007-02-27 13:27:37 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SC_TPSORT_HXX #define SC_TPSORT_HXX #ifndef _SFXTABDLG_HXX //autogen #include <sfx2/tabdlg.hxx> #endif #ifndef _SV_EDIT_HXX //autogen #include <vcl/edit.hxx> #endif #ifndef _SV_FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _SV_LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _STDCTRL_HXX //autogen #include <svtools/stdctrl.hxx> #endif #ifndef _SVX_LANGBOX_HXX #include <svx/langbox.hxx> #endif #ifndef SC_SCGLOB_HXX #include "global.hxx" #endif #ifndef SC_ADDRESS_HXX #include "address.hxx" #endif //------------------------------------------------------------------------ #define SC_MAXFIELDS 200 class ScViewData; class ScSortDlg; struct ScSortParam; //======================================================================== // Kriterien class ScTabPageSortFields : public SfxTabPage { public: ScTabPageSortFields( Window* pParent, const SfxItemSet& rArgSet ); ~ScTabPageSortFields(); static SfxTabPage* Create ( Window* pParent, const SfxItemSet& rArgSet ); static USHORT* GetRanges (); virtual BOOL FillItemSet ( SfxItemSet& rArgSet ); virtual void Reset ( const SfxItemSet& rArgSet ); protected: // fuer Datenaustausch (sollte noch umgestellt werden!) // virtual void ActivatePage ( const SfxItemSet& rSet ); using SfxTabPage::ActivatePage; using SfxTabPage::DeactivatePage; virtual void ActivatePage (); virtual int DeactivatePage ( SfxItemSet* pSet = 0); private: FixedLine aFlSort1; ListBox aLbSort1; RadioButton aBtnUp1; RadioButton aBtnDown1; FixedLine aFlSort2; ListBox aLbSort2; RadioButton aBtnUp2; RadioButton aBtnDown2; FixedLine aFlSort3; ListBox aLbSort3; RadioButton aBtnUp3; RadioButton aBtnDown3; String aStrUndefined; String aStrColumn; String aStrRow; const USHORT nWhichSort; ScSortDlg* pDlg; ScViewData* pViewData; const ScSortParam& rSortData; SCCOLROW nFieldArr[SC_MAXFIELDS]; USHORT nFieldCount; SCCOL nFirstCol; SCROW nFirstRow; BOOL bHasHeader; BOOL bSortByRows; ListBox* aSortLbArr[3]; RadioButton* aDirBtnArr[3][2]; FixedLine* aFlArr[3]; #ifdef _TPSORT_CXX private: void Init (); void DisableField ( USHORT nField ); void EnableField ( USHORT nField ); void FillFieldLists (); USHORT GetFieldSelPos ( SCCOLROW nField ); // Handler ------------------------ DECL_LINK( SelectHdl, ListBox * ); #endif }; //======================================================================== // Sortieroptionen: class ScDocument; class ScRangeData; class CollatorRessource; class CollatorWrapper; class ScTabPageSortOptions : public SfxTabPage { public: ScTabPageSortOptions( Window* pParent, const SfxItemSet& rArgSet ); ~ScTabPageSortOptions(); static SfxTabPage* Create ( Window* pParent, const SfxItemSet& rArgSet ); static USHORT* GetRanges (); virtual BOOL FillItemSet ( SfxItemSet& rArgSet ); virtual void Reset ( const SfxItemSet& rArgSet ); protected: // fuer Datenaustausch (sollte noch umgestellt werden!) // virtual void ActivatePage ( const SfxItemSet& rSet ); using SfxTabPage::ActivatePage; using SfxTabPage::DeactivatePage; virtual void ActivatePage (); virtual int DeactivatePage ( SfxItemSet* pSet = 0); private: CheckBox aBtnCase; CheckBox aBtnHeader; CheckBox aBtnFormats; CheckBox aBtnCopyResult; ListBox aLbOutPos; Edit aEdOutPos; CheckBox aBtnSortUser; ListBox aLbSortUser; FixedText aFtLanguage; SvxLanguageBox aLbLanguage; FixedText aFtAlgorithm; ListBox aLbAlgorithm; FixedLine aLineDirection; RadioButton aBtnTopDown; RadioButton aBtnLeftRight; FixedText aFtAreaLabel; // FixedInfo aFtArea; String aStrRowLabel; String aStrColLabel; String aStrUndefined; String aStrNoName; String aStrAreaLabel; const USHORT nWhichSort; const ScSortParam& rSortData; ScViewData* pViewData; ScDocument* pDoc; ScSortDlg* pDlg; ScAddress theOutPos; CollatorRessource* pColRes; CollatorWrapper* pColWrap; #ifdef _TPSORT_CXX private: void Init (); void FillUserSortListBox (); void FillOutPosList (); // Handler ------------------------ DECL_LINK( EnableHdl, CheckBox * ); DECL_LINK( SelOutPosHdl, ListBox * ); void EdOutPosModHdl ( Edit* pEd ); DECL_LINK( SortDirHdl, RadioButton * ); DECL_LINK( FillAlgorHdl, void * ); #endif }; #endif // SC_TPSORT_HXX <commit_msg>INTEGRATION: CWS dr58_SRC680 (1.7.188); FILE MERGED 2007/12/21 16:26:41 er 1.7.188.1: #i30977# allow all columns in Sort and Subtotals<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tpsort.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2008-01-29 15:43:11 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SC_TPSORT_HXX #define SC_TPSORT_HXX #ifndef _SFXTABDLG_HXX //autogen #include <sfx2/tabdlg.hxx> #endif #ifndef _SV_EDIT_HXX //autogen #include <vcl/edit.hxx> #endif #ifndef _SV_FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _SV_LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _STDCTRL_HXX //autogen #include <svtools/stdctrl.hxx> #endif #ifndef _SVX_LANGBOX_HXX #include <svx/langbox.hxx> #endif #ifndef SC_SCGLOB_HXX #include "global.hxx" #endif #ifndef SC_ADDRESS_HXX #include "address.hxx" #endif //------------------------------------------------------------------------ // +1 because one field is reserved for the "- undefined -" entry #define SC_MAXFIELDS MAXCOLCOUNT+1 class ScViewData; class ScSortDlg; struct ScSortParam; //======================================================================== // Kriterien class ScTabPageSortFields : public SfxTabPage { public: ScTabPageSortFields( Window* pParent, const SfxItemSet& rArgSet ); ~ScTabPageSortFields(); static SfxTabPage* Create ( Window* pParent, const SfxItemSet& rArgSet ); static USHORT* GetRanges (); virtual BOOL FillItemSet ( SfxItemSet& rArgSet ); virtual void Reset ( const SfxItemSet& rArgSet ); protected: // fuer Datenaustausch (sollte noch umgestellt werden!) // virtual void ActivatePage ( const SfxItemSet& rSet ); using SfxTabPage::ActivatePage; using SfxTabPage::DeactivatePage; virtual void ActivatePage (); virtual int DeactivatePage ( SfxItemSet* pSet = 0); private: FixedLine aFlSort1; ListBox aLbSort1; RadioButton aBtnUp1; RadioButton aBtnDown1; FixedLine aFlSort2; ListBox aLbSort2; RadioButton aBtnUp2; RadioButton aBtnDown2; FixedLine aFlSort3; ListBox aLbSort3; RadioButton aBtnUp3; RadioButton aBtnDown3; String aStrUndefined; String aStrColumn; String aStrRow; const USHORT nWhichSort; ScSortDlg* pDlg; ScViewData* pViewData; const ScSortParam& rSortData; SCCOLROW nFieldArr[SC_MAXFIELDS]; USHORT nFieldCount; SCCOL nFirstCol; SCROW nFirstRow; BOOL bHasHeader; BOOL bSortByRows; ListBox* aSortLbArr[3]; RadioButton* aDirBtnArr[3][2]; FixedLine* aFlArr[3]; #ifdef _TPSORT_CXX private: void Init (); void DisableField ( USHORT nField ); void EnableField ( USHORT nField ); void FillFieldLists (); USHORT GetFieldSelPos ( SCCOLROW nField ); // Handler ------------------------ DECL_LINK( SelectHdl, ListBox * ); #endif }; //======================================================================== // Sortieroptionen: class ScDocument; class ScRangeData; class CollatorRessource; class CollatorWrapper; class ScTabPageSortOptions : public SfxTabPage { public: ScTabPageSortOptions( Window* pParent, const SfxItemSet& rArgSet ); ~ScTabPageSortOptions(); static SfxTabPage* Create ( Window* pParent, const SfxItemSet& rArgSet ); static USHORT* GetRanges (); virtual BOOL FillItemSet ( SfxItemSet& rArgSet ); virtual void Reset ( const SfxItemSet& rArgSet ); protected: // fuer Datenaustausch (sollte noch umgestellt werden!) // virtual void ActivatePage ( const SfxItemSet& rSet ); using SfxTabPage::ActivatePage; using SfxTabPage::DeactivatePage; virtual void ActivatePage (); virtual int DeactivatePage ( SfxItemSet* pSet = 0); private: CheckBox aBtnCase; CheckBox aBtnHeader; CheckBox aBtnFormats; CheckBox aBtnCopyResult; ListBox aLbOutPos; Edit aEdOutPos; CheckBox aBtnSortUser; ListBox aLbSortUser; FixedText aFtLanguage; SvxLanguageBox aLbLanguage; FixedText aFtAlgorithm; ListBox aLbAlgorithm; FixedLine aLineDirection; RadioButton aBtnTopDown; RadioButton aBtnLeftRight; FixedText aFtAreaLabel; // FixedInfo aFtArea; String aStrRowLabel; String aStrColLabel; String aStrUndefined; String aStrNoName; String aStrAreaLabel; const USHORT nWhichSort; const ScSortParam& rSortData; ScViewData* pViewData; ScDocument* pDoc; ScSortDlg* pDlg; ScAddress theOutPos; CollatorRessource* pColRes; CollatorWrapper* pColWrap; #ifdef _TPSORT_CXX private: void Init (); void FillUserSortListBox (); void FillOutPosList (); // Handler ------------------------ DECL_LINK( EnableHdl, CheckBox * ); DECL_LINK( SelOutPosHdl, ListBox * ); void EdOutPosModHdl ( Edit* pEd ); DECL_LINK( SortDirHdl, RadioButton * ); DECL_LINK( FillAlgorHdl, void * ); #endif }; #endif // SC_TPSORT_HXX <|endoftext|>
<commit_before>// // Created by Danni on 09.06.15. // #include "TweeCompiler.h" #include "ZAssemblyGenerator.h" #include "exceptions.h" #include <sstream> #include <iostream> #include <Passage/Body/Link.h> #include <Passage/Body/Text.h> #include <Passage/Body/Newline.h> #include <algorithm> using namespace std; static const string PASSAGE_GLOB = "PASSAGE_PTR", JUMP_TABLE_LABEL = "JUMP_TABLE_START", JUMP_TABLE_END_LABEL = "JUMP_TABLE_END", MAIN_ROUTINE = "main", USER_INPUT = "USER_INPUT", READ_BEGIN = "READ_BEGIN"; static const unsigned int ZSCII_NUM_OFFSET = 49; //#define ZAS_DEBUG void maskString(std::string& string) { std::replace( string.begin(), string.end(), ' ', '_'); } string routineNameForPassageName(std::string passageName) { stringstream ss; maskString(passageName); ss << "R_" << passageName; return ss.str(); } string routineNameForPassage(Passage& passage) { return routineNameForPassageName(passage.getHead().getName()); } string labelForPassage(Passage& passage) { stringstream ss; string passageName = passage.getHead().getName(); maskString(passageName); ss << "L_" << passageName; return ss.str(); } void TweeCompiler::compile(TweeFile &tweeFile, std::ostream &out) { ZAssemblyGenerator assgen(out); vector<Passage> passages = tweeFile.getPassages(); { int i = 0; for (auto passage = passages.begin(); passage != passages.end(); ++passage) { passageName2id[passage->getHead().getName()] = i; i++; } } // main routine { // globals assgen.addGlobal(PASSAGE_GLOB) .addGlobal(USER_INPUT); // call start routine first assgen.addRoutine(MAIN_ROUTINE) .markStart() .call(routineNameForPassageName("start"), PASSAGE_GLOB) .addLabel(JUMP_TABLE_LABEL); for(auto passage = passages.begin(); passage != passages.end(); ++passage) { int passageId = passageName2id.at(passage->getHead().getName()); assgen.jumpEquals(ZAssemblyGenerator::makeArgs({std::to_string(passageId), PASSAGE_GLOB}), labelForPassage(*passage)); } for(auto passage = passages.begin(); passage != passages.end(); ++passage) { assgen.addLabel(labelForPassage(*passage)) .call(routineNameForPassage(*passage), PASSAGE_GLOB) .jump(JUMP_TABLE_LABEL); } assgen.addLabel(JUMP_TABLE_END_LABEL); assgen.quit(); } // passage routines { for(auto passage = passages.begin(); passage != passages.end(); ++passage) { const vector<unique_ptr<BodyPart>>& bodyParts = passage->getBody().getBodyParts(); // declare passage routine assgen.addRoutine(routineNameForPassage(*passage)); assgen.println(string("***** ") + passage->getHead().getName() + string(" *****")); // print passage contents for(auto it = bodyParts.begin(); it != bodyParts.end(); it++) { BodyPart* bodyPart = it->get(); if(Text* text = dynamic_cast<Text*>(bodyPart)) { assgen.print(text->getContent()); } if(Newline* text = dynamic_cast<Newline*>(bodyPart)) { assgen.newline(); } } assgen.newline(); vector<Link*> links; // get links from passage for(auto it = bodyParts.begin(); it != bodyParts.end(); ++it) { BodyPart* bodyPart = it->get(); if(Link* link = dynamic_cast<Link*>(bodyPart)) { links.push_back(link); } } // present choices to user assgen.println("Select one of the following options"); int i = 1; for (auto link = links.begin(); link != links.end(); link++) { assgen.println(string(" ") + to_string(i) + string(") ") + (*link)->getTarget() ); i++; } assgen.addLabel(READ_BEGIN); // read user input assgen.read_char(USER_INPUT); // jump to according link selection i = 0; for (auto link = links.begin(); link != links.end(); link++) { string label = string("L") + to_string(i); assgen.jumpEquals(ZAssemblyGenerator::makeArgs({to_string(ZSCII_NUM_OFFSET + i), USER_INPUT}), label); i++; } // no proper selection was made assgen.jump(READ_BEGIN); i = 0; for (auto link = links.begin(); link != links.end(); link++) { string label = string("L") + to_string(i); try { int targetPassageId = passageName2id.at((*link)->getTarget()); assgen.addLabel(label); #ifdef ZAS_DEBUG assgen.print(string("selected ") + to_string(targetPassageId) ); #endif assgen.ret(to_string(targetPassageId)); } catch (const out_of_range &err) { cerr << "could not find passage for link target \"" << (*link)->getTarget() << "\"" << endl; throw TweeDocumentException(); } i++; } } } } <commit_msg>detect added<commit_after>// // Created by Danni on 09.06.15. // #include "TweeCompiler.h" #include "ZAssemblyGenerator.h" #include "exceptions.h" #include <sstream> #include <iostream> #include <Passage/Body/Link.h> #include <Passage/Body/Text.h> #include <Passage/Body/Newline.h> #include <Passage/Body/Macros/SetMacro.h> #include <plog/Log.h> #include <algorithm> using namespace std; static const string PASSAGE_GLOB = "PASSAGE_PTR", JUMP_TABLE_LABEL = "JUMP_TABLE_START", JUMP_TABLE_END_LABEL = "JUMP_TABLE_END", MAIN_ROUTINE = "main", USER_INPUT = "USER_INPUT", READ_BEGIN = "READ_BEGIN"; static const unsigned int ZSCII_NUM_OFFSET = 49; //#define ZAS_DEBUG void maskString(std::string& string) { std::replace( string.begin(), string.end(), ' ', '_'); } string routineNameForPassageName(std::string passageName) { stringstream ss; maskString(passageName); ss << "R_" << passageName; return ss.str(); } string routineNameForPassage(Passage& passage) { return routineNameForPassageName(passage.getHead().getName()); } string labelForPassage(Passage& passage) { stringstream ss; string passageName = passage.getHead().getName(); maskString(passageName); ss << "L_" << passageName; return ss.str(); } void TweeCompiler::compile(TweeFile &tweeFile, std::ostream &out) { ZAssemblyGenerator assgen(out); vector<Passage> passages = tweeFile.getPassages(); { int i = 0; for (auto passage = passages.begin(); passage != passages.end(); ++passage) { passageName2id[passage->getHead().getName()] = i; i++; } } // main routine { // globals assgen.addGlobal(PASSAGE_GLOB) .addGlobal(USER_INPUT); // call start routine first assgen.addRoutine(MAIN_ROUTINE) .markStart() .call(routineNameForPassageName("start"), PASSAGE_GLOB) .addLabel(JUMP_TABLE_LABEL); for(auto passage = passages.begin(); passage != passages.end(); ++passage) { int passageId = passageName2id.at(passage->getHead().getName()); assgen.jumpEquals(ZAssemblyGenerator::makeArgs({std::to_string(passageId), PASSAGE_GLOB}), labelForPassage(*passage)); } for(auto passage = passages.begin(); passage != passages.end(); ++passage) { assgen.addLabel(labelForPassage(*passage)) .call(routineNameForPassage(*passage), PASSAGE_GLOB) .jump(JUMP_TABLE_LABEL); } assgen.addLabel(JUMP_TABLE_END_LABEL); assgen.quit(); } // passage routines { for(auto passage = passages.begin(); passage != passages.end(); ++passage) { const vector<unique_ptr<BodyPart>>& bodyParts = passage->getBody().getBodyParts(); // declare passage routine assgen.addRoutine(routineNameForPassage(*passage)); assgen.println(string("***** ") + passage->getHead().getName() + string(" *****")); // print passage contents for(auto it = bodyParts.begin(); it != bodyParts.end(); it++) { BodyPart* bodyPart = it->get(); if(Text* text = dynamic_cast<Text*>(bodyPart)) { assgen.print(text->getContent()); } if(Newline* text = dynamic_cast<Newline*>(bodyPart)) { assgen.newline(); } if(SetMacro* macro = dynamic_cast<SetMacro*>(bodyPart)) { std::cout << "huhu"; LOG_DEBUG << "lala"; } } assgen.newline(); vector<Link*> links; // get links from passage for(auto it = bodyParts.begin(); it != bodyParts.end(); ++it) { BodyPart* bodyPart = it->get(); if(Link* link = dynamic_cast<Link*>(bodyPart)) { links.push_back(link); } } // present choices to user assgen.println("Select one of the following options"); int i = 1; for (auto link = links.begin(); link != links.end(); link++) { assgen.println(string(" ") + to_string(i) + string(") ") + (*link)->getTarget() ); i++; } assgen.addLabel(READ_BEGIN); // read user input assgen.read_char(USER_INPUT); // jump to according link selection i = 0; for (auto link = links.begin(); link != links.end(); link++) { string label = string("L") + to_string(i); assgen.jumpEquals(ZAssemblyGenerator::makeArgs({to_string(ZSCII_NUM_OFFSET + i), USER_INPUT}), label); i++; } // no proper selection was made assgen.jump(READ_BEGIN); i = 0; for (auto link = links.begin(); link != links.end(); link++) { string label = string("L") + to_string(i); try { int targetPassageId = passageName2id.at((*link)->getTarget()); assgen.addLabel(label); #ifdef ZAS_DEBUG assgen.print(string("selected ") + to_string(targetPassageId) ); #endif assgen.ret(to_string(targetPassageId)); } catch (const out_of_range &err) { cerr << "could not find passage for link target \"" << (*link)->getTarget() << "\"" << endl; throw TweeDocumentException(); } i++; } } } } <|endoftext|>
<commit_before>#include "rendering/buffers/texture_manager.hh" #include "third_party/imgui/imgui.h" #include "util/clamp.hh" #include "util/eigen_clip.hh" // TODO #include "eigen.hh" namespace jcc { namespace { void show_tooltip(void* tex_id, double draw_w, double draw_h, float region_sz) { const ImGuiIO& io = ImGui::GetIO(); const ImVec2 cursor_pos = ImGui::GetCursorScreenPos(); // Position of mouse in screen coordinates const jcc::Vec2 mouse_from_screen(io.MousePos.x, io.MousePos.y); const jcc::Vec2 image_bl_from_screen(cursor_pos.x, cursor_pos.y); const jcc::Vec2 image_origin_from_screen = image_bl_from_screen - jcc::Vec2(0.0, draw_w); const jcc::Vec2 mouse_from_image = mouse_from_screen - image_origin_from_screen; const jcc::Vec2 region_size(32, 32); const jcc::Vec2 image_size(draw_w, draw_h); const jcc::Vec2 region_min_unclipped = mouse_from_image - (region_size * 0.5); const jcc::Vec2 region_max_unclipped = mouse_from_image + (region_size * 0.5); const jcc::Vec2 region_min = eigen_clip(region_min_unclipped, jcc::Vec2::Zero(), image_size); const jcc::Vec2 region_max = eigen_clip(region_max_unclipped, jcc::Vec2::Zero(), image_size); const jcc::Vec2 uv0 = region_min.array() / image_size.array; const jcc::Vec2 uv1 = region_max.array() / image_size.array; // TODO: Implement a picker ImGui::BeginTooltip(); ImGui::Text("MfromI %.2f, %.2f", mouse_from_image.x(), mouse_from_image.y()); /* float region_x = io.MousePos.x - cursor_pos.x - (region_sz * 0.5f); if (region_x < 0.0f) { region_x = 0.0f; } else if (region_x > draw_w - region_sz) { region_x = draw_w - region_sz; } float region_y = io.MousePos.y - cursor_pos.y - (region_sz * 0.5f); int branch_num = 0; if (region_y < 0.0f) { region_y = 0.0f; branch_num = 1; } else if (region_y > draw_h - region_sz) { // region_y -= draw_h + region_sz; region_y += draw_h - region_sz; branch_num = 2; } */ ImGui::Text("Branch: %d", branch_num); ImGui::Text("Mouse: (%.2f, %.2f)", io.MousePos.x, io.MousePos.y); ImGui::Text("Pos: (%.2f, %.2f)", cursor_pos.x, cursor_pos.y); float zoom = 4.0f; ImGui::Text("Min: (%.2f, %.2f)", region_x, region_y); ImGui::SameLine(); ImGui::Text("Max: (%.2f, %.2f)", region_x + region_sz, region_y + region_sz); const ImVec2 uv0 = ImVec2((region_x) / draw_w, (region_y) / draw_h); const ImVec2 uv1 = ImVec2((region_x + region_sz) / draw_w, (region_y + region_sz) / draw_h); ImGui::Image(tex_id, ImVec2(region_sz * zoom, region_sz * zoom), uv0, uv1, ImVec4(1.0f, 1.0f, 1.0f, 1.0f), ImVec4(1.0f, 1.0f, 1.0f, 0.5f)); ImGui::EndTooltip(); } } // namespace TextureManager::TextureManager() { } void TextureManager::show_ui() const { ImGui::Begin("Textures"); for (const auto& tex_pair : textures_) { const auto& name = tex_pair.first; const auto& tex = tex_pair.second; if (!ImGui::CollapsingHeader(name.c_str())) { continue; } ImGui::Text("%s", name.c_str()); const int width = tex.size().width; const int height = tex.size().height; if (width != 0 && height != 0) { const auto tex_id = (void*)(intptr_t)tex.get_id(); const double draw_w = 0.2 * width; const double draw_h = 0.2 * height; ImGui::Image(tex_id, ImVec2(draw_w, draw_h)); if (ImGui::IsItemHovered()) { show_tooltip(tex_id, draw_w, draw_h, 32.0f); } } } if (ImGui::CollapsingHeader("Picker")) { const ImGuiIO& io = ImGui::GetIO(); constexpr int ORIGIN_X = 0; constexpr int ORIGIN_Y = 0; constexpr int FORMAT = GL_BGR; GLint m_viewport[4]; glGetIntegerv(GL_VIEWPORT, m_viewport); const GLint width_px = m_viewport[2]; const GLint height_px = m_viewport[3]; ImGui::Text("Resolution: %dx%d", m_viewport[2], m_viewport[3]); ImGui::Text("Mouse Location: (%.2f, %.2f)", io.MousePos.x, io.MousePos.y); constexpr int TYPE = GL_UNSIGNED_BYTE; uint8_t* out_data = new uint8_t[width_px * height_px * 3]; glReadPixels(ORIGIN_X, ORIGIN_Y, width_px, height_px, FORMAT, TYPE, out_data); const int col_dist = jcc::clamp(static_cast<int>(io.MousePos.x), 0, width_px); const int row_dist = jcc::clamp(height_px - static_cast<int>(io.MousePos.y), 0, height_px); constexpr int CELLS_PER_PX = 3; const int cells_per_row = CELLS_PER_PX * width_px; const int cells_per_col = CELLS_PER_PX; const int cell = (cells_per_col * col_dist) + (cells_per_row * row_dist); const uint8_t px_r = out_data[cell + 0]; const uint8_t px_g = out_data[cell + 1]; const uint8_t px_b = out_data[cell + 2]; ImGui::Text("Pick Location Info: (%d, %d, %d)", col_dist, row_dist, cell); ImGui::Text("Color @ Pick: (%u, %u, %u)", px_r, px_g, px_b); delete out_data; } ImGui::End(); } } // namespace jcc<commit_msg>Use group intuition for texture preview<commit_after>#include "rendering/buffers/texture_manager.hh" #include "third_party/imgui/imgui.h" #include "util/clamp.hh" #include "util/eigen_clip.hh" // TODO #include "eigen.hh" namespace jcc { namespace { void show_tooltip(void* tex_id, double draw_w, double draw_h, float region_sz) { const ImGuiIO& io = ImGui::GetIO(); const ImVec2 cursor_pos = ImGui::GetCursorScreenPos(); // Position of mouse in screen coordinates const jcc::Vec2 mouse_from_screen(io.MousePos.x, io.MousePos.y); const jcc::Vec2 image_bl_from_screen(cursor_pos.x, cursor_pos.y); const jcc::Vec2 image_origin_from_screen = image_bl_from_screen - jcc::Vec2(0.0, draw_w); const jcc::Vec2 mouse_from_image = mouse_from_screen - image_origin_from_screen; const jcc::Vec2 region_size(region_sz, region_sz); const jcc::Vec2 image_size(draw_w, draw_h); // const jcc::Vec2 region_min_unclipped = mouse_from_image - (region_size * 0.5); // const jcc::Vec2 region_max_unclipped = mouse_from_image + (region_size * 0.5); const jcc::Vec2 region_min_unclipped = mouse_from_image; const jcc::Vec2 region_max_unclipped = mouse_from_image + region_size; const jcc::Vec2 origin = jcc::Vec2::Zero(); const jcc::Vec2 region_min = eigen_clip(region_min_unclipped, origin, image_size); const jcc::Vec2 region_max = eigen_clip(region_max_unclipped, origin, image_size); const jcc::Vec2 uv0 = region_min.array() / image_size.array(); const jcc::Vec2 uv1 = region_max.array() / image_size.array(); // TODO: Implement a picker ImGui::BeginTooltip(); float zoom = 4.0f; ImGui::Text("Min: (%.2f, %.2f)", region_min.x(), region_min.y()); ImGui::SameLine(); ImGui::Text("Max: (%.2f, %.2f)", region_max.x(), region_max.y()); const ImVec2 im_uv0 = ImVec2(uv0.x(), uv0.y()); const ImVec2 im_uv1 = ImVec2(uv1.x(), uv1.y()); ImGui::Image(tex_id, ImVec2(region_sz * zoom, region_sz * zoom), im_uv0, im_uv1, ImVec4(1.0f, 1.0f, 1.0f, 1.0f), ImVec4(1.0f, 1.0f, 1.0f, 0.5f)); ImGui::EndTooltip(); } } // namespace TextureManager::TextureManager() { } void TextureManager::show_ui() const { ImGui::Begin("Textures"); for (const auto& tex_pair : textures_) { const auto& name = tex_pair.first; const auto& tex = tex_pair.second; if (!ImGui::CollapsingHeader(name.c_str())) { continue; } ImGui::Text("%s", name.c_str()); const int width = tex.size().width; const int height = tex.size().height; if (width != 0 && height != 0) { const auto tex_id = (void*)(intptr_t)tex.get_id(); const double draw_w = 0.2 * width; const double draw_h = 0.2 * height; ImGui::Image(tex_id, ImVec2(draw_w, draw_h)); if (ImGui::IsItemHovered()) { show_tooltip(tex_id, draw_w, draw_h, 64.0f); } } } if (ImGui::CollapsingHeader("Picker")) { const ImGuiIO& io = ImGui::GetIO(); constexpr int ORIGIN_X = 0; constexpr int ORIGIN_Y = 0; constexpr int FORMAT = GL_BGR; GLint m_viewport[4]; glGetIntegerv(GL_VIEWPORT, m_viewport); const GLint width_px = m_viewport[2]; const GLint height_px = m_viewport[3]; ImGui::Text("Resolution: %dx%d", m_viewport[2], m_viewport[3]); ImGui::Text("Mouse Location: (%.2f, %.2f)", io.MousePos.x, io.MousePos.y); constexpr int TYPE = GL_UNSIGNED_BYTE; uint8_t* out_data = new uint8_t[width_px * height_px * 3]; glReadPixels(ORIGIN_X, ORIGIN_Y, width_px, height_px, FORMAT, TYPE, out_data); const int col_dist = jcc::clamp(static_cast<int>(io.MousePos.x), 0, width_px); const int row_dist = jcc::clamp(height_px - static_cast<int>(io.MousePos.y), 0, height_px); constexpr int CELLS_PER_PX = 3; const int cells_per_row = CELLS_PER_PX * width_px; const int cells_per_col = CELLS_PER_PX; const int cell = (cells_per_col * col_dist) + (cells_per_row * row_dist); const uint8_t px_r = out_data[cell + 0]; const uint8_t px_g = out_data[cell + 1]; const uint8_t px_b = out_data[cell + 2]; ImGui::Text("Pick Location Info: (%d, %d, %d)", col_dist, row_dist, cell); ImGui::Text("Color @ Pick: (%u, %u, %u)", px_r, px_g, px_b); delete out_data; } ImGui::End(); } } // namespace jcc<|endoftext|>
<commit_before>/* Gobby - GTK-based collaborative text editor * Copyright (C) 2008-2013 Armin Burgmeier <armin@arbur.net> * * 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. * * 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 * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "operations/operation-subscribe-path.hpp" #include "util/i18n.hpp" #include "util/uri.hpp" namespace { std::vector<std::string> split_path(const std::string& path) { std::vector<std::string> result; if(path.empty()) return result; if(path[0] != '/') { throw std::runtime_error( Glib::ustring::compose( Gobby::_("Invalid path: \"%1\""), path)); } std::string::size_type prev = 1, pos; while( (pos = path.find('/', prev)) != std::string::npos) { std::string component = path.substr(prev, pos - prev); if(component.empty()) { throw std::runtime_error( Glib::ustring::compose( Gobby::_("Invalid path " "component: \"%1\""), component)); } result.push_back(component); prev = pos + 1; } // Trailing '/' is allowed std::string component = path.substr(prev); if(!component.empty()) result.push_back(component); return result; } std::string make_path_string(const std::vector<std::string>& path) { std::string result; for(std::vector<std::string>::const_iterator iter = path.begin(); iter != path.end(); ++iter) { result += "/"; result += *iter; } return result; } } Gobby::OperationSubscribePath::OperationSubscribePath(Operations& operations, Folder& folder, const std::string& uri): Operation(operations), m_folder(folder), m_browser(NULL), m_target(uri), m_request(NULL), m_request_finished_id(0), m_notify_status_id(0) { std::string scheme, netloc, path; parse_uri(uri, scheme, netloc, path); if(scheme != "infinote") { throw std::runtime_error( Glib::ustring::compose( _("URI scheme \"%1\" not supported"), scheme)); } m_path = split_path(path); std::string hostname, service; unsigned int device_index; parse_netloc(netloc, hostname, service, device_index); m_resolve_handle = Gobby::resolve( hostname, service, sigc::bind( sigc::mem_fun( *this, &OperationSubscribePath::on_resolv_done), hostname, device_index), sigc::bind( sigc::mem_fun( *this, &OperationSubscribePath::on_resolv_error), hostname)); if(path.empty()) { m_message_handle = get_status_bar().add_info_message( Glib::ustring::compose( _("Connecting to \"%1\"..."), uri)); } else { m_message_handle = get_status_bar().add_info_message( Glib::ustring::compose( _("Subscribing to \"%1\"..."), uri)); } } Gobby::OperationSubscribePath::OperationSubscribePath(Operations& operations, Folder& folder, InfBrowser* inf_browser, const std::string& p): Operation(operations), m_folder(folder), m_browser(inf_browser), m_target(p), m_path(split_path(p)), m_request(NULL), m_request_finished_id(0), m_notify_status_id(0) { // This might finish immediately, however the Operations manager // does not support this. Therefore, delay the call. Glib::signal_idle().connect( sigc::bind_return( sigc::mem_fun( *this, &OperationSubscribePath::start_with_browser), false)); m_message_handle = get_status_bar().add_info_message( Glib::ustring::compose(_("Subscribing to \"%1\"..."), p)); } Gobby::OperationSubscribePath::~OperationSubscribePath() { if(m_request != NULL) g_signal_handler_disconnect(m_request, m_request_finished_id); if(m_notify_status_id != 0) g_signal_handler_disconnect(m_browser, m_notify_status_id); if(m_message_handle != get_status_bar().invalid_handle()) get_status_bar().remove_message(m_message_handle); } void Gobby::OperationSubscribePath::start_with_browser() { if(m_path.empty()) { get_browser().set_selected(m_browser, NULL); finish(); } else { InfBrowserStatus status; g_object_get(G_OBJECT(m_browser), "status", &status, NULL); if(status == INF_BROWSER_OPEN) { inf_browser_get_root(m_browser, &m_path_iter); m_path_index = 0; explore(); } else { m_notify_status_id = g_signal_connect( G_OBJECT(m_browser), "notify::status", G_CALLBACK(on_notify_status_static), this); } } } void Gobby::OperationSubscribePath::explore() { if(m_path_index == m_path.size()) { // We are done get_browser().set_selected(m_browser, &m_path_iter); if(!inf_browser_is_subdirectory(m_browser, &m_path_iter)) { InfSessionProxy* proxy = inf_browser_get_session( m_browser, &m_path_iter); if(proxy != NULL) { InfSession* session; g_object_get(G_OBJECT(proxy), "session", &session, NULL); SessionView* view = m_folder.lookup_document(session); g_object_unref(session); g_assert(view != NULL); m_folder.switch_to_document(*view); } else { m_request = INF_NODE_REQUEST( inf_browser_get_pending_request( m_browser, &m_path_iter, "subscribe-session")); if(m_request == NULL) { m_request = inf_browser_subscribe( m_browser, &m_path_iter); } m_request_finished_id = g_signal_connect( G_OBJECT(m_request), "finished", G_CALLBACK( on_subscribe_finished_static), this); } } finish(); } else { if(inf_browser_is_subdirectory(m_browser, &m_path_iter)) { // This is a subdirectory node. Explore it. if(inf_browser_get_explored(m_browser, &m_path_iter)) { descend(); } else { m_request = INF_NODE_REQUEST( inf_browser_get_pending_request( m_browser, &m_path_iter, "explore-node")); if(m_request == NULL) { m_request = INF_NODE_REQUEST( inf_browser_explore( m_browser, &m_path_iter)); } m_request_finished_id = g_signal_connect( G_OBJECT(m_request), "finished", G_CALLBACK( on_explore_finished_static), this); } } else { // This is a leaf node. This is an error, since we // did not yet end up at the end of the path. get_browser().set_selected(m_browser, &m_path_iter); get_status_bar().remove_message(m_message_handle); get_status_bar().add_error_message( Glib::ustring::compose( _("Could not subscribe to \"%1\""), m_target), Glib::ustring::compose( _("Path \"%1\" does not exist"), make_path_string(m_path))); fail(); } } } void Gobby::OperationSubscribePath::descend() { g_assert(m_path_index < m_path.size()); g_assert(inf_browser_is_subdirectory(m_browser, &m_path_iter)); g_assert(inf_browser_get_explored(m_browser, &m_path_iter)); if(inf_browser_get_child(m_browser, &m_path_iter)) { do { const char* name = inf_browser_get_node_name( m_browser, &m_path_iter); if(m_path[m_path_index] == name) { ++m_path_index; explore(); return; } } while(inf_browser_get_next(m_browser, &m_path_iter)); } // Cannot find child get_status_bar().remove_message(m_message_handle); m_message_handle = get_status_bar().invalid_handle(); get_status_bar().add_error_message( Glib::ustring::compose( _("Could not subscribe to \"%1\""), m_target), Glib::ustring::compose( _("Path \"%1\" does not exist"), make_path_string(m_path))); fail(); } void Gobby::OperationSubscribePath::on_resolv_done( const ResolvHandle* handle, const InfIpAddress* address, guint port, const std::string& hostname, unsigned int device_index) { try { m_browser = get_browser().connect_to_host( address, port, device_index, hostname); g_assert(m_browser != NULL); // From here, go on as if we started from the 2nd destructor start_with_browser(); } catch(const std::exception& ex) { if(m_path.empty()) { get_status_bar().add_error_message( Glib::ustring::compose( _("Failed to connect to \"%1\""), m_target), ex.what()); } else { get_status_bar().add_error_message( Glib::ustring::compose( _("Could not subscribe to \"%1\""), m_target), ex.what()); } fail(); } } void Gobby::OperationSubscribePath::on_resolv_error( const ResolvHandle* handle, const std::runtime_error& error, const std::string& hostname) { get_status_bar().remove_message(m_message_handle); m_message_handle = get_status_bar().invalid_handle(); if(m_path.empty()) { get_status_bar().add_error_message( Glib::ustring::compose( _("Failed to connect to \"%1\""), m_target), Glib::ustring::compose( _("Failed to resolve \"%1\": %2"), hostname, error.what())); } else { get_status_bar().add_error_message( Glib::ustring::compose( _("Could not subscribe to \"%1\""), m_target), Glib::ustring::compose( _("Failed to resolve \"%1\": %2"), hostname, error.what())); } fail(); } void Gobby::OperationSubscribePath::on_notify_status() { InfBrowserStatus status; g_object_get(G_OBJECT(m_browser), "status", &status, NULL); switch(status) { case INF_BROWSER_OPEN: g_signal_handler_disconnect(m_browser, m_notify_status_id); m_notify_status_id = 0; inf_browser_get_root(m_browser, &m_path_iter); m_path_index = 0; explore(); break; case INF_BROWSER_OPENING: break; case INF_BROWSER_CLOSED: // Don't set an error message, the user will already be // notified by the closed browser. fail(); break; default: g_assert_not_reached(); break; } } void Gobby::OperationSubscribePath::on_explore_finished( const InfBrowserIter* iter, const GError* error) { m_request = NULL; m_request_finished_id = 0; if(error != NULL) { get_status_bar().add_error_message( Glib::ustring::compose( _("Could not subscribe to \"%1\""), m_target), error->message); fail(); } else { descend(); } } void Gobby::OperationSubscribePath::on_subscribe_finished( const InfBrowserIter* iter, const GError* error) { m_request = NULL; m_request_finished_id = 0; if(error != NULL) { get_status_bar().add_error_message( Glib::ustring::compose( _("Could not subscribe to \"%1\""), m_target), error->message); fail(); } /* From this point on subscription-commands takes over */ finish(); } <commit_msg>Wait for connection to finish before finishing OperationSubscribePath<commit_after>/* Gobby - GTK-based collaborative text editor * Copyright (C) 2008-2013 Armin Burgmeier <armin@arbur.net> * * 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. * * 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 * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "operations/operation-subscribe-path.hpp" #include "util/i18n.hpp" #include "util/uri.hpp" namespace { std::vector<std::string> split_path(const std::string& path) { std::vector<std::string> result; if(path.empty()) return result; if(path[0] != '/') { throw std::runtime_error( Glib::ustring::compose( Gobby::_("Invalid path: \"%1\""), path)); } std::string::size_type prev = 1, pos; while( (pos = path.find('/', prev)) != std::string::npos) { std::string component = path.substr(prev, pos - prev); if(component.empty()) { throw std::runtime_error( Glib::ustring::compose( Gobby::_("Invalid path " "component: \"%1\""), component)); } result.push_back(component); prev = pos + 1; } // Trailing '/' is allowed std::string component = path.substr(prev); if(!component.empty()) result.push_back(component); return result; } std::string make_path_string(const std::vector<std::string>& path) { std::string result; for(std::vector<std::string>::const_iterator iter = path.begin(); iter != path.end(); ++iter) { result += "/"; result += *iter; } return result; } } Gobby::OperationSubscribePath::OperationSubscribePath(Operations& operations, Folder& folder, const std::string& uri): Operation(operations), m_folder(folder), m_browser(NULL), m_target(uri), m_request(NULL), m_request_finished_id(0), m_notify_status_id(0) { std::string scheme, netloc, path; parse_uri(uri, scheme, netloc, path); if(scheme != "infinote") { throw std::runtime_error( Glib::ustring::compose( _("URI scheme \"%1\" not supported"), scheme)); } m_path = split_path(path); std::string hostname, service; unsigned int device_index; parse_netloc(netloc, hostname, service, device_index); m_resolve_handle = Gobby::resolve( hostname, service, sigc::bind( sigc::mem_fun( *this, &OperationSubscribePath::on_resolv_done), hostname, device_index), sigc::bind( sigc::mem_fun( *this, &OperationSubscribePath::on_resolv_error), hostname)); if(path.empty()) { m_message_handle = get_status_bar().add_info_message( Glib::ustring::compose( _("Connecting to \"%1\"..."), uri)); } else { m_message_handle = get_status_bar().add_info_message( Glib::ustring::compose( _("Subscribing to \"%1\"..."), uri)); } } Gobby::OperationSubscribePath::OperationSubscribePath(Operations& operations, Folder& folder, InfBrowser* inf_browser, const std::string& p): Operation(operations), m_folder(folder), m_browser(inf_browser), m_target(p), m_path(split_path(p)), m_request(NULL), m_request_finished_id(0), m_notify_status_id(0) { // This might finish immediately, however the Operations manager // does not support this. Therefore, delay the call. Glib::signal_idle().connect( sigc::bind_return( sigc::mem_fun( *this, &OperationSubscribePath::start_with_browser), false)); m_message_handle = get_status_bar().add_info_message( Glib::ustring::compose(_("Subscribing to \"%1\"..."), p)); } Gobby::OperationSubscribePath::~OperationSubscribePath() { if(m_request != NULL) g_signal_handler_disconnect(m_request, m_request_finished_id); if(m_notify_status_id != 0) g_signal_handler_disconnect(m_browser, m_notify_status_id); if(m_message_handle != get_status_bar().invalid_handle()) get_status_bar().remove_message(m_message_handle); } void Gobby::OperationSubscribePath::start_with_browser() { InfBrowserStatus status; g_object_get(G_OBJECT(m_browser), "status", &status, NULL); if(status == INF_BROWSER_OPEN) { inf_browser_get_root(m_browser, &m_path_iter); m_path_index = 0; explore(); } else { m_notify_status_id = g_signal_connect( G_OBJECT(m_browser), "notify::status", G_CALLBACK(on_notify_status_static), this); } } void Gobby::OperationSubscribePath::explore() { if(m_path_index == m_path.size()) { // We are done get_browser().set_selected(m_browser, &m_path_iter); if(!inf_browser_is_subdirectory(m_browser, &m_path_iter)) { InfSessionProxy* proxy = inf_browser_get_session( m_browser, &m_path_iter); if(proxy != NULL) { InfSession* session; g_object_get(G_OBJECT(proxy), "session", &session, NULL); SessionView* view = m_folder.lookup_document(session); g_object_unref(session); g_assert(view != NULL); m_folder.switch_to_document(*view); } else { m_request = INF_NODE_REQUEST( inf_browser_get_pending_request( m_browser, &m_path_iter, "subscribe-session")); if(m_request == NULL) { m_request = inf_browser_subscribe( m_browser, &m_path_iter); } m_request_finished_id = g_signal_connect( G_OBJECT(m_request), "finished", G_CALLBACK( on_subscribe_finished_static), this); } } finish(); } else { if(inf_browser_is_subdirectory(m_browser, &m_path_iter)) { // This is a subdirectory node. Explore it. if(inf_browser_get_explored(m_browser, &m_path_iter)) { descend(); } else { m_request = INF_NODE_REQUEST( inf_browser_get_pending_request( m_browser, &m_path_iter, "explore-node")); if(m_request == NULL) { m_request = INF_NODE_REQUEST( inf_browser_explore( m_browser, &m_path_iter)); } m_request_finished_id = g_signal_connect( G_OBJECT(m_request), "finished", G_CALLBACK( on_explore_finished_static), this); } } else { // This is a leaf node. This is an error, since we // did not yet end up at the end of the path. get_browser().set_selected(m_browser, &m_path_iter); get_status_bar().remove_message(m_message_handle); get_status_bar().add_error_message( Glib::ustring::compose( _("Could not subscribe to \"%1\""), m_target), Glib::ustring::compose( _("Path \"%1\" does not exist"), make_path_string(m_path))); fail(); } } } void Gobby::OperationSubscribePath::descend() { g_assert(m_path_index < m_path.size()); g_assert(inf_browser_is_subdirectory(m_browser, &m_path_iter)); g_assert(inf_browser_get_explored(m_browser, &m_path_iter)); if(inf_browser_get_child(m_browser, &m_path_iter)) { do { const char* name = inf_browser_get_node_name( m_browser, &m_path_iter); if(m_path[m_path_index] == name) { ++m_path_index; explore(); return; } } while(inf_browser_get_next(m_browser, &m_path_iter)); } // Cannot find child get_status_bar().remove_message(m_message_handle); m_message_handle = get_status_bar().invalid_handle(); get_status_bar().add_error_message( Glib::ustring::compose( _("Could not subscribe to \"%1\""), m_target), Glib::ustring::compose( _("Path \"%1\" does not exist"), make_path_string(m_path))); fail(); } void Gobby::OperationSubscribePath::on_resolv_done( const ResolvHandle* handle, const InfIpAddress* address, guint port, const std::string& hostname, unsigned int device_index) { try { m_browser = get_browser().connect_to_host( address, port, device_index, hostname); g_assert(m_browser != NULL); // From here, go on as if we started from the 2nd destructor start_with_browser(); } catch(const std::exception& ex) { if(m_path.empty()) { get_status_bar().add_error_message( Glib::ustring::compose( _("Failed to connect to \"%1\""), m_target), ex.what()); } else { get_status_bar().add_error_message( Glib::ustring::compose( _("Could not subscribe to \"%1\""), m_target), ex.what()); } fail(); } } void Gobby::OperationSubscribePath::on_resolv_error( const ResolvHandle* handle, const std::runtime_error& error, const std::string& hostname) { get_status_bar().remove_message(m_message_handle); m_message_handle = get_status_bar().invalid_handle(); if(m_path.empty()) { get_status_bar().add_error_message( Glib::ustring::compose( _("Failed to connect to \"%1\""), m_target), Glib::ustring::compose( _("Failed to resolve \"%1\": %2"), hostname, error.what())); } else { get_status_bar().add_error_message( Glib::ustring::compose( _("Could not subscribe to \"%1\""), m_target), Glib::ustring::compose( _("Failed to resolve \"%1\": %2"), hostname, error.what())); } fail(); } void Gobby::OperationSubscribePath::on_notify_status() { InfBrowserStatus status; g_object_get(G_OBJECT(m_browser), "status", &status, NULL); switch(status) { case INF_BROWSER_OPEN: g_signal_handler_disconnect(m_browser, m_notify_status_id); m_notify_status_id = 0; inf_browser_get_root(m_browser, &m_path_iter); m_path_index = 0; explore(); break; case INF_BROWSER_OPENING: break; case INF_BROWSER_CLOSED: // Don't set an error message, the user will already be // notified by the closed browser. fail(); break; default: g_assert_not_reached(); break; } } void Gobby::OperationSubscribePath::on_explore_finished( const InfBrowserIter* iter, const GError* error) { m_request = NULL; m_request_finished_id = 0; if(error != NULL) { get_status_bar().add_error_message( Glib::ustring::compose( _("Could not subscribe to \"%1\""), m_target), error->message); fail(); } else { descend(); } } void Gobby::OperationSubscribePath::on_subscribe_finished( const InfBrowserIter* iter, const GError* error) { m_request = NULL; m_request_finished_id = 0; if(error != NULL) { get_status_bar().add_error_message( Glib::ustring::compose( _("Could not subscribe to \"%1\""), m_target), error->message); fail(); } /* From this point on subscription-commands takes over */ finish(); } <|endoftext|>
<commit_before>//Contains hooks that control attack range and seek range (AKA target acquisition range). #include "weapon_range.h" #include "../SCBW/scbwdata.h" #include "../SCBW/enumerations.h" #include "../SCBW/api.h" namespace hooks { /// Returns the modified seek range (AKA target acquisition range) for the unit. /// Note: Seek ranges are measured in matrices (1 matrix = 32 pixels). /// This hook affects the behavior of CUnit::getSeekRange(). u8 getSeekRangeHook(const CUnit *unit) { //Default StarCraft behavior using UnitStatus::Cloaked; using UnitStatus::RequiresDetection; using scbw::getUpgradeLevel; const u16 unitId = unit->id; //Cloaked ghosts do not voluntarily attack enemy units if ((unitId == UnitId::ghost || unitId == UnitId::sarah_kerrigan || unitId == UnitId::Hero_AlexeiStukov || unitId == UnitId::Hero_SamirDuran || unitId == UnitId::Hero_InfestedDuran) && unit->status & (Cloaked | RequiresDetection) && unit->mainOrderId != OrderId::HoldPosition2) return 0; u8 bonusAmount = 0; switch (unitId) { case UnitId::marine: if (getUpgradeLevel(unit->playerId, UpgradeId::U_238Shells)) bonusAmount = 1; break; case UnitId::hydralisk: if (getUpgradeLevel(unit->playerId, UpgradeId::GroovedSpines)) bonusAmount = 1; break; case UnitId::dragoon: if (getUpgradeLevel(unit->playerId, UpgradeId::SingularityCharge)) bonusAmount = 2; break; case UnitId::fenix_dragoon: if (scbw::isBroodWarMode()) bonusAmount = 2; break; case UnitId::goliath: case UnitId::goliath_turret: if (getUpgradeLevel(unit->playerId, UpgradeId::CharonBooster)) bonusAmount = 3; break; case UnitId::alan_schezar: case UnitId::alan_schezar_turret: if (scbw::isBroodWarMode()) bonusAmount = 3; break; } return Unit::SeekRange[unitId] + bonusAmount; } /// Returns the modified max range for the weapon, which is assumed to be /// attached to the given unit. /// This hook affects the behavior of CUnit::getMaxWeaponRange(). /// Note: Weapon ranges are measured in pixels. /// /// @param weapon The weapons.dat ID of the weapon. /// @param unit The unit that owns the weapon. Use this to check upgrades. u32 getMaxWeaponRangeHook(const CUnit *unit, u8 weaponId) { //Default StarCraft behavior using scbw::getUpgradeLevel; u32 bonusAmount = 0; //Give bonus range to units inside Bunkers if (unit->status & UnitStatus::InBuilding) bonusAmount = 64; switch (unit->id) { case UnitId::marine: if (getUpgradeLevel(unit->playerId, UpgradeId::U_238Shells)) bonusAmount += 32; break; case UnitId::hydralisk: if (getUpgradeLevel(unit->playerId, UpgradeId::GroovedSpines)) bonusAmount += 32; break; case UnitId::dragoon: if (getUpgradeLevel(unit->playerId, UpgradeId::SingularityCharge)) bonusAmount += 64; break; case UnitId::fenix_dragoon: if (scbw::isBroodWarMode()) bonusAmount += 64; break; case UnitId::goliath: case UnitId::goliath_turret: if (weaponId == WeaponId::HellfireMissilePack && getUpgradeLevel(unit->playerId, UpgradeId::CharonBooster)) bonusAmount += 96; break; case UnitId::alan_schezar: case UnitId::alan_schezar_turret: if (weaponId == WeaponId::HellfireMissilePack_AlanSchezar && scbw::isBroodWarMode()) bonusAmount += 96; break; } return Weapon::MaxRange[weaponId] + bonusAmount; } } //hooks <commit_msg>SCT: * Thermal Sensors adds +1 Spider Mine activation range * Ocular Implants adds +1 seek range and weapon range<commit_after>//Contains hooks that control attack range and seek range (AKA target acquisition range). #include "weapon_range.h" #include "../SCBW/scbwdata.h" #include "../SCBW/enumerations.h" #include "../SCBW/api.h" namespace hooks { /// Returns the modified seek range (AKA target acquisition range) for the unit. /// Note: Seek ranges are measured in matrices (1 matrix = 32 pixels). /// This hook affects the behavior of CUnit::getSeekRange(). u8 getSeekRangeHook(const CUnit *unit) { using UnitStatus::Cloaked; using UnitStatus::RequiresDetection; using scbw::getUpgradeLevel; const u16 unitId = unit->id; //Cloaked ghosts do not voluntarily attack enemy units if ((unitId == UnitId::ghost || unitId == UnitId::sarah_kerrigan || unitId == UnitId::Hero_AlexeiStukov || unitId == UnitId::Hero_SamirDuran || unitId == UnitId::Hero_InfestedDuran) && unit->status & (Cloaked | RequiresDetection) && unit->mainOrderId != OrderId::HoldPosition2) return 0; u8 bonusAmount = 0; switch (unitId) { case UnitId::marine: if (getUpgradeLevel(unit->playerId, UpgradeId::U_238Shells)) bonusAmount = 1; break; case UnitId::hydralisk: if (getUpgradeLevel(unit->playerId, UpgradeId::GroovedSpines)) bonusAmount = 1; break; case UnitId::dragoon: if (getUpgradeLevel(unit->playerId, UpgradeId::SingularityCharge)) bonusAmount = 2; break; case UnitId::fenix_dragoon: if (scbw::isBroodWarMode()) bonusAmount = 2; break; case UnitId::goliath: case UnitId::goliath_turret: if (getUpgradeLevel(unit->playerId, UpgradeId::CharonBooster)) bonusAmount = 3; break; case UnitId::alan_schezar: case UnitId::alan_schezar_turret: if (scbw::isBroodWarMode()) bonusAmount = 3; break; //Added case UnitId::spider_mine: if (getUpgradeLevel(unit->playerId, UPGRADE_THERMAL_SENSORS)) bonusAmount = 1; break; } //Added: Ocular Implants adds a flat +1 seek range if (unit->isBlind) bonusAmount += 1; return Unit::SeekRange[unitId] + bonusAmount; } /// Returns the modified max range for the weapon, which is assumed to be /// attached to the given unit. /// This hook affects the behavior of CUnit::getMaxWeaponRange(). /// Note: Weapon ranges are measured in pixels. /// /// @param weapon The weapons.dat ID of the weapon. /// @param unit The unit that owns the weapon. Use this to check upgrades. u32 getMaxWeaponRangeHook(const CUnit *unit, u8 weaponId) { using scbw::getUpgradeLevel; u32 bonusAmount = 0; //Give bonus range to units inside Bunkers if (unit->status & UnitStatus::InBuilding) bonusAmount = 64; switch (unit->id) { case UnitId::marine: if (getUpgradeLevel(unit->playerId, UpgradeId::U_238Shells)) bonusAmount += 32; break; case UnitId::hydralisk: if (getUpgradeLevel(unit->playerId, UpgradeId::GroovedSpines)) bonusAmount += 32; break; case UnitId::dragoon: if (getUpgradeLevel(unit->playerId, UpgradeId::SingularityCharge)) bonusAmount += 64; break; case UnitId::fenix_dragoon: if (scbw::isBroodWarMode()) bonusAmount += 64; break; case UnitId::goliath: case UnitId::goliath_turret: if (weaponId == WeaponId::HellfireMissilePack && getUpgradeLevel(unit->playerId, UpgradeId::CharonBooster)) bonusAmount += 96; break; case UnitId::alan_schezar: case UnitId::alan_schezar_turret: if (weaponId == WeaponId::HellfireMissilePack_AlanSchezar && scbw::isBroodWarMode()) bonusAmount += 96; break; } //Added: Ocular Implants adds a flat +32 weapon range if (unit->isBlind) bonusAmount += 32; return Weapon::MaxRange[weaponId] + bonusAmount; } } //hooks <|endoftext|>
<commit_before>#include "aks.h" #include <gmp.h> #include <mpfr.h> #include <stdlib.h> #define FALSE 0 #define TRUE 1 #define COMPOSITE 0 #define PRIME 1 int aks_debug = 0; /** * Wrapper function to find the log of a number of type mpz_t. */ void compute_logn(mpz_t rop, mpz_t n) { mpfr_t tmp; mpfr_init(tmp); mpfr_set_z(tmp, n, MPFR_RNDN); mpfr_log(tmp, tmp, MPFR_RNDN); mpfr_get_z(rop, tmp, MPFR_RNDN); mpfr_clear(tmp); } /** * Wrapper function to find the square of the log of a number of type mpz_t. */ void compute_logn2(mpz_t rop, mpz_t n) { mpfr_t tmp; mpfr_init(tmp); mpfr_set_z(tmp, n, MPFR_RNDN); mpfr_log(tmp, tmp, MPFR_RNDA); mpfr_pow_ui(tmp, tmp, 2, MPFR_RNDA); mpfr_ceil(tmp, tmp); mpfr_get_z(rop, tmp, MPFR_RNDA); mpfr_clear(tmp); } /** * Finds the smallest r such that order of the a modula r which is the * smallest number k such that n ^ k = 1 (mod r) is greater than log(n) ^ 2. */ void find_smallest_r(mpz_t r, mpz_t n) { mpz_t logn2, k, tmp; mpz_init(logn2); mpz_init(k); mpz_init(tmp); // Compute log(n) ^ 2 in order to do the comparisons compute_logn2(logn2, n); // R must be at least log(n) ^ 2 mpz_set(r, logn2); int found_r = FALSE; while (!found_r) { found_r = TRUE; // Check several values of k from 1 up to log(n) ^ 2 to find one that satisfies the equality for (mpz_set_ui(k, 1); mpz_cmp(k, logn2) <= 0; mpz_add_ui(k, k, 1)) { // Compute n ^ k % r mpz_powm(tmp, n, k, r); // If it is not equal to 1 than the equality n ^ k = 1 (mod r) does not hold // and we must find test a different value of k if (mpz_cmp_ui(tmp, 1) == 0) { found_r = FALSE; break; } } // All possible values of k were checked so we must start looking for a new r if (!found_r) { mpz_add_ui(r, r, 1); } } mpz_clear(logn2); mpz_clear(k); mpz_clear(tmp); } /** * Return true if there exists an a such that 1 < gcd(a, n) < n for some a <= r. */ int check_a_exists(mpz_t n, mpz_t r) { mpz_t a, gcd; mpz_init(a); mpz_init(gcd); int exists = FALSE; // Simply iterate for values of a from 1 to r and see if equations hold for the gcd of a and n for (mpz_set_ui(a, 1); mpz_cmp(a, r) <= 0; mpz_add_ui(a, a, 1)) { mpz_gcd(gcd, a, n); if (mpz_cmp_ui(gcd, 1) > 0 && mpz_cmp(gcd, n) < 0) { exists = TRUE; break; } } mpz_clear(a); mpz_clear(gcd); return exists; } /** * Return the totient of op, which is the count of numbers less than op which are coprime to op. */ void totient(mpz_t rop, mpz_t op) { mpz_t i, gcd; mpz_init(i); mpz_init(gcd); mpz_set_ui(rop, 0); // Simply iterate through all values from op to 1 and see if the gcd of that number and op is 1. // If it is then it is coprime and added to the totient count. for (mpz_set(i, op); mpz_cmp_ui(i, 0) != 0; mpz_sub_ui(i, i, 1)) { mpz_gcd(gcd, i, op); if (mpz_cmp_ui(gcd, 1) == 0) { mpz_add_ui(rop, rop, 1); } } mpz_clear(i); mpz_clear(gcd); } /** * Returns sqrt(totient(r)) * log(n) which is used by step 5. */ void compute_upper_limit(mpz_t rop, mpz_t r, mpz_t n) { mpz_t tot, logn; mpz_init(tot); mpz_init(logn); totient(tot, r); if (aks_debug) gmp_printf("tot=%Zd\n", tot); mpz_sqrt(tot, tot); compute_logn(logn, n); mpz_mul(rop, tot, logn); mpz_clear(tot); mpz_clear(logn); } /** * Multiplies two polynomials with appropriate mod where their coefficients are indexed into the array. */ void polymul(mpz_t* rop, mpz_t* op1, unsigned int len1, mpz_t* op2, unsigned int len2, mpz_t n) { int i, j, t; for (i = 0; i < len1; i++) { for (j = 0; j < len2; j++) { t = (i + j) % len1; mpz_addmul(rop[t], op1[i], op2[j]); mpz_mod(rop[t], rop[t], n); } } } /** * Allocates an array where each element represents a coeffecient of the polynomial. */ mpz_t* init_poly(unsigned int terms) { int i; mpz_t* poly = (mpz_t*) malloc(sizeof(mpz_t) * terms); for (i = 0; i < terms; i++) { mpz_init(poly[i]); } return poly; } /** * Frees the array and clears each element in the array. */ void clear_poly(mpz_t* poly, unsigned int terms) { int i; for (i = 0; i < terms; i++) { mpz_clear(poly[i]); } free(poly); } /** * Test if (X + a) ^ n != X ^ n + a (mod X ^ r - 1,n) */ int check_poly(mpz_t n, mpz_t a, mpz_t r) { unsigned int i, terms, equality_holds; mpz_t tmp, neg_a, loop; mpz_init(tmp); mpz_init(neg_a); mpz_init(loop); terms = mpz_get_ui(r) + 1; mpz_t* poly = init_poly(terms); mpz_t* ptmp = init_poly(terms); mpz_t* stmp; mpz_mul_ui(neg_a, a, -1); mpz_set(poly[0], neg_a); mpz_set_ui(poly[1], 1); for (mpz_set_ui(loop, 2); mpz_cmp(loop, n) <= 0; mpz_mul(loop, loop, loop)) { polymul(ptmp, poly, terms, poly, terms, n); stmp = poly; poly = ptmp; ptmp = stmp; } mpz_t* xMinusA = init_poly(2); mpz_set(ptmp[0], neg_a); mpz_set_ui(ptmp[1], 1); for (; mpz_cmp(loop, n) <= 0; mpz_add_ui(loop, loop, 1)) { polymul(ptmp, poly, terms, xMinusA, 2, n); stmp = poly; poly = ptmp; ptmp = stmp; } clear_poly(xMinusA, 2); equality_holds = TRUE; if (mpz_cmp(poly[0], neg_a) != 0 || mpz_cmp_ui(poly[terms - 1], 1) != 0) { equality_holds = FALSE; } else { for (i = 1; i < terms - 1; i++) { if (mpz_cmp_ui(poly[i], 0) != 0) { equality_holds = FALSE; break; } } } clear_poly(poly, terms); clear_poly(ptmp, terms); mpz_clear(tmp); mpz_clear(neg_a); mpz_clear(loop); return equality_holds; } /** * Run step 5 of the AKS algorithm. */ int check_polys(mpz_t r, mpz_t n) { mpz_t a, lim; mpz_init(a); mpz_init(lim); int status = PRIME; if (aks_debug) gmp_printf("computing upper limit\n"); compute_upper_limit(lim, r, n); if (aks_debug) gmp_printf("lim=%Zd\n", lim); // For values of a from 1 to sqrt(totient(r)) * log(n) for (mpz_set_ui(a, 1); mpz_cmp(a, lim) <= 0; mpz_add_ui(a, a, 1)) { if (!check_poly(n, a, r)) { status = COMPOSITE; break; } } mpz_clear(a); mpz_clear(lim); return status; } int aks_is_prime(mpz_t n) { // Peform simple checks before running the AKS algorithm if (mpz_cmp_ui(n, 2) == 0) { return PRIME; } if (mpz_cmp_ui(n, 1) <= 0 || mpz_divisible_ui_p(n, 2)) { return COMPOSITE; } // Step 1: Check if n is a perfect power, meaning n = a ^ b where a is a natural number and b > 1 if (mpz_perfect_power_p(n)) { return COMPOSITE; } // Step 2: Find the smallest r such that or(n) > log(n) ^ 2 mpz_t r; mpz_init(r); find_smallest_r(r, n); if (aks_debug) gmp_printf("r=%Zd\n", r); // Step 3: Check if there exists an a <= r such that 1 < (a,n) < n if (check_a_exists(n, r)) { mpz_clear(r); return COMPOSITE; } if (aks_debug) gmp_printf("a does not exist\n"); // Step 4: Check if n <= r if (mpz_cmp(n, r) <= 0) { mpz_clear(r); return PRIME; } if (aks_debug) gmp_printf("checking polynomial equation\n"); // Step 5 if (check_polys(r, n)) { mpz_clear(r); return COMPOSITE; } mpz_clear(r); // Step 6 return PRIME; } <commit_msg>adding new implementatin of AKS<commit_after>#include "aks.h" #include <gmp.h> #include <mpfr.h> #include <stdlib.h> #define FALSE 0 #define TRUE 1 #define COMPOSITE 0 #define PRIME 1 int aks_debug = 0; /** * Wrapper function to find the log of a number of type mpz_t. */ void compute_logn(mpz_t rop, mpz_t n) { mpfr_t tmp; mpfr_init(tmp); mpfr_set_z(tmp, n, MPFR_RNDN); mpfr_log2(tmp, tmp, MPFR_RNDN); mpfr_get_z(rop, tmp, MPFR_RNDN); mpfr_clear(tmp); } /** * Wrapper function to find the square of the log of a number of type mpz_t. */ void compute_logn2(mpz_t rop, mpz_t n) { mpfr_t tmp; mpfr_init(tmp); mpfr_set_z(tmp, n, MPFR_RNDN); mpfr_log2(tmp, tmp, MPFR_RNDA); mpfr_pow_ui(tmp, tmp, 2, MPFR_RNDA); mpfr_ceil(tmp, tmp); mpfr_get_z(rop, tmp, MPFR_RNDA); mpfr_clear(tmp); } /** * Finds the smallest r such that order of the a modula r which is the * smallest number k such that n ^ k = 1 (mod r) is greater than log(n) ^ 2. * * Will also return composite if the number is guaranteed to be composite. */ int find_smallest_r(mpz_t r, mpz_t n) { int retval = PRIME; int found_r; mpz_t logn2, k, tmp; mpz_init(logn2); mpz_init(k); mpz_init(tmp); // Compute log(n) ^ 2 in order to know when r is found compute_logn2(logn2, n); // The value r <= ceil(log(n) ^ 5), but can go up to n for n <= 5,690,034 for (mpz_set_ui(r, 2); mpz_cmp(r, n) < 0; mpz_add_ui(r, r, 1)) { if (mpz_divisible_p(n, r)) { retval = COMPOSITE; break; } mpz_gcd(tmp, n, r); if (mpz_cmp_ui(tmp, 1) != 0) { continue; } found_r = TRUE; // Check values of k from 1 up to log(n) ^ 2 to see if any value satisfies the equality for (mpz_set_ui(k, 1); mpz_cmp(k, logn2) <= 0; mpz_add_ui(k, k, 1)) { // Compute n ^ k % r mpz_powm(tmp, n, k, r); if (mpz_cmp_ui(tmp, 1) == 0) { found_r = FALSE; break; } } // k is greater than log(n) ^ 2 so we have found r if (found_r == TRUE) { break; } } mpz_clear(logn2); mpz_clear(k); mpz_clear(tmp); return retval; } /** * Return true if there exists an a such that 1 < gcd(a, n) < n for some a <= r. */ int check_a_exists(mpz_t n, mpz_t r) { mpz_t a, gcd; mpz_init(a); mpz_init(gcd); int exists = FALSE; // Simply iterate for values of a from 1 to r and see if equations hold for the gcd of a and n for (mpz_set_ui(a, 1); mpz_cmp(a, r) <= 0; mpz_add_ui(a, a, 1)) { mpz_gcd(gcd, a, n); if (mpz_cmp_ui(gcd, 1) > 0 && mpz_cmp(gcd, n) < 0) { exists = TRUE; break; } } mpz_clear(a); mpz_clear(gcd); return exists; } /** * Return the totient of op, which is the count of numbers less than or equal to op which are coprime to op. */ void totient(mpz_t rop, mpz_t op) { mpz_t i, gcd; mpz_init(i); mpz_init(gcd); mpz_set_ui(rop, 0); for (mpz_sub_ui(i, op, 1); mpz_cmp_ui(i, 0) != 0; mpz_sub_ui(i, i, 1)) { mpz_gcd(gcd, i, op); if (mpz_cmp_ui(gcd, 1) == 0) { mpz_add_ui(rop, rop, 1); } } mpz_clear(i); mpz_clear(gcd); } /** * Returns sqrt(r) * log(n) which is used by step 5. * Uses the Lenstra and Pomerance improvements */ void compute_upper_limit(mpz_t rop, mpz_t r, mpz_t n) { mpz_t logn; mpz_init(logn); totient(rop, r); mpz_sqrt(rop, rop); compute_logn(logn, n); mpz_mul(rop, rop, logn); mpz_clear(logn); } /** * Prints a coefficient array representing a polynomial. */ void polyprint(mpz_t* poly, unsigned int len) { unsigned int i; for (i = 0; i < len; i++) { gmp_printf("%Zd ", poly[i]); } gmp_printf("\n"); } /** * Copies the op polynomial coefficient array into rop. */ void polycopy(mpz_t* rop, mpz_t* op, unsigned int len) { unsigned int i; for (i = 0; i < len; i++) { mpz_set(rop[i], op[i]); } } /** * Multiplies two polynomials (mod x^r - 1, n) where the ops are coefficient arrays. */ void polymul(mpz_t* rop, mpz_t* op1, mpz_t* op2, unsigned int len, mpz_t n, mpz_t* tmp) { int i, j, t; for (i = 0; i < len; i++) { mpz_set_ui(tmp[i], 0); } for (i = 0; i < len; i++) { for (j = 0; j < len; j++) { t = (i + j) % len; mpz_addmul(tmp[t], op1[i], op2[j]); mpz_mod(tmp[t], tmp[t], n); } } polycopy(rop, tmp, len); } /** * Raise the given polynomial to the given power (mod x^r - 1, n). This is done * by repeated squaring. */ void polypow(mpz_t* rop, mpz_t* op, unsigned int len, mpz_t n, mpz_t* tmp, mpz_t* tmp2) { mpz_t s, i, remainder; mpz_init(s); mpz_init(i); mpz_init(remainder); mpz_set_ui(s, 0); polycopy(rop, op, len); while (mpz_cmp(s, n) < 0) { mpz_sub(remainder, n, s); polycopy(tmp, op, len); if (mpz_cmp_ui(remainder, 1) == 0) { polymul(rop, rop, op, len, n, tmp); break; } for (mpz_set_ui(i, 2); mpz_cmp(i, remainder) <= 0; mpz_mul_ui(i, i, 2)) { polymul(tmp, tmp, tmp, len, n, tmp2); } if (mpz_cmp_ui(s, 0) == 0) { polycopy(rop, tmp, len); } else { polymul(rop, rop, tmp, len, n, tmp2); } mpz_divexact_ui(i, i, 2); mpz_add(s, s, i); } mpz_clear(s); mpz_clear(i); mpz_clear(remainder); } /** * Allocates an array where each element represents a coeffecient of the polynomial. */ mpz_t* init_poly(unsigned int terms) { int i; mpz_t* poly = (mpz_t*) malloc(sizeof(mpz_t) * terms); for (i = 0; i < terms; i++) { mpz_init(poly[i]); mpz_set_ui(poly[i], 0); } return poly; } /** * Frees the array and clears each element in the array. */ void clear_poly(mpz_t* poly, unsigned int terms) { int i; for (i = 0; i < terms; i++) { mpz_clear(poly[i]); } free(poly); } /** * Test if (X + a) ^ n != X ^ n + a (mod X ^ r - 1,n) */ int check_poly(mpz_t n, mpz_t a, mpz_t r, mpz_t* poly, mpz_t* xpa, mpz_t* tmp1, mpz_t* tmp2) { unsigned int i, terms, retval; terms = mpz_get_ui(r); mpz_set(xpa[0], a); mpz_set_ui(xpa[1], 1); polypow(poly, xpa, terms, n, tmp1, tmp2); retval = PRIME; mpz_t nmodr; mpz_init(nmodr); mpz_mod(nmodr, n, r); unsigned int index = mpz_get_ui(nmodr); if (mpz_cmp(poly[0], a) != 0 || mpz_cmp_ui(poly[index], 1) != 0) { retval = COMPOSITE; } if (retval == PRIME) { for (i = 1; i < index; i++) { if (mpz_cmp_ui(poly[i], 0) != 0) { retval = COMPOSITE; break; } } if (retval == PRIME) { for (i = index + 1; i < terms; i++) { if (mpz_cmp_ui(poly[i], 0) != 0) { retval = COMPOSITE; break; } } } } mpz_clear(nmodr); if (aks_debug) gmp_printf("check_poly returning %d\n", retval); return retval; } /** * Run step 5 of the AKS algorithm. */ int check_polys(mpz_t r, mpz_t n) { int retval = PRIME; mpz_t a, lim; mpz_init(a); mpz_init(lim); unsigned int terms = mpz_get_ui(r); mpz_t* pol1 = init_poly(terms); mpz_t* pol2 = init_poly(terms); mpz_t* tmp1 = init_poly(terms); mpz_t* tmp2 = init_poly(terms); if (aks_debug) gmp_printf("computing upper limit\n"); compute_upper_limit(lim, r, n); if (aks_debug) gmp_printf("lim=%Zd\n", lim); for (mpz_set_ui(a, 1); mpz_cmp(a, lim) <= 0; mpz_add_ui(a, a, 1)) { if (aks_debug) gmp_printf("checking a=%Zd\n", a); if (check_poly(n, a, r, pol1, pol2, tmp1, tmp2) == COMPOSITE) { if (aks_debug) gmp_printf("proven composite\n"); retval = COMPOSITE; break; } } clear_poly(pol1, terms); clear_poly(pol2, terms); clear_poly(tmp1, terms); clear_poly(tmp2, terms); mpz_clear(a); mpz_clear(lim); return retval; } int aks_is_prime(mpz_t n) { // Peform simple checks before running the AKS algorithm if (mpz_cmp_ui(n, 2) == 0) { return PRIME; } if (mpz_cmp_ui(n, 1) <= 0 || mpz_divisible_ui_p(n, 2)) { return COMPOSITE; } // Step 1: Check if n is a perfect power, meaning n = a ^ b where a is a natural number and b > 1 if (mpz_perfect_power_p(n)) { return COMPOSITE; } // Step 2: Find the smallest r such that or(n) > log(n) ^ 2 mpz_t r; mpz_init(r); if (find_smallest_r(r, n) == COMPOSITE) { mpz_clear(r); return COMPOSITE; } if (aks_debug) gmp_printf("r=%Zd\n", r); // Step 3: Check if there exists an a <= r such that 1 < (a,n) < n if (check_a_exists(n, r)) { mpz_clear(r); return COMPOSITE; } if (aks_debug) gmp_printf("a does not exist\n"); // Step 4: Check if n <= r, is only relevant for n <= 5,690,034 if (mpz_cmp(n, r) <= 0) { mpz_clear(r); return PRIME; } if (aks_debug) gmp_printf("checking polynomial equation\n"); // Step 5 if (check_polys(r, n) == COMPOSITE) { mpz_clear(r); return COMPOSITE; } mpz_clear(r); // Step 6 return PRIME; } <|endoftext|>
<commit_before><commit_msg>This test fails for Windows, so skip it for now.<commit_after><|endoftext|>
<commit_before>/* * Copyright (C) 2005, 2006, 2009 Apple Inc. All rights reserved. * * 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 "config.h" #ifdef SKIP_STATIC_CONSTRUCTORS_ON_GCC #define WEBCORE_QUALIFIEDNAME_HIDE_GLOBALS 1 #else #define QNAME_DEFAULT_CONSTRUCTOR #endif #include "HTMLNames.h" #include "SVGNames.h" #include "XLinkNames.h" #include "XMLNSNames.h" #include "XMLNames.h" #include "core/dom/QualifiedName.h" #include "wtf/Assertions.h" #include "wtf/HashSet.h" #include "wtf/StaticConstructors.h" namespace WebCore { static const int staticQualifiedNamesCount = HTMLNames::HTMLTagsCount + HTMLNames::HTMLAttrsCount + SVGNames::SVGTagsCount + SVGNames::SVGAttrsCount + XLinkNames::XLinkAttrsCount + XMLNSNames::XMLNSAttrsCount + XMLNames::XMLAttrsCount; struct QualifiedNameHashTraits : public HashTraits<QualifiedName::QualifiedNameImpl*> { static const int minimumTableSize = WTF::HashTableCapacityForSize<staticQualifiedNamesCount>::value; }; typedef HashSet<QualifiedName::QualifiedNameImpl*, QualifiedNameHash, QualifiedNameHashTraits> QNameSet; struct QNameComponentsTranslator { static unsigned hash(const QualifiedNameComponents& components) { return hashComponents(components); } static bool equal(QualifiedName::QualifiedNameImpl* name, const QualifiedNameComponents& c) { return c.m_prefix == name->m_prefix.impl() && c.m_localName == name->m_localName.impl() && c.m_namespace == name->m_namespace.impl(); } static void translate(QualifiedName::QualifiedNameImpl*& location, const QualifiedNameComponents& components, unsigned) { location = QualifiedName::QualifiedNameImpl::create(components.m_prefix, components.m_localName, components.m_namespace).leakRef(); } }; static QNameSet* gNameCache; QualifiedName::QualifiedName(const AtomicString& p, const AtomicString& l, const AtomicString& n) { if (!gNameCache) gNameCache = new QNameSet; QualifiedNameComponents components = { p.impl(), l.impl(), n.isEmpty() ? nullAtom.impl() : n.impl() }; QNameSet::AddResult addResult = gNameCache->add<QNameComponentsTranslator>(components); m_impl = *addResult.iterator; if (!addResult.isNewEntry) m_impl->ref(); } QualifiedName::~QualifiedName() { deref(); } void QualifiedName::deref() { #ifdef QNAME_DEFAULT_CONSTRUCTOR if (!m_impl) return; #endif ASSERT(!isHashTableDeletedValue()); m_impl->deref(); } QualifiedName::QualifiedNameImpl::~QualifiedNameImpl() { gNameCache->remove(this); } String QualifiedName::toString() const { String local = localName(); if (hasPrefix()) return prefix().string() + ":" + local; return local; } // Global init routines DEFINE_GLOBAL(QualifiedName, anyName, nullAtom, starAtom, starAtom) void QualifiedName::init() { ASSERT(starAtom.impl()); new ((void*)&anyName) QualifiedName(nullAtom, starAtom, starAtom); } const QualifiedName& nullQName() { DEFINE_STATIC_LOCAL(QualifiedName, nullName, (nullAtom, nullAtom, nullAtom)); return nullName; } const AtomicString& QualifiedName::localNameUpper() const { if (!m_impl->m_localNameUpper) m_impl->m_localNameUpper = m_impl->m_localName.upper(); return m_impl->m_localNameUpper; } unsigned QualifiedName::QualifiedNameImpl::computeHash() const { QualifiedNameComponents components = { m_prefix.impl(), m_localName.impl(), m_namespace.impl() }; return hashComponents(components); } void createQualifiedName(void* targetAddress, StringImpl* name, const AtomicString& nameNamespace) { new (targetAddress) QualifiedName(nullAtom, AtomicString(name), nameNamespace); } void createQualifiedName(void* targetAddress, StringImpl* name) { new (targetAddress) QualifiedName(nullAtom, AtomicString(name), nullAtom); } } <commit_msg>ASSERT that QualifiedNames are only ever created/destroyed on the main thread<commit_after>/* * Copyright (C) 2005, 2006, 2009 Apple Inc. All rights reserved. * * 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 "config.h" #ifdef SKIP_STATIC_CONSTRUCTORS_ON_GCC #define WEBCORE_QUALIFIEDNAME_HIDE_GLOBALS 1 #else #define QNAME_DEFAULT_CONSTRUCTOR #endif #include "HTMLNames.h" #include "SVGNames.h" #include "XLinkNames.h" #include "XMLNSNames.h" #include "XMLNames.h" #include "core/dom/QualifiedName.h" #include "wtf/Assertions.h" #include "wtf/HashSet.h" #include "wtf/MainThread.h" #include "wtf/StaticConstructors.h" namespace WebCore { static const int staticQualifiedNamesCount = HTMLNames::HTMLTagsCount + HTMLNames::HTMLAttrsCount + SVGNames::SVGTagsCount + SVGNames::SVGAttrsCount + XLinkNames::XLinkAttrsCount + XMLNSNames::XMLNSAttrsCount + XMLNames::XMLAttrsCount; struct QualifiedNameHashTraits : public HashTraits<QualifiedName::QualifiedNameImpl*> { static const int minimumTableSize = WTF::HashTableCapacityForSize<staticQualifiedNamesCount>::value; }; typedef HashSet<QualifiedName::QualifiedNameImpl*, QualifiedNameHash, QualifiedNameHashTraits> QualifiedNameCache; static QualifiedNameCache& qualifiedNameCache() { // This code is lockless and thus assumes it all runs on one thread! ASSERT(isMainThread()); static QualifiedNameCache* gNameCache = new QualifiedNameCache; return *gNameCache; } struct QNameComponentsTranslator { static unsigned hash(const QualifiedNameComponents& components) { return hashComponents(components); } static bool equal(QualifiedName::QualifiedNameImpl* name, const QualifiedNameComponents& c) { return c.m_prefix == name->m_prefix.impl() && c.m_localName == name->m_localName.impl() && c.m_namespace == name->m_namespace.impl(); } static void translate(QualifiedName::QualifiedNameImpl*& location, const QualifiedNameComponents& components, unsigned) { location = QualifiedName::QualifiedNameImpl::create(components.m_prefix, components.m_localName, components.m_namespace).leakRef(); } }; QualifiedName::QualifiedName(const AtomicString& p, const AtomicString& l, const AtomicString& n) { QualifiedNameComponents components = { p.impl(), l.impl(), n.isEmpty() ? nullAtom.impl() : n.impl() }; QualifiedNameCache::AddResult addResult = qualifiedNameCache().add<QNameComponentsTranslator>(components); m_impl = *addResult.iterator; if (!addResult.isNewEntry) m_impl->ref(); } QualifiedName::~QualifiedName() { deref(); } void QualifiedName::deref() { #ifdef QNAME_DEFAULT_CONSTRUCTOR if (!m_impl) return; #endif ASSERT(!isHashTableDeletedValue()); m_impl->deref(); } QualifiedName::QualifiedNameImpl::~QualifiedNameImpl() { qualifiedNameCache().remove(this); } String QualifiedName::toString() const { String local = localName(); if (hasPrefix()) return prefix().string() + ":" + local; return local; } // Global init routines DEFINE_GLOBAL(QualifiedName, anyName, nullAtom, starAtom, starAtom) void QualifiedName::init() { ASSERT(starAtom.impl()); new ((void*)&anyName) QualifiedName(nullAtom, starAtom, starAtom); } const QualifiedName& nullQName() { DEFINE_STATIC_LOCAL(QualifiedName, nullName, (nullAtom, nullAtom, nullAtom)); return nullName; } const AtomicString& QualifiedName::localNameUpper() const { if (!m_impl->m_localNameUpper) m_impl->m_localNameUpper = m_impl->m_localName.upper(); return m_impl->m_localNameUpper; } unsigned QualifiedName::QualifiedNameImpl::computeHash() const { QualifiedNameComponents components = { m_prefix.impl(), m_localName.impl(), m_namespace.impl() }; return hashComponents(components); } void createQualifiedName(void* targetAddress, StringImpl* name, const AtomicString& nameNamespace) { new (targetAddress) QualifiedName(nullAtom, AtomicString(name), nameNamespace); } void createQualifiedName(void* targetAddress, StringImpl* name) { new (targetAddress) QualifiedName(nullAtom, AtomicString(name), nullAtom); } } <|endoftext|>
<commit_before>/* * Copyright (C) 2013 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/fileapi/FileError.h" #include "bindings/v8/ExceptionState.h" #include "core/dom/ExceptionCode.h" namespace WebCore { const char FileError::abortErrorMessage[] = "An ongoing operation was aborted, typically with a call to abort()."; const char FileError::encodingErrorMessage[] = "A URI supplied to the API was malformed, or the resulting Data URL has exceeded the URL length limitations for Data URLs."; const char FileError::invalidStateErrorMessage[] = "An operation that depends on state cached in an interface object was made but the state had changed since it was read from disk."; const char FileError::noModificationAllowedErrorMessage[] = "An attempt was made to write to a file or directory which could not be modified due to the state of the underlying filesystem."; const char FileError::notFoundErrorMessage[] = "A requested file or directory could not be found at the time an operation was processed."; const char FileError::notReadableErrorMessage[] = "The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired."; const char FileError::pathExistsErrorMessage[] = "An attempt was made to create a file or directory where an element already exists."; const char FileError::quotaExceededErrorMessage[] = "The operation failed because it would cause the application to exceed its storage quota."; const char FileError::securityErrorMessage[] = "It was determined that certain files are unsafe for access within a Web application, or that too many calls are being made on file resources."; const char FileError::syntaxErrorMessage[] = "An invalid or unsupported argument was given, like an invalid line ending specifier."; const char FileError::typeMismatchErrorMessage[] = "The path supplied exists, but was not an entry of requested type."; void FileError::throwDOMException(ExceptionState& es, ErrorCode code) { if (code == FileError::OK) return; ExceptionCode ec; const char* message = 0; // Note that some of these do not set message. If message is 0 then the default message is used. switch (code) { case FileError::NOT_FOUND_ERR: ec = NotFoundError; message = FileError::notFoundErrorMessage; break; case FileError::SECURITY_ERR: ec = SecurityError; message = FileError::securityErrorMessage; break; case FileError::ABORT_ERR: ec = AbortError; message = FileError::abortErrorMessage; break; case FileError::NOT_READABLE_ERR: ec = NotReadableError; message = FileError::notReadableErrorMessage; break; case FileError::ENCODING_ERR: ec = EncodingError; message = FileError::encodingErrorMessage; break; case FileError::NO_MODIFICATION_ALLOWED_ERR: ec = NoModificationAllowedError; message = FileError::noModificationAllowedErrorMessage; break; case FileError::INVALID_STATE_ERR: ec = InvalidStateError; message = FileError::invalidStateErrorMessage; break; case FileError::SYNTAX_ERR: ec = SyntaxError; message = FileError::syntaxErrorMessage; break; case FileError::INVALID_MODIFICATION_ERR: ec = InvalidModificationError; break; case FileError::QUOTA_EXCEEDED_ERR: ec = QuotaExceededError; message = FileError::quotaExceededErrorMessage; break; case FileError::TYPE_MISMATCH_ERR: ec = TypeMismatchError; break; case FileError::PATH_EXISTS_ERR: ec = PathExistsError; message = FileError::pathExistsErrorMessage; break; default: ASSERT_NOT_REACHED(); return; } es.throwDOMException(ec, message); } } // namespace WebCore <commit_msg>Convert 'FileError::throwDOMException' to use 'ExceptionState::throwSecurityError'<commit_after>/* * Copyright (C) 2013 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/fileapi/FileError.h" #include "bindings/v8/ExceptionState.h" #include "core/dom/ExceptionCode.h" namespace WebCore { const char FileError::abortErrorMessage[] = "An ongoing operation was aborted, typically with a call to abort()."; const char FileError::encodingErrorMessage[] = "A URI supplied to the API was malformed, or the resulting Data URL has exceeded the URL length limitations for Data URLs."; const char FileError::invalidStateErrorMessage[] = "An operation that depends on state cached in an interface object was made but the state had changed since it was read from disk."; const char FileError::noModificationAllowedErrorMessage[] = "An attempt was made to write to a file or directory which could not be modified due to the state of the underlying filesystem."; const char FileError::notFoundErrorMessage[] = "A requested file or directory could not be found at the time an operation was processed."; const char FileError::notReadableErrorMessage[] = "The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired."; const char FileError::pathExistsErrorMessage[] = "An attempt was made to create a file or directory where an element already exists."; const char FileError::quotaExceededErrorMessage[] = "The operation failed because it would cause the application to exceed its storage quota."; const char FileError::securityErrorMessage[] = "It was determined that certain files are unsafe for access within a Web application, or that too many calls are being made on file resources."; const char FileError::syntaxErrorMessage[] = "An invalid or unsupported argument was given, like an invalid line ending specifier."; const char FileError::typeMismatchErrorMessage[] = "The path supplied exists, but was not an entry of requested type."; void FileError::throwDOMException(ExceptionState& es, ErrorCode code) { if (code == FileError::OK) return; ExceptionCode ec; const char* message = 0; // Note that some of these do not set message. If message is 0 then the default message is used. switch (code) { case FileError::NOT_FOUND_ERR: ec = NotFoundError; message = FileError::notFoundErrorMessage; break; case FileError::ABORT_ERR: ec = AbortError; message = FileError::abortErrorMessage; break; case FileError::NOT_READABLE_ERR: ec = NotReadableError; message = FileError::notReadableErrorMessage; break; case FileError::ENCODING_ERR: ec = EncodingError; message = FileError::encodingErrorMessage; break; case FileError::NO_MODIFICATION_ALLOWED_ERR: ec = NoModificationAllowedError; message = FileError::noModificationAllowedErrorMessage; break; case FileError::INVALID_STATE_ERR: ec = InvalidStateError; message = FileError::invalidStateErrorMessage; break; case FileError::SYNTAX_ERR: ec = SyntaxError; message = FileError::syntaxErrorMessage; break; case FileError::INVALID_MODIFICATION_ERR: ec = InvalidModificationError; break; case FileError::QUOTA_EXCEEDED_ERR: ec = QuotaExceededError; message = FileError::quotaExceededErrorMessage; break; case FileError::TYPE_MISMATCH_ERR: ec = TypeMismatchError; break; case FileError::PATH_EXISTS_ERR: ec = PathExistsError; message = FileError::pathExistsErrorMessage; break; // SecurityError is special-cased, as we want to route those exceptions through ExceptionState::throwSecurityError. case FileError::SECURITY_ERR: es.throwSecurityError(FileError::securityErrorMessage); return; default: ASSERT_NOT_REACHED(); return; } es.throwDOMException(ec, message); } } // namespace WebCore <|endoftext|>
<commit_before>/* Copyright (C) 2005-2006 MySQL AB 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; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "mysql_priv.h" #include "rpl_rli.h" #include "base64.h" /** Execute a BINLOG statement To execute the BINLOG command properly the server needs to know which format the BINLOG command's event is in. Therefore, the first BINLOG statement seen must be a base64 encoding of the Format_description_log_event, as outputted by mysqlbinlog. This Format_description_log_event is cached in rli->description_event_for_exec. */ void mysql_client_binlog_statement(THD* thd) { DBUG_ENTER("mysql_client_binlog_statement"); DBUG_PRINT("info",("binlog base64: '%*s'", (int) (thd->lex->comment.length < 2048 ? thd->lex->comment.length : 2048), thd->lex->comment.str)); if (check_global_access(thd, SUPER_ACL)) DBUG_VOID_RETURN; size_t coded_len= thd->lex->comment.length + 1; size_t decoded_len= base64_needed_decoded_length(coded_len); DBUG_ASSERT(coded_len > 0); /* Allocation */ /* If we do not have a Format_description_event, we create a dummy one here. In this case, the first event we read must be a Format_description_event. */ my_bool have_fd_event= TRUE; if (!thd->rli_fake) { thd->rli_fake= new Relay_log_info; #ifdef HAVE_purify thd->rli_fake->is_fake= TRUE; #endif have_fd_event= FALSE; } if (thd->rli_fake && !thd->rli_fake->relay_log.description_event_for_exec) { thd->rli_fake->relay_log.description_event_for_exec= new Format_description_log_event(4); have_fd_event= FALSE; } const char *error= 0; char *buf= (char *) my_malloc(decoded_len, MYF(MY_WME)); Log_event *ev = 0; /* Out of memory check */ if (!(thd->rli_fake && thd->rli_fake->relay_log.description_event_for_exec && buf)) { my_error(ER_OUTOFMEMORY, MYF(0), 1); /* needed 1 bytes */ goto end; } thd->rli_fake->sql_thd= thd; thd->rli_fake->no_storage= TRUE; for (char const *strptr= thd->lex->comment.str ; strptr < thd->lex->comment.str + thd->lex->comment.length ; ) { char const *endptr= 0; int bytes_decoded= base64_decode(strptr, coded_len, buf, &endptr); #ifndef HAVE_purify /* This debug printout should not be used for valgrind builds since it will read from unassigned memory. */ DBUG_PRINT("info", ("bytes_decoded: %d strptr: 0x%lx endptr: 0x%lx ('%c':%d)", bytes_decoded, (long) strptr, (long) endptr, *endptr, *endptr)); #endif if (bytes_decoded < 0) { my_error(ER_BASE64_DECODE_ERROR, MYF(0)); goto end; } else if (bytes_decoded == 0) break; // If no bytes where read, the string contained only whitespace DBUG_ASSERT(bytes_decoded > 0); DBUG_ASSERT(endptr > strptr); coded_len-= endptr - strptr; strptr= endptr; /* Now we have one or more events stored in the buffer. The size of the buffer is computed based on how much base64-encoded data there were, so there should be ample space for the data (maybe even too much, since a statement can consist of a considerable number of events). TODO: Switch to use a stream-based base64 encoder/decoder in order to be able to read exactly what is necessary. */ DBUG_PRINT("info",("binlog base64 decoded_len: %lu bytes_decoded: %d", (ulong) decoded_len, bytes_decoded)); /* Now we start to read events of the buffer, until there are no more. */ for (char *bufptr= buf ; bytes_decoded > 0 ; ) { /* Checking that the first event in the buffer is not truncated. */ ulong event_len= uint4korr(bufptr + EVENT_LEN_OFFSET); DBUG_PRINT("info", ("event_len=%lu, bytes_decoded=%d", event_len, bytes_decoded)); if (bytes_decoded < EVENT_LEN_OFFSET || (uint) bytes_decoded < event_len) { my_error(ER_SYNTAX_ERROR, MYF(0)); goto end; } /* If we have not seen any Format_description_event, then we must see one; it is the only statement that can be read in base64 without a prior Format_description_event. */ if (!have_fd_event) { int type = bufptr[EVENT_TYPE_OFFSET]; if (type == FORMAT_DESCRIPTION_EVENT || type == START_EVENT_V3) have_fd_event= TRUE; else { my_error(ER_NO_FORMAT_DESCRIPTION_EVENT_BEFORE_BINLOG_STATEMENT, MYF(0), Log_event::get_type_str((Log_event_type)type)); goto end; } } ev= Log_event::read_log_event(bufptr, event_len, &error, thd->rli_fake->relay_log. description_event_for_exec); DBUG_PRINT("info",("binlog base64 err=%s", error)); if (!ev) { /* This could actually be an out-of-memory, but it is more likely causes by a bad statement */ my_error(ER_SYNTAX_ERROR, MYF(0)); goto end; } bytes_decoded -= event_len; bufptr += event_len; DBUG_PRINT("info",("ev->get_type_code()=%d", ev->get_type_code())); #ifndef HAVE_purify /* This debug printout should not be used for valgrind builds since it will read from unassigned memory. */ DBUG_PRINT("info",("bufptr+EVENT_TYPE_OFFSET: 0x%lx", (long) (bufptr+EVENT_TYPE_OFFSET))); DBUG_PRINT("info", ("bytes_decoded: %d bufptr: 0x%lx buf[EVENT_LEN_OFFSET]: %lu", bytes_decoded, (long) bufptr, (ulong) uint4korr(bufptr+EVENT_LEN_OFFSET))); #endif ev->thd= thd; /* We go directly to the application phase, since we don't need to check if the event shall be skipped or not. Neither do we have to update the log positions, since that is not used at all: the rli_fake instance is used only for error reporting. */ #if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) if (apply_event_and_update_pos(ev, thd, thd->rli_fake, FALSE)) { /* TODO: Maybe a better error message since the BINLOG statement now contains several events. */ my_error(ER_UNKNOWN_ERROR, MYF(0), "Error executing BINLOG statement"); goto end; } #endif /* Format_description_log_event should not be deleted because it will be used to read info about the relay log's format; it will be deleted when the SQL thread does not need it, i.e. when this thread terminates. */ if (ev->get_type_code() != FORMAT_DESCRIPTION_EVENT) delete ev; ev= 0; } } DBUG_PRINT("info",("binlog base64 execution finished successfully")); my_ok(thd); end: thd->rli_fake->clear_tables_to_lock(); my_free(buf, MYF(MY_ALLOW_ZERO_PTR)); DBUG_VOID_RETURN; } <commit_msg>BUG#38290 valgrind warnings in binlog_base64_flag<commit_after>/* Copyright (C) 2005-2006 MySQL AB 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; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "mysql_priv.h" #include "rpl_rli.h" #include "base64.h" /** Execute a BINLOG statement To execute the BINLOG command properly the server needs to know which format the BINLOG command's event is in. Therefore, the first BINLOG statement seen must be a base64 encoding of the Format_description_log_event, as outputted by mysqlbinlog. This Format_description_log_event is cached in rli->description_event_for_exec. */ void mysql_client_binlog_statement(THD* thd) { DBUG_ENTER("mysql_client_binlog_statement"); DBUG_PRINT("info",("binlog base64: '%*s'", (int) (thd->lex->comment.length < 2048 ? thd->lex->comment.length : 2048), thd->lex->comment.str)); if (check_global_access(thd, SUPER_ACL)) DBUG_VOID_RETURN; size_t coded_len= thd->lex->comment.length + 1; size_t decoded_len= base64_needed_decoded_length(coded_len); DBUG_ASSERT(coded_len > 0); /* Allocation */ /* If we do not have a Format_description_event, we create a dummy one here. In this case, the first event we read must be a Format_description_event. */ my_bool have_fd_event= TRUE; if (!thd->rli_fake) { thd->rli_fake= new Relay_log_info; #ifdef HAVE_purify thd->rli_fake->is_fake= TRUE; #endif have_fd_event= FALSE; } if (thd->rli_fake && !thd->rli_fake->relay_log.description_event_for_exec) { thd->rli_fake->relay_log.description_event_for_exec= new Format_description_log_event(4); have_fd_event= FALSE; } const char *error= 0; char *buf= (char *) my_malloc(decoded_len, MYF(MY_WME)); Log_event *ev = 0; /* Out of memory check */ if (!(thd->rli_fake && thd->rli_fake->relay_log.description_event_for_exec && buf)) { my_error(ER_OUTOFMEMORY, MYF(0), 1); /* needed 1 bytes */ goto end; } thd->rli_fake->sql_thd= thd; thd->rli_fake->no_storage= TRUE; for (char const *strptr= thd->lex->comment.str ; strptr < thd->lex->comment.str + thd->lex->comment.length ; ) { char const *endptr= 0; int bytes_decoded= base64_decode(strptr, coded_len, buf, &endptr); #ifndef HAVE_purify /* This debug printout should not be used for valgrind builds since it will read from unassigned memory. */ DBUG_PRINT("info", ("bytes_decoded: %d strptr: 0x%lx endptr: 0x%lx ('%c':%d)", bytes_decoded, (long) strptr, (long) endptr, *endptr, *endptr)); #endif if (bytes_decoded < 0) { my_error(ER_BASE64_DECODE_ERROR, MYF(0)); goto end; } else if (bytes_decoded == 0) break; // If no bytes where read, the string contained only whitespace DBUG_ASSERT(bytes_decoded > 0); DBUG_ASSERT(endptr > strptr); coded_len-= endptr - strptr; strptr= endptr; /* Now we have one or more events stored in the buffer. The size of the buffer is computed based on how much base64-encoded data there were, so there should be ample space for the data (maybe even too much, since a statement can consist of a considerable number of events). TODO: Switch to use a stream-based base64 encoder/decoder in order to be able to read exactly what is necessary. */ DBUG_PRINT("info",("binlog base64 decoded_len: %lu bytes_decoded: %d", (ulong) decoded_len, bytes_decoded)); /* Now we start to read events of the buffer, until there are no more. */ for (char *bufptr= buf ; bytes_decoded > 0 ; ) { /* Checking that the first event in the buffer is not truncated. */ ulong event_len= uint4korr(bufptr + EVENT_LEN_OFFSET); DBUG_PRINT("info", ("event_len=%lu, bytes_decoded=%d", event_len, bytes_decoded)); if (bytes_decoded < EVENT_LEN_OFFSET || (uint) bytes_decoded < event_len) { my_error(ER_SYNTAX_ERROR, MYF(0)); goto end; } /* If we have not seen any Format_description_event, then we must see one; it is the only statement that can be read in base64 without a prior Format_description_event. */ if (!have_fd_event) { int type = bufptr[EVENT_TYPE_OFFSET]; if (type == FORMAT_DESCRIPTION_EVENT || type == START_EVENT_V3) have_fd_event= TRUE; else { my_error(ER_NO_FORMAT_DESCRIPTION_EVENT_BEFORE_BINLOG_STATEMENT, MYF(0), Log_event::get_type_str((Log_event_type)type)); goto end; } } ev= Log_event::read_log_event(bufptr, event_len, &error, thd->rli_fake->relay_log. description_event_for_exec); DBUG_PRINT("info",("binlog base64 err=%s", error)); if (!ev) { /* This could actually be an out-of-memory, but it is more likely causes by a bad statement */ my_error(ER_SYNTAX_ERROR, MYF(0)); goto end; } bytes_decoded -= event_len; bufptr += event_len; DBUG_PRINT("info",("ev->get_type_code()=%d", ev->get_type_code())); #ifndef HAVE_purify /* This debug printout should not be used for valgrind builds since it will read from unassigned memory. */ DBUG_PRINT("info",("bufptr+EVENT_TYPE_OFFSET: 0x%lx", (long) (bufptr+EVENT_TYPE_OFFSET))); DBUG_PRINT("info", ("bytes_decoded: %d bufptr: 0x%lx buf[EVENT_LEN_OFFSET]: %lu", bytes_decoded, (long) bufptr, (ulong) uint4korr(bufptr+EVENT_LEN_OFFSET))); #endif ev->thd= thd; /* We go directly to the application phase, since we don't need to check if the event shall be skipped or not. Neither do we have to update the log positions, since that is not used at all: the rli_fake instance is used only for error reporting. */ #if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) if (apply_event_and_update_pos(ev, thd, thd->rli_fake, FALSE)) { delete ev; /* TODO: Maybe a better error message since the BINLOG statement now contains several events. */ my_error(ER_UNKNOWN_ERROR, MYF(0), "Error executing BINLOG statement"); goto end; } #endif /* Format_description_log_event should not be deleted because it will be used to read info about the relay log's format; it will be deleted when the SQL thread does not need it, i.e. when this thread terminates. */ if (ev->get_type_code() != FORMAT_DESCRIPTION_EVENT) delete ev; ev= 0; } } DBUG_PRINT("info",("binlog base64 execution finished successfully")); my_ok(thd); end: thd->rli_fake->clear_tables_to_lock(); my_free(buf, MYF(MY_ALLOW_ZERO_PTR)); DBUG_VOID_RETURN; } <|endoftext|>
<commit_before>#ifndef AppConfig_hpp #define AppConfig_hpp #include <string> class AppConfig { public: AppConfig(); void setFileName(std::string fileName); void setDeviceID(int deviceID); void setIsFile(int isFile); void setIsDevice(int isDevice); void setIsHeadless(int isHeadless); void setIsNetworking(int isNetworking); void setIsDebug(int debug); int getDeviceID(); int getIsFile(); int getIsDevice(); int getIsHeadless(); int getIsNetworking(); int getIsDebug(); std::string getFileName(); private: std::string fileName; int deviceID; int isFile; int isDevice; int isHeadless; int isNetworking; int isDebug; }; #endif /* AppConfig_hpp */ <commit_msg>Deleting old files<commit_after><|endoftext|>
<commit_before>#include "Benchmark.h" #include <iostream> Benchmark::Benchmark(const int runtimeMs, const int allocation_size, const int alignment_size){ m_runtimeMs = runtimeMs; m_allocationSize = allocation_size; m_alignmentSize = alignment_size; } BenchmarkResults Benchmark::Allocation(Allocator* allocator){ std::cout << "BENCHMARK: ALLOCATION" << std::endl; setTimer(m_start); int operations = 0; while(!outOfTime()){ allocator->Allocate(m_allocationSize, m_alignmentSize); ++operations; } BenchmarkResults results = buildResults(operations, m_runtimeMs, 0,0); printResults(results); return results; } void Benchmark::setStartTimer(){ setTimer(m_start); } void Benchmark::setTimer(timespec& timer){ clock_gettime(CLOCK_REALTIME, &timer); } const bool Benchmark::outOfTime() { timespec now; setTimer(now); double elapsedTime = calculateElapsedTime(m_start, now); if (elapsedTime > m_runtimeMs){ return true; } //std::cout << elapsedTime << std::endl; return false; } const double Benchmark::calculateElapsedTime(const timespec& start, const timespec& end) const { timespec temp; if ((end.tv_nsec-start.tv_nsec) < 0) { temp.tv_sec = end.tv_sec-start.tv_sec-1; temp.tv_nsec = 1e9+end.tv_nsec-start.tv_nsec; } else { temp.tv_sec = end.tv_sec-start.tv_sec; temp.tv_nsec = end.tv_nsec-start.tv_nsec; } const double time_sec = (double) temp.tv_sec; const double time_nsec = (double) temp.tv_nsec; const double time_msec = (time_sec * 1e3) + (time_nsec / 1e6); return time_msec; } void Benchmark::printResults(const BenchmarkResults& results) const { std::cout << "\tRESULTS:" << std::endl; std::cout << "\t\tOperations: \t" << results.nOperations << std::endl; std::cout << "\t\tTime elapsed: \t" << results.elapsedTime << " ms" << std::endl; std::cout << "\t\tOp per sec: \t" << results.operationsPerSec << " ops/ms" << std::endl; std::cout << "\t\tTimer per op: \t" << results.timePerOperation << " ms/ops" << std::endl; if (results.memoryUsed > 0) { std::cout << "\t\tMemory used: \t" << results.memoryUsed << " bytes" << std::endl; std::cout << "\t\tMemory wasted: \t" << results.memoryWasted << " bytes\t" << "\t" << ((float) results.memoryWasted / results.memoryUsed)*100 << "%" << std::endl; } std::cout << std::endl; } const BenchmarkResults Benchmark::buildResults(const long nOperations, const double elapsedTime, const std::size_t memoryUsed, const std::size_t memoryWasted) const{ BenchmarkResults results; results.nOperations = nOperations; results.elapsedTime = elapsedTime; results.operationsPerSec = results.nOperations / results.elapsedTime; results.timePerOperation = results.elapsedTime / results.nOperations; results.memoryUsed = memoryUsed; results.memoryWasted = memoryWasted; return results; } <commit_msg>Added size and alignment information on print<commit_after>#include "Benchmark.h" #include <iostream> Benchmark::Benchmark(const int runtimeMs, const int allocation_size, const int alignment_size){ m_runtimeMs = runtimeMs; m_allocationSize = allocation_size; m_alignmentSize = alignment_size; } BenchmarkResults Benchmark::Allocation(Allocator* allocator){ std::cout << "BENCHMARK: ALLOCATION" << std::endl; std::cout << "\tSize: \t" << m_allocationSize << std::endl; std::cout << "\tAlignment\t" << m_alignmentSize << std::endl; setTimer(m_start); int operations = 0; while(!outOfTime()){ allocator->Allocate(m_allocationSize, m_alignmentSize); ++operations; } BenchmarkResults results = buildResults(operations, m_runtimeMs, 0,0); printResults(results); return results; } void Benchmark::setStartTimer(){ setTimer(m_start); } void Benchmark::setTimer(timespec& timer){ clock_gettime(CLOCK_REALTIME, &timer); } const bool Benchmark::outOfTime() { timespec now; setTimer(now); double elapsedTime = calculateElapsedTime(m_start, now); if (elapsedTime > m_runtimeMs){ return true; } //std::cout << elapsedTime << std::endl; return false; } const double Benchmark::calculateElapsedTime(const timespec& start, const timespec& end) const { timespec temp; if ((end.tv_nsec-start.tv_nsec) < 0) { temp.tv_sec = end.tv_sec-start.tv_sec-1; temp.tv_nsec = 1e9+end.tv_nsec-start.tv_nsec; } else { temp.tv_sec = end.tv_sec-start.tv_sec; temp.tv_nsec = end.tv_nsec-start.tv_nsec; } const double time_sec = (double) temp.tv_sec; const double time_nsec = (double) temp.tv_nsec; const double time_msec = (time_sec * 1e3) + (time_nsec / 1e6); return time_msec; } void Benchmark::printResults(const BenchmarkResults& results) const { std::cout << "\tRESULTS:" << std::endl; std::cout << "\t\tOperations: \t" << results.nOperations << std::endl; std::cout << "\t\tTime elapsed: \t" << results.elapsedTime << " ms" << std::endl; std::cout << "\t\tOp per sec: \t" << results.operationsPerSec << " ops/ms" << std::endl; std::cout << "\t\tTimer per op: \t" << results.timePerOperation << " ms/ops" << std::endl; if (results.memoryUsed > 0) { std::cout << "\t\tMemory used: \t" << results.memoryUsed << " bytes" << std::endl; std::cout << "\t\tMemory wasted: \t" << results.memoryWasted << " bytes\t" << "\t" << ((float) results.memoryWasted / results.memoryUsed)*100 << "%" << std::endl; } std::cout << std::endl; } const BenchmarkResults Benchmark::buildResults(const long nOperations, const double elapsedTime, const std::size_t memoryUsed, const std::size_t memoryWasted) const{ BenchmarkResults results; results.nOperations = nOperations; results.elapsedTime = elapsedTime; results.operationsPerSec = results.nOperations / results.elapsedTime; results.timePerOperation = results.elapsedTime / results.nOperations; results.memoryUsed = memoryUsed; results.memoryWasted = memoryWasted; return results; } <|endoftext|>
<commit_before>namespace bmi { const int BMI_SUCCESS = 0; const int BMI_FAILURE = 1; const int MAX_COMPONENT_NAME = 2048; const int MAX_VAR_NAME = 2048; const int MAX_UNITS_NAME = 2048; const int MAX_TYPE_NAME = 2048; class Bmi { public: // Model control functions. virtual void Initialize(std::string config_file) = 0; virtual void Update() = 0; virtual void UpdateUntil(double time) = 0; virtual void Finalize() = 0; // Model information functions. virtual std::string GetComponentName() = 0; virtual int GetInputItemCount() = 0; virtual int GetOutputItemCount() = 0; virtual void GetInputVarNames(char **names) = 0; virtual void GetOutputVarNames(char **names) = 0; // Variable information functions virtual int GetVarGrid(std::string name) = 0; virtual std::string GetVarType(std::string name) = 0; virtual std::string GetVarUnits(std::string name) = 0; virtual int GetVarItemsize(std::string name) = 0; virtual int GetVarNbytes(std::string name) = 0; virtual std::string GetVarLocation(std::string name) = 0; virtual double GetCurrentTime() = 0; virtual double GetStartTime() = 0; virtual double GetEndTime() = 0; virtual std::string GetTimeUnits() = 0; virtual double GetTimeStep() = 0; // Variable getters virtual void GetValue(std::string name, void *dest) = 0; virtual void *GetValuePtr(std::string name) = 0; virtual void GetValueAtIndices(std::string name, void *dest, int *inds, int count) = 0; // Variable setters virtual void SetValue(std::string name, void *src) = 0; virtual void SetValueAtIndices(std::string name, int *inds, int count, void *src) = 0; // Grid information functions virtual int GetGridRank(const int grid) = 0; virtual int GetGridSize(const int grid) = 0; virtual std::string GetGridType(const int grid) = 0; virtual void GetGridShape(const int grid, int *shape) = 0; virtual void GetGridSpacing(const int grid, double *spacing) = 0; virtual void GetGridOrigin(const int grid, double *origin) = 0; virtual void GetGridX(const int grid, double *x) = 0; virtual void GetGridY(const int grid, double *y) = 0; virtual void GetGridZ(const int grid, double *z) = 0; virtual int GetGridNodeCount(const int grid) = 0; virtual int GetGridEdgeCount(const int grid) = 0; virtual int GetGridFaceCount(const int grid) = 0; virtual void GetGridEdgeNodes(const int grid, int *edge_nodes) = 0; virtual void GetGridFaceEdges(const int grid, int *face_edges) = 0; virtual void GetGridFaceNodes(const int grid, int *face_nodes) = 0; virtual void GetGridNodesPerFace(const int grid, int *nodes_per_face) = 0; }; } <commit_msg>Get input/output variable names with vector<string><commit_after>namespace bmi { const int BMI_SUCCESS = 0; const int BMI_FAILURE = 1; const int MAX_COMPONENT_NAME = 2048; const int MAX_VAR_NAME = 2048; const int MAX_UNITS_NAME = 2048; const int MAX_TYPE_NAME = 2048; class Bmi { public: // Model control functions. virtual void Initialize(std::string config_file) = 0; virtual void Update() = 0; virtual void UpdateUntil(double time) = 0; virtual void Finalize() = 0; // Model information functions. virtual std::string GetComponentName() = 0; virtual int GetInputItemCount() = 0; virtual int GetOutputItemCount() = 0; virtual void GetInputVarNames(std::vector<std::string>&) = 0; virtual void GetOutputVarNames(std::vector<std::string>&) = 0; // Variable information functions virtual int GetVarGrid(std::string name) = 0; virtual std::string GetVarType(std::string name) = 0; virtual std::string GetVarUnits(std::string name) = 0; virtual int GetVarItemsize(std::string name) = 0; virtual int GetVarNbytes(std::string name) = 0; virtual std::string GetVarLocation(std::string name) = 0; virtual double GetCurrentTime() = 0; virtual double GetStartTime() = 0; virtual double GetEndTime() = 0; virtual std::string GetTimeUnits() = 0; virtual double GetTimeStep() = 0; // Variable getters virtual void GetValue(std::string name, void *dest) = 0; virtual void *GetValuePtr(std::string name) = 0; virtual void GetValueAtIndices(std::string name, void *dest, int *inds, int count) = 0; // Variable setters virtual void SetValue(std::string name, void *src) = 0; virtual void SetValueAtIndices(std::string name, int *inds, int count, void *src) = 0; // Grid information functions virtual int GetGridRank(const int grid) = 0; virtual int GetGridSize(const int grid) = 0; virtual std::string GetGridType(const int grid) = 0; virtual void GetGridShape(const int grid, int *shape) = 0; virtual void GetGridSpacing(const int grid, double *spacing) = 0; virtual void GetGridOrigin(const int grid, double *origin) = 0; virtual void GetGridX(const int grid, double *x) = 0; virtual void GetGridY(const int grid, double *y) = 0; virtual void GetGridZ(const int grid, double *z) = 0; virtual int GetGridNodeCount(const int grid) = 0; virtual int GetGridEdgeCount(const int grid) = 0; virtual int GetGridFaceCount(const int grid) = 0; virtual void GetGridEdgeNodes(const int grid, int *edge_nodes) = 0; virtual void GetGridFaceEdges(const int grid, int *face_edges) = 0; virtual void GetGridFaceNodes(const int grid, int *face_nodes) = 0; virtual void GetGridNodesPerFace(const int grid, int *nodes_per_face) = 0; }; } <|endoftext|>
<commit_before>// Vaca - Visual Application Components Abstraction // Copyright (c) 2005, 2006, 2007, 2008, 2009, David Capello // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // * Neither the name of the author nor the names of its contributors // may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. #include "Vaca/Clipboard.h" #include "Vaca/Widget.h" #include "Vaca/System.h" #include "Vaca/String.h" using namespace Vaca; Clipboard::Clipboard(Widget* owner) { m_owner = owner; } Clipboard::~Clipboard() { } bool Clipboard::isText() const { return IsClipboardFormatAvailable(CF_TEXT) ? true: false; } String Clipboard::getString() const { HWND hwndOwner = m_owner ? m_owner->getHandle(): NULL; String str; if (!IsClipboardFormatAvailable(CF_TEXT)) return str; if (!OpenClipboard(hwndOwner)) return str; HGLOBAL hglobal = GetClipboardData(CF_TEXT); if (hglobal != NULL) { LPTSTR lptstr = static_cast<LPTSTR>(GlobalLock(hglobal)); if (lptstr != NULL) { str.assign(lptstr); GlobalUnlock(hglobal); } } CloseClipboard(); return str; } void Clipboard::setString(const String& str) { HWND hwndOwner = m_owner ? m_owner->getHandle(): NULL; if (!OpenClipboard(hwndOwner)) return; EmptyClipboard(); // NT, 2K and XP if (System::isWinNT_2K_XP()) { int len = str.size(); HGLOBAL hglobal = GlobalAlloc(GMEM_MOVEABLE, sizeof(Char)*(len+1)); LPTSTR lptstr = static_cast<LPTSTR>(GlobalLock(hglobal)); copy_string_to(str, lptstr, len); GlobalUnlock(hglobal); #ifdef _UNICODE SetClipboardData(CF_UNICODETEXT, hglobal); #else SetClipboardData(CF_TEXT, hglobal); #endif } // 98, Me else { #ifdef _UNICODE // TODO convert the str to ANSI and copy the content to Clipboard #else int len = str.size(); HGLOBAL hglobal = GlobalAlloc(GMEM_MOVEABLE, sizeof(Char)*(len+1)); LPTSTR lptstr = static_cast<LPTSTR>(GlobalLock(hglobal)); str.copyTo(lptstr, len); GlobalUnlock(hglobal); SetClipboardData(CF_TEXT, hglobal); #endif } CloseClipboard(); } <commit_msg>Fixed a problem getting Unicode text in Clipboard.<commit_after>// Vaca - Visual Application Components Abstraction // Copyright (c) 2005, 2006, 2007, 2008, 2009, David Capello // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // * Neither the name of the author nor the names of its contributors // may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. #include "Vaca/Clipboard.h" #include "Vaca/Widget.h" #include "Vaca/System.h" #include "Vaca/String.h" using namespace Vaca; Clipboard::Clipboard(Widget* owner) { m_owner = owner; } Clipboard::~Clipboard() { } bool Clipboard::isText() const { return IsClipboardFormatAvailable(CF_TEXT) ? true: false; } String Clipboard::getString() const { HWND hwndOwner = m_owner ? m_owner->getHandle(): NULL; String str; if (!IsClipboardFormatAvailable(CF_TEXT) && !IsClipboardFormatAvailable(CF_UNICODETEXT)) return str; if (!OpenClipboard(hwndOwner)) return str; HGLOBAL hglobal = GetClipboardData(CF_UNICODETEXT); if (hglobal != NULL) { LPWSTR lpwstr = static_cast<LPWSTR>(GlobalLock(hglobal)); if (lpwstr != NULL) { str = lpwstr; GlobalUnlock(hglobal); } } else { hglobal = GetClipboardData(CF_TEXT); if (hglobal != NULL) { LPSTR lpstr = static_cast<LPSTR>(GlobalLock(hglobal)); if (lpstr != NULL) { str = convert_to<String>(lpstr); GlobalUnlock(hglobal); } } } CloseClipboard(); return str; } void Clipboard::setString(const String& str) { HWND hwndOwner = m_owner ? m_owner->getHandle(): NULL; if (!OpenClipboard(hwndOwner)) return; EmptyClipboard(); // NT, 2K and XP if (System::isWinNT_2K_XP()) { int len = str.size(); HGLOBAL hglobal = GlobalAlloc(GMEM_MOVEABLE, sizeof(Char)*(len+1)); LPTSTR lptstr = static_cast<LPTSTR>(GlobalLock(hglobal)); copy_string_to(str, lptstr, len); GlobalUnlock(hglobal); #ifdef _UNICODE SetClipboardData(CF_UNICODETEXT, hglobal); #else SetClipboardData(CF_TEXT, hglobal); #endif } // 98, Me else { #ifdef _UNICODE // TODO convert the str to ANSI and copy the content to Clipboard #else int len = str.size(); HGLOBAL hglobal = GlobalAlloc(GMEM_MOVEABLE, sizeof(Char)*(len+1)); LPTSTR lptstr = static_cast<LPTSTR>(GlobalLock(hglobal)); str.copyTo(lptstr, len); GlobalUnlock(hglobal); SetClipboardData(CF_TEXT, hglobal); #endif } CloseClipboard(); } <|endoftext|>
<commit_before>/* * BLINKERCOUGH: NSA Playset implant for IR bridging of airgap * * Copyright (C) 2015 Hacker, J.R. <r00tkillah@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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "mac.h" #include "util.h" #include <Arduino.h> BlinkerMac mac; MemberFunctionCallable<BlinkerMac> MACRelayCB(&mac, &BlinkerMac::relayCallback); BlinkerMac::BlinkerMac() : serial(SoftwareSerial(IR_RX_PIN, IR_TX_PIN, false)) { } void BlinkerMac::begin() { serial.begin(IR_BAUD); reset(); buf = FrameFactory.alloc(); eventManager.addListener(BlinkerMac::PacketNeedsRelayEvent, &MACRelayCB); } void BlinkerMac::reset() { rx_blink = false; packet_in_progress = false; buf_pos = 0; prefix_state = 0; reset_codec_state(); } void BlinkerMac::write_prefix() { for (uint8_t i = 0; i < preamble_count; i++) { (*this)(preamble_byte); } for (uint8_t i = 0; i < sizeof(packet_prefix); i++) { (*this)(packet_prefix[i]); } } bool BlinkerMac::prefix_hit(uint8_t input) { debug("prefix state: %d; input=%02x", prefix_state, input); if (prefix_state == 0) { if (input == packet_prefix[0]) { prefix_state = 1; } } else if (prefix_state == 1) { if (input == packet_prefix[1]) { prefix_state = 2; } else { prefix_state = 0; } } else if (prefix_state == 2) { if (input == packet_prefix[2]) { prefix_state = 3; } else { prefix_state = 0; } } else if (prefix_state == 3) { prefix_state = 0; if (input == packet_prefix[3]) { return true; } } return false; } bool BlinkerMac::blink() { rx_blink = rx_blink ? false : true; return rx_blink; } bool BlinkerMac::stalled() { const unsigned long now = millis(); if (now - last_rx_time > 250) { return true; } last_rx_time = now; return false; } //expectation here is that hton is done //and crc is calculated void BlinkerMac::send_frame(IRFrame &frame) { debug("Sending packet"); write_prefix(); for (uint16_t i = 0; i < sizeof(IRFrame); i++) { encode_byte(frame.blob()[i], *this); } serial.flush(); // while this is happening, you'll get crap that is your own packet. // clear out any remaining input while(serial.available()) { (void)serial.read(); delay(1); } } void BlinkerMac::recv(const uint8_t c) { digitalWrite(13, blink()); // if you haven't gotten a byte in a while, then what you have // is probably garbage. if (packet_in_progress && stalled()) { Serial.println("aborting rcv"); IRFrame::hexdump(buf); reset(); return; } if (!packet_in_progress) { packet_in_progress = prefix_hit(c); last_rx_time = millis(); return; //the next byte should be the first byte of a packet } debugstart("%d", buf_pos); debugcont(" "); //geting a packet uint8_t input; if (decode_byte(c, input)) { buf->blob()[buf_pos] = input; buf_pos++; } else { return; // was a stuffed byte } if (buf_pos >= sizeof(IRFrame)) { //whole packet recieved! buf_pos = 0; packet_in_progress = false; if (buf->valid()) { buf->ntoh(); if (buf->destination != address) { if (buf->hops < MAX_HOPS) { auto newbuf = FrameFactory.alloc(); IRFrame::copy(newbuf, buf); eventManager.queueEvent(PacketNeedsRelayEvent, (int)newbuf); return; } else { debugcont("too many hops.. eating"); debugend(); reset(); return; } } auto newbuf = FrameFactory.alloc(); IRFrame::copy(newbuf, buf); eventManager.queueEvent(ValidFrameRecievedEvent, (int)newbuf); return; } else { auto newbuf = FrameFactory.alloc(); IRFrame::copy(newbuf, buf); eventManager.queueEvent(InvalidFrameRecievedEvent, (int)newbuf); reset(); } } return; } void BlinkerMac::relayCallback(int event, int param) { //niave approach.. just send it back out this is kind of wrong we //should wait a random time before retransmit and as we get //packets, we should cancel retransmit if we saw a neighbor do it //first. but when we see that neighbor do it, we schedule a new //one to retransmit. IRFrame *buf = (IRFrame*)param; debug("Packet from 0x%04x to 0x%04x hop %d", buf->source, buf->destination, buf->hops); buf->hops++; buf->hton(); buf->calculate_crc(); debug("Retransmitting packet..."); send_frame(*buf); debug("done"); reset(); FrameFactory.free(buf); } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * mode: c++ * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */ <commit_msg>catch some cases where debug wasn't used right<commit_after>/* * BLINKERCOUGH: NSA Playset implant for IR bridging of airgap * * Copyright (C) 2015 Hacker, J.R. <r00tkillah@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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "mac.h" #include "util.h" #include <Arduino.h> BlinkerMac mac; MemberFunctionCallable<BlinkerMac> MACRelayCB(&mac, &BlinkerMac::relayCallback); BlinkerMac::BlinkerMac() : serial(SoftwareSerial(IR_RX_PIN, IR_TX_PIN, false)) { } void BlinkerMac::begin() { serial.begin(IR_BAUD); reset(); buf = FrameFactory.alloc(); eventManager.addListener(BlinkerMac::PacketNeedsRelayEvent, &MACRelayCB); } void BlinkerMac::reset() { rx_blink = false; packet_in_progress = false; buf_pos = 0; prefix_state = 0; reset_codec_state(); } void BlinkerMac::write_prefix() { for (uint8_t i = 0; i < preamble_count; i++) { (*this)(preamble_byte); } for (uint8_t i = 0; i < sizeof(packet_prefix); i++) { (*this)(packet_prefix[i]); } } bool BlinkerMac::prefix_hit(uint8_t input) { debug("prefix state: %d; input=%02x", prefix_state, input); if (prefix_state == 0) { if (input == packet_prefix[0]) { prefix_state = 1; } } else if (prefix_state == 1) { if (input == packet_prefix[1]) { prefix_state = 2; } else { prefix_state = 0; } } else if (prefix_state == 2) { if (input == packet_prefix[2]) { prefix_state = 3; } else { prefix_state = 0; } } else if (prefix_state == 3) { prefix_state = 0; if (input == packet_prefix[3]) { return true; } } return false; } bool BlinkerMac::blink() { rx_blink = rx_blink ? false : true; return rx_blink; } bool BlinkerMac::stalled() { const unsigned long now = millis(); if (now - last_rx_time > 250) { return true; } last_rx_time = now; return false; } //expectation here is that hton is done //and crc is calculated void BlinkerMac::send_frame(IRFrame &frame) { debug("Sending packet"); write_prefix(); for (uint16_t i = 0; i < sizeof(IRFrame); i++) { encode_byte(frame.blob()[i], *this); } serial.flush(); // while this is happening, you'll get crap that is your own packet. // clear out any remaining input while(serial.available()) { (void)serial.read(); delay(1); } } void BlinkerMac::recv(const uint8_t c) { digitalWrite(13, blink()); // if you haven't gotten a byte in a while, then what you have // is probably garbage. if (packet_in_progress && stalled()) { debug("aborting rcv"); IRFrame::hexdump(buf); reset(); return; } if (!packet_in_progress) { packet_in_progress = prefix_hit(c); last_rx_time = millis(); return; //the next byte should be the first byte of a packet } debugstart("%d", buf_pos); debugcont(" "); //geting a packet uint8_t input; if (decode_byte(c, input)) { buf->blob()[buf_pos] = input; buf_pos++; } else { return; // was a stuffed byte } if (buf_pos >= sizeof(IRFrame)) { //whole packet recieved! buf_pos = 0; packet_in_progress = false; if (buf->valid()) { buf->ntoh(); if (buf->destination != address) { if (buf->hops < MAX_HOPS) { auto newbuf = FrameFactory.alloc(); IRFrame::copy(newbuf, buf); eventManager.queueEvent(PacketNeedsRelayEvent, (int)newbuf); debugend(); return; } else { debugcont("too many hops.. eating"); debugend(); reset(); return; } } auto newbuf = FrameFactory.alloc(); IRFrame::copy(newbuf, buf); eventManager.queueEvent(ValidFrameRecievedEvent, (int)newbuf); debugend(); return; } else { auto newbuf = FrameFactory.alloc(); IRFrame::copy(newbuf, buf); eventManager.queueEvent(InvalidFrameRecievedEvent, (int)newbuf); debugend(); reset(); } } return; } void BlinkerMac::relayCallback(int event, int param) { //niave approach.. just send it back out this is kind of wrong we //should wait a random time before retransmit and as we get //packets, we should cancel retransmit if we saw a neighbor do it //first. but when we see that neighbor do it, we schedule a new //one to retransmit. IRFrame *buf = (IRFrame*)param; debug("Packet from 0x%04x to 0x%04x hop %d", buf->source, buf->destination, buf->hops); buf->hops++; buf->hton(); buf->calculate_crc(); debug("Retransmitting packet..."); send_frame(*buf); debug("done"); reset(); FrameFactory.free(buf); } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * mode: c++ * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */ <|endoftext|>
<commit_before>/* * BLINKERCOUGH: NSA Playset implant for IR bridging of airgap * * Copyright (C) 2015 Hacker, J.R. <r00tkillah@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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "mac.h" #include "util.h" #include <Arduino.h> BlinkerMac mac; MemberFunctionCallable<BlinkerMac> MACRelayCB(&mac, &BlinkerMac::relayCallback); BlinkerMac::BlinkerMac() : serial(SoftwareSerial(IR_RX_PIN, IR_TX_PIN, false)) { } void BlinkerMac::begin() { serial.begin(IR_BAUD); reset(); buf = FrameFactory.alloc(); eventManager.addListener(BlinkerMac::PacketNeedsRelayEvent, &MACRelayCB); } void BlinkerMac::reset() { rx_blink = false; packet_in_progress = false; buf_pos = 0; prefix_state = 0; reset_codec_state(); } void BlinkerMac::write_prefix() { for (uint8_t i = 0; i < preamble_count; i++) { (*this)(preamble_byte); } for (uint8_t i = 0; i < sizeof(packet_prefix); i++) { (*this)(packet_prefix[i]); } } bool BlinkerMac::prefix_hit(uint8_t input) { debug("prefix state: %d; input=%02x", prefix_state, input); if (prefix_state == 0) { if (input == packet_prefix[0]) { prefix_state = 1; } } else if (prefix_state == 1) { if (input == packet_prefix[1]) { prefix_state = 2; } else { prefix_state = 0; } } else if (prefix_state == 2) { if (input == packet_prefix[2]) { prefix_state = 3; } else { prefix_state = 0; } } else if (prefix_state == 3) { prefix_state = 0; if (input == packet_prefix[3]) { return true; } } return false; } bool BlinkerMac::blink() { rx_blink = rx_blink ? false : true; return rx_blink; } bool BlinkerMac::stalled() { const unsigned long now = millis(); if (now - last_rx_time > 250) { return true; } last_rx_time = now; return false; } //expectation here is that hton is done //and crc is calculated void BlinkerMac::send_frame(IRFrame &frame) { debug("Sending packet"); write_prefix(); for (uint16_t i = 0; i < sizeof(IRFrame); i++) { encode_byte(frame.blob()[i], *this); } serial.flush(); // while this is happening, you'll get crap that is your own packet. // clear out any remaining input while(serial.available()) { (void)serial.read(); delay(1); } } void BlinkerMac::recv(const uint8_t c) { digitalWrite(13, blink()); // if you haven't gotten a byte in a while, then what you have // is probably garbage. if (packet_in_progress && stalled()) { debug("aborting rcv"); IRFrame::hexdump(buf); reset(); return; } if (!packet_in_progress) { packet_in_progress = prefix_hit(c); last_rx_time = millis(); return; //the next byte should be the first byte of a packet } debugstart("%d", buf_pos); debugcont(" "); //geting a packet uint8_t input; if (decode_byte(c, input)) { buf->blob()[buf_pos] = input; buf_pos++; } else { return; // was a stuffed byte } if (buf_pos >= sizeof(IRFrame)) { //whole packet recieved! buf_pos = 0; packet_in_progress = false; if (buf->valid()) { buf->ntoh(); if (buf->destination != address) { if (buf->hops < MAX_HOPS) { auto newbuf = FrameFactory.alloc(); IRFrame::copy(newbuf, buf); eventManager.queueEvent(PacketNeedsRelayEvent, (int)newbuf); debugend(); reset(); return; } else { debugcont("too many hops.. eating"); debugend(); reset(); return; } } auto newbuf = FrameFactory.alloc(); IRFrame::copy(newbuf, buf); eventManager.queueEvent(ValidFrameRecievedEvent, (int)newbuf); debugend(); reset(); return; } else { auto newbuf = FrameFactory.alloc(); IRFrame::copy(newbuf, buf); eventManager.queueEvent(InvalidFrameRecievedEvent, (int)newbuf); debugend(); reset(); } } return; } void BlinkerMac::relayCallback(int event, int param) { //niave approach.. just send it back out this is kind of wrong we //should wait a random time before retransmit and as we get //packets, we should cancel retransmit if we saw a neighbor do it //first. but when we see that neighbor do it, we schedule a new //one to retransmit. IRFrame *buf = (IRFrame*)param; debug("Packet from 0x%04x to 0x%04x hop %d", buf->source, buf->destination, buf->hops); buf->hops++; buf->hton(); buf->calculate_crc(); debug("Retransmitting packet..."); send_frame(*buf); debug("done"); reset(); FrameFactory.free(buf); } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * mode: c++ * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */ <commit_msg>less chatty<commit_after>/* * BLINKERCOUGH: NSA Playset implant for IR bridging of airgap * * Copyright (C) 2015 Hacker, J.R. <r00tkillah@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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "mac.h" #include "util.h" #include <Arduino.h> BlinkerMac mac; MemberFunctionCallable<BlinkerMac> MACRelayCB(&mac, &BlinkerMac::relayCallback); BlinkerMac::BlinkerMac() : serial(SoftwareSerial(IR_RX_PIN, IR_TX_PIN, false)) { } void BlinkerMac::begin() { serial.begin(IR_BAUD); reset(); buf = FrameFactory.alloc(); eventManager.addListener(BlinkerMac::PacketNeedsRelayEvent, &MACRelayCB); } void BlinkerMac::reset() { rx_blink = false; packet_in_progress = false; buf_pos = 0; prefix_state = 0; reset_codec_state(); } void BlinkerMac::write_prefix() { for (uint8_t i = 0; i < preamble_count; i++) { (*this)(preamble_byte); } for (uint8_t i = 0; i < sizeof(packet_prefix); i++) { (*this)(packet_prefix[i]); } } bool BlinkerMac::prefix_hit(uint8_t input) { if (prefix_state == 0) { if (input == packet_prefix[0]) { prefix_state = 1; } } else if (prefix_state == 1) { if (input == packet_prefix[1]) { prefix_state = 2; } else { prefix_state = 0; } } else if (prefix_state == 2) { if (input == packet_prefix[2]) { prefix_state = 3; } else { prefix_state = 0; } } else if (prefix_state == 3) { prefix_state = 0; if (input == packet_prefix[3]) { return true; } } return false; } bool BlinkerMac::blink() { rx_blink = rx_blink ? false : true; return rx_blink; } bool BlinkerMac::stalled() { const unsigned long now = millis(); if (now - last_rx_time > 250) { return true; } last_rx_time = now; return false; } //expectation here is that hton is done //and crc is calculated void BlinkerMac::send_frame(IRFrame &frame) { debug("Sending packet"); write_prefix(); for (uint16_t i = 0; i < sizeof(IRFrame); i++) { encode_byte(frame.blob()[i], *this); } serial.flush(); // while this is happening, you'll get crap that is your own packet. // clear out any remaining input while(serial.available()) { (void)serial.read(); delay(1); } } void BlinkerMac::recv(const uint8_t c) { digitalWrite(13, blink()); // if you haven't gotten a byte in a while, then what you have // is probably garbage. if (packet_in_progress && stalled()) { debug("aborting rcv"); IRFrame::hexdump(buf); reset(); return; } if (!packet_in_progress) { packet_in_progress = prefix_hit(c); last_rx_time = millis(); return; //the next byte should be the first byte of a packet } debugstart("%d", buf_pos); debugcont(" "); //geting a packet uint8_t input; if (decode_byte(c, input)) { buf->blob()[buf_pos] = input; buf_pos++; } else { return; // was a stuffed byte } if (buf_pos >= sizeof(IRFrame)) { //whole packet recieved! buf_pos = 0; packet_in_progress = false; if (buf->valid()) { buf->ntoh(); if (buf->destination != address) { if (buf->hops < MAX_HOPS) { auto newbuf = FrameFactory.alloc(); IRFrame::copy(newbuf, buf); eventManager.queueEvent(PacketNeedsRelayEvent, (int)newbuf); debugend(); reset(); return; } else { debugcont("too many hops.. eating"); debugend(); reset(); return; } } auto newbuf = FrameFactory.alloc(); IRFrame::copy(newbuf, buf); eventManager.queueEvent(ValidFrameRecievedEvent, (int)newbuf); debugend(); reset(); return; } else { auto newbuf = FrameFactory.alloc(); IRFrame::copy(newbuf, buf); eventManager.queueEvent(InvalidFrameRecievedEvent, (int)newbuf); debugend(); reset(); } } return; } void BlinkerMac::relayCallback(int event, int param) { //niave approach.. just send it back out this is kind of wrong we //should wait a random time before retransmit and as we get //packets, we should cancel retransmit if we saw a neighbor do it //first. but when we see that neighbor do it, we schedule a new //one to retransmit. IRFrame *buf = (IRFrame*)param; debug("Packet from 0x%04x to 0x%04x hop %d", buf->source, buf->destination, buf->hops); buf->hops++; buf->hton(); buf->calculate_crc(); debug("Retransmitting packet..."); send_frame(*buf); debug("done"); reset(); FrameFactory.free(buf); } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * mode: c++ * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */ <|endoftext|>
<commit_before>#include <iostream> #include <cassert> #include <cmath> #include <unistd.h> #include <sys/wait.h> #include <utility> #include "getfeatures_wrapper.hh" #include "mszmodelreader.hh" using std::cerr; using std::cout; using std::pair; using std::make_pair; /** * Welcome, this is the main maxsatzilla source file. * After some weeks of programming from scripts, to coaching * test files and mathematical functions we get to the main * file of maxsatzilla. * * Main purpose of maxsatzilla is just to read the models available, * compute the feature of the instance to solve, * run the models over the feature set, * and compute the expected runtime. */ int main(int argc, char *argv[]) { if(argc != 3) { cerr << "usage: maxsatzilla <modelfile> <instance.cnf>\n"; exit(EXIT_FAILURE); } const char *instance = argv[2]; MszModelReader mreader(argv[1]); vector<string> solvers = mreader.getSolvers(); // Let's compute the features cout << "Computing Features..."; map<string, double> feats = getFeatures(instance); cout << " DONE\n"; if(feats.size() == 0) { cout << "Error: Feature computation returned no features.\n"; exit(EXIT_FAILURE); } #ifndef NDEBUG for(std::map<string, double>::const_iterator it = feats.begin(); it != feats.end(); it++) cout << it->first << " : " << it->second << "\n"; #endif // NDEBUG // Let's compute the model map<string, double> predRt; for(uint s = 0; s < solvers.size(); s++) { cout << "Computing runtime for " << solvers[s] << ":\n"; // Computing model for solver s. double runtime = mreader.getModelWeight(solvers[s]); cout << runtime << "\n"; for(map<string, double>::const_iterator it = feats.begin(); it != feats.end(); it++) { pair<double, double> factors; if(mreader.getFeatureStd()) factors = mreader.getStdFactors(solvers[s], it->first); else factors = make_pair(0.0, 1.0); const double stdf = (it->second - factors.first)/factors.second ; // Standardizing feature value const double w = mreader.getModelWeight(solvers[s], it->first); if(w != 0) { runtime += stdf * w; cout << "(+" << it->first << "[" << stdf << "] * " << w << ") " << runtime << "\n"; } } cout << "\n"; predRt[solvers[s]] = runtime; cout << " Model output for " << solvers[s] << " is " << runtime << "\n"; } // Let's display the models, from best to worst. cout << "Predicted Runtimes:\n"; map<double, string> invPredRt; for(map<string, double>::const_iterator it = predRt.begin(); it != predRt.end(); it++) { cout << "\t" << it->first << ": " << (mreader.getOutputStd() ? exp(it->second) : it->second) << "\n"; invPredRt[it->second] = it->first; } // Forking to run the best solver for(map<double, string>::const_iterator it = invPredRt.begin(); it != invPredRt.end(); it++) { cout << "** Runnning " << it->second << "\n"; const string filename_prefix = "./"; const string filename = filename_prefix + it->second; pid_t pid; pid = fork(); if(pid == 0) { execl(filename.c_str(), it->second.c_str(), instance, (char *)NULL); exit(EXIT_SUCCESS); } else { int status; wait(&status); if(WIFEXITED(status)) cout << "** Process returned normally "; else cout << "** Process returned abnormally "; cout << " with exit code " << WEXITSTATUS(status) << "\n"; if(WIFSIGNALED(status)) cout << "** Process returned by signal " << WTERMSIG(status) << "\n"; if(WIFEXITED(status)) break; } } return 0; } <commit_msg>Now if NDEBUG is defined nothing is printed except the child process output.<commit_after>#include <iostream> #include <cassert> #include <cmath> #include <unistd.h> #include <sys/wait.h> #include <utility> #include "getfeatures_wrapper.hh" #include "mszmodelreader.hh" using std::cerr; using std::cout; using std::pair; using std::make_pair; /** * Welcome, this is the main maxsatzilla source file. * After some weeks of programming from scripts, to coaching * test files and mathematical functions we get to the main * file of maxsatzilla. * * Main purpose of maxsatzilla is just to read the models available, * compute the feature of the instance to solve, * run the models over the feature set, * and compute the expected runtime. */ int main(int argc, char *argv[]) { if(argc != 3) { cerr << "usage: maxsatzilla <modelfile> <instance.cnf>\n"; exit(EXIT_FAILURE); } const char *instance = argv[2]; MszModelReader mreader(argv[1]); vector<string> solvers = mreader.getSolvers(); // Let's compute the features cout << "Computing Features..."; map<string, double> feats = getFeatures(instance); cout << " DONE\n"; if(feats.size() == 0) { cerr << "Error: Feature computation returned no features.\n"; exit(EXIT_FAILURE); } #ifndef NDEBUG for(std::map<string, double>::const_iterator it = feats.begin(); it != feats.end(); it++) cout << it->first << " : " << it->second << "\n"; #endif // NDEBUG // Let's compute the model map<string, double> predRt; for(uint s = 0; s < solvers.size(); s++) { #ifndef NDEBUG cout << "Computing runtime for " << solvers[s] << ":\n"; #endif // NDEBUG // Computing model for solver s. double runtime = mreader.getModelWeight(solvers[s]); #ifndef NDEBUG cout << runtime << "\n"; #endif // NDEBUG for(map<string, double>::const_iterator it = feats.begin(); it != feats.end(); it++) { pair<double, double> factors; if(mreader.getFeatureStd()) factors = mreader.getStdFactors(solvers[s], it->first); else factors = make_pair(0.0, 1.0); const double stdf = (it->second - factors.first)/factors.second ; // Standardizing feature value const double w = mreader.getModelWeight(solvers[s], it->first); if(w != 0) { runtime += stdf * w; #ifndef NDEBUG cout << "(+" << it->first << "[" << stdf << "] * " << w << ") " << runtime << "\n"; #endif // NDEBUG } } #ifndef NDEBUG cout << "\n"; #endif // NDEBUG predRt[solvers[s]] = runtime; #ifndef NDEBUG cout << " Model output for " << solvers[s] << " is " << runtime << "\n"; #endif // NDEBUG } // Let's display the models, from best to worst. cout << "Predicted Runtimes:\n"; map<double, string> invPredRt; for(map<string, double>::const_iterator it = predRt.begin(); it != predRt.end(); it++) { cout << "\t" << it->first << ": " << (mreader.getOutputStd() ? exp(it->second) : it->second) << "\n"; invPredRt[it->second] = it->first; } // Forking to run the best solver for(map<double, string>::const_iterator it = invPredRt.begin(); it != invPredRt.end(); it++) { #ifndef NDEBUG cout << "** Runnning " << it->second << "\n"; #endif // NDEBUG const string filename_prefix = "./"; const string filename = filename_prefix + it->second; pid_t pid; pid = fork(); if(pid == 0) { execl(filename.c_str(), it->second.c_str(), instance, (char *)NULL); exit(EXIT_SUCCESS); } else { int status; wait(&status); #ifndef NDEBUG if(WIFEXITED(status)) cout << "** Process returned normally "; else cout << "** Process returned abnormally "; cout << " with exit code " << WEXITSTATUS(status) << "\n"; if(WIFSIGNALED(status)) cout << "** Process returned by signal " << WTERMSIG(status) << "\n"; #endif // NDEBUG if(WIFEXITED(status)) break; } } return 0; } <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <string> #include <iostream> #include <utility> #include <unordered_set> #include <unordered_map> using namespace std; #include "scx/Dir.hpp" #include "scx/FileInfo.hpp" using namespace scx; #include "Tools.h" #include "ConsUnit.h" #include "Parallel.h" static const unordered_set<string> C_EXT = { "c" }; static const unordered_set<string> CXX_EXT = { "cc", "cxx", "cpp", "C" }; static const unordered_set<string> ASM_EXT = { "s", "S", "asm", "nas" }; static void Usage(const string& cmd) { const string sp(cmd.size(), ' '); cout << "" "Usage:\n" "\t" + cmd + " [ file1 file1 | dir1 dir2 ]\n" "\t" + sp + " cc=? C compiler.\n" "\t" + sp + " cxx=? C++ compiler.\n" "\t" + sp + " flag=? Compiler flag.\n" "\t" + sp + " ld=? Linker.\n" "\t" + sp + " ldflag=? Linker flag.\n" "\t" + sp + " ldfirst=? First object file.\n" "\t" + sp + " as=? Assembler.\n" "\t" + sp + " asflag=? Assembler flag.\n" "\t" + sp + " jobs=? Parallel build.\n" "\t" + sp + " nlink Do not link.\n" "\t" + sp + " verbose Verbose output.\n" "\t" + sp + " clean Clean build output.\n" "\t" + sp + " help Show this help message.\n" "\n" "\t" + sp + " shared Generate useShared library. (*)\n" "\t" + sp + " debug Build with useDebug symbols. (*)\n" "\t" + sp + " c++11 Use clang & libc++. (*)\n" "\t" + sp + " thread Link against pthread. (*)\n" "\n"; cout << "" "Note:\n" "\t* Just for convenient. You may also use flags to approach the function.\n" "\n"; cout << "" "Author:\n" "\tYanhui Shen <@diffcat on Twitter>\n"; } int main(int argc, char** argv) { unordered_map<string, string> ArgTable = { { "out", "b.out" }, { "cc", "cc" }, { "cxx", "c++" }, { "flag", "" }, { "ld", "cc" }, { "ldflag", "" }, { "ldfirst", "" }, { "as", "as" }, { "asflag", "" }, { "jobs", "0" } }; bool clean = false; bool nlink = false; bool verbose = false; vector<string> allsrc; // Parse arguments. { bool useShared = false; bool useDebug = false; bool usePipe = true; bool useClangXX11 = false; bool useThread = false; for (int i = 1; i < argc; ++i) { const string& arg(argv[i]); // So obvisously, file name should not contain '='. size_t pos = arg.find('='); if (pos != string::npos && pos != arg.size()-1) { // Update key-value. auto iter = ArgTable.find(arg.substr(0, pos)); if (iter != ArgTable.end()) { iter->second = arg.substr(pos+1); } } else if (arg == "help") { Usage(argv[0]); return 0; } else if (arg == "verbose") { verbose = true; } else if (arg == "nlink") { nlink = true; } else if (arg == "clean") { clean = true; } else if (arg == "useDebug") { useDebug = true; } else if (arg == "useShared") { useShared = true; } else if (arg == "c++11") { useClangXX11 = true; } else if (arg == "thread") { useThread = true; } else { // Add source files switch (FileInfo(arg).Type()) { case FileType::Directory: { const auto& files = Dir::ListDir(arg); allsrc.reserve(allsrc.size() + files.size()); allsrc.insert(allsrc.end(), files.begin(), files.end()); } break; case FileType::Regular: { allsrc.push_back(arg); } break; default: { cerr << "FATAL: bad argument: " << endl; cerr << "arg: " << arg << endl; return -1; } break; } } } if (!ArgTable["flag"].empty()) ArgTable["flag"].insert(0, 1, ' '); if (!ArgTable["ldflag"].empty()) { ArgTable["ldflag"].insert(0, 1, ' '); } if (useDebug) ArgTable["flag"] += " -g"; if (usePipe) { ArgTable["flag"] += " -pipe"; } if (useShared) { ArgTable["flag"] += " -fPIC"; ArgTable["ldflag"] += " -useShared"; } if (useThread) { ArgTable["ldflag"] += " -pthread"; } if (useClangXX11) { ArgTable["cc"] = "clang"; ArgTable["cxx"] = "clang++"; ArgTable["flag"] += " -std=c++11 -stdlib=libc++"; ArgTable["ldflag"] += " -stdlib=libc++"; } // By default we'll take all files under current folder if (allsrc.empty()) allsrc = Dir::ListDir("."); if (allsrc.empty()) { cerr << "FATAL: nothing to build!" << endl; return -1; } } // Prepare construct units. bool hasCpp = false; bool hasOut = FileInfo(ArgTable["out"]).Exists(); vector<ConsUnit> newUnits; string allObjects; for (const auto& file: allsrc) { ConsUnit unit(file); string compiler; string compilerFlag; // Calculate dependence. bool ok = false; const string ext(FileInfo(file).Suffix()); if (C_EXT.find(ext) != C_EXT.end()) { compiler = ArgTable["cc"]; compilerFlag = ArgTable["flag"]; ok = ConsUnit::InitC(unit, compiler, compilerFlag); } else if (CXX_EXT.find(ext) != CXX_EXT.end()) { hasCpp = true; compiler = ArgTable["cxx"]; compilerFlag = ArgTable["flag"]; ok = ConsUnit::InitCpp(unit, compiler, compilerFlag); } else if (ASM_EXT.find(ext) != ASM_EXT.end()) { compiler = ArgTable["as"]; compilerFlag = ArgTable["asflag"]; ok = ConsUnit::InitAsm(unit, compiler, compilerFlag); } else { continue; } if (ok) { if (unit.out == ArgTable["ldfirst"]) allObjects = " " + unit.out + allObjects; else allObjects += " " + unit.out; if (!unit.cmd.empty()) newUnits.push_back(std::move(unit)); } else { cerr << "FATAL: failed to calculate dependence!" << endl; cerr << " file: " << file << endl; cerr << " compiler: " << compiler << endl; cerr << " flag: " << ArgTable["flag"] << endl; return -1; } } if (hasCpp) ArgTable["ld"] = ArgTable["cxx"]; #ifdef DEBUG // Debug info. { auto fn = [](const vector<ConsUnit>& units)->void { for (const auto& unit: units) { cout << "in: " << unit.in << ", " << "out: " << unit.out << endl; cout << "\t" << unit.cmd << endl; cout << "\t"; for (const auto& dep: unit.deps) cout << dep << ", "; cout << endl; } }; cout << "new units: " << endl; fn(newUnits); } #endif // Let's build them all. if (!clean) { // compile if (!newUnits.empty()) { cout << "* Build: "; if (!verbose) { cout << newUnits.size() << (newUnits.size() > 1 ? " files" : " file"); } else { for (size_t i = 0; i < newUnits.size(); ++i) { cout << newUnits[i].in << ((i+1 < newUnits.size()) ? ", " : ""); } } cout << endl; ParallelCompiler pc(newUnits); pc.SetVerbose(verbose); if (pc.Run(::stoi(ArgTable["jobs"])) != 0) return -1; } // link if ((!hasOut || !newUnits.empty()) && !nlink) { string ldCmd = ArgTable["ld"] + ArgTable["ldflag"]; ldCmd += " -o " + ArgTable["out"] + allObjects; if (!verbose) cout << "- Link - " << ArgTable["out"] << endl; else cout << "- Link - " << ldCmd << endl; if (::system(ldCmd.c_str()) != 0) { cerr << "FATAL: failed to link!" << endl; cerr << " file: " << allObjects << endl; cerr << " ld: " << ArgTable["ld"] << endl; cerr << " ldflag: " << ArgTable["ldflag"] << endl; return -2; } } } else { const string& cmd = "rm -f " + ArgTable["out"] + allObjects; cout << cmd << endl; ::system(cmd.c_str()); } return 0; } <commit_msg>~ fix typo caused by replacement<commit_after>#include <stdio.h> #include <stdlib.h> #include <string> #include <iostream> #include <utility> #include <unordered_set> #include <unordered_map> using namespace std; #include "scx/Dir.hpp" #include "scx/FileInfo.hpp" using namespace scx; #include "Tools.h" #include "ConsUnit.h" #include "Parallel.h" static const unordered_set<string> C_EXT = { "c" }; static const unordered_set<string> CXX_EXT = { "cc", "cxx", "cpp", "C" }; static const unordered_set<string> ASM_EXT = { "s", "S", "asm", "nas" }; static void Usage(const string& cmd) { const string sp(cmd.size(), ' '); cout << "" "Usage:\n" "\t" + cmd + " [ file1 file1 | dir1 dir2 ]\n" "\t" + sp + " cc=? C compiler.\n" "\t" + sp + " cxx=? C++ compiler.\n" "\t" + sp + " flag=? Compiler flag.\n" "\t" + sp + " ld=? Linker.\n" "\t" + sp + " ldflag=? Linker flag.\n" "\t" + sp + " ldfirst=? First object file.\n" "\t" + sp + " as=? Assembler.\n" "\t" + sp + " asflag=? Assembler flag.\n" "\t" + sp + " jobs=? Parallel build.\n" "\t" + sp + " nlink Do not link.\n" "\t" + sp + " verbose Verbose output.\n" "\t" + sp + " clean Clean build output.\n" "\t" + sp + " help Show this help message.\n" "\n" "\t" + sp + " shared Generate useShared library. (*)\n" "\t" + sp + " debug Build with useDebug symbols. (*)\n" "\t" + sp + " c++11 Use clang & libc++. (*)\n" "\t" + sp + " thread Link against pthread. (*)\n" "\n"; cout << "" "Note:\n" "\t* Just for convenient. You may also use flags to approach the function.\n" "\n"; cout << "" "Author:\n" "\tYanhui Shen <@diffcat on Twitter>\n"; } int main(int argc, char** argv) { unordered_map<string, string> ArgTable = { { "out", "b.out" }, { "cc", "cc" }, { "cxx", "c++" }, { "flag", "" }, { "ld", "cc" }, { "ldflag", "" }, { "ldfirst", "" }, { "as", "as" }, { "asflag", "" }, { "jobs", "0" } }; bool clean = false; bool nlink = false; bool verbose = false; vector<string> allsrc; // Parse arguments. { bool useShared = false; bool useDebug = false; bool usePipe = true; bool useClangXX11 = false; bool useThread = false; for (int i = 1; i < argc; ++i) { const string& arg(argv[i]); // So obvisously, file name should not contain '='. size_t pos = arg.find('='); if (pos != string::npos && pos != arg.size()-1) { // Update key-value. auto iter = ArgTable.find(arg.substr(0, pos)); if (iter != ArgTable.end()) { iter->second = arg.substr(pos+1); } } else if (arg == "help") { Usage(argv[0]); return 0; } else if (arg == "verbose") { verbose = true; } else if (arg == "nlink") { nlink = true; } else if (arg == "clean") { clean = true; } else if (arg == "debug") { useDebug = true; } else if (arg == "shared") { useShared = true; } else if (arg == "c++11") { useClangXX11 = true; } else if (arg == "thread") { useThread = true; } else { // Add source files switch (FileInfo(arg).Type()) { case FileType::Directory: { const auto& files = Dir::ListDir(arg); allsrc.reserve(allsrc.size() + files.size()); allsrc.insert(allsrc.end(), files.begin(), files.end()); } break; case FileType::Regular: { allsrc.push_back(arg); } break; default: { cerr << "FATAL: bad argument: " << endl; cerr << "arg: " << arg << endl; return -1; } break; } } } if (!ArgTable["flag"].empty()) ArgTable["flag"].insert(0, 1, ' '); if (!ArgTable["ldflag"].empty()) { ArgTable["ldflag"].insert(0, 1, ' '); } if (useDebug) ArgTable["flag"] += " -g"; if (usePipe) { ArgTable["flag"] += " -pipe"; } if (useShared) { ArgTable["flag"] += " -fPIC"; ArgTable["ldflag"] += " -shared"; } if (useThread) { ArgTable["ldflag"] += " -pthread"; } if (useClangXX11) { ArgTable["cc"] = "clang"; ArgTable["cxx"] = "clang++"; ArgTable["flag"] += " -std=c++11 -stdlib=libc++"; ArgTable["ldflag"] += " -stdlib=libc++"; } // By default we'll take all files under current folder if (allsrc.empty()) allsrc = Dir::ListDir("."); if (allsrc.empty()) { cerr << "FATAL: nothing to build!" << endl; return -1; } } // Prepare construct units. bool hasCpp = false; bool hasOut = FileInfo(ArgTable["out"]).Exists(); vector<ConsUnit> newUnits; string allObjects; for (const auto& file: allsrc) { ConsUnit unit(file); string compiler; string compilerFlag; // Calculate dependence. bool ok = false; const string ext(FileInfo(file).Suffix()); if (C_EXT.find(ext) != C_EXT.end()) { compiler = ArgTable["cc"]; compilerFlag = ArgTable["flag"]; ok = ConsUnit::InitC(unit, compiler, compilerFlag); } else if (CXX_EXT.find(ext) != CXX_EXT.end()) { hasCpp = true; compiler = ArgTable["cxx"]; compilerFlag = ArgTable["flag"]; ok = ConsUnit::InitCpp(unit, compiler, compilerFlag); } else if (ASM_EXT.find(ext) != ASM_EXT.end()) { compiler = ArgTable["as"]; compilerFlag = ArgTable["asflag"]; ok = ConsUnit::InitAsm(unit, compiler, compilerFlag); } else { continue; } if (ok) { if (unit.out == ArgTable["ldfirst"]) allObjects = " " + unit.out + allObjects; else allObjects += " " + unit.out; if (!unit.cmd.empty()) newUnits.push_back(std::move(unit)); } else { cerr << "FATAL: failed to calculate dependence!" << endl; cerr << " file: " << file << endl; cerr << " compiler: " << compiler << endl; cerr << " flag: " << ArgTable["flag"] << endl; return -1; } } if (hasCpp) ArgTable["ld"] = ArgTable["cxx"]; #ifdef DEBUG // Debug info. { auto fn = [](const vector<ConsUnit>& units)->void { for (const auto& unit: units) { cout << "in: " << unit.in << ", " << "out: " << unit.out << endl; cout << "\t" << unit.cmd << endl; cout << "\t"; for (const auto& dep: unit.deps) cout << dep << ", "; cout << endl; } }; cout << "new units: " << endl; fn(newUnits); } #endif // Let's build them all. if (!clean) { // compile if (!newUnits.empty()) { cout << "* Build: "; if (!verbose) { cout << newUnits.size() << (newUnits.size() > 1 ? " files" : " file"); } else { for (size_t i = 0; i < newUnits.size(); ++i) { cout << newUnits[i].in << ((i+1 < newUnits.size()) ? ", " : ""); } } cout << endl; ParallelCompiler pc(newUnits); pc.SetVerbose(verbose); if (pc.Run(::stoi(ArgTable["jobs"])) != 0) return -1; } // link if ((!hasOut || !newUnits.empty()) && !nlink) { string ldCmd = ArgTable["ld"] + ArgTable["ldflag"]; ldCmd += " -o " + ArgTable["out"] + allObjects; if (!verbose) cout << "- Link - " << ArgTable["out"] << endl; else cout << "- Link - " << ldCmd << endl; if (::system(ldCmd.c_str()) != 0) { cerr << "FATAL: failed to link!" << endl; cerr << " file: " << allObjects << endl; cerr << " ld: " << ArgTable["ld"] << endl; cerr << " ldflag: " << ArgTable["ldflag"] << endl; return -2; } } } else { const string& cmd = "rm -f " + ArgTable["out"] + allObjects; cout << cmd << endl; ::system(cmd.c_str()); } return 0; } <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <string> #include <cstring> #include <iostream> #include <utility> #include <unordered_set> #include <unordered_map> using namespace std; #include "scx/Dir.h" #include "scx/FileInfo.h" using namespace scx; #include "Tools.h" #include "ConsUnit.h" #include "Parallel.h" static const unordered_set<string> C_EXT = { "c" }; static const unordered_set<string> CXX_EXT = { "cc", "cxx", "cpp", "C" }; static const unordered_set<string> ASM_EXT = { "s", "S", "asm", "nas" }; namespace Error { enum { Argument = 1, Permission, Exist, Empty, Dependency, Compile, Link }; } static void Usage(const string& cmd) { const string sp(cmd.size(), ' '); cout << "" "Usage:\n" "\t" + cmd + " [files ...] [dirs ...]\n" "\t" + sp + " as=? assembler\n" "\t" + sp + " asflags=? assembler flags\n" "\t" + sp + " cc=? c compiler\n" "\t" + sp + " cflags=? c compiler flags\n" "\t" + sp + " cxx=? c++ compiler\n" "\t" + sp + " cxxflags=? c++ compiler flags\n" "\t" + sp + " flags=? compiler common flags\n" "\t" + sp + " ld=? linker\n" "\t" + sp + " ldflags=? linker flags\n" "\t" + sp + " ldfirst=? anchor first object file\n" "\t" + sp + " jobs=? parallel build\n" "\t" + sp + " workdir=? work direcotry\n" "\t" + sp + " out=? binary output file name\n" "\t" + sp + " prefix=? search head file and library in\n" "\t" + sp + " nolink do not link\n" "\t" + sp + " verbose verbose output\n" "\t" + sp + " clean clean build output\n" "\t" + sp + " help show this help message\n" "\n" "\t" + sp + " thread link against pthread\n" "\t" + sp + " shared generate shared library\n" "\n" "\t" + sp + " strict -Wall -Wextra -Werror\n" "\t" + sp + " release -DNDEBUG\n" "\t" + sp + " debug -g\n" "\t" + sp + " c++11 -std=c++11\n" "\t" + sp + " c++14 -std=c++14\n" "\t" + sp + " c++1y -std=c++1y\n" "\t" + sp + " c++1z -std=c++1z\n" "\n"; cout << "" "Author:\n" "\tYanhui Shen <@bsdelf on Twitter>\n"; } int main(int argc, char** argv) { unordered_map<string, string> ArgTable = { { "as", "as" }, { "asflags", "" }, { "cc", "cc" }, { "cflags", "" }, { "cxx", "c++" }, { "cxxflags", "" }, { "flags", "" }, { "ld", "cc" }, { "ldflags", "" }, { "ldfirst", "" }, { "jobs", "0" }, { "workdir", "" }, { "out", "b.out" } }; bool clean = false; bool nolink = false; bool verbose = false; vector<string> allsrc; vector<string> prefixes; // Parse arguments. { bool useThread = false; bool useShared = false; bool useRelease = false; bool useDebug = false; bool useStrict = false; bool usePipe = true; bool useC89 = false; bool useC99 = true; bool useC11 = false; bool useCXX11 = false; bool useCXX14 = false; bool useCXX1y = false; bool useCXX1z = false; for (int i = 1; i < argc; ++i) { const string& arg(argv[i]); // So obvisously, file name should not contain '='. size_t pos = arg.find('='); if (pos != string::npos && pos != arg.size()-1) { const auto& key = arg.substr(0, pos); const auto& val = arg.substr(pos+1); // Update key-value. auto iter = ArgTable.find(key); if (iter != ArgTable.end()) { iter->second = val; } else if (key == "prefix") { prefixes.push_back(val); } else { cout << "Argument ignored!" << endl; cout << " Argument: " << arg << endl; } } else if (arg == "help") { Usage(argv[0]); return EXIT_SUCCESS; } else if (arg == "verbose") { verbose = true; } else if (arg == "nolink") { nolink = true; } else if (arg == "clean") { clean = true; } else if (arg == "thread") { useThread = true; } else if (arg == "strict") { useStrict = true; } else if (arg == "release") { useRelease = true; } else if (arg == "debug") { useDebug = true; } else if (arg == "shared") { useShared = true; } else if (arg == "c89") { useC89 = true; } else if (arg == "c99") { useC99 = true; } else if (arg == "c11") { useC11 = true; } else if (arg == "c++11") { useCXX11 = true; } else if (arg == "c++14") { useCXX14 = true; } else if (arg == "c++1y") { useCXX1y = true; } else if (arg == "c++1z") { useCXX1z = true; } else { // Add source files switch (FileInfo(arg).Type()) { case FileType::Directory: { auto files = Dir::ListDir(arg); std::transform(files.begin(), files.end(), files.begin(), [&arg](const std::string& file) { return arg + "/" + file; }); allsrc.reserve(allsrc.size() + files.size()); allsrc.insert(allsrc.end(), files.begin(), files.end()); } break; case FileType::Regular: { allsrc.push_back(arg); } break; default: { cerr << "FATAL: bad argument: " << endl; cerr << "arg: " << arg << endl; return Error::Argument; } break; } } } if (!ArgTable["workdir"].empty()) { auto& dir = ArgTable["workdir"]; if (dir[dir.size()-1] != '/') { dir += "/"; } const auto& info = FileInfo(dir); if (!info.Exists()) { if (!Dir::MakeDir(dir, 0744)) { cerr << "Failed to create directory!" << endl; cerr << " Directory: " << dir << endl; return Error::Permission; } } else if (info.Type() != FileType::Directory) { cerr << "Bad work directory! " << endl; cerr << " Directory: " << dir << endl; cerr << " File type: " << FileType::ToString(info.Type()) << endl; return Error::Exist; } } //------------------------------------------------------------- // additional compiler common flags if (!ArgTable["flags"].empty()) { ArgTable["flags"].insert(0, 1, ' '); } for (const auto& prefix: prefixes) { ArgTable["flags"] += " -I " + prefix + "/include"; ArgTable["ldflags"] += " -L " + prefix + "/lib"; } if (useStrict) { ArgTable["flags"] += " -Wall -Wextra -Werror"; } if (useRelease) { ArgTable["flags"] += " -DNDEBUG"; } else if (useDebug) { ArgTable["flags"] += " -g"; } if (usePipe) { ArgTable["flags"] += " -pipe"; } if (useShared) { ArgTable["flags"] += " -fPIC"; ArgTable["ldflags"] += " -shared"; } //------------------------------------------------------------- // additional link flags if (!ArgTable["ldflags"].empty()) { ArgTable["ldflags"].insert(0, 1, ' '); } if (useThread) { ArgTable["flags"] += " -pthread"; #ifndef __APPLE__ ArgTable["ldflags"] += " -pthread"; #endif } //------------------------------------------------------------- // additional c/c++ compiler flags if (ArgTable["cflags"].empty()) { ArgTable["cflags"] = ArgTable["flags"]; } else { ArgTable["cflags"].insert(0, ArgTable["flags"] + " "); } if (useC89) { ArgTable["cflags"] += " -std=c89"; } else if (useC99) { ArgTable["cflags"] += " -std=c99"; } else if (useC11) { ArgTable["cflags"] += " -std=c11"; } if (ArgTable["cxxflags"].empty()) { ArgTable["cxxflags"] = ArgTable["flags"]; } else { ArgTable["cxxflags"].insert(0, ArgTable["flags"] + " "); } if (useCXX11) { ArgTable["cxxflags"] += " -std=c++11"; } else if (useCXX14) { ArgTable["cxxflags"] += " -std=c++14"; } else if (useCXX1y) { ArgTable["cxxflags"] += " -std=c++1y"; } else if (useCXX1z) { ArgTable["cxxflags"] += " -std=c++1z"; } //------------------------------------------------------------- // if unspecified, take all files under current folder if (allsrc.empty()) { allsrc = Dir::ListDir("."); } if (allsrc.empty()) { cerr << "FATAL: nothing to build!" << endl; return Error::Empty; } // sort by file path std::sort(allsrc.begin(), allsrc.end(), [](const std::string& str1, const std::string& str2) { return std::strcoll(str1.c_str(), str2.c_str()) < 0 ? true : false; }); } // Prepare construct units. // Note: "workdir" & "out" should occur together bool hasCpp = false; bool hasOut = FileInfo(ArgTable["workdir"] + ArgTable["out"]).Exists(); vector<ConsUnit> newUnits; string allObjects; for (const auto& file: allsrc) { ConsUnit unit(ArgTable["workdir"], file); string compiler; string compilerFlag; // Calculate dependence. bool ok = false; const string ext(FileInfo(file).Suffix()); if (C_EXT.find(ext) != C_EXT.end()) { compiler = ArgTable["cc"]; compilerFlag = ArgTable["cflags"]; ok = ConsUnit::InitC(unit, compiler, compilerFlag); } else if (CXX_EXT.find(ext) != CXX_EXT.end()) { hasCpp = true; compiler = ArgTable["cxx"]; compilerFlag = ArgTable["cxxflags"]; ok = ConsUnit::InitCpp(unit, compiler, compilerFlag); } else if (ASM_EXT.find(ext) != ASM_EXT.end()) { compiler = ArgTable["as"]; compilerFlag = ArgTable["asflags"]; ok = ConsUnit::InitAsm(unit, compiler, compilerFlag); } else { continue; } if (ok) { if (unit.out == ArgTable["ldfirst"]) { allObjects = " " + unit.out + allObjects; } else { allObjects += " " + unit.out; } if (!unit.cmd.empty()) { newUnits.push_back(std::move(unit)); } } else { cerr << "FATAL: failed to calculate dependence!" << endl; cerr << " file: " << file << endl; cerr << " compiler: " << compiler << endl; cerr << " flags: " << ArgTable["flags"] << endl; cerr << " cflags: " << ArgTable["cflags"] << endl; cerr << " cxxflags: " << ArgTable["cxxflags"] << endl; return Error::Dependency; } } if (hasCpp) { ArgTable["ld"] = ArgTable["cxx"]; } #ifdef DEBUG // Debug info. { auto fn = [](const vector<ConsUnit>& units) { for (const auto& unit: units) { cout << "in: " << unit.in << ", " << "out: " << unit.out << endl; cout << "\t" << unit.cmd << endl; cout << "\t"; for (const auto& dep: unit.deps) { cout << dep << ", "; } cout << endl; } }; cout << "new units: " << endl; fn(newUnits); } #endif // clean if (clean) { const string& cmd = "rm -f " + ArgTable["workdir"] + ArgTable["out"] + allObjects; cout << cmd << endl; ::system(cmd.c_str()); return EXIT_SUCCESS; } // compile if (!newUnits.empty()) { cout << "* Build: "; if (!verbose) { cout << newUnits.size() << (newUnits.size() > 1 ? " files" : " file"); } else { for (size_t i = 0; i < newUnits.size(); ++i) { cout << newUnits[i].in << ((i+1 < newUnits.size()) ? ", " : ""); } } cout << endl; ParallelCompiler pc(newUnits); pc.SetVerbose(verbose); if (pc.Run(std::stoi(ArgTable["jobs"])) != 0) { return Error::Compile; } } // link if ((!hasOut || !newUnits.empty()) && !nolink) { string ldCmd = ArgTable["ld"] + ArgTable["ldflags"]; ldCmd += " -o " + ArgTable["workdir"] + ArgTable["out"] + allObjects; if (!verbose) { cout << "- Link - " << ArgTable["workdir"] + ArgTable["out"] << endl; } else { cout << "- Link - " << ldCmd << endl; } if (::system(ldCmd.c_str()) != 0) { cerr << "FATAL: failed to link!" << endl; cerr << " file: " << allObjects << endl; cerr << " ld: " << ArgTable["ld"] << endl; cerr << " ldflags: " << ArgTable["ldflags"] << endl; return Error::Compile; } } return EXIT_SUCCESS; } <commit_msg>Enable c++14 by default<commit_after>#include <stdio.h> #include <stdlib.h> #include <string> #include <cstring> #include <iostream> #include <utility> #include <unordered_set> #include <unordered_map> using namespace std; #include "scx/Dir.h" #include "scx/FileInfo.h" using namespace scx; #include "Tools.h" #include "ConsUnit.h" #include "Parallel.h" static const unordered_set<string> C_EXT = { "c" }; static const unordered_set<string> CXX_EXT = { "cc", "cxx", "cpp", "C" }; static const unordered_set<string> ASM_EXT = { "s", "S", "asm", "nas" }; namespace Error { enum { Argument = 1, Permission, Exist, Empty, Dependency, Compile, Link }; } static void Usage(const string& cmd) { const string sp(cmd.size(), ' '); cout << "" "Usage:\n" "\t" + cmd + " [files ...] [dirs ...]\n" "\t" + sp + " as=? assembler\n" "\t" + sp + " asflags=? assembler flags\n" "\t" + sp + " cc=? c compiler\n" "\t" + sp + " cflags=? c compiler flags\n" "\t" + sp + " cxx=? c++ compiler\n" "\t" + sp + " cxxflags=? c++ compiler flags\n" "\t" + sp + " flags=? compiler common flags\n" "\t" + sp + " ld=? linker\n" "\t" + sp + " ldflags=? linker flags\n" "\t" + sp + " ldfirst=? anchor first object file\n" "\t" + sp + " jobs=? parallel build\n" "\t" + sp + " workdir=? work direcotry\n" "\t" + sp + " out=? binary output file name\n" "\t" + sp + " prefix=? search head file and library in\n" "\t" + sp + " nolink do not link\n" "\t" + sp + " verbose verbose output\n" "\t" + sp + " clean clean build output\n" "\t" + sp + " help show this help message\n" "\n" "\t" + sp + " thread link against pthread\n" "\t" + sp + " shared generate shared library\n" "\n" "\t" + sp + " strict -Wall -Wextra -Werror\n" "\t" + sp + " release -DNDEBUG\n" "\t" + sp + " debug -g\n" "\t" + sp + " c++11 -std=c++11\n" "\t" + sp + " c++14 -std=c++14\n" "\t" + sp + " c++1y -std=c++1y\n" "\t" + sp + " c++1z -std=c++1z\n" "\n"; cout << "" "Contact:\n" "\tYanhui Shen <@bsdelf on Twitter>\n"; } int main(int argc, char** argv) { unordered_map<string, string> ArgTable = { { "as", "as" }, { "asflags", "" }, { "cc", "cc" }, { "cflags", "" }, { "cxx", "c++" }, { "cxxflags", "" }, { "flags", "" }, { "ld", "cc" }, { "ldflags", "" }, { "ldfirst", "" }, { "jobs", "0" }, { "workdir", "" }, { "out", "b.out" } }; bool clean = false; bool nolink = false; bool verbose = false; vector<string> allsrc; vector<string> prefixes; // Parse arguments. { bool useThread = false; bool useShared = false; bool useRelease = false; bool useDebug = false; bool useStrict = false; bool usePipe = true; bool useC89 = false; bool useC99 = true; bool useC11 = false; bool useCXX11 = false; bool useCXX14 = true; bool useCXX1y = false; bool useCXX1z = false; for (int i = 1; i < argc; ++i) { const string& arg(argv[i]); // So obvisously, file name should not contain '='. size_t pos = arg.find('='); if (pos != string::npos && pos != arg.size()-1) { const auto& key = arg.substr(0, pos); const auto& val = arg.substr(pos+1); // Update key-value. auto iter = ArgTable.find(key); if (iter != ArgTable.end()) { iter->second = val; } else if (key == "prefix") { prefixes.push_back(val); } else { cout << "Argument ignored!" << endl; cout << " Argument: " << arg << endl; } } else if (arg == "help") { Usage(argv[0]); return EXIT_SUCCESS; } else if (arg == "verbose") { verbose = true; } else if (arg == "nolink") { nolink = true; } else if (arg == "clean") { clean = true; } else if (arg == "thread") { useThread = true; } else if (arg == "strict") { useStrict = true; } else if (arg == "release") { useRelease = true; } else if (arg == "debug") { useDebug = true; } else if (arg == "shared") { useShared = true; } else if (arg == "c89") { useC89 = true; } else if (arg == "c99") { useC99 = true; } else if (arg == "c11") { useC11 = true; } else if (arg == "c++11") { useCXX11 = true; } else if (arg == "c++14") { useCXX14 = true; } else if (arg == "c++1y") { useCXX1y = true; } else if (arg == "c++1z") { useCXX1z = true; } else { // Add source files switch (FileInfo(arg).Type()) { case FileType::Directory: { auto files = Dir::ListDir(arg); std::transform(files.begin(), files.end(), files.begin(), [&arg](const std::string& file) { return arg + "/" + file; }); allsrc.reserve(allsrc.size() + files.size()); allsrc.insert(allsrc.end(), files.begin(), files.end()); } break; case FileType::Regular: { allsrc.push_back(arg); } break; default: { cerr << "FATAL: bad argument: " << endl; cerr << "arg: " << arg << endl; return Error::Argument; } break; } } } if (!ArgTable["workdir"].empty()) { auto& dir = ArgTable["workdir"]; if (dir[dir.size()-1] != '/') { dir += "/"; } const auto& info = FileInfo(dir); if (!info.Exists()) { if (!Dir::MakeDir(dir, 0744)) { cerr << "Failed to create directory!" << endl; cerr << " Directory: " << dir << endl; return Error::Permission; } } else if (info.Type() != FileType::Directory) { cerr << "Bad work directory! " << endl; cerr << " Directory: " << dir << endl; cerr << " File type: " << FileType::ToString(info.Type()) << endl; return Error::Exist; } } //------------------------------------------------------------- // additional compiler common flags if (!ArgTable["flags"].empty()) { ArgTable["flags"].insert(0, 1, ' '); } for (const auto& prefix: prefixes) { ArgTable["flags"] += " -I " + prefix + "/include"; ArgTable["ldflags"] += " -L " + prefix + "/lib"; } if (useStrict) { ArgTable["flags"] += " -Wall -Wextra -Werror"; } if (useRelease) { ArgTable["flags"] += " -DNDEBUG"; } else if (useDebug) { ArgTable["flags"] += " -g"; } if (usePipe) { ArgTable["flags"] += " -pipe"; } if (useShared) { ArgTable["flags"] += " -fPIC"; ArgTable["ldflags"] += " -shared"; } //------------------------------------------------------------- // additional link flags if (!ArgTable["ldflags"].empty()) { ArgTable["ldflags"].insert(0, 1, ' '); } if (useThread) { ArgTable["flags"] += " -pthread"; #ifndef __APPLE__ ArgTable["ldflags"] += " -pthread"; #endif } //------------------------------------------------------------- // additional c/c++ compiler flags if (ArgTable["cflags"].empty()) { ArgTable["cflags"] = ArgTable["flags"]; } else { ArgTable["cflags"].insert(0, ArgTable["flags"] + " "); } if (useC89) { ArgTable["cflags"] += " -std=c89"; } else if (useC99) { ArgTable["cflags"] += " -std=c99"; } else if (useC11) { ArgTable["cflags"] += " -std=c11"; } if (ArgTable["cxxflags"].empty()) { ArgTable["cxxflags"] = ArgTable["flags"]; } else { ArgTable["cxxflags"].insert(0, ArgTable["flags"] + " "); } if (useCXX11) { ArgTable["cxxflags"] += " -std=c++11"; } else if (useCXX14) { ArgTable["cxxflags"] += " -std=c++14"; } else if (useCXX1y) { ArgTable["cxxflags"] += " -std=c++1y"; } else if (useCXX1z) { ArgTable["cxxflags"] += " -std=c++1z"; } //------------------------------------------------------------- // if unspecified, take all files under current folder if (allsrc.empty()) { allsrc = Dir::ListDir("."); } if (allsrc.empty()) { cerr << "FATAL: nothing to build!" << endl; return Error::Empty; } // sort by file path std::sort(allsrc.begin(), allsrc.end(), [](const std::string& str1, const std::string& str2) { return std::strcoll(str1.c_str(), str2.c_str()) < 0 ? true : false; }); } // Prepare construct units. // Note: "workdir" & "out" should occur together bool hasCpp = false; bool hasOut = FileInfo(ArgTable["workdir"] + ArgTable["out"]).Exists(); vector<ConsUnit> newUnits; string allObjects; for (const auto& file: allsrc) { ConsUnit unit(ArgTable["workdir"], file); string compiler; string compilerFlag; // Calculate dependence. bool ok = false; const string ext(FileInfo(file).Suffix()); if (C_EXT.find(ext) != C_EXT.end()) { compiler = ArgTable["cc"]; compilerFlag = ArgTable["cflags"]; ok = ConsUnit::InitC(unit, compiler, compilerFlag); } else if (CXX_EXT.find(ext) != CXX_EXT.end()) { hasCpp = true; compiler = ArgTable["cxx"]; compilerFlag = ArgTable["cxxflags"]; ok = ConsUnit::InitCpp(unit, compiler, compilerFlag); } else if (ASM_EXT.find(ext) != ASM_EXT.end()) { compiler = ArgTable["as"]; compilerFlag = ArgTable["asflags"]; ok = ConsUnit::InitAsm(unit, compiler, compilerFlag); } else { continue; } if (ok) { if (unit.out == ArgTable["ldfirst"]) { allObjects = " " + unit.out + allObjects; } else { allObjects += " " + unit.out; } if (!unit.cmd.empty()) { newUnits.push_back(std::move(unit)); } } else { cerr << "FATAL: failed to calculate dependence!" << endl; cerr << " file: " << file << endl; cerr << " compiler: " << compiler << endl; cerr << " flags: " << ArgTable["flags"] << endl; cerr << " cflags: " << ArgTable["cflags"] << endl; cerr << " cxxflags: " << ArgTable["cxxflags"] << endl; return Error::Dependency; } } if (hasCpp) { ArgTable["ld"] = ArgTable["cxx"]; } #ifdef DEBUG // Debug info. { auto fn = [](const vector<ConsUnit>& units) { for (const auto& unit: units) { cout << "in: " << unit.in << ", " << "out: " << unit.out << endl; cout << "\t" << unit.cmd << endl; cout << "\t"; for (const auto& dep: unit.deps) { cout << dep << ", "; } cout << endl; } }; cout << "new units: " << endl; fn(newUnits); } #endif // clean if (clean) { const string& cmd = "rm -f " + ArgTable["workdir"] + ArgTable["out"] + allObjects; cout << cmd << endl; ::system(cmd.c_str()); return EXIT_SUCCESS; } // compile if (!newUnits.empty()) { cout << "* Build: "; if (!verbose) { cout << newUnits.size() << (newUnits.size() > 1 ? " files" : " file"); } else { for (size_t i = 0; i < newUnits.size(); ++i) { cout << newUnits[i].in << ((i+1 < newUnits.size()) ? ", " : ""); } } cout << endl; ParallelCompiler pc(newUnits); pc.SetVerbose(verbose); if (pc.Run(std::stoi(ArgTable["jobs"])) != 0) { return Error::Compile; } } // link if ((!hasOut || !newUnits.empty()) && !nolink) { string ldCmd = ArgTable["ld"] + ArgTable["ldflags"]; ldCmd += " -o " + ArgTable["workdir"] + ArgTable["out"] + allObjects; if (!verbose) { cout << "- Link - " << ArgTable["workdir"] + ArgTable["out"] << endl; } else { cout << "- Link - " << ldCmd << endl; } if (::system(ldCmd.c_str()) != 0) { cerr << "FATAL: failed to link!" << endl; cerr << " file: " << allObjects << endl; cerr << " ld: " << ArgTable["ld"] << endl; cerr << " ldflags: " << ArgTable["ldflags"] << endl; return Error::Compile; } } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* cbr * FairQueue.hpp * * Copyright (c) 2009, Ewen Cheslack-Postava * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of cbr nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _FAIR_MESSAGE_QUEUE_HPP_ #define _FAIR_MESSAGE_QUEUE_HPP_ #include "Time.hpp" #include "Queue.hpp" namespace CBR { /** Predicate for FairQueue which never rejects the item being considered. */ struct AlwaysUsePredicate { template<typename Key, typename Message> bool operator()(const Key& key, const Message* msg) const { return true; } }; /** Fair Queue with one input queue of Messages per Key, backed by a TQueue. Each * input queue can be assigned a weight and selection happens according to FairQueuing, * with the additional constraint that each potential front element will be checked * against a Predicate to give the user a chance to block certain queues from being used * (for instance, if the downstream queue couldn't handle it). */ template <class Message,class Key,class TQueue,class Predicate=AlwaysUsePredicate> class FairQueue { public: struct ServerQueueInfo { private: ServerQueueInfo():nextFinishTime(0) { messageQueue=NULL; weight=1.0; } public: ServerQueueInfo(Key serverName, TQueue* queue, float w) : messageQueue(queue), weight(w), nextFinishTime(0),mKey(serverName) {} TQueue* messageQueue; float weight; Time nextFinishTime; Key mKey; struct FinishTimeOrder { bool operator()(const ServerQueueInfo* lhs, const ServerQueueInfo* rhs) { return (lhs->nextFinishTime < rhs->nextFinishTime); } }; }; typedef std::map<Key, ServerQueueInfo> ServerQueueInfoMap; typedef TQueue MessageQueue; FairQueue(const Predicate pred = Predicate()) :mCurrentVirtualTime(0), mServerQueues(), mPredicate(pred), mFrontQueue(NULL) { } ~FairQueue() { typename ServerQueueInfoMap::iterator it = mServerQueues.begin(); for(; it != mServerQueues.end(); it++) { ServerQueueInfo* queue_info = &it->second; delete queue_info->messageQueue; } } void addQueue(MessageQueue *mq, Key server, float weight) { //assert(mq->empty()); ServerQueueInfo queue_info (server, mq, weight); mServerQueues.insert(std::pair<Key,ServerQueueInfo>(server, queue_info)); } void setQueueWeight(Key server, float weight) { typename ServerQueueInfoMap::iterator where=mServerQueues.find(server); bool retval=( where != mServerQueues.end() ); if (where != mServerQueues.end()) { where->second.weight = weight; } } float getQueueWeight(Key server) const { typename ServerQueueInfoMap::const_iterator where=mServerQueues.find(server); if (where != mServerQueues.end()) { return where->second.weight; } return 0; } bool deprioritize(Key server,float factor, float affine, float minval,float maxval) { return changepriority(server,factor,affine,minval,maxval,true); } bool reprioritize(Key server,float factor, float affine, float minval,float maxval) { return changepriority(server,factor,affine,minval,maxval,false); } bool changepriority(Key server,float factor, float affine, float minval,float maxval, bool passOnDeprioritize) { typename ServerQueueInfoMap::iterator where=mServerQueues.find(server); if ( where == mServerQueues.end() ) return false; float oldweight=where->second.weight; oldweight*=factor; oldweight+=affine; if (oldweight<minval){ oldweight=minval; } this->setQueueWeight(server,oldweight); return true; } bool removeQueue(Key server) { typename ServerQueueInfoMap::iterator where=mServerQueues.find(server); bool retval=( where != mServerQueues.end() ); if (retval) { delete where->second.messageQueue; mServerQueues.erase(where); } return retval; } bool hasQueue(Key server) const{ return ( mServerQueues.find(server) != mServerQueues.end() ); } unsigned int numQueues() const { return (unsigned int)mServerQueues.size(); } QueueEnum::PushResult push(Key dest_server, Message *msg){ typename ServerQueueInfoMap::iterator qi_it = mServerQueues.find(dest_server); assert( qi_it != mServerQueues.end() ); ServerQueueInfo* queue_info = &qi_it->second; // If the queue was empty then the new packet is first and its finish time needs to be computed. if (queue_info->messageQueue->empty()) queue_info->nextFinishTime = finishTime(msg->size(), queue_info->weight); return queue_info->messageQueue->push(msg); } // Returns the next message to deliver, given the number of bytes available for transmission // \param bytes number of bytes available; updated appropriately for intermediate null messages when returns // \returns the next message, or NULL if the queue is empty or the next message cannot be handled // given the number of bytes allocated Message* front(uint64* bytes, Key*keyAtFront) { Message* result = NULL; Time vftime(0); mFrontQueue = NULL; nextMessage(bytes, &result, &vftime, &mFrontQueue); if (result != NULL) { assert( *bytes >= result->size() ); *keyAtFront = mFrontQueue->mKey; return result; } return NULL; } // Returns the next message to deliver, given the number of bytes available for transmission // \param bytes number of bytes available; updated appropriately when returns // \returns the next message, or NULL if the queue is empty or the next message cannot be handled // given the number of bytes allotted Message* pop(uint64* bytes) { Message* result = NULL; Time vftime(0); // If we haven't marked any queue as holding the front item, do so now if (mFrontQueue == NULL) nextMessage(bytes, &result, &vftime, &mFrontQueue); else { // Otherwise, just fill in the information we need from the marked queue assert(!mFrontQueue->messageQueue->empty()); result = mFrontQueue->messageQueue->front(); vftime = mFrontQueue->nextFinishTime; } if (result != NULL) { // Note: we may have skipped a msg using the predicate, so we use max here to make sure // the virtual time increases monotonically. mCurrentVirtualTime = std::max(vftime, mCurrentVirtualTime); assert(mFrontQueue != NULL); assert( *bytes >= result->size() ); *bytes -= result->size(); mFrontQueue->messageQueue->pop(); // update the next finish time if there's anything in the queue if (!mFrontQueue->messageQueue->empty()) mFrontQueue->nextFinishTime = finishTime(mFrontQueue->messageQueue->front()->size(), mFrontQueue->weight, mFrontQueue->nextFinishTime); // Unmark the queue as being in front mFrontQueue = NULL; } return result; } bool empty() const { // FIXME we could track a count ourselves instead of checking all these queues for(typename ServerQueueInfoMap::const_iterator it = mServerQueues.begin(); it != mServerQueues.end(); it++) { const ServerQueueInfo* queue_info = &it->second; if (!queue_info->messageQueue->empty()) return false; } return true; } // Returns the total amount of space that can be allocated for the destination uint32 maxSize(Key dest) const { typename ServerQueueInfoMap::const_iterator it = mServerQueues.find(dest); if (it == mServerQueues.end()) return 0; return it->second.messageQueue->maxSize(); } // Returns the total amount of space currently used for the destination uint32 size(Key dest) const { typename ServerQueueInfoMap::const_iterator it = mServerQueues.find(dest); if (it == mServerQueues.end()) return 0; return it->second.messageQueue->size(); } protected: // Retrieves the next message to deliver, along with its virtual finish time, given the number of bytes available // for transmission. May update bytes for null messages, but does not update it to remove bytes to be used for // the returned message. Returns null either if the number of bytes is not sufficient or the queue is empty. void nextMessage(uint64* bytes, Message** result_out, Time* vftime_out, ServerQueueInfo** min_queue_info_out) { // Create a list of queues, sorted by nextFinishTime. FIXME we should probably track this instead of regenerating it every time std::vector<ServerQueueInfo*> queues_by_finish_time; queues_by_finish_time.reserve(mServerQueues.size()); for(typename ServerQueueInfoMap::iterator it = mServerQueues.begin(); it != mServerQueues.end(); it++) { ServerQueueInfo* queue_info = &it->second; if (queue_info->messageQueue->empty()) continue; queues_by_finish_time.push_back(queue_info); } // If this list ends up empty then there are no enqueued messages if (queues_by_finish_time.empty()) { *result_out = NULL; return; } std::sort(queues_by_finish_time.begin(), queues_by_finish_time.end(), typename ServerQueueInfo::FinishTimeOrder()); // Loop through until we find one that has data and can be handled. for(uint32 i = 0; i < queues_by_finish_time.size(); i++) { ServerQueueInfo* min_queue_info = queues_by_finish_time[i]; // Check that we have enough bytes to deliver. If not stop the search and return since doing otherwise // would violate the ordering. if (*bytes < min_queue_info->messageQueue->front()->size()) { *result_out = NULL; return; } // Now give the user a chance to veto this packet. If they can use it, set output and return. // Otherwise just continue trying the rest of the options. if (mPredicate(min_queue_info->mKey, min_queue_info->messageQueue->front())) { *min_queue_info_out = min_queue_info; *vftime_out = min_queue_info->nextFinishTime; *result_out = min_queue_info->messageQueue->front(); return; } } // If we get here then we've tried everything and nothing has satisfied our constraints. Give up. *result_out = NULL; return; } /** Finish time for a packet that was inserted into a non-empty queue, i.e. based on the previous packet's * finish time. */ Time finishTime(uint32 size, float weight, const Time& last_finish_time) const { float queue_frac = weight; Duration transmitTime = Duration::seconds( size / queue_frac ); if (transmitTime == Duration(0)) transmitTime = Duration(1); // just make sure we take *some* time return last_finish_time + transmitTime; } /** Finish time for a packet inserted into an empty queue, i.e. based on the most recent virtual time. */ Time finishTime(uint32 size, float weight) const { float queue_frac = weight; Duration transmitTime = Duration::seconds( size / queue_frac ); if (transmitTime == Duration(0)) transmitTime = Duration(1); // just make sure we take *some* time return mCurrentVirtualTime + transmitTime; } protected: uint32 mRate; Time mCurrentVirtualTime; ServerQueueInfoMap mServerQueues; Predicate mPredicate; ServerQueueInfo* mFrontQueue; // The queue we've marked as the one containing the front item }; // class FairQueue } // namespace CBR #endif //_FAIR_MESSAGE_QUEUE_HPP_ <commit_msg>Make FairQueue handle zero weights.<commit_after>/* cbr * FairQueue.hpp * * Copyright (c) 2009, Ewen Cheslack-Postava * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of cbr nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _FAIR_MESSAGE_QUEUE_HPP_ #define _FAIR_MESSAGE_QUEUE_HPP_ #include "Time.hpp" #include "Queue.hpp" namespace CBR { /** Predicate for FairQueue which never rejects the item being considered. */ struct AlwaysUsePredicate { template<typename Key, typename Message> bool operator()(const Key& key, const Message* msg) const { return true; } }; /** Fair Queue with one input queue of Messages per Key, backed by a TQueue. Each * input queue can be assigned a weight and selection happens according to FairQueuing, * with the additional constraint that each potential front element will be checked * against a Predicate to give the user a chance to block certain queues from being used * (for instance, if the downstream queue couldn't handle it). */ template <class Message,class Key,class TQueue,class Predicate=AlwaysUsePredicate> class FairQueue { public: struct ServerQueueInfo { private: ServerQueueInfo():nextFinishTime(0) { messageQueue=NULL; weight=1.0; } public: ServerQueueInfo(Key serverName, TQueue* queue, float w) : messageQueue(queue), weight(w), nextFinishTime(0),mKey(serverName) {} TQueue* messageQueue; float weight; Time nextFinishTime; Key mKey; struct FinishTimeOrder { bool operator()(const ServerQueueInfo* lhs, const ServerQueueInfo* rhs) { return (lhs->nextFinishTime < rhs->nextFinishTime); } }; }; typedef std::map<Key, ServerQueueInfo> ServerQueueInfoMap; typedef TQueue MessageQueue; FairQueue(const Predicate pred = Predicate()) :mCurrentVirtualTime(0), mServerQueues(), mPredicate(pred), mFrontQueue(NULL) { } ~FairQueue() { typename ServerQueueInfoMap::iterator it = mServerQueues.begin(); for(; it != mServerQueues.end(); it++) { ServerQueueInfo* queue_info = &it->second; delete queue_info->messageQueue; } } void addQueue(MessageQueue *mq, Key server, float weight) { //assert(mq->empty()); ServerQueueInfo queue_info (server, mq, weight); mServerQueues.insert(std::pair<Key,ServerQueueInfo>(server, queue_info)); } void setQueueWeight(Key server, float weight) { typename ServerQueueInfoMap::iterator where=mServerQueues.find(server); bool retval=( where != mServerQueues.end() ); if (where != mServerQueues.end()) { where->second.weight = weight; } } float getQueueWeight(Key server) const { typename ServerQueueInfoMap::const_iterator where=mServerQueues.find(server); if (where != mServerQueues.end()) { return where->second.weight; } return 0; } bool deprioritize(Key server,float factor, float affine, float minval,float maxval) { return changepriority(server,factor,affine,minval,maxval,true); } bool reprioritize(Key server,float factor, float affine, float minval,float maxval) { return changepriority(server,factor,affine,minval,maxval,false); } bool changepriority(Key server,float factor, float affine, float minval,float maxval, bool passOnDeprioritize) { typename ServerQueueInfoMap::iterator where=mServerQueues.find(server); if ( where == mServerQueues.end() ) return false; float oldweight=where->second.weight; oldweight*=factor; oldweight+=affine; if (oldweight<minval){ oldweight=minval; } this->setQueueWeight(server,oldweight); return true; } bool removeQueue(Key server) { typename ServerQueueInfoMap::iterator where=mServerQueues.find(server); bool retval=( where != mServerQueues.end() ); if (retval) { delete where->second.messageQueue; mServerQueues.erase(where); } return retval; } bool hasQueue(Key server) const{ return ( mServerQueues.find(server) != mServerQueues.end() ); } unsigned int numQueues() const { return (unsigned int)mServerQueues.size(); } QueueEnum::PushResult push(Key dest_server, Message *msg){ typename ServerQueueInfoMap::iterator qi_it = mServerQueues.find(dest_server); assert( qi_it != mServerQueues.end() ); ServerQueueInfo* queue_info = &qi_it->second; // If the queue was empty then the new packet is first and its finish time needs to be computed. if (queue_info->messageQueue->empty()) queue_info->nextFinishTime = finishTime(msg->size(), queue_info->weight); return queue_info->messageQueue->push(msg); } // Returns the next message to deliver, given the number of bytes available for transmission // \param bytes number of bytes available; updated appropriately for intermediate null messages when returns // \returns the next message, or NULL if the queue is empty or the next message cannot be handled // given the number of bytes allocated Message* front(uint64* bytes, Key*keyAtFront) { Message* result = NULL; Time vftime(0); mFrontQueue = NULL; nextMessage(bytes, &result, &vftime, &mFrontQueue); if (result != NULL) { assert( *bytes >= result->size() ); *keyAtFront = mFrontQueue->mKey; return result; } return NULL; } // Returns the next message to deliver, given the number of bytes available for transmission // \param bytes number of bytes available; updated appropriately when returns // \returns the next message, or NULL if the queue is empty or the next message cannot be handled // given the number of bytes allotted Message* pop(uint64* bytes) { Message* result = NULL; Time vftime(0); // If we haven't marked any queue as holding the front item, do so now if (mFrontQueue == NULL) nextMessage(bytes, &result, &vftime, &mFrontQueue); else { // Otherwise, just fill in the information we need from the marked queue assert(!mFrontQueue->messageQueue->empty()); result = mFrontQueue->messageQueue->front(); vftime = mFrontQueue->nextFinishTime; } if (result != NULL) { // Note: we may have skipped a msg using the predicate, so we use max here to make sure // the virtual time increases monotonically. mCurrentVirtualTime = std::max(vftime, mCurrentVirtualTime); assert(mFrontQueue != NULL); assert( *bytes >= result->size() ); *bytes -= result->size(); mFrontQueue->messageQueue->pop(); // update the next finish time if there's anything in the queue if (!mFrontQueue->messageQueue->empty()) mFrontQueue->nextFinishTime = finishTime(mFrontQueue->messageQueue->front()->size(), mFrontQueue->weight, mFrontQueue->nextFinishTime); // Unmark the queue as being in front mFrontQueue = NULL; } return result; } bool empty() const { // FIXME we could track a count ourselves instead of checking all these queues for(typename ServerQueueInfoMap::const_iterator it = mServerQueues.begin(); it != mServerQueues.end(); it++) { const ServerQueueInfo* queue_info = &it->second; if (!queue_info->messageQueue->empty()) return false; } return true; } // Returns the total amount of space that can be allocated for the destination uint32 maxSize(Key dest) const { typename ServerQueueInfoMap::const_iterator it = mServerQueues.find(dest); if (it == mServerQueues.end()) return 0; return it->second.messageQueue->maxSize(); } // Returns the total amount of space currently used for the destination uint32 size(Key dest) const { typename ServerQueueInfoMap::const_iterator it = mServerQueues.find(dest); if (it == mServerQueues.end()) return 0; return it->second.messageQueue->size(); } protected: // Retrieves the next message to deliver, along with its virtual finish time, given the number of bytes available // for transmission. May update bytes for null messages, but does not update it to remove bytes to be used for // the returned message. Returns null either if the number of bytes is not sufficient or the queue is empty. void nextMessage(uint64* bytes, Message** result_out, Time* vftime_out, ServerQueueInfo** min_queue_info_out) { // Create a list of queues, sorted by nextFinishTime. FIXME we should probably track this instead of regenerating it every time std::vector<ServerQueueInfo*> queues_by_finish_time; queues_by_finish_time.reserve(mServerQueues.size()); for(typename ServerQueueInfoMap::iterator it = mServerQueues.begin(); it != mServerQueues.end(); it++) { ServerQueueInfo* queue_info = &it->second; if (queue_info->messageQueue->empty()) continue; queues_by_finish_time.push_back(queue_info); } // If this list ends up empty then there are no enqueued messages if (queues_by_finish_time.empty()) { *result_out = NULL; return; } std::sort(queues_by_finish_time.begin(), queues_by_finish_time.end(), typename ServerQueueInfo::FinishTimeOrder()); // Loop through until we find one that has data and can be handled. for(uint32 i = 0; i < queues_by_finish_time.size(); i++) { ServerQueueInfo* min_queue_info = queues_by_finish_time[i]; // Check that we have enough bytes to deliver. If not stop the search and return since doing otherwise // would violate the ordering. if (*bytes < min_queue_info->messageQueue->front()->size()) { *result_out = NULL; return; } // Now give the user a chance to veto this packet. If they can use it, set output and return. // Otherwise just continue trying the rest of the options. if (mPredicate(min_queue_info->mKey, min_queue_info->messageQueue->front())) { *min_queue_info_out = min_queue_info; *vftime_out = min_queue_info->nextFinishTime; *result_out = min_queue_info->messageQueue->front(); return; } } // If we get here then we've tried everything and nothing has satisfied our constraints. Give up. *result_out = NULL; return; } /** Finish time for a packet that was inserted into a non-empty queue, i.e. based on the previous packet's * finish time. */ Time finishTime(uint32 size, float weight, const Time& last_finish_time) const { float queue_frac = weight; Duration transmitTime = queue_frac == 0 ? Duration::seconds((float)1000) : Duration::seconds( size / queue_frac ); if (transmitTime == Duration(0)) transmitTime = Duration(1); // just make sure we take *some* time return last_finish_time + transmitTime; } /** Finish time for a packet inserted into an empty queue, i.e. based on the most recent virtual time. */ Time finishTime(uint32 size, float weight) const { float queue_frac = weight; Duration transmitTime = queue_frac == 0 ? Duration::seconds((float)1000) : Duration::seconds( size / queue_frac ); if (transmitTime == Duration(0)) transmitTime = Duration(1); // just make sure we take *some* time return mCurrentVirtualTime + transmitTime; } protected: uint32 mRate; Time mCurrentVirtualTime; ServerQueueInfoMap mServerQueues; Predicate mPredicate; ServerQueueInfo* mFrontQueue; // The queue we've marked as the one containing the front item }; // class FairQueue } // namespace CBR #endif //_FAIR_MESSAGE_QUEUE_HPP_ <|endoftext|>
<commit_before>// Theme.cc for FbTk - Fluxbox ToolKit // Copyright (c) 2002 - 2003 Henrik Kinnunen (fluxgen at users.sourceforge.net) // // 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. // $Id: Theme.cc,v 1.8 2003/07/01 12:39:49 fluxgen Exp $ #include "Theme.hh" #include "XrmDatabaseHelper.hh" #include "Font.hh" #include "Color.hh" #include "Texture.hh" #include "App.hh" #ifdef HAVE_CONFIG_H #include "config.h" #endif // HAVE_CONFIG_H #ifdef HAVE_XPM #include <X11/xpm.h> #endif // HAVE_XPM #include <iostream> using namespace std; namespace FbTk { // create default handlers for Color, Font, Texture, int and string template <> void FbTk::ThemeItem<std::string>::load() { } template <> void FbTk::ThemeItem<std::string>::setDefaultValue() { *(*this) = ""; } template <> void FbTk::ThemeItem<std::string>::setFromString(const char *str) { *(*this) = (str ? str : ""); } template <> void FbTk::ThemeItem<int>::load() { } template <> void FbTk::ThemeItem<int>::setDefaultValue() { *(*this) = 0; } template <> void FbTk::ThemeItem<int>::setFromString(const char *str) { if (str == 0) return; sscanf(str, "%d", &m_value); } template <> void ThemeItem<FbTk::Font>::setDefaultValue() { if (!m_value.load("fixed")) { cerr<<"FbTk::ThemeItem<FbTk::Font>: Warning! Failed to load default value 'fixed'"<<endl; } } template <> void ThemeItem<FbTk::Font>::setFromString(const char *str) { if (m_value.load(str) == false) { cerr<<"FbTk::Theme: Error loading font "<< ((m_value.isAntialias() || m_value.utf8()) ? "(" : "")<< (m_value.isAntialias() ? "antialias" : "")<< (m_value.utf8() ? " utf8" : "")<< ((m_value.isAntialias() || m_value.utf8()) ? ") " : "")<< "for \""<<name()<<"\" or \""<<altName()<<"\": "<<str<<endl; cerr<<"FbTk::Theme: Setting default value"<<endl; setDefaultValue(); } } // do nothing template <> void ThemeItem<FbTk::Font>::load() { } template <> void ThemeItem<FbTk::Texture>::setFromString(const char *str) { m_value.setFromString(str); } template <> void ThemeItem<FbTk::Texture>::setDefaultValue() { m_value.setType(0); } template <> void ThemeItem<FbTk::Texture>::load() { string color_name(ThemeManager::instance(). resourceValue(name()+".color", altName()+".Color")); string colorto_name(ThemeManager::instance(). resourceValue(name()+".colorTo", altName()+".ColorTo")); string pixmap_name(ThemeManager::instance(). resourceValue(name()+".pixmap", altName()+".Pixmap")); m_value.color().setFromString(color_name.c_str(), m_tm.screenNum()); m_value.colorTo().setFromString(colorto_name.c_str(), m_tm.screenNum()); #ifdef HAVE_XPM XpmAttributes xpm_attr; xpm_attr.valuemask = 0; Display *dpy = FbTk::App::instance()->display(); Pixmap pm = 0, mask = 0; int retvalue = XpmReadFileToPixmap(dpy, RootWindow(dpy, m_tm.screenNum()), const_cast<char *>(pixmap_name.c_str()), &pm, &mask, &xpm_attr); if (retvalue == 0) { // success m_value.pixmap() = pm; if (mask != 0) XFreePixmap(dpy, mask); } else { // failure #ifdef DEBUG cerr<<"Couldn't load pixmap: "<<pixmap_name<<endl; #endif // DEBUG // create empty pixmap m_value.pixmap() = FbTk::FbPixmap(); } #endif // HAVE_XPM } template <> void ThemeItem<FbTk::Color>::setDefaultValue() { m_value.setFromString("white", m_tm.screenNum()); } template <> void ThemeItem<FbTk::Color>::setFromString(const char *str) { if (!m_value.setFromString(str, m_tm.screenNum())) { cerr<<"FbTk::Theme: Error loading color value for \""<<name()<<"\" or \""<<altName()<<"\"."<<endl; setDefaultValue(); } } // does nothing template <> void ThemeItem<FbTk::Color>::load() { } Theme::Theme(int screen_num):m_screen_num(screen_num) { if (!ThemeManager::instance().registerTheme(*this)) { // should it be fatal or not? cerr<<"FbTk::Theme Warning: Failed to register Theme"<<endl; } } Theme::~Theme() { if (!ThemeManager::instance().unregisterTheme(*this)) { #ifdef DEBUG cerr<<"Warning: Theme not registered!"<<endl; #endif // DEBUG } } ThemeManager &ThemeManager::instance() { static ThemeManager tm; return tm; } ThemeManager::ThemeManager(): m_max_screens(ScreenCount(FbTk::App::instance()->display())) { } bool ThemeManager::registerTheme(Theme &tm) { // valid screen num? if (m_max_screens < tm.screenNum() || tm.screenNum() < 0) return false; // TODO: use find and return false if it's already there // instead of unique m_themelist.push_back(&tm); m_themelist.unique(); return true; } bool ThemeManager::unregisterTheme(Theme &tm) { m_themelist.remove(&tm); return true; } bool ThemeManager::load(const char *filename) { if (!m_database.load(filename)) return false; //get list and go throu all the resources and load them ThemeList::iterator theme_it = m_themelist.begin(); const ThemeList::iterator theme_it_end = m_themelist.end(); for (; theme_it != theme_it_end; ++theme_it) { loadTheme(**theme_it); } return true; } void ThemeManager::loadTheme(Theme &tm) { XrmValue value; char *value_type; std::list<ThemeItem_base *>::iterator i = tm.itemList().begin(); std::list<ThemeItem_base *>::iterator i_end = tm.itemList().end(); for (; i != i_end; ++i) { ThemeItem_base *resource = *i; if (XrmGetResource(*m_database, resource->name().c_str(), resource->altName().c_str(), &value_type, &value)) { resource->setFromString(value.addr); resource->load(); // load additional stuff by the ThemeItem } else { cerr<<"Failed to read theme item: "<<resource->name()<<endl; cerr<<"Setting default value"<<endl; resource->setDefaultValue(); } } // send reconfiguration signal to theme tm.reconfigTheme(); } std::string ThemeManager::resourceValue(const std::string &name, const std::string &altname) { XrmValue value; char *value_type; if (*m_database != 0 && XrmGetResource(*m_database, name.c_str(), altname.c_str(), &value_type, &value) && value.addr != 0) { return string(value.addr); } return ""; } }; // end namespace FbTk <commit_msg>cstdio for sscanf<commit_after>// Theme.cc for FbTk - Fluxbox ToolKit // Copyright (c) 2002 - 2003 Henrik Kinnunen (fluxgen at users.sourceforge.net) // // 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. // $Id: Theme.cc,v 1.9 2003/07/04 10:25:11 fluxgen Exp $ #include "Theme.hh" #include "XrmDatabaseHelper.hh" #include "Font.hh" #include "Color.hh" #include "Texture.hh" #include "App.hh" #include <cstdio> #ifdef HAVE_CONFIG_H #include "config.h" #endif // HAVE_CONFIG_H #ifdef HAVE_XPM #include <X11/xpm.h> #endif // HAVE_XPM #include <iostream> using namespace std; namespace FbTk { // create default handlers for Color, Font, Texture, int and string template <> void FbTk::ThemeItem<std::string>::load() { } template <> void FbTk::ThemeItem<std::string>::setDefaultValue() { *(*this) = ""; } template <> void FbTk::ThemeItem<std::string>::setFromString(const char *str) { *(*this) = (str ? str : ""); } template <> void FbTk::ThemeItem<int>::load() { } template <> void FbTk::ThemeItem<int>::setDefaultValue() { *(*this) = 0; } template <> void FbTk::ThemeItem<int>::setFromString(const char *str) { if (str == 0) return; sscanf(str, "%d", &m_value); } template <> void ThemeItem<FbTk::Font>::setDefaultValue() { if (!m_value.load("fixed")) { cerr<<"FbTk::ThemeItem<FbTk::Font>: Warning! Failed to load default value 'fixed'"<<endl; } } template <> void ThemeItem<FbTk::Font>::setFromString(const char *str) { if (m_value.load(str) == false) { cerr<<"FbTk::Theme: Error loading font "<< ((m_value.isAntialias() || m_value.utf8()) ? "(" : "")<< (m_value.isAntialias() ? "antialias" : "")<< (m_value.utf8() ? " utf8" : "")<< ((m_value.isAntialias() || m_value.utf8()) ? ") " : "")<< "for \""<<name()<<"\" or \""<<altName()<<"\": "<<str<<endl; cerr<<"FbTk::Theme: Setting default value"<<endl; setDefaultValue(); } } // do nothing template <> void ThemeItem<FbTk::Font>::load() { } template <> void ThemeItem<FbTk::Texture>::setFromString(const char *str) { m_value.setFromString(str); } template <> void ThemeItem<FbTk::Texture>::setDefaultValue() { m_value.setType(0); } template <> void ThemeItem<FbTk::Texture>::load() { string color_name(ThemeManager::instance(). resourceValue(name()+".color", altName()+".Color")); string colorto_name(ThemeManager::instance(). resourceValue(name()+".colorTo", altName()+".ColorTo")); string pixmap_name(ThemeManager::instance(). resourceValue(name()+".pixmap", altName()+".Pixmap")); m_value.color().setFromString(color_name.c_str(), m_tm.screenNum()); m_value.colorTo().setFromString(colorto_name.c_str(), m_tm.screenNum()); #ifdef HAVE_XPM XpmAttributes xpm_attr; xpm_attr.valuemask = 0; Display *dpy = FbTk::App::instance()->display(); Pixmap pm = 0, mask = 0; int retvalue = XpmReadFileToPixmap(dpy, RootWindow(dpy, m_tm.screenNum()), const_cast<char *>(pixmap_name.c_str()), &pm, &mask, &xpm_attr); if (retvalue == 0) { // success m_value.pixmap() = pm; if (mask != 0) XFreePixmap(dpy, mask); } else { // failure #ifdef DEBUG cerr<<"Couldn't load pixmap: "<<pixmap_name<<endl; #endif // DEBUG // create empty pixmap m_value.pixmap() = FbTk::FbPixmap(); } #endif // HAVE_XPM } template <> void ThemeItem<FbTk::Color>::setDefaultValue() { m_value.setFromString("white", m_tm.screenNum()); } template <> void ThemeItem<FbTk::Color>::setFromString(const char *str) { if (!m_value.setFromString(str, m_tm.screenNum())) { cerr<<"FbTk::Theme: Error loading color value for \""<<name()<<"\" or \""<<altName()<<"\"."<<endl; setDefaultValue(); } } // does nothing template <> void ThemeItem<FbTk::Color>::load() { } Theme::Theme(int screen_num):m_screen_num(screen_num) { if (!ThemeManager::instance().registerTheme(*this)) { // should it be fatal or not? cerr<<"FbTk::Theme Warning: Failed to register Theme"<<endl; } } Theme::~Theme() { if (!ThemeManager::instance().unregisterTheme(*this)) { #ifdef DEBUG cerr<<"Warning: Theme not registered!"<<endl; #endif // DEBUG } } ThemeManager &ThemeManager::instance() { static ThemeManager tm; return tm; } ThemeManager::ThemeManager(): m_max_screens(ScreenCount(FbTk::App::instance()->display())) { } bool ThemeManager::registerTheme(Theme &tm) { // valid screen num? if (m_max_screens < tm.screenNum() || tm.screenNum() < 0) return false; // TODO: use find and return false if it's already there // instead of unique m_themelist.push_back(&tm); m_themelist.unique(); return true; } bool ThemeManager::unregisterTheme(Theme &tm) { m_themelist.remove(&tm); return true; } bool ThemeManager::load(const char *filename) { if (!m_database.load(filename)) return false; //get list and go throu all the resources and load them ThemeList::iterator theme_it = m_themelist.begin(); const ThemeList::iterator theme_it_end = m_themelist.end(); for (; theme_it != theme_it_end; ++theme_it) { loadTheme(**theme_it); } return true; } void ThemeManager::loadTheme(Theme &tm) { XrmValue value; char *value_type; std::list<ThemeItem_base *>::iterator i = tm.itemList().begin(); std::list<ThemeItem_base *>::iterator i_end = tm.itemList().end(); for (; i != i_end; ++i) { ThemeItem_base *resource = *i; if (XrmGetResource(*m_database, resource->name().c_str(), resource->altName().c_str(), &value_type, &value)) { resource->setFromString(value.addr); resource->load(); // load additional stuff by the ThemeItem } else { cerr<<"Failed to read theme item: "<<resource->name()<<endl; cerr<<"Setting default value"<<endl; resource->setDefaultValue(); } } // send reconfiguration signal to theme tm.reconfigTheme(); } std::string ThemeManager::resourceValue(const std::string &name, const std::string &altname) { XrmValue value; char *value_type; if (*m_database != 0 && XrmGetResource(*m_database, name.c_str(), altname.c_str(), &value_type, &value) && value.addr != 0) { return string(value.addr); } return ""; } }; // end namespace FbTk <|endoftext|>
<commit_before> #include "Network.hpp" #include "Server.hpp" #include "Proximity.hpp" #include "CoordinateSegmentation.hpp" #include "Message.hpp" #include "ServerIDMap.hpp" #include "ServerMessageQueue.hpp" #include "Statistics.hpp" #include "Options.hpp" #include "ObjectMessageQueue.hpp" #include "LoadMonitor.hpp" #include "ForwarderUtilityClasses.hpp" #include "Forwarder.hpp" #include "ObjectSegmentation.hpp" #include "Proximity.hpp" #include "ObjectConnection.hpp" #include "Random.hpp" namespace CBR { /* Constructor for Forwarder */ Forwarder::Forwarder(SpaceContext* ctx) : mContext(ctx), mCSeg(NULL), mOSeg(NULL), mLocationService(NULL), mObjectMessageQueue(NULL), mServerMessageQueue(NULL), mLoadMonitor(NULL), mProximity(NULL), mLastSampleTime(Time::null()), mSampleRate( GetOption(STATS_SAMPLE_RATE)->as<Duration>() ) { //no need to initialize mSelfMessages and mOutgoingMessages. // Fill in the rest of the context mContext->router = this; mContext->dispatcher = this; // Messages destined for objects are subscribed to here so we can easily pick them // out and decide whether they can be delivered directly or need forwarding this->registerMessageRecipient(MESSAGE_TYPE_OBJECT, this); } //Don't need to do anything special for destructor Forwarder::~Forwarder() { this->unregisterMessageRecipient(MESSAGE_TYPE_OBJECT, this); } /* Assigning time and mObjects, which should have been constructed in Server's constructor. */ void Forwarder::initialize(CoordinateSegmentation* cseg, ObjectSegmentation* oseg, LocationService* locService, ObjectMessageQueue* omq, ServerMessageQueue* smq, LoadMonitor* lm, Proximity* prox) { mCSeg = cseg; mOSeg = oseg; mLocationService = locService; mObjectMessageQueue = omq; mServerMessageQueue =smq; mLoadMonitor = lm; mProximity = prox; } /* Sends a tick to OSeg. Receives messages from oseg. Adds them to mOutgoingQueue. */ void Forwarder::tickOSeg(const Time&t) { // getOSegMessages(); //bftm tmp, nothing // mOSeg -> tick(t,mOutgoingMessages); //objects from std::map<UUID,ServerID> updatedObjectLocations; std::map<UUID,ServerID>::iterator iter; std::map<UUID,ObjectMessageList>::iterator iterObjectsInTransit; std::map<UUID,ObjMessQBeginSendList>::iterator iterQueueMap; mOSeg->service(updatedObjectLocations); //deliver acknowledge messages. if (updatedObjectLocations.size() !=0) { // std::cout<<"\n\nbftm debug: inside of forwarder.cpp this is the number of updatedObjectLocations: "<<updatedObjectLocations.size()<<"\n\n"; } // cross-check updates against held messages. for (iter = updatedObjectLocations.begin(); iter != updatedObjectLocations.end(); ++iter) { iterObjectsInTransit = mObjectsInTransit.find(iter->first); if (iterObjectsInTransit != mObjectsInTransit.end()) { //means that we can route messages being held in mObjectsInTransit for (int s=0; s < (signed)((iterObjectsInTransit->second).size()); ++s) { // std::cout<<"\n\nbftm debug: inside of forwarder. Actually routing a message that I had saved up\n\n"; route((iterObjectsInTransit->second)[s],iter->second,false); } //remove the messages from the objects in transit mObjectsInTransit.erase(iterObjectsInTransit); } iterQueueMap = queueMap.find(iter->first); if (iterQueueMap != queueMap.end()) { //means that we have to call endSend on the message. for (int s=0; s < (signed) ((iterQueueMap->second).size()); ++ s) { mObjectMessageQueue->endSend(iterQueueMap->second[s],iter->second); //iter->second is the dest_server_id } queueMap.erase(iterQueueMap); } } } void Forwarder::service() { Time t = mContext->time; if (t - mLastSampleTime > mSampleRate) { mServerMessageQueue->reportQueueInfo(t); mLastSampleTime = t; } mLoadMonitor->service(); tickOSeg(t);//updates oseg std::deque<SelfMessage> self_messages; self_messages.swap( mSelfMessages ); while (!self_messages.empty()) { processChunk(self_messages.front().data, mContext->id, self_messages.front().forwarded); self_messages.pop_front(); } while(!mOutgoingMessages.empty()) { OutgoingMessage& next_msg = mOutgoingMessages.front(); bool send_success = mServerMessageQueue->addMessage(next_msg.dest, next_msg.data); if (!send_success) break; mOutgoingMessages.pop_front(); } // XXXXXXXXXXXXXXXXXXXXXX Generate noise if (GetOption(NOISE)->as<bool>()) { if (GetOption(SERVER_QUEUE)->as<String>() == "fair") { for(ServerID sid = 1; sid <= mCSeg->numServers(); sid++) { if (sid == mContext->id) continue; while(true) { NoiseMessage* noise_msg = new NoiseMessage(mContext->id, (uint32)(50 + 200*randFloat())); // FIXME control size from options? uint32 offset = 0; Network::Chunk msg_serialized; offset = noise_msg->serialize(msg_serialized, offset); bool sent_success = mServerMessageQueue->addMessage(sid, msg_serialized); if (sent_success) mContext->trace->serverDatagramQueued(mContext->time, sid, noise_msg->id(), offset); delete noise_msg; if (!sent_success) break; } } } else { // For FIFO we generate for random servers because they all // share a single internal queue. uint32 nfail = 0; uint32 nservers = mCSeg->numServers(); while(nfail < nservers) { ServerID sid = randInt<uint32>(1, nservers); if (sid == mContext->id) continue; NoiseMessage* noise_msg = new NoiseMessage(mContext->id, (uint32)(50 + 200*randFloat())); // FIXME control size from options? uint32 offset = 0; Network::Chunk msg_serialized; offset = noise_msg->serialize(msg_serialized, offset); bool sent_success = mServerMessageQueue->addMessage(sid, msg_serialized); if (sent_success) mContext->trace->serverDatagramQueued(mContext->time, sid, noise_msg->id(), offset); delete noise_msg; if (!sent_success) nfail++; } } } // XXXXXXXXXXXXXXXXXXXXXXXX mObjectMessageQueue->service(); mServerMessageQueue->service(); Sirikata::Network::Chunk *c=NULL; ServerID source_server; while(mServerMessageQueue->receive(&c, &source_server)) { processChunk(*c, source_server, false); delete c; } } //bftm note: this is fine even after message overhaul. // Routing interface for servers. This is used to route messages that originate from // a server provided service, and thus don't have a source object. Messages may be destined // for either servers or objects. The second form will simply automatically do the destination // server lookup. // if forwarding is true the message will be stuck onto a queue no matter what, otherwise it may be delivered directly void Forwarder::route(Message* msg, const ServerID& dest_server, bool is_forward) { uint32 offset = 0; Network::Chunk msg_serialized; offset = msg->serialize(msg_serialized, offset); if (dest_server==mContext->id) { if (!is_forward) { mContext->trace->serverDatagramQueued(mContext->time, dest_server, msg->id(), offset); mContext->trace->serverDatagramSent(mContext->time, mContext->time, 0 , dest_server, msg->id(), offset); // self rate is infinite => start and end times are identical } else { // The more times the message goes through a forward to self loop, the more times this will record, causing an explosion // in trace size. It's probably not worth recording this information... //mContext->trace->serverDatagramQueued(mContext->time, dest_server, msg->id(), offset); } mSelfMessages.push_back( SelfMessage(msg_serialized, is_forward) ); } else { mContext->trace->serverDatagramQueued(mContext->time, dest_server, msg->id(), offset); mOutgoingMessages.push_back( OutgoingMessage(msg_serialized, dest_server) ); } delete msg; } void Forwarder::route(CBR::Protocol::Object::ObjectMessage* msg, bool is_forward) { UUID dest_obj = msg->dest_object(); // ServerID dest_server_id = lookup(dest_obj); mOSeg->lookup(dest_obj); //add message to objects in transit. // if (mObjectsInTransit[dest_obj] == null) if (mObjectsInTransit.find(dest_obj) == mObjectsInTransit.end()) { //no messages have been queued for mObjectsInTransit //add this as the beginning of a vector of message pointers. ObjectMessageList tmp; tmp.push_back(msg); mObjectsInTransit[dest_obj] = tmp; } else { //add message to queue of objects in transit. mObjectsInTransit[dest_obj].push_back(msg); } } //end what i think it should be replaced with bool Forwarder::routeObjectHostMessage(CBR::Protocol::Object::ObjectMessage* obj_msg) { // Messages destined for the space skip the object message queue and just get dispatched if (obj_msg->dest_object() == UUID::null()) { dispatchMessage(*obj_msg); delete obj_msg; return true; } ObjMessQBeginSend beginMess; bool send_success = mObjectMessageQueue->beginSend(obj_msg, beginMess); if (send_success) { mOSeg->lookup(beginMess.dest_uuid); if (queueMap.find(beginMess.dest_uuid) == queueMap.end()) { //nothing is in queueMap ObjMessQBeginSendList tmpList; tmpList.push_back(beginMess); queueMap[beginMess.dest_uuid] = tmpList; } else { queueMap[beginMess.dest_uuid].push_back(beginMess); } } return send_success; } //ewen changes. // void Forwarder::route(CBR::Protocol::Object::ObjectMessage* msg, bool is_forward) // { // UUID dest_obj = msg->dest_object(); // ServerID dest_server_id = mOSeg->lookup(dest_obj); // route(msg, dest_server_id, is_forward); // } // void Forwarder::route(CBR::Protocol::Object::ObjectMessage* msg, ServerID dest_serv, bool is_forward) { // if (dest_serv == OBJECT_IN_TRANSIT) void Forwarder::processChunk(const Network::Chunk&chunk, const ServerID& source_server, bool forwarded_self_msg) { Message* result; uint32 offset=0; do { offset = Message::deserialize(chunk,offset,&result); if (!forwarded_self_msg) mContext->trace->serverDatagramReceived(mContext->time, mContext->time, source_server, result->id(), offset); deliver(result); //if (delivered) // mContext->trace->serverDatagramReceived(mContext->time, mContext->time, source_server, result->id(), offset); }while (offset<chunk.size()); } // Delivery interface. This should be used to deliver received messages to the correct location - // the server or object it is addressed to. void Forwarder::deliver(Message* msg) { switch(msg->type()) { case MESSAGE_TYPE_OBJECT: { dispatchMessage(msg); } break; case MESSAGE_TYPE_NOISE: { NoiseMessage* noise_msg = dynamic_cast<NoiseMessage*>(msg); assert(noise_msg != NULL); delete noise_msg; } break; case MESSAGE_TYPE_MIGRATE: { dispatchMessage(msg); } break; case MESSAGE_TYPE_CSEG_CHANGE: { dispatchMessage(msg); } break; case MESSAGE_TYPE_LOAD_STATUS: { dispatchMessage(msg); } break; case MESSAGE_TYPE_OSEG_MIGRATE_MOVE: { dispatchMessage(msg); } break; case MESSAGE_TYPE_OSEG_MIGRATE_ACKNOWLEDGE: { dispatchMessage(msg); } break; case MESSAGE_TYPE_SERVER_PROX_QUERY: { dispatchMessage(msg); } break; case MESSAGE_TYPE_SERVER_PROX_RESULT: { dispatchMessage(msg); } break; case MESSAGE_TYPE_BULK_LOCATION: { dispatchMessage(msg); } break; default: assert(false); break; } } void Forwarder::receiveMessage(Message* msg) { // Forwarder only subscribes as a recipient for object messages // so it can easily check whether it can deliver directly // or needs to forward them. assert(msg->type() == MESSAGE_TYPE_OBJECT); ObjectMessage* obj_msg = dynamic_cast<ObjectMessage*>(msg); assert(obj_msg != NULL); UUID dest = obj_msg->contents.dest_object(); // Special case: Object 0 is the space itself if (dest == UUID::null()) { dispatchMessage(obj_msg->contents); return; } // Otherwise, either deliver or forward it, depending on whether the destination object is attached to this server ObjectConnection* conn = getObjectConnection(dest); if (conn != NULL) conn->deliver(obj_msg->contents); else { CBR::Protocol::Object::ObjectMessage* obj_msg_cpy = new CBR::Protocol::Object::ObjectMessage(obj_msg->contents); route(obj_msg_cpy, true); } delete msg; } // void Forwarder::forward(Message* msg, const UUID& dest_obj) // { // conn->deliver(obj_msg->contents, mContext->time); // } // else // { // CBR::Protocol::Object::ObjectMessage* obj_msg_cpy = new CBR::Protocol::Object::ObjectMessage(obj_msg->contents); // route(obj_msg_cpy, true); // } // delete msg; // } void Forwarder::route(CBR::Protocol::Object::ObjectMessage* msg, ServerID dest_serv, bool is_forward) { // Wrap it up in one of our ObjectMessages and ship it. ObjectMessage* obj_msg = new ObjectMessage(mContext->id, *msg); //turns the cbr::prot::message into just an object message. route(obj_msg, dest_serv, is_forward); delete msg; } ServerID Forwarder::lookup(const Vector3f& pos) { ServerID sid = mCSeg->lookup(pos); return sid; } void Forwarder::addObjectConnection(const UUID& dest_obj, ObjectConnection* conn) { mObjectConnections[dest_obj] = conn; mObjectMessageQueue->registerClient(dest_obj, 1); // FIXME weight? } ObjectConnection* Forwarder::removeObjectConnection(const UUID& dest_obj) { mObjectMessageQueue->unregisterClient(dest_obj); ObjectConnection* conn = mObjectConnections[dest_obj]; mObjectConnections.erase(dest_obj); return conn; } ObjectConnection* Forwarder::getObjectConnection(const UUID& dest_obj) { ObjectConnectionMap::iterator it = mObjectConnections.find(dest_obj); return (it == mObjectConnections.end()) ? NULL : it->second; } } //end namespace <commit_msg>Make forwarder try to service all outgoing messages so we won't get head of line blocking.<commit_after> #include "Network.hpp" #include "Server.hpp" #include "Proximity.hpp" #include "CoordinateSegmentation.hpp" #include "Message.hpp" #include "ServerIDMap.hpp" #include "ServerMessageQueue.hpp" #include "Statistics.hpp" #include "Options.hpp" #include "ObjectMessageQueue.hpp" #include "LoadMonitor.hpp" #include "ForwarderUtilityClasses.hpp" #include "Forwarder.hpp" #include "ObjectSegmentation.hpp" #include "Proximity.hpp" #include "ObjectConnection.hpp" #include "Random.hpp" namespace CBR { /* Constructor for Forwarder */ Forwarder::Forwarder(SpaceContext* ctx) : mContext(ctx), mCSeg(NULL), mOSeg(NULL), mLocationService(NULL), mObjectMessageQueue(NULL), mServerMessageQueue(NULL), mLoadMonitor(NULL), mProximity(NULL), mLastSampleTime(Time::null()), mSampleRate( GetOption(STATS_SAMPLE_RATE)->as<Duration>() ) { //no need to initialize mSelfMessages and mOutgoingMessages. // Fill in the rest of the context mContext->router = this; mContext->dispatcher = this; // Messages destined for objects are subscribed to here so we can easily pick them // out and decide whether they can be delivered directly or need forwarding this->registerMessageRecipient(MESSAGE_TYPE_OBJECT, this); } //Don't need to do anything special for destructor Forwarder::~Forwarder() { this->unregisterMessageRecipient(MESSAGE_TYPE_OBJECT, this); } /* Assigning time and mObjects, which should have been constructed in Server's constructor. */ void Forwarder::initialize(CoordinateSegmentation* cseg, ObjectSegmentation* oseg, LocationService* locService, ObjectMessageQueue* omq, ServerMessageQueue* smq, LoadMonitor* lm, Proximity* prox) { mCSeg = cseg; mOSeg = oseg; mLocationService = locService; mObjectMessageQueue = omq; mServerMessageQueue =smq; mLoadMonitor = lm; mProximity = prox; } /* Sends a tick to OSeg. Receives messages from oseg. Adds them to mOutgoingQueue. */ void Forwarder::tickOSeg(const Time&t) { // getOSegMessages(); //bftm tmp, nothing // mOSeg -> tick(t,mOutgoingMessages); //objects from std::map<UUID,ServerID> updatedObjectLocations; std::map<UUID,ServerID>::iterator iter; std::map<UUID,ObjectMessageList>::iterator iterObjectsInTransit; std::map<UUID,ObjMessQBeginSendList>::iterator iterQueueMap; mOSeg->service(updatedObjectLocations); //deliver acknowledge messages. if (updatedObjectLocations.size() !=0) { // std::cout<<"\n\nbftm debug: inside of forwarder.cpp this is the number of updatedObjectLocations: "<<updatedObjectLocations.size()<<"\n\n"; } // cross-check updates against held messages. for (iter = updatedObjectLocations.begin(); iter != updatedObjectLocations.end(); ++iter) { iterObjectsInTransit = mObjectsInTransit.find(iter->first); if (iterObjectsInTransit != mObjectsInTransit.end()) { //means that we can route messages being held in mObjectsInTransit for (int s=0; s < (signed)((iterObjectsInTransit->second).size()); ++s) { // std::cout<<"\n\nbftm debug: inside of forwarder. Actually routing a message that I had saved up\n\n"; route((iterObjectsInTransit->second)[s],iter->second,false); } //remove the messages from the objects in transit mObjectsInTransit.erase(iterObjectsInTransit); } iterQueueMap = queueMap.find(iter->first); if (iterQueueMap != queueMap.end()) { //means that we have to call endSend on the message. for (int s=0; s < (signed) ((iterQueueMap->second).size()); ++ s) { mObjectMessageQueue->endSend(iterQueueMap->second[s],iter->second); //iter->second is the dest_server_id } queueMap.erase(iterQueueMap); } } } void Forwarder::service() { Time t = mContext->time; if (t - mLastSampleTime > mSampleRate) { mServerMessageQueue->reportQueueInfo(t); mLastSampleTime = t; } mLoadMonitor->service(); tickOSeg(t);//updates oseg std::deque<SelfMessage> self_messages; self_messages.swap( mSelfMessages ); while (!self_messages.empty()) { processChunk(self_messages.front().data, mContext->id, self_messages.front().forwarded); self_messages.pop_front(); } std::deque<OutgoingMessage> outgoing_messages; while(!mOutgoingMessages.empty()) { OutgoingMessage& next_msg = mOutgoingMessages.front(); bool send_success = mServerMessageQueue->addMessage(next_msg.dest, next_msg.data); if (!send_success) outgoing_messages.push_back(next_msg); mOutgoingMessages.pop_front(); } mOutgoingMessages.swap(outgoing_messages); // XXXXXXXXXXXXXXXXXXXXXX Generate noise if (GetOption(NOISE)->as<bool>()) { if (GetOption(SERVER_QUEUE)->as<String>() == "fair") { for(ServerID sid = 1; sid <= mCSeg->numServers(); sid++) { if (sid == mContext->id) continue; while(true) { NoiseMessage* noise_msg = new NoiseMessage(mContext->id, (uint32)(50 + 200*randFloat())); // FIXME control size from options? uint32 offset = 0; Network::Chunk msg_serialized; offset = noise_msg->serialize(msg_serialized, offset); bool sent_success = mServerMessageQueue->addMessage(sid, msg_serialized); if (sent_success) mContext->trace->serverDatagramQueued(mContext->time, sid, noise_msg->id(), offset); delete noise_msg; if (!sent_success) break; } } } else { // For FIFO we generate for random servers because they all // share a single internal queue. uint32 nfail = 0; uint32 nservers = mCSeg->numServers(); while(nfail < nservers) { ServerID sid = randInt<uint32>(1, nservers); if (sid == mContext->id) continue; NoiseMessage* noise_msg = new NoiseMessage(mContext->id, (uint32)(50 + 200*randFloat())); // FIXME control size from options? uint32 offset = 0; Network::Chunk msg_serialized; offset = noise_msg->serialize(msg_serialized, offset); bool sent_success = mServerMessageQueue->addMessage(sid, msg_serialized); if (sent_success) mContext->trace->serverDatagramQueued(mContext->time, sid, noise_msg->id(), offset); delete noise_msg; if (!sent_success) nfail++; } } } // XXXXXXXXXXXXXXXXXXXXXXXX mObjectMessageQueue->service(); mServerMessageQueue->service(); Sirikata::Network::Chunk *c=NULL; ServerID source_server; while(mServerMessageQueue->receive(&c, &source_server)) { processChunk(*c, source_server, false); delete c; } } //bftm note: this is fine even after message overhaul. // Routing interface for servers. This is used to route messages that originate from // a server provided service, and thus don't have a source object. Messages may be destined // for either servers or objects. The second form will simply automatically do the destination // server lookup. // if forwarding is true the message will be stuck onto a queue no matter what, otherwise it may be delivered directly void Forwarder::route(Message* msg, const ServerID& dest_server, bool is_forward) { uint32 offset = 0; Network::Chunk msg_serialized; offset = msg->serialize(msg_serialized, offset); if (dest_server==mContext->id) { if (!is_forward) { mContext->trace->serverDatagramQueued(mContext->time, dest_server, msg->id(), offset); mContext->trace->serverDatagramSent(mContext->time, mContext->time, 0 , dest_server, msg->id(), offset); // self rate is infinite => start and end times are identical } else { // The more times the message goes through a forward to self loop, the more times this will record, causing an explosion // in trace size. It's probably not worth recording this information... //mContext->trace->serverDatagramQueued(mContext->time, dest_server, msg->id(), offset); } mSelfMessages.push_back( SelfMessage(msg_serialized, is_forward) ); } else { mContext->trace->serverDatagramQueued(mContext->time, dest_server, msg->id(), offset); mOutgoingMessages.push_back( OutgoingMessage(msg_serialized, dest_server) ); } delete msg; } void Forwarder::route(CBR::Protocol::Object::ObjectMessage* msg, bool is_forward) { UUID dest_obj = msg->dest_object(); // ServerID dest_server_id = lookup(dest_obj); mOSeg->lookup(dest_obj); //add message to objects in transit. // if (mObjectsInTransit[dest_obj] == null) if (mObjectsInTransit.find(dest_obj) == mObjectsInTransit.end()) { //no messages have been queued for mObjectsInTransit //add this as the beginning of a vector of message pointers. ObjectMessageList tmp; tmp.push_back(msg); mObjectsInTransit[dest_obj] = tmp; } else { //add message to queue of objects in transit. mObjectsInTransit[dest_obj].push_back(msg); } } //end what i think it should be replaced with bool Forwarder::routeObjectHostMessage(CBR::Protocol::Object::ObjectMessage* obj_msg) { // Messages destined for the space skip the object message queue and just get dispatched if (obj_msg->dest_object() == UUID::null()) { dispatchMessage(*obj_msg); delete obj_msg; return true; } ObjMessQBeginSend beginMess; bool send_success = mObjectMessageQueue->beginSend(obj_msg, beginMess); if (send_success) { mOSeg->lookup(beginMess.dest_uuid); if (queueMap.find(beginMess.dest_uuid) == queueMap.end()) { //nothing is in queueMap ObjMessQBeginSendList tmpList; tmpList.push_back(beginMess); queueMap[beginMess.dest_uuid] = tmpList; } else { queueMap[beginMess.dest_uuid].push_back(beginMess); } } return send_success; } //ewen changes. // void Forwarder::route(CBR::Protocol::Object::ObjectMessage* msg, bool is_forward) // { // UUID dest_obj = msg->dest_object(); // ServerID dest_server_id = mOSeg->lookup(dest_obj); // route(msg, dest_server_id, is_forward); // } // void Forwarder::route(CBR::Protocol::Object::ObjectMessage* msg, ServerID dest_serv, bool is_forward) { // if (dest_serv == OBJECT_IN_TRANSIT) void Forwarder::processChunk(const Network::Chunk&chunk, const ServerID& source_server, bool forwarded_self_msg) { Message* result; uint32 offset=0; do { offset = Message::deserialize(chunk,offset,&result); if (!forwarded_self_msg) mContext->trace->serverDatagramReceived(mContext->time, mContext->time, source_server, result->id(), offset); deliver(result); //if (delivered) // mContext->trace->serverDatagramReceived(mContext->time, mContext->time, source_server, result->id(), offset); }while (offset<chunk.size()); } // Delivery interface. This should be used to deliver received messages to the correct location - // the server or object it is addressed to. void Forwarder::deliver(Message* msg) { switch(msg->type()) { case MESSAGE_TYPE_OBJECT: { dispatchMessage(msg); } break; case MESSAGE_TYPE_NOISE: { NoiseMessage* noise_msg = dynamic_cast<NoiseMessage*>(msg); assert(noise_msg != NULL); delete noise_msg; } break; case MESSAGE_TYPE_MIGRATE: { dispatchMessage(msg); } break; case MESSAGE_TYPE_CSEG_CHANGE: { dispatchMessage(msg); } break; case MESSAGE_TYPE_LOAD_STATUS: { dispatchMessage(msg); } break; case MESSAGE_TYPE_OSEG_MIGRATE_MOVE: { dispatchMessage(msg); } break; case MESSAGE_TYPE_OSEG_MIGRATE_ACKNOWLEDGE: { dispatchMessage(msg); } break; case MESSAGE_TYPE_SERVER_PROX_QUERY: { dispatchMessage(msg); } break; case MESSAGE_TYPE_SERVER_PROX_RESULT: { dispatchMessage(msg); } break; case MESSAGE_TYPE_BULK_LOCATION: { dispatchMessage(msg); } break; default: assert(false); break; } } void Forwarder::receiveMessage(Message* msg) { // Forwarder only subscribes as a recipient for object messages // so it can easily check whether it can deliver directly // or needs to forward them. assert(msg->type() == MESSAGE_TYPE_OBJECT); ObjectMessage* obj_msg = dynamic_cast<ObjectMessage*>(msg); assert(obj_msg != NULL); UUID dest = obj_msg->contents.dest_object(); // Special case: Object 0 is the space itself if (dest == UUID::null()) { dispatchMessage(obj_msg->contents); return; } // Otherwise, either deliver or forward it, depending on whether the destination object is attached to this server ObjectConnection* conn = getObjectConnection(dest); if (conn != NULL) conn->deliver(obj_msg->contents); else { CBR::Protocol::Object::ObjectMessage* obj_msg_cpy = new CBR::Protocol::Object::ObjectMessage(obj_msg->contents); route(obj_msg_cpy, true); } delete msg; } // void Forwarder::forward(Message* msg, const UUID& dest_obj) // { // conn->deliver(obj_msg->contents, mContext->time); // } // else // { // CBR::Protocol::Object::ObjectMessage* obj_msg_cpy = new CBR::Protocol::Object::ObjectMessage(obj_msg->contents); // route(obj_msg_cpy, true); // } // delete msg; // } void Forwarder::route(CBR::Protocol::Object::ObjectMessage* msg, ServerID dest_serv, bool is_forward) { // Wrap it up in one of our ObjectMessages and ship it. ObjectMessage* obj_msg = new ObjectMessage(mContext->id, *msg); //turns the cbr::prot::message into just an object message. route(obj_msg, dest_serv, is_forward); delete msg; } ServerID Forwarder::lookup(const Vector3f& pos) { ServerID sid = mCSeg->lookup(pos); return sid; } void Forwarder::addObjectConnection(const UUID& dest_obj, ObjectConnection* conn) { mObjectConnections[dest_obj] = conn; mObjectMessageQueue->registerClient(dest_obj, 1); // FIXME weight? } ObjectConnection* Forwarder::removeObjectConnection(const UUID& dest_obj) { mObjectMessageQueue->unregisterClient(dest_obj); ObjectConnection* conn = mObjectConnections[dest_obj]; mObjectConnections.erase(dest_obj); return conn; } ObjectConnection* Forwarder::getObjectConnection(const UUID& dest_obj) { ObjectConnectionMap::iterator it = mObjectConnections.find(dest_obj); return (it == mObjectConnections.end()) ? NULL : it->second; } } //end namespace <|endoftext|>
<commit_before>/// JSON encoding and decoding // Encoding Lua tables to JSON strings, and decoding JSON strings to Lua tables. // @module json #include "JSON.h" #include <Poco/JSON/Parser.h> #include <Poco/JSON/Handler.h> #include <Poco/JSON/PrintHandler.h> #include <Poco/JSON/JSONException.h> #include <Poco/JSONString.h> #include <Poco/SharedPtr.h> #include "Userdata.h" #include "LuaPocoUtils.h" int luaopen_poco_json(lua_State* L) { struct LuaPoco::UserdataMethod methods[] = { { "encode", LuaPoco::JSON::encode }, { "decode", LuaPoco::JSON::decode }, { "null", LuaPoco::JSON::getNull }, { "emptyObject", LuaPoco::JSON::getEmptyObject }, { "emptyArray", LuaPoco::JSON::getEmptyArray }, { NULL, NULL} }; lua_createtable(L, 0, 5); setMetatableFunctions(L, methods); return 1; } namespace LuaPoco { char jsonNull[] = "Poco.JSON.null"; char jsonEmptyArray[] = "Poco.JSON.Empty.Array"; char jsonEmptyObject[] = "Poco.JSON.Empty.Object"; struct TableInfo { enum TableType { object, array} tableType; size_t currentArrayIndex; int tableStackIndex; }; class JsonDecoder : public Poco::JSON::Handler { public: JsonDecoder(lua_State* L) : mState(L), mBaseTop(lua_gettop(L)) {} virtual ~JsonDecoder() {} virtual void reset() { lua_settop(mState, mBaseTop); } virtual void startObject() { lua_newtable(mState); TableInfo ti = { TableInfo::TableType::object, 0, lua_gettop(mState) }; mTableQueue.push_back(ti); } virtual void endObject() { mTableQueue.pop_back(); setValue(); } virtual void startArray() { lua_newtable(mState); TableInfo ti = { TableInfo::TableType::array, 0, lua_gettop(mState) }; mTableQueue.push_back(ti); } virtual void endArray() { mTableQueue.pop_back(); setValue(); } virtual void key(const std::string& k) { // leave the key on the stack such that on a value, setValue is called to pop both off. lua_pushlstring(mState, k.c_str(), k.size()); } virtual void null() { // use sentinel value jsonNull lua_pushlightuserdata(mState, static_cast<void*>(jsonNull)); setValue(); } // based on the poco code, int and unsigned are pure virtual functions, but will never be // called as ParserImpl only uses Int64s for whatever reason. including for completeness. virtual void value(int v) { lua_Integer i = 0; if (checkSignedToLuaInteger<int>(v, i)) { lua_pushinteger(mState, static_cast<lua_Integer>(i)); setValue(); } else throw Poco::JSON::JSONException("out of range number"); } virtual void value(unsigned v) { lua_Integer i = 0; if (checkUnsignedToLuaInteger<unsigned>(v, i)) { lua_pushinteger(mState, static_cast<lua_Integer>(i)); setValue(); } else throw Poco::JSON::JSONException("out of range number"); } #if defined(POCO_HAVE_INT64) virtual void value(Poco::Int64 v) { lua_Integer i = 0; if (checkSignedToLuaInteger<Poco::Int64>(v, i)) { lua_pushinteger(mState, static_cast<lua_Integer>(i)); setValue(); } else throw Poco::JSON::JSONException("out of range number"); } virtual void value(Poco::UInt64 v) { lua_Integer i = 0; if (checkUnsignedToLuaInteger<Poco::UInt64>(v, i)) { lua_pushinteger(mState, static_cast<lua_Integer>(i)); setValue(); } else throw Poco::JSON::JSONException("out of range number"); } #endif virtual void value(const std::string& s) { lua_pushlstring(mState, s.c_str(), s.size()); setValue(); } virtual void value(double d) { lua_pushnumber(mState, static_cast<lua_Number>(d)); setValue(); } virtual void value(bool b) { lua_pushboolean(mState, static_cast<int>(b)); setValue(); } private: // utility functions void setValue() { if (mTableQueue.size() > 0) { TableInfo& ti = mTableQueue.back(); if (ti.tableType == TableInfo::TableType::array) { ++ti.currentArrayIndex; lua_rawseti(mState, ti.tableStackIndex, ti.currentArrayIndex); } else { const char *tn = lua_typename(mState, lua_type(mState, -1)); lua_rawset(mState, ti.tableStackIndex); } } else { // the last value is a table that should be left behind and returned. if (lua_type(mState, -1) != LUA_TTABLE) throw Poco::JSON::JSONException("attempt to set a value when no objects present"); } } lua_State* mState; int mBaseTop; std::vector<TableInfo> mTableQueue; }; class TableEncoder { public: TableEncoder(lua_State* L, unsigned indent) : mState(L), mStream(), mPrintHandler(mStream, indent) {} ~TableEncoder() {} bool encode() { handleTable(); while (mTableQueue.size() > 0) { TableInfo& ti = mTableQueue.back(); if (ti.tableType == TableInfo::TableType::array) { lua_rawgeti(mState, ti.tableStackIndex, ++ti.currentArrayIndex); if (!lua_isnil(mState, -1)) { handleValue(); } else { // pop nil, array lua_pop(mState, 2); mTableQueue.pop_back(); mPrintHandler.endArray(); } } else { // handleTable() leaves nil on the stack to for the nested table iteration. if (lua_next(mState, ti.tableStackIndex)) { if (lua_isstring(mState, -2)) { const char* key = lua_tostring(mState, -2); mPrintHandler.key(key); handleValue(); } else throw Poco::JSON::JSONException("encountered key value that is not a string."); } else { // done with object, pop it. lua_pop(mState, 1); mTableQueue.pop_back(); mPrintHandler.endObject(); } } } std::string jsonString = mStream.str(); lua_pushlstring(mState, jsonString.c_str(), jsonString.size()); // return all pending tables were processed return mTableQueue.empty(); } private: // arrays are defined as tables that operate as sequences from 1 to n with [n + 1] == nil to terminate. // objects are defined as not having an array part, and only string keys being present. bool isArray(int index) { lua_rawgeti(mState, index, 1); bool result = !lua_isnil(mState, -1); lua_pop(mState, 1); return result; } void handleTable() { // store table information in mQueue. TableInfo ti = { isArray(-1) ? TableInfo::TableType::array : TableInfo::TableType::object, 0, lua_gettop(mState) }; mTableQueue.push_back(ti); // leave key on the top of the stack so the loop can process it with calls to lua_next. // inform printer of the start of a new object/array. if (ti.tableType == TableInfo::TableType::object) { mPrintHandler.startObject(); lua_pushnil(mState); } else { mPrintHandler.startArray(); } } void handleValue() { int type = lua_type(mState, -1); switch (type) { case LUA_TNIL: throw Poco::JSON::JSONException("nil is an invalid value, use json.null"); break; case LUA_TNUMBER: #if LUA_VERSION_NUM > 502 if (lua_isinteger(mState, -1)) { lua_Integer i = lua_tointeger(mState, -1); mPrintHandler.value(i); } else #endif { lua_Number n = lua_tonumber(mState, -1); mPrintHandler.value(n); } break; case LUA_TBOOLEAN: { bool b = static_cast<bool>(lua_toboolean(mState, -1)); mPrintHandler.value(b); break; } case LUA_TSTRING: { const std::string str = lua_tostring(mState, -1); mPrintHandler.value(str); break; } case LUA_TTABLE: handleTable(); // the table value must stay on the top of the stack in order to be iterated by // encode loop. when the end of the table is encountered, it is popped. // returning here avoids the pop that is needed for all other values. return; break; case LUA_TFUNCTION: throw Poco::JSON::JSONException("function type invalid for json."); break; case LUA_TUSERDATA: throw Poco::JSON::JSONException("userdata type invalid for json."); break; case LUA_TTHREAD: throw Poco::JSON::JSONException("thread type invalid for json."); break; case LUA_TLIGHTUSERDATA: { const char *lud = static_cast<const char*>(lua_touserdata(mState, -1)); if (lud == jsonNull) { mPrintHandler.null(); } else if (lud == jsonEmptyArray) { mPrintHandler.startArray(); mPrintHandler.endArray(); } else if (lud == jsonEmptyObject) { mPrintHandler.startObject(); mPrintHandler.endObject(); } else throw Poco::JSON::JSONException("unknown json lightuserdata value."); break; } default: throw Poco::JSON::JSONException("unknown value for json conversion."); break; } // all values except for table needs to be popped. // the table case returns early to avoid this pop. lua_pop(mState, 1); } lua_State* mState; std::stringstream mStream; Poco::JSON::PrintHandler mPrintHandler; std::vector<TableInfo> mTableQueue; }; /// encodes a table into a JSON string. // @table table to encode // @return value as string or nil. (error) // @return error message. // @function encode int JSON::encode(lua_State* L) { int rv = 0; unsigned indent = 0; luaL_checktype(L, 1, LUA_TTABLE); if (lua_isnumber(L, 2)) { indent = static_cast<unsigned>(lua_tointeger(L, 2)); } // TableEncoder expects the table it is encoding at the top of the stack. lua_pushvalue(L, 1); try { TableEncoder te(L, indent); // either a string is returned at the top of the stack // or nil, errmsg if (te.encode()) { rv = 1; } else { rv = 2; } } catch (const Poco::Exception& e) { rv = pushPocoException(L, e); } catch (...) { rv = pushUnknownException(L); } return rv; } /// decodes a JSON string into a table. // @string JSON encoded string // @return table or nil. (error) // @return error message. // @function decode int JSON::decode(lua_State* L) { int rv = 0; const char* jss = luaL_checkstring(L, 1); try { Poco::SharedPtr<JsonDecoder> lh(new JsonDecoder(L)); Poco::JSON::Parser jsonParser(lh); jsonParser.parse(jss); rv = 1; } catch (const Poco::Exception& e) { rv = pushPocoException(L, e); } catch (...) { rv = pushUnknownException(L); } return rv; } /// returns the 'null' sentinel value as a lightuserdata. // @return lightuserdata // @function null int JSON::getNull(lua_State* L) { lua_pushlightuserdata(L, static_cast<void*>(jsonNull)); return 1; } /// returns the 'emptyObject' sentinel value as a lightuserdata. // @return lightuserdata // @function emptyObject int JSON::getEmptyObject(lua_State* L) { lua_pushlightuserdata(L, static_cast<void*>(jsonEmptyObject)); return 1; } /// returns the 'emptyArray' sentinel value as a lightuserdata. // @return lightuserdata // @function emptyArray int JSON::getEmptyArray(lua_State* L) { lua_pushlightuserdata(L, static_cast<void*>(jsonEmptyArray)); return 1; } } // LuaPoco <commit_msg>fix JSON LDoc table parameter from @table to @tab<commit_after>/// JSON encoding and decoding // Encoding Lua tables to JSON strings, and decoding JSON strings to Lua tables. // @module json #include "JSON.h" #include <Poco/JSON/Parser.h> #include <Poco/JSON/Handler.h> #include <Poco/JSON/PrintHandler.h> #include <Poco/JSON/JSONException.h> #include <Poco/JSONString.h> #include <Poco/SharedPtr.h> #include "Userdata.h" #include "LuaPocoUtils.h" int luaopen_poco_json(lua_State* L) { struct LuaPoco::UserdataMethod methods[] = { { "encode", LuaPoco::JSON::encode }, { "decode", LuaPoco::JSON::decode }, { "null", LuaPoco::JSON::getNull }, { "emptyObject", LuaPoco::JSON::getEmptyObject }, { "emptyArray", LuaPoco::JSON::getEmptyArray }, { NULL, NULL} }; lua_createtable(L, 0, 5); setMetatableFunctions(L, methods); return 1; } namespace LuaPoco { char jsonNull[] = "Poco.JSON.null"; char jsonEmptyArray[] = "Poco.JSON.Empty.Array"; char jsonEmptyObject[] = "Poco.JSON.Empty.Object"; struct TableInfo { enum TableType { object, array} tableType; size_t currentArrayIndex; int tableStackIndex; }; class JsonDecoder : public Poco::JSON::Handler { public: JsonDecoder(lua_State* L) : mState(L), mBaseTop(lua_gettop(L)) {} virtual ~JsonDecoder() {} virtual void reset() { lua_settop(mState, mBaseTop); } virtual void startObject() { lua_newtable(mState); TableInfo ti = { TableInfo::TableType::object, 0, lua_gettop(mState) }; mTableQueue.push_back(ti); } virtual void endObject() { mTableQueue.pop_back(); setValue(); } virtual void startArray() { lua_newtable(mState); TableInfo ti = { TableInfo::TableType::array, 0, lua_gettop(mState) }; mTableQueue.push_back(ti); } virtual void endArray() { mTableQueue.pop_back(); setValue(); } virtual void key(const std::string& k) { // leave the key on the stack such that on a value, setValue is called to pop both off. lua_pushlstring(mState, k.c_str(), k.size()); } virtual void null() { // use sentinel value jsonNull lua_pushlightuserdata(mState, static_cast<void*>(jsonNull)); setValue(); } // based on the poco code, int and unsigned are pure virtual functions, but will never be // called as ParserImpl only uses Int64s for whatever reason. including for completeness. virtual void value(int v) { lua_Integer i = 0; if (checkSignedToLuaInteger<int>(v, i)) { lua_pushinteger(mState, static_cast<lua_Integer>(i)); setValue(); } else throw Poco::JSON::JSONException("out of range number"); } virtual void value(unsigned v) { lua_Integer i = 0; if (checkUnsignedToLuaInteger<unsigned>(v, i)) { lua_pushinteger(mState, static_cast<lua_Integer>(i)); setValue(); } else throw Poco::JSON::JSONException("out of range number"); } #if defined(POCO_HAVE_INT64) virtual void value(Poco::Int64 v) { lua_Integer i = 0; if (checkSignedToLuaInteger<Poco::Int64>(v, i)) { lua_pushinteger(mState, static_cast<lua_Integer>(i)); setValue(); } else throw Poco::JSON::JSONException("out of range number"); } virtual void value(Poco::UInt64 v) { lua_Integer i = 0; if (checkUnsignedToLuaInteger<Poco::UInt64>(v, i)) { lua_pushinteger(mState, static_cast<lua_Integer>(i)); setValue(); } else throw Poco::JSON::JSONException("out of range number"); } #endif virtual void value(const std::string& s) { lua_pushlstring(mState, s.c_str(), s.size()); setValue(); } virtual void value(double d) { lua_pushnumber(mState, static_cast<lua_Number>(d)); setValue(); } virtual void value(bool b) { lua_pushboolean(mState, static_cast<int>(b)); setValue(); } private: // utility functions void setValue() { if (mTableQueue.size() > 0) { TableInfo& ti = mTableQueue.back(); if (ti.tableType == TableInfo::TableType::array) { ++ti.currentArrayIndex; lua_rawseti(mState, ti.tableStackIndex, ti.currentArrayIndex); } else { const char *tn = lua_typename(mState, lua_type(mState, -1)); lua_rawset(mState, ti.tableStackIndex); } } else { // the last value is a table that should be left behind and returned. if (lua_type(mState, -1) != LUA_TTABLE) throw Poco::JSON::JSONException("attempt to set a value when no objects present"); } } lua_State* mState; int mBaseTop; std::vector<TableInfo> mTableQueue; }; class TableEncoder { public: TableEncoder(lua_State* L, unsigned indent) : mState(L), mStream(), mPrintHandler(mStream, indent) {} ~TableEncoder() {} bool encode() { handleTable(); while (mTableQueue.size() > 0) { TableInfo& ti = mTableQueue.back(); if (ti.tableType == TableInfo::TableType::array) { lua_rawgeti(mState, ti.tableStackIndex, ++ti.currentArrayIndex); if (!lua_isnil(mState, -1)) { handleValue(); } else { // pop nil, array lua_pop(mState, 2); mTableQueue.pop_back(); mPrintHandler.endArray(); } } else { // handleTable() leaves nil on the stack to for the nested table iteration. if (lua_next(mState, ti.tableStackIndex)) { if (lua_isstring(mState, -2)) { const char* key = lua_tostring(mState, -2); mPrintHandler.key(key); handleValue(); } else throw Poco::JSON::JSONException("encountered key value that is not a string."); } else { // done with object, pop it. lua_pop(mState, 1); mTableQueue.pop_back(); mPrintHandler.endObject(); } } } std::string jsonString = mStream.str(); lua_pushlstring(mState, jsonString.c_str(), jsonString.size()); // return all pending tables were processed return mTableQueue.empty(); } private: // arrays are defined as tables that operate as sequences from 1 to n with [n + 1] == nil to terminate. // objects are defined as not having an array part, and only string keys being present. bool isArray(int index) { lua_rawgeti(mState, index, 1); bool result = !lua_isnil(mState, -1); lua_pop(mState, 1); return result; } void handleTable() { // store table information in mQueue. TableInfo ti = { isArray(-1) ? TableInfo::TableType::array : TableInfo::TableType::object, 0, lua_gettop(mState) }; mTableQueue.push_back(ti); // leave key on the top of the stack so the loop can process it with calls to lua_next. // inform printer of the start of a new object/array. if (ti.tableType == TableInfo::TableType::object) { mPrintHandler.startObject(); lua_pushnil(mState); } else { mPrintHandler.startArray(); } } void handleValue() { int type = lua_type(mState, -1); switch (type) { case LUA_TNIL: throw Poco::JSON::JSONException("nil is an invalid value, use json.null"); break; case LUA_TNUMBER: #if LUA_VERSION_NUM > 502 if (lua_isinteger(mState, -1)) { lua_Integer i = lua_tointeger(mState, -1); mPrintHandler.value(i); } else #endif { lua_Number n = lua_tonumber(mState, -1); mPrintHandler.value(n); } break; case LUA_TBOOLEAN: { bool b = static_cast<bool>(lua_toboolean(mState, -1)); mPrintHandler.value(b); break; } case LUA_TSTRING: { const std::string str = lua_tostring(mState, -1); mPrintHandler.value(str); break; } case LUA_TTABLE: handleTable(); // the table value must stay on the top of the stack in order to be iterated by // encode loop. when the end of the table is encountered, it is popped. // returning here avoids the pop that is needed for all other values. return; break; case LUA_TFUNCTION: throw Poco::JSON::JSONException("function type invalid for json."); break; case LUA_TUSERDATA: throw Poco::JSON::JSONException("userdata type invalid for json."); break; case LUA_TTHREAD: throw Poco::JSON::JSONException("thread type invalid for json."); break; case LUA_TLIGHTUSERDATA: { const char *lud = static_cast<const char*>(lua_touserdata(mState, -1)); if (lud == jsonNull) { mPrintHandler.null(); } else if (lud == jsonEmptyArray) { mPrintHandler.startArray(); mPrintHandler.endArray(); } else if (lud == jsonEmptyObject) { mPrintHandler.startObject(); mPrintHandler.endObject(); } else throw Poco::JSON::JSONException("unknown json lightuserdata value."); break; } default: throw Poco::JSON::JSONException("unknown value for json conversion."); break; } // all values except for table needs to be popped. // the table case returns early to avoid this pop. lua_pop(mState, 1); } lua_State* mState; std::stringstream mStream; Poco::JSON::PrintHandler mPrintHandler; std::vector<TableInfo> mTableQueue; }; /// encodes a table into a JSON string. // @tab table to encode // @return value as string or nil. (error) // @return error message. // @function encode int JSON::encode(lua_State* L) { int rv = 0; unsigned indent = 0; luaL_checktype(L, 1, LUA_TTABLE); if (lua_isnumber(L, 2)) { indent = static_cast<unsigned>(lua_tointeger(L, 2)); } // TableEncoder expects the table it is encoding at the top of the stack. lua_pushvalue(L, 1); try { TableEncoder te(L, indent); // either a string is returned at the top of the stack // or nil, errmsg if (te.encode()) { rv = 1; } else { rv = 2; } } catch (const Poco::Exception& e) { rv = pushPocoException(L, e); } catch (...) { rv = pushUnknownException(L); } return rv; } /// decodes a JSON string into a table. // @string JSON encoded string // @return table or nil. (error) // @return error message. // @function decode int JSON::decode(lua_State* L) { int rv = 0; const char* jss = luaL_checkstring(L, 1); try { Poco::SharedPtr<JsonDecoder> lh(new JsonDecoder(L)); Poco::JSON::Parser jsonParser(lh); jsonParser.parse(jss); rv = 1; } catch (const Poco::Exception& e) { rv = pushPocoException(L, e); } catch (...) { rv = pushUnknownException(L); } return rv; } /// returns the 'null' sentinel value as a lightuserdata. // @return lightuserdata // @function null int JSON::getNull(lua_State* L) { lua_pushlightuserdata(L, static_cast<void*>(jsonNull)); return 1; } /// returns the 'emptyObject' sentinel value as a lightuserdata. // @return lightuserdata // @function emptyObject int JSON::getEmptyObject(lua_State* L) { lua_pushlightuserdata(L, static_cast<void*>(jsonEmptyObject)); return 1; } /// returns the 'emptyArray' sentinel value as a lightuserdata. // @return lightuserdata // @function emptyArray int JSON::getEmptyArray(lua_State* L) { lua_pushlightuserdata(L, static_cast<void*>(jsonEmptyArray)); return 1; } } // LuaPoco <|endoftext|>
<commit_before>#include "MPPreview.h" MPPreview::MPPreview(int ideaID) : BWindow(BRect(100, 100, 900, 700), "tmp", B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS, B_CURRENT_WORKSPACE) { // initialize controls BRect r = Bounds(); r.bottom = r.bottom - 50; previewTextView = new BTextView(r, NULL, r, B_FOLLOW_ALL, B_WILL_DRAW); previewTextView->SetStylable(true); previewTextView->MakeEditable(false); previewTextView->MakeSelectable(true); previewTextView->MakeResizable(true); backView = new BView(Bounds(), "backview", B_FOLLOW_ALL, B_WILL_DRAW); backView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR)); AddChild(backView); // gui layout builder backView->SetLayout(new BGroupLayout(B_HORIZONTAL, 0.0)); backView->AddChild(BGridLayoutBuilder() .Add(new BScrollView("scroll_editor", previewTextView, B_FOLLOW_ALL_SIDES, 0, false, true, B_FANCY_BORDER), 0, 0) .SetInsets(0, 0, 0, 0) ); currentideaID = ideaID; // pass current idea id selected to editor window for use if(currentideaID != -1) // if id has a real value { sqlObject = new SqlObject(ideaStatement, "7"); sqlObject->PrepareSql("select ideatext, ideaname, ismp from ideatable where ideaid = ?"); sqlObject->BindValue(1, currentideaID); sqlObject->StepSql(); if(sqlObject->ReturnInt(2) == 0) // thought was selected to preview { rawText = sqlObject->ReturnText(0); previewTextView->SetText(rawText); BString tmpText; tmpText = "MasterPiece Preview - "; tmpText += sqlObject->ReturnText(1); this->SetTitle(tmpText); IdeaParser(rawText, previewTextView); // parse rawText here.... // getfontandcolor, store it, modify it, then setfontandcolor // ParseRawText(rawText, previewTextView); /* { previewTextView->InsertText(parsed lines); BEST METHOD MIGHT BE TO SETTEXT IN PREVIEWTEXTVIEW, THEN SELECT THE TEXT AND PARSE ACCORDINGLY USING SETFONTANDCOLOR } */ // display text in previewTextView such as... } else if(sqlObject->ReturnInt(2) == 1) // masterpiece was selected to preview { // sql query to get all thoughts // parse rawText for each thought and call insert to previewtextview here.... } sqlObject->FinalizeSql(); sqlObject->CloseSql(); } } /* void GetFontAndColor(BFont *font, uint32 *sameProperties, rgb_color *color = NULL, bool *sameColor = NULL) void SetFontAndColor(const BFont *font, uint32 properties = B_FONT_ALL, rgb_color *color = NULL) BFont font; uint32 sameProperties; theTextView->GetFontAndColor(&font, &sameProperties); font.SetSize(24.0); theTextView->SetFontAndColor(&font, B_FONT_ALL); BFont theBigFont(be_plain_font); theBigFont.SetSize(48.0); theBigFont.SetRotation(-45.0); theBigFont.SetShear(120.0); theTextView->SetFontAndColor(&theBigFont, B_FONT_SIZE); BFont font; uint32 sameProperties; rgb_color redColor = {255, 0, 0, 255}; theTextView->GetFontAndColor(&font, &sameProperties); theTextView->SetFontAndColor(&font, B_FONT_ALL, &redColor); */ void MPPreview::IdeaParser(BString inputText, BTextView* displayTextView) { displayTextView->SelectAll(); displayTextView->GetSelection(&startPos, &endPos); displayTextView->GetFontAndColor(&parseFont, &sameProperties); parseFont.SetSize(24.0); displayTextView->SetFontAndColor(startPos, endPos, &parseFont, B_FONT_SIZE); // create parser here //return displayTextView; // TEST REGEX PARSER - this works and handles the parser conversion from BString to C string and back... /* string s; int i; pcrecpp::RE re("(\\w+):(\\d+)"); re.FullMatch("ruby:1234 ruby:123", &s, &i); printf("\r\n%d\r\n", i); reTester = s.c_str(); eAlert = new ErrorAlert(reTester); eAlert->Launch(); s = "yabba dabba doo"; pcrecpp::RE("b+").GlobalReplace("d", &s); eAlert = new ErrorAlert(s.c_str()); eAlert->Launch(); */ // TEST REGEX PARSER } void MPPreview::MessageReceived(BMessage* msg) { switch(msg->what) { default: { BWindow::MessageReceived(msg); break; } } } bool MPPreview::QuitRequested(void) { return true; } <commit_msg>trying to figure out the right method for parsing and adding style's... without knowing the highlighted bits. can probably figure out a way to do a word processor using this parsing method.<commit_after>#include "MPPreview.h" MPPreview::MPPreview(int ideaID) : BWindow(BRect(100, 100, 900, 700), "tmp", B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS, B_CURRENT_WORKSPACE) { // initialize controls BRect r = Bounds(); r.bottom = r.bottom - 50; previewTextView = new BTextView(r, NULL, r, B_FOLLOW_ALL, B_WILL_DRAW); previewTextView->SetStylable(true); previewTextView->MakeEditable(false); previewTextView->MakeSelectable(true); previewTextView->MakeResizable(true); backView = new BView(Bounds(), "backview", B_FOLLOW_ALL, B_WILL_DRAW); backView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR)); AddChild(backView); // gui layout builder backView->SetLayout(new BGroupLayout(B_HORIZONTAL, 0.0)); backView->AddChild(BGridLayoutBuilder() .Add(new BScrollView("scroll_editor", previewTextView, B_FOLLOW_ALL_SIDES, 0, false, true, B_FANCY_BORDER), 0, 0) .SetInsets(0, 0, 0, 0) ); currentideaID = ideaID; // pass current idea id selected to editor window for use if(currentideaID != -1) // if id has a real value { sqlObject = new SqlObject(ideaStatement, "7"); sqlObject->PrepareSql("select ideatext, ideaname, ismp from ideatable where ideaid = ?"); sqlObject->BindValue(1, currentideaID); sqlObject->StepSql(); if(sqlObject->ReturnInt(2) == 0) // thought was selected to preview { rawText = sqlObject->ReturnText(0); previewTextView->SetText(rawText); BString tmpText; tmpText = "MasterPiece Preview - "; tmpText += sqlObject->ReturnText(1); this->SetTitle(tmpText); IdeaParser(rawText, previewTextView); // parse rawText here.... // getfontandcolor, store it, modify it, then setfontandcolor // ParseRawText(rawText, previewTextView); /* { previewTextView->InsertText(parsed lines); BEST METHOD MIGHT BE TO SETTEXT IN PREVIEWTEXTVIEW, THEN SELECT THE TEXT AND PARSE ACCORDINGLY USING SETFONTANDCOLOR } */ // display text in previewTextView such as... } else if(sqlObject->ReturnInt(2) == 1) // masterpiece was selected to preview { // sql query to get all thoughts // parse rawText for each thought and call insert to previewtextview here.... } sqlObject->FinalizeSql(); sqlObject->CloseSql(); } } /* void GetFontAndColor(BFont *font, uint32 *sameProperties, rgb_color *color = NULL, bool *sameColor = NULL) void SetFontAndColor(const BFont *font, uint32 properties = B_FONT_ALL, rgb_color *color = NULL) BFont font; uint32 sameProperties; theTextView->GetFontAndColor(&font, &sameProperties); font.SetSize(24.0); theTextView->SetFontAndColor(&font, B_FONT_ALL); BFont theBigFont(be_plain_font); theBigFont.SetSize(48.0); theBigFont.SetRotation(-45.0); theBigFont.SetShear(120.0); theTextView->SetFontAndColor(&theBigFont, B_FONT_SIZE); BFont font; uint32 sameProperties; rgb_color redColor = {255, 0, 0, 255}; theTextView->GetFontAndColor(&font, &sameProperties); theTextView->SetFontAndColor(&font, B_FONT_ALL, &redColor); */ void MPPreview::IdeaParser(BString inputText, BTextView* displayTextView) { displayTextView->SelectAll(); displayTextView->GetSelection(&startPos, &endPos); displayTextView->GetFontAndColor(&parseFont, &sameProperties); parseFont.SetSize(24.0); displayTextView->SetFontAndColor(startPos, endPos, &parseFont, B_FONT_SIZE); // create parser here //return displayTextView; // TEST REGEX PARSER - this works and handles the parser conversion from BString to C string and back... /* string s; int i; pcrecpp::RE re("(\\w+):(\\d+)"); re.FullMatch("ruby:1234 ruby:123", &s, &i); printf("\r\n%d\r\n", i); reTester = s.c_str(); eAlert = new ErrorAlert(reTester); eAlert->Launch(); s = "yabba dabba doo"; pcrecpp::RE("b+").GlobalReplace("d", &s); eAlert = new ErrorAlert(s.c_str()); eAlert->Launch(); */ // TEST REGEX PARSER // 1. it seems to do this, i will need to copy the string from the textview // 2. split the string into substrings based on the parsing... // 3. get the start/finish offsets of the string based on the parsing // 4. then do the style applications to the selected string lengths based on parser values } void MPPreview::MessageReceived(BMessage* msg) { switch(msg->what) { default: { BWindow::MessageReceived(msg); break; } } } bool MPPreview::QuitRequested(void) { return true; } <|endoftext|>
<commit_before>#ifndef MATH_HPP #define MATH_HPP #include <cmath> namespace swift { namespace math { constexpr float PI = 3.14159265359; /* vector math */ template<typename T> T magnitude(const sf::Vector2<T>& vec) { return std::sqrt(vec.x * vec.x + vec.y * vec.y); } template<typename T> sf::Vector2<T> unit(const sf::Vector2<T>& vec) { T mag = magnitude(vec); if(mag == 0) return {0, 0}; return vec / mag; } template<typename T> T dot(const sf::Vector2<T>& one, const sf::Vector2<T>& two) { return one.x * two.x + one.y * two.y; } // projection of one onto two template<typename T> T projection(const sf::Vector2<T>& one, const sf::Vector2<T>& two) { return dot(one, unit(two)); } template<typename T> sf::Vector2<T> normalY(const sf::Vector2<T>& vec) { sf::Vector2<T> nonNormalized(-vec.y, vec.x); return unit(nonNormalized); } template<typename T> sf::Vector2<T> normalX(const sf::Vector2<T>& vec) { sf::Vector2<T> nonNormalized(vec.y, -vec.x); return unit(nonNormalized); } /* distance math */ template<typename T> T distance(const sf::Vector2<T>& one, const sf::Vector2<T>& two) { return std::sqrt((two.x - one.x) * (two.x - one.x) + (two.y - one.y) * (two.y - one.y)); } template<typename T> T distanceSquared(const sf::Vector2<T>& one, const sf::Vector2<T>& two) { return (two.x - one.x) * (two.x - one.x) + (two.y - one.y) * (two.y - one.y); } } } #endif // MATH_HPP <commit_msg>Added lerp function<commit_after>#ifndef MATH_HPP #define MATH_HPP #include <cmath> namespace swift { namespace math { constexpr float PI = 3.14159265359; /* vector math */ template<typename T> T magnitude(const sf::Vector2<T>& vec) { return std::sqrt(vec.x * vec.x + vec.y * vec.y); } template<typename T> sf::Vector2<T> unit(const sf::Vector2<T>& vec) { T mag = magnitude(vec); if(mag == 0) return {0, 0}; return vec / mag; } template<typename T> T dot(const sf::Vector2<T>& one, const sf::Vector2<T>& two) { return one.x * two.x + one.y * two.y; } // projection of one onto two template<typename T> T projection(const sf::Vector2<T>& one, const sf::Vector2<T>& two) { return dot(one, unit(two)); } template<typename T> sf::Vector2<T> normalY(const sf::Vector2<T>& vec) { sf::Vector2<T> nonNormalized(-vec.y, vec.x); return unit(nonNormalized); } template<typename T> sf::Vector2<T> normalX(const sf::Vector2<T>& vec) { sf::Vector2<T> nonNormalized(vec.y, -vec.x); return unit(nonNormalized); } /* distance math */ template<typename T> T distance(const sf::Vector2<T>& one, const sf::Vector2<T>& two) { return std::sqrt((two.x - one.x) * (two.x - one.x) + (two.y - one.y) * (two.y - one.y)); } template<typename T> T distanceSquared(const sf::Vector2<T>& one, const sf::Vector2<T>& two) { return (two.x - one.x) * (two.x - one.x) + (two.y - one.y) * (two.y - one.y); } template<typename T> T lerp(T p0, T p1, double w) { return (1.f - w) * p0 + w * p1; } } } #endif // MATH_HPP <|endoftext|>
<commit_before>/* * PNG_codec.cpp * C++ Wrapper around libpng, providing encoding and decoding functions * * (C)Lucian Plesea 2016-2017 */ #include "mod_reproject.h" #include <png.h> #include <vector> // TODO: Add palette PNG support, possibly other fancy options // Memory output doesn't need flushing static void flush_png(png_structp) {}; // Do nothing for warnings static void pngWH(png_struct *pngp, png_const_charp message) { }; // Error function static void pngEH(png_struct *pngp, png_const_charp message) { codec_params *params = (codec_params *)(png_get_error_ptr(pngp)); strncpy(params->error_message, message, 1024); longjmp(png_jmpbuf(pngp), 1); } // Read memory handler for PNG static void get_data(png_structp pngp, png_bytep data, png_size_t length) { storage_manager *src = static_cast<storage_manager *>(png_get_io_ptr(pngp)); if (static_cast<png_size_t>(src->size) < length) { codec_params *params = (codec_params *)(png_get_error_ptr(pngp)); strcpy(params->error_message, "PNG decode expects more data than given"); longjmp(png_jmpbuf(pngp), 1); } memcpy(data, src->buffer, length); src->buffer += length; src->size -= length; } // Write memory handler for PNG static void store_data(png_structp pngp, png_bytep data, png_size_t length) { storage_manager *dst = static_cast<storage_manager *>(png_get_io_ptr(pngp)); if (static_cast<png_size_t>(dst->size) < length) { codec_params *params = (codec_params *)(png_get_error_ptr(pngp)); strcpy(params->error_message, "PNG encode buffer overflow"); longjmp(png_jmpbuf(pngp), 1); } memcpy(dst->buffer, data, length); dst->buffer += length; dst->size -= length; } const char *png_stride_decode(codec_params &params, const TiledRaster &raster, storage_manager &src, void *buffer) { png_structp pngp = NULL; png_infop infop = NULL; std::vector<png_bytep> png_rowp(static_cast<int>(raster.pagesize.y)); for (size_t i = 0; i < png_rowp.size(); i++) // line_stride is always in bytes png_rowp[i] = reinterpret_cast<png_bytep>( static_cast<char *>(buffer)+i * params.line_stride); png_uint_32 width, height; int bit_depth, ct; pngp = png_create_read_struct(PNG_LIBPNG_VER_STRING, &params, pngEH, pngEH); if (!pngp) return "PNG decode error while creating PNG structure"; infop = png_create_info_struct(pngp); if (!infop) return "PNG decode error while creating info structure"; if (setjmp(png_jmpbuf(pngp))) // This is the error return return params.error_message; png_set_read_fn(pngp, &src, get_data); png_read_info(pngp, infop); // TODO: Decode to expected format // png_set_palette_to_rgb(pngp); // Palette to RGB // png_set_tRNS_to_alpha(pngp); // transparency palette to Alpha // png_set_add_alpha(pngp, 255, PNG_FILLER_AFTER); // Add alpha if not there // png_read_update_info(pngp, infop); // update the reader // TODO: Check that it matches the expected raster png_get_IHDR(pngp, infop, &width, &height, &bit_depth, &ct, NULL, NULL, NULL); if (static_cast<png_uint_32>(raster.pagesize.y) != height || static_cast<png_uint_32>(raster.pagesize.x) != width) { strcpy(params.error_message, "Input PNG has the wrong size"); longjmp(png_jmpbuf(pngp), 1); } if (png_get_rowbytes(pngp, infop) != params.line_stride) { strcpy(params.error_message, "Input PNG has the wrong type"); longjmp(png_jmpbuf(pngp), 1); } png_read_image(pngp, png_rowp.data()); png_read_end(pngp, infop); png_destroy_read_struct(&pngp, &infop, 0); // setjmp no longer active, don't call any png functions if (bit_depth == 16) for (size_t i = 0; i < png_rowp.size(); i++) { unsigned short int*p = reinterpret_cast<unsigned short int *>(png_rowp[i]); // Swap bytes to host order, in place, on little endian hosts for (int j = 0; j < raster.pagesize.x; j++, p++) *p = ntoh16(*p); } return NULL; } const char *png_encode(png_params *params, const TiledRaster &raster, storage_manager &src, storage_manager &dst) { png_structp pngp = NULL; png_infop infop = NULL; png_uint_32 width = static_cast<png_uint_32>(raster.pagesize.x); png_uint_32 height = static_cast<png_uint_32>(raster.pagesize.y); // Use a vector so it cleans up itself std::vector<png_bytep> png_rowp(height); int rowbytes = 0; // To avoid changing the buffer pointer storage_manager mgr = dst; pngp = png_create_write_struct(PNG_LIBPNG_VER_STRING, params, pngEH, pngWH); if (!pngp) return "PNG encode error while creating PNG structure"; if (setjmp(png_jmpbuf(pngp))) // This is the error return return params->error_message; infop = png_create_info_struct(pngp); if (!infop) return "PNG encode error while creating info structure"; png_set_write_fn(pngp, &mgr, store_data, flush_png); png_set_IHDR(pngp, infop, width, height, params->bit_depth, params->color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_set_compression_level(pngp, params->compression_level); if (params->has_transparency) { // TODO: Pass the transparent value via params // For now, 0 is the no data value, regardless of type of data png_color_16 tcolor; memset(&tcolor, 0, sizeof(tcolor)); png_set_tRNS(pngp, infop, 0, 0, &tcolor); } rowbytes = png_get_rowbytes(pngp, infop); // Initialize the row pointers and swap bytes if the input is 16 bit for (size_t i = 0; i < png_rowp.size(); i++) { png_rowp[i] = reinterpret_cast<png_bytep>(src.buffer + i * rowbytes); if (params->bit_depth == 16) { unsigned short int*p = reinterpret_cast<unsigned short int *>(png_rowp[i]); // Swap bytes to net order, in place for (int j = 0; j < rowbytes / 2; j++, p++) *p = hton16(*p); } } png_write_info(pngp, infop); png_write_image(pngp, png_rowp.data()); png_write_end(pngp, infop); png_destroy_write_struct(&pngp, &infop); dst.size -= mgr.size; // mgr.size is bytes left return NULL; } int set_png_params(const TiledRaster &raster, png_params *params) { // Pick some defaults params->bit_depth = 8; params->compression_level = 6; params->has_transparency = FALSE; switch (raster.pagesize.c) { case 1: params->color_type = PNG_COLOR_TYPE_GRAY; break; case 2: params->color_type = PNG_COLOR_TYPE_GA; break; case 3: params->color_type = PNG_COLOR_TYPE_RGB; break; case 4: params->color_type = PNG_COLOR_TYPE_RGBA; break; } if (raster.datatype != GDT_Byte) params->bit_depth = 16; // PNG only handles 8 or 16 bits return APR_SUCCESS; } <commit_msg>Fix type check<commit_after>/* * PNG_codec.cpp * C++ Wrapper around libpng, providing encoding and decoding functions * * (C)Lucian Plesea 2016-2017 */ #include "mod_reproject.h" #include <png.h> #include <vector> // TODO: Add palette PNG support, possibly other fancy options // Memory output doesn't need flushing static void flush_png(png_structp) {}; // Do nothing for warnings static void pngWH(png_struct *pngp, png_const_charp message) { }; // Error function static void pngEH(png_struct *pngp, png_const_charp message) { codec_params *params = (codec_params *)(png_get_error_ptr(pngp)); strncpy(params->error_message, message, 1024); longjmp(png_jmpbuf(pngp), 1); } // Read memory handler for PNG static void get_data(png_structp pngp, png_bytep data, png_size_t length) { storage_manager *src = static_cast<storage_manager *>(png_get_io_ptr(pngp)); if (static_cast<png_size_t>(src->size) < length) { codec_params *params = (codec_params *)(png_get_error_ptr(pngp)); strcpy(params->error_message, "PNG decode expects more data than given"); longjmp(png_jmpbuf(pngp), 1); } memcpy(data, src->buffer, length); src->buffer += length; src->size -= length; } // Write memory handler for PNG static void store_data(png_structp pngp, png_bytep data, png_size_t length) { storage_manager *dst = static_cast<storage_manager *>(png_get_io_ptr(pngp)); if (static_cast<png_size_t>(dst->size) < length) { codec_params *params = (codec_params *)(png_get_error_ptr(pngp)); strcpy(params->error_message, "PNG encode buffer overflow"); longjmp(png_jmpbuf(pngp), 1); } memcpy(dst->buffer, data, length); dst->buffer += length; dst->size -= length; } const char *png_stride_decode(codec_params &params, const TiledRaster &raster, storage_manager &src, void *buffer) { png_structp pngp = NULL; png_infop infop = NULL; std::vector<png_bytep> png_rowp(static_cast<int>(raster.pagesize.y)); for (size_t i = 0; i < png_rowp.size(); i++) // line_stride is always in bytes png_rowp[i] = reinterpret_cast<png_bytep>( static_cast<char *>(buffer)+i * params.line_stride); png_uint_32 width, height; int bit_depth, ct; pngp = png_create_read_struct(PNG_LIBPNG_VER_STRING, &params, pngEH, pngEH); if (!pngp) return "PNG decode error while creating PNG structure"; infop = png_create_info_struct(pngp); if (!infop) return "PNG decode error while creating info structure"; if (setjmp(png_jmpbuf(pngp))) // This is the error return return params.error_message; png_set_read_fn(pngp, &src, get_data); png_read_info(pngp, infop); // TODO: Decode to expected format // png_set_palette_to_rgb(pngp); // Palette to RGB // png_set_tRNS_to_alpha(pngp); // transparency palette to Alpha // png_set_add_alpha(pngp, 255, PNG_FILLER_AFTER); // Add alpha if not there // png_read_update_info(pngp, infop); // update the reader // TODO: Check that it matches the expected raster png_get_IHDR(pngp, infop, &width, &height, &bit_depth, &ct, NULL, NULL, NULL); if (static_cast<png_uint_32>(raster.pagesize.y) != height || static_cast<png_uint_32>(raster.pagesize.x) != width) { strcpy(params.error_message, "Input PNG has the wrong size"); longjmp(png_jmpbuf(pngp), 1); } if ((raster.datatype == GDT_Byte && bit_depth != 8) || ((raster.datatype == GDT_UInt16 || raster.datatype == GDT_Short) && bit_depth != 16)) { strcpy(params.error_message, "Input PNG has the wrong type"); longjmp(png_jmpbuf(pngp), 1); } // If the row is larger than the stride, it might overflow the buffer if (png_get_rowbytes(pngp, infop) > params.line_stride) { strcpy(params.error_message, "PNG decode buffer too small"); longjmp(png_jmpbuf(pngp), 1); } png_read_image(pngp, png_rowp.data()); png_read_end(pngp, infop); png_destroy_read_struct(&pngp, &infop, 0); // setjmp no longer active, don't call any png functions if (bit_depth == 16) for (size_t i = 0; i < png_rowp.size(); i++) { unsigned short int*p = reinterpret_cast<unsigned short int *>(png_rowp[i]); // Swap bytes to host order, in place, on little endian hosts for (int j = 0; j < raster.pagesize.x; j++, p++) *p = ntoh16(*p); } return NULL; } const char *png_encode(png_params *params, const TiledRaster &raster, storage_manager &src, storage_manager &dst) { png_structp pngp = NULL; png_infop infop = NULL; png_uint_32 width = static_cast<png_uint_32>(raster.pagesize.x); png_uint_32 height = static_cast<png_uint_32>(raster.pagesize.y); // Use a vector so it cleans up itself std::vector<png_bytep> png_rowp(height); int rowbytes = 0; // To avoid changing the buffer pointer storage_manager mgr = dst; pngp = png_create_write_struct(PNG_LIBPNG_VER_STRING, params, pngEH, pngWH); if (!pngp) return "PNG encode error while creating PNG structure"; if (setjmp(png_jmpbuf(pngp))) // This is the error return return params->error_message; infop = png_create_info_struct(pngp); if (!infop) return "PNG encode error while creating info structure"; png_set_write_fn(pngp, &mgr, store_data, flush_png); png_set_IHDR(pngp, infop, width, height, params->bit_depth, params->color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_set_compression_level(pngp, params->compression_level); if (params->has_transparency) { // TODO: Pass the transparent value via params // For now, 0 is the no data value, regardless of type of data png_color_16 tcolor; memset(&tcolor, 0, sizeof(tcolor)); png_set_tRNS(pngp, infop, 0, 0, &tcolor); } rowbytes = png_get_rowbytes(pngp, infop); // Initialize the row pointers and swap bytes if the input is 16 bit for (size_t i = 0; i < png_rowp.size(); i++) { png_rowp[i] = reinterpret_cast<png_bytep>(src.buffer + i * rowbytes); if (params->bit_depth == 16) { unsigned short int*p = reinterpret_cast<unsigned short int *>(png_rowp[i]); // Swap bytes to net order, in place for (int j = 0; j < rowbytes / 2; j++, p++) *p = hton16(*p); } } png_write_info(pngp, infop); png_write_image(pngp, png_rowp.data()); png_write_end(pngp, infop); png_destroy_write_struct(&pngp, &infop); dst.size -= mgr.size; // mgr.size is bytes left return NULL; } int set_png_params(const TiledRaster &raster, png_params *params) { // Pick some defaults params->bit_depth = 8; params->compression_level = 6; params->has_transparency = FALSE; switch (raster.pagesize.c) { case 1: params->color_type = PNG_COLOR_TYPE_GRAY; break; case 2: params->color_type = PNG_COLOR_TYPE_GA; break; case 3: params->color_type = PNG_COLOR_TYPE_RGB; break; case 4: params->color_type = PNG_COLOR_TYPE_RGBA; break; } if (raster.datatype != GDT_Byte) params->bit_depth = 16; // PNG only handles 8 or 16 bits return APR_SUCCESS; } <|endoftext|>
<commit_before>/* * Copyright (c) 2014, Nick Potts * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of SpectralSignalHound nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SHWrapper.h" #define SVN_REV "0.0.0" namespace po = boost::program_options; namespace SignalHound { SHWrapper::~SHWrapper() { if (sh != NULL) delete(sh); } SHWrapper::SHWrapper(bool &ok, int argc, char *args[]): sh(NULL), verbosity(NORMAL), modes(SLOW_SWEEP) { std::string errmsg; ok = parseArgs(argc, args); sh = new SignalHound(&sh_opts, &sh_rfopts); std::cout << sh->info(); ok &= sh->verfyRFConfig(errmsg, sh_rfopts); } void SHWrapper::message(std::string msg, int level) { if (level > verbosity) std::cout << msg << endl; } bool SHWrapper::parseArgs( int ac, char *av[]) { /* This ugly long function does one thing: populate the two structures that configure the Signal Hound*/ try { po::options_description od_general( "" "sh-spectrum-logger: A Signal Hound (SA44B) Spectrum Analyzer Logger\n" "\nUsage: sh-spectrum-logger <Arguments>\n" "General Options" ); od_general.add_options() /**/( "help,h", "Show this message" ) /**/( "version,V", "Print version information and quit" ) /**/( "quiet,q", "Setting this will cease all non-fatal displayed messages." ) /**/( "verbose,v", "Setting this will cause a gratuitous amount of babble to be displayed. This overrides --quiet." ) /**/( "caldata,c", po::value<std::string>()->default_value( "" ) , "Use this file as the calibration data for the signal hound. This should radically spead up initialization. Use 'sh-extract-cal-data' to extract this calibration data and reference it here." ) /**/( "attenuation", po::value<double>(&sh_opts.attenuation)->default_value( 10.0 ), "Set the internal input attenuation. Must be one of the following values: 0.0, 5.0, 10.0 (default), or 15.0. Any other value will revert to the default." ) /**/( "low-mixer", "If flag is set, this will change the front end down converter to work with frequencies below 150MHz. If your frequency range will traverse above 150MHz, do not set this flag." ) /**/( "sensitivity", po::value<int>(&sh_opts.sensitivity)->default_value( 0 ), "Set the sensitivity of the Signal Hound. 0 (default) is lowest sensitivity, 2 is the highest." ) /**/( "decimation", po::value<int>(&sh_opts.decimation)->default_value( 1 ), "Sample Rate is set to 486.111Ksps/arg. Must be between [1, 16]. Resolution bandwidth is calculated from this and fft (below)." ) /**/( "alt-iflo", "If flag is set, this forces selection of the 2.9MHz Intermediate Frequency (IF) Local Oscillator (LO). The default is 10.7MHz and has higher selectivity but lower sensitivity. The 2.9MHz IF LO which features higher sensitivity yet lower selectivity." ) /**/( "alt-clock", "If flag is set, this forces selection of the 22.5MHz ADC clock. The default uses a 23-1/3 MHz clock, but changing this is helpful if the signal you are interested in is a multiple of a 23-1/3MHz." ) //( "device", po::value<int>()->default_value( 0 ), "Select which Signal Hound Device to use. Up to 8 can be connected to the same computer. This seems to be disabled in the linux API" ) /**/( "preset", "If flag is set, the Signal Hound will be preset immediately after initialzing and prior to sampling. This does set the Signal Hound to a known state, but it also adds another 2.5 seconds to start up time." ) /**/( "extref", "If flag is set, the Signal Hound will attempt to use a 10MHz external reference. Input power to the Signal Hound must be greater than 0dBm in order for this to be used." ) /**/( "trigger", po::value<int>(&sh_opts.ext_trigger)->default_value( 0 ), "Change the trigger mode. 0 (default) triggers immediately. 1 will only trigger on an external logic high. 2 will cause the trigger signal to pulse high when data collection begins." ) //( "temp-cal", po::value<std::string>()->default_value( "" ), "Filename of the temperate correction factors. Often, it is a filename like \"D01234567.bin\". Currently not implemented." ) /**/( "preamp", "If flag is set, will attempt to activate the built in RF preamplifier. Only available on a Signal Hound SA44B." ) ; po::options_description od_output( "Data Output" ); od_output.add_options() ( "database", po::value<std::string>()->default_value( "" ), "Write data into a sqlite database specified by the arg." ) ( "sql,s", po::value<std::string>()->default_value( "" ), "Produce a text files that could be used to import data into a database." ) ( "csv,c", po::value<std::string>()->default_value( "" ), "Produce a comma seperated file with data specified by arg." ) ( "log,l", po::value<std::string>()->default_value( "" ), "Write program log to file specified by arg. Defaults to stdout/stderr." ) ; po::options_description od_rfopts( "RF Options" ); od_rfopts.add_options() /**/( "start", po::value<double>(&sh_rfopts.start_freq)->default_value( 1.0e6 ), "Lower bound frequency to use for the spectral sweep." ) /**/( "stop", po::value<double>(&sh_rfopts.stop_freq)->default_value( 1.0e7 ), "Upper bound frequency to use for the spectral sweep. Due to rounding, you may get measured values past this value." ) /**/( "image-rejection", po::value<int>(&sh_rfopts.image_rejection)->default_value( 0 ), "Configure Image Rejection. Default of 0 masks both high and low side injection. Value of 1 only apply high side injection. Value of 2 only applies low side injection." ) /**/( "fft", po::value<int>(&sh_rfopts.fftsize)->default_value( -1 ), "Size of the FFT. Default value of -1 will autoselect the prefered FFT window. This and the decimation setting are used to calculate the RBW. In --slow mode, may be 16-65536 in powers of 2 while the default resolves to 1024. In --fast mode, may be 1, 16-256 in powers of 2 while the default resolves to 16." ) /**/( "average", po::value<int>(&sh_rfopts.average)->default_value( 16 ), "Only used in --slow sweep. Arg is the number of FFTs that get averaged together to produce the output. The value of (average*fft) must be an integer multiple of 512." ) ; po::options_description od_modes( "Sweep Modes" ); od_modes.add_options() /**/( "info", "Calculated parameters and dumps a list of what would be done. This is helpful if you want to see the Resolution Bandwidth (RBW) or other RF parameters" ) /**/( "slow", "Use slow sweep mode. Slow sweep is which is more thorough and not bandwidth limited. Data points will be spaced 486.111KHz/(fft*decimation). Each measurement cycle will take: (40 + (fft*average*decimation)/486)*(stop_freq - start_freq)/201000 milliseconds, rounded up. Furthermore, fft*average must be a integer multiple of 512." ) /**/( "fast", "Use fast sleep mode. Fast sweep captures a single sweep of data. The start_freq, and stop_freq are rounded to the nearest 200KHz. If fft=1, only the raw power is sampled, and samples are spaced 200KHz apart. If fft > 1, samples are spaced 200KHz. RBW is set solely on FFT size as the decimation is equal to 1 (fixed internally)" ) /**/( "fast", "Use fast sleep mode. Fast sweep captures a single sweep of data. The start_freq, and stop_freq are rounded to the nearest 200KHz. If fft=1, only the raw power is sampled, and samples are spaced 200KHz apart. If fft > 1, samples are spaced 200KHz. RBW is set solely on FFT size as the decimation is equal to 1 (fixed internally)" ) ( "delay", po::value<int>(&pause_between_traces)->default_value( 0 ), "In order to limit on the rediculously large file sizes, how long should this program pause between sweeps in milliseconds" ) ( "repetitions", po::value<int>(&repetitions)->default_value( -1 ), "How many sweeps should be done before exiting. Default of -1 means sweep forever (well... at least until Ctrl-C hit or power cycled)" ) ; po::options_description all( "" ); all.add( od_general ).add( od_rfopts ).add( od_modes ).add( od_output ); boost::program_options::variables_map vm; po::store( po::command_line_parser( ac, av ).options( all ).run(), vm ); po::notify( vm ); if ( vm.count( "help" ) ) { std::cout << all << "\n"; exit( 0 ); } if ( vm.count("version") ) { std::cout << "sh-spectrum-logger rev-" << SVN_REV << std::endl; exit(0); } if ( vm.count("quiet") ) verbosity = SILENT; if ( vm.count("verbose") ) verbosity = GRATUITOUS; if ( vm.count("low-mixer") ) sh_opts.mixerBand = 0; if ( vm.count("alt-iflo") ) sh_opts.iflo_path = 1; if ( vm.count("alt-clock") ) sh_opts.adcclk_path = 1; if ( vm.count("caldata") ) { //open the file and read in the bytes std::string fname = vm["caldata"].as<std::string>(); try { std::ifstream bin(fname.c_str(), std::ios::binary); bin.read( (char *) sh_opts.caldata, 4096); if (bin.gcount() == 4096) sh_opts.docal = true; } catch (std::exception &e) { std::cerr << "Error opening cal file: " << e.what() << std::endl; } } if ( vm.count("preset") ) sh_opts.preset = true; if ( vm.count("extref") ) sh_opts.ext_ref = true; if ( vm.count("fast") ) modes = FAST_SWEEP; if ( vm.count("info") ) modes = INFODISPLAY; if ( vm.count("slow") ) modes = SLOW_SWEEP; //perform validation if (!((sh_opts.attenuation == 0.0) | (sh_opts.attenuation == 5.0) | (sh_opts.attenuation == 10.0) | (sh_opts.attenuation == 15.0))) sh_opts.attenuation=10; if ( (sh_opts.sensitivity < 0) | (sh_opts.sensitivity > 2)) sh_opts.sensitivity = 0; switch(sh_opts.ext_trigger) { case 0: sh_opts.ext_trigger = SHAPI_EXTERNALTRIGGER; break; case 1: sh_opts.ext_trigger = SHAPI_SYNCOUT; break; default: sh_opts.ext_trigger = SHAPI_TRIGGERNORMAL; break; } if ((sh_rfopts.image_rejection < 0) | (sh_rfopts.image_rejection > 2)) sh_rfopts.image_rejection = 0; return true; } catch ( std::exception &e ) { std::cout << "Error parsing arguments: " << e.what() << std::endl; return false; } return false; } };<commit_msg>Due to typo copy-n-paste, I had 2 --fast operators. one has been removed so it works again. fft of -1 defaults to using sane defaults for the configuration sweep<commit_after>/* * Copyright (c) 2014, Nick Potts * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of SpectralSignalHound nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "SHWrapper.h" #define SVN_REV "0.0.0" namespace po = boost::program_options; namespace SignalHound { SHWrapper::~SHWrapper() { if (sh != NULL) delete(sh); } SHWrapper::SHWrapper(bool &ok, int argc, char *args[]): sh(NULL), verbosity(NORMAL), modes(SLOW_SWEEP) { std::string errmsg; ok = parseArgs(argc, args); sh = new SignalHound(&sh_opts, &sh_rfopts); std::cout << sh->info(); ok &= sh->verfyRFConfig(errmsg, sh_rfopts); } void SHWrapper::message(std::string msg, int level) { if (level > verbosity) std::cout << msg << endl; } bool SHWrapper::parseArgs( int ac, char *av[]) { /* This ugly long function does one thing: populate the two structures that configure the Signal Hound*/ try { po::options_description od_general( "" "sh-spectrum-logger: A Signal Hound (SA44B) Spectrum Analyzer Logger\n" "\nUsage: sh-spectrum-logger <Arguments>\n" "General Options" ); od_general.add_options() /**/( "help,h", "Show this message" ) /**/( "version,V", "Print version information and quit" ) /**/( "quiet,q", "Setting this will cease all non-fatal displayed messages." ) /**/( "verbose,v", "Setting this will cause a gratuitous amount of babble to be displayed. This overrides --quiet." ) /**/( "caldata,c", po::value<std::string>()->default_value( "" ) , "Use this file as the calibration data for the signal hound. This should radically spead up initialization. Use 'sh-extract-cal-data' to extract this calibration data and reference it here." ) /**/( "attenuation", po::value<double>(&sh_opts.attenuation)->default_value( 10.0 ), "Set the internal input attenuation. Must be one of the following values: 0.0, 5.0, 10.0 (default), or 15.0. Any other value will revert to the default." ) /**/( "low-mixer", "If flag is set, this will change the front end down converter to work with frequencies below 150MHz. If your frequency range will traverse above 150MHz, do not set this flag." ) /**/( "sensitivity", po::value<int>(&sh_opts.sensitivity)->default_value( 0 ), "Set the sensitivity of the Signal Hound. 0 (default) is lowest sensitivity, 2 is the highest." ) /**/( "decimation", po::value<int>(&sh_opts.decimation)->default_value( 1 ), "Sample Rate is set to 486.111Ksps/arg. Must be between [1, 16]. Resolution bandwidth is calculated from this and fft (below)." ) /**/( "alt-iflo", "If flag is set, this forces selection of the 2.9MHz Intermediate Frequency (IF) Local Oscillator (LO). The default is 10.7MHz and has higher selectivity but lower sensitivity. The 2.9MHz IF LO which features higher sensitivity yet lower selectivity." ) /**/( "alt-clock", "If flag is set, this forces selection of the 22.5MHz ADC clock. The default uses a 23-1/3 MHz clock, but changing this is helpful if the signal you are interested in is a multiple of a 23-1/3MHz." ) //( "device", po::value<int>()->default_value( 0 ), "Select which Signal Hound Device to use. Up to 8 can be connected to the same computer. This seems to be disabled in the linux API" ) /**/( "preset", "If flag is set, the Signal Hound will be preset immediately after initialzing and prior to sampling. This does set the Signal Hound to a known state, but it also adds another 2.5 seconds to start up time." ) /**/( "extref", "If flag is set, the Signal Hound will attempt to use a 10MHz external reference. Input power to the Signal Hound must be greater than 0dBm in order for this to be used." ) /**/( "trigger", po::value<int>(&sh_opts.ext_trigger)->default_value( 0 ), "Change the trigger mode. 0 (default) triggers immediately. 1 will only trigger on an external logic high. 2 will cause the trigger signal to pulse high when data collection begins." ) //( "temp-cal", po::value<std::string>()->default_value( "" ), "Filename of the temperate correction factors. Often, it is a filename like \"D01234567.bin\". Currently not implemented." ) /**/( "preamp", "If flag is set, will attempt to activate the built in RF preamplifier. Only available on a Signal Hound SA44B." ) ; po::options_description od_output( "Data Output" ); od_output.add_options() ( "database", po::value<std::string>()->default_value( "" ), "Write data into a sqlite database specified by the arg." ) ( "sql,s", po::value<std::string>()->default_value( "" ), "Produce a text files that could be used to import data into a database." ) ( "csv,c", po::value<std::string>()->default_value( "" ), "Produce a comma seperated file with data specified by arg." ) ( "log,l", po::value<std::string>()->default_value( "" ), "Write program log to file specified by arg. Defaults to stdout/stderr." ) ; po::options_description od_rfopts( "RF Options" ); od_rfopts.add_options() /**/( "start", po::value<double>(&sh_rfopts.start_freq)->default_value( 1.0e6 ), "Lower bound frequency to use for the spectral sweep." ) /**/( "stop", po::value<double>(&sh_rfopts.stop_freq)->default_value( 1.0e7 ), "Upper bound frequency to use for the spectral sweep. Due to rounding, you may get measured values past this value." ) /**/( "image-rejection", po::value<int>(&sh_rfopts.image_rejection)->default_value( 0 ), "Configure Image Rejection. Default of 0 masks both high and low side injection. Value of 1 only apply high side injection. Value of 2 only applies low side injection." ) /**/( "fft", po::value<int>(&sh_rfopts.fftsize)->default_value( -1 ), "Size of the FFT. Default value of -1 will autoselect the prefered FFT window. This and the decimation setting are used to calculate the RBW. In --slow mode, may be 16-65536 in powers of 2 while the default resolves to 1024. In --fast mode, may be 1, 16-256 in powers of 2 while the default resolves to 16." ) /**/( "average", po::value<int>(&sh_rfopts.average)->default_value( 16 ), "Only used in --slow sweep. Arg is the number of FFTs that get averaged together to produce the output. The value of (average*fft) must be an integer multiple of 512." ) ; po::options_description od_modes( "Sweep Modes" ); od_modes.add_options() /**/( "info", "Calculated parameters and dumps a list of what would be done. This is helpful if you want to see the Resolution Bandwidth (RBW) or other RF parameters" ) /**/( "slow", "Use slow sweep mode. Slow sweep is which is more thorough and not bandwidth limited. Data points will be spaced 486.111KHz/(fft*decimation). Each measurement cycle will take: (40 + (fft*average*decimation)/486)*(stop_freq - start_freq)/201000 milliseconds, rounded up. Furthermore, fft*average must be a integer multiple of 512." ) /**/( "fast", "Use fast sleep mode. Fast sweep captures a single sweep of data. The start_freq, and stop_freq are rounded to the nearest 200KHz. If fft=1, only the raw power is sampled, and samples are spaced 200KHz apart. If fft > 1, samples are spaced 200KHz. RBW is set solely on FFT size as the decimation is equal to 1 (fixed internally)" ) ( "delay", po::value<int>(&pause_between_traces)->default_value( 0 ), "In order to limit on the rediculously large file sizes, how long should this program pause between sweeps in milliseconds" ) ( "repetitions", po::value<int>(&repetitions)->default_value( -1 ), "How many sweeps should be done before exiting. Default of -1 means sweep forever (well... at least until Ctrl-C hit or power cycled)" ) ; po::options_description all( "" ); all.add( od_general ).add( od_rfopts ).add( od_modes ).add( od_output ); boost::program_options::variables_map vm; po::store( po::command_line_parser( ac, av ).options( all ).run(), vm ); po::notify( vm ); if ( vm.count( "help" ) ) { std::cout << all << "\n"; exit( 0 ); } if ( vm.count("version") ) { std::cout << "sh-spectrum-logger rev-" << SVN_REV << std::endl; exit(0); } if ( vm.count("quiet") ) verbosity = SILENT; if ( vm.count("verbose") ) verbosity = GRATUITOUS; if ( vm.count("low-mixer") ) sh_opts.mixerBand = 0; if ( vm.count("alt-iflo") ) sh_opts.iflo_path = 1; if ( vm.count("alt-clock") ) sh_opts.adcclk_path = 1; if ( vm.count("caldata") ) { //open the file and read in the bytes std::string fname = vm["caldata"].as<std::string>(); try { std::ifstream bin(fname.c_str(), std::ios::binary); bin.read( (char *) sh_opts.caldata, 4096); if (bin.gcount() == 4096) sh_opts.docal = true; } catch (std::exception &e) { std::cerr << "Error opening cal file: " << e.what() << std::endl; } } if ( vm.count("preset") ) sh_opts.preset = true; if ( vm.count("extref") ) sh_opts.ext_ref = true; if ( vm.count("fast") ) sh_rfopts.slowSweep = false; if ( vm.count("info") ) modes = INFODISPLAY; if ( vm.count("slow") ) sh_rfopts.slowSweep = true; //perform validation if (!((sh_opts.attenuation == 0.0) | (sh_opts.attenuation == 5.0) | (sh_opts.attenuation == 10.0) | (sh_opts.attenuation == 15.0))) sh_opts.attenuation=10; if ( (sh_opts.sensitivity < 0) | (sh_opts.sensitivity > 2)) sh_opts.sensitivity = 0; switch(sh_opts.ext_trigger) { case 0: sh_opts.ext_trigger = SHAPI_EXTERNALTRIGGER; break; case 1: sh_opts.ext_trigger = SHAPI_SYNCOUT; break; default: sh_opts.ext_trigger = SHAPI_TRIGGERNORMAL; break; } if ((sh_rfopts.image_rejection < 0) | (sh_rfopts.image_rejection > 2)) sh_rfopts.image_rejection = 0; if (sh_rfopts.fftsize == -1) sh_rfopts.fftsize = sh_rfopts.slowSweep ? 1024 : 16; return true; } catch ( std::exception &e ) { std::cout << "Error parsing arguments: " << e.what() << std::endl; return false; } return false; } };<|endoftext|>
<commit_before>// // Copyright (c) 2017, Boris Popov <popov@whitekefir.ru> // // 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 "Semaphore.hpp" #include "ErrorBuilder.hpp" ////////////////////////////////////////////////////////////////// linux::posix:: Semaphore::Semaphore(const Name n, const UNLINK_AFTER_DESTROY d, const OpenOptions oo, unsigned int v): name(n), destroy(d), options(oo), value(v), semaphore(nullptr) { return; } void linux::posix::Semaphore::open() { semaphore = sem_open(name.c_str(), options.get_oflag().get(), options.get_mode().get(), value); if (semaphore == SEM_FAILED) { int e = errno; ErrorBuilder eb; throw eb.build(e); } } void linux::posix::Semaphore::close() const { if (semaphore == SEM_FAILED) return; if (semaphore == nullptr) return; int res = sem_close(semaphore); if (res == -1) { int e = errno; ErrorBuilder eb; throw eb.build(e); } } void linux::posix::Semaphore::post() const { int res = sem_post(semaphore); if (res == -1) { int e = errno; ErrorBuilder eb; throw eb.build(e); } } void linux::posix::Semaphore::wait() const { int res = sem_wait(semaphore); if (res == -1) { int e = errno; ErrorBuilder eb; throw eb.build(e); } } bool linux::posix::Semaphore::trywait() const { int res = sem_trywait(semaphore); if (res == -1) { int e = errno; if (e == EAGAIN) return false; ErrorBuilder eb; throw eb.build(e); } return true; } int linux::posix::Semaphore::get() const { int ret = 0; int res = sem_getvalue(semaphore, &ret); if (res == -1) { int e = errno; ErrorBuilder eb; throw eb.build(e); } return ret; } linux::posix:: Semaphore::~Semaphore() { if (semaphore == SEM_FAILED) return; if (semaphore == nullptr) return; sem_close(semaphore); if (destroy) sem_unlink(name.c_str()); } ////////////////////////////////////////////////////////////////// <commit_msg>fix Semaphore<commit_after>// // Copyright (c) 2017, Boris Popov <popov@whitekefir.ru> // // 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 "Semaphore.hpp" #include "ErrorBuilder.hpp" ////////////////////////////////////////////////////////////////// linux::posix:: Semaphore::Semaphore(const Name n, const UNLINK_AFTER_DESTROY d, const OpenOptions oo, unsigned int v): name(n), destroy(d), options(oo), value(v), semaphore(nullptr) { return; } void linux::posix::Semaphore::open() { semaphore = sem_open(name.c_str(), options.get_oflag().get(), options.get_mode().get(), value); if (semaphore == SEM_FAILED) { int e = errno; ErrorBuilder eb; throw eb.build(e); } } void linux::posix::Semaphore::close() const { if (semaphore == nullptr) throw NullPointer(); int res = sem_close(semaphore); if (res == -1) { int e = errno; ErrorBuilder eb; throw eb.build(e); } } void linux::posix::Semaphore::post() const { if (semaphore == nullptr) throw NullPointer(); int res = sem_post(semaphore); if (res == -1) { int e = errno; ErrorBuilder eb; throw eb.build(e); } } void linux::posix::Semaphore::wait() const { if (semaphore == nullptr) throw NullPointer(); int res = sem_wait(semaphore); if (res == -1) { int e = errno; ErrorBuilder eb; throw eb.build(e); } } bool linux::posix::Semaphore::trywait() const { if (semaphore == nullptr) throw NullPointer(); int res = sem_trywait(semaphore); if (res == -1) { int e = errno; if (e == EAGAIN) return false; ErrorBuilder eb; throw eb.build(e); } return true; } int linux::posix::Semaphore::get() const { if (semaphore == nullptr) throw NullPointer(); int ret = 0; int res = sem_getvalue(semaphore, &ret); if (res == -1) { int e = errno; ErrorBuilder eb; throw eb.build(e); } return ret; } linux::posix:: Semaphore::~Semaphore() { if (semaphore != nullptr) sem_close(semaphore); if (destroy) sem_unlink(name.c_str()); } ////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>// // TcpSocket.cpp for TcpSocket in // // Made by mognetworkhrabi Alexandre // Login <alexmog@epitech.net> // // Started on Thu Jun 5 20:09:34 2014 mognetworkhrabi Alexandre // Last update Mon Mar 23 10:27:39 2015 Moghrabi Alexandre // #include "mognetwork/OS.hh" #include <sys/types.h> #ifndef OS_WINDOWS #include <sys/socket.h> #include <netdb.h> #else #include <winsock2.h> #include <Ws2tcpip.h> #endif // !OS_WINDOWS #include <algorithm> #include <cstring> #include <iostream> #include "mognetwork/TcpSocket.hh" #include "mognetwork/OsSocket.hh" #include "mognetwork/Packet.hh" namespace { #ifdef OS_LINUX const int flags = MSG_NOSIGNAL; #else const int flags = 0; #endif } // ! Every packets sends a header (who contains the size of the packet) BEFORE its content. namespace mognetwork { bool deleteAll(TcpSocket::Data* elem) {delete elem; return true;} TcpSocket::TcpSocket() : Socket(Tcp), m_userData(NULL) { // Create the socket, and init it create(); } TcpSocket::TcpSocket(SocketFD fd) : Socket(Tcp), m_userData(NULL) { create(fd); } Socket::Status TcpSocket::connect(const IpAddress& rAddress, unsigned short port) { // Create the sockaddr by the OS sockaddr_in address = OsSocket::createAddress(rAddress.getInt(), port); // connect the socket to the address return (::connect(getSocketFD(), reinterpret_cast<sockaddr*>(&address), sizeof(address)) == -1 ? OsSocket::getErrorStatus() : Ok); } void TcpSocket::disconnect() { close(); m_pendingDatas.remove_if(deleteAll); m_pendingRDatas = ReadedDatas(); } Socket::Status TcpSocket::receive(char* data, std::size_t size, std::size_t& received, int _flags) { received = 0; if (!data) { std::cerr << "Cannot receive datas if the buffer is null." << std::endl; return (Error); } int readed = recv(getSocketFD(), data, static_cast<int>(size), flags | _flags); if (readed > 0) { received = static_cast<std::size_t>(readed); return (Ok); } else if (readed == 0) return (Disconnected); else return (OsSocket::getErrorStatus()); } Socket::Status TcpSocket::receiveAll(Data& data) { std::size_t readed = 0; char buffer[1024]; // Buffer to get the datas std::size_t numReaded = 0; ReadedDatas _data = ReadedDatas(); data.clear(); // Read the size of the pending packet while (readed < sizeof(std::size_t)) { char* d = reinterpret_cast<char*>(&_data.totalSize) + numReaded; Socket::Status status = receive(d, sizeof(std::size_t) - _data.readed, readed, 0); numReaded += readed; if (status != Ok) return (status); } // Size is set, let's read the content! if (numReaded >= sizeof(std::size_t)) { while (_data.readed < _data.totalSize) { std::size_t toGet = std::min(static_cast<std::size_t>(_data.totalSize - _data.readed), sizeof(buffer)); Socket::Status status = receive(buffer, toGet, readed, 0); if (status != Ok) return (status); _data.readed += readed; if (readed > 0) { data.resize(data.size() + readed); char* begin = &data[0] + data.size() - readed; std::memcpy(begin, buffer, readed); } if (_data.readed >= _data.totalSize) return (Ok); } } return (Error); } Socket::Status TcpSocket::asyncSend(const char* data, std::size_t size) { if (!data || (size == 0)) { std::cerr << "Cannot send null data" << std::endl; return (Error); } Data* _data = new Data; _data->resize(size + sizeof(std::size_t)); std::memcpy(&_data->front(), &size, sizeof(std::size_t)); std::memcpy(&_data->front() + sizeof(std::size_t), data, size); m_mutex.lock(); m_pendingDatas.push_back(_data); m_mutex.unlock(); return (Ok); } bool TcpSocket::havingPendingDatas() { m_mutex.lock(); bool status = m_pendingDatas.empty(); m_mutex.unlock(); return (status); } Socket::Status TcpSocket::sendPendingDatas() { // m_mutex.lock(); if (!m_pendingDatas.empty()) { int sended; DataList::iterator it = m_pendingDatas.begin(); sended = ::send(getSocketFD(), &(*it)->front(), (*it)->size(), flags | MSG_DONTWAIT); if (sended < 0) { // m_mutex.unlock(); return (OsSocket::getErrorStatus()); } if (sended == 0) { //m_mutex.unlock(); return (Disconnected); } if ((std::size_t)sended == (*it)->size()) { delete *it; m_pendingDatas.pop_front(); //m_mutex.unlock(); return (sendPendingDatas()); } Data temp; temp.resize((*it)->size()); std::memcpy(&temp[0], &(*it)->front(), (*it)->size()); std::size_t waiting = (*it)->size() - sended; (*it)->resize(waiting); std::memcpy(&(*it)->front(), &temp[0], waiting); // m_mutex.unlock(); return (Ok); } // m_mutex.unlock(); return (Nok); } // Normal send method, waits until the server has received everything. Socket::Status TcpSocket::send(const char* data, std::size_t size) { int sent; if (!data || (size == 0)) { std::cerr << "Cannot send null data" << std::endl; return (Error); } Data dat; dat.resize(size + sizeof(std::size_t)); std::memcpy(&dat[0], &size, sizeof(std::size_t)); std::memcpy(&dat[0] + sizeof(std::size_t), data, size); sent = ::send(getSocketFD(), &dat[0], dat.size(), 0); if (sent < 0) return (OsSocket::getErrorStatus()); if (sent == 0) return (Disconnected); return (Ok); } void TcpSocket::setUserData(void* userData) { m_mutex.lock(); m_userData = userData; m_mutex.unlock(); } void* TcpSocket::getUserData() const { return (m_userData); } Socket::Status TcpSocket::readPendingDatas() { std::size_t readed; char buffer[1024]; // Buffer to get the datas // Read the size of the pending packet if (m_pendingRDatas.readed < sizeof(std::size_t)) { char* data = reinterpret_cast<char*>(&m_pendingRDatas.totalSize) + m_pendingRDatas.readed; Socket::Status status = receive(data, sizeof(std::size_t) - m_pendingRDatas.readed, readed, MSG_DONTWAIT); m_pendingRDatas.readed += readed; if (status != Ok) return (status); } // Size is set, let's read the content! if (m_pendingRDatas.readed >= sizeof(std::size_t)) { std::size_t toGet = std::min(static_cast<std::size_t>(m_pendingRDatas.totalSize - m_pendingRDatas.datas.size()), sizeof(buffer)); Socket::Status status = receive(buffer, toGet, readed, MSG_DONTWAIT); if (status != Ok) return (status); m_pendingRDatas.readed += readed; if (readed > 0) { m_pendingRDatas.datas.resize(m_pendingRDatas.datas.size() + readed); char* begin = &m_pendingRDatas.datas[0] + m_pendingRDatas.datas.size() - readed; std::memcpy(begin, buffer, readed); } if (m_pendingRDatas.readed >= m_pendingRDatas.totalSize) { m_allDataReaded = new ReadedDatas(); m_allDataReaded->datas = m_pendingRDatas.datas; m_allDataReaded->readed = m_pendingRDatas.readed; m_allDataReaded->totalSize = m_pendingRDatas.totalSize; m_pendingRDatas = ReadedDatas(); return (Ok); } } return (Waiting); } TcpSocket::ReadedDatas* TcpSocket::getDatasReaded() const { return (m_allDataReaded); } void TcpSocket::setServer(TcpASIOServer* server) { m_mutex.lock(); m_server = server; m_mutex.unlock(); } TcpASIOServer* TcpSocket::getServer() const { return m_server; } Packet* TcpSocket::getPacketReaded() { return new Packet(m_allDataReaded); } TcpSocket::ReadedDatas::ReadedDatas() : readed(0), totalSize(0), datas() {} } // namespace mognetwork <commit_msg>removing more mutex<commit_after>// // TcpSocket.cpp for TcpSocket in // // Made by mognetworkhrabi Alexandre // Login <alexmog@epitech.net> // // Started on Thu Jun 5 20:09:34 2014 mognetworkhrabi Alexandre // Last update Mon Mar 23 10:31:39 2015 Moghrabi Alexandre // #include "mognetwork/OS.hh" #include <sys/types.h> #ifndef OS_WINDOWS #include <sys/socket.h> #include <netdb.h> #else #include <winsock2.h> #include <Ws2tcpip.h> #endif // !OS_WINDOWS #include <algorithm> #include <cstring> #include <iostream> #include "mognetwork/TcpSocket.hh" #include "mognetwork/OsSocket.hh" #include "mognetwork/Packet.hh" namespace { #ifdef OS_LINUX const int flags = MSG_NOSIGNAL; #else const int flags = 0; #endif } // ! Every packets sends a header (who contains the size of the packet) BEFORE its content. namespace mognetwork { bool deleteAll(TcpSocket::Data* elem) {delete elem; return true;} TcpSocket::TcpSocket() : Socket(Tcp), m_userData(NULL) { // Create the socket, and init it create(); } TcpSocket::TcpSocket(SocketFD fd) : Socket(Tcp), m_userData(NULL) { create(fd); } Socket::Status TcpSocket::connect(const IpAddress& rAddress, unsigned short port) { // Create the sockaddr by the OS sockaddr_in address = OsSocket::createAddress(rAddress.getInt(), port); // connect the socket to the address return (::connect(getSocketFD(), reinterpret_cast<sockaddr*>(&address), sizeof(address)) == -1 ? OsSocket::getErrorStatus() : Ok); } void TcpSocket::disconnect() { close(); m_pendingDatas.remove_if(deleteAll); m_pendingRDatas = ReadedDatas(); } Socket::Status TcpSocket::receive(char* data, std::size_t size, std::size_t& received, int _flags) { received = 0; if (!data) { std::cerr << "Cannot receive datas if the buffer is null." << std::endl; return (Error); } int readed = recv(getSocketFD(), data, static_cast<int>(size), flags | _flags); if (readed > 0) { received = static_cast<std::size_t>(readed); return (Ok); } else if (readed == 0) return (Disconnected); else return (OsSocket::getErrorStatus()); } Socket::Status TcpSocket::receiveAll(Data& data) { std::size_t readed = 0; char buffer[1024]; // Buffer to get the datas std::size_t numReaded = 0; ReadedDatas _data = ReadedDatas(); data.clear(); // Read the size of the pending packet while (readed < sizeof(std::size_t)) { char* d = reinterpret_cast<char*>(&_data.totalSize) + numReaded; Socket::Status status = receive(d, sizeof(std::size_t) - _data.readed, readed, 0); numReaded += readed; if (status != Ok) return (status); } // Size is set, let's read the content! if (numReaded >= sizeof(std::size_t)) { while (_data.readed < _data.totalSize) { std::size_t toGet = std::min(static_cast<std::size_t>(_data.totalSize - _data.readed), sizeof(buffer)); Socket::Status status = receive(buffer, toGet, readed, 0); if (status != Ok) return (status); _data.readed += readed; if (readed > 0) { data.resize(data.size() + readed); char* begin = &data[0] + data.size() - readed; std::memcpy(begin, buffer, readed); } if (_data.readed >= _data.totalSize) return (Ok); } } return (Error); } Socket::Status TcpSocket::asyncSend(const char* data, std::size_t size) { if (!data || (size == 0)) { std::cerr << "Cannot send null data" << std::endl; return (Error); } Data* _data = new Data; _data->resize(size + sizeof(std::size_t)); std::memcpy(&_data->front(), &size, sizeof(std::size_t)); std::memcpy(&_data->front() + sizeof(std::size_t), data, size); m_pendingDatas.push_back(_data); return (Ok); } bool TcpSocket::havingPendingDatas() { m_mutex.lock(); bool status = m_pendingDatas.empty(); m_mutex.unlock(); return (status); } Socket::Status TcpSocket::sendPendingDatas() { // m_mutex.lock(); if (!m_pendingDatas.empty()) { int sended; DataList::iterator it = m_pendingDatas.begin(); sended = ::send(getSocketFD(), &(*it)->front(), (*it)->size(), flags | MSG_DONTWAIT); if (sended < 0) { // m_mutex.unlock(); return (OsSocket::getErrorStatus()); } if (sended == 0) { //m_mutex.unlock(); return (Disconnected); } if ((std::size_t)sended == (*it)->size()) { delete *it; m_pendingDatas.pop_front(); //m_mutex.unlock(); return (sendPendingDatas()); } Data temp; temp.resize((*it)->size()); std::memcpy(&temp[0], &(*it)->front(), (*it)->size()); std::size_t waiting = (*it)->size() - sended; (*it)->resize(waiting); std::memcpy(&(*it)->front(), &temp[0], waiting); // m_mutex.unlock(); return (Ok); } // m_mutex.unlock(); return (Nok); } // Normal send method, waits until the server has received everything. Socket::Status TcpSocket::send(const char* data, std::size_t size) { int sent; if (!data || (size == 0)) { std::cerr << "Cannot send null data" << std::endl; return (Error); } Data dat; dat.resize(size + sizeof(std::size_t)); std::memcpy(&dat[0], &size, sizeof(std::size_t)); std::memcpy(&dat[0] + sizeof(std::size_t), data, size); sent = ::send(getSocketFD(), &dat[0], dat.size(), 0); if (sent < 0) return (OsSocket::getErrorStatus()); if (sent == 0) return (Disconnected); return (Ok); } void TcpSocket::setUserData(void* userData) { m_mutex.lock(); m_userData = userData; m_mutex.unlock(); } void* TcpSocket::getUserData() const { return (m_userData); } Socket::Status TcpSocket::readPendingDatas() { std::size_t readed; char buffer[1024]; // Buffer to get the datas // Read the size of the pending packet if (m_pendingRDatas.readed < sizeof(std::size_t)) { char* data = reinterpret_cast<char*>(&m_pendingRDatas.totalSize) + m_pendingRDatas.readed; Socket::Status status = receive(data, sizeof(std::size_t) - m_pendingRDatas.readed, readed, MSG_DONTWAIT); m_pendingRDatas.readed += readed; if (status != Ok) return (status); } // Size is set, let's read the content! if (m_pendingRDatas.readed >= sizeof(std::size_t)) { std::size_t toGet = std::min(static_cast<std::size_t>(m_pendingRDatas.totalSize - m_pendingRDatas.datas.size()), sizeof(buffer)); Socket::Status status = receive(buffer, toGet, readed, MSG_DONTWAIT); if (status != Ok) return (status); m_pendingRDatas.readed += readed; if (readed > 0) { m_pendingRDatas.datas.resize(m_pendingRDatas.datas.size() + readed); char* begin = &m_pendingRDatas.datas[0] + m_pendingRDatas.datas.size() - readed; std::memcpy(begin, buffer, readed); } if (m_pendingRDatas.readed >= m_pendingRDatas.totalSize) { m_allDataReaded = new ReadedDatas(); m_allDataReaded->datas = m_pendingRDatas.datas; m_allDataReaded->readed = m_pendingRDatas.readed; m_allDataReaded->totalSize = m_pendingRDatas.totalSize; m_pendingRDatas = ReadedDatas(); return (Ok); } } return (Waiting); } TcpSocket::ReadedDatas* TcpSocket::getDatasReaded() const { return (m_allDataReaded); } void TcpSocket::setServer(TcpASIOServer* server) { m_mutex.lock(); m_server = server; m_mutex.unlock(); } TcpASIOServer* TcpSocket::getServer() const { return m_server; } Packet* TcpSocket::getPacketReaded() { return new Packet(m_allDataReaded); } TcpSocket::ReadedDatas::ReadedDatas() : readed(0), totalSize(0), datas() {} } // namespace mognetwork <|endoftext|>
<commit_before>/* * fMBT, free Model Based Testing tool * Copyright (c) 2012 Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include "config.h" #ifndef DROID #include "aal_remote.hh" #include <glib-object.h> #include <glib.h> #include "helper.hh" aal_remote::aal_remote(Log&l,std::string& s) : aal(l) { int _stdin,_stdout,_stderr; g_type_init (); gchar **argv = NULL; gint argc; GError *gerr=NULL; std::string errormsg; g_shell_parse_argv(s.c_str(),&argc,&argv,&gerr); if (gerr) { errormsg = "aal_remote: g_shell_parse_argv error: " + std::string(gerr->message) + " when parsing " + s; _log.debug(errormsg.c_str()); ok = false; return; } g_spawn_async_with_pipes(NULL,argv,NULL,G_SPAWN_SEARCH_PATH,NULL,&pid,NULL,&_stdin,&_stdout,&_stderr,&gerr); if (gerr) { errormsg = "aal_remote g_spawn_async_with_pipes error: " + std::string(gerr->message); _log.debug(errormsg.c_str()); ok=false; return; } d_stdin=fdopen(_stdin,"w"); d_stdout=fdopen(_stdout,"r"); d_stderr=fdopen(_stderr,"r"); ssize_t red=getline(&read_buf,&read_buf_pos,d_stdout); while (red>1) { action_names.push_back(read_buf); red=getline(&read_buf,&read_buf_pos,d_stdout); } red=getline(&read_buf,&read_buf_pos,d_stdout); while (red>1) { tag_names.push_back(read_buf); red=getline(&read_buf,&read_buf_pos,d_stdout); } nonblock(_stdin); nonblock(_stdout); fflush(d_stdin); } int aal_remote::adapter_execute(int action) { std::fprintf(d_stdin, "a%i\n", action); return getint(d_stdin,d_stdout); } int aal_remote::model_execute(int action) { std::fprintf(d_stdin, "m%i\n", action); return getint(d_stdin,d_stdout); } void aal_remote::push() { std::fprintf(d_stdin,"mu\n"); fflush(d_stdin); } void aal_remote::pop() { std::fprintf(d_stdin,"mo\n"); fflush(d_stdin); } bool aal_remote::reset() { std::fprintf(d_stdin, "mr\n"); return getint(d_stdin,d_stdout); } int aal_remote::getActions(int** act) { std::fprintf(d_stdin, "ma\n"); return getact(act,actions,d_stdin,d_stdout); } int aal_remote::getprops(int** pro) { std::fprintf(d_stdin, "mp\n"); return getact(pro,tags,d_stdin,d_stdout); } #include <cstring> #include "helper.hh" namespace { std::map<std::string,aal_remote*> storage; Adapter* adapter_creator(Log& l, std::string params = "") { std::string remotename(unescape_string(strdup(params.c_str()))); aal_remote* al=storage[remotename]; if (!al) { al=new aal_remote(l,remotename); if (al->ok) { storage[remotename]=al; } else { delete al; al=NULL; } } if (al) { return new Awrapper(l,params,al); } return NULL; } Model* model_creator(Log& l, std::string params) { std::string remotename(unescape_string(strdup(params.c_str()))); aal_remote* al=storage[remotename]; if (!al) { al=new aal_remote(l,remotename); if (al->ok) { storage[remotename]=al; } else { delete al; al=NULL; } } if (al) { return new Mwrapper(l,params,al); } return NULL; } static ModelFactory ::Register Mo("remote", model_creator); static AdapterFactory::Register Ad("remote", adapter_creator); } #endif <commit_msg>remote -> aalremote<commit_after>/* * fMBT, free Model Based Testing tool * Copyright (c) 2012 Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include "config.h" #ifndef DROID #include "aal_remote.hh" #include <glib-object.h> #include <glib.h> #include "helper.hh" aal_remote::aal_remote(Log&l,std::string& s) : aal(l) { int _stdin,_stdout,_stderr; g_type_init (); gchar **argv = NULL; gint argc; GError *gerr=NULL; std::string errormsg; g_shell_parse_argv(s.c_str(),&argc,&argv,&gerr); if (gerr) { errormsg = "aal_remote: g_shell_parse_argv error: " + std::string(gerr->message) + " when parsing " + s; _log.debug(errormsg.c_str()); ok = false; return; } g_spawn_async_with_pipes(NULL,argv,NULL,G_SPAWN_SEARCH_PATH,NULL,&pid,NULL,&_stdin,&_stdout,&_stderr,&gerr); if (gerr) { errormsg = "aal_remote g_spawn_async_with_pipes error: " + std::string(gerr->message); _log.debug(errormsg.c_str()); ok=false; return; } d_stdin=fdopen(_stdin,"w"); d_stdout=fdopen(_stdout,"r"); d_stderr=fdopen(_stderr,"r"); ssize_t red=getline(&read_buf,&read_buf_pos,d_stdout); while (red>1) { action_names.push_back(read_buf); red=getline(&read_buf,&read_buf_pos,d_stdout); } red=getline(&read_buf,&read_buf_pos,d_stdout); while (red>1) { tag_names.push_back(read_buf); red=getline(&read_buf,&read_buf_pos,d_stdout); } nonblock(_stdin); nonblock(_stdout); fflush(d_stdin); } int aal_remote::adapter_execute(int action) { std::fprintf(d_stdin, "a%i\n", action); return getint(d_stdin,d_stdout); } int aal_remote::model_execute(int action) { std::fprintf(d_stdin, "m%i\n", action); return getint(d_stdin,d_stdout); } void aal_remote::push() { std::fprintf(d_stdin,"mu\n"); fflush(d_stdin); } void aal_remote::pop() { std::fprintf(d_stdin,"mo\n"); fflush(d_stdin); } bool aal_remote::reset() { std::fprintf(d_stdin, "mr\n"); return getint(d_stdin,d_stdout); } int aal_remote::getActions(int** act) { std::fprintf(d_stdin, "ma\n"); return getact(act,actions,d_stdin,d_stdout); } int aal_remote::getprops(int** pro) { std::fprintf(d_stdin, "mp\n"); return getact(pro,tags,d_stdin,d_stdout); } #include <cstring> #include "helper.hh" namespace { std::map<std::string,aal_remote*> storage; Adapter* adapter_creator(Log& l, std::string params = "") { std::string remotename(unescape_string(strdup(params.c_str()))); aal_remote* al=storage[remotename]; if (!al) { al=new aal_remote(l,remotename); if (al->ok) { storage[remotename]=al; } else { delete al; al=NULL; } } if (al) { return new Awrapper(l,params,al); } return NULL; } Model* model_creator(Log& l, std::string params) { std::string remotename(unescape_string(strdup(params.c_str()))); aal_remote* al=storage[remotename]; if (!al) { al=new aal_remote(l,remotename); if (al->ok) { storage[remotename]=al; } else { delete al; al=NULL; } } if (al) { return new Mwrapper(l,params,al); } return NULL; } static ModelFactory ::Register Mo("aalremote", model_creator); static AdapterFactory::Register Ad("aalremote", adapter_creator); } #endif <|endoftext|>
<commit_before>#include "socket.h" // PDTK #include <cxxutils/error_helpers.h> #include <cxxutils/colors.h> namespace posix { inline bool peercred(fd_t sockfd, proccred_t& cred) noexcept { return ::peercred(sockfd, cred) == posix::success_response; } } GenericSocket::GenericSocket(EDomain domain, EType type, EProtocol protocol, int flags) noexcept : GenericSocket(posix::socket(domain, type, protocol, flags)) { } GenericSocket::GenericSocket(posix::fd_t fd) noexcept : m_connected(false), m_socket(fd) { Object::connect(m_socket, EventFlags::Readable, this, &GenericSocket::read); // monitor socket connection } GenericSocket::~GenericSocket(void) noexcept { disconnect(); } void GenericSocket::disconnect(void) noexcept { if(m_selfaddr != EDomain::unspec) { ::unlink(m_selfaddr.sun_path); m_selfaddr = EDomain::unspec; } if(m_socket != posix::invalid_descriptor) { Object::enqueue(disconnected, m_socket); Object::disconnect(m_socket, EventFlags::Readable); posix::close(m_socket); // connection severed! m_socket = posix::invalid_descriptor; } m_connected = false; } bool ClientSocket::connect(const char *socket_path) noexcept { flaw(m_connected, posix::warning,,false, "Client socket is already connected!") flaw(std::strlen(socket_path) >= sizeof(sockaddr_un::sun_path),posix::warning,,false, "socket_path exceeds the maximum path length, %lu bytes", sizeof(sockaddr_un::sun_path)) posix::sockaddr_t peeraddr; proccred_t peercred; peeraddr = socket_path; peeraddr = EDomain::local; m_selfaddr = EDomain::unspec; flaw(!posix::connect(m_socket, peeraddr, peeraddr.size()), posix::warning,, false, "connect() failure: %s", std::strerror(errno)) // connect to peer process m_connected = true; flaw(!posix::peercred(m_socket, peercred), posix::warning,, false, "peercred() failure: %s", std::strerror(errno)) // get creditials of connected peer process Object::enqueue(connected, m_socket, peeraddr, peercred); return true; } bool ClientSocket::write(const vfifo& buffer, posix::fd_t fd) noexcept { msghdr header = {}; iovec iov = {}; char aux_buffer[CMSG_SPACE(sizeof(int))] = { 0 }; header.msg_iov = &iov; header.msg_iovlen = 1; header.msg_control = aux_buffer; iov.iov_base = buffer.begin(); iov.iov_len = buffer.size(); header.msg_controllen = 0; if(fd != posix::invalid_descriptor) // if a file descriptor needs to be sent { header.msg_controllen = CMSG_SPACE(sizeof(int)); cmsghdr* cmsg = CMSG_FIRSTHDR(&header); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SCM_RIGHTS; cmsg->cmsg_len = CMSG_LEN(sizeof(int)); *reinterpret_cast<int*>(CMSG_DATA(cmsg)) = fd; } flaw(posix::sendmsg(m_socket, &header) == posix::error_response, posix::warning,,false, "sendmsg() failure: %s", std::strerror(errno)) return true; } bool ClientSocket::read(posix::fd_t socket, EventData_t event) noexcept { (void)event; msghdr header = {}; iovec iov = {}; char aux_buffer[CMSG_SPACE(sizeof(int))] = { 0 }; header.msg_iov = &iov; header.msg_iovlen = 1; header.msg_control = aux_buffer; iov.iov_base = m_buffer.begin(); iov.iov_len = m_buffer.capacity(); header.msg_controllen = sizeof(aux_buffer); posix::ssize_t byte_count = posix::recvmsg(socket, &header, 0); flaw(byte_count == posix::error_response, posix::warning,, false, "recvmsg() failure: %i : %s", errno, std::strerror(errno)) flaw(!byte_count, posix::information, disconnect(), false, "Socket disconnected.") flaw(!m_buffer.resize(byte_count), posix::severe, posix::error(std::errc::not_enough_memory), false, "Failed to resize buffer to %li bytes", byte_count) posix::fd_t fd = posix::invalid_descriptor; if(header.msg_controllen == CMSG_SPACE(sizeof(int))) { cmsghdr* cmsg = CMSG_FIRSTHDR(&header); if(cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS && cmsg->cmsg_len == CMSG_LEN(sizeof(int))) fd = *reinterpret_cast<int*>(CMSG_DATA(cmsg)); } else { flaw(header.msg_flags, posix::warning,, false, "error, message flags: 0x%04x", header.msg_flags) } Object::enqueue(newMessage, m_socket, m_buffer, fd); return true; } bool ServerSocket::bind(const char* socket_path, EDomain domain, int socket_backlog) noexcept { flaw(m_connected, posix::warning,,false, "Server socket is already bound!") flaw(socket_path == nullptr,posix::warning,,false, "socket_path is a null value") flaw(std::strlen(socket_path) >= sizeof(sockaddr_un::sun_path),posix::warning,,false, "socket_path exceeds the maximum path length, %lu bytes", sizeof(sockaddr_un::sun_path)) m_selfaddr = socket_path; m_selfaddr = domain; flaw(!posix::bind(m_socket, m_selfaddr, m_selfaddr.size()),posix::warning,,false, "Unable to bind to socket to %s: %s", socket_path, std::strerror(errno)) m_connected = true; flaw(!posix::listen(m_socket, socket_backlog),posix::warning,,false, "Unable to listen to server socket: %s", std::strerror(errno)) return true; } bool ServerSocket::peerData(posix::fd_t fd, posix::sockaddr_t* addr, proccred_t* creds) const noexcept { auto peer = m_peers.find(fd); if(peer == m_peers.end()) return false; if(addr != nullptr) *addr = peer->second.addr; if(creds != nullptr) *creds = peer->second.creds; return true; } void ServerSocket::acceptPeerRequest(posix::fd_t fd) noexcept { if(m_peers.find(fd) != m_peers.end()) { auto connection = m_connections.emplace(fd, fd).first; Object::connect(connection->second.disconnected, this, &ServerSocket::disconnectPeer); Object::connect(connection->second.newMessage, newPeerMessage); Object::enqueue(connectedPeer, fd); } } void ServerSocket::rejectPeerRequest(posix::fd_t fd) noexcept { auto peer = m_peers.find(fd); if(peer != m_peers.end()) { m_peers.erase(peer); posix::close(fd); Object::enqueue(disconnectedPeer, fd); } } void ServerSocket::disconnectPeer(posix::fd_t fd) noexcept { m_peers.erase(fd); m_connections.erase(fd); Object::enqueue(disconnectedPeer, fd); } // accepts socket connections and then enqueues newPeerRequest bool ServerSocket::read(posix::fd_t socket, EventData_t event) noexcept { (void)socket; (void)event; proccred_t peercred; posix::sockaddr_t peeraddr; socklen_t addrlen = 0; posix::fd_t fd = posix::accept(m_socket, peeraddr, &addrlen); // accept a new socket connection flaw(fd == posix::error_response, posix::warning,, false, "accept() failure: %s", std::strerror(errno)) flaw(addrlen >= sizeof(sockaddr_un::sun_path), posix::severe,, false, "accept() implementation bug: %s", "address length exceeds availible storage"); flaw(addrlen != peeraddr.size(), posix::warning,, false, "accept() implementation bug: %s", "address length does not match string length"); flaw(!posix::peercred(fd, peercred), posix::warning,, false, "peercred() failure: %s", std::strerror(errno)) // get creditials of connected peer process m_peers.emplace(fd, peer_t(fd, peeraddr, peercred)); Object::enqueue(newPeerRequest, fd, peeraddr, peercred); return true; } bool ServerSocket::write(posix::fd_t socket, const vfifo& buffer, posix::fd_t fd) noexcept { auto connection = m_connections.find(socket); if(connection != m_connections.end()) return connection->second.write(buffer, fd); return false; } <commit_msg>remove debug output<commit_after>#include "socket.h" // PDTK #include <cxxutils/error_helpers.h> #include <cxxutils/colors.h> namespace posix { inline bool peercred(fd_t sockfd, proccred_t& cred) noexcept { return ::peercred(sockfd, cred) == posix::success_response; } } GenericSocket::GenericSocket(EDomain domain, EType type, EProtocol protocol, int flags) noexcept : GenericSocket(posix::socket(domain, type, protocol, flags)) { } GenericSocket::GenericSocket(posix::fd_t fd) noexcept : m_connected(false), m_socket(fd) { Object::connect(m_socket, EventFlags::Readable, this, &GenericSocket::read); // monitor socket connection } GenericSocket::~GenericSocket(void) noexcept { disconnect(); } void GenericSocket::disconnect(void) noexcept { if(m_selfaddr != EDomain::unspec) { ::unlink(m_selfaddr.sun_path); m_selfaddr = EDomain::unspec; } if(m_socket != posix::invalid_descriptor) { Object::enqueue(disconnected, m_socket); Object::disconnect(m_socket, EventFlags::Readable); posix::close(m_socket); // connection severed! m_socket = posix::invalid_descriptor; } m_connected = false; } bool ClientSocket::connect(const char *socket_path) noexcept { flaw(m_connected, posix::warning,,false, "Client socket is already connected!") flaw(std::strlen(socket_path) >= sizeof(sockaddr_un::sun_path),posix::warning,,false, "socket_path exceeds the maximum path length, %lu bytes", sizeof(sockaddr_un::sun_path)) posix::sockaddr_t peeraddr; proccred_t peercred; peeraddr = socket_path; peeraddr = EDomain::local; m_selfaddr = EDomain::unspec; flaw(!posix::connect(m_socket, peeraddr, peeraddr.size()), posix::warning,, false, "connect() failure: %s", std::strerror(errno)) // connect to peer process m_connected = true; flaw(!posix::peercred(m_socket, peercred), posix::warning,, false, "peercred() failure: %s", std::strerror(errno)) // get creditials of connected peer process Object::enqueue(connected, m_socket, peeraddr, peercred); return true; } bool ClientSocket::write(const vfifo& buffer, posix::fd_t fd) noexcept { msghdr header = {}; iovec iov = {}; char aux_buffer[CMSG_SPACE(sizeof(int))] = { 0 }; header.msg_iov = &iov; header.msg_iovlen = 1; header.msg_control = aux_buffer; iov.iov_base = buffer.begin(); iov.iov_len = buffer.size(); header.msg_controllen = 0; if(fd != posix::invalid_descriptor) // if a file descriptor needs to be sent { header.msg_controllen = CMSG_SPACE(sizeof(int)); cmsghdr* cmsg = CMSG_FIRSTHDR(&header); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SCM_RIGHTS; cmsg->cmsg_len = CMSG_LEN(sizeof(int)); *reinterpret_cast<int*>(CMSG_DATA(cmsg)) = fd; } flaw(posix::sendmsg(m_socket, &header) == posix::error_response, posix::warning,,false, "sendmsg() failure: %s", std::strerror(errno)) return true; } bool ClientSocket::read(posix::fd_t socket, EventData_t event) noexcept { (void)event; msghdr header = {}; iovec iov = {}; char aux_buffer[CMSG_SPACE(sizeof(int))] = { 0 }; header.msg_iov = &iov; header.msg_iovlen = 1; header.msg_control = aux_buffer; iov.iov_base = m_buffer.begin(); iov.iov_len = m_buffer.capacity(); header.msg_controllen = sizeof(aux_buffer); posix::ssize_t byte_count = posix::recvmsg(socket, &header, 0); flaw(byte_count == posix::error_response, posix::warning,, false, "recvmsg() failure: %s", std::strerror(errno)) flaw(!byte_count, posix::information, disconnect(), false, "Socket disconnected.") flaw(!m_buffer.resize(byte_count), posix::severe, posix::error(std::errc::not_enough_memory), false, "Failed to resize buffer to %li bytes", byte_count) posix::fd_t fd = posix::invalid_descriptor; if(header.msg_controllen == CMSG_SPACE(sizeof(int))) { cmsghdr* cmsg = CMSG_FIRSTHDR(&header); if(cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS && cmsg->cmsg_len == CMSG_LEN(sizeof(int))) fd = *reinterpret_cast<int*>(CMSG_DATA(cmsg)); } else { flaw(header.msg_flags, posix::warning,, false, "error, message flags: 0x%04x", header.msg_flags) } Object::enqueue(newMessage, m_socket, m_buffer, fd); return true; } bool ServerSocket::bind(const char* socket_path, EDomain domain, int socket_backlog) noexcept { flaw(m_connected, posix::warning,,false, "Server socket is already bound!") flaw(socket_path == nullptr,posix::warning,,false, "socket_path is a null value") flaw(std::strlen(socket_path) >= sizeof(sockaddr_un::sun_path),posix::warning,,false, "socket_path exceeds the maximum path length, %lu bytes", sizeof(sockaddr_un::sun_path)) m_selfaddr = socket_path; m_selfaddr = domain; flaw(!posix::bind(m_socket, m_selfaddr, m_selfaddr.size()),posix::warning,,false, "Unable to bind to socket to %s: %s", socket_path, std::strerror(errno)) m_connected = true; flaw(!posix::listen(m_socket, socket_backlog),posix::warning,,false, "Unable to listen to server socket: %s", std::strerror(errno)) return true; } bool ServerSocket::peerData(posix::fd_t fd, posix::sockaddr_t* addr, proccred_t* creds) const noexcept { auto peer = m_peers.find(fd); if(peer == m_peers.end()) return false; if(addr != nullptr) *addr = peer->second.addr; if(creds != nullptr) *creds = peer->second.creds; return true; } void ServerSocket::acceptPeerRequest(posix::fd_t fd) noexcept { if(m_peers.find(fd) != m_peers.end()) { auto connection = m_connections.emplace(fd, fd).first; Object::connect(connection->second.disconnected, this, &ServerSocket::disconnectPeer); Object::connect(connection->second.newMessage, newPeerMessage); Object::enqueue(connectedPeer, fd); } } void ServerSocket::rejectPeerRequest(posix::fd_t fd) noexcept { auto peer = m_peers.find(fd); if(peer != m_peers.end()) { m_peers.erase(peer); posix::close(fd); Object::enqueue(disconnectedPeer, fd); } } void ServerSocket::disconnectPeer(posix::fd_t fd) noexcept { m_peers.erase(fd); m_connections.erase(fd); Object::enqueue(disconnectedPeer, fd); } // accepts socket connections and then enqueues newPeerRequest bool ServerSocket::read(posix::fd_t socket, EventData_t event) noexcept { (void)socket; (void)event; proccred_t peercred; posix::sockaddr_t peeraddr; socklen_t addrlen = 0; posix::fd_t fd = posix::accept(m_socket, peeraddr, &addrlen); // accept a new socket connection flaw(fd == posix::error_response, posix::warning,, false, "accept() failure: %s", std::strerror(errno)) flaw(addrlen >= sizeof(sockaddr_un::sun_path), posix::severe,, false, "accept() implementation bug: %s", "address length exceeds availible storage"); flaw(addrlen != peeraddr.size(), posix::warning,, false, "accept() implementation bug: %s", "address length does not match string length"); flaw(!posix::peercred(fd, peercred), posix::warning,, false, "peercred() failure: %s", std::strerror(errno)) // get creditials of connected peer process m_peers.emplace(fd, peer_t(fd, peeraddr, peercred)); Object::enqueue(newPeerRequest, fd, peeraddr, peercred); return true; } bool ServerSocket::write(posix::fd_t socket, const vfifo& buffer, posix::fd_t fd) noexcept { auto connection = m_connections.find(socket); if(connection != m_connections.end()) return connection->second.write(buffer, fd); return false; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: moduleoptions.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: vg $ $Date: 2007-08-30 16:43:12 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef INCLUDED_SVTOOLS_MODULEOPTIONS_HXX #define INCLUDED_SVTOOLS_MODULEOPTIONS_HXX //_________________________________________________________________________________________________________________ // includes //_________________________________________________________________________________________________________________ #ifndef INCLUDED_SVLDLLAPI_H #include "svtools/svldllapi.h" #endif #ifndef _SALHELPER_SINGLETONREF_HXX_ #include <salhelper/singletonref.hxx> #endif #ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_ #include <com/sun/star/frame/XModel.hpp> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef INCLUDED_SVTOOLS_OPTIONS_HXX #include <svtools/options.hxx> #endif //_________________________________________________________________________________________________________________ // const //_________________________________________________________________________________________________________________ #define FEATUREFLAG_BASICIDE 0x00000020 #define FEATUREFLAG_MATH 0x00000100 #define FEATUREFLAG_CHART 0x00000200 #define FEATUREFLAG_CALC 0x00000800 #define FEATUREFLAG_DRAW 0x00001000 #define FEATUREFLAG_WRITER 0x00002000 #define FEATUREFLAG_IMPRESS 0x00008000 #define FEATUREFLAG_INSIGHT 0x00010000 //_________________________________________________________________________________________________________________ // forward declarations //_________________________________________________________________________________________________________________ /*-************************************************************************************************************//** @short forward declaration to our private date container implementation @descr We use these class as internal member to support small memory requirements. You can create the container if it is neccessary. The class which use these mechanism is faster and smaller then a complete implementation! *//*-*************************************************************************************************************/ class SvtModuleOptions_Impl; //_________________________________________________________________________________________________________________ // declarations //_________________________________________________________________________________________________________________ /*-************************************************************************************************************//** @short collect informations about installation state of modules @descr Use these class to get installation state of different office modules like writer, calc etc Further you can ask for additional informations; e.g. name of standard template file, which should be used by corresponding module; or short/long name of these module factory. @implements - @base - @devstatus ready to use @threadsafe yes *//*-*************************************************************************************************************/ class SVL_DLLPUBLIC SvtModuleOptions: public svt::detail::Options { //------------------------------------------------------------------------------------------------------------- // public const declarations! //------------------------------------------------------------------------------------------------------------- public: enum EModule { E_SWRITER = 0, E_SCALC = 1, E_SDRAW = 2, E_SIMPRESS = 3, E_SMATH = 4, E_SCHART = 5, E_SSTARTMODULE = 6, E_SBASIC = 7, E_SDATABASE = 8, E_SWEB = 9, E_SGLOBAL = 10 }; /*ATTENTION: If you change these enum ... don't forget to change reading/writing and order of configuration values too! See "SvtModuleOptions_Impl::impl_GetSetNames()" and his ctor for further informations. */ enum EFactory { E_UNKNOWN_FACTORY = -1, E_WRITER = 0, E_WRITERWEB = 1, E_WRITERGLOBAL = 2, E_CALC = 3, E_DRAW = 4, E_IMPRESS = 5, E_MATH = 6, E_CHART = 7, E_STARTMODULE = 8, E_DATABASE = 9, E_BASIC = 10 }; //------------------------------------------------------------------------------------------------------------- // public methods //------------------------------------------------------------------------------------------------------------- public: //--------------------------------------------------------------------------------------------------------- // constructor / destructor //--------------------------------------------------------------------------------------------------------- SvtModuleOptions(); virtual ~SvtModuleOptions(); //--------------------------------------------------------------------------------------------------------- // interface //--------------------------------------------------------------------------------------------------------- sal_Bool IsModuleInstalled ( EModule eModule ) const; ::rtl::OUString GetModuleName ( EModule eModule ) const; ::rtl::OUString GetModuleName ( EFactory eFactory ) const; ::rtl::OUString GetFactoryName ( EFactory eFactory ) const; ::rtl::OUString GetFactoryShortName ( EFactory eFactory ) const; ::rtl::OUString GetFactoryStandardTemplate( EFactory eFactory ) const; ::rtl::OUString GetFactoryWindowAttributes( EFactory eFactory ) const; ::rtl::OUString GetFactoryEmptyDocumentURL( EFactory eFactory ) const; ::rtl::OUString GetFactoryDefaultFilter ( EFactory eFactory ) const; sal_Bool IsDefaultFilterReadonly ( EFactory eFactory ) const; sal_Int32 GetFactoryIcon ( EFactory eFactory ) const; static sal_Bool ClassifyFactoryByName ( const ::rtl::OUString& sName , EFactory& eFactory ); void SetFactoryStandardTemplate( EFactory eFactory , const ::rtl::OUString& sTemplate ); void SetFactoryWindowAttributes( EFactory eFactory , const ::rtl::OUString& sAttributes); void SetFactoryDefaultFilter ( EFactory eFactory , const ::rtl::OUString& sFilter ); //_______________________________________ /** @short return the corresponding application ID for the given document service name. */ static EFactory ClassifyFactoryByServiceName(const ::rtl::OUString& sName); //_______________________________________ /** @short return the corresponding application ID for the given short name. */ static EFactory ClassifyFactoryByShortName(const ::rtl::OUString& sName); //_______________________________________ /** @short return the corresponding application ID for the given properties. @descr Because this search base on filters currently (till we have a better solution) a result is not guaranteed everytimes. May a filter does not exists for the specified content (but a FrameLoader which is not bound to any application!) ... or the given properties describe a stream (and we make no deep detection inside here!). @attention The module BASIC cant be detected here. Because it does not has an own URL schema. @param sURL the complete URL! @param lMediaDescriptor additional informations @return A suitable enum value. See EFactory above. */ static EFactory ClassifyFactoryByURL(const ::rtl::OUString& sURL , const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lMediaDescriptor); //_______________________________________ /** @short return the corresponding application ID for the given properties. @descr Here we try to use the list of supported service names of the given model to find out the right application module. @attention The module BASIC cant be detected here. Because it does not support any model/ctrl/view paradigm. @param xModel the document model @return A suitable enum value. See EFactory above. */ static EFactory ClassifyFactoryByModel(const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& xModel); ::rtl::OUString GetDefaultModuleName(); //--------------------------------------------------------------------------------------------------------- // old interface ... //--------------------------------------------------------------------------------------------------------- sal_Bool IsMath () const; sal_Bool IsChart () const; sal_Bool IsCalc () const; sal_Bool IsDraw () const; sal_Bool IsWriter () const; sal_Bool IsImpress () const; sal_Bool IsBasicIDE () const; sal_Bool IsDataBase () const; sal_uInt32 GetFeatures() const; ::com::sun::star::uno::Sequence < ::rtl::OUString > GetAllServiceNames(); //------------------------------------------------------------------------------------------------------------- // private methods //------------------------------------------------------------------------------------------------------------- private: SVL_DLLPRIVATE static ::osl::Mutex& impl_GetOwnStaticMutex(); //------------------------------------------------------------------------------------------------------------- // private member //------------------------------------------------------------------------------------------------------------- private: /*Attention Don't initialize these static member in these header! a) Double defined symbols will be detected ... b) and unresolved externals exist at linking time. Do it in your source only. */ static SvtModuleOptions_Impl* m_pDataContainer ; /// impl. data container as dynamic pointer for smaller memory requirements! static sal_Int32 m_nRefCount ; /// internal ref count mechanism }; // class SvtModuleOptions #endif // #ifndef INCLUDED_SVTOOLS_MODULEOPTIONS_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.3.174); FILE MERGED 2008/04/01 15:44:32 thb 1.3.174.3: #i85898# Stripping all external header guards 2008/04/01 12:43:13 thb 1.3.174.2: #i85898# Stripping all external header guards 2008/03/31 13:01:06 rt 1.3.174.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: moduleoptions.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef INCLUDED_SVTOOLS_MODULEOPTIONS_HXX #define INCLUDED_SVTOOLS_MODULEOPTIONS_HXX //_________________________________________________________________________________________________________________ // includes //_________________________________________________________________________________________________________________ #include "svtools/svldllapi.h" #include <salhelper/singletonref.hxx> #include <com/sun/star/frame/XModel.hpp> #include <com/sun/star/uno/Sequence.hxx> #include <rtl/ustring.hxx> #include <sal/types.h> #include <osl/mutex.hxx> #include <svtools/options.hxx> //_________________________________________________________________________________________________________________ // const //_________________________________________________________________________________________________________________ #define FEATUREFLAG_BASICIDE 0x00000020 #define FEATUREFLAG_MATH 0x00000100 #define FEATUREFLAG_CHART 0x00000200 #define FEATUREFLAG_CALC 0x00000800 #define FEATUREFLAG_DRAW 0x00001000 #define FEATUREFLAG_WRITER 0x00002000 #define FEATUREFLAG_IMPRESS 0x00008000 #define FEATUREFLAG_INSIGHT 0x00010000 //_________________________________________________________________________________________________________________ // forward declarations //_________________________________________________________________________________________________________________ /*-************************************************************************************************************//** @short forward declaration to our private date container implementation @descr We use these class as internal member to support small memory requirements. You can create the container if it is neccessary. The class which use these mechanism is faster and smaller then a complete implementation! *//*-*************************************************************************************************************/ class SvtModuleOptions_Impl; //_________________________________________________________________________________________________________________ // declarations //_________________________________________________________________________________________________________________ /*-************************************************************************************************************//** @short collect informations about installation state of modules @descr Use these class to get installation state of different office modules like writer, calc etc Further you can ask for additional informations; e.g. name of standard template file, which should be used by corresponding module; or short/long name of these module factory. @implements - @base - @devstatus ready to use @threadsafe yes *//*-*************************************************************************************************************/ class SVL_DLLPUBLIC SvtModuleOptions: public svt::detail::Options { //------------------------------------------------------------------------------------------------------------- // public const declarations! //------------------------------------------------------------------------------------------------------------- public: enum EModule { E_SWRITER = 0, E_SCALC = 1, E_SDRAW = 2, E_SIMPRESS = 3, E_SMATH = 4, E_SCHART = 5, E_SSTARTMODULE = 6, E_SBASIC = 7, E_SDATABASE = 8, E_SWEB = 9, E_SGLOBAL = 10 }; /*ATTENTION: If you change these enum ... don't forget to change reading/writing and order of configuration values too! See "SvtModuleOptions_Impl::impl_GetSetNames()" and his ctor for further informations. */ enum EFactory { E_UNKNOWN_FACTORY = -1, E_WRITER = 0, E_WRITERWEB = 1, E_WRITERGLOBAL = 2, E_CALC = 3, E_DRAW = 4, E_IMPRESS = 5, E_MATH = 6, E_CHART = 7, E_STARTMODULE = 8, E_DATABASE = 9, E_BASIC = 10 }; //------------------------------------------------------------------------------------------------------------- // public methods //------------------------------------------------------------------------------------------------------------- public: //--------------------------------------------------------------------------------------------------------- // constructor / destructor //--------------------------------------------------------------------------------------------------------- SvtModuleOptions(); virtual ~SvtModuleOptions(); //--------------------------------------------------------------------------------------------------------- // interface //--------------------------------------------------------------------------------------------------------- sal_Bool IsModuleInstalled ( EModule eModule ) const; ::rtl::OUString GetModuleName ( EModule eModule ) const; ::rtl::OUString GetModuleName ( EFactory eFactory ) const; ::rtl::OUString GetFactoryName ( EFactory eFactory ) const; ::rtl::OUString GetFactoryShortName ( EFactory eFactory ) const; ::rtl::OUString GetFactoryStandardTemplate( EFactory eFactory ) const; ::rtl::OUString GetFactoryWindowAttributes( EFactory eFactory ) const; ::rtl::OUString GetFactoryEmptyDocumentURL( EFactory eFactory ) const; ::rtl::OUString GetFactoryDefaultFilter ( EFactory eFactory ) const; sal_Bool IsDefaultFilterReadonly ( EFactory eFactory ) const; sal_Int32 GetFactoryIcon ( EFactory eFactory ) const; static sal_Bool ClassifyFactoryByName ( const ::rtl::OUString& sName , EFactory& eFactory ); void SetFactoryStandardTemplate( EFactory eFactory , const ::rtl::OUString& sTemplate ); void SetFactoryWindowAttributes( EFactory eFactory , const ::rtl::OUString& sAttributes); void SetFactoryDefaultFilter ( EFactory eFactory , const ::rtl::OUString& sFilter ); //_______________________________________ /** @short return the corresponding application ID for the given document service name. */ static EFactory ClassifyFactoryByServiceName(const ::rtl::OUString& sName); //_______________________________________ /** @short return the corresponding application ID for the given short name. */ static EFactory ClassifyFactoryByShortName(const ::rtl::OUString& sName); //_______________________________________ /** @short return the corresponding application ID for the given properties. @descr Because this search base on filters currently (till we have a better solution) a result is not guaranteed everytimes. May a filter does not exists for the specified content (but a FrameLoader which is not bound to any application!) ... or the given properties describe a stream (and we make no deep detection inside here!). @attention The module BASIC cant be detected here. Because it does not has an own URL schema. @param sURL the complete URL! @param lMediaDescriptor additional informations @return A suitable enum value. See EFactory above. */ static EFactory ClassifyFactoryByURL(const ::rtl::OUString& sURL , const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lMediaDescriptor); //_______________________________________ /** @short return the corresponding application ID for the given properties. @descr Here we try to use the list of supported service names of the given model to find out the right application module. @attention The module BASIC cant be detected here. Because it does not support any model/ctrl/view paradigm. @param xModel the document model @return A suitable enum value. See EFactory above. */ static EFactory ClassifyFactoryByModel(const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& xModel); ::rtl::OUString GetDefaultModuleName(); //--------------------------------------------------------------------------------------------------------- // old interface ... //--------------------------------------------------------------------------------------------------------- sal_Bool IsMath () const; sal_Bool IsChart () const; sal_Bool IsCalc () const; sal_Bool IsDraw () const; sal_Bool IsWriter () const; sal_Bool IsImpress () const; sal_Bool IsBasicIDE () const; sal_Bool IsDataBase () const; sal_uInt32 GetFeatures() const; ::com::sun::star::uno::Sequence < ::rtl::OUString > GetAllServiceNames(); //------------------------------------------------------------------------------------------------------------- // private methods //------------------------------------------------------------------------------------------------------------- private: SVL_DLLPRIVATE static ::osl::Mutex& impl_GetOwnStaticMutex(); //------------------------------------------------------------------------------------------------------------- // private member //------------------------------------------------------------------------------------------------------------- private: /*Attention Don't initialize these static member in these header! a) Double defined symbols will be detected ... b) and unresolved externals exist at linking time. Do it in your source only. */ static SvtModuleOptions_Impl* m_pDataContainer ; /// impl. data container as dynamic pointer for smaller memory requirements! static sal_Int32 m_nRefCount ; /// internal ref count mechanism }; // class SvtModuleOptions #endif // #ifndef INCLUDED_SVTOOLS_MODULEOPTIONS_HXX <|endoftext|>
<commit_before>#include <iostream> #include <boost/filesystem.hpp> #include <boost/date_time/posix_time/posix_time.hpp> using namespace std; using namespace boost::filesystem; using namespace boost::posix_time; #define STATS 0 #define LIST 1 #define ALL 2 #define STATS_ARG "--stats" #define LIST_ARG "--list" #define ALL_ARG "--all" int main(int argc, char* argv[]) { if (argc < 2) { // If no input file argument provided - error cout << "Input file missing!\n"; cout << "Try again: " << argv[0] << " <filename> --optionalArgument\n"; cout << "\n"; // Arguments info: cout << "--stats\nOutputs statistical information about time stamp anomalies.\n"; cout << "--list\nOutputs lines with erroneous time stamps along with line numbers.\n"; cout << "--all\nOutputs lines with erroneous time stamps along with line numbers and statistical information about time stamp anomalies.\n"; return -1; } try { path p(argv[1]); if (exists(p)) { if (!is_regular_file(p)) { cout << "Not regular file provided!\n"; return -1; } // Open file after checking that it exists and is regular std::ifstream file(p.c_str()); long fileLines = count(istreambuf_iterator<char>(file), istreambuf_iterator<char>(), '\n') + 1; // Go back to beginning of file file.clear(); file.seekg(0, ios::beg); // Reading every line into vector string str; vector<string> lines; while (getline(file, str)) { lines.push_back(str); } // Parsing date-time and checking for errors const locale loc = locale(locale::classic(), new time_input_facet("%Y-%m-%d %H:%M:%s")); ptime* lastNormalTimestamp = NULL; int lastNormalTimestampLine = 1; vector<int> invalidTimestampsLines; for (int i = 0; i < fileLines; ++i) { // PARSING PART string lineDate = lines[i].substr(0, 23); istringstream is(lineDate); is.imbue(loc); ptime currentTimestamp; is >> currentTimestamp; // ERROR CHECKING PART if (lastNormalTimestamp != NULL && (lastNormalTimestamp->time_of_day() > currentTimestamp.time_of_day() || lastNormalTimestamp->date() > currentTimestamp.date())) { invalidTimestampsLines.push_back(i + 1); cout << "Line invalid : " << (i + 1) << "\n"; } else { free(lastNormalTimestamp); lastNormalTimestamp = new ptime(currentTimestamp); } } // Checking additional action argument: int action = STATS; if (argc > 2 && argv[2] != STATS) { if (argv[2] != LIST_ARG && argv[2] != ALL_ARG) { cout << "Wrong action. Default action '--stats' selected instead."; } else { action = ALL; if (argv[2] == LIST_ARG) { action = LIST; } } } if (action == STATS || action == ALL) { cout << "Number of lines:\n" << fileLines << "\n"; cout << "Invalid time stamps at line(s):\n"; // Showing line numbers here cout << "\n"; } if (action == LIST || action == ALL) { // Showing lines here } } else { cout << "File does not exist!\n"; return -1; } } catch (const filesystem_error& ex) { cout << "Error occured!\n" << ex.what() << '\n'; return -1; } return 0; } <commit_msg>Final Working Version<commit_after>#include <iostream> #include <boost/filesystem.hpp> #include <boost/date_time/posix_time/posix_time.hpp> using namespace std; using namespace boost::filesystem; using namespace boost::posix_time; #define STATS 0 #define LIST 1 #define ALL 2 #define STATS_ARG "--stats" #define LIST_ARG "--list" #define ALL_ARG "--all" int main(int argc, char* argv[]) { if (argc < 2) { // If no input file argument provided - error cout << "Input file missing!\n"; cout << "Try again: " << argv[0] << " <filename> --optionalArgument\n"; cout << "\n"; // Arguments info: cout << "--stats\nOutputs statistical information about time stamp anomalies.\n"; cout << "--list\nOutputs lines with erroneous time stamps along with line numbers.\n"; cout << "--all\nOutputs lines with erroneous time stamps along with line numbers and statistical information about time stamp anomalies.\n"; return -1; } try { path p(argv[1]); if (exists(p)) { if (!is_regular_file(p)) { cout << "Not regular file provided!\n"; return -1; } // Open file after checking that it exists and is regular std::ifstream file(p.c_str()); long fileLines = count(istreambuf_iterator<char>(file), istreambuf_iterator<char>(), '\n') + 1; // Go back to beginning of file file.clear(); file.seekg(0, ios::beg); // Reading every line into vector string str; vector<string> lines; while (getline(file, str)) { lines.push_back(str); } // Parsing date-time and checking for errors const locale loc = locale(locale::classic(), new time_input_facet("%Y-%m-%d %H:%M:%s")); ptime* lastNormalTimestamp = NULL; vector<int> invalidTimestampsLines; int i, totalInvalidTimestamps = 0; for (i = 0; i < fileLines; ++i) { // PARSING PART string lineDate = lines[i].substr(0, 23); istringstream is(lineDate); is.imbue(loc); ptime currentTimestamp; is >> currentTimestamp; // ERROR CHECKING PART if (lastNormalTimestamp != NULL && (lastNormalTimestamp->time_of_day() > currentTimestamp.time_of_day() || lastNormalTimestamp->date() > currentTimestamp.date())) { invalidTimestampsLines.push_back(i); totalInvalidTimestamps++; } else { free(lastNormalTimestamp); lastNormalTimestamp = new ptime(currentTimestamp); } } // Checking additional action argument: int action = STATS; if (argc > 2 && strcmp(argv[2], STATS_ARG) != 0) { if (strcmp(argv[2], LIST_ARG) != 0 && strcmp(argv[2], ALL_ARG) != 0) { cout << "Wrong action. Default action '--stats' selected instead."; } else { action = ALL; if (strcmp(argv[2], LIST_ARG) == 0) { action = LIST; } } } if (action == STATS || action == ALL) { cout << "Number of lines:\n" << fileLines << "\n"; cout << "Invalid time stamps at line(s):\n"; bool isRange = false; string output; for (i = 0; i < totalInvalidTimestamps; ++i) { // Starting point ("x") if (!isRange) { output = to_string(invalidTimestampsLines[i] + 1); } // Check if next line number is next to this to form a range ("x-") if (i + 1 != totalInvalidTimestamps && !isRange && invalidTimestampsLines[i + 1] + 1 == invalidTimestampsLines[i] + 2) { isRange = true; output += "-"; } if (isRange) { // Check if there is no more line numbers in this range to close it ("x-y") if (i + 1 == totalInvalidTimestamps || invalidTimestampsLines[i + 1] + 1 != invalidTimestampsLines[i] + 2) { output += to_string(invalidTimestampsLines[i] + 1); isRange = false; } else { continue; } } cout << output << "\n"; } cout << "\n"; } if (action == LIST || action == ALL) { int currentInvalidTimestampLine; for (i = 0; i < totalInvalidTimestamps; ++i) { currentInvalidTimestampLine = invalidTimestampsLines[i]; // Normal entry before the invalid timestamp if (currentInvalidTimestampLine > 0 && (i == 0 || invalidTimestampsLines[i - 1] != currentInvalidTimestampLine - 1)) { cout << "[" << currentInvalidTimestampLine << "] " + lines[currentInvalidTimestampLine - 1] << "\n"; } // Invalid timestamp entry cout << "[" << currentInvalidTimestampLine + 1 << "] " + lines[currentInvalidTimestampLine] << "\n"; // Normal entry after invalid timestamp if (currentInvalidTimestampLine + 1 < fileLines && (i + 1 == totalInvalidTimestamps || invalidTimestampsLines[i + 1] != currentInvalidTimestampLine + 1)) { cout << "[" << currentInvalidTimestampLine + 2 << "] " + lines[currentInvalidTimestampLine + 1] << "\n"; cout << "---" << "\n"; } } } } else { cout << "File does not exist!\n"; return -1; } } catch (const filesystem_error& ex) { cout << "Error occured!\n" << ex.what() << '\n'; return -1; } return 0; } <|endoftext|>
<commit_before>#include <jansson.h> #include <vector> #include "utils/translate-commit-desc.h" #include "event.h" namespace { QString getStringFromJson(const json_t *json, const char* key) { return QString::fromUtf8(json_string_value(json_object_get(json, key))); } const char *kEventTypeRepoCreate = "repo-create"; const char *kEventTypeRepoDelete = "repo-delete"; } // namespace SeafEvent SeafEvent::fromJSON(const json_t *json, json_error_t */* error */) { SeafEvent event; event.author = getStringFromJson(json, "author"); if (event.author.isEmpty()) { event.author = "anonymous"; event.anonymous = true; } else { event.anonymous = false; } event.nick = getStringFromJson(json, "nick"); if (event.nick.isEmpty()) { event.nick = "anonymous"; } event.repo_id = getStringFromJson(json, "repo_id"); event.repo_name = getStringFromJson(json, "repo_name"); event.commit_id = getStringFromJson(json, "commit_id"); event.etype = getStringFromJson(json, "etype"); event.desc = getStringFromJson(json, "desc"); event.timestamp = json_integer_value(json_object_get(json, "time")); if (event.etype == kEventTypeRepoCreate) { event.desc = QObject::tr("Created library \"%1\"").arg(event.repo_name); } else if (event.etype == kEventTypeRepoDelete) { event.desc = QObject::tr("Deleted library \"%1\"").arg(event.repo_name); } event.desc = translateCommitDesc(event.desc); return event; } std::vector<SeafEvent> SeafEvent::listFromJSON(const json_t *json, json_error_t *error) { std::vector<SeafEvent> events; for (size_t i = 0; i < json_array_size(json); i++) { SeafEvent event = fromJSON(json_array_get(json, i), error); events.push_back(event); } return events; } QString SeafEvent::toString() const { return QString("type=\"%1\",author=\"%2\",repo_name=\"%3\",desc=\"%4\",commit=\"%5\"") .arg(etype).arg(author).arg(repo_name).arg(desc).arg(commit_id); } bool SeafEvent::isDetailsDisplayable() const { if (commit_id.isEmpty()) { return false; } // TODO: determine if there are files change in this commit return true; } <commit_msg>handle the timestamp part neatly<commit_after>#include <jansson.h> #include <vector> #include "utils/translate-commit-desc.h" #include "event.h" namespace { QString getStringFromJson(const json_t *json, const char* key) { return QString::fromUtf8(json_string_value(json_object_get(json, key))); } const char *kEventTypeRepoCreate = "repo-create"; const char *kEventTypeRepoDelete = "repo-delete"; } // namespace SeafEvent SeafEvent::fromJSON(const json_t *json, json_error_t */* error */) { SeafEvent event; event.author = getStringFromJson(json, "author"); if (event.author.isEmpty()) { event.author = "anonymous"; event.anonymous = true; } else { event.anonymous = false; } event.nick = getStringFromJson(json, "nick"); if (event.nick.isEmpty()) { event.nick = "anonymous"; } event.repo_id = getStringFromJson(json, "repo_id"); event.repo_name = getStringFromJson(json, "repo_name"); event.commit_id = getStringFromJson(json, "commit_id"); event.etype = getStringFromJson(json, "etype"); event.desc = getStringFromJson(json, "desc"); // the server might return float type integer which needs to be handled // neatly. event.timestamp = json_number_value(json_object_get(json, "time")); if (event.etype == kEventTypeRepoCreate) { event.desc = QObject::tr("Created library \"%1\"").arg(event.repo_name); // handle neatly with the server returning event.timestamp /= 1000; } else if (event.etype == kEventTypeRepoDelete) { event.desc = QObject::tr("Deleted library \"%1\"").arg(event.repo_name); // handle neatly with the server returning event.timestamp /= 1000; } event.desc = translateCommitDesc(event.desc); return event; } std::vector<SeafEvent> SeafEvent::listFromJSON(const json_t *json, json_error_t *error) { std::vector<SeafEvent> events; for (size_t i = 0; i < json_array_size(json); i++) { SeafEvent event = fromJSON(json_array_get(json, i), error); events.push_back(event); } return events; } QString SeafEvent::toString() const { return QString("type=\"%1\",author=\"%2\",repo_name=\"%3\",desc=\"%4\",commit=\"%5\"") .arg(etype).arg(author).arg(repo_name).arg(desc).arg(commit_id); } bool SeafEvent::isDetailsDisplayable() const { if (commit_id.isEmpty()) { return false; } // TODO: determine if there are files change in this commit return true; } <|endoftext|>
<commit_before>#include "internal.hpp" #include "macros.hpp" #include "message.hpp" #include <algorithm> namespace CaDiCaL { bool Internal::block_clause_on_literal (Clause * c, int pivot) { assert (!val (pivot)); assert (!eliminated (pivot)); LOG (c, "trying to block on %d", pivot); mark (c); assert (marked (pivot) > 0); Occs & os = occs (-pivot); const const_occs_iterator eos = os.end (); occs_iterator sos = os.begin (), i; for (i = sos; i != eos; i++) { Clause * d = *i; if (d->garbage) continue; const const_literal_iterator eoc = d->end (); const_literal_iterator l; bool satisfied = false; for (l = d->begin (); !satisfied && l != eoc; l++) { const int lit = *l; if (lit == -pivot) continue; const int tmp = val (lit); if (tmp > 0) satisfied = true; else if (tmp < 0) continue; else if (marked (lit) < 0) { LOG (d, "clashing literal %d", lit); break; } } if (satisfied) mark_garbage (d); else if (l == eoc) { LOG (d, "non-tautological resolution candidate on %d", pivot); break; } } unmark (c); if (i == eos) return true; if (i != sos) { occs_iterator j; Clause * last = *i; for (j = sos; j != i; j++) swap (last, *j); *i = last; } return false; } struct more_negated_occs { Internal * internal; more_negated_occs (Internal * i) : internal (i) { } bool operator () (int l, int k) const { long m = internal->occs (-l).size (); long n = internal->occs (-k).size (); if (m > n) return true; if (m < n) return false; int i = abs (k), j = abs (l); if (i > j) return true; if (i < j) return false; return l < k; } }; void Internal::block () { assert (!level); assert (!watches ()); if (!opts.block) return; START (block); stats.blockings++; LOG ("starting blocked clause elimination on %ld clauses", stats.irredundant); long before = stats.blocked, oldirr = stats.irredundant; init_occs (); const_clause_iterator i; for (i = clauses.begin (); i != clauses.end (); i++) { Clause * c = *i; if (c->redundant || c->garbage) continue; const const_literal_iterator eol = c->end (); const_literal_iterator l; bool satisfied = false; for (l = c->begin (); !satisfied && l != eol; l++) { const int lit = *l, tmp = val (lit); if (tmp > 0) satisfied = true; else if (!tmp) occs (lit).push_back (c); } if (satisfied) mark_garbage (c); } for (int idx = 1; idx <= max_var; idx++) { if (val (idx) || eliminated (idx)) continue; for (int sign = -1; sign <= 1; sign += 2) { const int lit = sign*idx; Occs & os = occs (lit); stable_sort (os.begin (), os.end (), smaller_size ()); } } vector<int> schedule; char * scheduled; NEW (scheduled, char, 2*(max_var + 1)); ZERO (scheduled, char, 2*(max_var + 1)); scheduled += max_var; for (int idx = 1; idx <= max_var; idx++) { if (val (idx)) continue; if (eliminated (idx)) continue; if (!flags (idx).removed) continue; schedule.push_back (idx); schedule.push_back (-idx); scheduled[idx] = scheduled[-idx] = 1; } sort (schedule.begin (), schedule.end (), more_negated_occs (internal)); LOG ("scheduled %ld literals", (long) schedule.size ()); while (!schedule.empty ()) { int lit = schedule.back (); schedule.pop_back (); assert (scheduled[lit]); scheduled[lit] = 0; Occs & os = occs (lit); LOG ("trying to block %ld clauses on %d", (long) os.size (), lit); const const_occs_iterator eor = os.end (); occs_iterator j = os.begin (); const_occs_iterator i; for (i = j; i != eor; i++) { Clause * c = *i; if (c->garbage) continue; if (block_clause_on_literal (c, lit)) { LOG (c, "blocked on %d", lit); push_on_extension_stack (c, lit); const const_literal_iterator eoc = c->end (); const_literal_iterator l; for (l = c->begin (); l != eoc; l++) { const int other = *l; if (val (other)) continue; if (scheduled[-other]) continue; scheduled[-other] = 1; schedule.push_back (-other); } stats.blocked++; mark_garbage (c); } else *j++ = c; } os.resize (j - os.begin ()); } scheduled -= max_var; DEL (scheduled, char, 2*(max_var + 1)); erase_vector (schedule); reset_occs (); long blocked = stats.blocked - before; VRB ("block", stats.blockings, "blocked %ld clauses out of %.2f%% (%.0f%% remain)", blocked, percent (blocked, oldirr), percent (stats.irredundant, stats.original)); report ('b'); STOP (block); } }; <commit_msg>removed sorting of occs lists block<commit_after>#include "internal.hpp" #include "macros.hpp" #include "message.hpp" #include <algorithm> namespace CaDiCaL { bool Internal::block_clause_on_literal (Clause * c, int pivot) { assert (!val (pivot)); assert (!eliminated (pivot)); LOG (c, "trying to block on %d", pivot); mark (c); assert (marked (pivot) > 0); Occs & os = occs (-pivot); const const_occs_iterator eos = os.end (); occs_iterator sos = os.begin (), i; for (i = sos; i != eos; i++) { Clause * d = *i; if (d->garbage) continue; const const_literal_iterator eoc = d->end (); const_literal_iterator l; bool satisfied = false; for (l = d->begin (); !satisfied && l != eoc; l++) { const int lit = *l; if (lit == -pivot) continue; const int tmp = val (lit); if (tmp > 0) satisfied = true; else if (tmp < 0) continue; else if (marked (lit) < 0) { LOG (d, "clashing literal %d", lit); break; } } if (satisfied) mark_garbage (d); else if (l == eoc) { LOG (d, "non-tautological resolution candidate on %d", pivot); break; } } unmark (c); if (i == eos) return true; if (i != sos) { occs_iterator j; Clause * last = *i; for (j = sos; j != i; j++) swap (last, *j); *i = last; } return false; } struct more_negated_occs { Internal * internal; more_negated_occs (Internal * i) : internal (i) { } bool operator () (int l, int k) const { long m = internal->occs (-l).size (); long n = internal->occs (-k).size (); if (m > n) return true; if (m < n) return false; int i = abs (k), j = abs (l); if (i > j) return true; if (i < j) return false; return l < k; } }; void Internal::block () { assert (!level); assert (!watches ()); if (!opts.block) return; START (block); stats.blockings++; LOG ("starting blocked clause elimination on %ld clauses", stats.irredundant); long before = stats.blocked, oldirr = stats.irredundant; init_occs (); const_clause_iterator i; for (i = clauses.begin (); i != clauses.end (); i++) { Clause * c = *i; if (c->redundant || c->garbage) continue; const const_literal_iterator eol = c->end (); const_literal_iterator l; bool satisfied = false; for (l = c->begin (); !satisfied && l != eol; l++) { const int lit = *l, tmp = val (lit); if (tmp > 0) satisfied = true; else if (!tmp) occs (lit).push_back (c); } if (satisfied) mark_garbage (c); } vector<int> schedule; char * scheduled; NEW (scheduled, char, 2*(max_var + 1)); ZERO (scheduled, char, 2*(max_var + 1)); scheduled += max_var; for (int idx = 1; idx <= max_var; idx++) { if (val (idx)) continue; if (eliminated (idx)) continue; if (!flags (idx).removed) continue; schedule.push_back (idx); schedule.push_back (-idx); scheduled[idx] = scheduled[-idx] = 1; } sort (schedule.begin (), schedule.end (), more_negated_occs (internal)); LOG ("scheduled %ld literals", (long) schedule.size ()); while (!schedule.empty ()) { int lit = schedule.back (); schedule.pop_back (); assert (scheduled[lit]); scheduled[lit] = 0; Occs & os = occs (lit); LOG ("trying to block %ld clauses on %d", (long) os.size (), lit); const const_occs_iterator eor = os.end (); occs_iterator j = os.begin (); const_occs_iterator i; for (i = j; i != eor; i++) { Clause * c = *i; if (c->garbage) continue; if (block_clause_on_literal (c, lit)) { LOG (c, "blocked on %d", lit); push_on_extension_stack (c, lit); const const_literal_iterator eoc = c->end (); const_literal_iterator l; for (l = c->begin (); l != eoc; l++) { const int other = *l; if (val (other)) continue; if (scheduled[-other]) continue; scheduled[-other] = 1; schedule.push_back (-other); } stats.blocked++; mark_garbage (c); } else *j++ = c; } os.resize (j - os.begin ()); } scheduled -= max_var; DEL (scheduled, char, 2*(max_var + 1)); erase_vector (schedule); reset_occs (); long blocked = stats.blocked - before; VRB ("block", stats.blockings, "blocked %ld clauses out of %.2f%% (%.0f%% remain)", blocked, percent (blocked, oldirr), percent (stats.irredundant, stats.original)); report ('b'); STOP (block); } }; <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // // File contains modifications by: The Gulden developers // All modifications: // Copyright (c) 2017-2018 The Gulden developers // Authored by: Malcolm MacLeod (mmacleod@webmail.co.za) // Distributed under the GULDEN software license, see the accompanying // file COPYING #include "chain.h" /** * CChain implementation */ void CChain::SetTip(CBlockIndex *pindex) { if (pindex == NULL) { vChain.clear(); return; } vChain.resize(pindex->nHeight + 1); while (pindex && vChain[pindex->nHeight] != pindex) { vChain[pindex->nHeight] = pindex; pindex = pindex->pprev; } } CBlockLocator CChain::GetLocatorLegacy(const CBlockIndex *pindex) const { int nStep = 1; std::vector<uint256> vHave; vHave.reserve(32); if (!pindex) pindex = Tip(); while (pindex) { vHave.push_back(pindex->GetBlockHashLegacy()); // Stop when we have added the genesis block. if (pindex->nHeight == 0) break; // Exponentially larger steps back, plus the genesis block. int nHeight = std::max(pindex->nHeight - nStep, 0); if (Contains(pindex)) { // Use O(1) CChain index if possible. pindex = (*this)[nHeight]; } else { // Otherwise, use O(log n) skiplist. pindex = pindex->GetAncestor(nHeight); } if (vHave.size() > 10) nStep *= 2; } return CBlockLocator(vHave); } CBlockLocator CChain::GetLocatorPoW2(const CBlockIndex *pindex) const { int nStep = 1; std::vector<uint256> vHave; vHave.reserve(32); if (!pindex) pindex = Tip(); while (pindex) { vHave.push_back(pindex->GetBlockHashPoW2()); // Stop when we have added the genesis block. if (pindex->nHeight == 0) break; // Exponentially larger steps back, plus the genesis block. int nHeight = std::max(pindex->nHeight - nStep, 0); if (Contains(pindex)) { // Use O(1) CChain index if possible. pindex = (*this)[nHeight]; } else { // Otherwise, use O(log n) skiplist. pindex = pindex->GetAncestor(nHeight); } if (vHave.size() > 10) nStep *= 2; } return CBlockLocator(vHave); } const CBlockIndex *CChain::FindFork(const CBlockIndex *pindex) const { if (pindex == NULL) { return NULL; } if (pindex->nHeight > Height()) pindex = pindex->GetAncestor(Height()); while (pindex && !Contains(pindex)) pindex = pindex->pprev; return pindex; } void CCloneChain::FreeMemory() { for (auto index : vFree) { if (vChain[index->nHeight - cloneFrom] == index) vChain[index->nHeight - cloneFrom] = nullptr; delete index; } for (auto index : vChain) { if (index) { delete index; } } vFree.clear(); vChain.clear(); } CCloneChain::CCloneChain(const CChain& _origin, unsigned int _cloneFrom, const CBlockIndex *retainIndexIn, CBlockIndex *&retainIndexOut) : CChain(), origin(_origin), cloneFrom(_cloneFrom) { //fixme: (2.0.x) - Temporarily allow nested cloning 'getwitnessinfo' needs this; however we should fix this in the near future. // NB! Nested cloning is okay IFF we stick to a fixed clone height, the second we start trying to optimise by using a non-fixed clone height there will be problems. // forbid nested cloning //assert(dynamic_cast<const CCloneChain*>(&origin) == nullptr); assert(cloneFrom >=0 && cloneFrom <= origin.Height()); vChain.reserve(origin.Height() + 1 - cloneFrom); vFree.reserve(origin.Height() + 1 - cloneFrom); CBlockIndex* pprev = nullptr; for (int i=cloneFrom; i<=origin.Height(); i++) { CBlockIndex* index = origin[i]; vChain.emplace_back(new CBlockIndex(*index)); vFree.push_back(vChain.back()); if (pprev) vChain.back()->pprev = pprev; vChain.back()->pskip = nullptr; vChain.back()->BuildSkip(); pprev = vChain.back(); if (index == retainIndexIn) retainIndexOut = pprev; } // case where retainIndexIn is in the chain before the part we've cloned // you better know what you're doing! if (!retainIndexOut && origin.Contains(retainIndexIn)) retainIndexOut = const_cast<CBlockIndex*>(retainIndexIn); if (retainIndexIn && !retainIndexOut) { // Link the pprev(s) of our new potential tip with a new pointer thats inside the cloned chain instead of the old pointer to the old chain. retainIndexOut = new CBlockIndex(*retainIndexIn); { //Don't worry about leaks, these become part of tempChain and are cleaned up along with tempChain. CBlockIndex* pNotInChain = retainIndexOut; // We might be sitting multiple blocks ahead of the chain, in which case we need to clone those blocks as well. while (pNotInChain->pprev->nHeight > Tip()->nHeight || pNotInChain->pprev->GetBlockHashPoW2() != vChain[pNotInChain->pprev->nHeight]->GetBlockHashPoW2()) { pNotInChain->pskip = nullptr; pNotInChain->pprev = new CBlockIndex(*pNotInChain->pprev); pNotInChain = pNotInChain->pprev; } while (pNotInChain->pprev != vChain[pNotInChain->pprev->nHeight]) { pNotInChain->pskip = nullptr; pNotInChain->pprev = vChain[pNotInChain->pprev->nHeight]; pNotInChain = pNotInChain->pprev; } } } } CBlockIndex *CCloneChain::operator[](int nHeight) const { if (nHeight >= cloneFrom && nHeight <= Height()) { return vChain[nHeight - cloneFrom]; } else return origin[nHeight]; } int CCloneChain::Height() const { return cloneFrom + vChain.size() - 1; } void CCloneChain::SetTip(CBlockIndex *pindex) { // not allowed to modify origin chain assert(pindex != nullptr && pindex->nHeight >= cloneFrom); vChain.resize(pindex->nHeight - cloneFrom + 1); while (pindex && vChain[pindex->nHeight - cloneFrom] != pindex) { vChain[pindex->nHeight - cloneFrom] = pindex; pindex = pindex->pprev; } } CBlockIndex* CChain::FindEarliestAtLeast(int64_t nTime) const { int first = 0; int it = 0; int count = Height() + 1; while (count > 0) { int step = count / 2; it += step; if (operator[](it)->GetBlockTimeMax() < nTime) { first = ++it; count -= step + 1; } else count = step; } return first <= Height() ? operator [](first) : nullptr; } /** Turn the lowest '1' bit in the binary representation of a number into a '0'. */ int static inline InvertLowestOne(int n) { return n & (n - 1); } /** Compute what height to jump back to with the CBlockIndex::pskip pointer. */ int static inline GetSkipHeight(int height) { if (height < 2) return 0; // Determine which height to jump back to. Any number strictly lower than height is acceptable, // but the following expression seems to perform well in simulations (max 110 steps to go back // up to 2**18 blocks). return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height); } CBlockIndex* CBlockIndex::GetAncestor(int height) { if (height > (int)nHeight || height < 0) return NULL; CBlockIndex* pindexWalk = this; int heightWalk = nHeight; while (heightWalk > height) { int heightSkip = GetSkipHeight(heightWalk); int heightSkipPrev = GetSkipHeight(heightWalk - 1); if (pindexWalk->pskip != NULL && (heightSkip == height || (heightSkip > height && !(heightSkipPrev < heightSkip - 2 && heightSkipPrev >= height)))) { // Only follow pskip if pprev->pskip isn't better than pskip->pprev. pindexWalk = pindexWalk->pskip; heightWalk = heightSkip; } else { assert(pindexWalk->pprev); pindexWalk = pindexWalk->pprev; heightWalk--; } } return pindexWalk; } const CBlockIndex* CBlockIndex::GetAncestor(int height) const { return const_cast<CBlockIndex*>(this)->GetAncestor(height); } void CBlockIndex::BuildSkip() { if (pprev) pskip = pprev->GetAncestor(GetSkipHeight(nHeight)); } arith_uint256 GetBlockProof(const CBlockIndex& block) { arith_uint256 bnTarget; bool fNegative; bool fOverflow; bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow); if (fNegative || fOverflow || bnTarget == 0) return 0; // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256 // as it's too large for a arith_uint256. However, as 2**256 is at least as large // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1, // or ~bnTarget / (nTarget+1) + 1. return (~bnTarget / (bnTarget + 1)) + 1; } int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params) { arith_uint256 r; int sign = 1; if (to.nChainWork > from.nChainWork) { r = to.nChainWork - from.nChainWork; } else { r = from.nChainWork - to.nChainWork; sign = -1; } r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip); if (r.bits() > 63) { return sign * std::numeric_limits<int64_t>::max(); } return sign * r.GetLow64(); } <commit_msg>Fix an error in recent CloneChain changes, picked up in further testing.<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // // File contains modifications by: The Gulden developers // All modifications: // Copyright (c) 2017-2018 The Gulden developers // Authored by: Malcolm MacLeod (mmacleod@webmail.co.za) // Distributed under the GULDEN software license, see the accompanying // file COPYING #include "chain.h" /** * CChain implementation */ void CChain::SetTip(CBlockIndex *pindex) { if (pindex == NULL) { vChain.clear(); return; } vChain.resize(pindex->nHeight + 1); while (pindex && vChain[pindex->nHeight] != pindex) { vChain[pindex->nHeight] = pindex; pindex = pindex->pprev; } } CBlockLocator CChain::GetLocatorLegacy(const CBlockIndex *pindex) const { int nStep = 1; std::vector<uint256> vHave; vHave.reserve(32); if (!pindex) pindex = Tip(); while (pindex) { vHave.push_back(pindex->GetBlockHashLegacy()); // Stop when we have added the genesis block. if (pindex->nHeight == 0) break; // Exponentially larger steps back, plus the genesis block. int nHeight = std::max(pindex->nHeight - nStep, 0); if (Contains(pindex)) { // Use O(1) CChain index if possible. pindex = (vChain)[nHeight]; } else { // Otherwise, use O(log n) skiplist. pindex = pindex->GetAncestor(nHeight); } if (vHave.size() > 10) nStep *= 2; } return CBlockLocator(vHave); } CBlockLocator CChain::GetLocatorPoW2(const CBlockIndex *pindex) const { int nStep = 1; std::vector<uint256> vHave; vHave.reserve(32); if (!pindex) pindex = Tip(); while (pindex) { vHave.push_back(pindex->GetBlockHashPoW2()); // Stop when we have added the genesis block. if (pindex->nHeight == 0) break; // Exponentially larger steps back, plus the genesis block. int nHeight = std::max(pindex->nHeight - nStep, 0); if (Contains(pindex)) { // Use O(1) CChain index if possible. pindex = vChain[nHeight]; } else { // Otherwise, use O(log n) skiplist. pindex = pindex->GetAncestor(nHeight); } if (vHave.size() > 10) nStep *= 2; } return CBlockLocator(vHave); } const CBlockIndex *CChain::FindFork(const CBlockIndex *pindex) const { if (pindex == NULL) { return NULL; } if (pindex->nHeight > Height()) pindex = pindex->GetAncestor(Height()); while (pindex && !Contains(pindex)) pindex = pindex->pprev; return pindex; } void CCloneChain::FreeMemory() { for (auto index : vFree) { if (vChain[index->nHeight - cloneFrom] == index) vChain[index->nHeight - cloneFrom] = nullptr; delete index; } for (auto index : vChain) { if (index) { delete index; } } vFree.clear(); vChain.clear(); } CCloneChain::CCloneChain(const CChain& _origin, unsigned int _cloneFrom, const CBlockIndex *retainIndexIn, CBlockIndex *&retainIndexOut) : CChain(), origin(_origin), cloneFrom(_cloneFrom) { //fixme: (2.0.x) - Temporarily allow nested cloning 'getwitnessinfo' needs this; however we should fix this in the near future. // NB! Nested cloning is okay IFF we stick to a fixed clone height, the second we start trying to optimise by using a non-fixed clone height there will be problems. // forbid nested cloning //assert(dynamic_cast<const CCloneChain*>(&origin) == nullptr); assert(cloneFrom >=0 && cloneFrom <= origin.Height()); vChain.reserve(origin.Height() + 1 - cloneFrom); vFree.reserve(origin.Height() + 1 - cloneFrom); CBlockIndex* pprev = nullptr; for (int i=cloneFrom; i<=origin.Height(); i++) { CBlockIndex* index = origin[i]; vChain.emplace_back(new CBlockIndex(*index)); vFree.push_back(vChain.back()); if (pprev) vChain.back()->pprev = pprev; vChain.back()->pskip = nullptr; vChain.back()->BuildSkip(); pprev = vChain.back(); if (index == retainIndexIn) retainIndexOut = pprev; } // case where retainIndexIn is in the chain before the part we've cloned // you better know what you're doing! if (!retainIndexOut && origin.Contains(retainIndexIn)) retainIndexOut = const_cast<CBlockIndex*>(retainIndexIn); if (retainIndexIn && !retainIndexOut) { // Link the pprev(s) of our new potential tip with a new pointer thats inside the cloned chain instead of the old pointer to the old chain. retainIndexOut = new CBlockIndex(*retainIndexIn); { //Don't worry about leaks, these become part of tempChain and are cleaned up along with tempChain. CBlockIndex* pNotInChain = retainIndexOut; // We might be sitting multiple blocks ahead of the chain, in which case we need to clone those blocks as well. while (pNotInChain->pprev->nHeight > Tip()->nHeight || pNotInChain->pprev->GetBlockHashPoW2() != vChain[pNotInChain->pprev->nHeight - cloneFrom]->GetBlockHashPoW2()) { pNotInChain->pskip = nullptr; pNotInChain->pprev = new CBlockIndex(*pNotInChain->pprev); pNotInChain = pNotInChain->pprev; } while (pNotInChain->pprev != vChain[pNotInChain->pprev->nHeight - cloneFrom]) { pNotInChain->pskip = nullptr; pNotInChain->pprev = vChain[pNotInChain->pprev->nHeight - cloneFrom]; pNotInChain = pNotInChain->pprev; } } } } CBlockIndex *CCloneChain::operator[](int nHeight) const { if (nHeight >= cloneFrom && nHeight <= Height()) { return vChain[nHeight - cloneFrom]; } else return origin[nHeight]; } int CCloneChain::Height() const { return cloneFrom + vChain.size() - 1; } void CCloneChain::SetTip(CBlockIndex *pindex) { // not allowed to modify origin chain assert(pindex != nullptr && pindex->nHeight >= cloneFrom); vChain.resize(pindex->nHeight - cloneFrom + 1); while (pindex && vChain[pindex->nHeight - cloneFrom] != pindex) { vChain[pindex->nHeight - cloneFrom] = pindex; pindex = pindex->pprev; } } CBlockIndex* CChain::FindEarliestAtLeast(int64_t nTime) const { int first = 0; int it = 0; int count = Height() + 1; while (count > 0) { int step = count / 2; it += step; if (operator[](it)->GetBlockTimeMax() < nTime) { first = ++it; count -= step + 1; } else count = step; } return first <= Height() ? operator [](first) : nullptr; } /** Turn the lowest '1' bit in the binary representation of a number into a '0'. */ int static inline InvertLowestOne(int n) { return n & (n - 1); } /** Compute what height to jump back to with the CBlockIndex::pskip pointer. */ int static inline GetSkipHeight(int height) { if (height < 2) return 0; // Determine which height to jump back to. Any number strictly lower than height is acceptable, // but the following expression seems to perform well in simulations (max 110 steps to go back // up to 2**18 blocks). return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height); } CBlockIndex* CBlockIndex::GetAncestor(int height) { if (height > (int)nHeight || height < 0) return NULL; CBlockIndex* pindexWalk = this; int heightWalk = nHeight; while (heightWalk > height) { int heightSkip = GetSkipHeight(heightWalk); int heightSkipPrev = GetSkipHeight(heightWalk - 1); if (pindexWalk->pskip != NULL && (heightSkip == height || (heightSkip > height && !(heightSkipPrev < heightSkip - 2 && heightSkipPrev >= height)))) { // Only follow pskip if pprev->pskip isn't better than pskip->pprev. pindexWalk = pindexWalk->pskip; heightWalk = heightSkip; } else { assert(pindexWalk->pprev); pindexWalk = pindexWalk->pprev; heightWalk--; } } return pindexWalk; } const CBlockIndex* CBlockIndex::GetAncestor(int height) const { return const_cast<CBlockIndex*>(this)->GetAncestor(height); } void CBlockIndex::BuildSkip() { if (pprev) pskip = pprev->GetAncestor(GetSkipHeight(nHeight)); } arith_uint256 GetBlockProof(const CBlockIndex& block) { arith_uint256 bnTarget; bool fNegative; bool fOverflow; bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow); if (fNegative || fOverflow || bnTarget == 0) return 0; // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256 // as it's too large for a arith_uint256. However, as 2**256 is at least as large // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1, // or ~bnTarget / (nTarget+1) + 1. return (~bnTarget / (bnTarget + 1)) + 1; } int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params) { arith_uint256 r; int sign = 1; if (to.nChainWork > from.nChainWork) { r = to.nChainWork - from.nChainWork; } else { r = from.nChainWork - to.nChainWork; sign = -1; } r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip); if (r.bits() > 63) { return sign * std::numeric_limits<int64_t>::max(); } return sign * r.GetLow64(); } <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chain.h" #include "validation.h" using namespace std; /* Moved here from the header, because we need auxpow and the logic becomes more involved. */ CBlockHeader CBlockIndex::GetBlockHeader(const Consensus::Params& consensusParams) const { CBlockHeader block; /* The CBlockIndex object's block header is missing the auxpow. So if this is an auxpow block, read it from disk instead. We only have to read the actual *header*, not the full block. */ if (block.IsAuxpow()) { ReadBlockHeaderFromDisk(block, this, consensusParams); return block; } block.nVersion = nVersion; if (pprev) block.hashPrevBlock = pprev->GetBlockHash(); block.hashMerkleRoot = hashMerkleRoot; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; return block; } /** * CChain implementation */ void CChain::SetTip(CBlockIndex *pindex) { if (pindex == NULL) { vChain.clear(); return; } vChain.resize(pindex->nHeight + 1); while (pindex && vChain[pindex->nHeight] != pindex) { vChain[pindex->nHeight] = pindex; pindex = pindex->pprev; } } CBlockLocator CChain::GetLocator(const CBlockIndex *pindex) const { int nStep = 1; std::vector<uint256> vHave; vHave.reserve(32); if (!pindex) pindex = Tip(); while (pindex) { vHave.push_back(pindex->GetBlockHash()); // Stop when we have added the genesis block. if (pindex->nHeight == 0) break; // Exponentially larger steps back, plus the genesis block. int nHeight = std::max(pindex->nHeight - nStep, 0); if (Contains(pindex)) { // Use O(1) CChain index if possible. pindex = (*this)[nHeight]; } else { // Otherwise, use O(log n) skiplist. pindex = pindex->GetAncestor(nHeight); } if (vHave.size() > 10) nStep *= 2; } return CBlockLocator(vHave); } const CBlockIndex *CChain::FindFork(const CBlockIndex *pindex) const { if (pindex == NULL) { return NULL; } if (pindex->nHeight > Height()) pindex = pindex->GetAncestor(Height()); while (pindex && !Contains(pindex)) pindex = pindex->pprev; return pindex; } CBlockIndex* CChain::FindEarliestAtLeast(int64_t nTime) const { std::vector<CBlockIndex*>::const_iterator lower = std::lower_bound(vChain.begin(), vChain.end(), nTime, [](CBlockIndex* pBlock, const int64_t& time) -> bool { return pBlock->GetBlockTimeMax() < time; }); return (lower == vChain.end() ? NULL : *lower); } /** Turn the lowest '1' bit in the binary representation of a number into a '0'. */ int static inline InvertLowestOne(int n) { return n & (n - 1); } /** Compute what height to jump back to with the CBlockIndex::pskip pointer. */ int static inline GetSkipHeight(int height) { if (height < 2) return 0; // Determine which height to jump back to. Any number strictly lower than height is acceptable, // but the following expression seems to perform well in simulations (max 110 steps to go back // up to 2**18 blocks). return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height); } CBlockIndex* CBlockIndex::GetAncestor(int height) { if (height > nHeight || height < 0) return NULL; CBlockIndex* pindexWalk = this; int heightWalk = nHeight; while (heightWalk > height) { int heightSkip = GetSkipHeight(heightWalk); int heightSkipPrev = GetSkipHeight(heightWalk - 1); if (pindexWalk->pskip != NULL && (heightSkip == height || (heightSkip > height && !(heightSkipPrev < heightSkip - 2 && heightSkipPrev >= height)))) { // Only follow pskip if pprev->pskip isn't better than pskip->pprev. pindexWalk = pindexWalk->pskip; heightWalk = heightSkip; } else { assert(pindexWalk->pprev); pindexWalk = pindexWalk->pprev; heightWalk--; } } return pindexWalk; } const CBlockIndex* CBlockIndex::GetAncestor(int height) const { return const_cast<CBlockIndex*>(this)->GetAncestor(height); } void CBlockIndex::BuildSkip() { if (pprev) pskip = pprev->GetAncestor(GetSkipHeight(nHeight)); } arith_uint256 GetBlockProof(const CBlockIndex& block) { arith_uint256 bnTarget; bool fNegative; bool fOverflow; bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow); if (fNegative || fOverflow || bnTarget == 0) return 0; // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256 // as it's too large for a arith_uint256. However, as 2**256 is at least as large // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1, // or ~bnTarget / (nTarget+1) + 1. return (~bnTarget / (bnTarget + 1)) + 1; } int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params) { arith_uint256 r; int sign = 1; if (to.nChainWork > from.nChainWork) { r = to.nChainWork - from.nChainWork; } else { r = from.nChainWork - to.nChainWork; sign = -1; } r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip); if (r.bits() > 63) { return sign * std::numeric_limits<int64_t>::max(); } return sign * r.GetLow64(); } <commit_msg>Load AuxPoW blocks from index correctly (#1443)<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chain.h" #include "validation.h" using namespace std; /* Moved here from the header, because we need auxpow and the logic becomes more involved. */ CBlockHeader CBlockIndex::GetBlockHeader(const Consensus::Params& consensusParams) const { CBlockHeader block; block.nVersion = nVersion; /* The CBlockIndex object's block header is missing the auxpow. So if this is an auxpow block, read it from disk instead. We only have to read the actual *header*, not the full block. */ if (block.IsAuxpow()) { ReadBlockHeaderFromDisk(block, this, consensusParams); return block; } if (pprev) block.hashPrevBlock = pprev->GetBlockHash(); block.hashMerkleRoot = hashMerkleRoot; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; return block; } /** * CChain implementation */ void CChain::SetTip(CBlockIndex *pindex) { if (pindex == NULL) { vChain.clear(); return; } vChain.resize(pindex->nHeight + 1); while (pindex && vChain[pindex->nHeight] != pindex) { vChain[pindex->nHeight] = pindex; pindex = pindex->pprev; } } CBlockLocator CChain::GetLocator(const CBlockIndex *pindex) const { int nStep = 1; std::vector<uint256> vHave; vHave.reserve(32); if (!pindex) pindex = Tip(); while (pindex) { vHave.push_back(pindex->GetBlockHash()); // Stop when we have added the genesis block. if (pindex->nHeight == 0) break; // Exponentially larger steps back, plus the genesis block. int nHeight = std::max(pindex->nHeight - nStep, 0); if (Contains(pindex)) { // Use O(1) CChain index if possible. pindex = (*this)[nHeight]; } else { // Otherwise, use O(log n) skiplist. pindex = pindex->GetAncestor(nHeight); } if (vHave.size() > 10) nStep *= 2; } return CBlockLocator(vHave); } const CBlockIndex *CChain::FindFork(const CBlockIndex *pindex) const { if (pindex == NULL) { return NULL; } if (pindex->nHeight > Height()) pindex = pindex->GetAncestor(Height()); while (pindex && !Contains(pindex)) pindex = pindex->pprev; return pindex; } CBlockIndex* CChain::FindEarliestAtLeast(int64_t nTime) const { std::vector<CBlockIndex*>::const_iterator lower = std::lower_bound(vChain.begin(), vChain.end(), nTime, [](CBlockIndex* pBlock, const int64_t& time) -> bool { return pBlock->GetBlockTimeMax() < time; }); return (lower == vChain.end() ? NULL : *lower); } /** Turn the lowest '1' bit in the binary representation of a number into a '0'. */ int static inline InvertLowestOne(int n) { return n & (n - 1); } /** Compute what height to jump back to with the CBlockIndex::pskip pointer. */ int static inline GetSkipHeight(int height) { if (height < 2) return 0; // Determine which height to jump back to. Any number strictly lower than height is acceptable, // but the following expression seems to perform well in simulations (max 110 steps to go back // up to 2**18 blocks). return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height); } CBlockIndex* CBlockIndex::GetAncestor(int height) { if (height > nHeight || height < 0) return NULL; CBlockIndex* pindexWalk = this; int heightWalk = nHeight; while (heightWalk > height) { int heightSkip = GetSkipHeight(heightWalk); int heightSkipPrev = GetSkipHeight(heightWalk - 1); if (pindexWalk->pskip != NULL && (heightSkip == height || (heightSkip > height && !(heightSkipPrev < heightSkip - 2 && heightSkipPrev >= height)))) { // Only follow pskip if pprev->pskip isn't better than pskip->pprev. pindexWalk = pindexWalk->pskip; heightWalk = heightSkip; } else { assert(pindexWalk->pprev); pindexWalk = pindexWalk->pprev; heightWalk--; } } return pindexWalk; } const CBlockIndex* CBlockIndex::GetAncestor(int height) const { return const_cast<CBlockIndex*>(this)->GetAncestor(height); } void CBlockIndex::BuildSkip() { if (pprev) pskip = pprev->GetAncestor(GetSkipHeight(nHeight)); } arith_uint256 GetBlockProof(const CBlockIndex& block) { arith_uint256 bnTarget; bool fNegative; bool fOverflow; bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow); if (fNegative || fOverflow || bnTarget == 0) return 0; // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256 // as it's too large for a arith_uint256. However, as 2**256 is at least as large // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1, // or ~bnTarget / (nTarget+1) + 1. return (~bnTarget / (bnTarget + 1)) + 1; } int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params) { arith_uint256 r; int sign = 1; if (to.nChainWork > from.nChainWork) { r = to.nChainWork - from.nChainWork; } else { r = from.nChainWork - to.nChainWork; sign = -1; } r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip); if (r.bits() > 63) { return sign * std::numeric_limits<int64_t>::max(); } return sign * r.GetLow64(); } <|endoftext|>
<commit_before>/* Copyright 2015 The TensorFlow 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 "tensorflow/python/lib/core/py_util.h" // Place `<locale>` before <Python.h> to avoid build failure in macOS. #include <locale> #include <Python.h> #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/strings/strcat.h" namespace tensorflow { namespace { // py.__class__.__name__ const char* ClassName(PyObject* py) { /* PyPy doesn't have a separate C API for old-style classes. */ #if PY_MAJOR_VERSION < 3 && !defined(PYPY_VERSION) if (PyClass_Check(py)) return PyString_AS_STRING( CHECK_NOTNULL(reinterpret_cast<PyClassObject*>(py)->cl_name)); if (PyInstance_Check(py)) return PyString_AS_STRING(CHECK_NOTNULL( reinterpret_cast<PyInstanceObject*>(py)->in_class->cl_name)); #endif if (Py_TYPE(py) == &PyType_Type) { return reinterpret_cast<PyTypeObject*>(py)->tp_name; } return Py_TYPE(py)->tp_name; } } // end namespace // Returns a PyObject containing a string, or null void TryAppendTraceback(PyObject* ptype, PyObject* pvalue, PyObject* ptraceback, string* out) { // The "traceback" module is assumed to be imported already by script_ops.py. PyObject* tb_module = PyImport_AddModule("traceback"); if (!tb_module) { return; } PyObject* format_exception = PyObject_GetAttrString(tb_module, "format_exception"); if (!format_exception) { return; } if (!PyCallable_Check(format_exception)) { Py_DECREF(format_exception); return; } PyObject* ret_val = PyObject_CallFunctionObjArgs(format_exception, ptype, pvalue, ptraceback, nullptr); Py_DECREF(format_exception); if (!ret_val) { return; } if (!PyList_Check(ret_val)) { Py_DECREF(ret_val); return; } Py_ssize_t n = PyList_GET_SIZE(ret_val); for (Py_ssize_t i = 0; i < n; ++i) { PyObject* v = PyList_GET_ITEM(ret_val, i); #if PY_MAJOR_VERSION < 3 strings::StrAppend(out, PyString_AS_STRING(v), "\n"); #else strings::StrAppend(out, PyUnicode_AsUTF8(v), "\n"); #endif } // Iterate through ret_val. Py_DECREF(ret_val); } string PyExceptionFetch() { CHECK(PyErr_Occurred()) << "Must only call PyExceptionFetch after an exception."; PyObject* ptype; PyObject* pvalue; PyObject* ptraceback; PyErr_Fetch(&ptype, &pvalue, &ptraceback); PyErr_NormalizeException(&ptype, &pvalue, &ptraceback); string err = ClassName(ptype); if (pvalue) { PyObject* str = PyObject_Str(pvalue); if (str) { #if PY_MAJOR_VERSION < 3 strings::StrAppend(&err, ": ", PyString_AS_STRING(str), "\n"); #else strings::StrAppend(&err, ": ", PyUnicode_AsUTF8(str), "\n"); #endif Py_DECREF(str); } else { strings::StrAppend(&err, "(unknown error message)\n"); } TryAppendTraceback(ptype, pvalue, ptraceback, &err); Py_DECREF(pvalue); } Py_DECREF(ptype); Py_XDECREF(ptraceback); return err; } } // end namespace tensorflow <commit_msg>Fix build issue on mac with python-2.7.10 and clang 9.1.0<commit_after>/* Copyright 2015 The TensorFlow 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 "tensorflow/python/lib/core/py_util.h" // Place `<locale>` before <Python.h> to avoid build failure in macOS. #include <locale> // The empty line above is on purpose as otherwise clang-format will // automatically move <Python.h> before <locale>. #include <Python.h> #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/strings/strcat.h" namespace tensorflow { namespace { // py.__class__.__name__ const char* ClassName(PyObject* py) { /* PyPy doesn't have a separate C API for old-style classes. */ #if PY_MAJOR_VERSION < 3 && !defined(PYPY_VERSION) if (PyClass_Check(py)) return PyString_AS_STRING( CHECK_NOTNULL(reinterpret_cast<PyClassObject*>(py)->cl_name)); if (PyInstance_Check(py)) return PyString_AS_STRING(CHECK_NOTNULL( reinterpret_cast<PyInstanceObject*>(py)->in_class->cl_name)); #endif if (Py_TYPE(py) == &PyType_Type) { return reinterpret_cast<PyTypeObject*>(py)->tp_name; } return Py_TYPE(py)->tp_name; } } // end namespace // Returns a PyObject containing a string, or null void TryAppendTraceback(PyObject* ptype, PyObject* pvalue, PyObject* ptraceback, string* out) { // The "traceback" module is assumed to be imported already by script_ops.py. PyObject* tb_module = PyImport_AddModule("traceback"); if (!tb_module) { return; } PyObject* format_exception = PyObject_GetAttrString(tb_module, "format_exception"); if (!format_exception) { return; } if (!PyCallable_Check(format_exception)) { Py_DECREF(format_exception); return; } PyObject* ret_val = PyObject_CallFunctionObjArgs(format_exception, ptype, pvalue, ptraceback, nullptr); Py_DECREF(format_exception); if (!ret_val) { return; } if (!PyList_Check(ret_val)) { Py_DECREF(ret_val); return; } Py_ssize_t n = PyList_GET_SIZE(ret_val); for (Py_ssize_t i = 0; i < n; ++i) { PyObject* v = PyList_GET_ITEM(ret_val, i); #if PY_MAJOR_VERSION < 3 strings::StrAppend(out, PyString_AS_STRING(v), "\n"); #else strings::StrAppend(out, PyUnicode_AsUTF8(v), "\n"); #endif } // Iterate through ret_val. Py_DECREF(ret_val); } string PyExceptionFetch() { CHECK(PyErr_Occurred()) << "Must only call PyExceptionFetch after an exception."; PyObject* ptype; PyObject* pvalue; PyObject* ptraceback; PyErr_Fetch(&ptype, &pvalue, &ptraceback); PyErr_NormalizeException(&ptype, &pvalue, &ptraceback); string err = ClassName(ptype); if (pvalue) { PyObject* str = PyObject_Str(pvalue); if (str) { #if PY_MAJOR_VERSION < 3 strings::StrAppend(&err, ": ", PyString_AS_STRING(str), "\n"); #else strings::StrAppend(&err, ": ", PyUnicode_AsUTF8(str), "\n"); #endif Py_DECREF(str); } else { strings::StrAppend(&err, "(unknown error message)\n"); } TryAppendTraceback(ptype, pvalue, ptraceback, &err); Py_DECREF(pvalue); } Py_DECREF(ptype); Py_XDECREF(ptraceback); return err; } } // end namespace tensorflow <|endoftext|>
<commit_before> inline kth_cv::kth_cv(const std::string in_path, const std::string in_actionNames, const field<std::string> in_all_people, const int in_scale_factor, const int in_shift, const int in_scene, //only for kth const int in_segment_length, const int in_dim ):path(in_path), actionNames(in_actionNames), all_people (in_all_people), scale_factor(in_scale_factor), shift(in_shift), total_scenes(in_scene), segment_length(in_segment_length), dim(in_dim) { actions.load( actionNames ); } inline void kth_cv::logEucl() { int n_actions = actions.n_rows; int n_peo = all_people.n_rows; int acc; acc = 0; int n_test = n_peo*n_actions*total_scenes; for (int sc = 1; sc<=total_scenes; ++sc) //scene { for (int pe = 0; pe< n_peo; ++pe) { for (int act=0; act<n_actions; ++act) { //load number of segments vec total_seg; int num_s; std::stringstream load_sub_path; std::stringstream load_num_seg; load_sub_path << path << "/kth-cov-mat/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; load_num_seg << load_sub_path.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.load( load_num_seg.str()); num_s = total_seg(0); uvec est_lab_segm; est_lab_segm.zeros(num_s); vec count = zeros<vec>( n_actions ); for (int s=0; s<num_s; ++s) { std::stringstream load_cov_seg; load_cov_seg << load_sub_path.str() << "/LogMcov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; cout << "LogMcov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5" << endl; //debe devolver el est_labe de ese segmento est_lab_segm(s) = one_seg_est_lab( pe, load_sub_path.str(), load_cov_seg.str()); count( est_lab_segm(s) )++; //getchar(); } uword index_video; double max_val = count.max(index_video); //est_lab_segm.t().print("est_lab_segm"); cout << "This video is " << actions(act) << " and was classified as class: " << actions(index_video ) << endl; if (index_video == act) { acc++; } //getchar(); } } } cout << "Performance: " << acc*100/n_test << " %" << endl; } inline uword kth_cv::one_seg_est_lab(int pe_test, std::string load_sub_path, std::string segm_name) { wall_clock timer; timer.tic(); mat logMtest_cov; logMtest_cov.load(segm_name); int n_actions = actions.n_rows; int n_peo = all_people.n_rows; double dist, tmp_dist; tmp_dist = datum::inf; double est_lab; //cout << "Comparing with person "; for (int pe_tr = 0; pe_tr< n_peo; ++pe_tr) { if (pe_tr!= pe_test) { //cout << " " << all_people (pe_tr); for (int sc = 1; sc<=total_scenes; ++sc) //scene { for (int act=0; act<n_actions; ++act) { vec total_seg; int num_s; std::stringstream load_num_seg; load_num_seg << load_sub_path << "/num_seg_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.load( load_num_seg.str()); num_s = total_seg(0); for (int s_tr=0; s_tr<num_s; ++s_tr) { std::stringstream load_cov_seg_tr; load_cov_seg_tr << load_sub_path << "/LogMcov_seg" << s_tr << "_" << all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5"; //cout << "Comparing with cov_seg" << s_tr << "_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5" << endl; mat logMtrain_cov; logMtrain_cov.load( load_cov_seg_tr.str() ); //logMtest_cov.print("logMtest_cov"); //train_cov.print("train_cov"); dist = norm( logMtest_cov - logMtrain_cov, "fro"); //cout << "dist " << dist << endl; if (dist < tmp_dist) { //cout << "Es menor" << endl; tmp_dist = dist; est_lab = act; } //cout << "Press a key" << endl; //getchar(); } } } } } double n = timer.toc(); //cout << "number of seconds: " << n << endl; //cout << " est_lab "<< est_lab << endl << endl; //getchar(); return est_lab; }<commit_msg>Run for 4 scenarios<commit_after> inline kth_cv::kth_cv(const std::string in_path, const std::string in_actionNames, const field<std::string> in_all_people, const int in_scale_factor, const int in_shift, const int in_scene, //only for kth const int in_segment_length, const int in_dim ):path(in_path), actionNames(in_actionNames), all_people (in_all_people), scale_factor(in_scale_factor), shift(in_shift), total_scenes(in_scene), segment_length(in_segment_length), dim(in_dim) { actions.load( actionNames ); } inline void kth_cv::logEucl() { int n_actions = actions.n_rows; int n_peo = all_people.n_rows; float acc; acc = 0; int n_test = n_peo*n_actions*total_scenes; vec real_labels; vec est_labels; field<std::string> test_video_list(n_test); real_labels.zeros(n_test); est_labels.zeros(n_test); int k=0; for (int sc = 1; sc<=total_scenes; ++sc) //scene { for (int pe = 0; pe< n_peo; ++pe) { for (int act=0; act<n_actions; ++act) { //load number of segments vec total_seg; int num_s; std::stringstream load_sub_path; std::stringstream load_num_seg; load_sub_path << path << "/kth-cov-mat/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; load_num_seg << load_sub_path.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.load( load_num_seg.str()); num_s = total_seg(0); uvec est_lab_segm; est_lab_segm.zeros(num_s); vec count = zeros<vec>( n_actions ); for (int s=0; s<num_s; ++s) { std::stringstream load_cov_seg; load_cov_seg << load_sub_path.str() << "/LogMcov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; //cout << "LogMcov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5" << endl; //debe devolver el est_labe de ese segmento est_lab_segm(s) = one_seg_est_lab( pe, load_sub_path.str(), load_cov_seg.str()); count( est_lab_segm(s) )++; //getchar(); } uword index_video; double max_val = count.max(index_video); //est_lab_segm.t().print("est_lab_segm"); cout << "This video is " << actions(act) << " and was classified as class: " << actions(index_video ) << endl; real_labels(k) = act; est_labels(k) = index_video; test_video_list(k) = load_sub_path.str(); real_labels.save("real_labels.dat", raw_ascii); est_labels.save("est_labels.dat", raw_ascii); test_video_list.save("test_video_list.dat", raw_ascii); k++; if (index_video == act) { acc++; } //getchar(); } } } cout << "Performance: " << acc*100/n_test << " %" << endl; } inline uword kth_cv::one_seg_est_lab(int pe_test, std::string load_sub_path, std::string segm_name) { wall_clock timer; timer.tic(); mat logMtest_cov; logMtest_cov.load(segm_name); int n_actions = actions.n_rows; int n_peo = all_people.n_rows; double dist, tmp_dist; tmp_dist = datum::inf; double est_lab; //cout << "Comparing with person "; for (int pe_tr = 0; pe_tr< n_peo; ++pe_tr) { if (pe_tr!= pe_test) { //cout << " " << all_people (pe_tr); for (int sc = 1; sc<=total_scenes; ++sc) //scene { for (int act=0; act<n_actions; ++act) { vec total_seg; int num_s; std::stringstream load_num_seg; load_num_seg << load_sub_path << "/num_seg_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.load( load_num_seg.str()); num_s = total_seg(0); for (int s_tr=0; s_tr<num_s; ++s_tr) { std::stringstream load_cov_seg_tr; load_cov_seg_tr << load_sub_path << "/LogMcov_seg" << s_tr << "_" << all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5"; //cout << "Comparing with cov_seg" << s_tr << "_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5" << endl; mat logMtrain_cov; logMtrain_cov.load( load_cov_seg_tr.str() ); //logMtest_cov.print("logMtest_cov"); //train_cov.print("train_cov"); dist = norm( logMtest_cov - logMtrain_cov, "fro"); //cout << "dist " << dist << endl; if (dist < tmp_dist) { //cout << "Es menor" << endl; tmp_dist = dist; est_lab = act; } //cout << "Press a key" << endl; //getchar(); } } } } } double n = timer.toc(); //cout << "number of seconds: " << n << endl; //cout << " est_lab "<< est_lab << endl << endl; //getchar(); return est_lab; }<|endoftext|>
<commit_before>// S4Game.cpp : 콘솔 응용 프로그램에 대한 진입점을 정의합니다. // #include "stdafx.h" #include "../../S4Thread/ThreadLocal.h" #include "../../S4Thread/ConcurrentJobManager.h" #include "../../S4Network/NetworkManager.h" #include <boost/log/trivial.hpp> #include "../../S4Util/Exception.h" #include "../../S4Util/TimeStamp.h" #pragma comment(lib, "S4Thread.lib") #pragma comment(lib, "S4Network.lib") #pragma comment(lib, "Dbghelp.lib") #pragma comment(lib, "S4Util.lib") const int PORT_NUM = 35555; S4Network::NetworkManager GNetworkManager(PORT_NUM); S4Thread::ConcurrentJobManager GJobManager(8); int main() { /// for dump on crash SetUnhandledExceptionFilter(S4Util::ExceptionFilter); S4Thread::LThreadType = S4Thread::THREAD_TYPE::THREAD_MAIN; GNetworkManager.Run(); BOOST_LOG_TRIVIAL(info) << "네트워크 접속 종료"; getchar(); return 0; }<commit_msg>인코딩 변경 테스트<commit_after>// S4Game.cpp : 콘솔 응용 프로그램에 대한 진입점을 정의합니다. // #include "stdafx.h" #include "../../S4Thread/ThreadLocal.h" #include "../../S4Thread/ConcurrentJobManager.h" #include "../../S4Network/NetworkManager.h" #include <boost/log/trivial.hpp> #include "../../S4Util/Exception.h" #include "../../S4Util/TimeStamp.h" #pragma comment(lib, "S4Thread.lib") #pragma comment(lib, "S4Network.lib") #pragma comment(lib, "Dbghelp.lib") #pragma comment(lib, "S4Util.lib") const int PORT_NUM = 35555; S4Network::NetworkManager GNetworkManager(PORT_NUM); S4Thread::ConcurrentJobManager GJobManager(8); int main() { /// for dump on crash SetUnhandledExceptionFilter(S4Util::ExceptionFilter); S4Thread::LThreadType = S4Thread::THREAD_TYPE::THREAD_MAIN; GNetworkManager.Run(); BOOST_LOG_TRIVIAL(info) << "네트워크 접속 종료"; getchar(); return 0; }<|endoftext|>
<commit_before>// dune-multiscale // Copyright Holders: Patrick Henning, Rene Milk // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // das alles klappt momentan nur in 2-D!!! Es laesst sich aber sehr einfach verallgemeinern. // Implementierung funktioniert unter folgenden Voraussetzungen an den (Diffusions-)Tensor: // 1. Elliptizitätsbedingung // 2. A(x,y) = A(y) #ifndef DUNE_HOMOGENIZER_HH #define DUNE_HOMOGENIZER_HH #include <dune/multiscale/fem/elliptic_fem_matrix_assembler.hh> #include <dune/fem/gridpart/periodicgridpart/periodicgridpart.hh> // for data output: #include <dune/fem/io/file/dataoutput.hh> #include <dune/fem/io/parameter.hh> #include <dune/fem/io/file/datawriter.hh> #include <dune/fem/quadrature/cachingquadrature.hh> #include <dune/stuff/fem/functions/analytical.hh> #include <dune/stuff/common/memory.hh> #include <dune/multiscale/common/righthandside_assembler.hh> namespace Dune { namespace Multiscale { //! define output traits struct CellDataOutputParameters : public Fem::DataOutputParameters { public: std::string my_prefix_; // path where the data is stored std::string path() const { return "data_output_hmm"; } void set_prefix(std::string my_prefix) { my_prefix_ = my_prefix; // std :: cout << "Set prefix. my_prefix_ = " << my_prefix_ << std :: endl; } // base of file name for data file std::string prefix() const { if (my_prefix_ == "") return "solutions_cell_problems"; else return my_prefix_; } // format of output: int outputformat() const { // return 0; // GRAPE (lossless format) return 1; // VTK // return 2; // VTK vertex data // return 3; // gnuplot } }; NULLFUNCTION(ZeroFunction) //! \TODO docme // (to replace the more general lower order term) class MassWeight : public Problem::ZeroLowerOrder { public: MassWeight(double lambda) : lambda_(lambda) {} void evaluate(const DomainType& /*x*/, const RangeType& position, const JacobianRangeType& /*direction_gradient*/, RangeType& y) const { y = lambda_ * position; } virtual void evaluate(const DomainType& /*x*/, RangeType& /*ret*/) const { DUNE_THROW(Dune::NotImplemented, ""); } double lambda_; }; /** since we need to evaluate A( x, \cdot ) to solve cellproblems (in comparison to A( \cdot, \frac{\cdot}{\epsilon} ) * for the global problem), we must transform the orginal tensor to be able to use a standard FEM operator for solving * cell problems (otherwise: calling the method evaluate(i,j,x,y) within the matrixassembler would evaluate A^{\epsilon} * instead of A(x,\cdot) ) **/ template <class TensorImp> class TransformTensor : public Problem::DiffusionBase { private: typedef CommonTraits::FunctionSpaceType FunctionSpaceType; typedef TensorImp TensorType; typedef typename FunctionSpaceType::DomainType DomainType; typedef typename FunctionSpaceType::RangeType RangeType; typedef typename FunctionSpaceType::JacobianRangeType JacobianRangeType; typedef typename FunctionSpaceType::DomainFieldType DomainFieldType; typedef typename FunctionSpaceType::RangeFieldType RangeFieldType; typedef DomainFieldType TimeType; static const int dimDomain = DomainType::dimension; const TensorType& tensor_; public: // Constructor inline explicit TransformTensor(const TensorType& tensor) : tensor_(tensor) {} void diffusiveFlux(const DomainType& y, const JacobianRangeType& direction, JacobianRangeType& flux) const { DomainType new_y = y; new_y *= DSC_CONFIG_GET("problem.epsilon", 1.0f); tensor_.diffusiveFlux(new_y, direction, flux); } // diffusiveFlux inline void evaluate(const int /*i*/, const int /*j*/, const DomainType& /*x*/, const TimeType& /*time*/, RangeType& /*y*/) const { DUNE_THROW(Dune::NotImplemented, ""); } inline void evaluate(const DomainType& /*x*/, RangeType& /*y*/) const { DUNE_THROW(Dune::NotImplemented, ""); } inline void evaluate(const DomainType& /*x*/, const TimeType& /*time*/, RangeType& /*y*/) const { DUNE_THROW(Dune::NotImplemented, ""); } virtual void jacobianDiffusiveFlux(const DomainType& /*x*/, const JacobianRangeType& /*position_gradient*/, const JacobianRangeType& /*direction_gradient*/, JacobianRangeType& /*flux*/) const { DUNE_THROW(Dune::NotImplemented, ""); } }; //! the following class is comparable to a SecondSource-Class (some kind of -div G ) template <class TensorImp> class CellSource : CommonTraits::FunctionBaseType { private: typedef TensorImp TensorType; typedef CommonTraits::FunctionSpaceType FunctionSpaceType; typedef typename FunctionSpaceType::DomainType DomainType; typedef typename FunctionSpaceType::RangeType RangeType; typedef typename FunctionSpaceType::JacobianRangeType JacobianRangeType; typedef typename FunctionSpaceType::DomainFieldType DomainFieldType; typedef typename FunctionSpaceType::RangeFieldType RangeFieldType; const FunctionSpaceType& functionSpace_; const TensorType& tensor_; const int& j_; public: inline explicit CellSource(const FunctionSpaceType& functionSpace, const TensorType& tensor, const int& j) : functionSpace_(functionSpace) , tensor_(tensor) , j_(j) // we solve the j'th cell problem {} inline void evaluate(const DomainType& /*x*/, RangeType& y) const { y[0] = 0; } inline void evaluate(const int i, const DomainType& y, RangeType& z) const { JacobianRangeType direction; JacobianRangeType flux; for (int j = 0; j < DomainType::dimension; ++j) { direction[0][j] = int(j_ == j); } tensor_.diffusiveFlux(y, direction, flux); // tensor_.evaluate( i, j_, y, z); z = -flux[0][i]; } // evaluate }; NULLFUNCTION(DefaultDummyAdvection) //! \TODO docme template <class TensorImp> class Homogenizer { private: typedef CommonTraits::GridType GridType; static const int dimension = GridType::dimension; typedef TensorImp TensorType; typedef Fem::PeriodicLeafGridPart<GridType> PeriodicGridPartType; typedef CommonTraits::FunctionSpaceType FunctionSpaceType; typedef Fem::LagrangeDiscreteFunctionSpace<FunctionSpaceType, PeriodicGridPartType, 1> PeriodicDiscreteFunctionSpaceType; // to avoid confusion: typedef PeriodicDiscreteFunctionSpaceType DummySpaceType; // (sometimes PeriodicDiscreteFunctionSpaceType is only a dummy) typedef Fem::AdaptiveDiscreteFunction<PeriodicDiscreteFunctionSpaceType> PeriodicDiscreteFunctionType; // to avoid confusion: typedef PeriodicDiscreteFunctionType DummyType; // (sometimes PeriodicDiscreteFunctionType is only a dummy) typedef MassWeight MassWeightType; typedef ZeroFunction<FunctionSpaceType> ZeroFunctionType; typedef DefaultDummyAdvection<FunctionSpaceType> DefaultDummyAdvectionType; typedef TransformTensor<TensorType> TransformTensorType; typedef CellSource<TransformTensorType> CellSourceType; typedef typename PeriodicDiscreteFunctionSpaceType::JacobianRangeType PeriodicJacobianRangeType; typedef typename PeriodicDiscreteFunctionType::LocalFunctionType PeriodicLocalFunctionType; typedef typename GridType::template Codim<0>::Entity EntityType; typedef typename BackendChooser<PeriodicDiscreteFunctionSpaceType>::LinearOperatorType LinearOperatorType; typedef typename BackendChooser<PeriodicDiscreteFunctionSpaceType>::InverseOperatorType InverseLinearOperatorType; // discrete elliptic operator (corresponds with FEM Matrix) typedef Multiscale::FEM::DiscreteEllipticOperator<PeriodicDiscreteFunctionType, TransformTensorType> EllipticOperatorType; typedef typename FunctionSpaceType::DomainType DomainType; typedef typename FunctionSpaceType::RangeType RangeType; enum { spacePolOrd = PeriodicDiscreteFunctionSpaceType::polynomialOrder }; // dgf file that describes the perforated domain const std::string& filename_; public: Homogenizer(const std::string& filename) : filename_(filename) {} typedef FieldMatrix<RangeType, dimension, dimension> HomTensorType; private: double getEntry(const TransformTensorType& tensor, const PeriodicDiscreteFunctionSpaceType& periodicDiscreteFunctionSpace, const PeriodicDiscreteFunctionType& w_i, const PeriodicDiscreteFunctionType& w_j, const int& i, const int& j) const { double a_ij_hom = 0; for (const auto& entity : periodicDiscreteFunctionSpace) { auto localW_i = w_i.localFunction(entity); auto localW_j = w_j.localFunction(entity); // create quadrature for given geometry type //!\TODO soll das WIRLKLICH pold order 2 sein? const auto quadrature = make_quadrature(entity, periodicDiscreteFunctionSpace, 2); // get geoemetry of entity const auto& geometry = entity.geometry(); // integrate for (const auto localQuadPoint : DSC::valueRange(quadrature.nop())) { RangeType localIntegral = 0; PeriodicJacobianRangeType grad_w_i; localW_i.jacobian(quadrature[localQuadPoint], grad_w_i); PeriodicJacobianRangeType grad_w_j; localW_j.jacobian(quadrature[localQuadPoint], grad_w_j); // local (barycentric) coordinates (with respect to cell grid entity) const auto& local_point = quadrature.point(localQuadPoint); // global point in the unit cell Y const auto global_point_in_Y = geometry.global(local_point); PeriodicJacobianRangeType direction_i; for (int k = 0; k < dimension; ++k) { direction_i[0][k] = grad_w_i[0][k]; if (k == i) { direction_i[0][k] += 1.0; } } PeriodicJacobianRangeType direction_j; for (int k = 0; k < dimension; ++k) { direction_j[0][k] = 0.0; if (k == j) { direction_j[0][k] += 1.0; } } PeriodicJacobianRangeType flux_i; tensor.diffusiveFlux(global_point_in_Y, direction_i, flux_i); localIntegral = (flux_i[0] * direction_j[0]); const double entityVolume = quadrature.weight(localQuadPoint) * geometry.integrationElement(quadrature.point(localQuadPoint)); a_ij_hom += entityVolume * localIntegral; } } return a_ij_hom; } // end of method public: HomTensorType getHomTensor(const TensorType& tensor) const { HomTensorType a_hom; // to solve cell problems, we always need to use a perforated unit cube as domain: GridPtr<GridType> periodicgridptr(filename_); Dune::Fem::GlobalRefine::apply(*periodicgridptr, 10); PeriodicGridPartType periodicGridPart(*periodicgridptr); PeriodicDiscreteFunctionSpaceType periodicDiscreteFunctionSpace(periodicGridPart); // to avoid confusions: const DummySpaceType dummySpace(periodicGridPart); // (sometimes periodicDiscreteFunctionSpace is only a dummy) //! define the type of the corresponding solutions ( discrete functions of the type 'DiscreteFunctionType'): PeriodicDiscreteFunctionType cellSolution_0("cellSolution 0", periodicDiscreteFunctionSpace); cellSolution_0.clear(); PeriodicDiscreteFunctionType cellSolution_1("cellSolution 1", periodicDiscreteFunctionSpace); cellSolution_1.clear(); PeriodicDiscreteFunctionType rhs_0("rhs_0", periodicDiscreteFunctionSpace); rhs_0.clear(); PeriodicDiscreteFunctionType rhs_1("rhs_1", periodicDiscreteFunctionSpace); rhs_1.clear(); const RangeType lambda = 1e-07; // we need solve several cell problems with a periodic boundary condition. To fix the solution we need some kind of // additional condition. Therefor we solve // \lambda w - \div A \nabla w = rhs instead of - \div A \nabla w = rhs const TransformTensorType tensor_transformed(tensor); // if we have some additional source term (-div G), define: const CellSourceType G_0(periodicDiscreteFunctionSpace, tensor_transformed, 0); // 0'th cell problem const CellSourceType G_1(periodicDiscreteFunctionSpace, tensor_transformed, 1); // 1'th cell problem // - div ( A \nabla u^{\epsilon} ) = f - div G // quite a dummy. It's always f = 0 const ZeroFunctionType zero; //! build the left hand side (lhs) of the problem const std::unique_ptr<const Problem::LowerOrderBase> mass(new MassWeightType(lambda)); // define mass (just for cell problems \lambda w - \div A \nabla w = rhs) const EllipticOperatorType discrete_cell_elliptic_op(periodicDiscreteFunctionSpace, tensor_transformed, mass); LinearOperatorType lhsMatrix("Cell Problem Stiffness Matrix", periodicDiscreteFunctionSpace, periodicDiscreteFunctionSpace); discrete_cell_elliptic_op.assemble_matrix(lhsMatrix, false /*no boundary treatment*/); //! build the right hand side (rhs) of the problem // the same right hand side for HM and FEM methods: typedef RightHandSideAssembler<PeriodicDiscreteFunctionType> RhsAssembler; // Alternativly it is possible to call the RightHandSideAssembler with a second source Term '- div G': // RightHandSideAssembler< DiscreteFunctionType > rhsassembler( tensor , G ); RhsAssembler::template assemble<2 * PeriodicDiscreteFunctionSpaceType::polynomialOrder>(zero, G_0, rhs_0); RhsAssembler::template assemble<2 * PeriodicDiscreteFunctionSpaceType::polynomialOrder>(zero, G_1, rhs_1); // solve the linear systems (with Bi-CG): const InverseLinearOperatorType fembiCG(lhsMatrix, 1e-8, 1e-8, 20000, DSC_CONFIG_GET("global.cgsolver_verbose", false)); fembiCG(rhs_0, cellSolution_0); fembiCG(rhs_1, cellSolution_1); a_hom[0][0] = getEntry(tensor_transformed, periodicDiscreteFunctionSpace, cellSolution_0, cellSolution_0, 0, 0); a_hom[1][1] = getEntry(tensor_transformed, periodicDiscreteFunctionSpace, cellSolution_1, cellSolution_1, 1, 1); a_hom[0][1] = getEntry(tensor_transformed, periodicDiscreteFunctionSpace, cellSolution_0, cellSolution_1, 0, 1); a_hom[1][0] = a_hom[0][1]; DSC_LOG_DEBUG << "A_homogenized[0][0] = " << a_hom[0][0] << std::endl << "A_homogenized[0][1] = " << a_hom[0][1] << std::endl << "A_homogenized[1][0] = " << a_hom[1][0] << std::endl << "A_homogenized[1][1] = " << a_hom[1][1] << std::endl; return a_hom; } // getHomTensor }; // end of class } // namespace Multiscale { } // end namespace #endif // ifndef DUNE_HOMOGENIZER_HH <commit_msg>fix massweight parent class<commit_after>// dune-multiscale // Copyright Holders: Patrick Henning, Rene Milk // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // das alles klappt momentan nur in 2-D!!! Es laesst sich aber sehr einfach verallgemeinern. // Implementierung funktioniert unter folgenden Voraussetzungen an den (Diffusions-)Tensor: // 1. Elliptizitätsbedingung // 2. A(x,y) = A(y) #ifndef DUNE_HOMOGENIZER_HH #define DUNE_HOMOGENIZER_HH #include <dune/multiscale/fem/elliptic_fem_matrix_assembler.hh> #include <dune/fem/gridpart/periodicgridpart/periodicgridpart.hh> // for data output: #include <dune/fem/io/file/dataoutput.hh> #include <dune/fem/io/parameter.hh> #include <dune/fem/io/file/datawriter.hh> #include <dune/fem/quadrature/cachingquadrature.hh> #include <dune/stuff/fem/functions/analytical.hh> #include <dune/stuff/common/memory.hh> #include <dune/multiscale/common/righthandside_assembler.hh> namespace Dune { namespace Multiscale { //! define output traits struct CellDataOutputParameters : public Fem::DataOutputParameters { public: std::string my_prefix_; // path where the data is stored std::string path() const { return "data_output_hmm"; } void set_prefix(std::string my_prefix) { my_prefix_ = my_prefix; // std :: cout << "Set prefix. my_prefix_ = " << my_prefix_ << std :: endl; } // base of file name for data file std::string prefix() const { if (my_prefix_ == "") return "solutions_cell_problems"; else return my_prefix_; } // format of output: int outputformat() const { // return 0; // GRAPE (lossless format) return 1; // VTK // return 2; // VTK vertex data // return 3; // gnuplot } }; NULLFUNCTION(ZeroFunction) //! \TODO docme // (to replace the more general lower order term) class MassWeight : public Problem::LowerOrderBase { public: MassWeight(double lambda) : lambda_(lambda) {} void evaluate(const DomainType& /*x*/, const RangeType& position, const JacobianRangeType& /*direction_gradient*/, RangeType& y) const { y = lambda_ * position; } virtual void evaluate(const DomainType& /*x*/, RangeType& /*ret*/) const { DUNE_THROW(Dune::NotImplemented, ""); } virtual void evaluate(const DomainType&, const TimeType&, RangeType& y) const { DUNE_THROW(Dune::NotImplemented, ""); } virtual void position_derivative(const DomainType&, const RangeType&, const JacobianRangeType&, RangeType& y) const { y = RangeType(0); } virtual void direction_derivative(const DomainType&, const RangeType&, const JacobianRangeType&, JacobianRangeType& y) const { y = JacobianRangeType(0); } double lambda_; }; /** since we need to evaluate A( x, \cdot ) to solve cellproblems (in comparison to A( \cdot, \frac{\cdot}{\epsilon} ) * for the global problem), we must transform the orginal tensor to be able to use a standard FEM operator for solving * cell problems (otherwise: calling the method evaluate(i,j,x,y) within the matrixassembler would evaluate A^{\epsilon} * instead of A(x,\cdot) ) **/ template <class TensorImp> class TransformTensor : public Problem::DiffusionBase { private: typedef CommonTraits::FunctionSpaceType FunctionSpaceType; typedef TensorImp TensorType; typedef typename FunctionSpaceType::DomainType DomainType; typedef typename FunctionSpaceType::RangeType RangeType; typedef typename FunctionSpaceType::JacobianRangeType JacobianRangeType; typedef typename FunctionSpaceType::DomainFieldType DomainFieldType; typedef typename FunctionSpaceType::RangeFieldType RangeFieldType; typedef DomainFieldType TimeType; static const int dimDomain = DomainType::dimension; const TensorType& tensor_; public: // Constructor inline explicit TransformTensor(const TensorType& tensor) : tensor_(tensor) {} void diffusiveFlux(const DomainType& y, const JacobianRangeType& direction, JacobianRangeType& flux) const { DomainType new_y = y; new_y *= DSC_CONFIG_GET("problem.epsilon", 1.0f); tensor_.diffusiveFlux(new_y, direction, flux); } // diffusiveFlux inline void evaluate(const int /*i*/, const int /*j*/, const DomainType& /*x*/, const TimeType& /*time*/, RangeType& /*y*/) const { DUNE_THROW(Dune::NotImplemented, ""); } inline void evaluate(const DomainType& /*x*/, RangeType& /*y*/) const { DUNE_THROW(Dune::NotImplemented, ""); } inline void evaluate(const DomainType& /*x*/, const TimeType& /*time*/, RangeType& /*y*/) const { DUNE_THROW(Dune::NotImplemented, ""); } virtual void jacobianDiffusiveFlux(const DomainType& /*x*/, const JacobianRangeType& /*position_gradient*/, const JacobianRangeType& /*direction_gradient*/, JacobianRangeType& /*flux*/) const { DUNE_THROW(Dune::NotImplemented, ""); } }; //! the following class is comparable to a SecondSource-Class (some kind of -div G ) template <class TensorImp> class CellSource : CommonTraits::FunctionBaseType { private: typedef TensorImp TensorType; typedef CommonTraits::FunctionSpaceType FunctionSpaceType; typedef typename FunctionSpaceType::DomainType DomainType; typedef typename FunctionSpaceType::RangeType RangeType; typedef typename FunctionSpaceType::JacobianRangeType JacobianRangeType; typedef typename FunctionSpaceType::DomainFieldType DomainFieldType; typedef typename FunctionSpaceType::RangeFieldType RangeFieldType; const FunctionSpaceType& functionSpace_; const TensorType& tensor_; const int& j_; public: inline explicit CellSource(const FunctionSpaceType& functionSpace, const TensorType& tensor, const int& j) : functionSpace_(functionSpace) , tensor_(tensor) , j_(j) // we solve the j'th cell problem {} inline void evaluate(const DomainType& /*x*/, RangeType& y) const { y[0] = 0; } inline void evaluate(const int i, const DomainType& y, RangeType& z) const { JacobianRangeType direction; JacobianRangeType flux; for (int j = 0; j < DomainType::dimension; ++j) { direction[0][j] = int(j_ == j); } tensor_.diffusiveFlux(y, direction, flux); // tensor_.evaluate( i, j_, y, z); z = -flux[0][i]; } // evaluate }; NULLFUNCTION(DefaultDummyAdvection) //! \TODO docme template <class TensorImp> class Homogenizer { private: typedef CommonTraits::GridType GridType; static const int dimension = GridType::dimension; typedef TensorImp TensorType; typedef Fem::PeriodicLeafGridPart<GridType> PeriodicGridPartType; typedef CommonTraits::FunctionSpaceType FunctionSpaceType; typedef Fem::LagrangeDiscreteFunctionSpace<FunctionSpaceType, PeriodicGridPartType, 1> PeriodicDiscreteFunctionSpaceType; // to avoid confusion: typedef PeriodicDiscreteFunctionSpaceType DummySpaceType; // (sometimes PeriodicDiscreteFunctionSpaceType is only a dummy) typedef Fem::AdaptiveDiscreteFunction<PeriodicDiscreteFunctionSpaceType> PeriodicDiscreteFunctionType; // to avoid confusion: typedef PeriodicDiscreteFunctionType DummyType; // (sometimes PeriodicDiscreteFunctionType is only a dummy) typedef MassWeight MassWeightType; typedef ZeroFunction<FunctionSpaceType> ZeroFunctionType; typedef DefaultDummyAdvection<FunctionSpaceType> DefaultDummyAdvectionType; typedef TransformTensor<TensorType> TransformTensorType; typedef CellSource<TransformTensorType> CellSourceType; typedef typename PeriodicDiscreteFunctionSpaceType::JacobianRangeType PeriodicJacobianRangeType; typedef typename PeriodicDiscreteFunctionType::LocalFunctionType PeriodicLocalFunctionType; typedef typename GridType::template Codim<0>::Entity EntityType; typedef typename BackendChooser<PeriodicDiscreteFunctionSpaceType>::LinearOperatorType LinearOperatorType; typedef typename BackendChooser<PeriodicDiscreteFunctionSpaceType>::InverseOperatorType InverseLinearOperatorType; // discrete elliptic operator (corresponds with FEM Matrix) typedef Multiscale::FEM::DiscreteEllipticOperator<PeriodicDiscreteFunctionType, TransformTensorType> EllipticOperatorType; typedef typename FunctionSpaceType::DomainType DomainType; typedef typename FunctionSpaceType::RangeType RangeType; enum { spacePolOrd = PeriodicDiscreteFunctionSpaceType::polynomialOrder }; // dgf file that describes the perforated domain const std::string& filename_; public: Homogenizer(const std::string& filename) : filename_(filename) {} typedef FieldMatrix<RangeType, dimension, dimension> HomTensorType; private: double getEntry(const TransformTensorType& tensor, const PeriodicDiscreteFunctionSpaceType& periodicDiscreteFunctionSpace, const PeriodicDiscreteFunctionType& w_i, const PeriodicDiscreteFunctionType& w_j, const int& i, const int& j) const { double a_ij_hom = 0; for (const auto& entity : periodicDiscreteFunctionSpace) { auto localW_i = w_i.localFunction(entity); auto localW_j = w_j.localFunction(entity); // create quadrature for given geometry type //!\TODO soll das WIRLKLICH pold order 2 sein? const auto quadrature = make_quadrature(entity, periodicDiscreteFunctionSpace, 2); // get geoemetry of entity const auto& geometry = entity.geometry(); // integrate for (const auto localQuadPoint : DSC::valueRange(quadrature.nop())) { RangeType localIntegral = 0; PeriodicJacobianRangeType grad_w_i; localW_i.jacobian(quadrature[localQuadPoint], grad_w_i); PeriodicJacobianRangeType grad_w_j; localW_j.jacobian(quadrature[localQuadPoint], grad_w_j); // local (barycentric) coordinates (with respect to cell grid entity) const auto& local_point = quadrature.point(localQuadPoint); // global point in the unit cell Y const auto global_point_in_Y = geometry.global(local_point); PeriodicJacobianRangeType direction_i; for (int k = 0; k < dimension; ++k) { direction_i[0][k] = grad_w_i[0][k]; if (k == i) { direction_i[0][k] += 1.0; } } PeriodicJacobianRangeType direction_j; for (int k = 0; k < dimension; ++k) { direction_j[0][k] = 0.0; if (k == j) { direction_j[0][k] += 1.0; } } PeriodicJacobianRangeType flux_i; tensor.diffusiveFlux(global_point_in_Y, direction_i, flux_i); localIntegral = (flux_i[0] * direction_j[0]); const double entityVolume = quadrature.weight(localQuadPoint) * geometry.integrationElement(quadrature.point(localQuadPoint)); a_ij_hom += entityVolume * localIntegral; } } return a_ij_hom; } // end of method public: HomTensorType getHomTensor(const TensorType& tensor) const { HomTensorType a_hom; // to solve cell problems, we always need to use a perforated unit cube as domain: GridPtr<GridType> periodicgridptr(filename_); Dune::Fem::GlobalRefine::apply(*periodicgridptr, 10); PeriodicGridPartType periodicGridPart(*periodicgridptr); PeriodicDiscreteFunctionSpaceType periodicDiscreteFunctionSpace(periodicGridPart); // to avoid confusions: const DummySpaceType dummySpace(periodicGridPart); // (sometimes periodicDiscreteFunctionSpace is only a dummy) //! define the type of the corresponding solutions ( discrete functions of the type 'DiscreteFunctionType'): PeriodicDiscreteFunctionType cellSolution_0("cellSolution 0", periodicDiscreteFunctionSpace); cellSolution_0.clear(); PeriodicDiscreteFunctionType cellSolution_1("cellSolution 1", periodicDiscreteFunctionSpace); cellSolution_1.clear(); PeriodicDiscreteFunctionType rhs_0("rhs_0", periodicDiscreteFunctionSpace); rhs_0.clear(); PeriodicDiscreteFunctionType rhs_1("rhs_1", periodicDiscreteFunctionSpace); rhs_1.clear(); const RangeType lambda = 1e-07; // we need solve several cell problems with a periodic boundary condition. To fix the solution we need some kind of // additional condition. Therefor we solve // \lambda w - \div A \nabla w = rhs instead of - \div A \nabla w = rhs const TransformTensorType tensor_transformed(tensor); // if we have some additional source term (-div G), define: const CellSourceType G_0(periodicDiscreteFunctionSpace, tensor_transformed, 0); // 0'th cell problem const CellSourceType G_1(periodicDiscreteFunctionSpace, tensor_transformed, 1); // 1'th cell problem // - div ( A \nabla u^{\epsilon} ) = f - div G // quite a dummy. It's always f = 0 const ZeroFunctionType zero; //! build the left hand side (lhs) of the problem const std::unique_ptr<const Problem::LowerOrderBase> mass(new MassWeightType(lambda)); // define mass (just for cell problems \lambda w - \div A \nabla w = rhs) const EllipticOperatorType discrete_cell_elliptic_op(periodicDiscreteFunctionSpace, tensor_transformed, mass); LinearOperatorType lhsMatrix("Cell Problem Stiffness Matrix", periodicDiscreteFunctionSpace, periodicDiscreteFunctionSpace); discrete_cell_elliptic_op.assemble_matrix(lhsMatrix, false /*no boundary treatment*/); //! build the right hand side (rhs) of the problem // the same right hand side for HM and FEM methods: typedef RightHandSideAssembler<PeriodicDiscreteFunctionType> RhsAssembler; // Alternativly it is possible to call the RightHandSideAssembler with a second source Term '- div G': // RightHandSideAssembler< DiscreteFunctionType > rhsassembler( tensor , G ); RhsAssembler::template assemble<2 * PeriodicDiscreteFunctionSpaceType::polynomialOrder>(zero, G_0, rhs_0); RhsAssembler::template assemble<2 * PeriodicDiscreteFunctionSpaceType::polynomialOrder>(zero, G_1, rhs_1); // solve the linear systems (with Bi-CG): const InverseLinearOperatorType fembiCG(lhsMatrix, 1e-8, 1e-8, 20000, DSC_CONFIG_GET("global.cgsolver_verbose", false)); fembiCG(rhs_0, cellSolution_0); fembiCG(rhs_1, cellSolution_1); a_hom[0][0] = getEntry(tensor_transformed, periodicDiscreteFunctionSpace, cellSolution_0, cellSolution_0, 0, 0); a_hom[1][1] = getEntry(tensor_transformed, periodicDiscreteFunctionSpace, cellSolution_1, cellSolution_1, 1, 1); a_hom[0][1] = getEntry(tensor_transformed, periodicDiscreteFunctionSpace, cellSolution_0, cellSolution_1, 0, 1); a_hom[1][0] = a_hom[0][1]; DSC_LOG_DEBUG << "A_homogenized[0][0] = " << a_hom[0][0] << std::endl << "A_homogenized[0][1] = " << a_hom[0][1] << std::endl << "A_homogenized[1][0] = " << a_hom[1][0] << std::endl << "A_homogenized[1][1] = " << a_hom[1][1] << std::endl; return a_hom; } // getHomTensor }; // end of class } // namespace Multiscale { } // end namespace #endif // ifndef DUNE_HOMOGENIZER_HH <|endoftext|>
<commit_before>#include "Renderer.h" #include <Probulator/Image.h> #include <string> #include <glm/gtc/type_ptr.hpp> TexturePtr createTextureFromImage( const Image& image, const TextureFilter& filter, bool verticalFlip) { assert(image.getPixelCount() != 0); TexturePtr result = std::make_shared<Texture>(); const GLenum type = GL_TEXTURE_2D; result->m_type = type; glGenTextures(1, &result->m_native); glBindTexture(result->m_type, result->m_native); glTexParameteri(type, GL_TEXTURE_WRAP_S, filter.wrapU); glTexParameteri(type, GL_TEXTURE_WRAP_T, filter.wrapV); glTexParameteri(type, GL_TEXTURE_MIN_FILTER, filter.filterMin); glTexParameteri(type, GL_TEXTURE_MAG_FILTER, filter.filterMag); const GLsizei w = image.getWidth(); const GLsizei h = image.getHeight(); if (verticalFlip) { Image flippedImage(w, h); for (int y = 0; y < h; ++y) { vec4* rowPixelsOut = flippedImage.getPixels() + w*y; const vec4* rowPixelsIn = image.getPixels() + w*(h - 1 - y); memcpy(rowPixelsOut, rowPixelsIn, sizeof(vec4) * w); } glTexImage2D(type, 0, GL_RGBA32F, w, h, 0, GL_RGBA, GL_FLOAT, flippedImage.data()); } else { glTexImage2D(type, 0, GL_RGBA32F, w, h, 0, GL_RGBA, GL_FLOAT, image.data()); } return result; } const char* toString(VertexAttribute attribute) { switch (attribute) { default: case VertexAttribute_Invalid: return "Invalid"; case VertexAttribute_Position: return "Position"; case VertexAttribute_Normal: return "Normal"; case VertexAttribute_TexCoord0: return "TexCoord0"; case VertexAttribute_TexCoord1: return "TexCoord1"; case VertexAttribute_TexCoord2: return "TexCoord2"; case VertexAttribute_TexCoord3: return "TexCoord3"; } } ShaderPtr createShaderFromSource(u32 type, const char* source) { ShaderPtr result = std::make_shared<Shader>(); result->m_type = type; result->m_native = glCreateShader(type); glShaderSource(result->m_native, 1, &source, nullptr); glCompileShader(result->m_native); GLint compileStatus = 0; glGetShaderiv(result->m_native, GL_COMPILE_STATUS, &compileStatus); if (!compileStatus) { GLint infoLogLength = 0; glGetShaderiv(result->m_native, GL_INFO_LOG_LENGTH, &infoLogLength); std::string shaderInfoLog; shaderInfoLog.resize(infoLogLength); glGetShaderInfoLog(result->m_native, infoLogLength, nullptr, &shaderInfoLog[0]); printf("ERROR: Could not compile shader.\n%s\n", shaderInfoLog.c_str()); throw std::exception("Failed to compile shader."); } return result; } ShaderProgramPtr createShaderProgram( const Shader& vertexShader, const Shader& pixelShader, const VertexFormat& vertexFormat) { assert(vertexShader.m_native); assert(pixelShader.m_native); ShaderProgramPtr result = std::make_shared<ShaderProgram>(); result->m_native = glCreateProgram(); result->m_vertexFormat = vertexFormat; glAttachShader(result->m_native, vertexShader.m_native); glAttachShader(result->m_native, pixelShader.m_native); glLinkProgram(result->m_native); GLint linkStatus = 0; glGetProgramiv(result->m_native, GL_LINK_STATUS, &linkStatus); if (!linkStatus) { GLchar errorLog[1024] = { 0 }; glGetProgramInfoLog(result->m_native, 1024, NULL, errorLog); printf((std::string() + "error linking program: " + errorLog).c_str()); throw std::exception("Failed to link shader program."); } glGenVertexArrays(1, &result->m_vertexArray); glBindVertexArray(result->m_vertexArray); for (u32 i = 0; i < vertexFormat.elementCount; ++i) { const VertexElement& element = vertexFormat.elements[i]; const char* attributeName = toString(element.attribute); GLint location = glGetAttribLocation(result->m_native, attributeName); if (location != -1) { glEnableVertexAttribArray(location); } result->m_vertexAttributeLocations[i] = location; } for (u32 i = vertexFormat.elementCount; i < VertexFormat::MaxElements; ++i) { result->m_vertexAttributeLocations[i] = -1; } for (u32 i = 0; i < ShaderProgram::MaxTextures; ++i) { char name[] = "Texture#"; name[7] = '0' + i; result->m_textureLocations[i] = glGetUniformLocation(result->m_native, name); } return result; } void setVertexBuffer(const ShaderProgram& shaderProgram, u32 vertexBuffer, u32 vertexStride) { glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); glBindVertexArray(shaderProgram.m_vertexArray); for (u32 i = 0; i < shaderProgram.m_vertexFormat.elementCount; ++i) { const VertexElement& element = shaderProgram.m_vertexFormat.elements[i]; glVertexAttribPointer( shaderProgram.m_vertexAttributeLocations[i], element.componentCount, element.dataType, element.normalized, vertexStride, ((char*)(nullptr)) + element.offset); } } void setTexture(const ShaderProgram& shaderProgram, u32 slotIndex, const Texture& texture) { GLint location = shaderProgram.m_textureLocations[slotIndex]; if (location == -1) return; glActiveTexture(GL_TEXTURE0 + slotIndex); glBindTexture(texture.m_type, texture.m_native); glUniform1i(location, slotIndex); } void setUniformByName(const ShaderProgram& shaderProgram, const char* name, float value) { GLint location = glGetUniformLocation(shaderProgram.m_native, name); // TODO: cache uniform bindings if (location == -1) return; glUniform1fv(location, 1, &value); } void setUniformByName(const ShaderProgram& shaderProgram, const char* name, const mat4& value) { GLint location = glGetUniformLocation(shaderProgram.m_native, name); // TODO: cache uniform bindings if (location == -1) return; glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(value)); } void setUniformByName(const ShaderProgram& shaderProgram, const char* name, const vec2& value) { GLint location = glGetUniformLocation(shaderProgram.m_native, name); // TODO: cache uniform bindings if (location == -1) return; glUniform2fv(location, 1, glm::value_ptr(value)); } <commit_msg>Fixed compile errors on MacOS<commit_after>#include "Renderer.h" #include <Probulator/Image.h> #include <string> #include <glm/gtc/type_ptr.hpp> TexturePtr createTextureFromImage( const Image& image, const TextureFilter& filter, bool verticalFlip) { assert(image.getPixelCount() != 0); TexturePtr result = std::make_shared<Texture>(); const GLenum type = GL_TEXTURE_2D; result->m_type = type; glGenTextures(1, &result->m_native); glBindTexture(result->m_type, result->m_native); glTexParameteri(type, GL_TEXTURE_WRAP_S, filter.wrapU); glTexParameteri(type, GL_TEXTURE_WRAP_T, filter.wrapV); glTexParameteri(type, GL_TEXTURE_MIN_FILTER, filter.filterMin); glTexParameteri(type, GL_TEXTURE_MAG_FILTER, filter.filterMag); const GLsizei w = image.getWidth(); const GLsizei h = image.getHeight(); if (verticalFlip) { Image flippedImage(w, h); for (int y = 0; y < h; ++y) { vec4* rowPixelsOut = flippedImage.getPixels() + w*y; const vec4* rowPixelsIn = image.getPixels() + w*(h - 1 - y); memcpy(rowPixelsOut, rowPixelsIn, sizeof(vec4) * w); } glTexImage2D(type, 0, GL_RGBA32F, w, h, 0, GL_RGBA, GL_FLOAT, flippedImage.data()); } else { glTexImage2D(type, 0, GL_RGBA32F, w, h, 0, GL_RGBA, GL_FLOAT, image.data()); } return result; } const char* toString(VertexAttribute attribute) { switch (attribute) { default: case VertexAttribute_Invalid: return "Invalid"; case VertexAttribute_Position: return "Position"; case VertexAttribute_Normal: return "Normal"; case VertexAttribute_TexCoord0: return "TexCoord0"; case VertexAttribute_TexCoord1: return "TexCoord1"; case VertexAttribute_TexCoord2: return "TexCoord2"; case VertexAttribute_TexCoord3: return "TexCoord3"; } } ShaderPtr createShaderFromSource(u32 type, const char* source) { ShaderPtr result = std::make_shared<Shader>(); result->m_type = type; result->m_native = glCreateShader(type); glShaderSource(result->m_native, 1, &source, nullptr); glCompileShader(result->m_native); GLint compileStatus = 0; glGetShaderiv(result->m_native, GL_COMPILE_STATUS, &compileStatus); if (!compileStatus) { GLint infoLogLength = 0; glGetShaderiv(result->m_native, GL_INFO_LOG_LENGTH, &infoLogLength); std::string shaderInfoLog; shaderInfoLog.resize(infoLogLength); glGetShaderInfoLog(result->m_native, infoLogLength, nullptr, &shaderInfoLog[0]); printf("ERROR: Could not compile shader.\n%s\n", shaderInfoLog.c_str()); throw std::runtime_error("Failed to compile shader."); } return result; } ShaderProgramPtr createShaderProgram( const Shader& vertexShader, const Shader& pixelShader, const VertexFormat& vertexFormat) { assert(vertexShader.m_native); assert(pixelShader.m_native); ShaderProgramPtr result = std::make_shared<ShaderProgram>(); result->m_native = glCreateProgram(); result->m_vertexFormat = vertexFormat; glAttachShader(result->m_native, vertexShader.m_native); glAttachShader(result->m_native, pixelShader.m_native); glLinkProgram(result->m_native); GLint linkStatus = 0; glGetProgramiv(result->m_native, GL_LINK_STATUS, &linkStatus); if (!linkStatus) { GLchar errorLog[1024] = { 0 }; glGetProgramInfoLog(result->m_native, 1024, NULL, errorLog); printf((std::string() + "error linking program: " + errorLog).c_str()); throw std::runtime_error("Failed to link shader program."); } glGenVertexArrays(1, &result->m_vertexArray); glBindVertexArray(result->m_vertexArray); for (u32 i = 0; i < vertexFormat.elementCount; ++i) { const VertexElement& element = vertexFormat.elements[i]; const char* attributeName = toString(element.attribute); GLint location = glGetAttribLocation(result->m_native, attributeName); if (location != -1) { glEnableVertexAttribArray(location); } result->m_vertexAttributeLocations[i] = location; } for (u32 i = vertexFormat.elementCount; i < VertexFormat::MaxElements; ++i) { result->m_vertexAttributeLocations[i] = -1; } for (u32 i = 0; i < ShaderProgram::MaxTextures; ++i) { char name[] = "Texture#"; name[7] = '0' + i; result->m_textureLocations[i] = glGetUniformLocation(result->m_native, name); } return result; } void setVertexBuffer(const ShaderProgram& shaderProgram, u32 vertexBuffer, u32 vertexStride) { glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); glBindVertexArray(shaderProgram.m_vertexArray); for (u32 i = 0; i < shaderProgram.m_vertexFormat.elementCount; ++i) { const VertexElement& element = shaderProgram.m_vertexFormat.elements[i]; glVertexAttribPointer( shaderProgram.m_vertexAttributeLocations[i], element.componentCount, element.dataType, element.normalized, vertexStride, ((char*)(nullptr)) + element.offset); } } void setTexture(const ShaderProgram& shaderProgram, u32 slotIndex, const Texture& texture) { GLint location = shaderProgram.m_textureLocations[slotIndex]; if (location == -1) return; glActiveTexture(GL_TEXTURE0 + slotIndex); glBindTexture(texture.m_type, texture.m_native); glUniform1i(location, slotIndex); } void setUniformByName(const ShaderProgram& shaderProgram, const char* name, float value) { GLint location = glGetUniformLocation(shaderProgram.m_native, name); // TODO: cache uniform bindings if (location == -1) return; glUniform1fv(location, 1, &value); } void setUniformByName(const ShaderProgram& shaderProgram, const char* name, const mat4& value) { GLint location = glGetUniformLocation(shaderProgram.m_native, name); // TODO: cache uniform bindings if (location == -1) return; glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(value)); } void setUniformByName(const ShaderProgram& shaderProgram, const char* name, const vec2& value) { GLint location = glGetUniformLocation(shaderProgram.m_native, name); // TODO: cache uniform bindings if (location == -1) return; glUniform2fv(location, 1, glm::value_ptr(value)); } <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include <fstream> #include <iterator> #include <exception> #include <boost/format.hpp> //#include <boost/date_time/posix_time/posix_time.hpp> #include "libtorrent/entry.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/session.hpp" #include "libtorrent/http_settings.hpp" #ifdef WIN32 #if defined(_MSC_VER) # define for if (false) {} else for #endif #include <windows.h> #include <conio.h> bool sleep_and_input(char* c) { Sleep(500); if (kbhit()) { *c = getch(); return true; } return false; }; void set_cursor(int x, int y) { HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE); COORD c = {x, y}; SetConsoleCursorPosition(h, c); } void clear() { HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE); COORD c = {0, 0}; DWORD n; FillConsoleOutputCharacter(h, ' ', 80 * 50, c, &n); } #else #include <stdlib.h> #include <stdio.h> #include <termios.h> #include <string.h> struct set_keypress { set_keypress() { termios new_settings; tcgetattr(0,&stored_settings); new_settings = stored_settings; // Disable canonical mode, and set buffer size to 1 byte new_settings.c_lflag &= (~ICANON); new_settings.c_cc[VTIME] = 0; new_settings.c_cc[VMIN] = 1; tcsetattr(0,TCSANOW,&new_settings); } ~set_keypress() { tcsetattr(0,TCSANOW,&stored_settings); } termios stored_settings; }; bool sleep_and_input(char* c) { // sets the terminal to single-character mode // and resets when destructed set_keypress s; fd_set set; FD_ZERO(&set); FD_SET(0, &set); timeval tv = {1, 0}; if (select(1, &set, 0, 0, &tv) > 0) { *c = getc(stdin); return true; } return false; } void set_cursor(int x, int y) { std::cout << "\033[" << y << ";" << x << "H"; } void clear() { std::cout << "\033[2J"; } #endif std::string to_string(float v) { std::stringstream s; s.precision(4); s.flags(std::ios_base::right); s.width(5); s.fill(' '); s << v; return s.str(); } std::string add_suffix(float val) { const char* prefix[] = {"B ", "kB", "MB", "GB", "TB"}; const int num_prefix = sizeof(prefix) / sizeof(const char*); int i; for (i = 0; i < num_prefix; ++i) { if (val < 1024.f) return to_string(val) + prefix[i]; val /= 1024.f; } return to_string(val) + prefix[i]; } int main(int argc, char* argv[]) { using namespace libtorrent; // TEMPORARY boost::filesystem::path::default_name_check(boost::filesystem::no_check); if (argc < 2) { std::cerr << "usage: ./client_test torrent-files ...\n" "to stop the client, press q.\n"; return 1; } http_settings settings; // settings.proxy_ip = "192.168.0.1"; // settings.proxy_port = 80; // settings.proxy_login = "hyd"; // settings.proxy_password = "foobar"; settings.user_agent = "example"; try { std::vector<torrent_handle> handles; session s(6881, "E\x1"); // limit upload rate to 100 kB/s // s.set_upload_rate_limit(100 * 1024); s.set_http_settings(settings); for (int i = 0; i < argc-1; ++i) { try { std::ifstream in(argv[i+1], std::ios_base::binary); in.unsetf(std::ios_base::skipws); entry e = bdecode(std::istream_iterator<char>(in), std::istream_iterator<char>()); torrent_info t(e); t.print(std::cout); handles.push_back(s.add_torrent(t, boost::filesystem::path("", boost::filesystem::native))); } catch (std::exception& e) { std::cout << e.what() << "\n"; } } std::vector<peer_info> peers; std::vector<partial_piece_info> queue; for (;;) { char c; if (sleep_and_input(&c)) { if (c == 'q') break; } clear(); set_cursor(0, 0); for (std::vector<torrent_handle>::iterator i = handles.begin(); i != handles.end(); ++i) { torrent_status s = i->status(); switch(s.state) { case torrent_status::queued_for_checking: std::cout << "queued "; break; case torrent_status::checking_files: std::cout << "checking "; break; case torrent_status::downloading: std::cout << "dloading "; break; case torrent_status::seeding: std::cout << "seeding "; break; }; // calculate download and upload speeds i->get_peer_info(peers); float down = s.download_rate; float up = s.upload_rate; unsigned int total_down = s.total_download; unsigned int total_up = s.total_upload; int num_peers = peers.size(); /* std::cout << boost::format("%f%% p:%d d:(%s) %s/s u:(%s) %s/s\n") % (s.progress*100) % num_peers % add_suffix(total_down) % add_suffix(down) % add_suffix(total_up) % add_suffix(up); */ std::cout << (s.progress*100) << "% p:" << num_peers << " d:(" << add_suffix(total_down) << ") " << add_suffix(down) << "/s u:(" << add_suffix(total_up) << ") " << add_suffix(up) << "/s\n"; boost::posix_time::time_duration t = s.next_announce; // std::cout << "next announce: " << boost::posix_time::to_simple_string(t) << "\n"; std::cout << "next announce: " << t.hours() << ":" << t.minutes() << ":" << t.seconds() << "\n"; for (std::vector<peer_info>::iterator i = peers.begin(); i != peers.end(); ++i) { std::cout << "d: " << add_suffix(i->down_speed) << "/s (" << add_suffix(i->total_download) << ") u: " << add_suffix(i->up_speed) << "/s (" << add_suffix(i->total_upload) << ") diff: " << add_suffix(i->total_download - i->total_upload) << " flags: " << static_cast<const char*>((i->flags & peer_info::interesting)?"I":"_") << static_cast<const char*>((i->flags & peer_info::choked)?"C":"_") << static_cast<const char*>((i->flags & peer_info::remote_interested)?"i":"_") << static_cast<const char*>((i->flags & peer_info::remote_choked)?"c":"_") << "\n"; } /* i->get_download_queue(queue); for (std::vector<partial_piece_info>::iterator i = queue.begin(); i != queue.end(); ++i) { std::cout << i->piece_index << ": "; for (int j = 0; j < i->blocks_in_piece; ++j) { if (i->finished_blocks[j]) std::cout << "+"; else if (i->requested_blocks[j]) std::cout << "-"; else std::cout << "."; } std::cout << "\n"; } */ std::cout << "___________________________________\n"; } } } catch (std::exception& e) { std::cout << e.what() << "\n"; } return 0; } <commit_msg>*** empty log message ***<commit_after>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include <fstream> #include <iterator> #include <exception> #include <boost/format.hpp> //#include <boost/date_time/posix_time/posix_time.hpp> #include "libtorrent/entry.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/session.hpp" #include "libtorrent/http_settings.hpp" #ifdef WIN32 #if defined(_MSC_VER) # define for if (false) {} else for #endif #include <windows.h> #include <conio.h> bool sleep_and_input(char* c) { Sleep(500); if (kbhit()) { *c = getch(); return true; } return false; }; void set_cursor(int x, int y) { HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE); COORD c = {x, y}; SetConsoleCursorPosition(h, c); } void clear() { HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE); COORD c = {0, 0}; DWORD n; FillConsoleOutputCharacter(h, ' ', 80 * 50, c, &n); } #else #include <stdlib.h> #include <stdio.h> #include <termios.h> #include <string.h> struct set_keypress { set_keypress() { termios new_settings; tcgetattr(0,&stored_settings); new_settings = stored_settings; // Disable canonical mode, and set buffer size to 1 byte new_settings.c_lflag &= (~ICANON); new_settings.c_cc[VTIME] = 0; new_settings.c_cc[VMIN] = 1; tcsetattr(0,TCSANOW,&new_settings); } ~set_keypress() { tcsetattr(0,TCSANOW,&stored_settings); } termios stored_settings; }; bool sleep_and_input(char* c) { // sets the terminal to single-character mode // and resets when destructed set_keypress s; fd_set set; FD_ZERO(&set); FD_SET(0, &set); timeval tv = {1, 0}; if (select(1, &set, 0, 0, &tv) > 0) { *c = getc(stdin); return true; } return false; } void set_cursor(int x, int y) { std::cout << "\033[" << y << ";" << x << "H"; } void clear() { std::cout << "\033[2J"; } #endif std::string to_string(float v) { std::stringstream s; s.precision(3); s.flags(std::ios_base::right); s.width(4); s.fill(' '); s << v; return s.str(); } std::string add_suffix(float val) { const char* prefix[] = {"B ", "kB", "MB", "GB", "TB"}; const int num_prefix = sizeof(prefix) / sizeof(const char*); int i; for (i = 0; i < num_prefix; ++i) { if (abs(val) < 1024.f) return to_string(val) + prefix[i]; val /= 1024.f; } return to_string(val) + prefix[i]; } int main(int argc, char* argv[]) { using namespace libtorrent; // TEMPORARY // boost::filesystem::path::default_name_check(boost::filesystem::no_check); if (argc < 2) { std::cerr << "usage: ./client_test torrent-files ...\n" "to stop the client, press q.\n"; return 1; } http_settings settings; // settings.proxy_ip = "192.168.0.1"; // settings.proxy_port = 80; // settings.proxy_login = "hyd"; // settings.proxy_password = "foobar"; settings.user_agent = "example"; try { std::vector<torrent_handle> handles; session s(6881, "E\x1"); // limit upload rate to 100 kB/s // s.set_upload_rate_limit(100 * 1024); s.set_http_settings(settings); for (int i = 0; i < argc-1; ++i) { try { std::ifstream in(argv[i+1], std::ios_base::binary); in.unsetf(std::ios_base::skipws); entry e = bdecode(std::istream_iterator<char>(in), std::istream_iterator<char>()); torrent_info t(e); t.print(std::cout); handles.push_back(s.add_torrent(t, boost::filesystem::path("", boost::filesystem::native))); } catch (std::exception& e) { std::cout << e.what() << "\n"; } } std::vector<peer_info> peers; std::vector<partial_piece_info> queue; for (;;) { char c; if (sleep_and_input(&c)) { if (c == 'q') break; } clear(); set_cursor(0, 0); for (std::vector<torrent_handle>::iterator i = handles.begin(); i != handles.end(); ++i) { torrent_status s = i->status(); switch(s.state) { case torrent_status::queued_for_checking: std::cout << "queued "; break; case torrent_status::checking_files: std::cout << "checking "; break; case torrent_status::downloading: std::cout << "dloading "; break; case torrent_status::seeding: std::cout << "seeding "; break; }; // calculate download and upload speeds i->get_peer_info(peers); float down = s.download_rate; float up = s.upload_rate; int total_down = s.total_download; int total_up = s.total_upload; int num_peers = peers.size(); /* std::cout << boost::format("%f%% p:%d d:(%s) %s/s u:(%s) %s/s\n") % (s.progress*100) % num_peers % add_suffix(total_down) % add_suffix(down) % add_suffix(total_up) % add_suffix(up); */ std::cout << (s.progress*100) << "% "; for (int i = 0; i < 50; ++i) { if (i / 50.f > s.progress) std::cout << "-"; else std::cout << "#"; } std::cout << "\n"; std::cout << "peers:" << num_peers << " d:" << add_suffix(down) << "/s (" << add_suffix(total_down) << ") u:" << add_suffix(up) << "/s (" << add_suffix(total_up) << ") diff: " << add_suffix(total_down - total_up) << "\n"; boost::posix_time::time_duration t = s.next_announce; // std::cout << "next announce: " << boost::posix_time::to_simple_string(t) << "\n"; std::cout << "next announce: " << t.hours() << ":" << t.minutes() << ":" << t.seconds() << "\n"; for (std::vector<peer_info>::iterator i = peers.begin(); i != peers.end(); ++i) { std::cout << "d: " << add_suffix(i->down_speed) << "/s (" << add_suffix(i->total_download) << ") u: " << add_suffix(i->up_speed) << "/s (" << add_suffix(i->total_upload) << ") df: " << add_suffix((int)i->total_download - (int)i->total_upload) << " f: " << static_cast<const char*>((i->flags & peer_info::interesting)?"I":"_") << static_cast<const char*>((i->flags & peer_info::choked)?"C":"_") << static_cast<const char*>((i->flags & peer_info::remote_interested)?"i":"_") << static_cast<const char*>((i->flags & peer_info::remote_choked)?"c":"_") << "\n"; } std::cout << "___________________________________\n"; i->get_download_queue(queue); for (std::vector<partial_piece_info>::iterator i = queue.begin(); i != queue.end(); ++i) { std::cout.width(4); std::cout.fill(' '); std::cout << i->piece_index << ": |"; for (int j = 0; j < i->blocks_in_piece; ++j) { if (i->finished_blocks[j]) std::cout << "#"; else if (i->requested_blocks[j]) std::cout << "="; else std::cout << "-"; } std::cout << "|\n"; } std::cout << "___________________________________\n"; } } } catch (std::exception& e) { std::cout << e.what() << "\n"; } return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2013 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "WebRuntimeFeatures.h" #include "RuntimeEnabledFeatures.h" #include "WebMediaPlayerClientImpl.h" using namespace WebCore; namespace blink { void WebRuntimeFeatures::enableStableFeatures(bool enable) { RuntimeEnabledFeatures::setStableFeaturesEnabled(enable); // FIXME: enableMediaPlayer does not use RuntimeEnabledFeatures // and does not belong as part of WebRuntimeFeatures. enableMediaPlayer(enable); } void WebRuntimeFeatures::enableExperimentalFeatures(bool enable) { RuntimeEnabledFeatures::setExperimentalFeaturesEnabled(enable); } void WebRuntimeFeatures::enableTestOnlyFeatures(bool enable) { RuntimeEnabledFeatures::setTestFeaturesEnabled(enable); } void WebRuntimeFeatures::enableApplicationCache(bool enable) { RuntimeEnabledFeatures::setApplicationCacheEnabled(enable); } bool WebRuntimeFeatures::isApplicationCacheEnabled() { return RuntimeEnabledFeatures::applicationCacheEnabled(); } void WebRuntimeFeatures::enableDatabase(bool enable) { RuntimeEnabledFeatures::setDatabaseEnabled(enable); } bool WebRuntimeFeatures::isDatabaseEnabled() { return RuntimeEnabledFeatures::databaseEnabled(); } void WebRuntimeFeatures::enableDeviceMotion(bool enable) { RuntimeEnabledFeatures::setDeviceMotionEnabled(enable); } bool WebRuntimeFeatures::isDeviceMotionEnabled() { return RuntimeEnabledFeatures::deviceMotionEnabled(); } void WebRuntimeFeatures::enableDeviceOrientation(bool enable) { RuntimeEnabledFeatures::setDeviceOrientationEnabled(enable); } bool WebRuntimeFeatures::isDeviceOrientationEnabled() { return RuntimeEnabledFeatures::deviceOrientationEnabled(); } void WebRuntimeFeatures::enableDialogElement(bool enable) { RuntimeEnabledFeatures::setDialogElementEnabled(enable); } bool WebRuntimeFeatures::isDialogElementEnabled() { return RuntimeEnabledFeatures::dialogElementEnabled(); } void WebRuntimeFeatures::enableEncryptedMedia(bool enable) { RuntimeEnabledFeatures::setEncryptedMediaEnabled(enable); // FIXME: Hack to allow MediaKeyError to be enabled for either version. RuntimeEnabledFeatures::setEncryptedMediaAnyVersionEnabled( RuntimeEnabledFeatures::encryptedMediaEnabled() || RuntimeEnabledFeatures::prefixedEncryptedMediaEnabled()); } bool WebRuntimeFeatures::isEncryptedMediaEnabled() { return RuntimeEnabledFeatures::encryptedMediaEnabled(); } void WebRuntimeFeatures::enablePrefixedEncryptedMedia(bool enable) { RuntimeEnabledFeatures::setPrefixedEncryptedMediaEnabled(enable); // FIXME: Hack to allow MediaKeyError to be enabled for either version. RuntimeEnabledFeatures::setEncryptedMediaAnyVersionEnabled( RuntimeEnabledFeatures::encryptedMediaEnabled() || RuntimeEnabledFeatures::prefixedEncryptedMediaEnabled()); } bool WebRuntimeFeatures::isPrefixedEncryptedMediaEnabled() { return RuntimeEnabledFeatures::prefixedEncryptedMediaEnabled(); } void WebRuntimeFeatures::enableDirectWrite(bool enable) { RuntimeEnabledFeatures::setDirectWriteEnabled(enable); } bool WebRuntimeFeatures::isDirectWriteEnabled() { return RuntimeEnabledFeatures::directWriteEnabled(); } void WebRuntimeFeatures::enableExperimentalCanvasFeatures(bool enable) { RuntimeEnabledFeatures::setExperimentalCanvasFeaturesEnabled(enable); } bool WebRuntimeFeatures::isExperimentalCanvasFeaturesEnabled() { return RuntimeEnabledFeatures::experimentalCanvasFeaturesEnabled(); } void WebRuntimeFeatures::enableFastTextAutosizing(bool enable) { RuntimeEnabledFeatures::setFastTextAutosizingEnabled(enable); } bool WebRuntimeFeatures::isFastTextAutosizingEnabled() { return RuntimeEnabledFeatures::fastTextAutosizingEnabled(); } void WebRuntimeFeatures::enableFileSystem(bool enable) { RuntimeEnabledFeatures::setFileSystemEnabled(enable); } bool WebRuntimeFeatures::isFileSystemEnabled() { return RuntimeEnabledFeatures::fileSystemEnabled(); } void WebRuntimeFeatures::enableFullscreen(bool enable) { RuntimeEnabledFeatures::setFullscreenEnabled(enable); } bool WebRuntimeFeatures::isFullscreenEnabled() { return RuntimeEnabledFeatures::fullscreenEnabled(); } void WebRuntimeFeatures::enableGamepad(bool enable) { RuntimeEnabledFeatures::setGamepadEnabled(enable); } bool WebRuntimeFeatures::isGamepadEnabled() { return RuntimeEnabledFeatures::gamepadEnabled(); } void WebRuntimeFeatures::enableGeolocation(bool enable) { RuntimeEnabledFeatures::setGeolocationEnabled(enable); } bool WebRuntimeFeatures::isGeolocationEnabled() { return RuntimeEnabledFeatures::geolocationEnabled(); } void WebRuntimeFeatures::enableLazyLayout(bool enable) { // FIXME: Remove this once Chromium stops calling this. } void WebRuntimeFeatures::enableLocalStorage(bool enable) { RuntimeEnabledFeatures::setLocalStorageEnabled(enable); } bool WebRuntimeFeatures::isLocalStorageEnabled() { return RuntimeEnabledFeatures::localStorageEnabled(); } void WebRuntimeFeatures::enableMediaPlayer(bool enable) { RuntimeEnabledFeatures::setMediaEnabled(enable); } bool WebRuntimeFeatures::isMediaPlayerEnabled() { return RuntimeEnabledFeatures::mediaEnabled(); } void WebRuntimeFeatures::enableWebKitMediaSource(bool enable) { RuntimeEnabledFeatures::setWebKitMediaSourceEnabled(enable); } bool WebRuntimeFeatures::isWebKitMediaSourceEnabled() { return RuntimeEnabledFeatures::webKitMediaSourceEnabled(); } void WebRuntimeFeatures::enableMediaSource(bool enable) { RuntimeEnabledFeatures::setMediaSourceEnabled(enable); } bool WebRuntimeFeatures::isMediaSourceEnabled() { return RuntimeEnabledFeatures::mediaSourceEnabled(); } void WebRuntimeFeatures::enableMediaStream(bool enable) { RuntimeEnabledFeatures::setMediaStreamEnabled(enable); } bool WebRuntimeFeatures::isMediaStreamEnabled() { return RuntimeEnabledFeatures::mediaStreamEnabled(); } void WebRuntimeFeatures::enableNotifications(bool enable) { RuntimeEnabledFeatures::setNotificationsEnabled(enable); } bool WebRuntimeFeatures::isNotificationsEnabled() { return RuntimeEnabledFeatures::notificationsEnabled(); } void WebRuntimeFeatures::enablePagePopup(bool enable) { RuntimeEnabledFeatures::setPagePopupEnabled(enable); } bool WebRuntimeFeatures::isPagePopupEnabled() { return RuntimeEnabledFeatures::pagePopupEnabled(); } void WebRuntimeFeatures::enablePeerConnection(bool enable) { RuntimeEnabledFeatures::setPeerConnectionEnabled(enable); } bool WebRuntimeFeatures::isPeerConnectionEnabled() { return RuntimeEnabledFeatures::peerConnectionEnabled(); } void WebRuntimeFeatures::enableRequestAutocomplete(bool enable) { RuntimeEnabledFeatures::setRequestAutocompleteEnabled(enable); } bool WebRuntimeFeatures::isRequestAutocompleteEnabled() { return RuntimeEnabledFeatures::requestAutocompleteEnabled(); } void WebRuntimeFeatures::enableScriptedSpeech(bool enable) { RuntimeEnabledFeatures::setScriptedSpeechEnabled(enable); } bool WebRuntimeFeatures::isScriptedSpeechEnabled() { return RuntimeEnabledFeatures::scriptedSpeechEnabled(); } void WebRuntimeFeatures::enableServiceWorker(bool enable) { RuntimeEnabledFeatures::setServiceWorkerEnabled(enable); } bool WebRuntimeFeatures::isServiceWorkerEnabled() { return RuntimeEnabledFeatures::serviceWorkerEnabled(); } void WebRuntimeFeatures::enableSessionStorage(bool enable) { RuntimeEnabledFeatures::setSessionStorageEnabled(enable); } bool WebRuntimeFeatures::isSessionStorageEnabled() { return RuntimeEnabledFeatures::sessionStorageEnabled(); } void WebRuntimeFeatures::enableSpeechInput(bool enable) { RuntimeEnabledFeatures::setSpeechInputEnabled(enable); } bool WebRuntimeFeatures::isSpeechInputEnabled() { return RuntimeEnabledFeatures::speechInputEnabled(); } void WebRuntimeFeatures::enableSpeechSynthesis(bool enable) { RuntimeEnabledFeatures::setSpeechSynthesisEnabled(enable); } bool WebRuntimeFeatures::isSpeechSynthesisEnabled() { return RuntimeEnabledFeatures::speechSynthesisEnabled(); } void WebRuntimeFeatures::enableTouch(bool enable) { RuntimeEnabledFeatures::setTouchEnabled(enable); } bool WebRuntimeFeatures::isTouchEnabled() { return RuntimeEnabledFeatures::touchEnabled(); } void WebRuntimeFeatures::enableWebAnimationsCSS(bool enable) { RuntimeEnabledFeatures::setWebAnimationsCSSEnabled(enable); } void WebRuntimeFeatures::enableWebAnimationsSVG(bool enable) { RuntimeEnabledFeatures::setWebAnimationsSVGEnabled(enable); } void WebRuntimeFeatures::enableWebAudio(bool enable) { RuntimeEnabledFeatures::setWebAudioEnabled(enable); } bool WebRuntimeFeatures::isWebAudioEnabled() { return RuntimeEnabledFeatures::webAudioEnabled(); } void WebRuntimeFeatures::enableWebGLDraftExtensions(bool enable) { RuntimeEnabledFeatures::setWebGLDraftExtensionsEnabled(enable); } bool WebRuntimeFeatures::isWebGLDraftExtensionsEnabled() { return RuntimeEnabledFeatures::webGLDraftExtensionsEnabled(); } void WebRuntimeFeatures::enableWebMIDI(bool enable) { return RuntimeEnabledFeatures::setWebMIDIEnabled(enable); } bool WebRuntimeFeatures::isWebMIDIEnabled() { return RuntimeEnabledFeatures::webMIDIEnabled(); } void WebRuntimeFeatures::enableDataListElement(bool enable) { RuntimeEnabledFeatures::setDataListElementEnabled(enable); } bool WebRuntimeFeatures::isDataListElementEnabled() { return RuntimeEnabledFeatures::dataListElementEnabled(); } void WebRuntimeFeatures::enableHTMLImports(bool enable) { RuntimeEnabledFeatures::setHTMLImportsEnabled(enable); } bool WebRuntimeFeatures::isHTMLImportsEnabled() { return RuntimeEnabledFeatures::htmlImportsEnabled(); } void WebRuntimeFeatures::enableXSLT(bool enable) { RuntimeEnabledFeatures::setXSLTEnabled(enable); } void WebRuntimeFeatures::enableEmbedderCustomElements(bool enable) { RuntimeEnabledFeatures::setEmbedderCustomElementsEnabled(enable); } void WebRuntimeFeatures::enableOverlayScrollbars(bool enable) { RuntimeEnabledFeatures::setOverlayScrollbarsEnabled(enable); } void WebRuntimeFeatures::enableInputModeAttribute(bool enable) { RuntimeEnabledFeatures::setInputModeAttributeEnabled(enable); } void WebRuntimeFeatures::enableOverlayFullscreenVideo(bool enable) { RuntimeEnabledFeatures::setOverlayFullscreenVideoEnabled(enable); } void WebRuntimeFeatures::enableSharedWorker(bool enable) { RuntimeEnabledFeatures::setSharedWorkerEnabled(enable); } void WebRuntimeFeatures::enableRepaintAfterLayout(bool enable) { RuntimeEnabledFeatures::setRepaintAfterLayoutEnabled(enable); } } // namespace blink <commit_msg>[win] Have direct-write flag enable subpixel font scaling<commit_after>/* * Copyright (C) 2013 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "WebRuntimeFeatures.h" #include "RuntimeEnabledFeatures.h" #include "WebMediaPlayerClientImpl.h" using namespace WebCore; namespace blink { void WebRuntimeFeatures::enableStableFeatures(bool enable) { RuntimeEnabledFeatures::setStableFeaturesEnabled(enable); // FIXME: enableMediaPlayer does not use RuntimeEnabledFeatures // and does not belong as part of WebRuntimeFeatures. enableMediaPlayer(enable); } void WebRuntimeFeatures::enableExperimentalFeatures(bool enable) { RuntimeEnabledFeatures::setExperimentalFeaturesEnabled(enable); } void WebRuntimeFeatures::enableTestOnlyFeatures(bool enable) { RuntimeEnabledFeatures::setTestFeaturesEnabled(enable); } void WebRuntimeFeatures::enableApplicationCache(bool enable) { RuntimeEnabledFeatures::setApplicationCacheEnabled(enable); } bool WebRuntimeFeatures::isApplicationCacheEnabled() { return RuntimeEnabledFeatures::applicationCacheEnabled(); } void WebRuntimeFeatures::enableDatabase(bool enable) { RuntimeEnabledFeatures::setDatabaseEnabled(enable); } bool WebRuntimeFeatures::isDatabaseEnabled() { return RuntimeEnabledFeatures::databaseEnabled(); } void WebRuntimeFeatures::enableDeviceMotion(bool enable) { RuntimeEnabledFeatures::setDeviceMotionEnabled(enable); } bool WebRuntimeFeatures::isDeviceMotionEnabled() { return RuntimeEnabledFeatures::deviceMotionEnabled(); } void WebRuntimeFeatures::enableDeviceOrientation(bool enable) { RuntimeEnabledFeatures::setDeviceOrientationEnabled(enable); } bool WebRuntimeFeatures::isDeviceOrientationEnabled() { return RuntimeEnabledFeatures::deviceOrientationEnabled(); } void WebRuntimeFeatures::enableDialogElement(bool enable) { RuntimeEnabledFeatures::setDialogElementEnabled(enable); } bool WebRuntimeFeatures::isDialogElementEnabled() { return RuntimeEnabledFeatures::dialogElementEnabled(); } void WebRuntimeFeatures::enableEncryptedMedia(bool enable) { RuntimeEnabledFeatures::setEncryptedMediaEnabled(enable); // FIXME: Hack to allow MediaKeyError to be enabled for either version. RuntimeEnabledFeatures::setEncryptedMediaAnyVersionEnabled( RuntimeEnabledFeatures::encryptedMediaEnabled() || RuntimeEnabledFeatures::prefixedEncryptedMediaEnabled()); } bool WebRuntimeFeatures::isEncryptedMediaEnabled() { return RuntimeEnabledFeatures::encryptedMediaEnabled(); } void WebRuntimeFeatures::enablePrefixedEncryptedMedia(bool enable) { RuntimeEnabledFeatures::setPrefixedEncryptedMediaEnabled(enable); // FIXME: Hack to allow MediaKeyError to be enabled for either version. RuntimeEnabledFeatures::setEncryptedMediaAnyVersionEnabled( RuntimeEnabledFeatures::encryptedMediaEnabled() || RuntimeEnabledFeatures::prefixedEncryptedMediaEnabled()); } bool WebRuntimeFeatures::isPrefixedEncryptedMediaEnabled() { return RuntimeEnabledFeatures::prefixedEncryptedMediaEnabled(); } void WebRuntimeFeatures::enableDirectWrite(bool enable) { RuntimeEnabledFeatures::setDirectWriteEnabled(enable); RuntimeEnabledFeatures::setSubpixelFontScalingEnabled(enable || RuntimeEnabledFeatures::subpixelFontScalingEnabled()); } bool WebRuntimeFeatures::isDirectWriteEnabled() { return RuntimeEnabledFeatures::directWriteEnabled(); } void WebRuntimeFeatures::enableExperimentalCanvasFeatures(bool enable) { RuntimeEnabledFeatures::setExperimentalCanvasFeaturesEnabled(enable); } bool WebRuntimeFeatures::isExperimentalCanvasFeaturesEnabled() { return RuntimeEnabledFeatures::experimentalCanvasFeaturesEnabled(); } void WebRuntimeFeatures::enableFastTextAutosizing(bool enable) { RuntimeEnabledFeatures::setFastTextAutosizingEnabled(enable); } bool WebRuntimeFeatures::isFastTextAutosizingEnabled() { return RuntimeEnabledFeatures::fastTextAutosizingEnabled(); } void WebRuntimeFeatures::enableFileSystem(bool enable) { RuntimeEnabledFeatures::setFileSystemEnabled(enable); } bool WebRuntimeFeatures::isFileSystemEnabled() { return RuntimeEnabledFeatures::fileSystemEnabled(); } void WebRuntimeFeatures::enableFullscreen(bool enable) { RuntimeEnabledFeatures::setFullscreenEnabled(enable); } bool WebRuntimeFeatures::isFullscreenEnabled() { return RuntimeEnabledFeatures::fullscreenEnabled(); } void WebRuntimeFeatures::enableGamepad(bool enable) { RuntimeEnabledFeatures::setGamepadEnabled(enable); } bool WebRuntimeFeatures::isGamepadEnabled() { return RuntimeEnabledFeatures::gamepadEnabled(); } void WebRuntimeFeatures::enableGeolocation(bool enable) { RuntimeEnabledFeatures::setGeolocationEnabled(enable); } bool WebRuntimeFeatures::isGeolocationEnabled() { return RuntimeEnabledFeatures::geolocationEnabled(); } void WebRuntimeFeatures::enableLazyLayout(bool enable) { // FIXME: Remove this once Chromium stops calling this. } void WebRuntimeFeatures::enableLocalStorage(bool enable) { RuntimeEnabledFeatures::setLocalStorageEnabled(enable); } bool WebRuntimeFeatures::isLocalStorageEnabled() { return RuntimeEnabledFeatures::localStorageEnabled(); } void WebRuntimeFeatures::enableMediaPlayer(bool enable) { RuntimeEnabledFeatures::setMediaEnabled(enable); } bool WebRuntimeFeatures::isMediaPlayerEnabled() { return RuntimeEnabledFeatures::mediaEnabled(); } void WebRuntimeFeatures::enableWebKitMediaSource(bool enable) { RuntimeEnabledFeatures::setWebKitMediaSourceEnabled(enable); } bool WebRuntimeFeatures::isWebKitMediaSourceEnabled() { return RuntimeEnabledFeatures::webKitMediaSourceEnabled(); } void WebRuntimeFeatures::enableMediaSource(bool enable) { RuntimeEnabledFeatures::setMediaSourceEnabled(enable); } bool WebRuntimeFeatures::isMediaSourceEnabled() { return RuntimeEnabledFeatures::mediaSourceEnabled(); } void WebRuntimeFeatures::enableMediaStream(bool enable) { RuntimeEnabledFeatures::setMediaStreamEnabled(enable); } bool WebRuntimeFeatures::isMediaStreamEnabled() { return RuntimeEnabledFeatures::mediaStreamEnabled(); } void WebRuntimeFeatures::enableNotifications(bool enable) { RuntimeEnabledFeatures::setNotificationsEnabled(enable); } bool WebRuntimeFeatures::isNotificationsEnabled() { return RuntimeEnabledFeatures::notificationsEnabled(); } void WebRuntimeFeatures::enablePagePopup(bool enable) { RuntimeEnabledFeatures::setPagePopupEnabled(enable); } bool WebRuntimeFeatures::isPagePopupEnabled() { return RuntimeEnabledFeatures::pagePopupEnabled(); } void WebRuntimeFeatures::enablePeerConnection(bool enable) { RuntimeEnabledFeatures::setPeerConnectionEnabled(enable); } bool WebRuntimeFeatures::isPeerConnectionEnabled() { return RuntimeEnabledFeatures::peerConnectionEnabled(); } void WebRuntimeFeatures::enableRequestAutocomplete(bool enable) { RuntimeEnabledFeatures::setRequestAutocompleteEnabled(enable); } bool WebRuntimeFeatures::isRequestAutocompleteEnabled() { return RuntimeEnabledFeatures::requestAutocompleteEnabled(); } void WebRuntimeFeatures::enableScriptedSpeech(bool enable) { RuntimeEnabledFeatures::setScriptedSpeechEnabled(enable); } bool WebRuntimeFeatures::isScriptedSpeechEnabled() { return RuntimeEnabledFeatures::scriptedSpeechEnabled(); } void WebRuntimeFeatures::enableServiceWorker(bool enable) { RuntimeEnabledFeatures::setServiceWorkerEnabled(enable); } bool WebRuntimeFeatures::isServiceWorkerEnabled() { return RuntimeEnabledFeatures::serviceWorkerEnabled(); } void WebRuntimeFeatures::enableSessionStorage(bool enable) { RuntimeEnabledFeatures::setSessionStorageEnabled(enable); } bool WebRuntimeFeatures::isSessionStorageEnabled() { return RuntimeEnabledFeatures::sessionStorageEnabled(); } void WebRuntimeFeatures::enableSpeechInput(bool enable) { RuntimeEnabledFeatures::setSpeechInputEnabled(enable); } bool WebRuntimeFeatures::isSpeechInputEnabled() { return RuntimeEnabledFeatures::speechInputEnabled(); } void WebRuntimeFeatures::enableSpeechSynthesis(bool enable) { RuntimeEnabledFeatures::setSpeechSynthesisEnabled(enable); } bool WebRuntimeFeatures::isSpeechSynthesisEnabled() { return RuntimeEnabledFeatures::speechSynthesisEnabled(); } void WebRuntimeFeatures::enableTouch(bool enable) { RuntimeEnabledFeatures::setTouchEnabled(enable); } bool WebRuntimeFeatures::isTouchEnabled() { return RuntimeEnabledFeatures::touchEnabled(); } void WebRuntimeFeatures::enableWebAnimationsCSS(bool enable) { RuntimeEnabledFeatures::setWebAnimationsCSSEnabled(enable); } void WebRuntimeFeatures::enableWebAnimationsSVG(bool enable) { RuntimeEnabledFeatures::setWebAnimationsSVGEnabled(enable); } void WebRuntimeFeatures::enableWebAudio(bool enable) { RuntimeEnabledFeatures::setWebAudioEnabled(enable); } bool WebRuntimeFeatures::isWebAudioEnabled() { return RuntimeEnabledFeatures::webAudioEnabled(); } void WebRuntimeFeatures::enableWebGLDraftExtensions(bool enable) { RuntimeEnabledFeatures::setWebGLDraftExtensionsEnabled(enable); } bool WebRuntimeFeatures::isWebGLDraftExtensionsEnabled() { return RuntimeEnabledFeatures::webGLDraftExtensionsEnabled(); } void WebRuntimeFeatures::enableWebMIDI(bool enable) { return RuntimeEnabledFeatures::setWebMIDIEnabled(enable); } bool WebRuntimeFeatures::isWebMIDIEnabled() { return RuntimeEnabledFeatures::webMIDIEnabled(); } void WebRuntimeFeatures::enableDataListElement(bool enable) { RuntimeEnabledFeatures::setDataListElementEnabled(enable); } bool WebRuntimeFeatures::isDataListElementEnabled() { return RuntimeEnabledFeatures::dataListElementEnabled(); } void WebRuntimeFeatures::enableHTMLImports(bool enable) { RuntimeEnabledFeatures::setHTMLImportsEnabled(enable); } bool WebRuntimeFeatures::isHTMLImportsEnabled() { return RuntimeEnabledFeatures::htmlImportsEnabled(); } void WebRuntimeFeatures::enableXSLT(bool enable) { RuntimeEnabledFeatures::setXSLTEnabled(enable); } void WebRuntimeFeatures::enableEmbedderCustomElements(bool enable) { RuntimeEnabledFeatures::setEmbedderCustomElementsEnabled(enable); } void WebRuntimeFeatures::enableOverlayScrollbars(bool enable) { RuntimeEnabledFeatures::setOverlayScrollbarsEnabled(enable); } void WebRuntimeFeatures::enableInputModeAttribute(bool enable) { RuntimeEnabledFeatures::setInputModeAttributeEnabled(enable); } void WebRuntimeFeatures::enableOverlayFullscreenVideo(bool enable) { RuntimeEnabledFeatures::setOverlayFullscreenVideoEnabled(enable); } void WebRuntimeFeatures::enableSharedWorker(bool enable) { RuntimeEnabledFeatures::setSharedWorkerEnabled(enable); } void WebRuntimeFeatures::enableRepaintAfterLayout(bool enable) { RuntimeEnabledFeatures::setRepaintAfterLayoutEnabled(enable); } } // namespace blink <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <string> #include "plugin.hxx" #include "compat.hxx" #include "clang/AST/CXXInheritance.h" // Final goal: Checker for VCL widget references. Makes sure that VCL Window subclasses are properly referenced counted and dispose()'ed. // // But at the moment it just finds subclasses of Window which are not heap-allocated // // TODO do I need to check for local and static variables, too ? // TODO when we have a dispose() method, verify that the dispose() methods releases all of the Window references // TODO when we have a dispose() method, verify that it calls the super-class dispose() method at some point. namespace { class VCLWidgets: public RecursiveASTVisitor<VCLWidgets>, public loplugin::Plugin { public: explicit VCLWidgets(InstantiationData const & data): Plugin(data) {} virtual void run() override { TraverseDecl(compiler.getASTContext().getTranslationUnitDecl()); } bool VisitCXXRecordDecl(const CXXRecordDecl * decl); bool VisitFieldDecl(const FieldDecl * decl); bool VisitParmVarDecl(ParmVarDecl const * decl); bool VisitFunctionDecl( const FunctionDecl* var ); private: bool isDisposeCallingSuperclassDispose(const CXXMethodDecl* pMethodDecl); }; bool BaseCheckNotWindowSubclass(const CXXRecordDecl *BaseDefinition, void *) { if (BaseDefinition->getQualifiedNameAsString().compare("vcl::Window") == 0) { return false; } return true; } bool isDerivedFromWindow(const CXXRecordDecl *decl) { if (!decl->hasDefinition()) return false; if (decl->getQualifiedNameAsString().compare("vcl::Window") == 0) return true; if (// not sure what hasAnyDependentBases() does, // but it avoids classes we don't want, e.g. WeakAggComponentImplHelper1 !decl->hasAnyDependentBases() && !decl->forallBases(BaseCheckNotWindowSubclass, nullptr, true)) { return true; } return false; } bool isPointerToWindowSubclass(const QualType& pType) { if (!pType->isPointerType()) return false; QualType pointeeType = pType->getPointeeType(); const RecordType *recordType = pointeeType->getAs<RecordType>(); if (recordType == nullptr) { return false; } const CXXRecordDecl *recordDecl = dyn_cast<CXXRecordDecl>(recordType->getDecl()); if (recordDecl == nullptr) { return false; } return isDerivedFromWindow(recordDecl); } bool VCLWidgets::VisitCXXRecordDecl(const CXXRecordDecl * recordDecl) { if (ignoreLocation(recordDecl)) { return true; } if (!recordDecl->isCompleteDefinition()) return true; // check if this class is derived from Window if (!isDerivedFromWindow(recordDecl)) { return true; } if (!recordDecl->hasUserDeclaredDestructor()) { return true; } bool foundDispose = false; for(auto methodDecl : recordDecl->methods()) { if (methodDecl->isInstance() && methodDecl->param_size()==0 && methodDecl->getNameAsString() == "dispose") { foundDispose = true; break; } } if (!foundDispose) { report( DiagnosticsEngine::Warning, "vcl::Window subclass with destructor should declare a dispose() method.", recordDecl->getLocation()) << recordDecl->getSourceRange(); } return true; } bool VCLWidgets::VisitFieldDecl(const FieldDecl * fieldDecl) { if (ignoreLocation(fieldDecl)) { return true; } if (fieldDecl->isBitField()) { return true; } if (isPointerToWindowSubclass(fieldDecl->getType())) { /* report( DiagnosticsEngine::Remark, "vcl::Window subclass declared as a pointer field, should be wrapped in VclPtr.", fieldDecl->getLocation()) << fieldDecl->getSourceRange(); return true;*/ } const RecordType *recordType = fieldDecl->getType()->getAs<RecordType>(); if (recordType == nullptr) { return true; } const CXXRecordDecl *recordDecl = dyn_cast<CXXRecordDecl>(recordType->getDecl()); if (recordDecl == nullptr) { return true; } // check if this field is derived from Window if (!isDerivedFromWindow(recordDecl)) { return true; } report( DiagnosticsEngine::Warning, "vcl::Window subclass allocated as a class member, should be allocated via VclPtr.", fieldDecl->getLocation()) << fieldDecl->getSourceRange(); return true; } bool VCLWidgets::VisitParmVarDecl(ParmVarDecl const * pvDecl) { if (ignoreLocation(pvDecl)) { return true; } // ignore the stuff in the VclPtr template class const CXXMethodDecl *pMethodDecl = dyn_cast<CXXMethodDecl>(pvDecl->getDeclContext()); if (pMethodDecl && pMethodDecl->getParent()->getQualifiedNameAsString().find("VclPtr") != std::string::npos) { return true; } if (pvDecl->getType().getAsString().find("VclPtr") != std::string::npos) { report( DiagnosticsEngine::Warning, "vcl::Window subclass passed as a VclPtr parameter, should be passed as a raw pointer.", pvDecl->getLocation()) << pvDecl->getSourceRange(); } return true; } bool VCLWidgets::VisitFunctionDecl( const FunctionDecl* functionDecl ) { if (ignoreLocation(functionDecl)) { return true; } // ignore the stuff in the VclPtr template class const CXXMethodDecl *pMethodDecl = dyn_cast<CXXMethodDecl>(functionDecl); if (pMethodDecl && pMethodDecl->getParent()->getQualifiedNameAsString().find("VclPtr") != std::string::npos) { return true; } if (pMethodDecl && pMethodDecl->getParent()->getQualifiedNameAsString().compare("vcl::Window") == 0) { return true; } QualType t1 { compat::getReturnType(*functionDecl) }; if (t1.getAsString().find("VclPtr") != std::string::npos) { report( DiagnosticsEngine::Warning, "VclPtr declared as a return type from a method/function, should be passed as a raw pointer.", functionDecl->getLocation()) << functionDecl->getSourceRange(); } if (functionDecl->hasBody() && pMethodDecl && isDerivedFromWindow(pMethodDecl->getParent())) { const CXXDestructorDecl *pDestructorDecl = dyn_cast<CXXDestructorDecl>(pMethodDecl); // check that the destructor for a vcl::Window subclass does nothing except call into the dispose() method if (pDestructorDecl) { const CompoundStmt *pCompoundStatement = dyn_cast<CompoundStmt>(functionDecl->getBody()); bool ok = false; if (pCompoundStatement && pCompoundStatement->size() == 1) { const CXXMemberCallExpr *pCallExpr = dyn_cast<CXXMemberCallExpr>(*pCompoundStatement->body_begin()); if (pCallExpr) { ok = true; } } if (!ok) { report( DiagnosticsEngine::Warning, "vcl::Window subclass should have nothing in it's destructor but a call to dispose().", functionDecl->getBody()->getLocStart()) << functionDecl->getBody()->getSourceRange(); } // check the last thing that the dispose() method does, is to call into the superclass dispose method } else if (pMethodDecl->getNameAsString() == "dispose") { if (!isDisposeCallingSuperclassDispose(pMethodDecl)) { report( DiagnosticsEngine::Warning, "vcl::Window subclass dispose() method MUST call it's superclass dispose() as the last thing it does.", functionDecl->getBody()->getLocStart()) << functionDecl->getBody()->getSourceRange(); } } } return true; } /** The AST looks like: `-CXXMemberCallExpr 0xb06d8b0 'void' `-MemberExpr 0xb06d868 '<bound member function type>' ->dispose 0x9d34880 `-ImplicitCastExpr 0xb06d8d8 'class SfxTabPage *' <UncheckedDerivedToBase (SfxTabPage)> `-CXXThisExpr 0xb06d850 'class SfxAcceleratorConfigPage *' this */ bool VCLWidgets::isDisposeCallingSuperclassDispose(const CXXMethodDecl* pMethodDecl) { const CompoundStmt *pCompoundStatement = dyn_cast<CompoundStmt>(pMethodDecl->getBody()); if (!pCompoundStatement) return false; // find the last statement const CXXMemberCallExpr *pCallExpr = dyn_cast<CXXMemberCallExpr>(*pCompoundStatement->body_rbegin()); if (!pCallExpr) return false; const MemberExpr *pMemberExpr = dyn_cast<MemberExpr>(pCallExpr->getCallee()); if (!pMemberExpr) return false; if (pMemberExpr->getMemberDecl()->getNameAsString() != "dispose") return false; const CXXMethodDecl *pDirectCallee = dyn_cast<CXXMethodDecl>(pCallExpr->getDirectCallee()); if (!pDirectCallee) return false; /* Not working yet. Partially because sometimes the superclass does not a dispose() method, so it gets passed up the chain. Need complex checking for that case. if (pDirectCallee->getParent()->getTypeForDecl() != (*pMethodDecl->getParent()->bases_begin()).getType().getTypePtr()) { report( DiagnosticsEngine::Warning, "dispose() method calling wrong baseclass, calling " + pDirectCallee->getParent()->getQualifiedNameAsString() + " should be calling " + (*pMethodDecl->getParent()->bases_begin()).getType().getAsString(), pCallExpr->getLocStart()) << pCallExpr->getSourceRange(); return false; }*/ return true; } loplugin::Plugin::Registration< VCLWidgets > X("vclwidgets"); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>loplugin: vclwidgets: make the dispose/destructor checking more robust<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <string> #include "plugin.hxx" #include "compat.hxx" #include "clang/AST/CXXInheritance.h" // Final goal: Checker for VCL widget references. Makes sure that VCL Window subclasses are properly referenced counted and dispose()'ed. // // But at the moment it just finds subclasses of Window which are not heap-allocated // // TODO do I need to check for local and static variables, too ? // TODO when we have a dispose() method, verify that the dispose() methods releases all of the Window references // TODO when we have a dispose() method, verify that it calls the super-class dispose() method at some point. namespace { class VCLWidgets: public RecursiveASTVisitor<VCLWidgets>, public loplugin::Plugin { public: explicit VCLWidgets(InstantiationData const & data): Plugin(data) {} virtual void run() override { TraverseDecl(compiler.getASTContext().getTranslationUnitDecl()); } bool VisitFieldDecl(const FieldDecl * decl); bool VisitParmVarDecl(ParmVarDecl const * decl); bool VisitFunctionDecl( const FunctionDecl* var ); bool VisitCXXDestructorDecl(const CXXDestructorDecl* pCXXDestructorDecl); private: bool isDisposeCallingSuperclassDispose(const CXXMethodDecl* pMethodDecl); }; bool BaseCheckNotWindowSubclass(const CXXRecordDecl *BaseDefinition, void *) { if (BaseDefinition->getQualifiedNameAsString().compare("vcl::Window") == 0) { return false; } return true; } bool isDerivedFromWindow(const CXXRecordDecl *decl) { if (!decl->hasDefinition()) return false; if (decl->getQualifiedNameAsString().compare("vcl::Window") == 0) return true; if (// not sure what hasAnyDependentBases() does, // but it avoids classes we don't want, e.g. WeakAggComponentImplHelper1 !decl->hasAnyDependentBases() && !decl->forallBases(BaseCheckNotWindowSubclass, nullptr, true)) { return true; } return false; } bool isPointerToWindowSubclass(const QualType& pType) { if (!pType->isPointerType()) return false; QualType pointeeType = pType->getPointeeType(); const RecordType *recordType = pointeeType->getAs<RecordType>(); if (recordType == nullptr) { return false; } const CXXRecordDecl *recordDecl = dyn_cast<CXXRecordDecl>(recordType->getDecl()); if (recordDecl == nullptr) { return false; } return isDerivedFromWindow(recordDecl); } bool VCLWidgets::VisitCXXDestructorDecl(const CXXDestructorDecl* pCXXDestructorDecl) { if (ignoreLocation(pCXXDestructorDecl)) { return true; } if (!pCXXDestructorDecl->hasBody()) { return true; } const CXXRecordDecl * pRecordDecl = pCXXDestructorDecl->getParent(); // check if this class is derived from Window if (!isDerivedFromWindow(pRecordDecl)) { return true; } bool foundVclPtrField = false; for(auto fieldDecl : pRecordDecl->fields()) { const RecordType *pFieldRecordType = fieldDecl->getType()->getAs<RecordType>(); if (pFieldRecordType) { const CXXRecordDecl *pFieldRecordDecl = dyn_cast<CXXRecordDecl>(pFieldRecordType->getDecl()); static const char sVclPtr[] = "VcllPtr"; if (pFieldRecordDecl->getQualifiedNameAsString().compare(0, strlen(sVclPtr), sVclPtr) == 0) { foundVclPtrField = true; break; } } } bool foundDispose = false; for(auto methodDecl : pRecordDecl->methods()) { if (methodDecl->isInstance() && methodDecl->param_size()==0 && methodDecl->getNameAsString() == "dispose") { foundDispose = true; break; } } const CompoundStmt *pCompoundStatement = dyn_cast<CompoundStmt>(pCXXDestructorDecl->getBody()); // having an empty body and no dispose() method is fine if (!foundVclPtrField && !foundDispose && pCompoundStatement->size() == 0) { return true; } if (foundVclPtrField && pCompoundStatement->size() == 0) { report( DiagnosticsEngine::Warning, "vcl::Window subclass with VclPtr field must call dispose() from it's destructor.", pCXXDestructorDecl->getBody()->getLocStart()) << pCXXDestructorDecl->getBody()->getSourceRange(); return true; } // check that the destructor for a vcl::Window subclass does nothing except call into the dispose() method bool ok = false; if (pCompoundStatement->size() == 1) { const CXXMemberCallExpr *pCallExpr = dyn_cast<CXXMemberCallExpr>(*pCompoundStatement->body_begin()); if (pCallExpr) { ok = true; } } if (!ok) { report( DiagnosticsEngine::Warning, "vcl::Window subclass should have nothing in it's destructor but a call to dispose().", pCXXDestructorDecl->getBody()->getLocStart()) << pCXXDestructorDecl->getBody()->getSourceRange() << pCXXDestructorDecl->getCanonicalDecl()->getSourceRange(); return true; } return true; } bool VCLWidgets::VisitFieldDecl(const FieldDecl * fieldDecl) { if (ignoreLocation(fieldDecl)) { return true; } if (fieldDecl->isBitField()) { return true; } if (isPointerToWindowSubclass(fieldDecl->getType())) { /* report( DiagnosticsEngine::Remark, "vcl::Window subclass declared as a pointer field, should be wrapped in VclPtr.", fieldDecl->getLocation()) << fieldDecl->getSourceRange(); return true;*/ } const RecordType *recordType = fieldDecl->getType()->getAs<RecordType>(); if (recordType == nullptr) { return true; } const CXXRecordDecl *recordDecl = dyn_cast<CXXRecordDecl>(recordType->getDecl()); if (recordDecl == nullptr) { return true; } // check if this field is derived from Window if (isDerivedFromWindow(recordDecl)) { report( DiagnosticsEngine::Warning, "vcl::Window subclass allocated as a class member, should be allocated via VclPtr.", fieldDecl->getLocation()) << fieldDecl->getSourceRange(); } // If this field is a VclPtr field, then the class MUST have a dispose method static const char sVclPtr[] = "VcllPtr"; if (recordDecl->getQualifiedNameAsString().compare(0, strlen(sVclPtr), sVclPtr) == 0) { bool foundDispose = false; for(auto methodDecl : recordDecl->methods()) { if (methodDecl->isInstance() && methodDecl->param_size()==0 && methodDecl->getNameAsString() == "dispose") { foundDispose = true; break; } } if (!foundDispose) { report( DiagnosticsEngine::Warning, "vcl::Window subclass with a VclPtr field MUST have a dispose() method.", recordDecl->getLocation()) << recordDecl->getSourceRange(); } } return true; } bool VCLWidgets::VisitParmVarDecl(ParmVarDecl const * pvDecl) { if (ignoreLocation(pvDecl)) { return true; } // ignore the stuff in the VclPtr template class const CXXMethodDecl *pMethodDecl = dyn_cast<CXXMethodDecl>(pvDecl->getDeclContext()); if (pMethodDecl && pMethodDecl->getParent()->getQualifiedNameAsString().find("VclPtr") != std::string::npos) { return true; } if (pvDecl->getType().getAsString().find("VclPtr") != std::string::npos) { report( DiagnosticsEngine::Warning, "vcl::Window subclass passed as a VclPtr parameter, should be passed as a raw pointer.", pvDecl->getLocation()) << pvDecl->getSourceRange(); } return true; } bool VCLWidgets::VisitFunctionDecl( const FunctionDecl* functionDecl ) { if (ignoreLocation(functionDecl)) { return true; } // ignore the stuff in the VclPtr template class const CXXMethodDecl *pMethodDecl = dyn_cast<CXXMethodDecl>(functionDecl); if (pMethodDecl && pMethodDecl->getParent()->getQualifiedNameAsString().find("VclPtr") != std::string::npos) { return true; } // ignore the vcl::Window::dispose() method if (pMethodDecl && pMethodDecl->getParent()->getQualifiedNameAsString().compare("vcl::Window") == 0) { return true; } QualType t1 { compat::getReturnType(*functionDecl) }; if (t1.getAsString().find("VclPtr") != std::string::npos) { report( DiagnosticsEngine::Warning, "VclPtr declared as a return type from a method/function, should be passed as a raw pointer.", functionDecl->getLocation()) << functionDecl->getSourceRange(); } if (functionDecl->hasBody() && pMethodDecl && isDerivedFromWindow(pMethodDecl->getParent())) { // check the last thing that the dispose() method does, is to call into the superclass dispose method if (pMethodDecl->getNameAsString() == "dispose") { if (!isDisposeCallingSuperclassDispose(pMethodDecl)) { report( DiagnosticsEngine::Warning, "vcl::Window subclass dispose() method MUST call it's superclass dispose() as the last thing it does", functionDecl->getBody()->getLocStart()) << functionDecl->getBody()->getSourceRange(); } } } return true; } /** The AST looks like: `-CXXMemberCallExpr 0xb06d8b0 'void' `-MemberExpr 0xb06d868 '<bound member function type>' ->dispose 0x9d34880 `-ImplicitCastExpr 0xb06d8d8 'class SfxTabPage *' <UncheckedDerivedToBase (SfxTabPage)> `-CXXThisExpr 0xb06d850 'class SfxAcceleratorConfigPage *' this */ bool VCLWidgets::isDisposeCallingSuperclassDispose(const CXXMethodDecl* pMethodDecl) { const CompoundStmt *pCompoundStatement = dyn_cast<CompoundStmt>(pMethodDecl->getBody()); if (!pCompoundStatement) return false; // find the last statement const CXXMemberCallExpr *pCallExpr = dyn_cast<CXXMemberCallExpr>(*pCompoundStatement->body_rbegin()); if (!pCallExpr) return false; const MemberExpr *pMemberExpr = dyn_cast<MemberExpr>(pCallExpr->getCallee()); if (!pMemberExpr) return false; if (pMemberExpr->getMemberDecl()->getNameAsString() != "dispose") return false; const CXXMethodDecl *pDirectCallee = dyn_cast<CXXMethodDecl>(pCallExpr->getDirectCallee()); if (!pDirectCallee) return false; /* Not working yet. Partially because sometimes the superclass does not a dispose() method, so it gets passed up the chain. Need complex checking for that case. if (pDirectCallee->getParent()->getTypeForDecl() != (*pMethodDecl->getParent()->bases_begin()).getType().getTypePtr()) { report( DiagnosticsEngine::Warning, "dispose() method calling wrong baseclass, calling " + pDirectCallee->getParent()->getQualifiedNameAsString() + " should be calling " + (*pMethodDecl->getParent()->bases_begin()).getType().getAsString(), pCallExpr->getLocStart()) << pCallExpr->getSourceRange(); return false; }*/ return true; } loplugin::Plugin::Registration< VCLWidgets > X("vclwidgets"); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: RefreshListener.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2003-03-19 17:52:05 $ * * 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 EXPRESS 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 DBA_CORE_REFRESHLISTENER_HXX #define DBA_CORE_REFRESHLISTENER_HXX #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif namespace com { namespace sun { namespace star { namespace container { class XNameAccess; } }}} //......................................................................... namespace dbaccess { //......................................................................... //===================================================================== //= IRefreshListener //===================================================================== class SAL_NO_VTABLE IRefreshListener { public: virtual void refresh(const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& _rToBeRefreshed) = 0; }; //......................................................................... } // namespace dbaccess //......................................................................... #endif // DBA_CORE_REFRESHLISTENER_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.2.434); FILE MERGED 2005/09/05 17:32:26 rt 1.2.434.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: RefreshListener.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 13:33:52 $ * * 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 DBA_CORE_REFRESHLISTENER_HXX #define DBA_CORE_REFRESHLISTENER_HXX #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif namespace com { namespace sun { namespace star { namespace container { class XNameAccess; } }}} //......................................................................... namespace dbaccess { //......................................................................... //===================================================================== //= IRefreshListener //===================================================================== class SAL_NO_VTABLE IRefreshListener { public: virtual void refresh(const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& _rToBeRefreshed) = 0; }; //......................................................................... } // namespace dbaccess //......................................................................... #endif // DBA_CORE_REFRESHLISTENER_HXX <|endoftext|>
<commit_before>/* * * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /* Microbenchmarks around CHTTP2 operations */ #include <grpc/support/log.h> #include <string.h> #include <sstream> extern "C" { #include "src/core/ext/transport/chttp2/transport/hpack_encoder.h" #include "src/core/ext/transport/chttp2/transport/hpack_parser.h" #include "src/core/lib/slice/slice_internal.h" #include "src/core/lib/transport/static_metadata.h" } #include "third_party/benchmark/include/benchmark/benchmark.h" static struct Init { Init() { grpc_init(); } ~Init() { grpc_shutdown(); } } g_init; //////////////////////////////////////////////////////////////////////////////// // HPACK encoder // static void BM_HpackEncoderInitDestroy(benchmark::State &state) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_chttp2_hpack_compressor c; while (state.KeepRunning()) { grpc_chttp2_hpack_compressor_init(&c); grpc_chttp2_hpack_compressor_destroy(&exec_ctx, &c); grpc_exec_ctx_flush(&exec_ctx); } grpc_exec_ctx_finish(&exec_ctx); } BENCHMARK(BM_HpackEncoderInitDestroy); template <class Fixture> static void BM_HpackEncoderEncodeHeader(benchmark::State &state) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_metadata_batch b; grpc_metadata_batch_init(&b); std::vector<grpc_mdelem> elems = Fixture::GetElems(&exec_ctx); std::vector<grpc_linked_mdelem> storage(elems.size()); for (size_t i = 0; i < elems.size(); i++) { GPR_ASSERT(GRPC_LOG_IF_ERROR( "addmd", grpc_metadata_batch_add_tail(&exec_ctx, &b, &storage[i], elems[i]))); } grpc_chttp2_hpack_compressor c; grpc_chttp2_hpack_compressor_init(&c); grpc_transport_one_way_stats stats; memset(&stats, 0, sizeof(stats)); grpc_slice_buffer outbuf; grpc_slice_buffer_init(&outbuf); while (state.KeepRunning()) { grpc_chttp2_encode_header(&exec_ctx, &c, (uint32_t)state.iterations(), &b, state.range(0), state.range(1), &stats, &outbuf); grpc_slice_buffer_reset_and_unref_internal(&exec_ctx, &outbuf); grpc_exec_ctx_flush(&exec_ctx); } grpc_metadata_batch_destroy(&exec_ctx, &b); grpc_chttp2_hpack_compressor_destroy(&exec_ctx, &c); grpc_exec_ctx_finish(&exec_ctx); std::ostringstream label; label << "framing_bytes/iter:" << (static_cast<double>(stats.framing_bytes) / static_cast<double>(state.iterations())) << " header_bytes/iter:" << (static_cast<double>(stats.header_bytes) / static_cast<double>(state.iterations())); state.SetLabel(label.str()); } namespace hpack_encoder_fixtures { class EmptyBatch { public: static std::vector<grpc_mdelem> GetElems(grpc_exec_ctx *exec_ctx) { return {}; } }; class SingleStaticElem { public: static std::vector<grpc_mdelem> GetElems(grpc_exec_ctx *exec_ctx) { return {GRPC_MDELEM_GRPC_ACCEPT_ENCODING_IDENTITY_COMMA_DEFLATE}; } }; class SingleInternedElem { public: static std::vector<grpc_mdelem> GetElems(grpc_exec_ctx *exec_ctx) { return {grpc_mdelem_from_slices( exec_ctx, grpc_slice_intern(grpc_slice_from_static_string("abc")), grpc_slice_intern(grpc_slice_from_static_string("def")))}; } }; class SingleInternedKeyElem { public: static std::vector<grpc_mdelem> GetElems(grpc_exec_ctx *exec_ctx) { return {grpc_mdelem_from_slices( exec_ctx, grpc_slice_intern(grpc_slice_from_static_string("abc")), grpc_slice_from_static_string("def"))}; } }; class SingleNonInternedElem { public: static std::vector<grpc_mdelem> GetElems(grpc_exec_ctx *exec_ctx) { return {grpc_mdelem_from_slices(exec_ctx, grpc_slice_from_static_string("abc"), grpc_slice_from_static_string("def"))}; } }; class RepresentativeClientInitialMetadata { public: static std::vector<grpc_mdelem> GetElems(grpc_exec_ctx *exec_ctx) { return { GRPC_MDELEM_SCHEME_HTTP, GRPC_MDELEM_METHOD_POST, grpc_mdelem_from_slices( exec_ctx, GRPC_MDSTR_PATH, grpc_slice_intern(grpc_slice_from_static_string("/foo/bar"))), grpc_mdelem_from_slices(exec_ctx, GRPC_MDSTR_AUTHORITY, grpc_slice_intern(grpc_slice_from_static_string( "foo.test.google.fr:1234"))), GRPC_MDELEM_GRPC_ACCEPT_ENCODING_IDENTITY_COMMA_DEFLATE_COMMA_GZIP, GRPC_MDELEM_TE_TRAILERS, GRPC_MDELEM_CONTENT_TYPE_APPLICATION_SLASH_GRPC, grpc_mdelem_from_slices( exec_ctx, GRPC_MDSTR_USER_AGENT, grpc_slice_intern(grpc_slice_from_static_string( "grpc-c/3.0.0-dev (linux; chttp2; green)")))}; } }; class RepresentativeServerInitialMetadata { public: static std::vector<grpc_mdelem> GetElems(grpc_exec_ctx *exec_ctx) { return {GRPC_MDELEM_STATUS_200, GRPC_MDELEM_CONTENT_TYPE_APPLICATION_SLASH_GRPC, GRPC_MDELEM_GRPC_ACCEPT_ENCODING_IDENTITY_COMMA_DEFLATE_COMMA_GZIP}; } }; class RepresentativeServerTrailingMetadata { public: static std::vector<grpc_mdelem> GetElems(grpc_exec_ctx *exec_ctx) { return {GRPC_MDELEM_GRPC_STATUS_0}; } }; BENCHMARK_TEMPLATE(BM_HpackEncoderEncodeHeader, EmptyBatch)->Args({0, 16384}); // test with eof (shouldn't affect anything) BENCHMARK_TEMPLATE(BM_HpackEncoderEncodeHeader, EmptyBatch)->Args({1, 16384}); BENCHMARK_TEMPLATE(BM_HpackEncoderEncodeHeader, SingleStaticElem) ->Args({0, 16384}); BENCHMARK_TEMPLATE(BM_HpackEncoderEncodeHeader, SingleInternedKeyElem) ->Args({0, 16384}); BENCHMARK_TEMPLATE(BM_HpackEncoderEncodeHeader, SingleInternedElem) ->Args({0, 16384}); BENCHMARK_TEMPLATE(BM_HpackEncoderEncodeHeader, SingleNonInternedElem) ->Args({0, 16384}); // test with a tiny frame size, to highlight continuation costs BENCHMARK_TEMPLATE(BM_HpackEncoderEncodeHeader, SingleNonInternedElem) ->Args({0, 1}); BENCHMARK_TEMPLATE(BM_HpackEncoderEncodeHeader, RepresentativeClientInitialMetadata) ->Args({0, 16384}); BENCHMARK_TEMPLATE(BM_HpackEncoderEncodeHeader, RepresentativeServerInitialMetadata) ->Args({0, 16384}); BENCHMARK_TEMPLATE(BM_HpackEncoderEncodeHeader, RepresentativeServerTrailingMetadata) ->Args({1, 16384}); } // namespace hpack_encoder_fixtures //////////////////////////////////////////////////////////////////////////////// // HPACK parser // static void BM_HpackParserInitDestroy(benchmark::State &state) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_chttp2_hpack_parser p; while (state.KeepRunning()) { grpc_chttp2_hpack_parser_init(&exec_ctx, &p); grpc_chttp2_hpack_parser_destroy(&exec_ctx, &p); grpc_exec_ctx_flush(&exec_ctx); } grpc_exec_ctx_finish(&exec_ctx); } BENCHMARK(BM_HpackParserInitDestroy); static void UnrefHeader(grpc_exec_ctx *exec_ctx, void *user_data, grpc_mdelem md) { GRPC_MDELEM_UNREF(exec_ctx, md); } template <class Fixture> static void BM_HpackParserParseHeader(benchmark::State &state) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; std::vector<grpc_slice> init_slices = Fixture::GetInitSlices(); std::vector<grpc_slice> benchmark_slices = Fixture::GetBenchmarkSlices(); grpc_chttp2_hpack_parser p; grpc_chttp2_hpack_parser_init(&exec_ctx, &p); p.on_header = UnrefHeader; p.on_header_user_data = nullptr; for (auto slice : init_slices) { grpc_chttp2_hpack_parser_parse(&exec_ctx, &p, slice); } while (state.KeepRunning()) { for (auto slice : benchmark_slices) { grpc_chttp2_hpack_parser_parse(&exec_ctx, &p, slice); } grpc_exec_ctx_flush(&exec_ctx); } grpc_chttp2_hpack_parser_destroy(&exec_ctx, &p); grpc_exec_ctx_finish(&exec_ctx); } namespace hpack_parser_fixtures { static grpc_slice MakeSlice(std::initializer_list<uint8_t> bytes) { grpc_slice s = grpc_slice_malloc(bytes.size()); uint8_t *p = GRPC_SLICE_START_PTR(s); for (auto b : bytes) { *p++ = b; } return s; } class EmptyBatch { public: static std::vector<grpc_slice> GetInitSlices() { return {}; } static std::vector<grpc_slice> GetBenchmarkSlices() { return {MakeSlice({})}; } }; class IndexedSingleStaticElem { public: static std::vector<grpc_slice> GetInitSlices() { return {MakeSlice( {0x40, 0x07, ':', 's', 't', 'a', 't', 'u', 's', 0x03, '2', '0', '0'})}; } static std::vector<grpc_slice> GetBenchmarkSlices() { return {MakeSlice({0xbf})}; } }; BENCHMARK_TEMPLATE(BM_HpackParserParseHeader, EmptyBatch); BENCHMARK_TEMPLATE(BM_HpackParserParseHeader, IndexedSingleStaticElem); } // namespace hpack_parser_fixtures BENCHMARK_MAIN(); <commit_msg>Basic parsing tests<commit_after>/* * * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /* Microbenchmarks around CHTTP2 operations */ #include <grpc/support/log.h> #include <string.h> #include <sstream> extern "C" { #include "src/core/ext/transport/chttp2/transport/hpack_encoder.h" #include "src/core/ext/transport/chttp2/transport/hpack_parser.h" #include "src/core/lib/slice/slice_internal.h" #include "src/core/lib/transport/static_metadata.h" } #include "third_party/benchmark/include/benchmark/benchmark.h" static struct Init { Init() { grpc_init(); } ~Init() { grpc_shutdown(); } } g_init; //////////////////////////////////////////////////////////////////////////////// // HPACK encoder // static void BM_HpackEncoderInitDestroy(benchmark::State &state) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_chttp2_hpack_compressor c; while (state.KeepRunning()) { grpc_chttp2_hpack_compressor_init(&c); grpc_chttp2_hpack_compressor_destroy(&exec_ctx, &c); grpc_exec_ctx_flush(&exec_ctx); } grpc_exec_ctx_finish(&exec_ctx); } BENCHMARK(BM_HpackEncoderInitDestroy); template <class Fixture> static void BM_HpackEncoderEncodeHeader(benchmark::State &state) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_metadata_batch b; grpc_metadata_batch_init(&b); std::vector<grpc_mdelem> elems = Fixture::GetElems(&exec_ctx); std::vector<grpc_linked_mdelem> storage(elems.size()); for (size_t i = 0; i < elems.size(); i++) { GPR_ASSERT(GRPC_LOG_IF_ERROR( "addmd", grpc_metadata_batch_add_tail(&exec_ctx, &b, &storage[i], elems[i]))); } grpc_chttp2_hpack_compressor c; grpc_chttp2_hpack_compressor_init(&c); grpc_transport_one_way_stats stats; memset(&stats, 0, sizeof(stats)); grpc_slice_buffer outbuf; grpc_slice_buffer_init(&outbuf); while (state.KeepRunning()) { grpc_chttp2_encode_header(&exec_ctx, &c, (uint32_t)state.iterations(), &b, state.range(0), state.range(1), &stats, &outbuf); grpc_slice_buffer_reset_and_unref_internal(&exec_ctx, &outbuf); grpc_exec_ctx_flush(&exec_ctx); } grpc_metadata_batch_destroy(&exec_ctx, &b); grpc_chttp2_hpack_compressor_destroy(&exec_ctx, &c); grpc_exec_ctx_finish(&exec_ctx); std::ostringstream label; label << "framing_bytes/iter:" << (static_cast<double>(stats.framing_bytes) / static_cast<double>(state.iterations())) << " header_bytes/iter:" << (static_cast<double>(stats.header_bytes) / static_cast<double>(state.iterations())); state.SetLabel(label.str()); } namespace hpack_encoder_fixtures { class EmptyBatch { public: static std::vector<grpc_mdelem> GetElems(grpc_exec_ctx *exec_ctx) { return {}; } }; class SingleStaticElem { public: static std::vector<grpc_mdelem> GetElems(grpc_exec_ctx *exec_ctx) { return {GRPC_MDELEM_GRPC_ACCEPT_ENCODING_IDENTITY_COMMA_DEFLATE}; } }; class SingleInternedElem { public: static std::vector<grpc_mdelem> GetElems(grpc_exec_ctx *exec_ctx) { return {grpc_mdelem_from_slices( exec_ctx, grpc_slice_intern(grpc_slice_from_static_string("abc")), grpc_slice_intern(grpc_slice_from_static_string("def")))}; } }; class SingleInternedKeyElem { public: static std::vector<grpc_mdelem> GetElems(grpc_exec_ctx *exec_ctx) { return {grpc_mdelem_from_slices( exec_ctx, grpc_slice_intern(grpc_slice_from_static_string("abc")), grpc_slice_from_static_string("def"))}; } }; class SingleNonInternedElem { public: static std::vector<grpc_mdelem> GetElems(grpc_exec_ctx *exec_ctx) { return {grpc_mdelem_from_slices(exec_ctx, grpc_slice_from_static_string("abc"), grpc_slice_from_static_string("def"))}; } }; class RepresentativeClientInitialMetadata { public: static std::vector<grpc_mdelem> GetElems(grpc_exec_ctx *exec_ctx) { return { GRPC_MDELEM_SCHEME_HTTP, GRPC_MDELEM_METHOD_POST, grpc_mdelem_from_slices( exec_ctx, GRPC_MDSTR_PATH, grpc_slice_intern(grpc_slice_from_static_string("/foo/bar"))), grpc_mdelem_from_slices(exec_ctx, GRPC_MDSTR_AUTHORITY, grpc_slice_intern(grpc_slice_from_static_string( "foo.test.google.fr:1234"))), GRPC_MDELEM_GRPC_ACCEPT_ENCODING_IDENTITY_COMMA_DEFLATE_COMMA_GZIP, GRPC_MDELEM_TE_TRAILERS, GRPC_MDELEM_CONTENT_TYPE_APPLICATION_SLASH_GRPC, grpc_mdelem_from_slices( exec_ctx, GRPC_MDSTR_USER_AGENT, grpc_slice_intern(grpc_slice_from_static_string( "grpc-c/3.0.0-dev (linux; chttp2; green)")))}; } }; class RepresentativeServerInitialMetadata { public: static std::vector<grpc_mdelem> GetElems(grpc_exec_ctx *exec_ctx) { return {GRPC_MDELEM_STATUS_200, GRPC_MDELEM_CONTENT_TYPE_APPLICATION_SLASH_GRPC, GRPC_MDELEM_GRPC_ACCEPT_ENCODING_IDENTITY_COMMA_DEFLATE_COMMA_GZIP}; } }; class RepresentativeServerTrailingMetadata { public: static std::vector<grpc_mdelem> GetElems(grpc_exec_ctx *exec_ctx) { return {GRPC_MDELEM_GRPC_STATUS_0}; } }; BENCHMARK_TEMPLATE(BM_HpackEncoderEncodeHeader, EmptyBatch)->Args({0, 16384}); // test with eof (shouldn't affect anything) BENCHMARK_TEMPLATE(BM_HpackEncoderEncodeHeader, EmptyBatch)->Args({1, 16384}); BENCHMARK_TEMPLATE(BM_HpackEncoderEncodeHeader, SingleStaticElem) ->Args({0, 16384}); BENCHMARK_TEMPLATE(BM_HpackEncoderEncodeHeader, SingleInternedKeyElem) ->Args({0, 16384}); BENCHMARK_TEMPLATE(BM_HpackEncoderEncodeHeader, SingleInternedElem) ->Args({0, 16384}); BENCHMARK_TEMPLATE(BM_HpackEncoderEncodeHeader, SingleNonInternedElem) ->Args({0, 16384}); // test with a tiny frame size, to highlight continuation costs BENCHMARK_TEMPLATE(BM_HpackEncoderEncodeHeader, SingleNonInternedElem) ->Args({0, 1}); BENCHMARK_TEMPLATE(BM_HpackEncoderEncodeHeader, RepresentativeClientInitialMetadata) ->Args({0, 16384}); BENCHMARK_TEMPLATE(BM_HpackEncoderEncodeHeader, RepresentativeServerInitialMetadata) ->Args({0, 16384}); BENCHMARK_TEMPLATE(BM_HpackEncoderEncodeHeader, RepresentativeServerTrailingMetadata) ->Args({1, 16384}); } // namespace hpack_encoder_fixtures //////////////////////////////////////////////////////////////////////////////// // HPACK parser // static void BM_HpackParserInitDestroy(benchmark::State &state) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_chttp2_hpack_parser p; while (state.KeepRunning()) { grpc_chttp2_hpack_parser_init(&exec_ctx, &p); grpc_chttp2_hpack_parser_destroy(&exec_ctx, &p); grpc_exec_ctx_flush(&exec_ctx); } grpc_exec_ctx_finish(&exec_ctx); } BENCHMARK(BM_HpackParserInitDestroy); static void UnrefHeader(grpc_exec_ctx *exec_ctx, void *user_data, grpc_mdelem md) { GRPC_MDELEM_UNREF(exec_ctx, md); } template <class Fixture> static void BM_HpackParserParseHeader(benchmark::State &state) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; std::vector<grpc_slice> init_slices = Fixture::GetInitSlices(); std::vector<grpc_slice> benchmark_slices = Fixture::GetBenchmarkSlices(); grpc_chttp2_hpack_parser p; grpc_chttp2_hpack_parser_init(&exec_ctx, &p); p.on_header = UnrefHeader; p.on_header_user_data = nullptr; for (auto slice : init_slices) { grpc_chttp2_hpack_parser_parse(&exec_ctx, &p, slice); } while (state.KeepRunning()) { for (auto slice : benchmark_slices) { grpc_chttp2_hpack_parser_parse(&exec_ctx, &p, slice); } grpc_exec_ctx_flush(&exec_ctx); } grpc_chttp2_hpack_parser_destroy(&exec_ctx, &p); grpc_exec_ctx_finish(&exec_ctx); } namespace hpack_parser_fixtures { static grpc_slice MakeSlice(std::initializer_list<uint8_t> bytes) { grpc_slice s = grpc_slice_malloc(bytes.size()); uint8_t *p = GRPC_SLICE_START_PTR(s); for (auto b : bytes) { *p++ = b; } return s; } class EmptyBatch { public: static std::vector<grpc_slice> GetInitSlices() { return {}; } static std::vector<grpc_slice> GetBenchmarkSlices() { return {MakeSlice({})}; } }; class IndexedSingleStaticElem { public: static std::vector<grpc_slice> GetInitSlices() { return {MakeSlice( {0x40, 0x07, ':', 's', 't', 'a', 't', 'u', 's', 0x03, '2', '0', '0'})}; } static std::vector<grpc_slice> GetBenchmarkSlices() { return {MakeSlice({0xbe})}; } }; class IndexedSingleInternedElem { public: static std::vector<grpc_slice> GetInitSlices() { return {MakeSlice( {0x40, 0x03, 'a', 'b', 'c', 0x03, 'd', 'e', 'f'})}; } static std::vector<grpc_slice> GetBenchmarkSlices() { return {MakeSlice({0xbe})}; } }; BENCHMARK_TEMPLATE(BM_HpackParserParseHeader, EmptyBatch); BENCHMARK_TEMPLATE(BM_HpackParserParseHeader, IndexedSingleStaticElem); BENCHMARK_TEMPLATE(BM_HpackParserParseHeader, IndexedSingleInternedElem); } // namespace hpack_parser_fixtures BENCHMARK_MAIN(); <|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2012-2016 Gael Guennebaud <gael.guennebaud@inria.fr> // // 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/. #define EIGEN_RUNTIME_NO_MALLOC #include "main.h" #include <limits> #include <Eigen/Eigenvalues> #include <Eigen/LU> template<typename MatrixType> void generalized_eigensolver_real(const MatrixType& m) { typedef typename MatrixType::Index Index; /* this test covers the following files: GeneralizedEigenSolver.h */ Index rows = m.rows(); Index cols = m.cols(); typedef typename MatrixType::Scalar Scalar; typedef std::complex<Scalar> ComplexScalar; typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType; MatrixType a = MatrixType::Random(rows,cols); MatrixType b = MatrixType::Random(rows,cols); MatrixType a1 = MatrixType::Random(rows,cols); MatrixType b1 = MatrixType::Random(rows,cols); MatrixType spdA = a.adjoint() * a + a1.adjoint() * a1; MatrixType spdB = b.adjoint() * b + b1.adjoint() * b1; // lets compare to GeneralizedSelfAdjointEigenSolver { GeneralizedSelfAdjointEigenSolver<MatrixType> symmEig(spdA, spdB); GeneralizedEigenSolver<MatrixType> eig(spdA, spdB); VERIFY_IS_EQUAL(eig.eigenvalues().imag().cwiseAbs().maxCoeff(), 0); VectorType realEigenvalues = eig.eigenvalues().real(); std::sort(realEigenvalues.data(), realEigenvalues.data()+realEigenvalues.size()); VERIFY_IS_APPROX(realEigenvalues, symmEig.eigenvalues()); // check eigenvectors typename GeneralizedEigenSolver<MatrixType>::EigenvectorsType D = eig.eigenvalues().asDiagonal(); typename GeneralizedEigenSolver<MatrixType>::EigenvectorsType V = eig.eigenvectors(); VERIFY_IS_APPROX(spdA*V, spdB*V*D); } // non symmetric case: { GeneralizedEigenSolver<MatrixType> eig(rows); // TODO enable full-prealocation of required memory, this probably requires an in-place mode for HessenbergDecomposition //Eigen::internal::set_is_malloc_allowed(false); eig.compute(a,b); //Eigen::internal::set_is_malloc_allowed(true); for(Index k=0; k<cols; ++k) { Matrix<ComplexScalar,Dynamic,Dynamic> tmp = (eig.betas()(k)*a).template cast<ComplexScalar>() - eig.alphas()(k)*b; if(tmp.norm()>(std::numeric_limits<Scalar>::min)()) tmp /= tmp.norm(); VERIFY_IS_MUCH_SMALLER_THAN( std::abs(tmp.determinant()), Scalar(1) ); } // check eigenvectors typename GeneralizedEigenSolver<MatrixType>::EigenvectorsType D = eig.eigenvalues().asDiagonal(); typename GeneralizedEigenSolver<MatrixType>::EigenvectorsType V = eig.eigenvectors(); VERIFY_IS_APPROX(a*V, b*V*D); } // regression test for bug 1098 { GeneralizedSelfAdjointEigenSolver<MatrixType> eig1(a.adjoint() * a,b.adjoint() * b); eig1.compute(a.adjoint() * a,b.adjoint() * b); GeneralizedEigenSolver<MatrixType> eig2(a.adjoint() * a,b.adjoint() * b); eig2.compute(a.adjoint() * a,b.adjoint() * b); } } void test_eigensolver_generalized_real() { for(int i = 0; i < g_repeat; i++) { int s = 0; CALL_SUBTEST_1( generalized_eigensolver_real(Matrix4f()) ); s = internal::random<int>(1,EIGEN_TEST_MAX_SIZE/4); CALL_SUBTEST_2( generalized_eigensolver_real(MatrixXd(s,s)) ); // some trivial but implementation-wise special cases CALL_SUBTEST_2( generalized_eigensolver_real(MatrixXd(1,1)) ); CALL_SUBTEST_2( generalized_eigensolver_real(MatrixXd(2,2)) ); CALL_SUBTEST_3( generalized_eigensolver_real(Matrix<double,1,1>()) ); CALL_SUBTEST_4( generalized_eigensolver_real(Matrix2d()) ); TEST_SET_BUT_UNUSED_VARIABLE(s) } } <commit_msg>Fix unit test for 1x1 matrices<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2012-2016 Gael Guennebaud <gael.guennebaud@inria.fr> // // 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/. #define EIGEN_RUNTIME_NO_MALLOC #include "main.h" #include <limits> #include <Eigen/Eigenvalues> #include <Eigen/LU> template<typename MatrixType> void generalized_eigensolver_real(const MatrixType& m) { typedef typename MatrixType::Index Index; /* this test covers the following files: GeneralizedEigenSolver.h */ Index rows = m.rows(); Index cols = m.cols(); typedef typename MatrixType::Scalar Scalar; typedef std::complex<Scalar> ComplexScalar; typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType; MatrixType a = MatrixType::Random(rows,cols); MatrixType b = MatrixType::Random(rows,cols); MatrixType a1 = MatrixType::Random(rows,cols); MatrixType b1 = MatrixType::Random(rows,cols); MatrixType spdA = a.adjoint() * a + a1.adjoint() * a1; MatrixType spdB = b.adjoint() * b + b1.adjoint() * b1; // lets compare to GeneralizedSelfAdjointEigenSolver { GeneralizedSelfAdjointEigenSolver<MatrixType> symmEig(spdA, spdB); GeneralizedEigenSolver<MatrixType> eig(spdA, spdB); VERIFY_IS_EQUAL(eig.eigenvalues().imag().cwiseAbs().maxCoeff(), 0); VectorType realEigenvalues = eig.eigenvalues().real(); std::sort(realEigenvalues.data(), realEigenvalues.data()+realEigenvalues.size()); VERIFY_IS_APPROX(realEigenvalues, symmEig.eigenvalues()); // check eigenvectors typename GeneralizedEigenSolver<MatrixType>::EigenvectorsType D = eig.eigenvalues().asDiagonal(); typename GeneralizedEigenSolver<MatrixType>::EigenvectorsType V = eig.eigenvectors(); VERIFY_IS_APPROX(spdA*V, spdB*V*D); } // non symmetric case: { GeneralizedEigenSolver<MatrixType> eig(rows); // TODO enable full-prealocation of required memory, this probably requires an in-place mode for HessenbergDecomposition //Eigen::internal::set_is_malloc_allowed(false); eig.compute(a,b); //Eigen::internal::set_is_malloc_allowed(true); for(Index k=0; k<cols; ++k) { Matrix<ComplexScalar,Dynamic,Dynamic> tmp = (eig.betas()(k)*a).template cast<ComplexScalar>() - eig.alphas()(k)*b; if(tmp.size()>1 && tmp.norm()>(std::numeric_limits<Scalar>::min)()) tmp /= tmp.norm(); VERIFY_IS_MUCH_SMALLER_THAN( std::abs(tmp.determinant()), Scalar(1) ); } // check eigenvectors typename GeneralizedEigenSolver<MatrixType>::EigenvectorsType D = eig.eigenvalues().asDiagonal(); typename GeneralizedEigenSolver<MatrixType>::EigenvectorsType V = eig.eigenvectors(); VERIFY_IS_APPROX(a*V, b*V*D); } // regression test for bug 1098 { GeneralizedSelfAdjointEigenSolver<MatrixType> eig1(a.adjoint() * a,b.adjoint() * b); eig1.compute(a.adjoint() * a,b.adjoint() * b); GeneralizedEigenSolver<MatrixType> eig2(a.adjoint() * a,b.adjoint() * b); eig2.compute(a.adjoint() * a,b.adjoint() * b); } } void test_eigensolver_generalized_real() { for(int i = 0; i < g_repeat; i++) { int s = 0; CALL_SUBTEST_1( generalized_eigensolver_real(Matrix4f()) ); s = internal::random<int>(1,EIGEN_TEST_MAX_SIZE/4); CALL_SUBTEST_2( generalized_eigensolver_real(MatrixXd(s,s)) ); // some trivial but implementation-wise special cases CALL_SUBTEST_2( generalized_eigensolver_real(MatrixXd(1,1)) ); CALL_SUBTEST_2( generalized_eigensolver_real(MatrixXd(2,2)) ); CALL_SUBTEST_3( generalized_eigensolver_real(Matrix<double,1,1>()) ); CALL_SUBTEST_4( generalized_eigensolver_real(Matrix2d()) ); TEST_SET_BUT_UNUSED_VARIABLE(s) } } <|endoftext|>
<commit_before>#include <lcaes.h> #include <lcencode.h> #include <limecrypt.h> #include <sstream> #include <iostream> #include <fstream> class Print { public: Print() : os(std::cout) {} template<typename T> Print(const T& input) : os(std::cout) { os << input; } ~Print() { os << std::endl; } template<typename T> std::ostream& operator<<(const T& input) { return std::cout << input; } private: std::ostream& os; }; using namespace LimeCrypt; // AES Examples static std::string aes_encrypt_string(const std::string& message, const std::string& passphrase) { std::stringstream in(message), out; Print("Original Message (") << message.size() << " bytes): " << message; AES::encrypt(passphrase, in, out); Print("Encrypted Message - Hex format (") << out.str().size() << " bytes): " << Hex::encode(out.str()); return out.str(); } static std::string aes_decrypt_string(const std::string& encrypted, const std::string& passphrase) { std::stringstream in(encrypted), out; AES::decrypt(passphrase, in, out); Print("Decrypted Message (") << out.str().size() << " bytes): " << out.str(); return out.str(); } static std::string aes_encrypt_file(const std::string& filename, const std::string& passphrase) { // For this example we will first create a file Print("Writing file with secret content: ") << filename; std::ofstream of(filename.c_str()); of << "This is a secret file content. Nobody should see it." << std::endl; std::string encrypted_filename(filename + ".enc"); Print("Encrypt '") << filename << "' to '" << encrypted_filename << "'"; AES::encryptFile(passphrase, filename, encrypted_filename); return encrypted_filename; } static void aes_decrypt_file(const std::string& filename, const std::string& passphrase) { Print("Decrypt '") << filename << "' to '" << filename + ".decrypted" << "'"; AES::decryptFile(passphrase, filename, filename + ".decrypted"); } int main(int argc, char** argv) { errorHandling(STDERR_OUT); const std::string message("This is a totally secret message. No one should see it."); const std::string passphrase("t0t@lly_sEcure-Pa55W0rD_;)"); Print("--- AES String Encryption/Decryption Example ---"); std::string encrypted = aes_encrypt_string(message, passphrase); std::string decrypted = aes_decrypt_string(encrypted, passphrase); Print("--- AES File Encryption/Decryption Example ---"); std::string encrypted_filename = aes_encrypt_file("SecretFile", passphrase); aes_decrypt_file(encrypted_filename, passphrase); return 0; } <commit_msg>Update some code comments.<commit_after>#include <lcaes.h> #include <lcencode.h> #include <limecrypt.h> #include <sstream> #include <iostream> #include <fstream> class Print { public: Print() : os(std::cout) {} template<typename T> Print(const T& input) : os(std::cout) { os << input; } ~Print() { os << std::endl; } template<typename T> std::ostream& operator<<(const T& input) { return std::cout << input; } private: std::ostream& os; }; using namespace LimeCrypt; // AES Examples static std::string aes_encrypt_string(const std::string& message, const std::string& passphrase) { std::stringstream in(message), out; Print("Original Message (") << message.size() << " bytes): " << message; AES::encrypt(passphrase, in, out); Print("Encrypted Message - Hex format (") << out.str().size() << " bytes): " << Hex::encode(out.str()); return out.str(); } static std::string aes_decrypt_string(const std::string& encrypted, const std::string& passphrase) { std::stringstream in(encrypted), out; AES::decrypt(passphrase, in, out); Print("Decrypted Message (") << out.str().size() << " bytes): " << out.str(); return out.str(); } static std::string aes_encrypt_file(const std::string& filename, const std::string& passphrase) { // For this example we will first create a file Print("Writing file with secret content: ") << filename; std::ofstream of(filename.c_str()); of << "This is a secret file content. Nobody should see it." << std::endl; std::string encrypted_filename(filename + ".enc"); Print("Encrypt '") << filename << "' to '" << encrypted_filename << "'"; AES::encryptFile(passphrase, filename, encrypted_filename); return encrypted_filename; } static void aes_decrypt_file(const std::string& filename, const std::string& passphrase) { Print("Decrypt '") << filename << "' to '" << filename + ".decrypted" << "'"; AES::decryptFile(passphrase, filename, filename + ".decrypted"); } int main(int argc, char** argv) { // The error handling of LimeCrypt can be configured globally: // BOOLEAN_RETURN : Methods only return true or false, this is the default. // STDERR_OUT : Methods return true or false and print a detailed error message to stderr. // THROW_EXCEPTION : Throw a LimeCrypt::Exception that contains a detailed error message. // For the examples we configure, the errors for boolean return value and stderr out errorHandling(STDERR_OUT); const std::string message("This is a totally secret message. No one should see it."); const std::string passphrase("t0t@lly_sEcure-Pa55W0rD_;)"); Print("--- AES String Encryption/Decryption Example ---"); std::string encrypted = aes_encrypt_string(message, passphrase); std::string decrypted = aes_decrypt_string(encrypted, passphrase); Print("--- AES File Encryption/Decryption Example ---"); std::string encrypted_filename = aes_encrypt_file("SecretFile", passphrase); aes_decrypt_file(encrypted_filename, passphrase); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2020, Pierre Moulon // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the copyright holder 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 <COPYRIGHT HOLDER> 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 "relpose_8pt.h" #include "PoseLib/misc/essential.h" #include <array> /** * Build a 9 x n matrix from bearing vector matches, where each row is equivalent to the * equation x'T*F*x = 0 for a single correspondence pair (x', x). * * Note that this does not resize the matrix A; it is expected to have the * appropriate size already (n x 9). */ void encode_epipolar_equation(const std::vector<Eigen::Vector3d> &x1, const std::vector<Eigen::Vector3d> &x2, Eigen::Matrix<double, Eigen::Dynamic, 9> *A) { assert(x1.size() == x2.size()); assert(A->cols() == 9); assert(A->rows() == x1.size()); for (size_t i = 0; i < x1.size(); ++i) { A->row(i) << x2[i].x() * x1[i].transpose(), x2[i].y() * x1[i].transpose(), x2[i].z() * x1[i].transpose(); } } void poselib::essential_matrix_8pt(const std::vector<Eigen::Vector3d> &x1, const std::vector<Eigen::Vector3d> &x2, Eigen::Matrix3d *essential_matrix) { assert(8 <= x1.size()); using MatX9 = Eigen::Matrix<double, Eigen::Dynamic, 9>; MatX9 epipolar_constraint(x1.size(), 9); encode_epipolar_equation(x1, x2, &epipolar_constraint); using RMat3 = Eigen::Matrix<double, 3, 3, Eigen::RowMajor>; Eigen::Matrix3d E; if (x1.size() == 8) { // In the case where we have exactly 8 correspondences, there is no need to compute the SVD Eigen::Matrix<double, 9, 9> Q = epipolar_constraint.transpose().householderQr().householderQ(); Eigen::Matrix<double, 9, 1> e = Q.col(8); E = Eigen::Map<const RMat3>(e.data()); } else { Eigen::SelfAdjointEigenSolver<Eigen::Matrix<double, 9, 9>> solver(epipolar_constraint.transpose() * epipolar_constraint); E = Eigen::Map<const RMat3>(solver.eigenvectors().leftCols<1>().data()); } // Find the closest essential matrix to E in frobenius norm // E = UD'VT Eigen::JacobiSVD<Eigen::Matrix3d> USV(E, Eigen::ComputeFullU | Eigen::ComputeFullV); Eigen::Vector3d d = USV.singularValues(); const double a = d[0]; const double b = d[1]; d << (a + b) / 2., (a + b) / 2., 0.0; E = USV.matrixU() * d.asDiagonal() * USV.matrixV().transpose(); (*essential_matrix) = E; } int poselib::relpose_8pt(const std::vector<Eigen::Vector3d> &x1, const std::vector<Eigen::Vector3d> &x2, CameraPoseVector *output) { Eigen::Matrix3d essential_matrix; essential_matrix_8pt(x1, x2, &essential_matrix); // Generate plausible relative motion from E output->clear(); poselib::motion_from_essential(essential_matrix, x1[0], x2[0], output); return output->size(); } <commit_msg>Fix Debug build (#39)<commit_after>// Copyright (c) 2020, Pierre Moulon // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the copyright holder 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 <COPYRIGHT HOLDER> 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 "relpose_8pt.h" #include "PoseLib/misc/essential.h" #include <array> /** * Build a 9 x n matrix from bearing vector matches, where each row is equivalent to the * equation x'T*F*x = 0 for a single correspondence pair (x', x). * * Note that this does not resize the matrix A; it is expected to have the * appropriate size already (n x 9). */ void encode_epipolar_equation(const std::vector<Eigen::Vector3d> &x1, const std::vector<Eigen::Vector3d> &x2, Eigen::Matrix<double, Eigen::Dynamic, 9> *A) { assert(x1.size() == x2.size()); assert(A->cols() == 9); assert(static_cast<size_t>(A->rows()) == x1.size()); for (size_t i = 0; i < x1.size(); ++i) { A->row(i) << x2[i].x() * x1[i].transpose(), x2[i].y() * x1[i].transpose(), x2[i].z() * x1[i].transpose(); } } void poselib::essential_matrix_8pt(const std::vector<Eigen::Vector3d> &x1, const std::vector<Eigen::Vector3d> &x2, Eigen::Matrix3d *essential_matrix) { assert(8 <= x1.size()); using MatX9 = Eigen::Matrix<double, Eigen::Dynamic, 9>; MatX9 epipolar_constraint(x1.size(), 9); encode_epipolar_equation(x1, x2, &epipolar_constraint); using RMat3 = Eigen::Matrix<double, 3, 3, Eigen::RowMajor>; Eigen::Matrix3d E; if (x1.size() == 8) { // In the case where we have exactly 8 correspondences, there is no need to compute the SVD Eigen::Matrix<double, 9, 9> Q = epipolar_constraint.transpose().householderQr().householderQ(); Eigen::Matrix<double, 9, 1> e = Q.col(8); E = Eigen::Map<const RMat3>(e.data()); } else { Eigen::SelfAdjointEigenSolver<Eigen::Matrix<double, 9, 9>> solver(epipolar_constraint.transpose() * epipolar_constraint); E = Eigen::Map<const RMat3>(solver.eigenvectors().leftCols<1>().data()); } // Find the closest essential matrix to E in frobenius norm // E = UD'VT Eigen::JacobiSVD<Eigen::Matrix3d> USV(E, Eigen::ComputeFullU | Eigen::ComputeFullV); Eigen::Vector3d d = USV.singularValues(); const double a = d[0]; const double b = d[1]; d << (a + b) / 2., (a + b) / 2., 0.0; E = USV.matrixU() * d.asDiagonal() * USV.matrixV().transpose(); (*essential_matrix) = E; } int poselib::relpose_8pt(const std::vector<Eigen::Vector3d> &x1, const std::vector<Eigen::Vector3d> &x2, CameraPoseVector *output) { Eigen::Matrix3d essential_matrix; essential_matrix_8pt(x1, x2, &essential_matrix); // Generate plausible relative motion from E output->clear(); poselib::motion_from_essential(essential_matrix, x1[0], x2[0], output); return output->size(); } <|endoftext|>
<commit_before>/* This file is part of the Vc project Copyright (C) 2009-2010 Matthias Kretz <kretz@kde.org> Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that the copyright notice and this permission notice and warranty disclaimer appear in supporting documentation, and that the name of the author not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. The author disclaim all warranties with regard to this software, including all implied warranties of merchantability and fitness. In no event shall the author be liable for any special, indirect or consequential damages or any damages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection with the use or performance of this software. */ #include <Vc/Vc> #include <Vc/IO> #include <iostream> #include <iomanip> template<typename T, unsigned int Size> class Matrix; template<typename T, unsigned int Size> std::ostream &operator<<(std::ostream &, const Matrix<T, Size> &); template<typename T, unsigned int Size> class Matrix { friend std::ostream &operator<< <>(std::ostream &, const Matrix<T, Size> &); private: typedef Vc::Vector<T> V; Vc::Memory<V, Size * Size> m_mem; public: Matrix &operator=(const T &val) { V vec(val); for (unsigned int i = 0; i < m_mem.vectorsCount(); ++i) { m_mem.vector(i) = vec; } return *this; } Matrix &operator+=(const Matrix &rhs) { for (unsigned int i = 0; i < m_mem.vectorsCount(); ++i) { V v1(m_mem.vector(i)); v1 += V(rhs.m_mem.vector(i)); m_mem.vector(i) = v1; } return *this; } }; template<typename T, unsigned int Size> std::ostream &operator<<(std::ostream &out, const Matrix<T, Size> &m) { for (unsigned int i = 0; i < Size; ++i) { std::cout << "[" << std::setw(6) << m.m_mem[i * Size]; for (unsigned int j = 1; j < Size; ++j) { std::cout << std::setw(6) << m.m_mem[i * Size + j]; } std::cout << " ]\n"; } return out; } int main() { Matrix<float, 15> m1; m1 = 1.f; Matrix<float, 15> m2; m2 = 2.f; m1 += m2; std::cout << m1 << std::endl; return 0; } <commit_msg>Matrix: rewrite the matrix example<commit_after>/* This file is part of the Vc project Copyright (C) 2009-2010 Matthias Kretz <kretz@kde.org> Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that the copyright notice and this permission notice and warranty disclaimer appear in supporting documentation, and that the name of the author not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. The author disclaim all warranties with regard to this software, including all implied warranties of merchantability and fitness. In no event shall the author be liable for any special, indirect or consequential damages or any damages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection with the use or performance of this software. */ #include <Vc/Vc> #include <Vc/IO> #include <iostream> #include <iomanip> #include "../tsc.h" static constexpr size_t UnrollOuterloop = 4; template <typename T, size_t N> class Matrix { using V = Vc::Vector<T>; // round up to the next multiple of V::size() static constexpr size_t NPadded = (N + V::size() - 1) / V::size() * V::size(); // the inner array stores one row of values and is padded using RowArray = std::array<T, NPadded>; // The outer array stores N rows and does not require further padding. It must be aligned // correctly for Vc::Aligned loads and stores, though. alignas(V::MemoryAlignment) std::array<RowArray, N> data; public: // returns a reference to the i-th row RowArray &operator[](size_t i) { return data[i]; } // const overload of the above const RowArray &operator[](size_t i) const { return data[i]; } }; // vectorized matrix multiplication template <typename T, size_t N> inline Matrix<T, N> operator*(const Matrix<T, N> &a, const Matrix<T, N> &b) { using V = Vc::Vector<T>; // resulting matrix c Matrix<T, N> c; // The row index (for a and c) is unrolled using the UnrollOuterloop stride. Therefore the last // rows may need special treatment if N is not a multiple of UnrollOuterloop. N0 is the number // of rows that can safely be iterated with a stride of UnrollOuterloop. constexpr size_t N0 = N / UnrollOuterloop * UnrollOuterloop; for (size_t i = 0; i < N0; i += UnrollOuterloop) { // The iteration over the column index of b and c uses a stride of V::size(). This enables // row-vector loads (from b) and stores (to c). The matrix storage is padded accordingly, // ensuring correct bounds and alignment. for (size_t j = 0; j < N; j += V::size()) { // This temporary variables are used to accumulate the results of the products producing // the new values for the c matrix. This variable is necessary because we need a V // object for data-parallel accumulation. Storing to c directly stores to scalar objects // and thus would drop the ability for data-parallel (SIMD) addition. V c_ij[UnrollOuterloop]; for (size_t n = 0; n < UnrollOuterloop; ++n) { c_ij[n] = a[i + n][0] * V(&b[0][j], Vc::Aligned); } for (size_t k = 1; k < N - 1; ++k) { for (size_t n = 0; n < UnrollOuterloop; ++n) { c_ij[n] += a[i + n][k] * V(&b[k][j], Vc::Aligned); } } for (size_t n = 0; n < UnrollOuterloop; ++n) { c_ij[n] += a[i + n][N - 1] * V(&b[N - 1][j], Vc::Aligned); c_ij[n].store(&c[i + n][j], Vc::Aligned); } } } // This final loop treats the remaining N - N0 rows. for (size_t j = 0; j < N; j += V::size()) { V c_ij[UnrollOuterloop]; for (size_t n = N0; n < N; ++n) { c_ij[n] = a[n][0] * V(&b[0][j], Vc::Aligned); } for (size_t k = 1; k < N - 1; ++k) { for (size_t n = N0; n < N; ++n) { c_ij[n] += a[n][k] * V(&b[k][j], Vc::Aligned); } } for (size_t n = N0; n < N; ++n) { c_ij[n] += a[n][N - 1] * V(&b[N - 1][j], Vc::Aligned); c_ij[n].store(&c[n][j], Vc::Aligned); } } return c; } // scalar vector multiplication template <typename T, size_t N> Matrix<T, N> scalar_mul(const Matrix<T, N> &a, const Matrix<T, N> &b) { Matrix<T, N> c; for (size_t i = 0; i < N; ++i) { for (size_t j = 0; j < N; ++j) { c[i][j] = a[i][0] * b[0][j]; for (size_t k = 1; k < N; ++k) { c[i][j] += a[i][k] * b[k][j]; } } } return c; } template<typename T, size_t N> std::ostream &operator<<(std::ostream &out, const Matrix<T, N> &m) { out.precision(3); auto &&w = std::setw(6); out << "⎡" << w << m[0][0]; for (size_t j = 1; j < N; ++j) { out << ", " << w << m[0][j]; } out << " ⎤\n"; for (size_t i = 1; i + 1 < N; ++i) { out << "⎢" << w << m[i][0]; for (size_t j = 1; j < N; ++j) { out << ", " << w << m[i][j]; } out << " ⎥\n"; } out << "⎣" << w << m[N - 1][0]; for (size_t j = 1; j < N; ++j) { out << ", " << w << m[N - 1][j]; } return out << " ⎦\n"; } int main() { static constexpr size_t N = 23; Matrix<float, N> A; Matrix<float, N> B ; for (size_t i = 0; i < N; ++i) { for (size_t j = 0; j < N; ++j) { A[i][j] = 0.01 * (i + j); B[i][j] = 0.01 * (N + i - j); } } { auto C = A * B; std::cout << A << "times\n" << B << "=\n" << C; auto CS = scalar_mul(A, B); std::cout << "scalar=\n" << CS; } TimeStampCounter tsc; for (int i = 0; i < 10; ++i) { tsc.start(); auto CS = scalar_mul(A, B); tsc.stop(); std::cout << tsc << " Cycles for " << N * N * (N + N - 1) << " FLOP => "; std::cout << double(N * N * (N + N - 1)) / tsc.cycles() << " FLOP/cycle (scalar)\n"; } for (int i = 0; i < 10; ++i) { tsc.start(); auto C = A * B; tsc.stop(); std::cout << tsc << " Cycles for " << N * N * (N + N - 1) << " FLOP => "; std::cout << double(N * N * (N + N - 1)) / tsc.cycles() << " FLOP/cycle (vector)\n"; } return 0; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "player.h" #include <QtGui> int main(int argc, char *argv[]) { QApplication app(argc, argv); #ifdef Q_OS_SYMBIAN QMainWindow window; Player *player = new Player(&window); window.setCentralWidget(player); window.showMaximized(); #else Player player; player.show(); #endif return app.exec(); }; <commit_msg>Symbian: Workaround fix for MOBILITY-843. This can be removed when real problem in Qt side http://bugreports.qt.nokia.com/browse/QTBUG-8697 is fixed<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "player.h" #include <QtGui> int main(int argc, char *argv[]) { QApplication app(argc, argv); #ifdef Q_OS_SYMBIAN QMainWindow window; window.setContentsMargins(10, 10, 10, 10); // workaround for issue where UI is not drawn in older SDKs // this line can be removed when bug QTBUG-8697 is fixed Player *player = new Player(&window); window.setCentralWidget(player); window.showMaximized(); #else Player player; player.show(); #endif return app.exec(); }; <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <gmock/gmock.h> #include <game/meta/boardmetaclass.hpp> #include <game/meta/terrainmetaclass.hpp> #include <engine/terrain.hpp> #include <game/meta/deploymentzonemetaclass.hpp> #include <game/deploymentzone.hpp> #include <game/meta/coordinatemetaclass.hpp> #include "game/states/skirmishpreparationstate.hpp" #include "game/states/deploystate.hpp" #include "game/skirmish/mapmanager.hpp" #include "engine/board.hpp" #include "game/deploymentzone.hpp" using ::testing::_; using ::testing::Return; using ::testing::ElementsAreArray; using ::testing::ElementsAre; class MapManagerMock : public qrw::MapManager { public: MapManagerMock(qrw::MetaManager& metaManager) : MapManager(metaManager) {} MOCK_METHOD3(loadMap, qrw::MapManager::LoadErrors(const std::string& mapName, qrw::Board*& board, std::vector<qrw::DeploymentZone*>& deploymentZones)); MOCK_CONST_METHOD0(getMapList, std::vector<std::string>()); }; ACTION_P2(LoadMapStub, board, deploymentZones) { arg1 = board; arg2 = deploymentZones; return qrw::MapManager::LoadErrors::SUCCESS; } TEST(DeployState_Init, Then_game_objects_are_added_to_scene) { // Arrange qrw::MetaManager metaManager; metaManager.registerMetaClass<qrw::BoardMetaClass>(qrw::Board::typeName); metaManager.registerMetaClass<qrw::TerrainMetaClass>(qrw::Terrain::typeName); metaManager.registerMetaClass<qrw::DeploymentZoneMetaClass>(qrw::DeploymentZone::typeName); metaManager.registerMetaClass<qrw::CoordinateMetaClass>(qrw::Coordinates::typeName); auto board = new qrw::Board(); auto terrain1 = new qrw::Terrain(); auto terrain2 = new qrw::Terrain(); board->setTerrain({0, 0}, terrain1); board->setTerrain({1, 0}, terrain2); auto deploymentZone1 = new qrw::DeploymentZone(); auto deploymentZone2 = new qrw::DeploymentZone(); std::vector<qrw::DeploymentZone*> deploymentZones { deploymentZone1, deploymentZone2 }; // Assert Mocks MapManagerMock mapManager(metaManager); EXPECT_CALL(mapManager, getMapList()) .WillOnce(Return(std::vector<std::string>{"HelloMap"})); EXPECT_CALL(mapManager, loadMap("HelloMap", _, _)) .WillOnce(LoadMapStub(board, deploymentZones)); sf::RenderWindow renderWindow; auto deployState = new qrw::DeployState(&renderWindow, mapManager); qrw::SkirmishPreparationState skirmishPreparationState(&renderWindow, mapManager); // Act deployState->init(&skirmishPreparationState); // Assert EXPECT_EQ(qrw::g_scene.findSingleGameObject<qrw::Board>(), board); EXPECT_THAT(qrw::g_scene.findGameObjects<qrw::DeploymentZone>(), ElementsAreArray(deploymentZones.data(), 2)); EXPECT_THAT(qrw::g_scene.findGameObjects<qrw::Terrain>(), ElementsAre(terrain1, terrain2)); // Cleanup delete deployState; qrw::g_scene.reset(); qrw::g_scene.update(0); }<commit_msg>Fix flaky test<commit_after>#include <gtest/gtest.h> #include <gmock/gmock.h> #include <game/meta/boardmetaclass.hpp> #include <game/meta/terrainmetaclass.hpp> #include <engine/terrain.hpp> #include <game/meta/deploymentzonemetaclass.hpp> #include <game/deploymentzone.hpp> #include <game/meta/coordinatemetaclass.hpp> #include "game/states/skirmishpreparationstate.hpp" #include "game/states/deploystate.hpp" #include "game/skirmish/mapmanager.hpp" #include "engine/board.hpp" #include "game/deploymentzone.hpp" using ::testing::_; using ::testing::Return; using ::testing::ElementsAreArray; using ::testing::Contains; class MapManagerMock : public qrw::MapManager { public: MapManagerMock(qrw::MetaManager& metaManager) : MapManager(metaManager) {} MOCK_METHOD3(loadMap, qrw::MapManager::LoadErrors(const std::string& mapName, qrw::Board*& board, std::vector<qrw::DeploymentZone*>& deploymentZones)); MOCK_CONST_METHOD0(getMapList, std::vector<std::string>()); }; ACTION_P2(LoadMapStub, board, deploymentZones) { arg1 = board; arg2 = deploymentZones; return qrw::MapManager::LoadErrors::SUCCESS; } TEST(DeployState_Init, Then_game_objects_are_added_to_scene) { // Arrange qrw::MetaManager metaManager; metaManager.registerMetaClass<qrw::BoardMetaClass>(qrw::Board::typeName); metaManager.registerMetaClass<qrw::TerrainMetaClass>(qrw::Terrain::typeName); metaManager.registerMetaClass<qrw::DeploymentZoneMetaClass>(qrw::DeploymentZone::typeName); metaManager.registerMetaClass<qrw::CoordinateMetaClass>(qrw::Coordinates::typeName); auto board = new qrw::Board(); auto terrain1 = new qrw::Terrain(); auto terrain2 = new qrw::Terrain(); board->setTerrain({0, 0}, terrain1); board->setTerrain({1, 0}, terrain2); auto deploymentZone1 = new qrw::DeploymentZone(); auto deploymentZone2 = new qrw::DeploymentZone(); std::vector<qrw::DeploymentZone*> deploymentZones { deploymentZone1, deploymentZone2 }; // Assert Mocks MapManagerMock mapManager(metaManager); EXPECT_CALL(mapManager, getMapList()) .WillOnce(Return(std::vector<std::string>{"HelloMap"})); EXPECT_CALL(mapManager, loadMap("HelloMap", _, _)) .WillOnce(LoadMapStub(board, deploymentZones)); sf::RenderWindow renderWindow; auto deployState = new qrw::DeployState(&renderWindow, mapManager); qrw::SkirmishPreparationState skirmishPreparationState(&renderWindow, mapManager); // Act deployState->init(&skirmishPreparationState); // Assert EXPECT_EQ(qrw::g_scene.findSingleGameObject<qrw::Board>(), board); EXPECT_THAT(qrw::g_scene.findGameObjects<qrw::DeploymentZone>(), ElementsAreArray(deploymentZones.data(), 2)); std::set<qrw::GameObject*>& terrainsInScene = qrw::g_scene.findGameObjects<qrw::Terrain>(); EXPECT_EQ(terrainsInScene.size(), 2); EXPECT_THAT(terrainsInScene, Contains(terrain1)); EXPECT_THAT(terrainsInScene, Contains(terrain2)); // Cleanup delete deployState; qrw::g_scene.reset(); qrw::g_scene.update(0); }<|endoftext|>
<commit_before>/* * sdppublishmsg.cpp * * Created on: Jul 25, 2014 * Author: dtvlab */ #include "sdppublishmsg.h" #include<Time.h> #include <avr/pgmspace.h> using namespace sdp::message; prog_char ValueJSON::LABEL_COMPONENTS[] PROGMEM = {"components"}; PROGMEM const char* ValueJSON::LABEL[] = // change "string_table" name to suit { LABEL_COMPONENTS }; prog_char PublishJSON::LABEL_VALUES[] PROGMEM = {"values"}; prog_char PublishJSON::LABEL_STREAM[] PROGMEM = {"stream"}; prog_char PublishJSON::LABEL_SENSOR[] PROGMEM = {"sensor"}; PROGMEM const char* PublishJSON::LABEL[] = // change "string_table" name to suit { LABEL_VALUES, LABEL_STREAM, LABEL_SENSOR }; prog_char SecureJSON::LABEL_MESSAGE[] PROGMEM = {"message"}; prog_char SecureJSON::LABEL_DIGEST[] PROGMEM = {"digest"}; PROGMEM const char* SecureJSON::LABEL[] = // change "string_table" name to suit { LABEL_MESSAGE, LABEL_DIGEST, }; <commit_msg>Arduino: secure protocol, changed labels of the JSON<commit_after>/* * sdppublishmsg.cpp * * Created on: Jul 25, 2014 * Author: dtvlab */ #include "sdppublishmsg.h" #include<Time.h> #include <avr/pgmspace.h> using namespace sdp::message; prog_char ValueJSON::LABEL_COMPONENTS[] PROGMEM = {"components"}; PROGMEM const char* ValueJSON::LABEL[] = // change "string_table" name to suit { LABEL_COMPONENTS }; prog_char PublishJSON::LABEL_VALUES[] PROGMEM = {"values"}; prog_char PublishJSON::LABEL_STREAM[] PROGMEM = {"stream"}; prog_char PublishJSON::LABEL_SENSOR[] PROGMEM = {"sensor"}; PROGMEM const char* PublishJSON::LABEL[] = // change "string_table" name to suit { LABEL_VALUES, LABEL_STREAM, LABEL_SENSOR }; prog_char SecureJSON::LABEL_MESSAGE[] PROGMEM = {"object"}; prog_char SecureJSON::LABEL_DIGEST[] PROGMEM = {"signature"}; PROGMEM const char* SecureJSON::LABEL[] = // change "string_table" name to suit { LABEL_MESSAGE, LABEL_DIGEST, }; <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** 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 The Qt Company Ltd 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." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ /* File is modified to include Ring Keywords and Ignore the Case Updated by : Mahmoud Fayed <msfclipper@yahoo.com> Date : 2016.09.14 */ #include "highlighter.h" Highlighter::Highlighter(QTextDocument *parent) : QSyntaxHighlighter(parent) { setColors(Qt::darkBlue,Qt::darkMagenta,Qt::red,Qt::darkGreen,Qt::blue); } void Highlighter::highlightBlock(const QString &text) { foreach (const HighlightingRule &rule, highlightingRules) { QRegExp expression(rule.pattern); int index = expression.indexIn(text); while (index >= 0) { int length = expression.matchedLength(); setFormat(index, length, rule.format); index = expression.indexIn(text, index + length); } } setCurrentBlockState(0); int startIndex = 0; if (previousBlockState() != 1) startIndex = commentStartExpression.indexIn(text); while (startIndex >= 0) { int endIndex = commentEndExpression.indexIn(text, startIndex); int commentLength; if (endIndex == -1) { setCurrentBlockState(1); commentLength = text.length() - startIndex; } else { commentLength = endIndex - startIndex + commentEndExpression.matchedLength(); } setFormat(startIndex, commentLength, multiLineCommentFormat); startIndex = commentStartExpression.indexIn(text, startIndex + commentLength); } } void Highlighter::setColors(QColor c1,QColor c2,QColor c3,QColor c4,QColor c5) { HighlightingRule rule; highlightingRules.remove(0,highlightingRules.count()); keywordFormat.setForeground(c1); if (this->nKeywordsBold) keywordFormat.setFontWeight(QFont::Bold); QStringList keywordPatterns; keywordPatterns << "\\bagain\\b" << "\\band\\b" << "\\bbut\\b" << "\\bbye\\b" << "\\bcall\\b" << "\\bcase\\b" << "\\bcatch\\b" << "\\bclass\\b" << "\\bdef\\b" << "\\bdo\\b" << "\\bdone\\b" << "\\belse\\b" << "\\belseif\\b" << "\\bend\\b" << "\\bexit\\b" << "\\bfor\\b" << "\\bfrom\\b" << "\\bfunc\\b" << "\\bget\\b" << "\\bgive\\b" << "\\bif\\b" << "\\bimport\\b" << "\\bin\\b" << "\\bload\\b" << "\\bloop\\b" << "\\bnew\\b" << "\\bnext\\b" << "\\bnot\\b" << "\\boff\\b" << "\\bok\\b" << "\\bon\\b" << "\\bor\\b" << "\\bother\\b" << "\\bpackage\\b" << "\\bprivate\\b" << "\\bput\\b" << "\\breturn\\b" << "\\bsee\\b" << "\\bstep\\b" << "\\bswitch\\b" << "\\bto\\b" << "\\btry\\b" << "\\bendfunc\\b" << "\\bendclass\\b" << "\\bendpackage\\b" << "\\bwhile\\b" << "\\bchangeringkeyword\\b" << "\\bchangeringoperator\\b" << "\\bloadsyntax\\b"; foreach (const QString &pattern, keywordPatterns) { rule.pattern = QRegExp(pattern,Qt::CaseInsensitive); rule.format = keywordFormat; highlightingRules.append(rule); } if (this->nKeywordsBold) classFormat.setFontWeight(QFont::Bold); classFormat.setForeground(c2); rule.pattern = QRegExp("\\bQ[A-Za-z]+\\b"); rule.format = classFormat; highlightingRules.append(rule); functionFormat.setFontItalic(true); functionFormat.setForeground(c5); rule.pattern = QRegExp("\\b[A-Za-z0-9_]+(?=\\()"); rule.format = functionFormat; highlightingRules.append(rule); singleLineCommentFormat.setForeground(c3); rule.pattern = QRegExp("//[^\n]*"); rule.format = singleLineCommentFormat; highlightingRules.append(rule); rule.pattern = QRegExp("^#+[^\n]*"); highlightingRules.append(rule); rule.pattern = QRegExp("#+( |-|=)[^\n]*"); highlightingRules.append(rule); multiLineCommentFormat.setForeground(c3); quotationFormat.setForeground(c4); rule.pattern = QRegExp("\"(?:(?!\\/\\/).)+\""); rule.pattern.setMinimal(true); rule.format = quotationFormat; highlightingRules.append(rule); quotationFormat2.setForeground(c4); rule.pattern = QRegExp("\'(?:(?!\\/\\/).)+\'"); rule.pattern.setMinimal(true); rule.format = quotationFormat2; highlightingRules.append(rule); quotationFormat3.setForeground(c4); rule.pattern = QRegExp("\`(?:(?!\\/\\/).)+\`"); rule.pattern.setMinimal(true); rule.format = quotationFormat3; highlightingRules.append(rule); commentStartExpression = QRegExp("^/\\*"); commentEndExpression = QRegExp("\\*/"); } void Highlighter::setKeywordsBold(int nStatus) { this->nKeywordsBold = nStatus; } <commit_msg>Update RingQt - highlighter.cpp<commit_after>/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** 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 The Qt Company Ltd 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." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ /* File is modified to include Ring Keywords and Ignore the Case Updated by : Mahmoud Fayed <msfclipper@yahoo.com> Date : 2016.09.14 */ #include "highlighter.h" Highlighter::Highlighter(QTextDocument *parent) : QSyntaxHighlighter(parent) { setColors(Qt::darkBlue,Qt::darkMagenta,Qt::red,Qt::darkGreen,Qt::blue); } void Highlighter::highlightBlock(const QString &text) { foreach (const HighlightingRule &rule, highlightingRules) { QRegExp expression(rule.pattern); int index = expression.indexIn(text); while (index >= 0) { int length = expression.matchedLength(); setFormat(index, length, rule.format); index = expression.indexIn(text, index + length); } } setCurrentBlockState(0); int startIndex = 0; if (previousBlockState() != 1) startIndex = commentStartExpression.indexIn(text); while (startIndex >= 0) { int endIndex = commentEndExpression.indexIn(text, startIndex); int commentLength; if (endIndex == -1) { setCurrentBlockState(1); commentLength = text.length() - startIndex; } else { commentLength = endIndex - startIndex + commentEndExpression.matchedLength(); } setFormat(startIndex, commentLength, multiLineCommentFormat); startIndex = commentStartExpression.indexIn(text, startIndex + commentLength); } } void Highlighter::setColors(QColor c1,QColor c2,QColor c3,QColor c4,QColor c5) { HighlightingRule rule; highlightingRules.remove(0,highlightingRules.count()); keywordFormat.setForeground(c1); if (this->nKeywordsBold) keywordFormat.setFontWeight(QFont::Bold); QStringList keywordPatterns; keywordPatterns << "\\bagain\\b" << "\\band\\b" << "\\bbut\\b" << "\\bbye\\b" << "\\bcall\\b" << "\\bcase\\b" << "\\bcatch\\b" << "\\bclass\\b" << "\\bdef\\b" << "\\bdo\\b" << "\\bdone\\b" << "\\belse\\b" << "\\belseif\\b" << "\\bend\\b" << "\\bexit\\b" << "\\bfor\\b" << "\\bfrom\\b" << "\\bfunc\\b" << "\\bget\\b" << "\\bgive\\b" << "\\bif\\b" << "\\bimport\\b" << "\\bin\\b" << "\\bload\\b" << "\\bloop\\b" << "\\bnew\\b" << "\\bnext\\b" << "\\bnot\\b" << "\\boff\\b" << "\\bok\\b" << "\\bon\\b" << "\\bor\\b" << "\\bother\\b" << "\\bpackage\\b" << "\\bprivate\\b" << "\\bput\\b" << "\\breturn\\b" << "\\bsee\\b" << "\\bstep\\b" << "\\bswitch\\b" << "\\bto\\b" << "\\btry\\b" << "\\bendfunc\\b" << "\\bendclass\\b" << "\\bendpackage\\b" << "\\bwhile\\b" << "\\bchangeringkeyword\\b" << "\\bchangeringoperator\\b" << "\\bloadsyntax\\b"; foreach (const QString &pattern, keywordPatterns) { rule.pattern = QRegExp(pattern,Qt::CaseInsensitive); rule.format = keywordFormat; highlightingRules.append(rule); } if (this->nKeywordsBold) classFormat.setFontWeight(QFont::Bold); classFormat.setForeground(c2); rule.pattern = QRegExp("\\bQ[A-Za-z]+\\b"); rule.format = classFormat; highlightingRules.append(rule); functionFormat.setFontItalic(true); functionFormat.setForeground(c5); rule.pattern = QRegExp("\\b[A-Za-z0-9_]+(?=\\()"); rule.format = functionFormat; highlightingRules.append(rule); singleLineCommentFormat.setForeground(c3); rule.pattern = QRegExp("//[^\n]*"); rule.format = singleLineCommentFormat; highlightingRules.append(rule); rule.pattern = QRegExp("^#+[^\n]*"); highlightingRules.append(rule); rule.pattern = QRegExp("#+( |-|=)[^\n]*"); highlightingRules.append(rule); multiLineCommentFormat.setForeground(c3); quotationFormat.setForeground(c4); rule.pattern = QRegExp("\"(?:(?!\\/\\/).)+\""); rule.pattern.setMinimal(true); rule.format = quotationFormat; highlightingRules.append(rule); quotationFormat2.setForeground(c4); rule.pattern = QRegExp("\'(?:(?!\\/\\/).)+\'"); rule.pattern.setMinimal(true); rule.format = quotationFormat2; highlightingRules.append(rule); quotationFormat3.setForeground(c4); rule.pattern = QRegExp("`(?:(?!\\/\\/).)+`"); rule.pattern.setMinimal(true); rule.format = quotationFormat3; highlightingRules.append(rule); commentStartExpression = QRegExp("^/\\*"); commentEndExpression = QRegExp("\\*/"); } void Highlighter::setKeywordsBold(int nStatus) { this->nKeywordsBold = nStatus; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ole2uno.hxx,v $ * * $Revision: 1.12 $ * * last change: $Author: ihi $ $Date: 2008-01-14 14:46:30 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _OLE2UNO_HXX #define _OLE2UNO_HXX #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #define STRICT #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0400 #endif #define _WIN32_DCOM #if OSL_DEBUG_LEVEL > 0 //#define _ATL_DEBUG_INTERFACES #endif #pragma warning (push,1) #pragma warning (disable:4917) #pragma warning (disable:4005) #pragma warning (disable:4548) #include <tools/prewin.h> #include <tchar.h> #if (_MSC_VER >= 1200) || defined(__MINGW32__) #include <dispex.h> #endif #include <tools/postwin.h> #include <tools/presys.h> #include <list> #include <tools/postsys.h> #pragma warning (pop) #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_ #include <com/sun/star/lang/XSingleServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_SCRIPT_XINVOCATION_HPP_ #include <com/sun/star/script/XInvocation.hpp> #endif #ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_ #include <com/sun/star/registry/XRegistryKey.hpp> #endif #ifndef _COM_SUN_STAR_BRIDGE_XBRIDGESUPPLIER2_HPP_ #include <com/sun/star/bridge/XBridgeSupplier2.hpp> #endif #ifndef _COM_SUN_STAR_BRIDGE_MODELDEPENDENT_HPP_ #include <com/sun/star/bridge/ModelDependent.hpp> #endif #ifndef _COM_SUN_STAR_REFLECTION_INVOCATIONTARGETEXCEPTION_HPP_ #include <com/sun/star/reflection/InvocationTargetException.hpp> #endif #ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP_ #include <com/sun/star/uno/Exception.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_UNKNOWNPROPERTYEXCEPTION_HPP_ #include <com/sun/star/beans/UnknownPropertyException.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE2_HXX_ #include <cppuhelper/implbase2.hxx> #endif #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif #ifndef _CPPUHELPER_TYPEPROVIDER_HXX_ #include <cppuhelper/typeprovider.hxx> #endif #ifndef _CPPUHELPER_FACTORY_HXX_ #include <cppuhelper/factory.hxx> #endif #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #ifndef _TYPELIB_TYPECLASS_H_ #include <typelib/typeclass.h> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif #ifndef _RTL_PROCESS_H_ #include <rtl/process.h> #endif #ifndef _RTL_UUID_H_ #include <rtl/uuid.h> #endif #define UNO_2_OLE_EXCEPTIONCODE 1001 #define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) ) using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::script; using namespace com::sun::star::registry; using namespace com::sun::star::reflection; using namespace com::sun::star::beans; using namespace osl; using namespace rtl; using namespace std; namespace ole_adapter { const VARTYPE getVarType( const Any& val); /* creates a Type object for a given type name. The function returns false if the name does not represent a valid type. */ bool getType( BSTR name, Type & type); void o2u_attachCurrentThread(); struct equalOUString_Impl { bool operator()(const OUString & s1, const OUString & s2) const { return s1 == s2; } }; struct hashOUString_Impl { size_t operator()(const OUString & rName) const { return rName.hashCode(); } }; class BridgeRuntimeError { public: BridgeRuntimeError(const OUString& sMessage) { message = sMessage; } OUString message; }; Mutex* getBridgeMutex(); } // end namespace #endif // _OLE2UNO_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.12.48); FILE MERGED 2008/04/01 15:15:08 thb 1.12.48.3: #i85898# Stripping all external header guards 2008/04/01 12:29:45 thb 1.12.48.2: #i85898# Stripping all external header guards 2008/03/31 12:31:33 rt 1.12.48.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: ole2uno.hxx,v $ * $Revision: 1.13 $ * * 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 _OLE2UNO_HXX #define _OLE2UNO_HXX #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #define STRICT #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0400 #endif #define _WIN32_DCOM #if OSL_DEBUG_LEVEL > 0 //#define _ATL_DEBUG_INTERFACES #endif #pragma warning (push,1) #pragma warning (disable:4917) #pragma warning (disable:4005) #pragma warning (disable:4548) #include <tools/prewin.h> #include <tchar.h> #if (_MSC_VER >= 1200) || defined(__MINGW32__) #include <dispex.h> #endif #include <tools/postwin.h> #include <tools/presys.h> #include <list> #include <tools/postsys.h> #pragma warning (pop) #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include <com/sun/star/lang/XSingleServiceFactory.hpp> #include <com/sun/star/script/XInvocation.hpp> #include <com/sun/star/registry/XRegistryKey.hpp> #include <com/sun/star/bridge/XBridgeSupplier2.hpp> #include <com/sun/star/bridge/ModelDependent.hpp> #include <com/sun/star/reflection/InvocationTargetException.hpp> #include <com/sun/star/uno/Exception.hpp> #include <com/sun/star/beans/UnknownPropertyException.hpp> #include <cppuhelper/implbase2.hxx> #include <cppuhelper/implbase1.hxx> #include <cppuhelper/typeprovider.hxx> #include <cppuhelper/factory.hxx> #include <sal/types.h> #include <typelib/typeclass.h> #include <osl/diagnose.h> #include <osl/mutex.hxx> #include <com/sun/star/uno/Reference.h> #include <rtl/process.h> #include <rtl/uuid.h> #define UNO_2_OLE_EXCEPTIONCODE 1001 #define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) ) using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::script; using namespace com::sun::star::registry; using namespace com::sun::star::reflection; using namespace com::sun::star::beans; using namespace osl; using namespace rtl; using namespace std; namespace ole_adapter { const VARTYPE getVarType( const Any& val); /* creates a Type object for a given type name. The function returns false if the name does not represent a valid type. */ bool getType( BSTR name, Type & type); void o2u_attachCurrentThread(); struct equalOUString_Impl { bool operator()(const OUString & s1, const OUString & s2) const { return s1 == s2; } }; struct hashOUString_Impl { size_t operator()(const OUString & rName) const { return rName.hashCode(); } }; class BridgeRuntimeError { public: BridgeRuntimeError(const OUString& sMessage) { message = sMessage; } OUString message; }; Mutex* getBridgeMutex(); } // end namespace #endif // _OLE2UNO_HXX <|endoftext|>
<commit_before>/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ // Copyright 2004-present Facebook. All rights reserved. #include "RouteTable.h" #include "fboss/agent/state/RouteTableRib.h" #include "fboss/agent/state/NodeBase-defs.h" #include "fboss/agent/FbossError.h" namespace { constexpr auto kRouterId = "routerId"; constexpr auto kRibV4 = "ribV4"; constexpr auto kRibV6 = "ribV6"; } namespace facebook { namespace fboss { RouteTableFields::RouteTableFields(RouterID id) : id(id), ribV4(std::make_shared<RibTypeV4>()), ribV6(std::make_shared<RibTypeV6>()) { } folly::dynamic RouteTableFields::toFollyDynamic() const { folly::dynamic rtable = folly::dynamic::object; rtable[kRouterId] = static_cast<uint32_t>(id); rtable[kRibV4] = ribV4->toFollyDynamic(); rtable[kRibV6] = ribV6->toFollyDynamic(); return rtable; } RouteTableFields RouteTableFields::fromFollyDynamic(const folly::dynamic& rtableJson) { RouteTableFields rtable(RouterID(rtableJson[kRouterId].asInt())); rtable.ribV4 = RibTypeV4::fromFollyDynamic(rtableJson[kRibV4]); rtable.ribV6 = RibTypeV6::fromFollyDynamic(rtableJson[kRibV6]); return rtable; } RouteTable::RouteTable(RouterID id) : NodeBaseT(id) { } RouteTable::~RouteTable() { } bool RouteTable::empty() const { return getRibV4()->empty() && getRibV6()->empty(); } template class NodeBaseT<RouteTable, RouteTableFields>; }} <commit_msg>fix clang build<commit_after>/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ // Copyright 2004-present Facebook. All rights reserved. #include "RouteTable.h" #include "fboss/agent/state/Route.h" #include "fboss/agent/state/RouteTableRib.h" #include "fboss/agent/state/NodeBase-defs.h" #include "fboss/agent/FbossError.h" namespace { constexpr auto kRouterId = "routerId"; constexpr auto kRibV4 = "ribV4"; constexpr auto kRibV6 = "ribV6"; } namespace facebook { namespace fboss { RouteTableFields::RouteTableFields(RouterID id) : id(id), ribV4(std::make_shared<RibTypeV4>()), ribV6(std::make_shared<RibTypeV6>()) { } folly::dynamic RouteTableFields::toFollyDynamic() const { folly::dynamic rtable = folly::dynamic::object; rtable[kRouterId] = static_cast<uint32_t>(id); rtable[kRibV4] = ribV4->toFollyDynamic(); rtable[kRibV6] = ribV6->toFollyDynamic(); return rtable; } RouteTableFields RouteTableFields::fromFollyDynamic(const folly::dynamic& rtableJson) { RouteTableFields rtable(RouterID(rtableJson[kRouterId].asInt())); rtable.ribV4 = RibTypeV4::fromFollyDynamic(rtableJson[kRibV4]); rtable.ribV6 = RibTypeV6::fromFollyDynamic(rtableJson[kRibV6]); return rtable; } RouteTable::RouteTable(RouterID id) : NodeBaseT(id) { } RouteTable::~RouteTable() { } bool RouteTable::empty() const { return getRibV4()->empty() && getRibV6()->empty(); } template class NodeBaseT<RouteTable, RouteTableFields>; }} <|endoftext|>
<commit_before><commit_msg>fix webgl build<commit_after><|endoftext|>
<commit_before><commit_msg>ShadowMapManager: fix MSAN use-of-uninitialized-value.<commit_after><|endoftext|>
<commit_before>#include <fstream> #include "cpu.h" #include <iostream> #include <stdexcept> #include <sstream> #include <iomanip> using namespace std; //TODO improve consistency of error handling/reporting //TODO improve debug info function names Cpu::Cpu(Display& d) { display = &d; } void Cpu::reset() { pc = 0x200; ir = getDWord(pc); for(auto i = 0; i < MEMORY_SIZE; i++) { memory[i] = 0x0; } for(auto i = 0; i < REGISTER_COUNT; i++) { v[i] = 0x0; } for(auto i = 0; i < STACK_SIZE; i++) { stack[i] = 0x0; } sp = 0; I = 0x0; uint8_t fonts[80] = { 0xF0, 0x90, 0x90, 0x90, 0xF0, 0x20, 0x60, 0x20, 0x20, 0x70, 0xF0, 0x10, 0xF0, 0x80, 0xF0, 0xF0, 0x10, 0xF0, 0x10, 0xF0, 0x90, 0x90, 0xF0, 0x10, 0x10, 0xF0, 0x80, 0xF0, 0x10, 0xF0, 0xF0, 0x80, 0xF0, 0x90, 0xF0, 0xF0, 0x10, 0x20, 0x40, 0x40, 0xF0, 0x90, 0xF0, 0x90, 0xF0, 0xF0, 0x90, 0xF0, 0x10, 0xF0, 0xF0, 0x90, 0xF0, 0x90, 0x90, 0xE0, 0x90, 0xE0, 0x90, 0xE0, 0xF0, 0x80, 0x80, 0x80, 0xF0, 0xE0, 0x90, 0x90, 0x90, 0xE0, 0xF0, 0x80, 0xF0, 0x80, 0xF0, 0xF0, 0x80, 0xF0, 0x80, 0x80 }; memcpy(&memory, &fonts, 80); //place fonts in memory starting at 0x0000 } void Cpu::loadProgram(const string& filename) { reset(); //puts the Cpu in a known state ifstream ifs(filename, ios::in | ios::binary); ifs.seekg(0, ifs.end); streampos size = ifs.tellg(); ifs.seekg(0, ifs.beg); ifs.read((char*)&memory[pc], size); //cout << "read " << size << " bytes\n"; ifs.close(); } void Cpu::dumpMemory() { //for(auto w = 0; w < ) //TODO } void Cpu::dumpRegisters() { //cout << hex << "pc: " << pc << ' '; //cout << hex << "ir: " << ir << ' '; //cout << hex << "I: " << I << '\n'; for(auto i = 0; i < REGISTER_COUNT; i++) { //cout << hex << "v" << i << ": " << setw(4) << unsigned(v[i]) << '\n'; } //cout << endl; } void Cpu::decode_failure(uint16_t instruction) { ostringstream oss; oss << hex << "unknown instruction: " << instruction; throw runtime_error(oss.str()); } void Cpu::step() { fetch(); const uint8_t msb = ir >> 12; const uint8_t lsb = ir & 0xF; const uint8_t x = (ir & 0xF00) >> 8; const uint8_t y = (ir & 0xF0) >> 4; const uint8_t kk = ir & 0xFF; const uint16_t nnn = ir & 0xFFF; const uint8_t Vx = v[x]; const uint8_t Vy = v[y]; //for displaying values auto d_x = unsigned(x); auto d_y = unsigned(y); auto d_kk = unsigned(kk); auto d_nnn = unsigned(nnn); //cout << hex << setw(4) << unsigned(pc) << ' ' << // setw(4) << unsigned(ir) << ' ' << // setw(2) << unsigned(sp) << ' '; //TODO inconsistent matching format switch(msb) { case 0x0: switch(kk) { case 0xE0: //TODO clear the screen //cout << hex << "CLS\n"; display->clear(); pc += 2; break; case 0xEE: //cout << hex << "RET\n"; pc = stack[--sp]; break; default: decode_failure(ir); break; } break; case 0x1: //cout << hex << "JP " << d_nnn << '\n'; pc = nnn; break; case 0x2: //cout << hex << "CALL " << d_nnn << '\n'; stack[sp++] = pc + 2; pc = nnn; break; case 0x3: //cout << hex << "SE V" << d_x << ", " << d_kk << '\n'; pc += Vx == kk ? 4 : 2; break; case 0x4: //cout << hex << "SNE V" << d_x << ", " << d_kk << '\n'; pc += Vx != kk ? 4 : 2; break; case 0x5: //cout << hex << "SE V" << d_x << ", V" << d_y << '\n'; pc += Vx == Vy ? 4 : 2; break; case 0x6: //cout << hex << "LD V" << d_x << ", " << d_kk << '\n'; v[x] = kk; pc += 2; break; case 0x7: //cout << hex << "ADD V" << d_x << ", " << d_kk << '\n'; v[x] += kk; pc += 2; break; case 0x8: switch(lsb) { case 0: //cout << hex << "LD V" << d_x << ", V" << d_y << '\n'; v[x] = v[y]; break; case 1: //cout << hex << "OR V" << d_x << ", V" << d_y << '\n'; v[x] = Vx | Vy; break; case 2: //cout << hex << "AND V" << d_x << ", V" << d_y << '\n'; v[x] = Vx & Vy; break; case 3: //cout << hex << "XOR V" << d_x << ", V" << d_y << '\n'; v[x] = Vx != Vy; break; case 4: //cout << hex << "ADD V" << d_x << ", V" << d_y << '\n'; //might be a better way to do this { auto x16 = static_cast<uint16_t>(v[x]); auto y16 = static_cast<uint16_t>(v[y]); v[0xF] = x16 + y16 > 255 ? 1 : 0; } v[x] = v[x] + v[y]; break; case 5: //cout << hex << "SUB V" << d_x << ", V" << d_y << '\n'; v[0xF] = Vx > Vy ? 1 : 0; v[x] = v[x] - v[y]; break; default: decode_failure(ir); break; } pc += 2; break; case 0x9: //cout << hex << "SNE V" << d_x << ", V" << d_y << '\n'; pc += Vx != Vy ? 4 : 2; break; case 0xA: //cout << hex << "LD I, " << d_nnn << '\n'; I = nnn; pc += 2; break; case 0xC: //cout << hex << "RND V" << d_x << ", " << d_kk << '\n'; v[x] = (rnd() & 0xFF) & kk; pc += 2; break; case 0xD: //cout << hex << "DRW V" << d_x << ", V" << d_y << ", " << lsb << '\n'; v[0xF] = display->blit(&memory[I], lsb, Vx, Vy); pc += 2; break; case 0xE: switch(kk) { case 0x9E: //cout << hex << "SKP V" << dx << '\n'; pc += keys[Vx] ? 4 : 2; break; case 0xA1: //cout << hex << "SKNP V" << dx << '\n'; pc += !keys[Vx] ? 4 : 2; break; default: decode_failure(ir); break; } break; case 0xF: switch(kk) { case 0x29: //cout << hex << "LD F, V" << d_x << '\n'; I = Vx * 5; break; case 0x55: //cout << hex << "LD [i], V" << d_x << '\n'; for(auto i = 0; i <= x; i++) { memory[I + i] = v[i]; } break; case 0x1E: //cout << hex << "ADD I, V" << d_x << '\n'; I += Vx; break; case 0x65: //cout << hex << "LD V" << d_x << ", [I]\n"; for(auto i = 0; i <= x; i++) { v[i] = memory[I + i]; } break; default: decode_failure(ir); break; } pc += 2; break; default: decode_failure(ir); break; } } void Cpu::fetch() { ir = getDWord(pc); } uint16_t Cpu::getDWord(uint16_t addr) { return (static_cast<uint16_t>(memory[addr]) << 8) | memory[addr + 1]; } void Cpu::pressKey(const uint8_t key) { keys[key] = true; //wait_for_key = false; } void Cpu::releaseKey(const uint8_t key) { keys[key] = false; } <commit_msg>implemented the remaining 8xxx instructions<commit_after>#include <fstream> #include "cpu.h" #include <iostream> #include <stdexcept> #include <sstream> #include <iomanip> using namespace std; //TODO improve consistency of error handling/reporting //TODO improve debug info function names Cpu::Cpu(Display& d) { display = &d; } void Cpu::reset() { pc = 0x200; ir = getDWord(pc); for(auto i = 0; i < MEMORY_SIZE; i++) { memory[i] = 0x0; } for(auto i = 0; i < REGISTER_COUNT; i++) { v[i] = 0x0; } for(auto i = 0; i < STACK_SIZE; i++) { stack[i] = 0x0; } sp = 0; I = 0x0; uint8_t fonts[80] = { 0xF0, 0x90, 0x90, 0x90, 0xF0, 0x20, 0x60, 0x20, 0x20, 0x70, 0xF0, 0x10, 0xF0, 0x80, 0xF0, 0xF0, 0x10, 0xF0, 0x10, 0xF0, 0x90, 0x90, 0xF0, 0x10, 0x10, 0xF0, 0x80, 0xF0, 0x10, 0xF0, 0xF0, 0x80, 0xF0, 0x90, 0xF0, 0xF0, 0x10, 0x20, 0x40, 0x40, 0xF0, 0x90, 0xF0, 0x90, 0xF0, 0xF0, 0x90, 0xF0, 0x10, 0xF0, 0xF0, 0x90, 0xF0, 0x90, 0x90, 0xE0, 0x90, 0xE0, 0x90, 0xE0, 0xF0, 0x80, 0x80, 0x80, 0xF0, 0xE0, 0x90, 0x90, 0x90, 0xE0, 0xF0, 0x80, 0xF0, 0x80, 0xF0, 0xF0, 0x80, 0xF0, 0x80, 0x80 }; memcpy(&memory, &fonts, 80); //place fonts in memory starting at 0x0000 } void Cpu::loadProgram(const string& filename) { reset(); //puts the Cpu in a known state ifstream ifs(filename, ios::in | ios::binary); ifs.seekg(0, ifs.end); streampos size = ifs.tellg(); ifs.seekg(0, ifs.beg); ifs.read((char*)&memory[pc], size); //cout << "read " << size << " bytes\n"; ifs.close(); } void Cpu::dumpMemory() { //for(auto w = 0; w < ) //TODO } void Cpu::dumpRegisters() { //cout << hex << "pc: " << pc << ' '; //cout << hex << "ir: " << ir << ' '; //cout << hex << "I: " << I << '\n'; for(auto i = 0; i < REGISTER_COUNT; i++) { //cout << hex << "v" << i << ": " << setw(4) << unsigned(v[i]) << '\n'; } //cout << endl; } void Cpu::decode_failure(uint16_t instruction) { ostringstream oss; oss << hex << "unknown instruction: " << instruction; throw runtime_error(oss.str()); } void Cpu::step() { fetch(); const uint8_t msb = ir >> 12; const uint8_t lsb = ir & 0xF; const uint8_t x = (ir & 0xF00) >> 8; const uint8_t y = (ir & 0xF0) >> 4; const uint8_t kk = ir & 0xFF; const uint16_t nnn = ir & 0xFFF; const uint8_t Vx = v[x]; const uint8_t Vy = v[y]; //for displaying values auto d_x = unsigned(x); auto d_y = unsigned(y); auto d_kk = unsigned(kk); auto d_nnn = unsigned(nnn); //cout << hex << setw(4) << unsigned(pc) << ' ' << // setw(4) << unsigned(ir) << ' ' << // setw(2) << unsigned(sp) << ' '; //TODO inconsistent matching format switch(msb) { case 0x0: switch(kk) { case 0xE0: //TODO clear the screen //cout << hex << "CLS\n"; display->clear(); pc += 2; break; case 0xEE: //cout << hex << "RET\n"; pc = stack[--sp]; break; default: decode_failure(ir); break; } break; case 0x1: //cout << hex << "JP " << d_nnn << '\n'; pc = nnn; break; case 0x2: //cout << hex << "CALL " << d_nnn << '\n'; stack[sp++] = pc + 2; pc = nnn; break; case 0x3: //cout << hex << "SE V" << d_x << ", " << d_kk << '\n'; pc += Vx == kk ? 4 : 2; break; case 0x4: //cout << hex << "SNE V" << d_x << ", " << d_kk << '\n'; pc += Vx != kk ? 4 : 2; break; case 0x5: //cout << hex << "SE V" << d_x << ", V" << d_y << '\n'; pc += Vx == Vy ? 4 : 2; break; case 0x6: //cout << hex << "LD V" << d_x << ", " << d_kk << '\n'; v[x] = kk; pc += 2; break; case 0x7: //cout << hex << "ADD V" << d_x << ", " << d_kk << '\n'; v[x] += kk; pc += 2; break; case 0x8: switch(lsb) { case 0x0: //cout << hex << "LD V" << d_x << ", V" << d_y << '\n'; v[x] = v[y]; break; case 0x1: //cout << hex << "OR V" << d_x << ", V" << d_y << '\n'; v[x] = Vx | Vy; break; case 0x2: //cout << hex << "AND V" << d_x << ", V" << d_y << '\n'; v[x] = Vx & Vy; break; case 0x3: //cout << hex << "XOR V" << d_x << ", V" << d_y << '\n'; v[x] = Vx != Vy; break; case 0x4: //cout << hex << "ADD V" << d_x << ", V" << d_y << '\n'; //might be a better way to do this { auto x16 = static_cast<uint16_t>(v[x]); auto y16 = static_cast<uint16_t>(v[y]); v[0xF] = x16 + y16 > 255 ? 1 : 0; } v[x] = v[x] + v[y]; break; case 0x5: //cout << hex << "SUB V" << d_x << ", V" << d_y << '\n'; v[0xF] = Vx > Vy ? 1 : 0; v[x] = v[x] - v[y]; break; case 0x6: //cout << hex << "SHR V" << d_x << ", {V" << d_y << "}\n"; v[0xF] = lsb == 0x1 ? 1 : 0; v[x] = v[x] >> 1; break; case 0x7: //cout << hex << "SUBN V" << d_x << ", V" << d_y << '\n'; v[0xF] = Vy > Vx ? 1 : 0; v[x] = v[y] - v[x]; break; case 0xE: //cout << hex << "SHL V" << d_x << ", {V" << d_y << "}\n"; v[0xF] = msb == 0x1 ? 1 : 0; v[x] = v[x] << 1; break; default: decode_failure(ir); break; } pc += 2; break; case 0x9: //cout << hex << "SNE V" << d_x << ", V" << d_y << '\n'; pc += Vx != Vy ? 4 : 2; break; case 0xA: //cout << hex << "LD I, " << d_nnn << '\n'; I = nnn; pc += 2; break; case 0xC: //cout << hex << "RND V" << d_x << ", " << d_kk << '\n'; v[x] = (rnd() & 0xFF) & kk; pc += 2; break; case 0xD: //cout << hex << "DRW V" << d_x << ", V" << d_y << ", " << lsb << '\n'; v[0xF] = display->blit(&memory[I], lsb, Vx, Vy); pc += 2; break; case 0xE: switch(kk) { case 0x9E: //cout << hex << "SKP V" << dx << '\n'; pc += keys[Vx] ? 4 : 2; break; case 0xA1: //cout << hex << "SKNP V" << dx << '\n'; pc += !keys[Vx] ? 4 : 2; break; default: decode_failure(ir); break; } break; case 0xF: switch(kk) { case 0x29: //cout << hex << "LD F, V" << d_x << '\n'; I = Vx * 5; break; case 0x55: //cout << hex << "LD [i], V" << d_x << '\n'; for(auto i = 0; i <= x; i++) { memory[I + i] = v[i]; } break; case 0x1E: //cout << hex << "ADD I, V" << d_x << '\n'; I += Vx; break; case 0x65: //cout << hex << "LD V" << d_x << ", [I]\n"; for(auto i = 0; i <= x; i++) { v[i] = memory[I + i]; } break; default: decode_failure(ir); break; } pc += 2; break; default: decode_failure(ir); break; } } void Cpu::fetch() { ir = getDWord(pc); } uint16_t Cpu::getDWord(uint16_t addr) { return (static_cast<uint16_t>(memory[addr]) << 8) | memory[addr + 1]; } void Cpu::pressKey(const uint8_t key) { keys[key] = true; //wait_for_key = false; } void Cpu::releaseKey(const uint8_t key) { keys[key] = false; } <|endoftext|>
<commit_before>#include <Arduino.h> #include "menu.h" #include "common.h" #include "options.h" #include "../config.h" #include "../displays.h" #include "../events.h" static TimerId updateBallTimer, updateSpeedTimer; static struct { byte x:3; byte y:3; signed char xDir:2; signed char yDir:2; unsigned short speed; // In milliseconds } ball; static struct { byte y:3; byte score; } players[2]; static void menu(byte data); static void newRound(byte playerStarting); static void endRound(void); static void updateBall(byte data) { matrix.setLed(0, ball.y, ball.x, false); if (ball.y <= 0 || ball.y >= 7) ball.yDir *= -1; if (ball.x == 1 or ball.x == 6) { byte player = (ball.x == 1) ? 0 : 1; if ((ball.y == players[player].y) or (ball.y == players[player].y + 1)) { ball.xDir *= -1; } else if ((ball.y == players[player].y - 1 and ball.yDir == 1) or (ball.y == players[player].y + 2 and ball.yDir == -1)) { ball.xDir *= -1; ball.yDir *= -1; } } else if (ball.x == 0 or ball.x == 7) { // Ball out of bound printLcd((ball.x == 0) ? 13 : 2, 1, "+1"); delay(2000); if (ball.x == 0) { players[1].score++; newRound(0); } else { players[0].score++; newRound(1); } return; } ball.x += ball.xDir; ball.y += ball.yDir; matrix.setLed(0, ball.y, ball.x, true); updateBallTimer = registerTimerEvent(ball.speed, updateBall, 0); } static void updateSpeed(byte data) { if (ball.speed > options[PONG_MIN_DELAY]) { ball.speed -= 50; updateSpeedTimer = registerTimerEvent(options[SPEED_INCREASE_DELAY], updateSpeed, 0); } } static void up1(byte data) { if (players[0].y > 0) { matrix.setLed(0, players[0].y + 1, 0, false); matrix.setLed(0, --players[0].y, 0, true); } } static void down1(byte data) { if (players[0].y < 6) { matrix.setLed(0, players[0].y, 0, false); matrix.setLed(0, ++players[0].y + 1, 0, true); } } static void up2(byte data) { if (players[1].y > 0) { matrix.setLed(0, players[1].y + 1, 7, false); matrix.setLed(0, --players[1].y, 7, true); } } static void down2(byte data) { if (players[1].y < 6) { matrix.setLed(0, players[1].y, 7, false); matrix.setLed(0, ++players[1].y + 1, 7, true); } } static void menu(byte data) { endRound(); showMenu(); } static void endRound(void) { cancelTimerEvent(&updateBallTimer); cancelTimerEvent(&updateSpeedTimer); } static void newRound(byte playerStarting) { endRound(); ball.x = (playerStarting == 0) ? 2 : 5; ball.y = random(1, 7); ball.xDir = (playerStarting == 0) ? 1 : -1; ball.yDir = (random(0, 2)) ? 1 : -1; ball.speed = options[PONG_START_DELAY]; players[0].y = players[1].y = 3; countdown(); matrix.setRow(0, 3, B10000001); matrix.setRow(0, 4, B10000001); matrix.setLed(0, ball.y, ball.x, true); printLcd(2, 0, players[0].score); printLcd(7, 0, "--"); printLcd(13, 0, players[1].score); delay(500); updateBallTimer = registerTimerEvent(ball.speed, updateBall, 0); updateSpeedTimer = registerTimerEvent(options[SPEED_INCREASE_DELAY], updateSpeed, 0); } void showPong(void) { setRepeatClickHandler(PLAYER1_LEFT, options[PONG_PADDLE_SPEED], up1, 0); setRepeatClickHandler(PLAYER1_RIGHT, options[PONG_PADDLE_SPEED], down1, 0); setRepeatClickHandler(PLAYER2_LEFT, options[PONG_PADDLE_SPEED], up2, 0); setRepeatClickHandler(PLAYER2_RIGHT, options[PONG_PADDLE_SPEED], down2, 0); setSingleClickHandler(MENU, menu, 0); updateBallTimer = updateSpeedTimer = -1; players[0].score = players[1].score = 0; newRound(0); } <commit_msg>Fixed bug while bouncing ball in pong<commit_after>#include <Arduino.h> #include "menu.h" #include "common.h" #include "options.h" #include "../config.h" #include "../displays.h" #include "../events.h" static TimerId updateBallTimer, updateSpeedTimer; static struct { byte x:3; byte y:3; signed char xDir:2; signed char yDir:2; unsigned short speed; // In milliseconds } ball; static struct { byte y:3; byte score; } players[2]; static void menu(byte data); static void newRound(byte playerStarting); static void endRound(void); static void updateBall(byte data) { matrix.setLed(0, ball.y, ball.x, false); if (ball.y <= 0 || ball.y >= 7) ball.yDir *= -1; if (ball.x == 1 || ball.x == 6) { byte player = (ball.x == 1) ? 0 : 1; if ((ball.y == players[player].y) || (ball.y == players[player].y + 1)) { ball.xDir *= -1; } else if (((ball.y == players[player].y - 1 && ball.yDir == 1) || (ball.y == players[player].y + 2 && ball.yDir == -1))) { ball.xDir *= -1; if (ball.y > 0 && ball.y < 7) // Avoid double y direction inversion ball.yDir *= -1; } } else if (ball.x == 0 || ball.x == 7) { // Ball out of bound printLcd((ball.x == 0) ? 13 : 2, 1, "+1"); delay(2000); if (ball.x == 0) { players[1].score++; newRound(0); } else { players[0].score++; newRound(1); } return; } ball.x += ball.xDir; ball.y += ball.yDir; matrix.setLed(0, ball.y, ball.x, true); updateBallTimer = registerTimerEvent(ball.speed, updateBall, 0); } static void updateSpeed(byte data) { if (ball.speed > options[PONG_MIN_DELAY]) { ball.speed -= 50; updateSpeedTimer = registerTimerEvent(options[SPEED_INCREASE_DELAY], updateSpeed, 0); } } static void up1(byte data) { if (players[0].y > 0) { matrix.setLed(0, players[0].y + 1, 0, false); matrix.setLed(0, --players[0].y, 0, true); } } static void down1(byte data) { if (players[0].y < 6) { matrix.setLed(0, players[0].y, 0, false); matrix.setLed(0, ++players[0].y + 1, 0, true); } } static void up2(byte data) { if (players[1].y > 0) { matrix.setLed(0, players[1].y + 1, 7, false); matrix.setLed(0, --players[1].y, 7, true); } } static void down2(byte data) { if (players[1].y < 6) { matrix.setLed(0, players[1].y, 7, false); matrix.setLed(0, ++players[1].y + 1, 7, true); } } static void menu(byte data) { endRound(); showMenu(); } static void endRound(void) { cancelTimerEvent(&updateBallTimer); cancelTimerEvent(&updateSpeedTimer); } static void newRound(byte playerStarting) { endRound(); ball.x = (playerStarting == 0) ? 2 : 5; ball.y = random(1, 7); ball.xDir = (playerStarting == 0) ? 1 : -1; ball.yDir = (random(0, 2)) ? 1 : -1; ball.speed = options[PONG_START_DELAY]; players[0].y = players[1].y = 3; countdown(); matrix.setRow(0, 3, B10000001); matrix.setRow(0, 4, B10000001); matrix.setLed(0, ball.y, ball.x, true); printLcd(2, 0, players[0].score); printLcd(7, 0, "--"); printLcd(13, 0, players[1].score); delay(500); updateBallTimer = registerTimerEvent(ball.speed, updateBall, 0); updateSpeedTimer = registerTimerEvent(options[SPEED_INCREASE_DELAY], updateSpeed, 0); } void showPong(void) { setRepeatClickHandler(PLAYER1_LEFT, options[PONG_PADDLE_SPEED], up1, 0); setRepeatClickHandler(PLAYER1_RIGHT, options[PONG_PADDLE_SPEED], down1, 0); setRepeatClickHandler(PLAYER2_LEFT, options[PONG_PADDLE_SPEED], up2, 0); setRepeatClickHandler(PLAYER2_RIGHT, options[PONG_PADDLE_SPEED], down2, 0); setSingleClickHandler(MENU, menu, 0); updateBallTimer = updateSpeedTimer = -1; players[0].score = players[1].score = 0; newRound(0); } <|endoftext|>
<commit_before>/* ************************************************************************ * HardwareSerial.cpp * * Arduino core files for MSP430 * Copyright (c) 2012 Robert Wessels. All right reserved. * * *********************************************************************** Derived from: HardwareSerial.cpp - Hardware serial library for Wiring Copyright (c) 2006 Nicholas Zambetti. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.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 Modified 23 November 2006 by David A. Mellis Modified 28 September 2010 by Mark Sproul */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <inttypes.h> #include "Energia.h" #include "wiring_private.h" #include "usci_isr_handler.h" #if defined(__MSP430_HAS_USCI__) || defined(__MSP430_HAS_USCI_A0__) || defined(__MSP430_HAS_USCI_A1__) || defined(__MSP430_HAS_EUSCI_A0__) #include "HardwareSerial.h" #define UCAxCTLW0 UCA0CTLW0 #define UCAxCTL0 UCA0CTL0 #define UCAxCTL1 UCA0CTL1 #define UCAxBRW UCA0BRW #define UCAxBR0 UCA0BR0 #define UCAxBR1 UCA0BR1 #define UCAxMCTL UCA0MCTL #define UCAxMCTLW UCA0MCTLW #define UCAxSTAT UCA0STAT #define UCAxRXBUF UCA0RXBUF #define UCAxTXBUF UCA0TXBUF #define UCAxABCTL UCA0ABCTL #define UCAxIRCTL UCA0IRCTL #define UCAxIRTCTL UCA0IRTCTL #define UCAxIRRCTL UCA0IRRCTL #define UCAxICTL UCA0ICTL #define UCAxIE UCA0IE #define UCAxIFG UCA0IFG #define UCAxIV UCA0IV #define SERIAL_BUFFER_SIZE 16 struct ring_buffer { unsigned char buffer[SERIAL_BUFFER_SIZE]; volatile unsigned int head; volatile unsigned int tail; }; ring_buffer rx_buffer = { { 0 }, 0, 0 }; ring_buffer tx_buffer = { { 0 }, 0, 0 }; #ifdef SERIAL1_AVAILABLE ring_buffer rx_buffer1 = { { 0 }, 0, 0 }; ring_buffer tx_buffer1 = { { 0 }, 0, 0 }; #endif inline void store_char(unsigned char c, ring_buffer *buffer) { unsigned int i = (unsigned int)(buffer->head + 1) % SERIAL_BUFFER_SIZE; // if we should be storing the received character into the location // just before the tail (meaning that the head would advance to the // current location of the tail), we're about to overflow the buffer // and so we don't write the character or advance the head. if (i != buffer->tail) { buffer->buffer[buffer->head] = c; buffer->head = i; } } void serialEvent() __attribute__((weak)); void serialEvent() {} #ifdef SERIAL1_AVAILABLE void serialEvent1() __attribute__((weak)); void serialEvent1() {} #endif void serialEventRun(void) { if (Serial.available()) serialEvent(); #ifdef SERIAL1_AVAILABLE if (Serial1.available()) serialEvent1(); #endif } // Public Methods ////////////////////////////////////////////////////////////// #define SMCLK F_CPU //SMCLK = F_CPU for now void HardwareSerial::begin(unsigned long baud) { unsigned int mod, divider; unsigned char oversampling; /* Calling this dummy function prevents the linker * from stripping the USCI interupt vectors.*/ usci_isr_install(); if (SMCLK/baud>=48) { // requires SMCLK for oversampling oversampling = 1; } else { oversampling= 0; } divider=(SMCLK<<4)/baud; pinMode_int(rxPin, rxPinMode); pinMode_int(txPin, txPinMode); delay(10); *(&(UCAxCTL1) + uartOffset) = UCSWRST; *(&(UCAxCTL1) + uartOffset) = UCSSEL_2; // SMCLK *(&(UCAxCTL0) + uartOffset) = 0; *(&(UCAxABCTL) + uartOffset) = 0; #if defined(__MSP430_HAS_EUSCI_A0__) if(!oversampling) { mod = ((divider&0xF)+1)&0xE; // UCBRSx (bit 1-3) divider >>=4; } else { mod = divider&0xFFF0; // UCBRFx = INT([(N/16) INT(N/16)] 16) divider>>=8; } *(&(UCAxBR0) + uartOffset) = divider; *(&(UCAxBR1) + uartOffset) = divider>>8; *(&(UCAxMCTLW) + uartOffset)= (oversampling ? UCOS16:0) | mod; #else if(!oversampling) { mod = ((divider&0xF)+1)&0xE; // UCBRSx (bit 1-3) divider >>=4; } else { mod = ((divider&0xf8)+0x8)&0xf0; // UCBRFx (bit 4-7) divider>>=8; } *(&(UCAxBR0) + uartOffset)= divider; *(&(UCAxBR1) + uartOffset) = divider>>8; *(&(UCAxMCTL) + uartOffset) = (unsigned char)(oversampling ? UCOS16:0) | mod; #endif *(&(UCAxCTL1) + uartOffset) &= ~UCSWRST; #if defined(__MSP430_HAS_USCI_A0__) || defined(__MSP430_HAS_USCI_A1__) || defined(__MSP430_HAS_EUSCI_A0__) *(&(UCAxIE) + uartOffset) |= UCRXIE; #else *(&(UC0IE) + uartOffset) |= UCA0RXIE; #endif } void HardwareSerial::end() { // wait for transmission of outgoing data while (_tx_buffer->head != _tx_buffer->tail); _rx_buffer->head = _rx_buffer->tail; } int HardwareSerial::available(void) { return (unsigned int)(SERIAL_BUFFER_SIZE + _rx_buffer->head - _rx_buffer->tail) % SERIAL_BUFFER_SIZE; } int HardwareSerial::peek(void) { if (_rx_buffer->head == _rx_buffer->tail) { return -1; } else { return _rx_buffer->buffer[_rx_buffer->tail]; } } int HardwareSerial::read(void) { // if the head isn't ahead of the tail, we don't have any characters if (_rx_buffer->head == _rx_buffer->tail) { return -1; } else { unsigned char c = _rx_buffer->buffer[_rx_buffer->tail]; _rx_buffer->tail = (unsigned int)(_rx_buffer->tail + 1) % SERIAL_BUFFER_SIZE; return c; } } void HardwareSerial::flush() { while (_tx_buffer->head != _tx_buffer->tail); } size_t HardwareSerial::write(uint8_t c) { unsigned int i = (_tx_buffer->head + 1) % SERIAL_BUFFER_SIZE; // If the output buffer is full, there's nothing for it other than to // wait for the interrupt handler to empty it a bit // ???: return 0 here instead? while (i == _tx_buffer->tail); _tx_buffer->buffer[_tx_buffer->head] = c; _tx_buffer->head = i; #if defined(__MSP430_HAS_USCI_A0__) || defined(__MSP430_HAS_USCI_A1__) || defined(__MSP430_HAS_EUSCI_A0__) *(&(UCAxIE) + uartOffset) |= UCTXIE; #else *(&(UC0IE) + uartOffset) |= UCA0TXIE; #endif return 1; } HardwareSerial::operator bool() { return true; } void uart_rx_isr(uint8_t offset) { #ifdef SERIAL1_AVAILABLE /* Debug uart aka Serial always gets rx_buffer and aux aka Serial1 gets rx_buffer1 */ ring_buffer *rx_buffer_ptr = (offset == DEBUG_UART_MODULE_OFFSET) ? &rx_buffer:&rx_buffer1; #else ring_buffer *rx_buffer_ptr = &rx_buffer; #endif unsigned char c = *(&(UCAxRXBUF) + offset); store_char(c, rx_buffer_ptr); } void uart_tx_isr(uint8_t offset) { #ifdef SERIAL1_AVAILABLE /* Debug uart aka Serial always gets rx_buffer and aux aka Serial1 gets rx_buffer1 */ ring_buffer *tx_buffer_ptr = (offset == DEBUG_UART_MODULE_OFFSET) ? &tx_buffer : &tx_buffer1; #else ring_buffer *tx_buffer_ptr = &tx_buffer; #endif if (tx_buffer_ptr->head == tx_buffer_ptr->tail) { // Buffer empty, so disable interrupts #if defined(__MSP430_HAS_USCI_A0__) || defined(__MSP430_HAS_USCI_A1__) || defined(__MSP430_HAS_EUSCI_A0__) *(&(UCAxIE) + offset) &= ~UCTXIE; *(&(UCAxIFG) + offset) |= UCTXIFG; // Set Flag again #else *(&(UC0IE) + offset) &= ~UCA0TXIE; #endif return; } unsigned char c = tx_buffer_ptr->buffer[tx_buffer_ptr->tail]; tx_buffer_ptr->tail = (tx_buffer_ptr->tail + 1) % SERIAL_BUFFER_SIZE; *(&(UCAxTXBUF) + offset) = c; } // Preinstantiate Objects ////////////////////////////////////////////////////// HardwareSerial Serial(&rx_buffer, &tx_buffer, DEBUG_UART_MODULE_OFFSET, DEBUG_UARTRXD_SET_MODE, DEBUG_UARTTXD_SET_MODE, DEBUG_UARTRXD, DEBUG_UARTTXD); #ifdef SERIAL1_AVAILABLE HardwareSerial Serial1(&rx_buffer1, &tx_buffer1, AUX_UART_MODULE_OFFSET, AUX_UARTRXD_SET_MODE, DEBUG_UARTTXD_SET_MODE, AUX_UARTRXD, AUX_UARTTXD); #endif #endif <commit_msg>Revert "Fix UART initial characters are garbage for G2 and F5529 #293"<commit_after>/* ************************************************************************ * HardwareSerial.cpp * * Arduino core files for MSP430 * Copyright (c) 2012 Robert Wessels. All right reserved. * * *********************************************************************** Derived from: HardwareSerial.cpp - Hardware serial library for Wiring Copyright (c) 2006 Nicholas Zambetti. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.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 Modified 23 November 2006 by David A. Mellis Modified 28 September 2010 by Mark Sproul */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <inttypes.h> #include "Energia.h" #include "wiring_private.h" #include "usci_isr_handler.h" #if defined(__MSP430_HAS_USCI__) || defined(__MSP430_HAS_USCI_A0__) || defined(__MSP430_HAS_USCI_A1__) || defined(__MSP430_HAS_EUSCI_A0__) #include "HardwareSerial.h" #define UCAxCTLW0 UCA0CTLW0 #define UCAxCTL0 UCA0CTL0 #define UCAxCTL1 UCA0CTL1 #define UCAxBRW UCA0BRW #define UCAxBR0 UCA0BR0 #define UCAxBR1 UCA0BR1 #define UCAxMCTL UCA0MCTL #define UCAxMCTLW UCA0MCTLW #define UCAxSTAT UCA0STAT #define UCAxRXBUF UCA0RXBUF #define UCAxTXBUF UCA0TXBUF #define UCAxABCTL UCA0ABCTL #define UCAxIRCTL UCA0IRCTL #define UCAxIRTCTL UCA0IRTCTL #define UCAxIRRCTL UCA0IRRCTL #define UCAxICTL UCA0ICTL #define UCAxIE UCA0IE #define UCAxIFG UCA0IFG #define UCAxIV UCA0IV #define SERIAL_BUFFER_SIZE 16 struct ring_buffer { unsigned char buffer[SERIAL_BUFFER_SIZE]; volatile unsigned int head; volatile unsigned int tail; }; ring_buffer rx_buffer = { { 0 }, 0, 0 }; ring_buffer tx_buffer = { { 0 }, 0, 0 }; #ifdef SERIAL1_AVAILABLE ring_buffer rx_buffer1 = { { 0 }, 0, 0 }; ring_buffer tx_buffer1 = { { 0 }, 0, 0 }; #endif inline void store_char(unsigned char c, ring_buffer *buffer) { unsigned int i = (unsigned int)(buffer->head + 1) % SERIAL_BUFFER_SIZE; // if we should be storing the received character into the location // just before the tail (meaning that the head would advance to the // current location of the tail), we're about to overflow the buffer // and so we don't write the character or advance the head. if (i != buffer->tail) { buffer->buffer[buffer->head] = c; buffer->head = i; } } void serialEvent() __attribute__((weak)); void serialEvent() {} #ifdef SERIAL1_AVAILABLE void serialEvent1() __attribute__((weak)); void serialEvent1() {} #endif void serialEventRun(void) { if (Serial.available()) serialEvent(); #ifdef SERIAL1_AVAILABLE if (Serial1.available()) serialEvent1(); #endif } // Public Methods ////////////////////////////////////////////////////////////// #define SMCLK F_CPU //SMCLK = F_CPU for now void HardwareSerial::begin(unsigned long baud) { unsigned int mod, divider; unsigned char oversampling; /* Calling this dummy function prevents the linker * from stripping the USCI interupt vectors.*/ usci_isr_install(); if (SMCLK/baud>=48) { // requires SMCLK for oversampling oversampling = 1; } else { oversampling= 0; } divider=(SMCLK<<4)/baud; pinMode_int(rxPin, rxPinMode); pinMode_int(txPin, txPinMode); *(&(UCAxCTL1) + uartOffset) = UCSWRST; *(&(UCAxCTL1) + uartOffset) = UCSSEL_2; // SMCLK *(&(UCAxCTL0) + uartOffset) = 0; *(&(UCAxABCTL) + uartOffset) = 0; #if defined(__MSP430_HAS_EUSCI_A0__) if(!oversampling) { mod = ((divider&0xF)+1)&0xE; // UCBRSx (bit 1-3) divider >>=4; } else { mod = divider&0xFFF0; // UCBRFx = INT([(N/16) INT(N/16)] 16) divider>>=8; } *(&(UCAxBR0) + uartOffset) = divider; *(&(UCAxBR1) + uartOffset) = divider>>8; *(&(UCAxMCTLW) + uartOffset)= (oversampling ? UCOS16:0) | mod; #else if(!oversampling) { mod = ((divider&0xF)+1)&0xE; // UCBRSx (bit 1-3) divider >>=4; } else { mod = ((divider&0xf8)+0x8)&0xf0; // UCBRFx (bit 4-7) divider>>=8; } *(&(UCAxBR0) + uartOffset)= divider; *(&(UCAxBR1) + uartOffset) = divider>>8; *(&(UCAxMCTL) + uartOffset) = (unsigned char)(oversampling ? UCOS16:0) | mod; #endif *(&(UCAxCTL1) + uartOffset) &= ~UCSWRST; #if defined(__MSP430_HAS_USCI_A0__) || defined(__MSP430_HAS_USCI_A1__) || defined(__MSP430_HAS_EUSCI_A0__) *(&(UCAxIE) + uartOffset) |= UCRXIE; #else *(&(UC0IE) + uartOffset) |= UCA0RXIE; #endif } void HardwareSerial::end() { // wait for transmission of outgoing data while (_tx_buffer->head != _tx_buffer->tail); _rx_buffer->head = _rx_buffer->tail; } int HardwareSerial::available(void) { return (unsigned int)(SERIAL_BUFFER_SIZE + _rx_buffer->head - _rx_buffer->tail) % SERIAL_BUFFER_SIZE; } int HardwareSerial::peek(void) { if (_rx_buffer->head == _rx_buffer->tail) { return -1; } else { return _rx_buffer->buffer[_rx_buffer->tail]; } } int HardwareSerial::read(void) { // if the head isn't ahead of the tail, we don't have any characters if (_rx_buffer->head == _rx_buffer->tail) { return -1; } else { unsigned char c = _rx_buffer->buffer[_rx_buffer->tail]; _rx_buffer->tail = (unsigned int)(_rx_buffer->tail + 1) % SERIAL_BUFFER_SIZE; return c; } } void HardwareSerial::flush() { while (_tx_buffer->head != _tx_buffer->tail); } size_t HardwareSerial::write(uint8_t c) { unsigned int i = (_tx_buffer->head + 1) % SERIAL_BUFFER_SIZE; // If the output buffer is full, there's nothing for it other than to // wait for the interrupt handler to empty it a bit // ???: return 0 here instead? while (i == _tx_buffer->tail); _tx_buffer->buffer[_tx_buffer->head] = c; _tx_buffer->head = i; #if defined(__MSP430_HAS_USCI_A0__) || defined(__MSP430_HAS_USCI_A1__) || defined(__MSP430_HAS_EUSCI_A0__) *(&(UCAxIE) + uartOffset) |= UCTXIE; #else *(&(UC0IE) + uartOffset) |= UCA0TXIE; #endif return 1; } HardwareSerial::operator bool() { return true; } void uart_rx_isr(uint8_t offset) { #ifdef SERIAL1_AVAILABLE /* Debug uart aka Serial always gets rx_buffer and aux aka Serial1 gets rx_buffer1 */ ring_buffer *rx_buffer_ptr = (offset == DEBUG_UART_MODULE_OFFSET) ? &rx_buffer:&rx_buffer1; #else ring_buffer *rx_buffer_ptr = &rx_buffer; #endif unsigned char c = *(&(UCAxRXBUF) + offset); store_char(c, rx_buffer_ptr); } void uart_tx_isr(uint8_t offset) { #ifdef SERIAL1_AVAILABLE /* Debug uart aka Serial always gets rx_buffer and aux aka Serial1 gets rx_buffer1 */ ring_buffer *tx_buffer_ptr = (offset == DEBUG_UART_MODULE_OFFSET) ? &tx_buffer : &tx_buffer1; #else ring_buffer *tx_buffer_ptr = &tx_buffer; #endif if (tx_buffer_ptr->head == tx_buffer_ptr->tail) { // Buffer empty, so disable interrupts #if defined(__MSP430_HAS_USCI_A0__) || defined(__MSP430_HAS_USCI_A1__) || defined(__MSP430_HAS_EUSCI_A0__) *(&(UCAxIE) + offset) &= ~UCTXIE; *(&(UCAxIFG) + offset) |= UCTXIFG; // Set Flag again #else *(&(UC0IE) + offset) &= ~UCA0TXIE; #endif return; } unsigned char c = tx_buffer_ptr->buffer[tx_buffer_ptr->tail]; tx_buffer_ptr->tail = (tx_buffer_ptr->tail + 1) % SERIAL_BUFFER_SIZE; *(&(UCAxTXBUF) + offset) = c; } // Preinstantiate Objects ////////////////////////////////////////////////////// HardwareSerial Serial(&rx_buffer, &tx_buffer, DEBUG_UART_MODULE_OFFSET, DEBUG_UARTRXD_SET_MODE, DEBUG_UARTTXD_SET_MODE, DEBUG_UARTRXD, DEBUG_UARTTXD); #ifdef SERIAL1_AVAILABLE HardwareSerial Serial1(&rx_buffer1, &tx_buffer1, AUX_UART_MODULE_OFFSET, AUX_UARTRXD_SET_MODE, DEBUG_UARTTXD_SET_MODE, AUX_UARTRXD, AUX_UARTTXD); #endif #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: ignoreWidth.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2003-04-28 16:53:09 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ // prevent internal compiler error with MSVC6SP3 #include <utility> #define TRANSLITERATION_Width #include <transliteration_Ignore.hxx> #define TRANSLITERATION_fullwidthToHalfwidth #define TRANSLITERATION_halfwidthToFullwidth #include <transliteration_OneToOne.hxx> using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace rtl; namespace com { namespace sun { namespace star { namespace i18n { OUString SAL_CALL ignoreWidth::folding( const OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, Sequence< sal_Int32 >& offset ) throw(RuntimeException) { fullwidthToHalfwidth t1; return t1.transliterate(inStr, startPos, nCount, offset); } Sequence< OUString > SAL_CALL ignoreWidth::transliterateRange( const OUString& str1, const OUString& str2 ) throw(RuntimeException) { halfwidthToFullwidth t1; fullwidthToHalfwidth t2; return transliteration_Ignore::transliterateRange(str1, str2, t1, t2); } sal_Unicode SAL_CALL ignoreWidth::transliterateChar2Char( sal_Unicode inChar) throw(RuntimeException, MultipleCharsOutputException) { fullwidthToHalfwidth t1; return t1.transliterateChar2Char(inChar); } } } } } <commit_msg>INTEGRATION: CWS i18n11 (1.7.70); FILE MERGED 2004/01/06 22:30:47 khong 1.7.70.1: #105745# #107978# #109715# #110835# #112014# #112068# #112094# #112102# #112282# fix Japanese ambiguous search problems<commit_after>/************************************************************************* * * $RCSfile: ignoreWidth.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: obo $ $Date: 2004-03-17 09:03:48 $ * * 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): _______________________________________ * * ************************************************************************/ // prevent internal compiler error with MSVC6SP3 #include <utility> #define TRANSLITERATION_Width #include <transliteration_Ignore.hxx> #define TRANSLITERATION_fullwidthToHalfwidth #define TRANSLITERATION_halfwidthToFullwidth #include <transliteration_OneToOne.hxx> using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace rtl; namespace com { namespace sun { namespace star { namespace i18n { OUString SAL_CALL ignoreWidth::folding( const OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, Sequence< sal_Int32 >& offset ) throw(RuntimeException) { halfwidthToFullwidth t1; return t1.transliterate(inStr, startPos, nCount, offset); } Sequence< OUString > SAL_CALL ignoreWidth::transliterateRange( const OUString& str1, const OUString& str2 ) throw(RuntimeException) { halfwidthToFullwidth t1; fullwidthToHalfwidth t2; return transliteration_Ignore::transliterateRange(str1, str2, t1, t2); } sal_Unicode SAL_CALL ignoreWidth::transliterateChar2Char( sal_Unicode inChar) throw(RuntimeException, MultipleCharsOutputException) { halfwidthToFullwidth t1; return t1.transliterateChar2Char(inChar); } } } } } <|endoftext|>
<commit_before>#include <node.h> #include <v8.h> #include <dns_sd.h> #include <mutex> #include <map> using namespace v8; using namespace node; using namespace std; Persistent<Function> AdvertisementConstructor; Persistent<Function> BrowserConstructor; map<DNSServiceRef volatile *, Local<Object> > refMap; void NewAdvertisement(const FunctionCallbackInfo<Value> &args) { auto isolate = Isolate::GetCurrent(); if (args.IsConstructCall()) { auto volatile ref = new DNSServiceRef; DNSServiceRegister(ref, 0, 0, NULL, *String::Utf8Value(args[0]->ToString()), NULL, NULL, args[1]->Int32Value(), 0, NULL, NULL, NULL); args.This()->SetAlignedPointerInInternalField(0, ref); args.This()->Set(String::NewSymbol("service"), args[0]->ToString(), ReadOnly); args.This()->Set(String::NewSymbol("port"), Number::New(args[1]->Int32Value()), ReadOnly); args.This()->Set(String::NewSymbol("advertising"), True(isolate), ReadOnly); args.GetReturnValue().Set(args.This()); } else { auto cons = Local<Function>::New(isolate, AdvertisementConstructor); args.GetReturnValue().Set(cons->NewInstance(2, (Local<Value>[]){ args[0], args[1] })); } } void NewBrowser(const FunctionCallbackInfo<Value> &args) { auto isolate = Isolate::GetCurrent(); if (args.IsConstructCall()) { auto volatile ref = new DNSServiceRef; DNSServiceBrowse(ref, 0, 0, *String::Utf8Value(args[0]->ToString()), NULL, [](DNSServiceRef sdRef, DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceErrorType errorCode, const char *serviceName, const char *regtype, const char *replyDomain, void *context) { auto isolate = Isolate::GetCurrent(); auto tpl = FunctionTemplate::New(); tpl->SetClassName(String::NewFromUtf8(isolate, "DNSServiceBrowserReply")); tpl->InstanceTemplate()->SetInternalFieldCount(0); auto ret = tpl->InstanceTemplate()->NewInstance(); auto type = ""; if (flags & kDNSServiceFlagsAdd) type = "found"; else type = "lost"; ret->Set(String::NewSymbol("type"), String::NewFromUtf8(isolate, type)); ret->Set(String::NewSymbol("host"), String::NewFromUtf8(isolate, serviceName)); ret->Set(String::NewSymbol("service"), String::NewFromUtf8(isolate, regtype)); MakeCallback(refMap[&sdRef], "emit", 2, (Local<Value>[]){ String::NewFromUtf8(isolate, type), ret }); }, NULL); args.This()->SetAlignedPointerInInternalField(0, ref); args.This()->Set(String::NewSymbol("service"), args[0]->ToString(), ReadOnly); args.This()->Set(String::NewSymbol("listening"), True(isolate), ReadOnly); args.This()->Set(String::NewSymbol("sockFd"), Integer::New(DNSServiceRefSockFD(*ref)), ReadOnly); NODE_SET_METHOD(args.This(), "processResult", [](const FunctionCallbackInfo<Value> &args){ auto isolate = Isolate::GetCurrent(); auto ref = (DNSServiceRef *)args.Holder()->GetAlignedPointerFromInternalField(0); if (ref) { DNSServiceProcessResult(*ref); args.GetReturnValue().Set(args.Holder()); } else { ThrowException(Exception::ReferenceError(String::NewFromUtf8(isolate, "Invoked processResult on terminated browser"))); } }); NODE_SET_METHOD(args.This(), "removeInits", [](const FunctionCallbackInfo<Value> &args){ auto isolate = Isolate::GetCurrent(); if (args.Holder()->Has(String::NewSymbol("removeInits"))) { args.Holder()->ForceDelete(String::NewSymbol("sockFd")); args.Holder()->ForceDelete(String::NewSymbol("processResult")); args.Holder()->ForceDelete(String::NewSymbol("removeInits")); args.GetReturnValue().Set(args.Holder()); } else { ThrowException(Exception::ReferenceError(String::NewFromUtf8(isolate, "Inits already removed"))); } }); refMap[ref] = Local<Object>::New(isolate, args.This()); args.GetReturnValue().Set(args.This()); } else { auto cons = Local<Function>::New(isolate, BrowserConstructor); args.GetReturnValue().Set(cons->NewInstance(2, (Local<Value>[]){ args[0], args[1] })); }} void Terminate(const FunctionCallbackInfo<Value> &args) { auto isolate = Isolate::GetCurrent(); auto ref = (DNSServiceRef *)args.Holder()->GetAlignedPointerFromInternalField(0); if (ref) { assert(ref != NULL); DNSServiceRefDeallocate(*ref); delete ref; args.Holder()->SetAlignedPointerInInternalField(0, NULL); if (args.Holder()->GetConstructorName()->Equals(String::NewFromUtf8(isolate, "DNSServiceAdvertisement"))) args.Holder()->ForceSet(String::NewSymbol("advertising"), False(isolate), ReadOnly); else if (args.Holder()->GetConstructorName()->Equals(String::NewFromUtf8(isolate, "DNSServiceBrowser"))) args.Holder()->ForceSet(String::NewSymbol("listening"), False(isolate), ReadOnly); else ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Terminate called on object of unknown type"))); args.GetReturnValue().Set(args.Holder()); } else { if (args.Holder()->GetConstructorName()->Equals(String::NewFromUtf8(isolate, "DNSServiceAdvertisement"))) ThrowException(Exception::ReferenceError(String::NewFromUtf8(isolate, "Advertisement already terminated"))); else if (args.Holder()->GetConstructorName()->Equals(String::NewFromUtf8(isolate, "DNSServiceBrowser"))) ThrowException(Exception::ReferenceError(String::NewFromUtf8(isolate, "Browser already terminated"))); else ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Terminate called on object of unknown type with no internal ref"))); } } void init(Handle<Object> exports) { auto isolate = Isolate::GetCurrent(); // Initializing Advertisement { auto tpl = FunctionTemplate::New(NewAdvertisement); tpl->SetClassName(String::NewFromUtf8(isolate, "DNSServiceAdvertisement")); tpl->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(tpl, "terminate", Terminate); AdvertisementConstructor.Reset(isolate, tpl->GetFunction()); NODE_SET_METHOD(exports, "DNSServiceAdvertisement", NewAdvertisement); } // Initializing Browser { auto tpl = FunctionTemplate::New(NewBrowser); tpl->SetClassName(String::NewFromUtf8(isolate, "DNSServiceBrowser")); tpl->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(tpl, "terminate", Terminate); BrowserConstructor.Reset(isolate, tpl->GetFunction()); NODE_SET_METHOD(exports, "DNSServiceBrowser", NewBrowser); } } NODE_MODULE(dns_sd, init)<commit_msg>Still working..<commit_after>#include <node.h> #include <v8.h> #include <dns_sd.h> #include <mutex> #include <map> using namespace v8; using namespace node; using namespace std; Persistent<Function> AdvertisementConstructor; Persistent<Function> BrowserConstructor; Persistent<Function> Require; map<DNSServiceRef volatile *, Local<Object> > refMap; void NewAdvertisement(const FunctionCallbackInfo<Value> &args) { auto isolate = Isolate::GetCurrent(); if (args.IsConstructCall()) { auto volatile ref = new DNSServiceRef; DNSServiceRegister(ref, 0, 0, NULL, *String::Utf8Value(args[0]->ToString()), NULL, NULL, args[1]->Int32Value(), 0, NULL, NULL, NULL); args.This()->SetAlignedPointerInInternalField(args.This()->InternalFieldCount() - 1, ref); args.This()->Set(String::NewSymbol("service"), args[0]->ToString(), ReadOnly); args.This()->Set(String::NewSymbol("port"), Number::New(args[1]->Int32Value()), ReadOnly); args.This()->Set(String::NewSymbol("advertising"), True(isolate), ReadOnly); args.GetReturnValue().Set(args.This()); } else { auto cons = Local<Function>::New(isolate, AdvertisementConstructor); args.GetReturnValue().Set(cons->NewInstance(2, (Local<Value>[]){ args[0], args[1] })); } } void NewBrowser(const FunctionCallbackInfo<Value> &args) { auto isolate = Isolate::GetCurrent(); if (args.IsConstructCall()) { auto volatile ref = new DNSServiceRef; auto Socket = Local<Function>::Cast(Local<Function>::New(isolate, Require)->Call(Null(isolate), 1, (Local<Value>[]){ String::NewFromUtf8("Socket") })); DNSServiceBrowse(ref, 0, 0, *String::Utf8Value(args[0]->ToString()), NULL, [](DNSServiceRef sdRef, DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceErrorType errorCode, const char *serviceName, const char *regtype, const char *replyDomain, void *context) { auto isolate = Isolate::GetCurrent(); auto tpl = FunctionTemplate::New(); tpl->SetClassName(String::NewFromUtf8(isolate, "DNSServiceBrowserReply")); tpl->InstanceTemplate()->SetInternalFieldCount(0); auto ret = tpl->InstanceTemplate()->NewInstance(); auto type = ""; if (flags & kDNSServiceFlagsAdd) type = "found"; else type = "lost"; ret->Set(String::NewSymbol("type"), String::NewFromUtf8(isolate, type)); ret->Set(String::NewSymbol("host"), String::NewFromUtf8(isolate, serviceName)); ret->Set(String::NewSymbol("service"), String::NewFromUtf8(isolate, regtype)); MakeCallback(refMap[&sdRef], "emit", 2, (Local<Value>[]){ String::NewFromUtf8(isolate, type), ret }); }, NULL); auto opts = Object::New(); opts->Set(String::NewSymbol("fd"), Integer::New(DNSServiceRefSockFD(*ref))); auto socket = Socket->NewInstance(1, (Local<Value>[]){ opts }); //... args.This()->SetAlignedPointerInInternalField(args.This()->InternalFieldCount() - 1, ref); args.This()->Set(String::NewSymbol("service"), args[0]->ToString(), ReadOnly); args.This()->Set(String::NewSymbol("listening"), True(isolate), ReadOnly); NODE_SET_METHOD(args.This(), "processResult", [](const FunctionCallbackInfo<Value> &args) { auto isolate = Isolate::GetCurrent(); auto ref = (DNSServiceRef *)args.Holder()->GetAlignedPointerFromInternalField(0); if (ref) { DNSServiceProcessResult(*ref); args.GetReturnValue().Set(args.Holder()); } else { ThrowException(Exception::ReferenceError(String::NewFromUtf8(isolate, "Invoked processResult on terminated browser"))); } }); NODE_SET_METHOD(args.This(), "removeInits", [](const FunctionCallbackInfo<Value> &args) { auto isolate = Isolate::GetCurrent(); if (args.Holder()->Has(String::NewSymbol("removeInits"))) { args.Holder()->ForceDelete(String::NewSymbol("sockFd")); args.Holder()->ForceDelete(String::NewSymbol("processResult")); args.Holder()->ForceDelete(String::NewSymbol("removeInits")); args.GetReturnValue().Set(args.Holder()); } else { ThrowException(Exception::ReferenceError(String::NewFromUtf8(isolate, "Inits already removed"))); } }); refMap[ref] = Local<Object>::New(isolate, args.This()); args.GetReturnValue().Set(args.This()); } else { auto cons = Local<Function>::New(isolate, BrowserConstructor); args.GetReturnValue().Set(cons->NewInstance(2, (Local<Value>[]){ args[0], args[1] })); }} void Terminate(const FunctionCallbackInfo<Value> &args) { auto isolate = Isolate::GetCurrent(); auto ref = (DNSServiceRef *)args.Holder()->GetAlignedPointerFromInternalField(args.Holder()->InternalFieldCount() - 1); if (ref) { assert(ref != NULL); DNSServiceRefDeallocate(*ref); delete ref; args.Holder()->SetAlignedPointerInInternalField(args.Holder()->InternalFieldCount() - 1, NULL); if (args.Holder()->GetConstructorName()->Equals(String::NewFromUtf8(isolate, "DNSServiceAdvertisement"))) args.Holder()->ForceSet(String::NewSymbol("advertising"), False(isolate), ReadOnly); else if (args.Holder()->GetConstructorName()->Equals(String::NewFromUtf8(isolate, "DNSServiceBrowser"))) args.Holder()->ForceSet(String::NewSymbol("listening"), False(isolate), ReadOnly); else ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Terminate called on object of unknown type"))); args.GetReturnValue().Set(args.Holder()); } else { if (args.Holder()->GetConstructorName()->Equals(String::NewFromUtf8(isolate, "DNSServiceAdvertisement"))) ThrowException(Exception::ReferenceError(String::NewFromUtf8(isolate, "Advertisement already terminated"))); else if (args.Holder()->GetConstructorName()->Equals(String::NewFromUtf8(isolate, "DNSServiceBrowser"))) ThrowException(Exception::ReferenceError(String::NewFromUtf8(isolate, "Browser already terminated"))); else ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Terminate called on object of unknown type with no internal ref"))); } } void init(Handle<Object> exports) { // Get handle to require NODE_SET_METHOD(exports, "registerRequire", [](const FunctionCallbackInfo<Value> &args) { auto isolate = Isolate::GetCurrent(); Require.Reset(isolate, Local<Function>::Cast(args[0])); args.Holder()->ForceDelete(String::NewSymbol("registerRequire")); args.GetReturnValue().Set(args.Holder()); // Initializing Advertisement { auto tpl = FunctionTemplate::New(NewAdvertisement); tpl->SetClassName(String::NewFromUtf8(isolate, "DNSServiceAdvertisement")); tpl->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(tpl, "terminate", Terminate); AdvertisementConstructor.Reset(isolate, tpl->GetFunction()); NODE_SET_METHOD(args.Holder(), "DNSServiceAdvertisement", NewAdvertisement); } // Initializing Browser { auto tpl = FunctionTemplate::New(NewBrowser); auto require = Local<Function>::New(isolate, Require); auto inherits = Local<Function>::Cast(Local<Object>::Cast(require->Call(Null(isolate), 1, (Local<Value>[]){ String::NewFromUtf8(isolate, "util") }))->Get(String::NewSymbol("inherits"))); auto EventEmitter = Local<Function>::Cast(Local<Object>::Cast(require->Call(Null(isolate), 1, (Local<Value>[]){ String::NewFromUtf8(isolate, "events") }))->Get(String::NewSymbol("EventEmitter"))); auto tempEventEmitter = EventEmitter->NewInstance(); tpl->SetClassName(String::NewFromUtf8(isolate, "DNSServiceBrowser")); tpl->InstanceTemplate()->SetInternalFieldCount(tempEventEmitter->InternalFieldCount() + 1); NODE_SET_PROTOTYPE_METHOD(tpl, "terminate", Terminate); auto ConstructorFunc = tpl->GetFunction(); inherits->Call(Null(isolate), 2, (Local<Value>[]){ ConstructorFunc, EventEmitter }); BrowserConstructor.Reset(isolate, ConstructorFunc); NODE_SET_METHOD(args.Holder(), "DNSServiceBrowser", NewBrowser); } }); } NODE_MODULE(dns_sd, init)<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: KColumns.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2006-09-17 02:51:26 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_connectivity.hxx" #include "KColumns.hxx" #ifndef _CONNECTIVITY_KAB_TABLE_HXX_ #include "KTable.hxx" #endif #ifndef _CONNECTIVITY_KAB_TABLES_HXX_ #include "KTables.hxx" #endif #ifndef _CONNECTIVITY_KAB_CATALOG_HXX_ #include "KCatalog.hxx" #endif #ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_ #include "connectivity/sdbcx/VColumn.hxx" #endif using namespace connectivity::kab; using namespace connectivity::sdbcx; using namespace connectivity; using namespace ::comphelper; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; // ------------------------------------------------------------------------- sdbcx::ObjectType KabColumns::createObject(const ::rtl::OUString& _rName) { Reference< XResultSet > xResult = m_pTable->getConnection()->getMetaData()->getColumns( Any(), m_pTable->getSchema(), m_pTable->getTableName(), _rName); sdbcx::ObjectType xRet = NULL; if (xResult.is()) { Reference< XRow > xRow(xResult,UNO_QUERY); while (xResult->next()) { if (xRow->getString(4) == _rName) { OColumn* pRet = new OColumn( _rName, xRow->getString(6), xRow->getString(13), xRow->getInt(11), xRow->getInt(7), xRow->getInt(9), xRow->getInt(5), sal_False, sal_False, sal_False, sal_True); xRet = pRet; break; } } } return xRet; } // ------------------------------------------------------------------------- void KabColumns::impl_refresh() throw(RuntimeException) { m_pTable->refreshColumns(); } // ------------------------------------------------------------------------- KabColumns::KabColumns( KabTable* _pTable, ::osl::Mutex& _rMutex, const TStringVector &_rVector) : sdbcx::OCollection(*_pTable, sal_True, _rMutex, _rVector), m_pTable(_pTable) { } <commit_msg>INTEGRATION: CWS changefileheader (1.3.216); FILE MERGED 2008/04/01 10:53:06 thb 1.3.216.2: #i85898# Stripping all external header guards 2008/03/28 15:23:44 rt 1.3.216.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: KColumns.cxx,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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_connectivity.hxx" #include "KColumns.hxx" #include "KTable.hxx" #include "KTables.hxx" #include "KCatalog.hxx" #include "connectivity/sdbcx/VColumn.hxx" using namespace connectivity::kab; using namespace connectivity::sdbcx; using namespace connectivity; using namespace ::comphelper; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; // ------------------------------------------------------------------------- sdbcx::ObjectType KabColumns::createObject(const ::rtl::OUString& _rName) { Reference< XResultSet > xResult = m_pTable->getConnection()->getMetaData()->getColumns( Any(), m_pTable->getSchema(), m_pTable->getTableName(), _rName); sdbcx::ObjectType xRet = NULL; if (xResult.is()) { Reference< XRow > xRow(xResult,UNO_QUERY); while (xResult->next()) { if (xRow->getString(4) == _rName) { OColumn* pRet = new OColumn( _rName, xRow->getString(6), xRow->getString(13), xRow->getInt(11), xRow->getInt(7), xRow->getInt(9), xRow->getInt(5), sal_False, sal_False, sal_False, sal_True); xRet = pRet; break; } } } return xRet; } // ------------------------------------------------------------------------- void KabColumns::impl_refresh() throw(RuntimeException) { m_pTable->refreshColumns(); } // ------------------------------------------------------------------------- KabColumns::KabColumns( KabTable* _pTable, ::osl::Mutex& _rMutex, const TStringVector &_rVector) : sdbcx::OCollection(*_pTable, sal_True, _rMutex, _rVector), m_pTable(_pTable) { } <|endoftext|>
<commit_before>void sim(Int_t nev=1) { const char * kYear = "08" ; AliSimulation simu; simu.SetMakeSDigits("TRD TOF PHOS HMPID EMCAL MUON FMD PMD T0 ZDC VZERO"); simu.SetMakeDigits ("TRD TOF PHOS HMPID EMCAL MUON FMD PMD T0 ZDC VZERO"); simu.SetMakeDigitsFromHits("ITS TPC"); simu.SetWriteRawData("ALL","raw.root",kTRUE); // simu.SetDefaultStorage("alien://Folder=/alice/simulation/2007/PDC07_v4-09-Rev-00/Ideal/CDB/"); simu->SetDefaultStorage("local://$ALICE_ROOT"); simu.SetSpecificStorage("EMCAL/*","local://DB"); simu.SetQA(kTRUE) ; AliQA::SetQARefStorage(Form("%s%s/", AliQA::GetQARefDefaultStorage(), kYear)) ; AliQA::SetQARefDataDirName("Sim") ; //Data, Pedestals, BlackEvent, ..... TStopwatch timer; timer.Start(); simu.Run(nev); WriteXsection(); timer.Stop(); timer.Print(); } WriteXsection() { TPythia6 *pythia = TPythia6::Instance(); pythia->Pystat(1); Double_t xsection = pythia->GetPARI(1); Int_t ntrials = pythia->GetMSTI(5); TTree *tree = new TTree("Xsection","Pythia cross section"); TBranch *branch = tree->Branch("xsection", &xsection, "X/D"); TBranch *branch = tree->Branch("ntrials" , &ntrials , "X/i"); tree->Fill(); TFile *file = new TFile("pyxsec.root","recreate"); tree->Write(); file->Close(); cout << "Pythia cross section: " << xsection << ", number of trials: " << ntrials << endl; } <commit_msg>typo<commit_after>void sim(Int_t nev=1) { const char * kYear = "08" ; AliSimulation simu; simu.SetMakeSDigits("TRD TOF PHOS HMPID EMCAL MUON FMD PMD T0 ZDC VZERO"); simu.SetMakeDigits ("TRD TOF PHOS HMPID EMCAL MUON FMD PMD T0 ZDC VZERO"); simu.SetMakeDigitsFromHits("ITS TPC"); simu.SetWriteRawData("ALL","raw.root",kTRUE); // simu.SetDefaultStorage("alien://Folder=/alice/simulation/2007/PDC07_v4-09-Rev-00/Ideal/CDB/"); simu.SetDefaultStorage("local://$ALICE_ROOT"); simu.SetSpecificStorage("EMCAL/*","local://DB"); simu.SetRunQA("ALL:ALL") ; AliQA::SetQARefStorage(Form("%s%s/", AliQA::GetQARefDefaultStorage(), kYear)) ; AliQA::SetQARefDataDirName("Sim") ; //Data, Pedestals, BlackEvent, ..... TStopwatch timer; timer.Start(); simu.Run(nev); WriteXsection(); timer.Stop(); timer.Print(); } WriteXsection() { TPythia6 *pythia = TPythia6::Instance(); pythia->Pystat(1); Double_t xsection = pythia->GetPARI(1); Int_t ntrials = pythia->GetMSTI(5); TTree *tree = new TTree("Xsection","Pythia cross section"); TBranch *branch = tree->Branch("xsection", &xsection, "X/D"); TBranch *branch = tree->Branch("ntrials" , &ntrials , "X/i"); tree->Fill(); TFile *file = new TFile("pyxsec.root","recreate"); tree->Write(); file->Close(); cout << "Pythia cross section: " << xsection << ", number of trials: " << ntrials << endl; } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/public/common/context_menu_params.h" namespace content { const int32 CustomContextMenuContext::kCurrentRenderWidget = kint32max; CustomContextMenuContext::CustomContextMenuContext() : is_pepper_menu(false), request_id(0), render_widget_id(kCurrentRenderWidget) { } ContextMenuParams::ContextMenuParams() : media_type(blink::WebContextMenuData::MediaTypeNone), x(0), y(0), has_image_contents(true), frame_id(0), media_flags(0), misspelling_hash(0), speech_input_enabled(false), spellcheck_enabled(false), is_editable(false), writing_direction_default( blink::WebContextMenuData::CheckableMenuItemDisabled), writing_direction_left_to_right( blink::WebContextMenuData::CheckableMenuItemEnabled), writing_direction_right_to_left( blink::WebContextMenuData::CheckableMenuItemEnabled), edit_flags(0), referrer_policy(blink::WebReferrerPolicyDefault) { } ContextMenuParams::~ContextMenuParams() { } } // namespace content <commit_msg>Initialize all members of ContextMenuParams in the ctor<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/public/common/context_menu_params.h" namespace content { const int32 CustomContextMenuContext::kCurrentRenderWidget = kint32max; CustomContextMenuContext::CustomContextMenuContext() : is_pepper_menu(false), request_id(0), render_widget_id(kCurrentRenderWidget) { } ContextMenuParams::ContextMenuParams() : media_type(blink::WebContextMenuData::MediaTypeNone), x(0), y(0), has_image_contents(true), frame_id(0), media_flags(0), misspelling_hash(0), speech_input_enabled(false), spellcheck_enabled(false), is_editable(false), writing_direction_default( blink::WebContextMenuData::CheckableMenuItemDisabled), writing_direction_left_to_right( blink::WebContextMenuData::CheckableMenuItemEnabled), writing_direction_right_to_left( blink::WebContextMenuData::CheckableMenuItemEnabled), edit_flags(0), referrer_policy(blink::WebReferrerPolicyDefault), source_type(ui::MENU_SOURCE_NONE) { } ContextMenuParams::~ContextMenuParams() { } } // namespace content <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) 2016, Johan Mabille and Sylvain Corlay * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #ifndef XSIMD_NUMERICAL_CONSTANT_HPP #define XSIMD_NUMERICAL_CONSTANT_HPP #include <limits> #include "../types/xsimd_types_include.hpp" namespace xsimd { template <class T> constexpr T allbits() noexcept; template <class T> constexpr T infinity() noexcept; template <class T> constexpr T invlog_2() noexcept; template <class T> constexpr T invlog_2hi() noexcept; template <class T> constexpr T invlog_2lo() noexcept; template <class T> constexpr T invlog10_2() noexcept; template <class T> constexpr T log_2() noexcept; template <class T> constexpr T log_2hi() noexcept; template <class T> constexpr T log_2lo() noexcept; template <class T> constexpr T log10_2hi() noexcept; template <class T> constexpr T log10_2lo() noexcept; template <class T> constexpr T logeps() noexcept; template <class T> constexpr as_integer_t<T> maxexponent() noexcept; template <class T> constexpr T maxflint() noexcept; template <class T> constexpr T maxlog() noexcept; template <class T> constexpr T maxlog2() noexcept; template <class T> constexpr T maxlog10() noexcept; template <class T> constexpr T minlog() noexcept; template <class T> constexpr T minlog2() noexcept; template <class T> constexpr T minlog10() noexcept; template <class T> constexpr T minusinfinity() noexcept; template <class T> constexpr T minuszero() noexcept; template <class T> constexpr T nan() noexcept; template <class T> constexpr int32_t nmb() noexcept; template <class T> constexpr T smallestposval() noexcept; template <class T> constexpr T twotonmb() noexcept; /************************** * allbits implementation * **************************/ namespace detail { template <class T, bool = std::is_integral<T>::value> struct allbits_impl { static constexpr T get_value() noexcept { return T(~0); } }; template <class T> struct allbits_impl<T, false> { static constexpr T get_value() noexcept { return nan<T>(); } }; } template <class T> constexpr T allbits() noexcept { return T(detail::allbits_impl<typename T::value_type>::get_value()); } /*************************** * infinity implementation * ***************************/ template <class T> constexpr T infinity() noexcept { return T(infinity<typename T::value_type>()); } template <> constexpr float infinity<float>() noexcept { return std::numeric_limits<float>::infinity(); } template <> constexpr double infinity<double>() noexcept { return std::numeric_limits<double>::infinity(); } /*************************** * invlog_2 implementation * ***************************/ template <class T> constexpr T invlog_2() noexcept { return T(invlog_2<typename T::value_type>()); } template <> constexpr float invlog_2<float>() noexcept { return float(1.442695040888963407359924681001892137426645954152986); } template <> constexpr double invlog_2<double>() noexcept { return double(1.442695040888963407359924681001892137426645954152986); } /***************************** * invlog_2hi implementation * *****************************/ template <class T> constexpr T invlog_2hi() noexcept { return T(invlog_2hi<typename T::value_type>()); } template <> constexpr float invlog_2hi<float>() noexcept { return detail::caster32_t(0x3fb8b000U).f; } template <> constexpr double invlog_2hi<double>() noexcept { return detail::caster64_t(uint64_t(0x3ff7154765200000U)).f; } /***************************** * invlog_2lo implementation * *****************************/ template <class T> constexpr T invlog_2lo() noexcept { return T(invlog_2lo<typename T::value_type>()); } template <> constexpr float invlog_2lo<float>() noexcept { return detail::caster32_t(0xb9389ad4U).f; } template <> constexpr double invlog_2lo<double>() noexcept { return detail::caster64_t(uint64_t(0x3de705fc2eefa200U)).f; } /***************************** * invlog10_2 implementation * *****************************/ template <class T> constexpr T invlog10_2() noexcept { return T(invlog10_2<typename T::value_type>()); } template <> constexpr float invlog10_2<float>() noexcept { return float(3.32192809488736234787031942949); } template <> constexpr double invlog10_2<double>() noexcept { return double(3.32192809488736234787031942949); } /************************ * log_2 implementation * ************************/ template <class T> constexpr T log_2() noexcept { return T(log_2<typename T::value_type>()); } template <> constexpr float log_2<float>() noexcept { return float(0.6931471805599453094172321214581765680755001343602553); } template <> constexpr double log_2<double>() noexcept { return double(0.6931471805599453094172321214581765680755001343602553); } /************************** * log_2hi implementation * **************************/ template <class T> constexpr T log_2hi() noexcept { return T(log_2hi<typename T::value_type>()); } template <> constexpr float log_2hi<float>() noexcept { return detail::caster32_t(0x3f318000U).f; } template <> constexpr double log_2hi<double>() noexcept { return detail::caster64_t(uint64_t(0x3fe62e42fee00000U)).f; } /************************** * log_2lo implementation * **************************/ template <class T> constexpr T log_2lo() noexcept { return T(log_2lo<typename T::value_type>()); } template <> constexpr float log_2lo<float>() noexcept { return detail::caster32_t(0xb95e8083U).f; } template <> constexpr double log_2lo<double>() noexcept { return detail::caster64_t(uint64_t(0x3dea39ef35793c76U)).f; } /**************************** * log10_2hi implementation * ****************************/ template <class T> constexpr T log10_2hi() noexcept { return T(log10_2hi<typename T::value_type>()); } template <> constexpr float log10_2hi<float>() noexcept { return detail::caster32_t(0x3e9a0000U).f; } template <> constexpr double log10_2hi<double>() noexcept { return detail::caster64_t(uint64_t(0x3fd3440000000000U)).f; } /**************************** * log10_2lo implementation * ****************************/ template <class T> constexpr T log10_2lo() noexcept { return T(log10_2lo<typename T::value_type>()); } template <> constexpr float log10_2lo<float>() noexcept { return detail::caster32_t(0x39826a14U).f; } template <> constexpr double log10_2lo<double>() noexcept { return detail::caster64_t(uint64_t(0x3ed3509f79fef312U)).f; } /************************* * logeps implementation * *************************/ template <class T> constexpr T logeps() noexcept { return T(logeps<typename T::value_type>()); } template <> constexpr float logeps<float>() noexcept { return detail::caster32_t(0xc17f1402U).f; } template <> constexpr double logeps<double>() noexcept { return detail::caster64_t(uint64_t(0xc04205966f2b4f12U)).f; } /****************************** * maxexponent implementation * ******************************/ template <class T> constexpr as_integer_t<T> maxexponent() noexcept { return as_integer_t<T>(maxexponent<typename T::value_type>()); } template<> constexpr int32_t maxexponent<float>() noexcept { return 127; } template <> constexpr int64_t maxexponent<double>() noexcept { return 1023; } /*************************** * maxflint implementation * ***************************/ template <class T> constexpr T maxflint() noexcept { return T(maxflint<typename T::value_type>()); } template <> constexpr float maxflint<float>() noexcept { return 16777216.0f; } template <> constexpr double maxflint<double>() noexcept { return 9007199254740992.0; } /************************* * maxlog implementation * *************************/ template <class T> constexpr T maxlog() noexcept { return T(maxlog<typename T::value_type>()); } template <> constexpr float maxlog<float>() noexcept { return 88.3762626647949f; } template <> constexpr double maxlog<double>() noexcept { return 709.78271289338400; } /************************** * maxlog2 implementation * **************************/ template <class T> constexpr T maxlog2() noexcept { return T(maxlog2<typename T::value_type>()); } template <> constexpr float maxlog2<float>() noexcept { return 127.0f; } template <> constexpr double maxlog2<double>() noexcept { return 1023.0; } /*************************** * maxlog10 implementation * ***************************/ template <class T> constexpr T maxlog10() noexcept { return T(maxlog10<typename T::value_type>()); } template <> constexpr float maxlog10<float>() noexcept { return 38.23080825805664f; } template <> constexpr double maxlog10<double>() noexcept { return 308.2547155599167; } /************************* * minlog implementation * *************************/ template <class T> constexpr T minlog() noexcept { return T(minlog<typename T::value_type>()); } template <> constexpr float minlog<float>() noexcept { return -88.3762626647949f; } template <> constexpr double minlog<double>() noexcept { return -708.3964185322641; } /************************** * minlog2 implementation * **************************/ template <class T> constexpr T minlog2() noexcept { return T(minlog2<typename T::value_type>()); } template <> constexpr float minlog2<float>() noexcept { return -127.0f; } template <> constexpr double minlog2<double>() noexcept { return -1023.0; } /*************************** * minlog10 implementation * ***************************/ template <class T> constexpr T minlog10() noexcept { return T(minlog10<typename T::value_type>()); } template <> constexpr float minlog10<float>() noexcept { return -37.89999771118164f; } template <> constexpr double minlog10<double>() noexcept { return -308.2547155599167; } /******************************** * minusinfinity implementation * ********************************/ template <class T> constexpr T minusinfinity() noexcept { return T(minusinfinity<typename T::value_type>()); } template <> constexpr float minusinfinity<float>() noexcept { return -infinity<float>(); } template <> constexpr double minusinfinity<double>() noexcept { return -infinity<double>(); } /**************************** * minuszero implementation * ****************************/ template <class T> constexpr T minuszero() noexcept { return T(minuszero<typename T::value_type>()); } template <> constexpr float minuszero<float>() noexcept { return -0.0f; } template <> constexpr double minuszero<double>() noexcept { return -0.0; } /********************** * nan implementation * **********************/ template <class T> constexpr T nan() noexcept { return T(nan<typename T::value_type>()); } template <> constexpr float nan<float>() noexcept { return detail::caster32_t(0xFFFFFFFFU).f; } template <> constexpr double nan<double>() noexcept { return detail::caster64_t(uint64_t(0xFFFFFFFFFFFFFFFFU)).f; } /********************** * nmb implementation * **********************/ template <class T> constexpr int32_t nmb() noexcept { return nmb<typename T::value_type>(); } template <> constexpr int32_t nmb<float>() noexcept { return 23; } template <> constexpr int32_t nmb<double>() noexcept { return 52; } /********************************* * smallestposval implementation * *********************************/ template <class T> constexpr T smallestposval() noexcept { return T(smallestposval<typename T::value_type>()); } template <> constexpr float smallestposval<float>() noexcept { return 1.1754944e-38f; } template <> constexpr double smallestposval<double>() noexcept { return 2.225073858507201e-308; } /*************************** * twotonmb implementation * ***************************/ template <class T> constexpr T twotonmb() noexcept { return T(twotonmb<typename T::value_type>()); } template <> constexpr float twotonmb<float>() noexcept { return 8388608.0f; } template <> constexpr double twotonmb<double>() noexcept { return 4503599627370496.0; } } #endif <commit_msg>constant refactoring<commit_after>/*************************************************************************** * Copyright (c) 2016, Johan Mabille and Sylvain Corlay * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #ifndef XSIMD_NUMERICAL_CONSTANT_HPP #define XSIMD_NUMERICAL_CONSTANT_HPP #include <limits> #include "../types/xsimd_types_include.hpp" namespace xsimd { #define XSIMD_DEFINE_CONSTANT(NAME, SINGLE, DOUBLE)\ template <class T>\ constexpr T NAME##() noexcept {\ return T(NAME##<typename T::value_type>());\ }\ template <>\ constexpr float NAME##<float>() noexcept {\ return SINGLE;\ }\ template <>\ constexpr double NAME##<double>() noexcept {\ return DOUBLE;\ } #define XSIMD_DEFINE_CONSTANT_HEX(NAME, SINGLE, DOUBLE)\ template <class T>\ constexpr T NAME##() noexcept {\ return T(NAME##<typename T::value_type>());\ }\ template <>\ constexpr float NAME##<float>() noexcept {\ return detail::caster32_t(SINGLE).f;\ }\ template <>\ constexpr double NAME##<double>() noexcept {\ return detail::caster64_t(uint64_t(DOUBLE)).f;\ } XSIMD_DEFINE_CONSTANT(infinity, (std::numeric_limits<float>::infinity()), (std::numeric_limits<double>::infinity())) XSIMD_DEFINE_CONSTANT(invlog_2, 1.442695040888963407359924681001892137426645954152986f, 1.442695040888963407359924681001892137426645954152986) XSIMD_DEFINE_CONSTANT_HEX(invlog_2hi, 0x3fb8b000, 0x3ff7154765200000) XSIMD_DEFINE_CONSTANT_HEX(invlog_2lo, 0xb9389ad4, 0x3de705fc2eefa200) XSIMD_DEFINE_CONSTANT(invlog10_2, 3.32192809488736234787031942949f, 3.32192809488736234787031942949) XSIMD_DEFINE_CONSTANT(log_2, 0.6931471805599453094172321214581765680755001343602553f, 0.6931471805599453094172321214581765680755001343602553) XSIMD_DEFINE_CONSTANT_HEX(log_2hi, 0x3f318000, 0x3fe62e42fee00000) XSIMD_DEFINE_CONSTANT_HEX(log_2lo, 0xb95e8083, 0x3dea39ef35793c76) XSIMD_DEFINE_CONSTANT_HEX(log10_2hi, 0x3e9a0000, 0x3fd3440000000000) XSIMD_DEFINE_CONSTANT_HEX(log10_2lo, 0x39826a14, 0x3ed3509f79fef312) XSIMD_DEFINE_CONSTANT_HEX(logeps, 0xc17f1402, 0xc04205966f2b4f12) XSIMD_DEFINE_CONSTANT(maxflint, 16777216.0f, 9007199254740992.0) XSIMD_DEFINE_CONSTANT(maxlog, 88.3762626647949f, 709.78271289338400) XSIMD_DEFINE_CONSTANT(maxlog2, 127.0f, 1023.) XSIMD_DEFINE_CONSTANT(maxlog10, 38.23080825805664f, 308.2547155599167) XSIMD_DEFINE_CONSTANT_HEX(mediumpi, 0x43490fdb, 0x412921fb54442d18) XSIMD_DEFINE_CONSTANT(minlog, -88.3762626647949f, -708.3964185322641) XSIMD_DEFINE_CONSTANT(minlog2, -127.0f, -1023.) XSIMD_DEFINE_CONSTANT(minlog10, -37.89999771118164f, -308.2547155599167) XSIMD_DEFINE_CONSTANT(minusinfinity, (-infinity<float>()), (-infinity<double>())) XSIMD_DEFINE_CONSTANT(minuszero, -0.0f, -0.0) XSIMD_DEFINE_CONSTANT_HEX(nan, 0xFFFFFFFF, 0xFFFFFFFFFFFFFFFF) XSIMD_DEFINE_CONSTANT_HEX(pio2, 0x3fc90fdb, 0x3ff921fb54442d18) XSIMD_DEFINE_CONSTANT_HEX(pio2_1, 0x3fc90f80, 0x3ff921fb54400000) XSIMD_DEFINE_CONSTANT_HEX(pio2_2, 0x37354400, 0x3dd0b4611a600000) XSIMD_DEFINE_CONSTANT_HEX(pio2_3, 0x2e85a300, 0x3ba3198a2e000000) XSIMD_DEFINE_CONSTANT_HEX(pio4, 0x3f490fdb, 0x3fe921fb54442d18) XSIMD_DEFINE_CONSTANT(smallestposval, 1.1754944e-38f, 2.225073858507201e-308) XSIMD_DEFINE_CONSTANT_HEX(twentypi, 0x427b53d1, 0x404f6a7a2955385e) XSIMD_DEFINE_CONSTANT_HEX(twoopi, 0x3f22f983, 0x3fe45f306dc9c883) XSIMD_DEFINE_CONSTANT_HEX(twotonmb, 8388608.0f, 4503599627370496.0) #undef XSIMD_DEFINE_CONSTANT #undef XSIMD_DEFINE_CONSTANT_HEX template <class T> constexpr T allbits() noexcept; template <class T> constexpr as_integer_t<T> maxexponent() noexcept; template <class T> constexpr int32_t nmb() noexcept; /************************** * allbits implementation * **************************/ namespace detail { template <class T, bool = std::is_integral<T>::value> struct allbits_impl { static constexpr T get_value() noexcept { return T(~0); } }; template <class T> struct allbits_impl<T, false> { static constexpr T get_value() noexcept { return nan<T>(); } }; } template <class T> constexpr T allbits() noexcept { return T(detail::allbits_impl<typename T::value_type>::get_value()); } /****************************** * maxexponent implementation * ******************************/ template <class T> constexpr as_integer_t<T> maxexponent() noexcept { return as_integer_t<T>(maxexponent<typename T::value_type>()); } template<> constexpr int32_t maxexponent<float>() noexcept { return 127; } template <> constexpr int64_t maxexponent<double>() noexcept { return 1023; } /********************** * nmb implementation * **********************/ template <class T> constexpr int32_t nmb() noexcept { return nmb<typename T::value_type>(); } template <> constexpr int32_t nmb<float>() noexcept { return 23; } template <> constexpr int32_t nmb<double>() noexcept { return 52; } } #endif <|endoftext|>
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/media/crypto/key_systems.h" #include <map> #include "base/lazy_instance.h" #include "base/logging.h" #include "base/strings/string_util.h" #include "content/renderer/media/crypto/key_systems_info.h" #include "net/base/mime_util.h" #include "third_party/WebKit/public/platform/WebCString.h" #include "third_party/WebKit/public/platform/WebString.h" namespace content { // Convert a WebString to ASCII, falling back on an empty string in the case // of a non-ASCII string. static std::string ToASCIIOrEmpty(const WebKit::WebString& string) { return IsStringASCII(string) ? UTF16ToASCII(string) : std::string(); } class KeySystems { public: static KeySystems* GetInstance(); void AddConcreteSupportedKeySystem( const std::string& key_system, bool use_aes_decryptor, #if defined(ENABLE_PEPPER_CDMS) const std::string& pepper_type, #elif defined(OS_ANDROID) const uint8 uuid[16], #endif const std::string& parent_key_system); void AddSupportedType(const std::string& key_system, const std::string& mime_type, const std::string& codecs_list); bool IsConcreteSupportedKeySystem(const std::string& key_system); bool IsSupportedKeySystemWithMediaMimeType( const std::string& mime_type, const std::vector<std::string>& codecs, const std::string& key_system); bool UseAesDecryptor(const std::string& concrete_key_system); #if defined(ENABLE_PEPPER_CDMS) std::string GetPepperType(const std::string& concrete_key_system); #elif defined(OS_ANDROID) std::vector<uint8> GetUUID(const std::string& concrete_key_system); #endif private: friend struct base::DefaultLazyInstanceTraits<KeySystems>; typedef base::hash_set<std::string> CodecMappings; typedef std::map<std::string, CodecMappings> MimeTypeMappings; struct KeySystemProperties { KeySystemProperties() : use_aes_decryptor(false) {} bool use_aes_decryptor; #if defined(ENABLE_PEPPER_CDMS) std::string pepper_type; #elif defined(OS_ANDROID) std::vector<uint8> uuid; #endif MimeTypeMappings types; }; typedef std::map<std::string, KeySystemProperties> KeySystemMappings; typedef std::map<std::string, std::string> ParentKeySystemMappings; KeySystems() {} bool IsSupportedKeySystemWithContainerAndCodec( const std::string& mime_type, const std::string& codec, const std::string& key_system); // Map from key system string to capabilities. KeySystemMappings key_system_map_; // Map from parent key system to the concrete key system that should be used // to represent its capabilities. ParentKeySystemMappings parent_key_system_map_; DISALLOW_COPY_AND_ASSIGN(KeySystems); }; static base::LazyInstance<KeySystems> g_key_systems = LAZY_INSTANCE_INITIALIZER; KeySystems* KeySystems::GetInstance() { KeySystems* key_systems = &g_key_systems.Get(); // TODO(ddorwin): Call out to ContentClient to register key systems. static bool is_registered = false; if (!is_registered) { is_registered = true; // Prevent reentrancy when Add*() is called. RegisterKeySystems(); } return key_systems; } // TODO(ddorwin): Change first parameter to |concrete_key_system|. void KeySystems::AddConcreteSupportedKeySystem( const std::string& key_system, bool use_aes_decryptor, #if defined(ENABLE_PEPPER_CDMS) const std::string& pepper_type, #elif defined(OS_ANDROID) const uint8 uuid[16], #endif const std::string& parent_key_system) { DCHECK(!IsConcreteSupportedKeySystem(key_system)) << "Key system '" << key_system << "' already registered"; KeySystemProperties properties; properties.use_aes_decryptor = use_aes_decryptor; #if defined(ENABLE_PEPPER_CDMS) DCHECK_EQ(use_aes_decryptor, pepper_type.empty()); properties.pepper_type = pepper_type; #elif defined(OS_ANDROID) // Since |uuid| can't be empty, use |use_aes_decryptor|. if (!use_aes_decryptor) properties.uuid.assign(uuid, uuid + 16); #endif key_system_map_[key_system] = properties; if (!parent_key_system.empty()) { DCHECK(parent_key_system_map_.find(parent_key_system) == parent_key_system_map_.end()) << "Parent '" << parent_key_system.c_str() << "' already registered."; parent_key_system_map_[parent_key_system] = key_system; } } // TODO(ddorwin): Change first parameter to |concrete_key_system|. void KeySystems::AddSupportedType(const std::string& key_system, const std::string& mime_type, const std::string& codecs_list) { std::vector<std::string> mime_type_codecs; net::ParseCodecString(codecs_list, &mime_type_codecs, false); CodecMappings codecs(mime_type_codecs.begin(), mime_type_codecs.end()); // Support the MIME type string alone, without codec(s) specified. codecs.insert(std::string()); KeySystemMappings::iterator key_system_iter = key_system_map_.find(key_system); DCHECK(key_system_iter != key_system_map_.end()); MimeTypeMappings& mime_types_map = key_system_iter->second.types; // mime_types_map must not be repeated for a given key system. DCHECK(mime_types_map.find(mime_type) == mime_types_map.end()); mime_types_map[mime_type] = codecs; } bool KeySystems::IsConcreteSupportedKeySystem(const std::string& key_system) { return key_system_map_.find(key_system) != key_system_map_.end(); } bool KeySystems::IsSupportedKeySystemWithContainerAndCodec( const std::string& mime_type, const std::string& codec, const std::string& key_system) { KeySystemMappings::const_iterator key_system_iter = key_system_map_.find(key_system); if (key_system_iter == key_system_map_.end()) return false; const MimeTypeMappings& mime_types_map = key_system_iter->second.types; MimeTypeMappings::const_iterator mime_iter = mime_types_map.find(mime_type); if (mime_iter == mime_types_map.end()) return false; const CodecMappings& codecs = mime_iter->second; return (codecs.find(codec) != codecs.end()); } bool KeySystems::IsSupportedKeySystemWithMediaMimeType( const std::string& mime_type, const std::vector<std::string>& codecs, const std::string& key_system) { // If |key_system| is a parent key_system, use its concrete child. // Otherwise, use |key_system|. std::string concrete_key_system; ParentKeySystemMappings::iterator parent_key_system_iter = parent_key_system_map_.find(key_system); if (parent_key_system_iter != parent_key_system_map_.end()) concrete_key_system = parent_key_system_iter->second; else concrete_key_system = key_system; // This method is only used by the canPlaytType() path (not the EME methods), // so we check for suppressed key_systems here. if(IsCanPlayTypeSuppressed(concrete_key_system)) return false; if (codecs.empty()) { return IsSupportedKeySystemWithContainerAndCodec( mime_type, std::string(), concrete_key_system); } for (size_t i = 0; i < codecs.size(); ++i) { if (!IsSupportedKeySystemWithContainerAndCodec( mime_type, codecs[i], concrete_key_system)) { return false; } } return true; } bool KeySystems::UseAesDecryptor(const std::string& concrete_key_system) { KeySystemMappings::iterator key_system_iter = key_system_map_.find(concrete_key_system); if (key_system_iter == key_system_map_.end()) { DLOG(FATAL) << concrete_key_system << " is not a known concrete system"; return false; } return key_system_iter->second.use_aes_decryptor; } #if defined(ENABLE_PEPPER_CDMS) std::string KeySystems::GetPepperType(const std::string& concrete_key_system) { KeySystemMappings::iterator key_system_iter = key_system_map_.find(concrete_key_system); if (key_system_iter == key_system_map_.end()) { DLOG(FATAL) << concrete_key_system << " is not a known concrete system"; return std::string(); } const std::string& type = key_system_iter->second.pepper_type; DLOG_IF(FATAL, type.empty()) << concrete_key_system << " is not Pepper-based"; return type; } #elif defined(OS_ANDROID) std::vector<uint8> KeySystems::GetUUID(const std::string& concrete_key_system) { KeySystemMappings::iterator key_system_iter = key_system_map_.find(concrete_key_system); if (key_system_iter == key_system_map_.end()) { DLOG(FATAL) << concrete_key_system << " is not a known concrete system"; return std::vector<uint8>(); } return key_system_iter->second.uuid; } #endif //------------------------------------------------------------------------------ void AddConcreteSupportedKeySystem( const std::string& key_system, bool use_aes_decryptor, #if defined(ENABLE_PEPPER_CDMS) const std::string& pepper_type, #elif defined(OS_ANDROID) const uint8 uuid[16], #endif const std::string& parent_key_system) { KeySystems::GetInstance()->AddConcreteSupportedKeySystem(key_system, use_aes_decryptor, #if defined(ENABLE_PEPPER_CDMS) pepper_type, #elif defined(OS_ANDROID) uuid, #endif parent_key_system); } void AddSupportedType(const std::string& key_system, const std::string& mime_type, const std::string& codecs_list) { KeySystems::GetInstance()->AddSupportedType(key_system, mime_type, codecs_list); } bool IsConcreteSupportedKeySystem(const WebKit::WebString& key_system) { return KeySystems::GetInstance()->IsConcreteSupportedKeySystem( ToASCIIOrEmpty(key_system)); } bool IsSupportedKeySystemWithMediaMimeType( const std::string& mime_type, const std::vector<std::string>& codecs, const std::string& key_system) { return KeySystems::GetInstance()->IsSupportedKeySystemWithMediaMimeType( mime_type, codecs, key_system); } std::string KeySystemNameForUMA(const WebKit::WebString& key_system) { return KeySystemNameForUMAInternal(key_system); } bool CanUseAesDecryptor(const std::string& concrete_key_system) { return KeySystems::GetInstance()->UseAesDecryptor(concrete_key_system); } #if defined(ENABLE_PEPPER_CDMS) std::string GetPepperType(const std::string& concrete_key_system) { return KeySystems::GetInstance()->GetPepperType(concrete_key_system); } #elif defined(OS_ANDROID) std::vector<uint8> GetUUID(const std::string& concrete_key_system) { return KeySystems::GetInstance()->GetUUID(concrete_key_system); } #endif } // namespace content <commit_msg>Address deferred comments from review of r220664.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/media/crypto/key_systems.h" #include <map> #include "base/lazy_instance.h" #include "base/logging.h" #include "base/strings/string_util.h" #include "content/renderer/media/crypto/key_systems_info.h" #include "net/base/mime_util.h" #include "third_party/WebKit/public/platform/WebCString.h" #include "third_party/WebKit/public/platform/WebString.h" namespace content { // Convert a WebString to ASCII, falling back on an empty string in the case // of a non-ASCII string. static std::string ToASCIIOrEmpty(const WebKit::WebString& string) { return IsStringASCII(string) ? UTF16ToASCII(string) : std::string(); } class KeySystems { public: static KeySystems* GetInstance(); void AddConcreteSupportedKeySystem( const std::string& key_system, bool use_aes_decryptor, #if defined(ENABLE_PEPPER_CDMS) const std::string& pepper_type, #elif defined(OS_ANDROID) const uint8 uuid[16], #endif const std::string& parent_key_system); void AddSupportedType(const std::string& key_system, const std::string& mime_type, const std::string& codecs_list); bool IsConcreteSupportedKeySystem(const std::string& key_system); bool IsSupportedKeySystemWithMediaMimeType( const std::string& mime_type, const std::vector<std::string>& codecs, const std::string& key_system); bool UseAesDecryptor(const std::string& concrete_key_system); #if defined(ENABLE_PEPPER_CDMS) std::string GetPepperType(const std::string& concrete_key_system); #elif defined(OS_ANDROID) std::vector<uint8> GetUUID(const std::string& concrete_key_system); #endif private: friend struct base::DefaultLazyInstanceTraits<KeySystems>; typedef base::hash_set<std::string> CodecSet; typedef std::map<std::string, CodecSet> MimeTypeMap; struct KeySystemProperties { KeySystemProperties() : use_aes_decryptor(false) {} bool use_aes_decryptor; #if defined(ENABLE_PEPPER_CDMS) std::string pepper_type; #elif defined(OS_ANDROID) std::vector<uint8> uuid; #endif MimeTypeMap types; }; typedef std::map<std::string, KeySystemProperties> KeySystemPropertiesMap; typedef std::map<std::string, std::string> ParentKeySystemMap; KeySystems() {} bool IsSupportedKeySystemWithContainerAndCodec( const std::string& mime_type, const std::string& codec, const std::string& key_system); // Map from key system string to capabilities. KeySystemPropertiesMap concrete_key_system_map_; // Map from parent key system to the concrete key system that should be used // to represent its capabilities. ParentKeySystemMap parent_key_system_map_; DISALLOW_COPY_AND_ASSIGN(KeySystems); }; static base::LazyInstance<KeySystems> g_key_systems = LAZY_INSTANCE_INITIALIZER; KeySystems* KeySystems::GetInstance() { KeySystems* key_systems = &g_key_systems.Get(); // TODO(ddorwin): Call out to ContentClient to register key systems. static bool is_registered = false; if (!is_registered) { is_registered = true; // Prevent reentrancy when Add*() is called. RegisterKeySystems(); } return key_systems; } void KeySystems::AddConcreteSupportedKeySystem( const std::string& concrete_key_system, bool use_aes_decryptor, #if defined(ENABLE_PEPPER_CDMS) const std::string& pepper_type, #elif defined(OS_ANDROID) const uint8 uuid[16], #endif const std::string& parent_key_system) { DCHECK(!IsConcreteSupportedKeySystem(concrete_key_system)) << "Key system '" << concrete_key_system << "' already registered"; KeySystemProperties properties; properties.use_aes_decryptor = use_aes_decryptor; #if defined(ENABLE_PEPPER_CDMS) DCHECK_EQ(use_aes_decryptor, pepper_type.empty()); properties.pepper_type = pepper_type; #elif defined(OS_ANDROID) // Since |uuid| can't be empty, use |use_aes_decryptor|. if (!use_aes_decryptor) properties.uuid.assign(uuid, uuid + 16); #endif concrete_key_system_map_[concrete_key_system] = properties; if (!parent_key_system.empty()) { DCHECK(parent_key_system_map_.find(parent_key_system) == parent_key_system_map_.end()) << "Parent '" << parent_key_system.c_str() << "' already registered."; parent_key_system_map_[parent_key_system] = concrete_key_system; } } void KeySystems::AddSupportedType(const std::string& concrete_key_system, const std::string& mime_type, const std::string& codecs_list) { std::vector<std::string> mime_type_codecs; net::ParseCodecString(codecs_list, &mime_type_codecs, false); CodecSet codecs(mime_type_codecs.begin(), mime_type_codecs.end()); // Support the MIME type string alone, without codec(s) specified. codecs.insert(std::string()); KeySystemPropertiesMap::iterator key_system_iter = concrete_key_system_map_.find(concrete_key_system); DCHECK(key_system_iter != concrete_key_system_map_.end()); MimeTypeMap& mime_types_map = key_system_iter->second.types; // mime_types_map must not be repeated for a given key system. DCHECK(mime_types_map.find(mime_type) == mime_types_map.end()); mime_types_map[mime_type] = codecs; } bool KeySystems::IsConcreteSupportedKeySystem(const std::string& key_system) { return concrete_key_system_map_.find(key_system) != concrete_key_system_map_.end(); } bool KeySystems::IsSupportedKeySystemWithContainerAndCodec( const std::string& mime_type, const std::string& codec, const std::string& key_system) { KeySystemPropertiesMap::const_iterator key_system_iter = concrete_key_system_map_.find(key_system); if (key_system_iter == concrete_key_system_map_.end()) return false; const MimeTypeMap& mime_types_map = key_system_iter->second.types; MimeTypeMap::const_iterator mime_iter = mime_types_map.find(mime_type); if (mime_iter == mime_types_map.end()) return false; const CodecSet& codecs = mime_iter->second; return (codecs.find(codec) != codecs.end()); } bool KeySystems::IsSupportedKeySystemWithMediaMimeType( const std::string& mime_type, const std::vector<std::string>& codecs, const std::string& key_system) { // If |key_system| is a parent key_system, use its concrete child. // Otherwise, use |key_system|. std::string concrete_key_system; ParentKeySystemMap::iterator parent_key_system_iter = parent_key_system_map_.find(key_system); if (parent_key_system_iter != parent_key_system_map_.end()) concrete_key_system = parent_key_system_iter->second; else concrete_key_system = key_system; // This method is only used by the canPlaytType() path (not the EME methods), // so we check for suppressed key_systems here. if(IsCanPlayTypeSuppressed(concrete_key_system)) return false; if (codecs.empty()) { return IsSupportedKeySystemWithContainerAndCodec( mime_type, std::string(), concrete_key_system); } for (size_t i = 0; i < codecs.size(); ++i) { if (!IsSupportedKeySystemWithContainerAndCodec( mime_type, codecs[i], concrete_key_system)) { return false; } } return true; } bool KeySystems::UseAesDecryptor(const std::string& concrete_key_system) { KeySystemPropertiesMap::iterator key_system_iter = concrete_key_system_map_.find(concrete_key_system); if (key_system_iter == concrete_key_system_map_.end()) { DLOG(FATAL) << concrete_key_system << " is not a known concrete system"; return false; } return key_system_iter->second.use_aes_decryptor; } #if defined(ENABLE_PEPPER_CDMS) std::string KeySystems::GetPepperType(const std::string& concrete_key_system) { KeySystemPropertiesMap::iterator key_system_iter = concrete_key_system_map_.find(concrete_key_system); if (key_system_iter == concrete_key_system_map_.end()) { DLOG(FATAL) << concrete_key_system << " is not a known concrete system"; return std::string(); } const std::string& type = key_system_iter->second.pepper_type; DLOG_IF(FATAL, type.empty()) << concrete_key_system << " is not Pepper-based"; return type; } #elif defined(OS_ANDROID) std::vector<uint8> KeySystems::GetUUID(const std::string& concrete_key_system) { KeySystemPropertiesMap::iterator key_system_iter = concrete_key_system_map_.find(concrete_key_system); if (key_system_iter == concrete_key_system_map_.end()) { DLOG(FATAL) << concrete_key_system << " is not a known concrete system"; return std::vector<uint8>(); } return key_system_iter->second.uuid; } #endif //------------------------------------------------------------------------------ void AddConcreteSupportedKeySystem( const std::string& key_system, bool use_aes_decryptor, #if defined(ENABLE_PEPPER_CDMS) const std::string& pepper_type, #elif defined(OS_ANDROID) const uint8 uuid[16], #endif const std::string& parent_key_system) { KeySystems::GetInstance()->AddConcreteSupportedKeySystem(key_system, use_aes_decryptor, #if defined(ENABLE_PEPPER_CDMS) pepper_type, #elif defined(OS_ANDROID) uuid, #endif parent_key_system); } void AddSupportedType(const std::string& key_system, const std::string& mime_type, const std::string& codecs_list) { KeySystems::GetInstance()->AddSupportedType(key_system, mime_type, codecs_list); } bool IsConcreteSupportedKeySystem(const WebKit::WebString& key_system) { return KeySystems::GetInstance()->IsConcreteSupportedKeySystem( ToASCIIOrEmpty(key_system)); } bool IsSupportedKeySystemWithMediaMimeType( const std::string& mime_type, const std::vector<std::string>& codecs, const std::string& key_system) { return KeySystems::GetInstance()->IsSupportedKeySystemWithMediaMimeType( mime_type, codecs, key_system); } std::string KeySystemNameForUMA(const WebKit::WebString& key_system) { return KeySystemNameForUMAInternal(key_system); } bool CanUseAesDecryptor(const std::string& concrete_key_system) { return KeySystems::GetInstance()->UseAesDecryptor(concrete_key_system); } #if defined(ENABLE_PEPPER_CDMS) std::string GetPepperType(const std::string& concrete_key_system) { return KeySystems::GetInstance()->GetPepperType(concrete_key_system); } #elif defined(OS_ANDROID) std::vector<uint8> GetUUID(const std::string& concrete_key_system) { return KeySystems::GetInstance()->GetUUID(concrete_key_system); } #endif } // namespace content <|endoftext|>
<commit_before>/* * Author: Vladimir Ivan * * Copyright (c) 2017, University Of Edinburgh * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of 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 "task_map/Distance.h" REGISTER_TASKMAP_TYPE("Distance", exotica::Distance); namespace exotica { Distance::Distance() { //!< Empty constructor } void Distance::update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi) { if(phi.rows() != Kinematics.Phi.rows()*3) throw_named("Wrong size of phi!"); for(int i=0;i<Kinematics.Phi.rows();i++) { phi(i) = Kinematics.Phi(i).p.Norm(); } } void Distance::update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi, Eigen::MatrixXdRef J) { if(phi.rows() != Kinematics.Phi.rows()) throw_named("Wrong size of phi!"); if(J.rows() != Kinematics.J.rows() || J.cols() != Kinematics.J(0).data.cols()) throw_named("Wrong size of J! " << Kinematics.J(0).data.cols()); for(int i=0;i<Kinematics.Phi.rows();i++) { phi(i) = Kinematics.Phi(i).p.Norm(); for (int j = 0; j < J.cols(); j++) { J(i,j) = ( Kinematics.Phi(i).p[0]*Kinematics.J[i].data(0,j) + Kinematics.Phi(i).p[1]*Kinematics.J[i].data(1,j) + Kinematics.Phi(i).p[2]*Kinematics.J[i].data(2,j) ) / phi(i); } } } void Distance::Instantiate(DistanceInitializer& init) { } int Distance::taskSpaceDim() { return Kinematics.Phi.rows(); } } <commit_msg>Fixed distance task map<commit_after>/* * Author: Vladimir Ivan * * Copyright (c) 2017, University Of Edinburgh * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of 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 "task_map/Distance.h" REGISTER_TASKMAP_TYPE("Distance", exotica::Distance); namespace exotica { Distance::Distance() { //!< Empty constructor } void Distance::update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi) { if(phi.rows() != Kinematics.Phi.rows()) throw_named("Wrong size of phi!"); for(int i=0;i<Kinematics.Phi.rows();i++) { phi(i) = Kinematics.Phi(i).p.Norm(); } } void Distance::update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi, Eigen::MatrixXdRef J) { if(phi.rows() != Kinematics.Phi.rows()) throw_named("Wrong size of phi!"); if(J.rows() != Kinematics.J.rows() || J.cols() != Kinematics.J(0).data.cols()) throw_named("Wrong size of J! " << Kinematics.J(0).data.cols()); for(int i=0;i<Kinematics.Phi.rows();i++) { phi(i) = Kinematics.Phi(i).p.Norm(); for (int j = 0; j < J.cols(); j++) { J(i,j) = ( Kinematics.Phi(i).p[0]*Kinematics.J[i].data(0,j) + Kinematics.Phi(i).p[1]*Kinematics.J[i].data(1,j) + Kinematics.Phi(i).p[2]*Kinematics.J[i].data(2,j) ) / phi(i); } } } void Distance::Instantiate(DistanceInitializer& init) { } int Distance::taskSpaceDim() { return Kinematics.Phi.rows(); } } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/in_process_webkit/webkit_thread.h" #include "base/command_line.h" #include "content/browser/in_process_webkit/browser_webkitplatformsupport_impl.h" #include "content/common/content_switches.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebKit.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebSecurityOrigin.h" #include "webkit/glue/webkit_glue.h" WebKitThread::WebKitThread() { } // This happens on the UI thread after the IO thread has been shut down. WebKitThread::~WebKitThread() { // We can't just check CurrentlyOn(BrowserThread::UI) because in unit tests, // MessageLoop::Current is sometimes NULL and other times valid and there's // no BrowserThread object. Can't check that CurrentlyOn is not IO since // some unit tests set that BrowserThread for other checks. DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::WEBKIT)); } void WebKitThread::Initialize() { DCHECK(!webkit_thread_.get()); if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess)) { // TODO(jorlow): We need a better story for single process mode. return; } webkit_thread_.reset(new InternalWebKitThread); bool started = webkit_thread_->Start(); DCHECK(started); } WebKitThread::InternalWebKitThread::InternalWebKitThread() : BrowserThread(BrowserThread::WEBKIT) { } WebKitThread::InternalWebKitThread::~InternalWebKitThread() { Stop(); } void WebKitThread::InternalWebKitThread::Init() { DCHECK(!webkit_platform_support_.get()); webkit_platform_support_.reset(new BrowserWebKitPlatformSupportImpl); WebKit::initialize(webkit_platform_support_.get()); webkit_glue::EnableWebCoreLogChannels( CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kWebCoreLogChannels)); // Exercise WebSecurityOrigin to get its underlying statics initialized. // TODO(michaeln): remove this when the following is landed. // https://bugs.webkit.org/show_bug.cgi?id=61145 WebKit::WebSecurityOrigin::create(GURL("http://chromium.org")); // If possible, post initialization tasks to this thread (rather than doing // them now) so we don't block the UI thread any longer than we have to. } void WebKitThread::InternalWebKitThread::CleanUp() { DCHECK(webkit_platform_support_.get()); WebKit::shutdown(); } <commit_msg>Do not intitialize V8 in browser process.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/in_process_webkit/webkit_thread.h" #include "base/command_line.h" #include "content/browser/in_process_webkit/browser_webkitplatformsupport_impl.h" #include "content/common/content_switches.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebKit.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebSecurityOrigin.h" #include "webkit/glue/webkit_glue.h" WebKitThread::WebKitThread() { } // This happens on the UI thread after the IO thread has been shut down. WebKitThread::~WebKitThread() { // We can't just check CurrentlyOn(BrowserThread::UI) because in unit tests, // MessageLoop::Current is sometimes NULL and other times valid and there's // no BrowserThread object. Can't check that CurrentlyOn is not IO since // some unit tests set that BrowserThread for other checks. DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::WEBKIT)); } void WebKitThread::Initialize() { DCHECK(!webkit_thread_.get()); if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess)) { // TODO(jorlow): We need a better story for single process mode. return; } webkit_thread_.reset(new InternalWebKitThread); bool started = webkit_thread_->Start(); DCHECK(started); } WebKitThread::InternalWebKitThread::InternalWebKitThread() : BrowserThread(BrowserThread::WEBKIT) { } WebKitThread::InternalWebKitThread::~InternalWebKitThread() { Stop(); } void WebKitThread::InternalWebKitThread::Init() { DCHECK(!webkit_platform_support_.get()); webkit_platform_support_.reset(new BrowserWebKitPlatformSupportImpl); WebKit::initializeWithoutV8(webkit_platform_support_.get()); webkit_glue::EnableWebCoreLogChannels( CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kWebCoreLogChannels)); // Exercise WebSecurityOrigin to get its underlying statics initialized. // TODO(michaeln): remove this when the following is landed. // https://bugs.webkit.org/show_bug.cgi?id=61145 WebKit::WebSecurityOrigin::create(GURL("http://chromium.org")); // If possible, post initialization tasks to this thread (rather than doing // them now) so we don't block the UI thread any longer than we have to. } void WebKitThread::InternalWebKitThread::CleanUp() { DCHECK(webkit_platform_support_.get()); WebKit::shutdown(); } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/renderer_host/pepper_udp_socket.h" #include <string.h> #include "base/compiler_specific.h" #include "base/logging.h" #include "content/browser/renderer_host/pepper_message_filter.h" #include "content/public/browser/browser_thread.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" #include "net/udp/udp_server_socket.h" #include "ppapi/proxy/ppapi_messages.h" #include "ppapi/shared_impl/private/net_address_private_impl.h" using content::BrowserThread; using ppapi::NetAddressPrivateImpl; PepperUDPSocket::PepperUDPSocket( PepperMessageFilter* manager, int32 routing_id, uint32 plugin_dispatcher_id, uint32 socket_id) : manager_(manager), routing_id_(routing_id), plugin_dispatcher_id_(plugin_dispatcher_id), socket_id_(socket_id) { DCHECK(manager); } PepperUDPSocket::~PepperUDPSocket() { // Make sure there are no further callbacks from socket_. if (socket_.get()) socket_->Close(); } void PepperUDPSocket::Bind(const PP_NetAddress_Private& addr) { socket_.reset(new net::UDPServerSocket(NULL, net::NetLog::Source())); net::IPEndPoint address; if (!socket_.get() || !NetAddressPrivateImpl::NetAddressToIPEndPoint(addr, &address)) { SendBindACKError(); return; } int result = socket_->Listen(address); if (result == net::OK && socket_->GetLocalAddress(&bound_address_) != net::OK) { SendBindACKError(); return; } OnBindCompleted(result); } void PepperUDPSocket::RecvFrom(int32_t num_bytes) { if (recvfrom_buffer_.get()) { SendRecvFromACKError(); return; } recvfrom_buffer_ = new net::IOBuffer(num_bytes); int result = socket_->RecvFrom( recvfrom_buffer_, num_bytes, &recvfrom_address_, base::Bind(&PepperUDPSocket::OnRecvFromCompleted, base::Unretained(this))); if (result != net::ERR_IO_PENDING) OnRecvFromCompleted(result); } void PepperUDPSocket::SendTo(const std::string& data, const PP_NetAddress_Private& addr) { if (sendto_buffer_.get() || data.empty()) { SendSendToACKError(); return; } net::IPEndPoint address; if (!NetAddressPrivateImpl::NetAddressToIPEndPoint(addr, &address)) { SendSendToACKError(); return; } int data_size = data.size(); sendto_buffer_ = new net::IOBuffer(data_size); memcpy(sendto_buffer_->data(), data.data(), data_size); int result = socket_->SendTo( sendto_buffer_, data_size, address, base::Bind(&PepperUDPSocket::OnSendToCompleted, base::Unretained(this))); if (result != net::ERR_IO_PENDING) OnSendToCompleted(result); } void PepperUDPSocket::SendRecvFromACKError() { PP_NetAddress_Private addr = NetAddressPrivateImpl::kInvalidNetAddress; manager_->Send(new PpapiMsg_PPBUDPSocket_RecvFromACK( routing_id_, plugin_dispatcher_id_, socket_id_, false, std::string(), addr)); } void PepperUDPSocket::SendSendToACKError() { manager_->Send(new PpapiMsg_PPBUDPSocket_SendToACK( routing_id_, plugin_dispatcher_id_, socket_id_, false, 0)); } void PepperUDPSocket::SendBindACKError() { PP_NetAddress_Private addr = NetAddressPrivateImpl::kInvalidNetAddress; manager_->Send(new PpapiMsg_PPBUDPSocket_BindACK( routing_id_, plugin_dispatcher_id_, socket_id_, false, addr)); } void PepperUDPSocket::OnBindCompleted(int result) { PP_NetAddress_Private addr = NetAddressPrivateImpl::kInvalidNetAddress; if (result < 0 || !NetAddressPrivateImpl::IPEndPointToNetAddress(bound_address_, &addr)) { SendBindACKError(); } else { manager_->Send(new PpapiMsg_PPBUDPSocket_BindACK( routing_id_, plugin_dispatcher_id_, socket_id_, true, addr)); } } void PepperUDPSocket::OnRecvFromCompleted(int result) { DCHECK(recvfrom_buffer_.get()); // Convert IPEndPoint we get back from RecvFrom to a PP_NetAddress_Private, // to send back. PP_NetAddress_Private addr = NetAddressPrivateImpl::kInvalidNetAddress; if (result < 0 || !NetAddressPrivateImpl::IPEndPointToNetAddress(recvfrom_address_, &addr)) { SendRecvFromACKError(); } else { manager_->Send(new PpapiMsg_PPBUDPSocket_RecvFromACK( routing_id_, plugin_dispatcher_id_, socket_id_, true, std::string(recvfrom_buffer_->data(), result), addr)); } recvfrom_buffer_ = NULL; } void PepperUDPSocket::OnSendToCompleted(int result) { DCHECK(sendto_buffer_.get()); manager_->Send(new PpapiMsg_PPBUDPSocket_SendToACK( routing_id_, plugin_dispatcher_id_, socket_id_, true, result)); sendto_buffer_ = NULL; } <commit_msg>Pepper: Make PPB_UDPSocket_Private SendTo() return proper error codes.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/renderer_host/pepper_udp_socket.h" #include <string.h> #include "base/compiler_specific.h" #include "base/logging.h" #include "content/browser/renderer_host/pepper_message_filter.h" #include "content/public/browser/browser_thread.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" #include "net/udp/udp_server_socket.h" #include "ppapi/proxy/ppapi_messages.h" #include "ppapi/shared_impl/private/net_address_private_impl.h" using content::BrowserThread; using ppapi::NetAddressPrivateImpl; PepperUDPSocket::PepperUDPSocket( PepperMessageFilter* manager, int32 routing_id, uint32 plugin_dispatcher_id, uint32 socket_id) : manager_(manager), routing_id_(routing_id), plugin_dispatcher_id_(plugin_dispatcher_id), socket_id_(socket_id) { DCHECK(manager); } PepperUDPSocket::~PepperUDPSocket() { // Make sure there are no further callbacks from socket_. if (socket_.get()) socket_->Close(); } void PepperUDPSocket::Bind(const PP_NetAddress_Private& addr) { socket_.reset(new net::UDPServerSocket(NULL, net::NetLog::Source())); net::IPEndPoint address; if (!socket_.get() || !NetAddressPrivateImpl::NetAddressToIPEndPoint(addr, &address)) { SendBindACKError(); return; } int result = socket_->Listen(address); if (result == net::OK && socket_->GetLocalAddress(&bound_address_) != net::OK) { SendBindACKError(); return; } OnBindCompleted(result); } void PepperUDPSocket::RecvFrom(int32_t num_bytes) { if (recvfrom_buffer_.get()) { SendRecvFromACKError(); return; } recvfrom_buffer_ = new net::IOBuffer(num_bytes); int result = socket_->RecvFrom( recvfrom_buffer_, num_bytes, &recvfrom_address_, base::Bind(&PepperUDPSocket::OnRecvFromCompleted, base::Unretained(this))); if (result != net::ERR_IO_PENDING) OnRecvFromCompleted(result); } void PepperUDPSocket::SendTo(const std::string& data, const PP_NetAddress_Private& addr) { if (sendto_buffer_.get() || data.empty()) { SendSendToACKError(); return; } net::IPEndPoint address; if (!NetAddressPrivateImpl::NetAddressToIPEndPoint(addr, &address)) { SendSendToACKError(); return; } int data_size = data.size(); sendto_buffer_ = new net::IOBuffer(data_size); memcpy(sendto_buffer_->data(), data.data(), data_size); int result = socket_->SendTo( sendto_buffer_, data_size, address, base::Bind(&PepperUDPSocket::OnSendToCompleted, base::Unretained(this))); if (result != net::ERR_IO_PENDING) OnSendToCompleted(result); } void PepperUDPSocket::SendRecvFromACKError() { PP_NetAddress_Private addr = NetAddressPrivateImpl::kInvalidNetAddress; manager_->Send(new PpapiMsg_PPBUDPSocket_RecvFromACK( routing_id_, plugin_dispatcher_id_, socket_id_, false, std::string(), addr)); } void PepperUDPSocket::SendSendToACKError() { manager_->Send(new PpapiMsg_PPBUDPSocket_SendToACK( routing_id_, plugin_dispatcher_id_, socket_id_, false, 0)); } void PepperUDPSocket::SendBindACKError() { PP_NetAddress_Private addr = NetAddressPrivateImpl::kInvalidNetAddress; manager_->Send(new PpapiMsg_PPBUDPSocket_BindACK( routing_id_, plugin_dispatcher_id_, socket_id_, false, addr)); } void PepperUDPSocket::OnBindCompleted(int result) { PP_NetAddress_Private addr = NetAddressPrivateImpl::kInvalidNetAddress; if (result < 0 || !NetAddressPrivateImpl::IPEndPointToNetAddress(bound_address_, &addr)) { SendBindACKError(); } else { manager_->Send(new PpapiMsg_PPBUDPSocket_BindACK( routing_id_, plugin_dispatcher_id_, socket_id_, true, addr)); } } void PepperUDPSocket::OnRecvFromCompleted(int result) { DCHECK(recvfrom_buffer_.get()); // Convert IPEndPoint we get back from RecvFrom to a PP_NetAddress_Private, // to send back. PP_NetAddress_Private addr = NetAddressPrivateImpl::kInvalidNetAddress; if (result < 0 || !NetAddressPrivateImpl::IPEndPointToNetAddress(recvfrom_address_, &addr)) { SendRecvFromACKError(); } else { manager_->Send(new PpapiMsg_PPBUDPSocket_RecvFromACK( routing_id_, plugin_dispatcher_id_, socket_id_, true, std::string(recvfrom_buffer_->data(), result), addr)); } recvfrom_buffer_ = NULL; } void PepperUDPSocket::OnSendToCompleted(int result) { DCHECK(sendto_buffer_.get()); if (result < 0) { SendSendToACKError(); } else { manager_->Send(new PpapiMsg_PPBUDPSocket_SendToACK( routing_id_, plugin_dispatcher_id_, socket_id_, true, result)); } sendto_buffer_ = NULL; } <|endoftext|>
<commit_before>/* Copyright 2017 creatorlxd 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"stdafx.h" #include "../Include/Mesh.h" using namespace SpaceGameEngine; REGISTERCOMPONENTCLASS(MeshComponent); SpaceGameEngine::MeshComponent::MeshComponent() :m_ObjectOctree(m_Vertices) { m_pVertexBuffer = nullptr; m_pIndexBuffer = nullptr; m_TypeName = "MeshComponent"; m_pTransform = nullptr; } void SpaceGameEngine::MeshComponent::Release() { if (m_pTransform) { Scene::GetMainScene()->m_GlobalOctree.DeleteObject(m_pFatherObject); } m_ObjectOctree.Release(); SafeRelease(m_pVertexBuffer); SafeRelease(m_pIndexBuffer); m_Vertices.clear(); m_Indices.clear(); m_pTransform = nullptr; } SpaceGameEngine::MeshComponent::~MeshComponent() { Release(); } void SpaceGameEngine::MeshComponent::InitFromMemory(int VertexSize, int IndexSize, DefaultVertex * pVertices, unsigned int* pIndices) { m_Vertices.clear(); m_Indices.clear(); m_Vertices.resize(VertexSize); m_Indices.resize(IndexSize); for (int i = 0; i < VertexSize; i++) { m_Vertices[i] = pVertices[i]; } for (int i = 0; i < IndexSize; i++) { m_Indices[i] = pIndices[i]; } } void SpaceGameEngine::MeshComponent::InitFromFile(const std::string & filename, int mode) { m_Mode = mode; if (m_Mode&ModelFileMode) { int v_s, i_s; File file(filename, FileMode::Read); file >> v_s >> i_s; m_Vertices.clear(); m_Indices.clear(); DefaultVertex vbuff; unsigned int ibuff; for (int i = 0; i < v_s; i++) { file >> vbuff.m_Position.x >> vbuff.m_Position.y >> vbuff.m_Position.z; file >> vbuff.m_Normal.x >> vbuff.m_Normal.y >> vbuff.m_Normal.z; file >> vbuff.m_TextureCoord.x >> vbuff.m_TextureCoord.y; m_Vertices.push_back(vbuff); } for (int i = 0; i < i_s; i++) { file >> ibuff; m_Indices.push_back(ibuff); } file.Close(); } } void SpaceGameEngine::MeshComponent::Start() { InitVertexBuffer(); InitIndexBuffer(); m_pTransform = dynamic_cast<TransformComponent*>(FindFatherComponent(STRING(TransformComponent))); m_ObjectOctree.BuildTree(m_Indices); if ((m_Mode&MeshComponent::DynamicMode) == 0) { if (m_pFatherObject == nullptr) { ThrowError("the father object of mesh component can not be nullptr"); } Vector<XMFLOAT3> points; for (const auto& i : m_Vertices) { points.push_back(TransformByWorldMatrix(m_pTransform->GetPosition(), m_pTransform->GetRotation(), m_pTransform->GetScale(), i.m_Position)); } m_Space = GetAxisAlignedBoundingBox(points); Scene::GetMainScene()->m_GlobalOctree.AddObject(std::make_pair(m_Space, m_pFatherObject)); } } void SpaceGameEngine::MeshComponent::Run(float DeltaTime) { if ((m_Mode&MeshComponent::DynamicMode) == 0) { if (m_pFatherObject->GetComponentByMessage(Event::PositionChange) || m_pFatherObject->GetComponentByMessage(Event::RotationChange) || m_pFatherObject->GetComponentByMessage(Event::ScaleChange)) { Vector<XMFLOAT3> points; for (const auto& i : m_Vertices) { points.push_back(TransformByWorldMatrix(m_pTransform->GetPosition(), m_pTransform->GetRotation(), m_pTransform->GetScale(), i.m_Position)); } m_Space = GetAxisAlignedBoundingBox(points); Scene::GetMainScene()->m_GlobalOctree.UpdateObject(std::make_pair(m_Space, m_pFatherObject)); } } if (m_pFatherObject->IfRender() == false) { return; } auto indices_buffer = m_ObjectOctree.Run(m_pTransform->GetPosition(), m_pTransform->GetRotation(), m_pTransform->GetScale()); D3D11_MAPPED_SUBRESOURCE mappeddata; HR(SpaceEngineWindow->GetD3DDeviceContext()->Map(m_pIndexBuffer,0,D3D11_MAP_WRITE_DISCARD,0,&mappeddata)); unsigned int* pi = reinterpret_cast<unsigned int*>(mappeddata.pData); for (int i = 0; i < indices_buffer.size(); i++) pi[i] = indices_buffer[i]; SpaceEngineWindow->GetD3DDeviceContext()->Unmap(m_pIndexBuffer, 0); unsigned int v_strides = sizeof(DefaultVertex); unsigned int v_offset = 0; GetGame()->m_Window.GetD3DDeviceContext()->IASetVertexBuffers(0, 1, &m_pVertexBuffer, &v_strides, &v_offset); GetGame()->m_Window.GetD3DDeviceContext()->IASetIndexBuffer(m_pIndexBuffer, DXGI_FORMAT_R32_UINT, 0); D3DX11_TECHNIQUE_DESC techDesc; SpaceEngineWindow->GetEffectShader().m_pTechnique->GetDesc(&techDesc); for (UINT p = 0; p < techDesc.Passes; ++p) { SpaceEngineWindow->GetEffectShader().m_pTechnique->GetPassByIndex(p)->Apply(0, SpaceEngineWindow->GetD3DDeviceContext()); SpaceEngineWindow->GetD3DDeviceContext()->DrawIndexed(indices_buffer.size(), 0, 0); } } void SpaceGameEngine::MeshComponent::InitVertexBuffer() { D3D11_BUFFER_DESC desc; desc.Usage = D3D11_USAGE_IMMUTABLE; desc.ByteWidth = sizeof(DefaultVertex)*m_Vertices.size(); desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; desc.CPUAccessFlags = 0; desc.MiscFlags = 0; desc.StructureByteStride = 0; D3D11_SUBRESOURCE_DATA initdata; initdata.pSysMem = m_Vertices.data(); HR(GetGame()->m_Window.GetD3DDevice()->CreateBuffer(&desc, &initdata, &m_pVertexBuffer)); } void SpaceGameEngine::MeshComponent::InitIndexBuffer() { D3D11_BUFFER_DESC desc; desc.Usage = D3D11_USAGE_DYNAMIC; desc.ByteWidth = sizeof(unsigned int)*m_Indices.size(); desc.BindFlags = D3D11_CPU_ACCESS_WRITE; desc.CPUAccessFlags = 0; desc.MiscFlags = 0; desc.StructureByteStride = 0; D3D11_SUBRESOURCE_DATA initdata; initdata.pSysMem = m_Indices.data(); HR(GetGame()->m_Window.GetD3DDevice()->CreateBuffer(&desc, &initdata, &m_pIndexBuffer)); } <commit_msg>fix a bug<commit_after>/* Copyright 2017 creatorlxd 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"stdafx.h" #include "../Include/Mesh.h" using namespace SpaceGameEngine; REGISTERCOMPONENTCLASS(MeshComponent); SpaceGameEngine::MeshComponent::MeshComponent() :m_ObjectOctree(m_Vertices) { m_pVertexBuffer = nullptr; m_pIndexBuffer = nullptr; m_TypeName = "MeshComponent"; m_pTransform = nullptr; } void SpaceGameEngine::MeshComponent::Release() { if (m_pTransform) { Scene::GetMainScene()->m_GlobalOctree.DeleteObject(m_pFatherObject); } m_ObjectOctree.Release(); SafeRelease(m_pVertexBuffer); SafeRelease(m_pIndexBuffer); m_Vertices.clear(); m_Indices.clear(); m_pTransform = nullptr; } SpaceGameEngine::MeshComponent::~MeshComponent() { Release(); } void SpaceGameEngine::MeshComponent::InitFromMemory(int VertexSize, int IndexSize, DefaultVertex * pVertices, unsigned int* pIndices) { m_Vertices.clear(); m_Indices.clear(); m_Vertices.resize(VertexSize); m_Indices.resize(IndexSize); for (int i = 0; i < VertexSize; i++) { m_Vertices[i] = pVertices[i]; } for (int i = 0; i < IndexSize; i++) { m_Indices[i] = pIndices[i]; } } void SpaceGameEngine::MeshComponent::InitFromFile(const std::string & filename, int mode) { m_Mode = mode; if (m_Mode&ModelFileMode) { int v_s, i_s; File file(filename, FileMode::Read); file >> v_s >> i_s; m_Vertices.clear(); m_Indices.clear(); DefaultVertex vbuff; unsigned int ibuff; for (int i = 0; i < v_s; i++) { file >> vbuff.m_Position.x >> vbuff.m_Position.y >> vbuff.m_Position.z; file >> vbuff.m_Normal.x >> vbuff.m_Normal.y >> vbuff.m_Normal.z; file >> vbuff.m_TextureCoord.x >> vbuff.m_TextureCoord.y; m_Vertices.push_back(vbuff); } for (int i = 0; i < i_s; i++) { file >> ibuff; m_Indices.push_back(ibuff); } file.Close(); } } void SpaceGameEngine::MeshComponent::Start() { InitVertexBuffer(); InitIndexBuffer(); m_pTransform = dynamic_cast<TransformComponent*>(FindFatherComponent(STRING(TransformComponent))); m_ObjectOctree.BuildTree(m_Indices); if ((m_Mode&MeshComponent::DynamicMode) == 0) { if (m_pFatherObject == nullptr) { ThrowError("the father object of mesh component can not be nullptr"); } Vector<XMFLOAT3> points; for (const auto& i : m_Vertices) { points.push_back(TransformByWorldMatrix(m_pTransform->GetPosition(), m_pTransform->GetRotation(), m_pTransform->GetScale(), i.m_Position)); } m_Space = GetAxisAlignedBoundingBox(points); Scene::GetMainScene()->m_GlobalOctree.AddObject(std::make_pair(m_Space, m_pFatherObject)); } } void SpaceGameEngine::MeshComponent::Run(float DeltaTime) { if ((m_Mode&MeshComponent::DynamicMode) == 0) { if (m_pFatherObject->GetComponentByMessage(Event::PositionChange) || m_pFatherObject->GetComponentByMessage(Event::RotationChange) || m_pFatherObject->GetComponentByMessage(Event::ScaleChange)) { Vector<XMFLOAT3> points; for (const auto& i : m_Vertices) { points.push_back(TransformByWorldMatrix(m_pTransform->GetPosition(), m_pTransform->GetRotation(), m_pTransform->GetScale(), i.m_Position)); } m_Space = GetAxisAlignedBoundingBox(points); Scene::GetMainScene()->m_GlobalOctree.UpdateObject(std::make_pair(m_Space, m_pFatherObject)); } } if (m_pFatherObject->IfRender() == false) { return; } auto indices_buffer = m_ObjectOctree.Run(m_pTransform->GetPosition(), m_pTransform->GetRotation(), m_pTransform->GetScale()); D3D11_MAPPED_SUBRESOURCE mappeddata; HR(SpaceEngineWindow->GetD3DDeviceContext()->Map(m_pIndexBuffer,0,D3D11_MAP_WRITE_DISCARD,0,&mappeddata)); unsigned int* pi = reinterpret_cast<unsigned int*>(mappeddata.pData); for (int i = 0; i < indices_buffer.size(); i++) pi[i] = indices_buffer[i]; SpaceEngineWindow->GetD3DDeviceContext()->Unmap(m_pIndexBuffer, 0); unsigned int v_strides = sizeof(DefaultVertex); unsigned int v_offset = 0; GetGame()->m_Window.GetD3DDeviceContext()->IASetVertexBuffers(0, 1, &m_pVertexBuffer, &v_strides, &v_offset); GetGame()->m_Window.GetD3DDeviceContext()->IASetIndexBuffer(m_pIndexBuffer, DXGI_FORMAT_R32_UINT, 0); D3DX11_TECHNIQUE_DESC techDesc; SpaceEngineWindow->GetEffectShader().m_pTechnique->GetDesc(&techDesc); for (UINT p = 0; p < techDesc.Passes; ++p) { SpaceEngineWindow->GetEffectShader().m_pTechnique->GetPassByIndex(p)->Apply(0, SpaceEngineWindow->GetD3DDeviceContext()); SpaceEngineWindow->GetD3DDeviceContext()->DrawIndexed(indices_buffer.size(), 0, 0); } } void SpaceGameEngine::MeshComponent::InitVertexBuffer() { D3D11_BUFFER_DESC desc; desc.Usage = D3D11_USAGE_IMMUTABLE; desc.ByteWidth = sizeof(DefaultVertex)*m_Vertices.size(); desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; desc.CPUAccessFlags = 0; desc.MiscFlags = 0; desc.StructureByteStride = 0; D3D11_SUBRESOURCE_DATA initdata; initdata.pSysMem = m_Vertices.data(); HR(GetGame()->m_Window.GetD3DDevice()->CreateBuffer(&desc, &initdata, &m_pVertexBuffer)); } void SpaceGameEngine::MeshComponent::InitIndexBuffer() { D3D11_BUFFER_DESC desc; desc.Usage = D3D11_USAGE_DYNAMIC; desc.ByteWidth = sizeof(unsigned int)*m_Indices.size(); desc.BindFlags = D3D11_BIND_INDEX_BUFFER; desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; desc.MiscFlags = 0; desc.StructureByteStride = 0; D3D11_SUBRESOURCE_DATA initdata; initdata.pSysMem = m_Indices.data(); HR(GetGame()->m_Window.GetD3DDevice()->CreateBuffer(&desc, &initdata, &m_pIndexBuffer)); } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/file_path.h" #include "base/string_number_conversions.h" #include "base/utf_string_conversions.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "content/browser/renderer_host/render_view_host.h" #include "content/browser/speech/speech_input_dispatcher_host.h" #include "content/browser/speech/speech_input_manager.h" #include "content/browser/tab_contents/tab_contents.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h" namespace speech_input { class FakeSpeechInputManager; } // This class does not need to be refcounted (typically done by PostTask) since // it will outlive the test and gets released only when the test shuts down. // Disabling refcounting here saves a bit of unnecessary code and the factory // method can return a plain pointer below as required by the real code. DISABLE_RUNNABLE_METHOD_REFCOUNT(speech_input::FakeSpeechInputManager); namespace speech_input { const char* kTestResult = "Pictures of the moon"; class FakeSpeechInputManager : public SpeechInputManager { public: FakeSpeechInputManager() : caller_id_(0), delegate_(NULL), did_cancel_all_(false), send_fake_response_(true) { } std::string grammar() { return grammar_; } bool did_cancel_all() { return did_cancel_all_; } void set_send_fake_response(bool send) { send_fake_response_ = send; } // SpeechInputManager methods. virtual void StartRecognition(Delegate* delegate, int caller_id, int render_process_id, int render_view_id, const gfx::Rect& element_rect, const std::string& language, const std::string& grammar, const std::string& origin_url) { VLOG(1) << "StartRecognition invoked."; EXPECT_EQ(0, caller_id_); EXPECT_EQ(NULL, delegate_); caller_id_ = caller_id; delegate_ = delegate; grammar_ = grammar; if (send_fake_response_) { // Give the fake result in a short while. MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(this, &FakeSpeechInputManager::SetFakeRecognitionResult)); } } virtual void CancelRecognition(int caller_id) { VLOG(1) << "CancelRecognition invoked."; EXPECT_EQ(caller_id_, caller_id); caller_id_ = 0; delegate_ = NULL; } virtual void StopRecording(int caller_id) { VLOG(1) << "StopRecording invoked."; EXPECT_EQ(caller_id_, caller_id); // Nothing to do here since we aren't really recording. } virtual void CancelAllRequestsWithDelegate(Delegate* delegate) { VLOG(1) << "CancelAllRequestsWithDelegate invoked."; // delegate_ is set to NULL if a fake result was received (see below), so // check that delegate_ matches the incoming parameter only when there is // no fake result sent. EXPECT_TRUE(send_fake_response_ || delegate_ == delegate); did_cancel_all_ = true; } private: void SetFakeRecognitionResult() { if (caller_id_) { // Do a check in case we were cancelled.. VLOG(1) << "Setting fake recognition result."; delegate_->DidCompleteRecording(caller_id_); SpeechInputResultArray results; results.push_back(SpeechInputResultItem(ASCIIToUTF16(kTestResult), 1.0)); delegate_->SetRecognitionResult(caller_id_, results); delegate_->DidCompleteRecognition(caller_id_); caller_id_ = 0; delegate_ = NULL; VLOG(1) << "Finished setting fake recognition result."; } } int caller_id_; Delegate* delegate_; std::string grammar_; bool did_cancel_all_; bool send_fake_response_; }; class SpeechInputBrowserTest : public InProcessBrowserTest { public: // InProcessBrowserTest methods virtual void SetUpCommandLine(CommandLine* command_line) { EXPECT_TRUE(!command_line->HasSwitch(switches::kDisableSpeechInput)); } GURL testUrl(const FilePath::CharType* filename) { const FilePath kTestDir(FILE_PATH_LITERAL("speech")); return ui_test_utils::GetTestUrl(kTestDir, FilePath(filename)); } protected: void LoadAndStartSpeechInputTest(const FilePath::CharType* filename) { // The test page calculates the speech button's coordinate in the page on // load & sets that coordinate in the URL fragment. We send mouse down & up // events at that coordinate to trigger speech recognition. GURL test_url = testUrl(filename); ui_test_utils::NavigateToURL(browser(), test_url); WebKit::WebMouseEvent mouse_event; mouse_event.type = WebKit::WebInputEvent::MouseDown; mouse_event.button = WebKit::WebMouseEvent::ButtonLeft; mouse_event.x = 0; mouse_event.y = 0; mouse_event.clickCount = 1; TabContents* tab_contents = browser()->GetSelectedTabContents(); tab_contents->render_view_host()->ForwardMouseEvent(mouse_event); mouse_event.type = WebKit::WebInputEvent::MouseUp; tab_contents->render_view_host()->ForwardMouseEvent(mouse_event); } void RunSpeechInputTest(const FilePath::CharType* filename) { LoadAndStartSpeechInputTest(filename); // The fake speech input manager would receive the speech input // request and return the test string as recognition result. The test page // then sets the URL fragment as 'pass' if it received the expected string. TabContents* tab_contents = browser()->GetSelectedTabContents(); ui_test_utils::WaitForNavigations(&tab_contents->controller(), 1); EXPECT_EQ("pass", browser()->GetSelectedTabContents()->GetURL().ref()); } // InProcessBrowserTest methods. virtual void SetUpInProcessBrowserTestFixture() { fake_speech_input_manager_.set_send_fake_response(true); speech_input_manager_ = &fake_speech_input_manager_; // Inject the fake manager factory so that the test result is returned to // the web page. SpeechInputDispatcherHost::set_manager_accessor(&fakeManagerAccessor); } virtual void TearDownInProcessBrowserTestFixture() { speech_input_manager_ = NULL; } // Factory method. static SpeechInputManager* fakeManagerAccessor() { return speech_input_manager_; } FakeSpeechInputManager fake_speech_input_manager_; // This is used by the static |fakeManagerAccessor|, and it is a pointer // rather than a direct instance per the style guide. static SpeechInputManager* speech_input_manager_; }; SpeechInputManager* SpeechInputBrowserTest::speech_input_manager_ = NULL; // Marked as DISABLED due to http://crbug.com/51337 // // TODO(satish): Once this flakiness has been fixed, add a second test here to // check for sending many clicks in succession to the speech button and verify // that it doesn't cause any crash but works as expected. This should act as the // test for http://crbug.com/59173 // // TODO(satish): Similar to above, once this flakiness has been fixed add // another test here to check that when speech recognition is in progress and // a renderer crashes, we get a call to // SpeechInputManager::CancelAllRequestsWithDelegate. // // Marked as DISABLED due to http://crbug.com/71227 #if defined(GOOGLE_CHROME_BUILD) #define MAYBE_TestBasicRecognition DISABLED_TestBasicRecognition #else #define MAYBE_TestBasicRecognition TestBasicRecognition #endif IN_PROC_BROWSER_TEST_F(SpeechInputBrowserTest, MAYBE_TestBasicRecognition) { RunSpeechInputTest(FILE_PATH_LITERAL("basic_recognition.html")); EXPECT_TRUE(fake_speech_input_manager_.grammar().empty()); } // Marked as FLAKY due to http://crbug.com/51337 // Marked as DISALBED due to http://crbug.com/71227 #if defined(GOOGLE_CHROME_BUILD) #define MAYBE_GrammarAttribute DISABLED_GrammarAttribute #else #define MAYBE_GrammarAttribute GrammarAttribute #endif IN_PROC_BROWSER_TEST_F(SpeechInputBrowserTest, MAYBE_GrammarAttribute) { RunSpeechInputTest(FILE_PATH_LITERAL("grammar_attribute.html")); EXPECT_EQ("http://example.com/grammar.xml", fake_speech_input_manager_.grammar()); } IN_PROC_BROWSER_TEST_F(SpeechInputBrowserTest, TestCancelAll) { // The test checks that the cancel-all callback gets issued when a session // is pending, so don't send a fake response. fake_speech_input_manager_.set_send_fake_response(false); LoadAndStartSpeechInputTest(FILE_PATH_LITERAL("basic_recognition.html")); // Make the renderer crash. This should trigger SpeechInputDispatcherHost to // cancel all pending sessions. GURL test_url("about:crash"); ui_test_utils::NavigateToURL(browser(), test_url); EXPECT_TRUE(fake_speech_input_manager_.did_cancel_all()); } } // namespace speech_input <commit_msg>Disable the newly added SpeechInputBrowserTest.TestCancelAll in official release builds. This is done because the test times out in the official builders, just like the other SpeechInputBrowserTest.* tests.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/file_path.h" #include "base/string_number_conversions.h" #include "base/utf_string_conversions.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "content/browser/renderer_host/render_view_host.h" #include "content/browser/speech/speech_input_dispatcher_host.h" #include "content/browser/speech/speech_input_manager.h" #include "content/browser/tab_contents/tab_contents.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h" namespace speech_input { class FakeSpeechInputManager; } // This class does not need to be refcounted (typically done by PostTask) since // it will outlive the test and gets released only when the test shuts down. // Disabling refcounting here saves a bit of unnecessary code and the factory // method can return a plain pointer below as required by the real code. DISABLE_RUNNABLE_METHOD_REFCOUNT(speech_input::FakeSpeechInputManager); namespace speech_input { const char* kTestResult = "Pictures of the moon"; class FakeSpeechInputManager : public SpeechInputManager { public: FakeSpeechInputManager() : caller_id_(0), delegate_(NULL), did_cancel_all_(false), send_fake_response_(true) { } std::string grammar() { return grammar_; } bool did_cancel_all() { return did_cancel_all_; } void set_send_fake_response(bool send) { send_fake_response_ = send; } // SpeechInputManager methods. virtual void StartRecognition(Delegate* delegate, int caller_id, int render_process_id, int render_view_id, const gfx::Rect& element_rect, const std::string& language, const std::string& grammar, const std::string& origin_url) { VLOG(1) << "StartRecognition invoked."; EXPECT_EQ(0, caller_id_); EXPECT_EQ(NULL, delegate_); caller_id_ = caller_id; delegate_ = delegate; grammar_ = grammar; if (send_fake_response_) { // Give the fake result in a short while. MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(this, &FakeSpeechInputManager::SetFakeRecognitionResult)); } } virtual void CancelRecognition(int caller_id) { VLOG(1) << "CancelRecognition invoked."; EXPECT_EQ(caller_id_, caller_id); caller_id_ = 0; delegate_ = NULL; } virtual void StopRecording(int caller_id) { VLOG(1) << "StopRecording invoked."; EXPECT_EQ(caller_id_, caller_id); // Nothing to do here since we aren't really recording. } virtual void CancelAllRequestsWithDelegate(Delegate* delegate) { VLOG(1) << "CancelAllRequestsWithDelegate invoked."; // delegate_ is set to NULL if a fake result was received (see below), so // check that delegate_ matches the incoming parameter only when there is // no fake result sent. EXPECT_TRUE(send_fake_response_ || delegate_ == delegate); did_cancel_all_ = true; } private: void SetFakeRecognitionResult() { if (caller_id_) { // Do a check in case we were cancelled.. VLOG(1) << "Setting fake recognition result."; delegate_->DidCompleteRecording(caller_id_); SpeechInputResultArray results; results.push_back(SpeechInputResultItem(ASCIIToUTF16(kTestResult), 1.0)); delegate_->SetRecognitionResult(caller_id_, results); delegate_->DidCompleteRecognition(caller_id_); caller_id_ = 0; delegate_ = NULL; VLOG(1) << "Finished setting fake recognition result."; } } int caller_id_; Delegate* delegate_; std::string grammar_; bool did_cancel_all_; bool send_fake_response_; }; class SpeechInputBrowserTest : public InProcessBrowserTest { public: // InProcessBrowserTest methods virtual void SetUpCommandLine(CommandLine* command_line) { EXPECT_TRUE(!command_line->HasSwitch(switches::kDisableSpeechInput)); } GURL testUrl(const FilePath::CharType* filename) { const FilePath kTestDir(FILE_PATH_LITERAL("speech")); return ui_test_utils::GetTestUrl(kTestDir, FilePath(filename)); } protected: void LoadAndStartSpeechInputTest(const FilePath::CharType* filename) { // The test page calculates the speech button's coordinate in the page on // load & sets that coordinate in the URL fragment. We send mouse down & up // events at that coordinate to trigger speech recognition. GURL test_url = testUrl(filename); ui_test_utils::NavigateToURL(browser(), test_url); WebKit::WebMouseEvent mouse_event; mouse_event.type = WebKit::WebInputEvent::MouseDown; mouse_event.button = WebKit::WebMouseEvent::ButtonLeft; mouse_event.x = 0; mouse_event.y = 0; mouse_event.clickCount = 1; TabContents* tab_contents = browser()->GetSelectedTabContents(); tab_contents->render_view_host()->ForwardMouseEvent(mouse_event); mouse_event.type = WebKit::WebInputEvent::MouseUp; tab_contents->render_view_host()->ForwardMouseEvent(mouse_event); } void RunSpeechInputTest(const FilePath::CharType* filename) { LoadAndStartSpeechInputTest(filename); // The fake speech input manager would receive the speech input // request and return the test string as recognition result. The test page // then sets the URL fragment as 'pass' if it received the expected string. TabContents* tab_contents = browser()->GetSelectedTabContents(); ui_test_utils::WaitForNavigations(&tab_contents->controller(), 1); EXPECT_EQ("pass", browser()->GetSelectedTabContents()->GetURL().ref()); } // InProcessBrowserTest methods. virtual void SetUpInProcessBrowserTestFixture() { fake_speech_input_manager_.set_send_fake_response(true); speech_input_manager_ = &fake_speech_input_manager_; // Inject the fake manager factory so that the test result is returned to // the web page. SpeechInputDispatcherHost::set_manager_accessor(&fakeManagerAccessor); } virtual void TearDownInProcessBrowserTestFixture() { speech_input_manager_ = NULL; } // Factory method. static SpeechInputManager* fakeManagerAccessor() { return speech_input_manager_; } FakeSpeechInputManager fake_speech_input_manager_; // This is used by the static |fakeManagerAccessor|, and it is a pointer // rather than a direct instance per the style guide. static SpeechInputManager* speech_input_manager_; }; SpeechInputManager* SpeechInputBrowserTest::speech_input_manager_ = NULL; // Marked as DISABLED due to http://crbug.com/51337 // // TODO(satish): Once this flakiness has been fixed, add a second test here to // check for sending many clicks in succession to the speech button and verify // that it doesn't cause any crash but works as expected. This should act as the // test for http://crbug.com/59173 // // TODO(satish): Similar to above, once this flakiness has been fixed add // another test here to check that when speech recognition is in progress and // a renderer crashes, we get a call to // SpeechInputManager::CancelAllRequestsWithDelegate. // // Marked as DISABLED due to http://crbug.com/71227 #if defined(GOOGLE_CHROME_BUILD) #define MAYBE_TestBasicRecognition DISABLED_TestBasicRecognition #else #define MAYBE_TestBasicRecognition TestBasicRecognition #endif IN_PROC_BROWSER_TEST_F(SpeechInputBrowserTest, MAYBE_TestBasicRecognition) { RunSpeechInputTest(FILE_PATH_LITERAL("basic_recognition.html")); EXPECT_TRUE(fake_speech_input_manager_.grammar().empty()); } // Marked as FLAKY due to http://crbug.com/51337 // Marked as DISALBED due to http://crbug.com/71227 #if defined(GOOGLE_CHROME_BUILD) #define MAYBE_GrammarAttribute DISABLED_GrammarAttribute #else #define MAYBE_GrammarAttribute GrammarAttribute #endif IN_PROC_BROWSER_TEST_F(SpeechInputBrowserTest, MAYBE_GrammarAttribute) { RunSpeechInputTest(FILE_PATH_LITERAL("grammar_attribute.html")); EXPECT_EQ("http://example.com/grammar.xml", fake_speech_input_manager_.grammar()); } // Marked as DISABLED due to http://crbug.com/71227 #if defined(GOOGLE_CHROME_BUILD) #define MAYBE_TestCancelAll DISABLED_TestCancelAll #else #define MAYBE_TestCancelAll TestCancelAll #endif IN_PROC_BROWSER_TEST_F(SpeechInputBrowserTest, MAYBE_TestCancelAll) { // The test checks that the cancel-all callback gets issued when a session // is pending, so don't send a fake response. fake_speech_input_manager_.set_send_fake_response(false); LoadAndStartSpeechInputTest(FILE_PATH_LITERAL("basic_recognition.html")); // Make the renderer crash. This should trigger SpeechInputDispatcherHost to // cancel all pending sessions. GURL test_url("about:crash"); ui_test_utils::NavigateToURL(browser(), test_url); EXPECT_TRUE(fake_speech_input_manager_.did_cancel_all()); } } // namespace speech_input <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: VTable.cxx,v $ * * $Revision: 1.19 $ * * last change: $Author: hr $ $Date: 2006-06-20 02:11:23 $ * * 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 _CONNECTIVITY_SDBCX_TABLE_HXX_ #include "connectivity/sdbcx/VTable.hxx" #endif #ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_ #include <com/sun/star/lang/DisposedException.hpp> #endif #ifndef _CONNECTIVITY_SDBCX_INDEX_HXX_ #include "connectivity/sdbcx/VIndex.hxx" #endif #ifndef _COMPHELPER_SEQUENCE_HXX_ #include <comphelper/sequence.hxx> #endif #ifndef _CONNECTIVITY_SDBCX_COLLECTION_HXX_ #include "connectivity/sdbcx/VCollection.hxx" #endif #ifndef CONNECTIVITY_CONNECTION_HXX #include "TConnection.hxx" #endif #ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_ #include "connectivity/sdbcx/VColumn.hxx" #endif #ifndef _CONNECTIVITY_SDBCX_KEY_HXX_ #include "connectivity/sdbcx/VKey.hxx" #endif #ifndef _CONNECTIVITY_DBTOOLS_HXX_ #include "connectivity/dbtools.hxx" #endif #ifndef _DBHELPER_DBEXCEPTION_HXX_ #include <connectivity/dbexception.hxx> #endif // ------------------------------------------------------------------------- using namespace ::connectivity; using namespace ::connectivity::sdbcx; using namespace ::dbtools; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; // ----------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OTable::getImplementationName( ) throw (::com::sun::star::uno::RuntimeException) { if(isNew()) return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.VTableDescriptor"); return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.Table"); } // ----------------------------------------------------------------------------- ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL OTable::getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException) { ::com::sun::star::uno::Sequence< ::rtl::OUString > aSupported(1); if(isNew()) aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.TableDescriptor"); else aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.Table"); return aSupported; } // ----------------------------------------------------------------------------- sal_Bool SAL_CALL OTable::supportsService( const ::rtl::OUString& _rServiceName ) throw(::com::sun::star::uno::RuntimeException) { Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames()); const ::rtl::OUString* pSupported = aSupported.getConstArray(); const ::rtl::OUString* pEnd = pSupported + aSupported.getLength(); for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported) ; return pSupported != pEnd; } // ------------------------------------------------------------------------- OTable::OTable(OCollection* _pTables, sal_Bool _bCase) : OTableDescriptor_BASE(m_aMutex) ,ODescriptor(OTableDescriptor_BASE::rBHelper,_bCase,sal_True) ,m_pKeys(NULL) ,m_pColumns(NULL) ,m_pIndexes(NULL) ,m_pTables(_pTables) { } // ----------------------------------------------------------------------------- OTable::OTable( OCollection* _pTables, sal_Bool _bCase, const ::rtl::OUString& _Name, const ::rtl::OUString& _Type, const ::rtl::OUString& _Description,const ::rtl::OUString& _SchemaName, const ::rtl::OUString& _CatalogName) : OTableDescriptor_BASE(m_aMutex) ,ODescriptor(OTableDescriptor_BASE::rBHelper,_bCase) ,m_CatalogName(_CatalogName) ,m_SchemaName(_SchemaName) ,m_Description(_Description) ,m_Type(_Type) ,m_pKeys(NULL) ,m_pColumns(NULL) ,m_pIndexes(NULL) ,m_pTables(_pTables) { m_Name = _Name; } // ------------------------------------------------------------------------- OTable::~OTable() { delete m_pKeys; delete m_pColumns; delete m_pIndexes; } // ------------------------------------------------------------------------- void OTable::construct() { ODescriptor::construct(); sal_Int32 nAttrib = isNew() ? 0 : PropertyAttribute::READONLY; registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_CATALOGNAME), PROPERTY_ID_CATALOGNAME,nAttrib,&m_CatalogName, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL))); registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCHEMANAME), PROPERTY_ID_SCHEMANAME, nAttrib,&m_SchemaName, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL))); registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DESCRIPTION), PROPERTY_ID_DESCRIPTION,nAttrib,&m_Description, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL))); registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE), PROPERTY_ID_TYPE, nAttrib,&m_Type, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL))); } // ----------------------------------------------------------------------------- void SAL_CALL OTable::acquire() throw() { OTableDescriptor_BASE::acquire(); } // ----------------------------------------------------------------------------- void SAL_CALL OTable::release() throw() { OTableDescriptor_BASE::release(); } // ------------------------------------------------------------------------- Any SAL_CALL OTable::queryInterface( const Type & rType ) throw(RuntimeException) { Any aRet = ODescriptor::queryInterface( rType); if(!aRet.hasValue()) { if(!isNew()) aRet = OTable_BASE::queryInterface( rType); if(isNew() && (rType == getCppuType( (Reference<XIndexesSupplier>*)0))) return Any(); if(!aRet.hasValue()) aRet = OTableDescriptor_BASE::queryInterface( rType); } return aRet; } // ------------------------------------------------------------------------- Sequence< Type > SAL_CALL OTable::getTypes( ) throw(RuntimeException) { if(isNew()) return ::comphelper::concatSequences(ODescriptor::getTypes(),OTableDescriptor_BASE::getTypes()); return ::comphelper::concatSequences(ODescriptor::getTypes(),OTableDescriptor_BASE::getTypes(),OTable_BASE::getTypes()); } // ------------------------------------------------------------------------- void SAL_CALL OTable::disposing(void) { ODescriptor::disposing(); ::osl::MutexGuard aGuard(m_aMutex); if(m_pKeys) m_pKeys->disposing(); if(m_pColumns) m_pColumns->disposing(); if(m_pIndexes) m_pIndexes->disposing(); m_pTables = NULL; } // ----------------------------------------------------------------------------- // XColumnsSupplier Reference< XNameAccess > SAL_CALL OTable::getColumns( ) throw(RuntimeException) { ::osl::MutexGuard aGuard(m_aMutex); checkDisposed(OTableDescriptor_BASE::rBHelper.bDisposed); try { if ( !m_pColumns ) refreshColumns(); } catch( const RuntimeException& ) { // allowed to leave this method throw; } catch( const Exception& ) { // allowed } return m_pColumns; } // ------------------------------------------------------------------------- // XKeysSupplier Reference< XIndexAccess > SAL_CALL OTable::getKeys( ) throw(RuntimeException) { ::osl::MutexGuard aGuard(m_aMutex); checkDisposed(OTableDescriptor_BASE::rBHelper.bDisposed); try { if(!m_pKeys) refreshKeys(); } catch( const RuntimeException& ) { // allowed to leave this method throw; } catch( const Exception& ) { // allowed } return m_pKeys; } // ----------------------------------------------------------------------------- cppu::IPropertyArrayHelper* OTable::createArrayHelper( sal_Int32 /*_nId*/ ) const { return doCreateArrayHelper(); } // ------------------------------------------------------------------------- cppu::IPropertyArrayHelper & OTable::getInfoHelper() { return *const_cast<OTable*>(this)->getArrayHelper(isNew() ? 1 : 0); } // ------------------------------------------------------------------------- Reference< XPropertySet > SAL_CALL OTable::createDataDescriptor( ) throw(RuntimeException) { ::osl::MutexGuard aGuard(m_aMutex); checkDisposed(OTableDescriptor_BASE::rBHelper.bDisposed); OTable* pTable = new OTable(m_pTables,isCaseSensitive(),m_Name,m_Type,m_Description,m_SchemaName,m_CatalogName); pTable->setNew(sal_True); return pTable; } // ------------------------------------------------------------------------- // XIndexesSupplier Reference< XNameAccess > SAL_CALL OTable::getIndexes( ) throw(RuntimeException) { ::osl::MutexGuard aGuard(m_aMutex); checkDisposed(OTableDescriptor_BASE::rBHelper.bDisposed); try { if ( !m_pIndexes ) refreshIndexes(); } catch( const RuntimeException& ) { // allowed to leave this method throw; } catch( const Exception& ) { // allowed } return m_pIndexes; } // ------------------------------------------------------------------------- // XRename void SAL_CALL OTable::rename( const ::rtl::OUString& newName ) throw(SQLException, ElementExistException, RuntimeException) { ::osl::MutexGuard aGuard(m_aMutex); checkDisposed(OTableDescriptor_BASE::rBHelper.bDisposed); ::rtl::OUString sOldComposedName = getName(); Reference< XDatabaseMetaData> xMetaData = getMetaData(); if ( xMetaData.is() ) ::dbtools::qualifiedNameComponents(xMetaData,newName,m_CatalogName,m_SchemaName,m_Name,::dbtools::eInDataManipulation); else m_Name = newName; m_pTables->renameObject(sOldComposedName,newName); } // ----------------------------------------------------------------------------- Reference< XDatabaseMetaData> OTable::getMetaData() const { return NULL; } // ------------------------------------------------------------------------- // XAlterTable void SAL_CALL OTable::alterColumnByName( const ::rtl::OUString& /*colName*/, const Reference< XPropertySet >& /*descriptor*/ ) throw(SQLException, NoSuchElementException, RuntimeException) { throwFeatureNotImplementedException( "XAlterTable::alterColumnByName", *this ); } // ------------------------------------------------------------------------- void SAL_CALL OTable::alterColumnByIndex( sal_Int32 /*index*/, const Reference< XPropertySet >& /*descriptor*/ ) throw(SQLException, ::com::sun::star::lang::IndexOutOfBoundsException, RuntimeException) { throwFeatureNotImplementedException( "XAlterTable::alterColumnByIndex", *this ); } // ------------------------------------------------------------------------- ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL OTable::getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException) { return ::cppu::OPropertySetHelper::createPropertySetInfo(getInfoHelper()); } // ----------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OTable::getName() throw(::com::sun::star::uno::RuntimeException) { // this is only correct for tables who haven't a schema or catalog name OSL_ENSURE(!m_CatalogName.getLength(),"getName(): forgot to overload getName()!"); OSL_ENSURE(!m_SchemaName.getLength(),"getName(): forgot to overload getName()!"); return m_Name; } // ----------------------------------------------------------------------------- void SAL_CALL OTable::setName( const ::rtl::OUString& /*aName*/ ) throw(::com::sun::star::uno::RuntimeException) { } // ----------------------------------------------------------------------------- void OTable::refreshColumns() { } // ----------------------------------------------------------------------------- void OTable::refreshKeys() { } // ----------------------------------------------------------------------------- void OTable::refreshIndexes() { } // ----------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS pchfix02 (1.19.60); FILE MERGED 2006/09/01 17:22:37 kaib 1.19.60.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: VTable.cxx,v $ * * $Revision: 1.20 $ * * last change: $Author: obo $ $Date: 2006-09-17 03:12:33 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_connectivity.hxx" #ifndef _CONNECTIVITY_SDBCX_TABLE_HXX_ #include "connectivity/sdbcx/VTable.hxx" #endif #ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_ #include <com/sun/star/lang/DisposedException.hpp> #endif #ifndef _CONNECTIVITY_SDBCX_INDEX_HXX_ #include "connectivity/sdbcx/VIndex.hxx" #endif #ifndef _COMPHELPER_SEQUENCE_HXX_ #include <comphelper/sequence.hxx> #endif #ifndef _CONNECTIVITY_SDBCX_COLLECTION_HXX_ #include "connectivity/sdbcx/VCollection.hxx" #endif #ifndef CONNECTIVITY_CONNECTION_HXX #include "TConnection.hxx" #endif #ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_ #include "connectivity/sdbcx/VColumn.hxx" #endif #ifndef _CONNECTIVITY_SDBCX_KEY_HXX_ #include "connectivity/sdbcx/VKey.hxx" #endif #ifndef _CONNECTIVITY_DBTOOLS_HXX_ #include "connectivity/dbtools.hxx" #endif #ifndef _DBHELPER_DBEXCEPTION_HXX_ #include <connectivity/dbexception.hxx> #endif // ------------------------------------------------------------------------- using namespace ::connectivity; using namespace ::connectivity::sdbcx; using namespace ::dbtools; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; // ----------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OTable::getImplementationName( ) throw (::com::sun::star::uno::RuntimeException) { if(isNew()) return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.VTableDescriptor"); return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.Table"); } // ----------------------------------------------------------------------------- ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL OTable::getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException) { ::com::sun::star::uno::Sequence< ::rtl::OUString > aSupported(1); if(isNew()) aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.TableDescriptor"); else aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.Table"); return aSupported; } // ----------------------------------------------------------------------------- sal_Bool SAL_CALL OTable::supportsService( const ::rtl::OUString& _rServiceName ) throw(::com::sun::star::uno::RuntimeException) { Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames()); const ::rtl::OUString* pSupported = aSupported.getConstArray(); const ::rtl::OUString* pEnd = pSupported + aSupported.getLength(); for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported) ; return pSupported != pEnd; } // ------------------------------------------------------------------------- OTable::OTable(OCollection* _pTables, sal_Bool _bCase) : OTableDescriptor_BASE(m_aMutex) ,ODescriptor(OTableDescriptor_BASE::rBHelper,_bCase,sal_True) ,m_pKeys(NULL) ,m_pColumns(NULL) ,m_pIndexes(NULL) ,m_pTables(_pTables) { } // ----------------------------------------------------------------------------- OTable::OTable( OCollection* _pTables, sal_Bool _bCase, const ::rtl::OUString& _Name, const ::rtl::OUString& _Type, const ::rtl::OUString& _Description,const ::rtl::OUString& _SchemaName, const ::rtl::OUString& _CatalogName) : OTableDescriptor_BASE(m_aMutex) ,ODescriptor(OTableDescriptor_BASE::rBHelper,_bCase) ,m_CatalogName(_CatalogName) ,m_SchemaName(_SchemaName) ,m_Description(_Description) ,m_Type(_Type) ,m_pKeys(NULL) ,m_pColumns(NULL) ,m_pIndexes(NULL) ,m_pTables(_pTables) { m_Name = _Name; } // ------------------------------------------------------------------------- OTable::~OTable() { delete m_pKeys; delete m_pColumns; delete m_pIndexes; } // ------------------------------------------------------------------------- void OTable::construct() { ODescriptor::construct(); sal_Int32 nAttrib = isNew() ? 0 : PropertyAttribute::READONLY; registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_CATALOGNAME), PROPERTY_ID_CATALOGNAME,nAttrib,&m_CatalogName, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL))); registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCHEMANAME), PROPERTY_ID_SCHEMANAME, nAttrib,&m_SchemaName, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL))); registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DESCRIPTION), PROPERTY_ID_DESCRIPTION,nAttrib,&m_Description, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL))); registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE), PROPERTY_ID_TYPE, nAttrib,&m_Type, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL))); } // ----------------------------------------------------------------------------- void SAL_CALL OTable::acquire() throw() { OTableDescriptor_BASE::acquire(); } // ----------------------------------------------------------------------------- void SAL_CALL OTable::release() throw() { OTableDescriptor_BASE::release(); } // ------------------------------------------------------------------------- Any SAL_CALL OTable::queryInterface( const Type & rType ) throw(RuntimeException) { Any aRet = ODescriptor::queryInterface( rType); if(!aRet.hasValue()) { if(!isNew()) aRet = OTable_BASE::queryInterface( rType); if(isNew() && (rType == getCppuType( (Reference<XIndexesSupplier>*)0))) return Any(); if(!aRet.hasValue()) aRet = OTableDescriptor_BASE::queryInterface( rType); } return aRet; } // ------------------------------------------------------------------------- Sequence< Type > SAL_CALL OTable::getTypes( ) throw(RuntimeException) { if(isNew()) return ::comphelper::concatSequences(ODescriptor::getTypes(),OTableDescriptor_BASE::getTypes()); return ::comphelper::concatSequences(ODescriptor::getTypes(),OTableDescriptor_BASE::getTypes(),OTable_BASE::getTypes()); } // ------------------------------------------------------------------------- void SAL_CALL OTable::disposing(void) { ODescriptor::disposing(); ::osl::MutexGuard aGuard(m_aMutex); if(m_pKeys) m_pKeys->disposing(); if(m_pColumns) m_pColumns->disposing(); if(m_pIndexes) m_pIndexes->disposing(); m_pTables = NULL; } // ----------------------------------------------------------------------------- // XColumnsSupplier Reference< XNameAccess > SAL_CALL OTable::getColumns( ) throw(RuntimeException) { ::osl::MutexGuard aGuard(m_aMutex); checkDisposed(OTableDescriptor_BASE::rBHelper.bDisposed); try { if ( !m_pColumns ) refreshColumns(); } catch( const RuntimeException& ) { // allowed to leave this method throw; } catch( const Exception& ) { // allowed } return m_pColumns; } // ------------------------------------------------------------------------- // XKeysSupplier Reference< XIndexAccess > SAL_CALL OTable::getKeys( ) throw(RuntimeException) { ::osl::MutexGuard aGuard(m_aMutex); checkDisposed(OTableDescriptor_BASE::rBHelper.bDisposed); try { if(!m_pKeys) refreshKeys(); } catch( const RuntimeException& ) { // allowed to leave this method throw; } catch( const Exception& ) { // allowed } return m_pKeys; } // ----------------------------------------------------------------------------- cppu::IPropertyArrayHelper* OTable::createArrayHelper( sal_Int32 /*_nId*/ ) const { return doCreateArrayHelper(); } // ------------------------------------------------------------------------- cppu::IPropertyArrayHelper & OTable::getInfoHelper() { return *const_cast<OTable*>(this)->getArrayHelper(isNew() ? 1 : 0); } // ------------------------------------------------------------------------- Reference< XPropertySet > SAL_CALL OTable::createDataDescriptor( ) throw(RuntimeException) { ::osl::MutexGuard aGuard(m_aMutex); checkDisposed(OTableDescriptor_BASE::rBHelper.bDisposed); OTable* pTable = new OTable(m_pTables,isCaseSensitive(),m_Name,m_Type,m_Description,m_SchemaName,m_CatalogName); pTable->setNew(sal_True); return pTable; } // ------------------------------------------------------------------------- // XIndexesSupplier Reference< XNameAccess > SAL_CALL OTable::getIndexes( ) throw(RuntimeException) { ::osl::MutexGuard aGuard(m_aMutex); checkDisposed(OTableDescriptor_BASE::rBHelper.bDisposed); try { if ( !m_pIndexes ) refreshIndexes(); } catch( const RuntimeException& ) { // allowed to leave this method throw; } catch( const Exception& ) { // allowed } return m_pIndexes; } // ------------------------------------------------------------------------- // XRename void SAL_CALL OTable::rename( const ::rtl::OUString& newName ) throw(SQLException, ElementExistException, RuntimeException) { ::osl::MutexGuard aGuard(m_aMutex); checkDisposed(OTableDescriptor_BASE::rBHelper.bDisposed); ::rtl::OUString sOldComposedName = getName(); Reference< XDatabaseMetaData> xMetaData = getMetaData(); if ( xMetaData.is() ) ::dbtools::qualifiedNameComponents(xMetaData,newName,m_CatalogName,m_SchemaName,m_Name,::dbtools::eInDataManipulation); else m_Name = newName; m_pTables->renameObject(sOldComposedName,newName); } // ----------------------------------------------------------------------------- Reference< XDatabaseMetaData> OTable::getMetaData() const { return NULL; } // ------------------------------------------------------------------------- // XAlterTable void SAL_CALL OTable::alterColumnByName( const ::rtl::OUString& /*colName*/, const Reference< XPropertySet >& /*descriptor*/ ) throw(SQLException, NoSuchElementException, RuntimeException) { throwFeatureNotImplementedException( "XAlterTable::alterColumnByName", *this ); } // ------------------------------------------------------------------------- void SAL_CALL OTable::alterColumnByIndex( sal_Int32 /*index*/, const Reference< XPropertySet >& /*descriptor*/ ) throw(SQLException, ::com::sun::star::lang::IndexOutOfBoundsException, RuntimeException) { throwFeatureNotImplementedException( "XAlterTable::alterColumnByIndex", *this ); } // ------------------------------------------------------------------------- ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL OTable::getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException) { return ::cppu::OPropertySetHelper::createPropertySetInfo(getInfoHelper()); } // ----------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OTable::getName() throw(::com::sun::star::uno::RuntimeException) { // this is only correct for tables who haven't a schema or catalog name OSL_ENSURE(!m_CatalogName.getLength(),"getName(): forgot to overload getName()!"); OSL_ENSURE(!m_SchemaName.getLength(),"getName(): forgot to overload getName()!"); return m_Name; } // ----------------------------------------------------------------------------- void SAL_CALL OTable::setName( const ::rtl::OUString& /*aName*/ ) throw(::com::sun::star::uno::RuntimeException) { } // ----------------------------------------------------------------------------- void OTable::refreshColumns() { } // ----------------------------------------------------------------------------- void OTable::refreshKeys() { } // ----------------------------------------------------------------------------- void OTable::refreshIndexes() { } // ----------------------------------------------------------------------------- <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: sqlerror.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: ihi $ $Date: 2007-11-21 14:59:40 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_connectivity.hxx" #include "connectivity/sqlerror.hxx" /** === begin UNO includes === **/ #include <com/sun/star/sdbc/SQLException.hpp> /** === end UNO includes === **/ #include <comphelper/officeresourcebundle.hxx> #include <cppuhelper/exc_hlp.hxx> #include <rtl/ustrbuf.hxx> //........................................................................ namespace connectivity { //........................................................................ /** === begin UNO using === **/ using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::UNO_QUERY; using ::com::sun::star::uno::UNO_QUERY_THROW; using ::com::sun::star::uno::Exception; using ::com::sun::star::uno::RuntimeException; using ::com::sun::star::uno::Any; using ::com::sun::star::uno::makeAny; using ::com::sun::star::uno::XInterface; using ::com::sun::star::sdbc::SQLException; using ::com::sun::star::uno::Type; /** === end UNO using === **/ //using SQLError::ParamValue; // GCC (unxlngi6) does not like this namespace { typedef SQLError::ParamValue ParamValue; } //==================================================================== //= SQLError_Impl - declaration //==================================================================== class SQLError_Impl { public: SQLError_Impl( const ::comphelper::ComponentContext& _rContext ); ~SQLError_Impl(); // versions of the public SQLError methods which are just delegated to this impl-class static const ::rtl::OUString& getMessagePrefix(); ::rtl::OUString getErrorMessage( const ErrorCondition _eCondition, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ); ::rtl::OUString getSQLState( const ErrorCondition _eCondition ); static ErrorCode getErrorCode( const ErrorCondition _eCondition ); void raiseException( const ErrorCondition _eCondition, const Reference< XInterface >& _rxContext, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ); void raiseException( const ErrorCondition _eCondition, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ); void raiseTypedException( const ErrorCondition _eCondition, const Reference< XInterface >& _rxContext, const Type& _rExceptionType, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ); SQLException getSQLException( const ErrorCondition _eCondition, const Reference< XInterface >& _rxContext, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ); private: /// returns the basic error message associated with the given error condition, without any parameter replacements ::rtl::OUString impl_getErrorMessage( const ErrorCondition& _eCondition ); /// returns the SQLState associated with the given error condition ::rtl::OUString impl_getSQLState( const ErrorCondition& _eCondition ); /// returns an SQLException describing the given error condition SQLException impl_buildSQLException( const ErrorCondition _eCondition, const Reference< XInterface >& _rxContext, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ); /// initializes our resource bundle bool impl_initResources(); private: ::osl::Mutex m_aMutex; ::comphelper::ComponentContext m_aContext; ::std::auto_ptr< ::comphelper::OfficeResourceBundle > m_pResources; bool m_bAttemptedInit; }; //==================================================================== //= SQLError_Impl - implementation //==================================================================== //-------------------------------------------------------------------- SQLError_Impl::SQLError_Impl( const ::comphelper::ComponentContext& _rContext ) :m_aContext( _rContext ) ,m_pResources( ) ,m_bAttemptedInit( false ) { } //-------------------------------------------------------------------- SQLError_Impl::~SQLError_Impl() { } //-------------------------------------------------------------------- const ::rtl::OUString& SQLError_Impl::getMessagePrefix() { static ::rtl::OUString s_sMessagePrefix( RTL_CONSTASCII_USTRINGPARAM( "[OOoBase]" ) ); return s_sMessagePrefix; } //-------------------------------------------------------------------- namespace { //................................................................ /** substitutes a given placeholder in the given message with the given value */ void lcl_substitutePlaceholder( ::rtl::OUString& _rMessage, const sal_Char* _pPlaceholder, ParamValue _rParamValue ) { size_t nPlaceholderLen( strlen( _pPlaceholder ) ); sal_Int32 nIndex = _rMessage.indexOfAsciiL( _pPlaceholder, nPlaceholderLen ); bool bHasPlaceholder = ( nIndex != -1 ); bool bWantsPlaceholder = _rParamValue.is(); OSL_ENSURE( bHasPlaceholder == bWantsPlaceholder, "lcl_substitutePlaceholder: placeholder where none is expected, or no placeholder where one is needed!" ); if ( bHasPlaceholder && bWantsPlaceholder ) _rMessage = _rMessage.replaceAt( nIndex, nPlaceholderLen, *_rParamValue ); } //................................................................ sal_Int32 lcl_getResourceID( const ErrorCondition _eCondition, bool _bSQLState ) { return 256 + 2 * ::sal::static_int_cast< sal_Int32, ErrorCondition >( _eCondition ) + ( _bSQLState ? 1 : 0 ); } } //-------------------------------------------------------------------- ::rtl::OUString SQLError_Impl::getErrorMessage( const ErrorCondition _eCondition, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ) { ::rtl::OUString sErrorMessage( impl_getErrorMessage( _eCondition ) ); lcl_substitutePlaceholder( sErrorMessage, "$1$", _rParamValue1 ); lcl_substitutePlaceholder( sErrorMessage, "$2$", _rParamValue2 ); lcl_substitutePlaceholder( sErrorMessage, "$3$", _rParamValue3 ); return sErrorMessage; } //-------------------------------------------------------------------- ::rtl::OUString SQLError_Impl::getSQLState( const ErrorCondition _eCondition ) { return impl_getSQLState( _eCondition ); } //-------------------------------------------------------------------- ErrorCode SQLError_Impl::getErrorCode( const ErrorCondition _eCondition ) { return 0 - ::sal::static_int_cast< ErrorCode, ErrorCondition >( _eCondition ); } //-------------------------------------------------------------------- void SQLError_Impl::raiseException( const ErrorCondition _eCondition, const Reference< XInterface >& _rxContext, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ) { raiseTypedException( _eCondition, _rxContext, ::cppu::UnoType< SQLException >::get(), _rParamValue1, _rParamValue2, _rParamValue3 ); } //-------------------------------------------------------------------- void SQLError_Impl::raiseException( const ErrorCondition _eCondition, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ) { raiseTypedException( _eCondition, NULL, ::cppu::UnoType< SQLException >::get(), _rParamValue1, _rParamValue2, _rParamValue3 ); } //-------------------------------------------------------------------- void SQLError_Impl::raiseTypedException( const ErrorCondition _eCondition, const Reference< XInterface >& _rxContext, const Type& _rExceptionType, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ) { if ( !::cppu::UnoType< SQLException >::get().isAssignableFrom( _rExceptionType ) ) throw ::std::bad_cast(); // default-construct an exception of the desired type Any aException( NULL, _rExceptionType ); // fill it SQLException* pException = static_cast< SQLException* >( aException.pData ); *pException = impl_buildSQLException( _eCondition, _rxContext, _rParamValue1, _rParamValue2, _rParamValue3 ); // throw it ::cppu::throwException( aException ); } //-------------------------------------------------------------------- SQLException SQLError_Impl::getSQLException( const ErrorCondition _eCondition, const Reference< XInterface >& _rxContext, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ) { return impl_buildSQLException( _eCondition, _rxContext, _rParamValue1, _rParamValue2, _rParamValue3 ); } //-------------------------------------------------------------------- SQLException SQLError_Impl::impl_buildSQLException( const ErrorCondition _eCondition, const Reference< XInterface >& _rxContext, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ) { return SQLException( getErrorMessage( _eCondition, _rParamValue1, _rParamValue2, _rParamValue3 ), _rxContext, getSQLState( _eCondition ), getErrorCode( _eCondition ), Any() ); } //-------------------------------------------------------------------- ::rtl::OUString SQLError_Impl::impl_getErrorMessage( const ErrorCondition& _eCondition ) { ::rtl::OUStringBuffer aMessage; if ( impl_initResources() ) { ::rtl::OUString sResMessage( m_pResources->loadString( lcl_getResourceID( _eCondition, false ) ) ); OSL_ENSURE( sResMessage.getLength(), "SQLError_Impl::impl_getErrorMessage: illegal error condition, or invalid resource!" ); aMessage.append( getMessagePrefix() ).appendAscii( " " ).append( sResMessage ); } return aMessage.makeStringAndClear(); } //-------------------------------------------------------------------- ::rtl::OUString SQLError_Impl::impl_getSQLState( const ErrorCondition& _eCondition ) { ::rtl::OUString sState; if ( impl_initResources() ) { sal_Int32 nResourceId( lcl_getResourceID( _eCondition, true ) ); if ( m_pResources->hasString( nResourceId ) ) sState = m_pResources->loadString( nResourceId ); } if ( !sState.getLength() ) sState = ::rtl::OUString::intern( RTL_CONSTASCII_USTRINGPARAM( "S1000" ), RTL_TEXTENCODING_ASCII_US ); return sState; } //-------------------------------------------------------------------- bool SQLError_Impl::impl_initResources() { if ( m_pResources.get() ) return true; if ( m_bAttemptedInit ) return false; ::osl::MutexGuard aGuard( m_aMutex ); m_bAttemptedInit = true; m_pResources.reset( new ::comphelper::OfficeResourceBundle( m_aContext.getUNOContext(), "sdberr" ) ); return m_pResources.get() != NULL; } //==================================================================== //= SQLError //==================================================================== //-------------------------------------------------------------------- SQLError::SQLError( const ::comphelper::ComponentContext& _rContext ) :m_pImpl( new SQLError_Impl( _rContext ) ) { } //-------------------------------------------------------------------- SQLError::~SQLError() { } //-------------------------------------------------------------------- const ::rtl::OUString& SQLError::getMessagePrefix() { return SQLError_Impl::getMessagePrefix(); } //-------------------------------------------------------------------- ::rtl::OUString SQLError::getErrorMessage( const ErrorCondition _eCondition, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ) const { return m_pImpl->getErrorMessage( _eCondition, _rParamValue1, _rParamValue2, _rParamValue3 ); } //-------------------------------------------------------------------- ::rtl::OUString SQLError::getSQLState( const ErrorCondition _eCondition ) const { return m_pImpl->getSQLState( _eCondition ); } //-------------------------------------------------------------------- ErrorCode SQLError::getErrorCode( const ErrorCondition _eCondition ) { return SQLError_Impl::getErrorCode( _eCondition ); } //-------------------------------------------------------------------- void SQLError::raiseException( const ErrorCondition _eCondition, const Reference< XInterface >& _rxContext, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ) const { m_pImpl->raiseException( _eCondition, _rxContext, _rParamValue1, _rParamValue2, _rParamValue3 ); } //-------------------------------------------------------------------- void SQLError::raiseException( const ErrorCondition _eCondition, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ) const { m_pImpl->raiseException( _eCondition, _rParamValue1, _rParamValue2, _rParamValue3 ); } //-------------------------------------------------------------------- void SQLError::raiseTypedException( const ErrorCondition _eCondition, const Reference< XInterface >& _rxContext, const Type& _rExceptionType, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ) const { m_pImpl->raiseTypedException( _eCondition, _rxContext, _rExceptionType, _rParamValue1, _rParamValue2, _rParamValue3 ); } //-------------------------------------------------------------------- SQLException SQLError::getSQLException( const ErrorCondition _eCondition, const Reference< XInterface >& _rxContext, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ) const { return m_pImpl->getSQLException( _eCondition, _rxContext, _rParamValue1, _rParamValue2, _rParamValue3 ); } //........................................................................ } // namespace connectivity //........................................................................ <commit_msg>INTEGRATION: CWS gcc430two (1.2.44); FILE MERGED 2008/01/28 09:53:03 rene 1.2.44.1: more gcc 4.3.0 things<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: sqlerror.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: ihi $ $Date: 2008-02-04 13:28:22 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_connectivity.hxx" #include "connectivity/sqlerror.hxx" /** === begin UNO includes === **/ #include <com/sun/star/sdbc/SQLException.hpp> /** === end UNO includes === **/ #include <comphelper/officeresourcebundle.hxx> #include <cppuhelper/exc_hlp.hxx> #include <rtl/ustrbuf.hxx> #include <string.h> //........................................................................ namespace connectivity { //........................................................................ /** === begin UNO using === **/ using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::UNO_QUERY; using ::com::sun::star::uno::UNO_QUERY_THROW; using ::com::sun::star::uno::Exception; using ::com::sun::star::uno::RuntimeException; using ::com::sun::star::uno::Any; using ::com::sun::star::uno::makeAny; using ::com::sun::star::uno::XInterface; using ::com::sun::star::sdbc::SQLException; using ::com::sun::star::uno::Type; /** === end UNO using === **/ //using SQLError::ParamValue; // GCC (unxlngi6) does not like this namespace { typedef SQLError::ParamValue ParamValue; } //==================================================================== //= SQLError_Impl - declaration //==================================================================== class SQLError_Impl { public: SQLError_Impl( const ::comphelper::ComponentContext& _rContext ); ~SQLError_Impl(); // versions of the public SQLError methods which are just delegated to this impl-class static const ::rtl::OUString& getMessagePrefix(); ::rtl::OUString getErrorMessage( const ErrorCondition _eCondition, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ); ::rtl::OUString getSQLState( const ErrorCondition _eCondition ); static ErrorCode getErrorCode( const ErrorCondition _eCondition ); void raiseException( const ErrorCondition _eCondition, const Reference< XInterface >& _rxContext, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ); void raiseException( const ErrorCondition _eCondition, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ); void raiseTypedException( const ErrorCondition _eCondition, const Reference< XInterface >& _rxContext, const Type& _rExceptionType, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ); SQLException getSQLException( const ErrorCondition _eCondition, const Reference< XInterface >& _rxContext, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ); private: /// returns the basic error message associated with the given error condition, without any parameter replacements ::rtl::OUString impl_getErrorMessage( const ErrorCondition& _eCondition ); /// returns the SQLState associated with the given error condition ::rtl::OUString impl_getSQLState( const ErrorCondition& _eCondition ); /// returns an SQLException describing the given error condition SQLException impl_buildSQLException( const ErrorCondition _eCondition, const Reference< XInterface >& _rxContext, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ); /// initializes our resource bundle bool impl_initResources(); private: ::osl::Mutex m_aMutex; ::comphelper::ComponentContext m_aContext; ::std::auto_ptr< ::comphelper::OfficeResourceBundle > m_pResources; bool m_bAttemptedInit; }; //==================================================================== //= SQLError_Impl - implementation //==================================================================== //-------------------------------------------------------------------- SQLError_Impl::SQLError_Impl( const ::comphelper::ComponentContext& _rContext ) :m_aContext( _rContext ) ,m_pResources( ) ,m_bAttemptedInit( false ) { } //-------------------------------------------------------------------- SQLError_Impl::~SQLError_Impl() { } //-------------------------------------------------------------------- const ::rtl::OUString& SQLError_Impl::getMessagePrefix() { static ::rtl::OUString s_sMessagePrefix( RTL_CONSTASCII_USTRINGPARAM( "[OOoBase]" ) ); return s_sMessagePrefix; } //-------------------------------------------------------------------- namespace { //................................................................ /** substitutes a given placeholder in the given message with the given value */ void lcl_substitutePlaceholder( ::rtl::OUString& _rMessage, const sal_Char* _pPlaceholder, ParamValue _rParamValue ) { size_t nPlaceholderLen( strlen( _pPlaceholder ) ); sal_Int32 nIndex = _rMessage.indexOfAsciiL( _pPlaceholder, nPlaceholderLen ); bool bHasPlaceholder = ( nIndex != -1 ); bool bWantsPlaceholder = _rParamValue.is(); OSL_ENSURE( bHasPlaceholder == bWantsPlaceholder, "lcl_substitutePlaceholder: placeholder where none is expected, or no placeholder where one is needed!" ); if ( bHasPlaceholder && bWantsPlaceholder ) _rMessage = _rMessage.replaceAt( nIndex, nPlaceholderLen, *_rParamValue ); } //................................................................ sal_Int32 lcl_getResourceID( const ErrorCondition _eCondition, bool _bSQLState ) { return 256 + 2 * ::sal::static_int_cast< sal_Int32, ErrorCondition >( _eCondition ) + ( _bSQLState ? 1 : 0 ); } } //-------------------------------------------------------------------- ::rtl::OUString SQLError_Impl::getErrorMessage( const ErrorCondition _eCondition, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ) { ::rtl::OUString sErrorMessage( impl_getErrorMessage( _eCondition ) ); lcl_substitutePlaceholder( sErrorMessage, "$1$", _rParamValue1 ); lcl_substitutePlaceholder( sErrorMessage, "$2$", _rParamValue2 ); lcl_substitutePlaceholder( sErrorMessage, "$3$", _rParamValue3 ); return sErrorMessage; } //-------------------------------------------------------------------- ::rtl::OUString SQLError_Impl::getSQLState( const ErrorCondition _eCondition ) { return impl_getSQLState( _eCondition ); } //-------------------------------------------------------------------- ErrorCode SQLError_Impl::getErrorCode( const ErrorCondition _eCondition ) { return 0 - ::sal::static_int_cast< ErrorCode, ErrorCondition >( _eCondition ); } //-------------------------------------------------------------------- void SQLError_Impl::raiseException( const ErrorCondition _eCondition, const Reference< XInterface >& _rxContext, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ) { raiseTypedException( _eCondition, _rxContext, ::cppu::UnoType< SQLException >::get(), _rParamValue1, _rParamValue2, _rParamValue3 ); } //-------------------------------------------------------------------- void SQLError_Impl::raiseException( const ErrorCondition _eCondition, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ) { raiseTypedException( _eCondition, NULL, ::cppu::UnoType< SQLException >::get(), _rParamValue1, _rParamValue2, _rParamValue3 ); } //-------------------------------------------------------------------- void SQLError_Impl::raiseTypedException( const ErrorCondition _eCondition, const Reference< XInterface >& _rxContext, const Type& _rExceptionType, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ) { if ( !::cppu::UnoType< SQLException >::get().isAssignableFrom( _rExceptionType ) ) throw ::std::bad_cast(); // default-construct an exception of the desired type Any aException( NULL, _rExceptionType ); // fill it SQLException* pException = static_cast< SQLException* >( aException.pData ); *pException = impl_buildSQLException( _eCondition, _rxContext, _rParamValue1, _rParamValue2, _rParamValue3 ); // throw it ::cppu::throwException( aException ); } //-------------------------------------------------------------------- SQLException SQLError_Impl::getSQLException( const ErrorCondition _eCondition, const Reference< XInterface >& _rxContext, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ) { return impl_buildSQLException( _eCondition, _rxContext, _rParamValue1, _rParamValue2, _rParamValue3 ); } //-------------------------------------------------------------------- SQLException SQLError_Impl::impl_buildSQLException( const ErrorCondition _eCondition, const Reference< XInterface >& _rxContext, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ) { return SQLException( getErrorMessage( _eCondition, _rParamValue1, _rParamValue2, _rParamValue3 ), _rxContext, getSQLState( _eCondition ), getErrorCode( _eCondition ), Any() ); } //-------------------------------------------------------------------- ::rtl::OUString SQLError_Impl::impl_getErrorMessage( const ErrorCondition& _eCondition ) { ::rtl::OUStringBuffer aMessage; if ( impl_initResources() ) { ::rtl::OUString sResMessage( m_pResources->loadString( lcl_getResourceID( _eCondition, false ) ) ); OSL_ENSURE( sResMessage.getLength(), "SQLError_Impl::impl_getErrorMessage: illegal error condition, or invalid resource!" ); aMessage.append( getMessagePrefix() ).appendAscii( " " ).append( sResMessage ); } return aMessage.makeStringAndClear(); } //-------------------------------------------------------------------- ::rtl::OUString SQLError_Impl::impl_getSQLState( const ErrorCondition& _eCondition ) { ::rtl::OUString sState; if ( impl_initResources() ) { sal_Int32 nResourceId( lcl_getResourceID( _eCondition, true ) ); if ( m_pResources->hasString( nResourceId ) ) sState = m_pResources->loadString( nResourceId ); } if ( !sState.getLength() ) sState = ::rtl::OUString::intern( RTL_CONSTASCII_USTRINGPARAM( "S1000" ), RTL_TEXTENCODING_ASCII_US ); return sState; } //-------------------------------------------------------------------- bool SQLError_Impl::impl_initResources() { if ( m_pResources.get() ) return true; if ( m_bAttemptedInit ) return false; ::osl::MutexGuard aGuard( m_aMutex ); m_bAttemptedInit = true; m_pResources.reset( new ::comphelper::OfficeResourceBundle( m_aContext.getUNOContext(), "sdberr" ) ); return m_pResources.get() != NULL; } //==================================================================== //= SQLError //==================================================================== //-------------------------------------------------------------------- SQLError::SQLError( const ::comphelper::ComponentContext& _rContext ) :m_pImpl( new SQLError_Impl( _rContext ) ) { } //-------------------------------------------------------------------- SQLError::~SQLError() { } //-------------------------------------------------------------------- const ::rtl::OUString& SQLError::getMessagePrefix() { return SQLError_Impl::getMessagePrefix(); } //-------------------------------------------------------------------- ::rtl::OUString SQLError::getErrorMessage( const ErrorCondition _eCondition, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ) const { return m_pImpl->getErrorMessage( _eCondition, _rParamValue1, _rParamValue2, _rParamValue3 ); } //-------------------------------------------------------------------- ::rtl::OUString SQLError::getSQLState( const ErrorCondition _eCondition ) const { return m_pImpl->getSQLState( _eCondition ); } //-------------------------------------------------------------------- ErrorCode SQLError::getErrorCode( const ErrorCondition _eCondition ) { return SQLError_Impl::getErrorCode( _eCondition ); } //-------------------------------------------------------------------- void SQLError::raiseException( const ErrorCondition _eCondition, const Reference< XInterface >& _rxContext, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ) const { m_pImpl->raiseException( _eCondition, _rxContext, _rParamValue1, _rParamValue2, _rParamValue3 ); } //-------------------------------------------------------------------- void SQLError::raiseException( const ErrorCondition _eCondition, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ) const { m_pImpl->raiseException( _eCondition, _rParamValue1, _rParamValue2, _rParamValue3 ); } //-------------------------------------------------------------------- void SQLError::raiseTypedException( const ErrorCondition _eCondition, const Reference< XInterface >& _rxContext, const Type& _rExceptionType, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ) const { m_pImpl->raiseTypedException( _eCondition, _rxContext, _rExceptionType, _rParamValue1, _rParamValue2, _rParamValue3 ); } //-------------------------------------------------------------------- SQLException SQLError::getSQLException( const ErrorCondition _eCondition, const Reference< XInterface >& _rxContext, const ParamValue& _rParamValue1, const ParamValue& _rParamValue2, const ParamValue& _rParamValue3 ) const { return m_pImpl->getSQLException( _eCondition, _rxContext, _rParamValue1, _rParamValue2, _rParamValue3 ); } //........................................................................ } // namespace connectivity //........................................................................ <|endoftext|>
<commit_before>/* Allocore Example: 2D drawing Description: This demonstrates how to do 2D drawing. Author: Lance Putnam, 2/2012 (putnam.lance at gmail dot com) */ #include "allocore/io/al_App.hpp" using namespace al; class MyApp : public App{ public: Mesh verts; MyApp(){ verts.primitive(Graphics::LINE_STRIP); verts.color(1,1,1); // Create a sine wave const int N = 128; for(int i=0; i<N; ++i){ float f = float(i)/N; verts.vertex(2*f-1, sin(f*M_PI*2)); } initWindow(); } virtual void onDraw(Graphics& g, const Viewpoint& v){ g.pushMatrix(g.PROJECTION); g.loadIdentity(); gluOrtho2D(-1,1,-1,1); g.pushMatrix(g.MODELVIEW); g.loadIdentity(); g.draw(verts); g.popMatrix(); g.popMatrix(g.PROJECTION); } }; int main(){ MyApp().start(); } <commit_msg>comments<commit_after>/* Allocore Example: 2D drawing Description: This demonstrates how to do 2D drawing. Author: Lance Putnam, 2/2012 (putnam.lance at gmail dot com) */ #include "allocore/io/al_App.hpp" using namespace al; class MyApp : public App{ public: Mesh verts; MyApp(){ verts.primitive(Graphics::LINE_STRIP); verts.color(1,1,1); // Create a sine wave const int N = 128; for(int i=0; i<N; ++i){ float f = float(i)/N; verts.vertex(2*f-1, sin(f*M_PI*2)); } initWindow(); } virtual void onDraw(Graphics& g, const Viewpoint& v){ // Start with a new projection matrix g.pushMatrix(g.PROJECTION); g.loadIdentity(); // Set up 2D orthographic projection coordinates // The args are left, right, bottom, top gluOrtho2D(-1,1,-1,1); g.pushMatrix(g.MODELVIEW); g.loadIdentity(); g.draw(verts); g.popMatrix(); // Don't forget to restore original projection matrix g.popMatrix(g.PROJECTION); } }; int main(){ MyApp().start(); } <|endoftext|>
<commit_before>#include <mlopen.h> #include "test.hpp" #include <array> #include <iterator> #include <memory> #include <utility> #include <iostream> #include <mlopen/tensor.hpp> #include <mlopen/convolution.hpp> #include <limits> // #include "network_data.hpp" #include "tensor_holder.hpp" #include "verify.hpp" #include "driver.hpp" #include "get_handle.hpp" template<class T> tensor<T> get_output_tensor(const mlopen::ConvolutionDescriptor& filter, const tensor<T>& input, const tensor<T>& weights) { assert(filter.GetBackwardOutputTensor(filter.GetForwardOutputTensor(input.desc, weights.desc), weights.desc) == input.desc); return tensor<T>{filter.GetForwardOutputTensor(input.desc, weights.desc)}; } struct verify_forward_conv { template<class T> tensor<T> cpu(const tensor<T>& input, const tensor<T>& weights, const mlopen::ConvolutionDescriptor& filter, int bias = 0) { auto out = get_output_tensor(filter, input, weights); int in_h, in_w; std::tie(std::ignore, std::ignore, in_h, in_w) = mlopen::tie4(input.desc.GetLengths()); int wei_c, wei_h, wei_w; std::tie(std::ignore, wei_c, wei_h, wei_w) = mlopen::tie4(weights.desc.GetLengths()); out.par_for_each([&](int o, int w, int i, int j) { const int start_x = i * filter.v - filter.pad_h; const int start_y = j * filter.u - filter.pad_w; double acc = bias; ford(wei_c, wei_h, wei_w)([&](int k, int x, int y) { const int in_x = start_x + x; const int in_y = start_y + y; if(in_x >= 0 && in_x < in_h && in_y >= 0 && in_y < in_w) { acc += input(o, k, in_x, in_y) * weights(w, k, x, y); } }); out(o, w, i, j) = acc; }); return out; } template<class T> tensor<T> gpu(const tensor<T>& input, const tensor<T>& weights, const mlopen::ConvolutionDescriptor& filter, int /* bias */ = 0) { auto&& handle = get_handle(); auto out = get_output_tensor(filter, input, weights); auto in_dev = handle.Write(input.data); auto wei_dev = handle.Write(weights.data); auto out_dev = handle.Create<T>(out.data.size()); size_t workspace_size = filter.ForwardGetWorkSpaceSize(weights.desc, out.desc); std::vector<char> workspace(workspace_size); auto workspace_dev = workspace_size != 0 ? handle.Write(workspace) : nullptr; int ret_algo_count; mlopenConvAlgoPerf_t perf; int alpha = 1, beta = 1; filter.FindConvFwdAlgorithm(handle, input.desc, in_dev.get(), weights.desc, wei_dev.get(), out.desc, out_dev.get(), 1, &ret_algo_count, &perf, mlopenConvolutionFastest, workspace_dev.get(), workspace_size, 0); // MD: Not performing exhaustiveSearch by default for now filter.ConvolutionForward(handle, &alpha, input.desc, in_dev.get(), weights.desc, wei_dev.get(), perf.fwd_algo, &beta, out.desc, out_dev.get(), workspace_dev.get(), workspace_size); out.data = handle.Read<T>(out_dev, out.data.size()); return out; } template<class T> void fail(float, const tensor<T>& input, const tensor<T>& weights, const mlopen::ConvolutionDescriptor& filter, int /*bias*/ = 0) { std::cout << "Forward convolution: " << std::endl; std::cout << "Input tensor: " << input.desc.ToString() << std::endl; std::cout << "Output tensor: " << filter.GetForwardOutputTensor(input.desc, weights.desc).ToString() << std::endl; std::cout << "Weights tensor: " << weights.desc.ToString() << std::endl; } }; template<class T> tensor<T> get_input_tensor(const mlopen::ConvolutionDescriptor& filter, const tensor<T>& out, const tensor<T>& weights) { assert(filter.GetForwardOutputTensor(filter.GetBackwardOutputTensor(out.desc, weights.desc), weights.desc) == out.desc); return tensor<T>{filter.GetBackwardOutputTensor(out.desc, weights.desc)}; } struct verify_backward_conv { template<class T> tensor<T> cpu(const tensor<T>& out, const tensor<T>& weights, const mlopen::ConvolutionDescriptor& filter, int /* bias */ = 0) { auto input = get_input_tensor(filter, out, weights); std::fill(input.begin(), input.end(), 0); int in_h, in_w; std::tie(std::ignore, std::ignore, in_h, in_w) = mlopen::tie4(input.desc.GetLengths()); int wei_c, wei_h, wei_w; std::tie(std::ignore, wei_c, wei_h, wei_w) = mlopen::tie4(weights.desc.GetLengths()); int out_n, out_c, out_h, out_w; std::tie(out_n, out_c, out_h, out_w) = mlopen::tie4(out.desc.GetLengths()); par_ford(out_n, wei_c)([&](int o, int k) { ford(out_c, out_h, out_w, wei_h, wei_w)([&](int w, int i, int j, int x, int y) { const int start_x = i * filter.v - filter.pad_h; const int start_y = j * filter.u - filter.pad_w; const int in_x = start_x + x; const int in_y = start_y + y; if(in_x >= 0 && in_x < in_h && in_y >= 0 && in_y < in_w) { input(o, k, in_x, in_y) += out(o, w, i, j) * weights(w, k, x, y); } }); }); return input; } template<class T> tensor<T> gpu(const tensor<T>& out, const tensor<T>& weights, const mlopen::ConvolutionDescriptor& filter, int /* bias */ = 0) { auto&& handle = get_handle(); auto input = get_input_tensor(filter, out, weights); std::fill(input.begin(), input.end(), 0); auto out_dev = handle.Write(out.data); auto wei_dev = handle.Write(weights.data); auto in_dev = handle.Create<T>(input.data.size()); int ret_algo_count; mlopenConvAlgoPerf_t perf; int alpha = 1, beta = 1; filter.FindConvBwdDataAlgorithm(handle, out.desc, out_dev.get(), weights.desc, wei_dev.get(), input.desc, in_dev.get(), 1, &ret_algo_count, &perf, mlopenConvolutionFastest, nullptr, 10, 0); // MD: Not performing exhaustiveSearch by default for now filter.ConvolutionBackwardData(handle, &alpha, out.desc, out_dev.get(), weights.desc, wei_dev.get(), perf.bwd_data_algo, &beta, input.desc, in_dev.get(), nullptr, 0); input.data = handle.Read<T>(in_dev, input.data.size()); return input; } template<class T> void fail(float, const tensor<T>& output, const tensor<T>& weights, const mlopen::ConvolutionDescriptor& filter, int /*bias*/ = 0) { std::cout << "Backward convolution: " << std::endl; std::cout << "Input tensor: " << filter.GetBackwardOutputTensor(output.desc, weights.desc).ToString() << std::endl; std::cout << "Output tensor: " << output.desc.ToString() << std::endl; std::cout << "Weights tensor: " << weights.desc.ToString() << std::endl; } }; template<class T> tensor<T> get_weight_tensor(const mlopen::ConvolutionDescriptor& filter, const tensor<T>& input, const tensor<T>& out) { return tensor<T>{filter.GetBackwardWeightsTensor(input.desc, out.desc)}; } struct verify_backward_weights_conv { template<class T> tensor<T> cpu(const tensor<T>& input, const tensor<T>& out, const mlopen::ConvolutionDescriptor& filter, int /* bias */ = 0) { auto weights = get_weight_tensor(filter, input, out); std::fill(weights.begin(), weights.end(), 0); int in_h, in_w; std::tie(std::ignore, std::ignore, in_h, in_w) = mlopen::tie4(input.desc.GetLengths()); int wei_c, wei_h, wei_w; std::tie(std::ignore, wei_c, wei_h, wei_w) = mlopen::tie4(weights.desc.GetLengths()); int out_n, out_c, out_h, out_w; std::tie(out_n, out_c, out_h, out_w) = mlopen::tie4(out.desc.GetLengths()); par_ford(out_c, wei_c, wei_h, wei_w)([&](int w, int k, int x, int y) { double acc = 0.0; ford(out_n, out_h, out_w)([&](int o, int i, int j) { const int start_x = i * filter.v - filter.pad_h; const int start_y = j * filter.u - filter.pad_w; const int in_x = start_x + x; const int in_y = start_y + y; if(in_x >= 0 && in_x < in_h && in_y >= 0 && in_y < in_w) { acc += input(o, k, in_x, in_y) * out(o, w, i, j); } }); weights(w, k, x, y) = acc; }); return weights; } template<class T> tensor<T> gpu(const tensor<T>& input, const tensor<T>& out, const mlopen::ConvolutionDescriptor& filter, int /* bias */ = 0) { auto&& handle = get_handle(); auto weights = get_weight_tensor(filter, input, out); std::fill(weights.begin(), weights.end(), 0); auto out_dev = handle.Write(out.data); auto wei_dev = handle.Create<T>(weights.data.size()); auto in_dev = handle.Write(input.data); std::size_t workspace_size = filter.ConvolutionBackwardWeightsGetWorkSpaceSize(out.desc, input.desc, weights.desc); std::vector<char> workspace(workspace_size); auto workspace_dev = handle.Write(workspace); int ret_algo_count; mlopenConvAlgoPerf_t perf; int alpha = 1, beta = 1; filter.FindConvBwdWeightsAlgorithm(handle, out.desc, out_dev.get(), input.desc, in_dev.get(), weights.desc, wei_dev.get(), 1, &ret_algo_count, &perf, mlopenConvolutionFastest, workspace_dev.get(), workspace_size, 0); // MD: Not performing exhaustiveSearch by default for now filter.ConvolutionBackwardWeights(handle, &alpha, out.desc, out_dev.get(), input.desc, in_dev.get(), perf.bwd_weights_algo, &beta, weights.desc, wei_dev.get(), workspace_dev.get(), workspace_size); weights.data = handle.Read<T>(wei_dev, weights.data.size()); return weights; } template<class T> void fail(float, const tensor<T>& input, const tensor<T>& output, const mlopen::ConvolutionDescriptor& filter, int /*bias*/ = 0) { std::cout << "Backward weights convolution: " << std::endl; std::cout << "Input tensor: " << input.desc.ToString() << std::endl; std::cout << "Output tensor: " << output.desc.ToString() << std::endl; std::cout << "Weights tensor: " << filter.GetBackwardWeightsTensor(input.desc, output.desc).ToString() << std::endl; } }; template<class T> struct conv_driver : test_driver { tensor<T> input; tensor<T> weights; mlopen::ConvolutionDescriptor filter; conv_driver() { add(input, "input", get_input_tensor()); add(weights, "weights", get_weights_tensor()); add(filter, "filter", generate_single(mlopen::ConvolutionDescriptor{0, 0})); } void run() { if (input.desc.GetLengths().at(1) == weights.desc.GetLengths().at(1)) { auto out_p = verify(verify_forward_conv{}, input, weights, filter); for(auto& x:out_p.first) x = (long(x+1)*2) % 17; // Clamp big numbers verify(verify_backward_conv{}, out_p.first, weights, filter); #if MLOPEN_USE_TINYGEMM verify(verify_backward_weights_conv{}, input, out_p.first, filter); #endif } } }; int main(int argc, const char *argv[]) { test_drive<conv_driver<float>>(argc, argv); } <commit_msg>fixing build fail<commit_after>#include <mlopen.h> #include "test.hpp" #include <array> #include <iterator> #include <memory> #include <utility> #include <iostream> #include <mlopen/tensor.hpp> #include <mlopen/convolution.hpp> #include <limits> // #include "network_data.hpp" #include "tensor_holder.hpp" #include "verify.hpp" #include "driver.hpp" #include "get_handle.hpp" template<class T> tensor<T> get_output_tensor(const mlopen::ConvolutionDescriptor& filter, const tensor<T>& input, const tensor<T>& weights) { assert(filter.GetBackwardOutputTensor(filter.GetForwardOutputTensor(input.desc, weights.desc), weights.desc) == input.desc); return tensor<T>{filter.GetForwardOutputTensor(input.desc, weights.desc)}; } struct verify_forward_conv { template<class T> tensor<T> cpu(const tensor<T>& input, const tensor<T>& weights, const mlopen::ConvolutionDescriptor& filter, int bias = 0) { auto out = get_output_tensor(filter, input, weights); int in_h, in_w; std::tie(std::ignore, std::ignore, in_h, in_w) = mlopen::tie4(input.desc.GetLengths()); int wei_c, wei_h, wei_w; std::tie(std::ignore, wei_c, wei_h, wei_w) = mlopen::tie4(weights.desc.GetLengths()); out.par_for_each([&](int o, int w, int i, int j) { const int start_x = i * filter.v - filter.pad_h; const int start_y = j * filter.u - filter.pad_w; double acc = bias; ford(wei_c, wei_h, wei_w)([&](int k, int x, int y) { const int in_x = start_x + x; const int in_y = start_y + y; if(in_x >= 0 && in_x < in_h && in_y >= 0 && in_y < in_w) { acc += input(o, k, in_x, in_y) * weights(w, k, x, y); } }); out(o, w, i, j) = acc; }); return out; } template<class T> tensor<T> gpu(const tensor<T>& input, const tensor<T>& weights, const mlopen::ConvolutionDescriptor& filter, int /* bias */ = 0) { auto&& handle = get_handle(); auto out = get_output_tensor(filter, input, weights); auto in_dev = handle.Write(input.data); auto wei_dev = handle.Write(weights.data); auto out_dev = handle.Create<T>(out.data.size()); size_t workspace_size = filter.ForwardGetWorkSpaceSize(weights.desc, input.desc, out.desc); std::vector<char> workspace(workspace_size); auto workspace_dev = workspace_size != 0 ? handle.Write(workspace) : nullptr; int ret_algo_count; mlopenConvAlgoPerf_t perf; int alpha = 1, beta = 1; filter.FindConvFwdAlgorithm(handle, input.desc, in_dev.get(), weights.desc, wei_dev.get(), out.desc, out_dev.get(), 1, &ret_algo_count, &perf, mlopenConvolutionFastest, workspace_dev.get(), workspace_size, 0); // MD: Not performing exhaustiveSearch by default for now filter.ConvolutionForward(handle, &alpha, input.desc, in_dev.get(), weights.desc, wei_dev.get(), perf.fwd_algo, &beta, out.desc, out_dev.get(), workspace_dev.get(), workspace_size); out.data = handle.Read<T>(out_dev, out.data.size()); return out; } template<class T> void fail(float, const tensor<T>& input, const tensor<T>& weights, const mlopen::ConvolutionDescriptor& filter, int /*bias*/ = 0) { std::cout << "Forward convolution: " << std::endl; std::cout << "Input tensor: " << input.desc.ToString() << std::endl; std::cout << "Output tensor: " << filter.GetForwardOutputTensor(input.desc, weights.desc).ToString() << std::endl; std::cout << "Weights tensor: " << weights.desc.ToString() << std::endl; } }; template<class T> tensor<T> get_input_tensor(const mlopen::ConvolutionDescriptor& filter, const tensor<T>& out, const tensor<T>& weights) { assert(filter.GetForwardOutputTensor(filter.GetBackwardOutputTensor(out.desc, weights.desc), weights.desc) == out.desc); return tensor<T>{filter.GetBackwardOutputTensor(out.desc, weights.desc)}; } struct verify_backward_conv { template<class T> tensor<T> cpu(const tensor<T>& out, const tensor<T>& weights, const mlopen::ConvolutionDescriptor& filter, int /* bias */ = 0) { auto input = get_input_tensor(filter, out, weights); std::fill(input.begin(), input.end(), 0); int in_h, in_w; std::tie(std::ignore, std::ignore, in_h, in_w) = mlopen::tie4(input.desc.GetLengths()); int wei_c, wei_h, wei_w; std::tie(std::ignore, wei_c, wei_h, wei_w) = mlopen::tie4(weights.desc.GetLengths()); int out_n, out_c, out_h, out_w; std::tie(out_n, out_c, out_h, out_w) = mlopen::tie4(out.desc.GetLengths()); par_ford(out_n, wei_c)([&](int o, int k) { ford(out_c, out_h, out_w, wei_h, wei_w)([&](int w, int i, int j, int x, int y) { const int start_x = i * filter.v - filter.pad_h; const int start_y = j * filter.u - filter.pad_w; const int in_x = start_x + x; const int in_y = start_y + y; if(in_x >= 0 && in_x < in_h && in_y >= 0 && in_y < in_w) { input(o, k, in_x, in_y) += out(o, w, i, j) * weights(w, k, x, y); } }); }); return input; } template<class T> tensor<T> gpu(const tensor<T>& out, const tensor<T>& weights, const mlopen::ConvolutionDescriptor& filter, int /* bias */ = 0) { auto&& handle = get_handle(); auto input = get_input_tensor(filter, out, weights); std::fill(input.begin(), input.end(), 0); auto out_dev = handle.Write(out.data); auto wei_dev = handle.Write(weights.data); auto in_dev = handle.Create<T>(input.data.size()); int ret_algo_count; mlopenConvAlgoPerf_t perf; int alpha = 1, beta = 1; filter.FindConvBwdDataAlgorithm(handle, out.desc, out_dev.get(), weights.desc, wei_dev.get(), input.desc, in_dev.get(), 1, &ret_algo_count, &perf, mlopenConvolutionFastest, nullptr, 10, 0); // MD: Not performing exhaustiveSearch by default for now filter.ConvolutionBackwardData(handle, &alpha, out.desc, out_dev.get(), weights.desc, wei_dev.get(), perf.bwd_data_algo, &beta, input.desc, in_dev.get(), nullptr, 0); input.data = handle.Read<T>(in_dev, input.data.size()); return input; } template<class T> void fail(float, const tensor<T>& output, const tensor<T>& weights, const mlopen::ConvolutionDescriptor& filter, int /*bias*/ = 0) { std::cout << "Backward convolution: " << std::endl; std::cout << "Input tensor: " << filter.GetBackwardOutputTensor(output.desc, weights.desc).ToString() << std::endl; std::cout << "Output tensor: " << output.desc.ToString() << std::endl; std::cout << "Weights tensor: " << weights.desc.ToString() << std::endl; } }; template<class T> tensor<T> get_weight_tensor(const mlopen::ConvolutionDescriptor& filter, const tensor<T>& input, const tensor<T>& out) { return tensor<T>{filter.GetBackwardWeightsTensor(input.desc, out.desc)}; } struct verify_backward_weights_conv { template<class T> tensor<T> cpu(const tensor<T>& input, const tensor<T>& out, const mlopen::ConvolutionDescriptor& filter, int /* bias */ = 0) { auto weights = get_weight_tensor(filter, input, out); std::fill(weights.begin(), weights.end(), 0); int in_h, in_w; std::tie(std::ignore, std::ignore, in_h, in_w) = mlopen::tie4(input.desc.GetLengths()); int wei_c, wei_h, wei_w; std::tie(std::ignore, wei_c, wei_h, wei_w) = mlopen::tie4(weights.desc.GetLengths()); int out_n, out_c, out_h, out_w; std::tie(out_n, out_c, out_h, out_w) = mlopen::tie4(out.desc.GetLengths()); par_ford(out_c, wei_c, wei_h, wei_w)([&](int w, int k, int x, int y) { double acc = 0.0; ford(out_n, out_h, out_w)([&](int o, int i, int j) { const int start_x = i * filter.v - filter.pad_h; const int start_y = j * filter.u - filter.pad_w; const int in_x = start_x + x; const int in_y = start_y + y; if(in_x >= 0 && in_x < in_h && in_y >= 0 && in_y < in_w) { acc += input(o, k, in_x, in_y) * out(o, w, i, j); } }); weights(w, k, x, y) = acc; }); return weights; } template<class T> tensor<T> gpu(const tensor<T>& input, const tensor<T>& out, const mlopen::ConvolutionDescriptor& filter, int /* bias */ = 0) { auto&& handle = get_handle(); auto weights = get_weight_tensor(filter, input, out); std::fill(weights.begin(), weights.end(), 0); auto out_dev = handle.Write(out.data); auto wei_dev = handle.Create<T>(weights.data.size()); auto in_dev = handle.Write(input.data); std::size_t workspace_size = filter.ConvolutionBackwardWeightsGetWorkSpaceSize(out.desc, input.desc, weights.desc); std::vector<char> workspace(workspace_size); auto workspace_dev = handle.Write(workspace); int ret_algo_count; mlopenConvAlgoPerf_t perf; int alpha = 1, beta = 1; filter.FindConvBwdWeightsAlgorithm(handle, out.desc, out_dev.get(), input.desc, in_dev.get(), weights.desc, wei_dev.get(), 1, &ret_algo_count, &perf, mlopenConvolutionFastest, workspace_dev.get(), workspace_size, 0); // MD: Not performing exhaustiveSearch by default for now filter.ConvolutionBackwardWeights(handle, &alpha, out.desc, out_dev.get(), input.desc, in_dev.get(), perf.bwd_weights_algo, &beta, weights.desc, wei_dev.get(), workspace_dev.get(), workspace_size); weights.data = handle.Read<T>(wei_dev, weights.data.size()); return weights; } template<class T> void fail(float, const tensor<T>& input, const tensor<T>& output, const mlopen::ConvolutionDescriptor& filter, int /*bias*/ = 0) { std::cout << "Backward weights convolution: " << std::endl; std::cout << "Input tensor: " << input.desc.ToString() << std::endl; std::cout << "Output tensor: " << output.desc.ToString() << std::endl; std::cout << "Weights tensor: " << filter.GetBackwardWeightsTensor(input.desc, output.desc).ToString() << std::endl; } }; template<class T> struct conv_driver : test_driver { tensor<T> input; tensor<T> weights; mlopen::ConvolutionDescriptor filter; conv_driver() { add(input, "input", get_input_tensor()); add(weights, "weights", get_weights_tensor()); add(filter, "filter", generate_single(mlopen::ConvolutionDescriptor{0, 0})); } void run() { if (input.desc.GetLengths().at(1) == weights.desc.GetLengths().at(1)) { auto out_p = verify(verify_forward_conv{}, input, weights, filter); for(auto& x:out_p.first) x = (long(x+1)*2) % 17; // Clamp big numbers verify(verify_backward_conv{}, out_p.first, weights, filter); #if MLOPEN_USE_TINYGEMM verify(verify_backward_weights_conv{}, input, out_p.first, filter); #endif } } }; int main(int argc, const char *argv[]) { test_drive<conv_driver<float>>(argc, argv); } <|endoftext|>
<commit_before>// // Copyright © 2017 Arm Ltd. All rights reserved. // SPDX-License-Identifier: MIT // #include "../../1.2/ArmnnDriverImpl.hpp" #include "Utils.h" #include <boost/test/unit_test.hpp> #include <boost/core/ignore_unused.hpp> #include <sys/system_properties.h> #include <cfloat> using namespace std; struct CapabilitiesFixture { CapabilitiesFixture() { const char* nullStr = ""; __system_property_set("Armnn.operandTypeTensorFloat32Performance.execTime", nullStr); __system_property_set("Armnn.operandTypeTensorFloat32Performance.powerUsage", nullStr); __system_property_set("Armnn.operandTypeFloat32Performance.execTime", nullStr); __system_property_set("Armnn.operandTypeFloat32Performance.powerUsage", nullStr); __system_property_set("Armnn.operandTypeTensorFloat16Performance.execTime", nullStr); __system_property_set("Armnn.operandTypeTensorFloat16Performance.powerUsage", nullStr); __system_property_set("Armnn.operandTypeFloat16Performance.execTime", nullStr); __system_property_set("Armnn.operandTypeFloat16Performance.powerUsage", nullStr); __system_property_set("Armnn.operandTypeTensorQuant8AsymmPerformance.execTime", nullStr); __system_property_set("Armnn.operandTypeTensorQuant8AsymmPerformance.powerUsage", nullStr); __system_property_set("Armnn.operandTypeTensorQuant16SymmPerformance.execTime", nullStr); __system_property_set("Armnn.operandTypeTensorQuant16SymmPerformance.powerUsage", nullStr); __system_property_set("Armnn.operandTypeTensorInt32Performance.execTime", nullStr); __system_property_set("Armnn.operandTypeTensorInt32Performance.powerUsage", nullStr); __system_property_set("Armnn.operandTypeInt32Performance.execTime", nullStr); __system_property_set("Armnn.operandTypeInt32Performance.powerUsage", nullStr); } ~CapabilitiesFixture(){} }; void CheckOperandType(const V1_2::Capabilities& capabilities, OperandType type, float execTime, float powerUsage) { PerformanceInfo perfInfo = android::nn::lookup(capabilities.operandPerformance, type); BOOST_ASSERT(perfInfo.execTime == execTime); BOOST_ASSERT(perfInfo.powerUsage == powerUsage); } BOOST_AUTO_TEST_SUITE(CapabilitiesTests) BOOST_AUTO_TEST_CASE(PerformanceCapabilitiesWithRuntime) { using namespace armnn_driver::hal_1_2; using namespace android::nn; auto getCapabilitiesFn = [&](ErrorStatus error, const V1_2::Capabilities& capabilities) { CheckOperandType(capabilities, OperandType::TENSOR_FLOAT32, 2.0f, 2.1f); CheckOperandType(capabilities, OperandType::FLOAT32, 2.2f, 2.3f); CheckOperandType(capabilities, OperandType::TENSOR_FLOAT16, 2.4f, 2.5f); CheckOperandType(capabilities, OperandType::FLOAT16, 2.6f, 2.7f); CheckOperandType(capabilities, OperandType::TENSOR_QUANT8_ASYMM, 2.8f, 2.9f); CheckOperandType(capabilities, OperandType::TENSOR_QUANT16_SYMM, 3.0f, 3.1f); CheckOperandType(capabilities, OperandType::TENSOR_INT32, 3.2f, 3.3f); CheckOperandType(capabilities, OperandType::INT32, 3.4f, 3.5f); // Unsupported operands take FLT_MAX value CheckOperandType(capabilities, OperandType::UINT32, FLT_MAX, FLT_MAX); CheckOperandType(capabilities, OperandType::BOOL, FLT_MAX, FLT_MAX); CheckOperandType(capabilities, OperandType::TENSOR_QUANT8_SYMM, FLT_MAX, FLT_MAX); CheckOperandType(capabilities, OperandType::TENSOR_QUANT16_ASYMM, FLT_MAX, FLT_MAX); CheckOperandType(capabilities, OperandType::TENSOR_BOOL8, FLT_MAX, FLT_MAX); CheckOperandType(capabilities, OperandType::TENSOR_QUANT8_SYMM_PER_CHANNEL, FLT_MAX, FLT_MAX); CheckOperandType(capabilities, OperandType::OEM, FLT_MAX, FLT_MAX); CheckOperandType(capabilities, OperandType::TENSOR_OEM_BYTE, FLT_MAX, FLT_MAX); BOOST_ASSERT(error == ErrorStatus::NONE); }; __system_property_set("Armnn.operandTypeTensorFloat32Performance.execTime", "2.0f"); __system_property_set("Armnn.operandTypeTensorFloat32Performance.powerUsage", "2.1f"); __system_property_set("Armnn.operandTypeFloat32Performance.execTime", "2.2f"); __system_property_set("Armnn.operandTypeFloat32Performance.powerUsage", "2.3f"); __system_property_set("Armnn.operandTypeTensorFloat16Performance.execTime", "2.4f"); __system_property_set("Armnn.operandTypeTensorFloat16Performance.powerUsage", "2.5f"); __system_property_set("Armnn.operandTypeFloat16Performance.execTime", "2.6f"); __system_property_set("Armnn.operandTypeFloat16Performance.powerUsage", "2.7f"); __system_property_set("Armnn.operandTypeTensorQuant8AsymmPerformance.execTime", "2.8f"); __system_property_set("Armnn.operandTypeTensorQuant8AsymmPerformance.powerUsage", "2.9f"); __system_property_set("Armnn.operandTypeTensorQuant16SymmPerformance.execTime", "3.0f"); __system_property_set("Armnn.operandTypeTensorQuant16SymmPerformance.powerUsage", "3.1f"); __system_property_set("Armnn.operandTypeTensorInt32Performance.execTime", "3.2f"); __system_property_set("Armnn.operandTypeTensorInt32Performance.powerUsage", "3.3f"); __system_property_set("Armnn.operandTypeInt32Performance.execTime", "3.4f"); __system_property_set("Armnn.operandTypeInt32Performance.powerUsage", "3.5f"); armnn::IRuntime::CreationOptions options; armnn::IRuntimePtr runtime(armnn::IRuntime::Create(options)); ArmnnDriverImpl::getCapabilities_1_2(runtime, getCapabilitiesFn); } BOOST_AUTO_TEST_CASE(PerformanceCapabilitiesUndefined) { using namespace armnn_driver::hal_1_2; using namespace android::nn; float defaultValue = .1f; auto getCapabilitiesFn = [&](ErrorStatus error, const V1_2::Capabilities& capabilities) { CheckOperandType(capabilities, OperandType::TENSOR_FLOAT32, defaultValue, defaultValue); CheckOperandType(capabilities, OperandType::FLOAT32, defaultValue, defaultValue); CheckOperandType(capabilities, OperandType::TENSOR_FLOAT16, defaultValue, defaultValue); CheckOperandType(capabilities, OperandType::FLOAT16, defaultValue, defaultValue); CheckOperandType(capabilities, OperandType::TENSOR_QUANT8_ASYMM, defaultValue, defaultValue); CheckOperandType(capabilities, OperandType::TENSOR_QUANT16_SYMM, defaultValue, defaultValue); CheckOperandType(capabilities, OperandType::TENSOR_INT32, defaultValue, defaultValue); CheckOperandType(capabilities, OperandType::INT32, defaultValue, defaultValue); // Unsupported operands take FLT_MAX value CheckOperandType(capabilities, OperandType::UINT32, FLT_MAX, FLT_MAX); CheckOperandType(capabilities, OperandType::BOOL, FLT_MAX, FLT_MAX); CheckOperandType(capabilities, OperandType::TENSOR_QUANT8_SYMM, FLT_MAX, FLT_MAX); CheckOperandType(capabilities, OperandType::TENSOR_QUANT16_ASYMM, FLT_MAX, FLT_MAX); CheckOperandType(capabilities, OperandType::TENSOR_BOOL8, FLT_MAX, FLT_MAX); CheckOperandType(capabilities, OperandType::TENSOR_QUANT8_SYMM_PER_CHANNEL, FLT_MAX, FLT_MAX); CheckOperandType(capabilities, OperandType::OEM, FLT_MAX, FLT_MAX); CheckOperandType(capabilities, OperandType::TENSOR_OEM_BYTE, FLT_MAX, FLT_MAX); BOOST_ASSERT(error == ErrorStatus::NONE); }; armnn::IRuntime::CreationOptions options; armnn::IRuntimePtr runtime(armnn::IRuntime::Create(options)); ArmnnDriverImpl::getCapabilities_1_2(runtime, getCapabilitiesFn); } BOOST_AUTO_TEST_SUITE_END()<commit_msg>IVGCVSW-3538 Fix Android driver getCapabilities_1_2() test<commit_after>// // Copyright © 2017 Arm Ltd. All rights reserved. // SPDX-License-Identifier: MIT // #include "../../1.2/ArmnnDriverImpl.hpp" #include "Utils.h" #include <boost/test/unit_test.hpp> #include <boost/core/ignore_unused.hpp> #include <sys/system_properties.h> #include <cfloat> using namespace std; struct CapabilitiesFixture { CapabilitiesFixture() { // CleanUp before the execution of each test CleanUp(); } ~CapabilitiesFixture() { // CleanUp after the execution of each test CleanUp(); } void CleanUp() { const char* nullStr = ""; __system_property_set("Armnn.operandTypeTensorFloat32Performance.execTime", nullStr); __system_property_set("Armnn.operandTypeTensorFloat32Performance.powerUsage", nullStr); __system_property_set("Armnn.operandTypeFloat32Performance.execTime", nullStr); __system_property_set("Armnn.operandTypeFloat32Performance.powerUsage", nullStr); __system_property_set("Armnn.operandTypeTensorFloat16Performance.execTime", nullStr); __system_property_set("Armnn.operandTypeTensorFloat16Performance.powerUsage", nullStr); __system_property_set("Armnn.operandTypeFloat16Performance.execTime", nullStr); __system_property_set("Armnn.operandTypeFloat16Performance.powerUsage", nullStr); __system_property_set("Armnn.operandTypeTensorQuant8AsymmPerformance.execTime", nullStr); __system_property_set("Armnn.operandTypeTensorQuant8AsymmPerformance.powerUsage", nullStr); __system_property_set("Armnn.operandTypeTensorQuant16SymmPerformance.execTime", nullStr); __system_property_set("Armnn.operandTypeTensorQuant16SymmPerformance.powerUsage", nullStr); __system_property_set("Armnn.operandTypeTensorInt32Performance.execTime", nullStr); __system_property_set("Armnn.operandTypeTensorInt32Performance.powerUsage", nullStr); __system_property_set("Armnn.operandTypeInt32Performance.execTime", nullStr); __system_property_set("Armnn.operandTypeInt32Performance.powerUsage", nullStr); } }; void CheckOperandType(const V1_2::Capabilities& capabilities, OperandType type, float execTime, float powerUsage) { PerformanceInfo perfInfo = android::nn::lookup(capabilities.operandPerformance, type); BOOST_ASSERT(perfInfo.execTime == execTime); BOOST_ASSERT(perfInfo.powerUsage == powerUsage); } BOOST_FIXTURE_TEST_SUITE(CapabilitiesTests, CapabilitiesFixture) BOOST_AUTO_TEST_CASE(PerformanceCapabilitiesWithRuntime) { using namespace armnn_driver::hal_1_2; using namespace android::nn; auto getCapabilitiesFn = [&](ErrorStatus error, const V1_2::Capabilities& capabilities) { CheckOperandType(capabilities, OperandType::TENSOR_FLOAT32, 2.0f, 2.1f); CheckOperandType(capabilities, OperandType::FLOAT32, 2.2f, 2.3f); CheckOperandType(capabilities, OperandType::TENSOR_FLOAT16, 2.4f, 2.5f); CheckOperandType(capabilities, OperandType::FLOAT16, 2.6f, 2.7f); CheckOperandType(capabilities, OperandType::TENSOR_QUANT8_ASYMM, 2.8f, 2.9f); CheckOperandType(capabilities, OperandType::TENSOR_QUANT16_SYMM, 3.0f, 3.1f); CheckOperandType(capabilities, OperandType::TENSOR_INT32, 3.2f, 3.3f); CheckOperandType(capabilities, OperandType::INT32, 3.4f, 3.5f); // Unsupported operands take FLT_MAX value CheckOperandType(capabilities, OperandType::UINT32, FLT_MAX, FLT_MAX); CheckOperandType(capabilities, OperandType::BOOL, FLT_MAX, FLT_MAX); CheckOperandType(capabilities, OperandType::TENSOR_QUANT8_SYMM, FLT_MAX, FLT_MAX); CheckOperandType(capabilities, OperandType::TENSOR_QUANT16_ASYMM, FLT_MAX, FLT_MAX); CheckOperandType(capabilities, OperandType::TENSOR_BOOL8, FLT_MAX, FLT_MAX); CheckOperandType(capabilities, OperandType::TENSOR_QUANT8_SYMM_PER_CHANNEL, FLT_MAX, FLT_MAX); CheckOperandType(capabilities, OperandType::OEM, FLT_MAX, FLT_MAX); CheckOperandType(capabilities, OperandType::TENSOR_OEM_BYTE, FLT_MAX, FLT_MAX); BOOST_ASSERT(error == ErrorStatus::NONE); }; __system_property_set("Armnn.operandTypeTensorFloat32Performance.execTime", "2.0f"); __system_property_set("Armnn.operandTypeTensorFloat32Performance.powerUsage", "2.1f"); __system_property_set("Armnn.operandTypeFloat32Performance.execTime", "2.2f"); __system_property_set("Armnn.operandTypeFloat32Performance.powerUsage", "2.3f"); __system_property_set("Armnn.operandTypeTensorFloat16Performance.execTime", "2.4f"); __system_property_set("Armnn.operandTypeTensorFloat16Performance.powerUsage", "2.5f"); __system_property_set("Armnn.operandTypeFloat16Performance.execTime", "2.6f"); __system_property_set("Armnn.operandTypeFloat16Performance.powerUsage", "2.7f"); __system_property_set("Armnn.operandTypeTensorQuant8AsymmPerformance.execTime", "2.8f"); __system_property_set("Armnn.operandTypeTensorQuant8AsymmPerformance.powerUsage", "2.9f"); __system_property_set("Armnn.operandTypeTensorQuant16SymmPerformance.execTime", "3.0f"); __system_property_set("Armnn.operandTypeTensorQuant16SymmPerformance.powerUsage", "3.1f"); __system_property_set("Armnn.operandTypeTensorInt32Performance.execTime", "3.2f"); __system_property_set("Armnn.operandTypeTensorInt32Performance.powerUsage", "3.3f"); __system_property_set("Armnn.operandTypeInt32Performance.execTime", "3.4f"); __system_property_set("Armnn.operandTypeInt32Performance.powerUsage", "3.5f"); armnn::IRuntime::CreationOptions options; armnn::IRuntimePtr runtime(armnn::IRuntime::Create(options)); ArmnnDriverImpl::getCapabilities_1_2(runtime, getCapabilitiesFn); } BOOST_AUTO_TEST_CASE(PerformanceCapabilitiesUndefined) { using namespace armnn_driver::hal_1_2; using namespace android::nn; float defaultValue = .1f; auto getCapabilitiesFn = [&](ErrorStatus error, const V1_2::Capabilities& capabilities) { CheckOperandType(capabilities, OperandType::TENSOR_FLOAT32, defaultValue, defaultValue); CheckOperandType(capabilities, OperandType::FLOAT32, defaultValue, defaultValue); CheckOperandType(capabilities, OperandType::TENSOR_FLOAT16, defaultValue, defaultValue); CheckOperandType(capabilities, OperandType::FLOAT16, defaultValue, defaultValue); CheckOperandType(capabilities, OperandType::TENSOR_QUANT8_ASYMM, defaultValue, defaultValue); CheckOperandType(capabilities, OperandType::TENSOR_QUANT16_SYMM, defaultValue, defaultValue); CheckOperandType(capabilities, OperandType::TENSOR_INT32, defaultValue, defaultValue); CheckOperandType(capabilities, OperandType::INT32, defaultValue, defaultValue); // Unsupported operands take FLT_MAX value CheckOperandType(capabilities, OperandType::UINT32, FLT_MAX, FLT_MAX); CheckOperandType(capabilities, OperandType::BOOL, FLT_MAX, FLT_MAX); CheckOperandType(capabilities, OperandType::TENSOR_QUANT8_SYMM, FLT_MAX, FLT_MAX); CheckOperandType(capabilities, OperandType::TENSOR_QUANT16_ASYMM, FLT_MAX, FLT_MAX); CheckOperandType(capabilities, OperandType::TENSOR_BOOL8, FLT_MAX, FLT_MAX); CheckOperandType(capabilities, OperandType::TENSOR_QUANT8_SYMM_PER_CHANNEL, FLT_MAX, FLT_MAX); CheckOperandType(capabilities, OperandType::OEM, FLT_MAX, FLT_MAX); CheckOperandType(capabilities, OperandType::TENSOR_OEM_BYTE, FLT_MAX, FLT_MAX); BOOST_ASSERT(error == ErrorStatus::NONE); }; armnn::IRuntime::CreationOptions options; armnn::IRuntimePtr runtime(armnn::IRuntime::Create(options)); ArmnnDriverImpl::getCapabilities_1_2(runtime, getCapabilitiesFn); } BOOST_AUTO_TEST_SUITE_END()<|endoftext|>
<commit_before><?hh /** * @author Alex Phillips <exonintrendo@gmail.com> * Date: 2/5/15 * Time: 6:05 PM */ namespace Titon\Context; use Titon\Test\TestCase; /** * @property \Titon\Context\Depository $object */ class DepositoryTest extends TestCase { protected function setUp() { parent::setUp(); $this->object = new Depository(); } public function testRegisterClassName() { $this->object->register('foo', 'Titon\\Context\\Foo'); $this->assertInstanceOf('Titon\\Context\\Foo', $this->object['foo']); } public function testClosure() { $this->object->register('bar', function() { $test = new Bar((new Foo())->setName('Foo Bar')); return $test; }); $this->assertInstanceOf('Titon\\Context\\Bar', $this->object['bar']); $this->assertEquals('Foo Bar', $this->object['bar']->getFoo()->getName()); } public function testSingleton() { $test = new Foo(); $this->object->singleton('foo', $test); $this->assertEquals('Alex Phillips', $this->object['foo']->getName()); $test = new Bar((new Foo())->setName('Foo Bar')); $this->object->singleton('bar', $test); $test = $this->object['bar']; $this->assertInstanceOf('Titon\\Context\\Bar', $test); $this->assertEquals('Foo Bar', $test->getFoo()->getName()); } public function testAutoDependencyResolution() { $test = $this->object['Titon\\Context\\Bar']; $this->assertInstanceOf('Titon\\Context\\Bar', $test); $this->assertInstanceOf('Titon\\Context\\Foo', $test->getFoo()); } public function testClassDefinitionWithMethodCalls() { $this->object->register('foo', 'Titon\\Context\\Foo')->call('setName', 'Foo Bar'); $this->assertInstanceOf('Titon\\Context\\Foo', $this->object['foo']); $this->assertEquals('Foo Bar', $this->object['foo']->getName()); } public function testCallMethodsWithObjects() { $test = $this->object['Titon\\Context\\Bar']->getFoo(); $this->assertInstanceOf('Titon\\Context\\Foo', $test); } public function testConstructorInjection() { $this->object->register('bar', 'Titon\\Context\\Bar')->with('Titon\\Context\\Foo'); $this->assertInstanceOf('Titon\\Context\\Bar', $this->object['bar']); $this->object->register('bar', 'Titon\\Context\\Bar')->with((new Foo())->setName('Foo Bar')); $this->assertInstanceOf('Titon\\Context\\Bar', $this->object['bar']); $this->assertEquals($this->object['bar']->getFoo()->getName(), 'Foo Bar'); } public function testMethodInjection() { $this->object->register('foo', 'Titon\\Context\\Foo')->call('setName', 'Foo Bar'); $this->assertEquals('Foo Bar', $this->object['foo']->getName()); } } class Foo { public $name; public function __construct($name = 'Alex Phillips') { $this->name = $name; } public function getName() { return $this->name; } public function setName($name) { $this->name = $name; return $this; } } class Bar { private $foo; public function __construct(Foo $foo) { $this->foo = $foo; } public function getFoo() { return $this->foo; } public function setFoo($foo) { $this->foo = $foo; } }<commit_msg>added test for passing constructor arguments when making the item<commit_after><?hh /** * @author Alex Phillips <exonintrendo@gmail.com> * Date: 2/5/15 * Time: 6:05 PM */ namespace Titon\Context; use Titon\Test\TestCase; /** * @property \Titon\Context\Depository $object */ class DepositoryTest extends TestCase { protected function setUp() { parent::setUp(); $this->object = new Depository(); } public function testRegisterClassName() { $this->object->register('foo', 'Titon\\Context\\Foo'); $this->assertInstanceOf('Titon\\Context\\Foo', $this->object['foo']); } public function testClosure() { $this->object->register('bar', function() { $test = new Bar((new Foo())->setName('Foo Bar')); return $test; }); $this->assertInstanceOf('Titon\\Context\\Bar', $this->object['bar']); $this->assertEquals('Foo Bar', $this->object['bar']->getFoo()->getName()); } public function testSingleton() { $test = new Foo(); $this->object->singleton('foo', $test); $this->assertEquals('Alex Phillips', $this->object['foo']->getName()); $test = new Bar((new Foo())->setName('Foo Bar')); $this->object->singleton('bar', $test); $test = $this->object['bar']; $this->assertInstanceOf('Titon\\Context\\Bar', $test); $this->assertEquals('Foo Bar', $test->getFoo()->getName()); } public function testAutoDependencyResolution() { $test = $this->object['Titon\\Context\\Bar']; $this->assertInstanceOf('Titon\\Context\\Bar', $test); $this->assertInstanceOf('Titon\\Context\\Foo', $test->getFoo()); } public function testClassDefinitionWithMethodCalls() { $this->object->register('foo', 'Titon\\Context\\Foo')->call('setName', 'Foo Bar'); $this->assertInstanceOf('Titon\\Context\\Foo', $this->object['foo']); $this->assertEquals('Foo Bar', $this->object['foo']->getName()); } public function testCallMethodsWithObjects() { $test = $this->object['Titon\\Context\\Bar']->getFoo(); $this->assertInstanceOf('Titon\\Context\\Foo', $test); } public function testConstructorInjection() { $this->object->register('bar', 'Titon\\Context\\Bar')->with('Titon\\Context\\Foo'); $this->assertInstanceOf('Titon\\Context\\Bar', $this->object['bar']); $this->object->register('bar', 'Titon\\Context\\Bar')->with((new Foo())->setName('Foo Bar')); $this->assertInstanceOf('Titon\\Context\\Bar', $this->object['bar']); $this->assertEquals($this->object['bar']->getFoo()->getName(), 'Foo Bar'); } public function testMethodInjection() { $this->object->register('foo', 'Titon\\Context\\Foo')->call('setName', 'Foo Bar'); $this->assertEquals('Foo Bar', $this->object['foo']->getName()); } public function testArgumentsAtCreation() { $this->object->register('bar', 'Titon\\Context\\Bar'); $test = $this->object->make('bar', new Foo('Foo Bar')); $this->assertInstanceOf('Titon\\Context\\Bar', $test); $this->assertEquals('Foo Bar', $test->getFoo()->getName()); } } class Foo { public $name; public function __construct($name = 'Alex Phillips') { $this->name = $name; } public function getName() { return $this->name; } public function setName($name) { $this->name = $name; return $this; } } class Bar { private $foo; public function __construct(Foo $foo) { $this->foo = $foo; } public function getFoo() { return $this->foo; } public function setFoo($foo) { $this->foo = $foo; } }<|endoftext|>
<commit_before>#pragma once #include <WinSock2.h> #include <deque> #include <functional> #include <memory> #include <thread> #include <future> #include <condition_variable> #include <iostream> namespace common { class Copyable { protected: Copyable() noexcept = default; ~Copyable() noexcept = default; Copyable(const Copyable&) noexcept = default; Copyable(Copyable&&) noexcept = default; Copyable& operator=(const Copyable&) noexcept = default; Copyable& operator=(Copyable&&) noexcept = default; }; class UnCopyable { UnCopyable(const UnCopyable&) noexcept = delete; UnCopyable(UnCopyable&&) noexcept = delete; UnCopyable& operator=(const UnCopyable&) noexcept = delete; UnCopyable& operator=(UnCopyable&&) noexcept = delete; protected: UnCopyable() noexcept = default; ~UnCopyable() noexcept = default; }; template <typename T> class Singleton : private UnCopyable { public: static T& get_instance() noexcept { static T _ins; return _ins; } }; class WSGuarder final : private UnCopyable { public: WSGuarder() noexcept; ~WSGuarder() noexcept; }; class UniqueSocket final : private UnCopyable { SOCKET sockfd_{}; public: UniqueSocket(SOCKET fd = INVALID_SOCKET) noexcept : sockfd_(fd) {} ~UniqueSocket() noexcept; inline void reset(SOCKET fd) noexcept { sockfd_ = fd; } inline operator SOCKET() const noexcept { return sockfd_; } inline operator bool() const noexcept { return sockfd_ != INVALID_SOCKET; } }; template <typename Fn, typename... Args> inline auto async(Fn&& fn, Args&&... args) { return std::async(std::launch::async, std::forward<Fn>(fn), std::forward<Args>(args)...); } class ThreadPool final : private UnCopyable { using TaskEntity = std::function<void ()>; using ThreadEntity = std::unique_ptr<std::thread>; bool running_{true}; mutable std::mutex mtx_; std::condition_variable non_empty_; std::vector<ThreadEntity> threads_; std::deque<TaskEntity> tasks_; TaskEntity fetch_task() { std::unique_lock<std::mutex> guard(mtx_); while (tasks_.empty() && running_) non_empty_.wait(guard); TaskEntity t; if (!tasks_.empty()) { t = tasks_.front(); tasks_.pop_front(); } return t; } public: ThreadPool(int thread_num = 4) noexcept { threads_.reserve(thread_num); for (int i = 0; i < thread_num; ++i) threads_.emplace_back(new std::thread([this] { while (running_) { auto t = fetch_task(); if (t) t(); } })); } ~ThreadPool() noexcept { if (running_) { { std::unique_lock<std::mutex> guard(mtx_); running_ = false; non_empty_.notify_all(); } for (auto& t : threads_) t->join(); } } template <typename Fn, typename... Args> void run_task(Fn&& fn, Args&&... args) { if (threads_.empty()) { fn(std::forward<Args>(args)...); } else { using ReturnType = typename std::invoke_result<Fn, Args...>::type; auto task = std::make_shared<std::packaged_task<ReturnType ()>>( std::bind(std::forward<Fn>(fn), std::forward<Args>(args)...)); { std::unique_lock<std::mutex> guard(mtx_); tasks_.emplace_back([task] { (*task)(); }); } non_empty_.notify_one(); } } }; }<commit_msg>:construction: chore(unique-socket): updated the methods for unique-socket<commit_after>#pragma once #include <WinSock2.h> #include <deque> #include <functional> #include <memory> #include <thread> #include <future> #include <condition_variable> #include <iostream> namespace common { class Copyable { protected: Copyable() noexcept = default; ~Copyable() noexcept = default; Copyable(const Copyable&) noexcept = default; Copyable(Copyable&&) noexcept = default; Copyable& operator=(const Copyable&) noexcept = default; Copyable& operator=(Copyable&&) noexcept = default; }; class UnCopyable { UnCopyable(const UnCopyable&) noexcept = delete; UnCopyable(UnCopyable&&) noexcept = delete; UnCopyable& operator=(const UnCopyable&) noexcept = delete; UnCopyable& operator=(UnCopyable&&) noexcept = delete; protected: UnCopyable() noexcept = default; ~UnCopyable() noexcept = default; }; template <typename T> class Singleton : private UnCopyable { public: static T& get_instance() noexcept { static T _ins; return _ins; } }; class WSGuarder final : private UnCopyable { public: WSGuarder() noexcept; ~WSGuarder() noexcept; }; class UniqueSocket final : private UnCopyable { SOCKET sockfd_{}; public: UniqueSocket(SOCKET fd = INVALID_SOCKET) noexcept : sockfd_(fd) {} ~UniqueSocket() noexcept; inline void reset(SOCKET fd) noexcept { sockfd_ = fd; } inline SOCKET get() const noexcept { return sockfd_; } inline operator SOCKET() const noexcept { return sockfd_; } inline operator bool() const noexcept { return sockfd_ != INVALID_SOCKET; } }; template <typename Fn, typename... Args> inline auto async(Fn&& fn, Args&&... args) { return std::async(std::launch::async, std::forward<Fn>(fn), std::forward<Args>(args)...); } class ThreadPool final : private UnCopyable { using TaskEntity = std::function<void ()>; using ThreadEntity = std::unique_ptr<std::thread>; bool running_{true}; mutable std::mutex mtx_; std::condition_variable non_empty_; std::vector<ThreadEntity> threads_; std::deque<TaskEntity> tasks_; TaskEntity fetch_task() { std::unique_lock<std::mutex> guard(mtx_); while (tasks_.empty() && running_) non_empty_.wait(guard); TaskEntity t; if (!tasks_.empty()) { t = tasks_.front(); tasks_.pop_front(); } return t; } public: ThreadPool(int thread_num = 4) noexcept { threads_.reserve(thread_num); for (int i = 0; i < thread_num; ++i) threads_.emplace_back(new std::thread([this] { while (running_) { auto t = fetch_task(); if (t) t(); } })); } ~ThreadPool() noexcept { if (running_) { { std::unique_lock<std::mutex> guard(mtx_); running_ = false; non_empty_.notify_all(); } for (auto& t : threads_) t->join(); } } template <typename Fn, typename... Args> void run_task(Fn&& fn, Args&&... args) { if (threads_.empty()) { fn(std::forward<Args>(args)...); } else { using ReturnType = typename std::invoke_result<Fn, Args...>::type; auto task = std::make_shared<std::packaged_task<ReturnType ()>>( std::bind(std::forward<Fn>(fn), std::forward<Args>(args)...)); { std::unique_lock<std::mutex> guard(mtx_); tasks_.emplace_back([task] { (*task)(); }); } non_empty_.notify_one(); } } }; }<|endoftext|>
<commit_before><commit_msg>Add HANDLE_CRASHES to Linux callback functions, since they are plugin entry points too. This makes no difference right now because we currently don't gate Linux crash uploading on HANDLE_CRASHES, but once we change that we'll want these in all the right places.<commit_after><|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2009, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ * */ #ifndef PCL_FEATURES_IMPL_FEATURE_H_ #define PCL_FEATURES_IMPL_FEATURE_H_ ////////////////////////////////////////////////////////////////////////////////////////////// inline void pcl::solvePlaneParameters (const Eigen::Matrix3f &covariance_matrix, const Eigen::Vector4f &point, Eigen::Vector4f &plane_parameters, float &curvature) { // Avoid getting hung on Eigen's optimizers for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) if (!pcl_isfinite (covariance_matrix (i, j))) { //PCL_WARN ("[pcl::solvePlaneParameteres] Covariance matrix has NaN/Inf values!\n"); plane_parameters.setConstant (std::numeric_limits<float>::quiet_NaN ()); curvature = std::numeric_limits<float>::quiet_NaN (); return; } // Extract the eigenvalues and eigenvectors //Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> ei_symm (covariance_matrix); //EIGEN_ALIGN16 Eigen::Vector3f eigen_values = ei_symm.eigenvalues (); //EIGEN_ALIGN16 Eigen::Matrix3f eigen_vectors = ei_symm.eigenvectors (); EIGEN_ALIGN16 Eigen::Vector3f eigen_values; EIGEN_ALIGN16 Eigen::Matrix3f eigen_vectors; pcl::eigen33 (covariance_matrix, eigen_vectors, eigen_values); // Normalize the surface normal (eigenvector corresponding to the smallest eigenvalue) // Note: Remember to take care of the eigen_vectors ordering //float norm = 1.0 / eigen_vectors.col (0).norm (); //plane_parameters[0] = eigen_vectors (0, 0) * norm; //plane_parameters[1] = eigen_vectors (1, 0) * norm; //plane_parameters[2] = eigen_vectors (2, 0) * norm; // The normalization is not necessary, since the eigenvectors from libeigen are already normalized plane_parameters[0] = eigen_vectors (0, 0); plane_parameters[1] = eigen_vectors (1, 0); plane_parameters[2] = eigen_vectors (2, 0); plane_parameters[3] = 0; // Hessian form (D = nc . p_plane (centroid here) + p) plane_parameters[3] = -1 * plane_parameters.dot (point); // Compute the curvature surface change float eig_sum = eigen_values.sum (); if (eig_sum != 0) curvature = fabs ( eigen_values[0] / eig_sum ); else curvature = 0; } ////////////////////////////////////////////////////////////////////////////////////////////// inline void pcl::solvePlaneParameters (const Eigen::Matrix3f &covariance_matrix, float &nx, float &ny, float &nz, float &curvature) { // Avoid getting hung on Eigen's optimizers for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) if (!pcl_isfinite (covariance_matrix (i, j))) { //PCL_WARN ("[pcl::solvePlaneParameteres] Covariance matrix has NaN/Inf values!\n"); nx = ny = nz = curvature = std::numeric_limits<float>::quiet_NaN (); return; } // Extract the eigenvalues and eigenvectors //Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> ei_symm (covariance_matrix); //EIGEN_ALIGN16 Eigen::Vector3f eigen_values = ei_symm.eigenvalues (); //EIGEN_ALIGN16 Eigen::Matrix3f eigen_vectors = ei_symm.eigenvectors (); EIGEN_ALIGN16 Eigen::Vector3f eigen_values; EIGEN_ALIGN16 Eigen::Matrix3f eigen_vectors; pcl::eigen33 (covariance_matrix, eigen_vectors, eigen_values); // Normalize the surface normal (eigenvector corresponding to the smallest eigenvalue) // Note: Remember to take care of the eigen_vectors ordering //float norm = 1.0 / eigen_vectors.col (0).norm (); //nx = eigen_vectors (0, 0) * norm; //ny = eigen_vectors (1, 0) * norm; //nz = eigen_vectors (2, 0) * norm; // The normalization is not necessary, since the eigenvectors from libeigen are already normalized nx = eigen_vectors (0, 0); ny = eigen_vectors (1, 0); nz = eigen_vectors (2, 0); // Compute the curvature surface change float eig_sum = eigen_values.sum (); if (eig_sum != 0) curvature = fabs ( eigen_values[0] / eig_sum ); else curvature = 0; } ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointOutT> bool pcl::Feature<PointInT, PointOutT>::initCompute () { if (!PCLBase<PointInT>::initCompute ()) { PCL_ERROR ("[pcl::%s::initCompute] Init failed.\n", getClassName ().c_str ()); return (false); } // If the dataset is empty, just return if (input_->points.empty ()) { PCL_ERROR ("[pcl::%s::compute] input_ is empty!\n", getClassName ().c_str ()); // Cleanup deinitCompute (); return (false); } // Check if a space search locator was given if (!tree_) { PCL_ERROR ("[pcl::%s::compute] No spatial search method was given!\n", getClassName ().c_str ()); // Cleanup deinitCompute (); return (false); } // If no search surface has been defined, use the input dataset as the search surface itself if (!surface_) { fake_surface_ = true; surface_ = input_; } // Send the surface dataset to the spatial locator tree_->setInputCloud (surface_); // Do a fast check to see if the search parameters are well defined if (search_radius_ != 0.0) { if (k_ != 0) { PCL_ERROR ("[pcl::%s::compute] Both radius (%f) and K (%d) defined! Set one of them to zero first and then re-run compute ().\n", getClassName ().c_str (), search_radius_, k_); // Cleanup deinitCompute (); // Reset the surface if (fake_surface_) { surface_.reset (); fake_surface_ = false; } return (false); } else // Use the radiusSearch () function { search_parameter_ = search_radius_; if (surface_ == input_) // if the two surfaces are the same { // Declare the search locator definition int (KdTree::*radiusSearch)(int index, double radius, std::vector<int> &k_indices, std::vector<float> &k_distances, int max_nn) const = &KdTree::radiusSearch; search_method_ = boost::bind (radiusSearch, boost::ref (tree_), _1, _2, _3, _4, INT_MAX); } else { // Declare the search locator definition int (KdTree::*radiusSearchSurface)(const PointCloudIn &cloud, int index, double radius, std::vector<int> &k_indices, std::vector<float> &k_distances, int max_nn) const = &KdTree::radiusSearch; search_method_surface_ = boost::bind (radiusSearchSurface, boost::ref (tree_), _1, _2, _3, _4, _5, INT_MAX); } } } else { if (k_ != 0) // Use the nearestKSearch () function { search_parameter_ = k_; if (surface_ == input_) // if the two surfaces are the same { // Declare the search locator definition int (KdTree::*nearestKSearch)(int index, int k, std::vector<int> &k_indices, std::vector<float> &k_distances) = &KdTree::nearestKSearch; search_method_ = boost::bind (nearestKSearch, boost::ref (tree_), _1, _2, _3, _4); } else { // Declare the search locator definition int (KdTree::*nearestKSearchSurface)(const PointCloudIn &cloud, int index, int k, std::vector<int> &k_indices, std::vector<float> &k_distances) = &KdTree::nearestKSearch; search_method_surface_ = boost::bind (nearestKSearchSurface, boost::ref (tree_), _1, _2, _3, _4, _5); } } else { PCL_ERROR ("[pcl::%s::compute] Neither radius nor K defined! Set one of them to a positive number first and then re-run compute ().\n", getClassName ().c_str ()); // Cleanup deinitCompute (); // Reset the surface if (fake_surface_) { surface_.reset (); fake_surface_ = false; } return (false); } } return (true); } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointOutT> void pcl::Feature<PointInT, PointOutT>::compute (PointCloudOut &output) { if (!initCompute ()) { output.width = output.height = 0; output.points.clear (); return; } // Copy the header output.header = input_->header; // Resize the output dataset if (output.points.size () != indices_->size ()) output.points.resize (indices_->size ()); // Check if the output will be computed for all points or only a subset if (indices_->size () != input_->points.size ()) { output.width = indices_->size (); output.height = 1; } else { output.width = input_->width; output.height = input_->height; } output.is_dense = input_->is_dense; // Perform the actual feature computation computeFeature (output); deinitCompute (); // Reset the surface if (fake_surface_) { surface_.reset (); fake_surface_ = false; } } ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointNT, typename PointOutT> bool pcl::FeatureFromNormals<PointInT, PointNT, PointOutT>::initCompute () { if (!Feature<PointInT, PointOutT>::initCompute ()) { PCL_ERROR ("[pcl::%s::initCompute] Init failed.\n", getClassName ().c_str ()); return (false); } // Check if input normals are set if (!normals_) { PCL_ERROR ("[pcl::%s::initCompute] No input dataset containing normals was given!\n", getClassName ().c_str ()); deinitCompute(); return (false); } // Check if the size of normals is the same as the size of the surface if (normals_->points.size () != surface_->points.size ()) { PCL_ERROR ("[pcl::%s::initCompute] The number of points in the input dataset differs from the number of points in the dataset containing the normals!\n", getClassName ().c_str ()); deinitCompute(); return (false); } return (true); } #endif //#ifndef PCL_FEATURES_IMPL_FEATURE_H_ <commit_msg>this should fix it<commit_after>/* * Software License Agreement (BSD License) * * Copyright (c) 2009, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ * */ #ifndef PCL_FEATURES_IMPL_FEATURE_H_ #define PCL_FEATURES_IMPL_FEATURE_H_ ////////////////////////////////////////////////////////////////////////////////////////////// inline void pcl::solvePlaneParameters (const Eigen::Matrix3f &covariance_matrix, const Eigen::Vector4f &point, Eigen::Vector4f &plane_parameters, float &curvature) { // Avoid getting hung on Eigen's optimizers for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) if (!pcl_isfinite (covariance_matrix (i, j))) { //PCL_WARN ("[pcl::solvePlaneParameteres] Covariance matrix has NaN/Inf values!\n"); plane_parameters.setConstant (std::numeric_limits<float>::quiet_NaN ()); curvature = std::numeric_limits<float>::quiet_NaN (); return; } // Extract the eigenvalues and eigenvectors //Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> ei_symm (covariance_matrix); //EIGEN_ALIGN16 Eigen::Vector3f eigen_values = ei_symm.eigenvalues (); //EIGEN_ALIGN16 Eigen::Matrix3f eigen_vectors = ei_symm.eigenvectors (); EIGEN_ALIGN16 Eigen::Vector3f eigen_values; EIGEN_ALIGN16 Eigen::Matrix3f eigen_vectors; pcl::eigen33 (covariance_matrix, eigen_vectors, eigen_values); // Normalize the surface normal (eigenvector corresponding to the smallest eigenvalue) // Note: Remember to take care of the eigen_vectors ordering //float norm = 1.0 / eigen_vectors.col (0).norm (); //plane_parameters[0] = eigen_vectors (0, 0) * norm; //plane_parameters[1] = eigen_vectors (1, 0) * norm; //plane_parameters[2] = eigen_vectors (2, 0) * norm; // The normalization is not necessary, since the eigenvectors from libeigen are already normalized plane_parameters[0] = eigen_vectors (0, 0); plane_parameters[1] = eigen_vectors (1, 0); plane_parameters[2] = eigen_vectors (2, 0); plane_parameters[3] = 0; // Hessian form (D = nc . p_plane (centroid here) + p) plane_parameters[3] = -1 * plane_parameters.dot (point); // Compute the curvature surface change float eig_sum = eigen_values.sum (); if (eig_sum != 0) curvature = fabs ( eigen_values[0] / eig_sum ); else curvature = 0; } ////////////////////////////////////////////////////////////////////////////////////////////// inline void pcl::solvePlaneParameters (const Eigen::Matrix3f &covariance_matrix, float &nx, float &ny, float &nz, float &curvature) { // Avoid getting hung on Eigen's optimizers for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) if (!pcl_isfinite (covariance_matrix (i, j))) { //PCL_WARN ("[pcl::solvePlaneParameteres] Covariance matrix has NaN/Inf values!\n"); nx = ny = nz = curvature = std::numeric_limits<float>::quiet_NaN (); return; } // Extract the eigenvalues and eigenvectors //Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> ei_symm (covariance_matrix); //EIGEN_ALIGN16 Eigen::Vector3f eigen_values = ei_symm.eigenvalues (); //EIGEN_ALIGN16 Eigen::Matrix3f eigen_vectors = ei_symm.eigenvectors (); EIGEN_ALIGN16 Eigen::Vector3f eigen_values; EIGEN_ALIGN16 Eigen::Matrix3f eigen_vectors; pcl::eigen33 (covariance_matrix, eigen_vectors, eigen_values); // Normalize the surface normal (eigenvector corresponding to the smallest eigenvalue) // Note: Remember to take care of the eigen_vectors ordering //float norm = 1.0 / eigen_vectors.col (0).norm (); //nx = eigen_vectors (0, 0) * norm; //ny = eigen_vectors (1, 0) * norm; //nz = eigen_vectors (2, 0) * norm; // The normalization is not necessary, since the eigenvectors from libeigen are already normalized nx = eigen_vectors (0, 0); ny = eigen_vectors (1, 0); nz = eigen_vectors (2, 0); // Compute the curvature surface change float eig_sum = eigen_values.sum (); if (eig_sum != 0) curvature = fabs ( eigen_values[0] / eig_sum ); else curvature = 0; } ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointOutT> bool pcl::Feature<PointInT, PointOutT>::initCompute () { if (!PCLBase<PointInT>::initCompute ()) { PCL_ERROR ("[pcl::%s::initCompute] Init failed.\n", getClassName ().c_str ()); return (false); } // If the dataset is empty, just return if (input_->points.empty ()) { PCL_ERROR ("[pcl::%s::compute] input_ is empty!\n", getClassName ().c_str ()); // Cleanup deinitCompute (); return (false); } // Check if a space search locator was given if (!tree_) { PCL_ERROR ("[pcl::%s::compute] No spatial search method was given!\n", getClassName ().c_str ()); // Cleanup deinitCompute (); return (false); } // If no search surface has been defined, use the input dataset as the search surface itself if (!surface_) { fake_surface_ = true; surface_ = input_; } // Send the surface dataset to the spatial locator tree_->setInputCloud (surface_); // Do a fast check to see if the search parameters are well defined if (search_radius_ != 0.0) { if (k_ != 0) { PCL_ERROR ("[pcl::%s::compute] Both radius (%f) and K (%d) defined! Set one of them to zero first and then re-run compute ().\n", getClassName ().c_str (), search_radius_, k_); // Cleanup deinitCompute (); // Reset the surface if (fake_surface_) { surface_.reset (); fake_surface_ = false; } return (false); } else // Use the radiusSearch () function { search_parameter_ = search_radius_; if (surface_ == input_) // if the two surfaces are the same { // Declare the search locator definition int (KdTree::*radiusSearch)(int index, double radius, std::vector<int> &k_indices, std::vector<float> &k_distances, int max_nn) const = &KdTree::radiusSearch; search_method_ = boost::bind (radiusSearch, boost::ref (tree_), _1, _2, _3, _4, INT_MAX); } else { // Declare the search locator definition int (KdTree::*radiusSearchSurface)(const PointCloudIn &cloud, int index, double radius, std::vector<int> &k_indices, std::vector<float> &k_distances, int max_nn) const = &KdTree::radiusSearch; search_method_surface_ = boost::bind (radiusSearchSurface, boost::ref (tree_), _1, _2, _3, _4, _5, INT_MAX); } } } else { if (k_ != 0) // Use the nearestKSearch () function { search_parameter_ = k_; if (surface_ == input_) // if the two surfaces are the same { // Declare the search locator definition int (KdTree::*nearestKSearch)(int index, int k, std::vector<int> &k_indices, std::vector<float> &k_distances) = &KdTree::nearestKSearch; search_method_ = boost::bind (nearestKSearch, boost::ref (tree_), _1, _2, _3, _4); } else { // Declare the search locator definition int (KdTree::*nearestKSearchSurface)(const PointCloudIn &cloud, int index, int k, std::vector<int> &k_indices, std::vector<float> &k_distances) = &KdTree::nearestKSearch; search_method_surface_ = boost::bind (nearestKSearchSurface, boost::ref (tree_), _1, _2, _3, _4, _5); } } else { PCL_ERROR ("[pcl::%s::compute] Neither radius nor K defined! Set one of them to a positive number first and then re-run compute ().\n", getClassName ().c_str ()); // Cleanup deinitCompute (); // Reset the surface if (fake_surface_) { surface_.reset (); fake_surface_ = false; } return (false); } } return (true); } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointOutT> void pcl::Feature<PointInT, PointOutT>::compute (PointCloudOut &output) { if (!initCompute ()) { output.width = output.height = 0; output.points.clear (); return; } // Copy the header output.header = input_->header; // Resize the output dataset if (output.points.size () != indices_->size ()) output.points.resize (indices_->size ()); // Check if the output will be computed for all points or only a subset if (indices_->size () != input_->points.size ()) { output.width = indices_->size (); output.height = 1; } else { output.width = input_->width; output.height = input_->height; } output.is_dense = input_->is_dense; // Perform the actual feature computation computeFeature (output); deinitCompute (); // Reset the surface if (fake_surface_) { surface_.reset (); fake_surface_ = false; } } ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointNT, typename PointOutT> bool pcl::FeatureFromNormals<PointInT, PointNT, PointOutT>::initCompute () { if (!Feature<PointInT, PointOutT>::initCompute ()) { PCL_ERROR ("[pcl::%s::initCompute] Init failed.\n", getClassName ().c_str ()); return (false); } // Check if input normals are set if (!normals_) { PCL_ERROR ("[pcl::%s::initCompute] No input dataset containing normals was given!\n", getClassName ().c_str ()); Feature<PointInT, PointOutT>::deinitCompute(); return (false); } // Check if the size of normals is the same as the size of the surface if (normals_->points.size () != surface_->points.size ()) { PCL_ERROR ("[pcl::%s::initCompute] The number of points in the input dataset differs from the number of points in the dataset containing the normals!\n", getClassName ().c_str ()); Feature<PointInT, PointOutT>::deinitCompute(); return (false); } return (true); } #endif //#ifndef PCL_FEATURES_IMPL_FEATURE_H_ <|endoftext|>
<commit_before>/* This file is part of the OPIE Project Copyright (c) 2002 Holger Freyther <zecke@handhelds.org> 2002 Maximilian Rei <harlekin@handhelds.org> =. .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. 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 ..}^=.= = ; Library General Public License for more ++= -. .` .: details. : = ...= . :.=- -. .:....=;==+<; You should have received a copy of the GNU -_. . . )=. = Library General Public License along with -- :-=` this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qcheckbox.h> #include <qgroupbox.h> #include <qlabel.h> #include <qvbox.h> #include <qlayout.h> #include <qlineedit.h> #include <qframe.h> //#include <qspacer.h> #include <qcombobox.h> #include <qlistview.h> #include <qpushbutton.h> #include <klocale.h> #include "ksync_configpart.h" using namespace KitchenSync; ConfigPart::ConfigPart(const Kapabilities &kaps, QWidget *parent, const char *name ) : QWidget( parent, name ) { initialize( kaps ); } void ConfigPart::initialize(const Kapabilities &kaps ){ // kaps.dump(); m_mainLayout = new QGridLayout( this, 6, 3 ); if ( kaps.supportsMetaSyncing() ) { m_ckbMetaSyncing = new QCheckBox(i18n( "Enable metasyncing"), this ); m_mainLayout->addWidget(m_ckbMetaSyncing, 0, 0); m_ckbMetaSyncing->setChecked( kaps.isMetaSyncingEnabled() ); } QLabel *lbl; push = false; if ( kaps.supportsPushSync() ) { push = true; lbl = new QLabel(i18n("You can push syncs to this device"), this ); }else lbl = new QLabel(i18n("You need to start the synchronization from your device"), this ); m_mainLayout->addWidget(lbl, 1, 0 ); if ( kaps.canAutoHandle() ) m_lblAutoHandle = new QLabel( i18n("This konnector establishes a connection to the device"), this ); else m_lblAutoHandle = new QLabel( i18n("To function properly you need to establish a connection"), this ); m_mainLayout->addWidget( m_lblAutoHandle, 2, 0 ); // Connection // column 0 = Label, 1= ComboBox, 2 = Space, 3 = Label, 4 = Combo m_grpConnection = new QGroupBox( i18n("Connection"), this ); m_conLayout = new QGridLayout(m_grpConnection, 4, 5); if ( !kaps.needsNetworkConnection() || kaps.canAutoHandle() ) { m_grpConnection->setEnabled( false ); }else{ m_grpConnection->setEnabled( true ); } m_conLayout->setMargin( 12 ); QSpacerItem *iti1b = new QSpacerItem(2, 10, QSizePolicy::Fixed, QSizePolicy::Fixed ); m_conLayout->addItem( iti1b, 0, 0); // Source m_lblSrcIp = new QLabel(i18n("Source Address: "), m_grpConnection); m_conSrcIp = new QComboBox(m_grpConnection); m_conSrcIp->setEditable( TRUE ); m_lblSrcIp->setBuddy( m_conSrcIp ); m_conLayout->addWidget(m_lblSrcIp, 1, 0 ); m_conLayout->addWidget(m_conSrcIp, 1, 1 ); if (!kaps.needsIPs() || !kaps.needsSrcIP() ) { m_lblSrcIp->setEnabled( false ); m_conSrcIp->setEnabled( false ); }else{ m_conSrcIp->insertItem( kaps.srcIP() ); } //Destination m_lblDestIp = new QLabel(i18n("Destination Address: "), m_grpConnection ); m_conDestIp = new QComboBox(m_grpConnection); m_conDestIp->setEditable( TRUE ); m_lblDestIp->setBuddy( m_conDestIp ); m_conLayout->addWidget( m_lblDestIp, 1, 3 ); m_conLayout->addWidget( m_conDestIp, 1, 4 ); if (!kaps.needsIPs() || !kaps.needsDestIP() ) { m_lblDestIp->setEnabled( false ); m_conDestIp->setEnabled( false ); }else{ QStringList ips = kaps.ipProposals(); QStringList::ConstIterator it; for ( it = ips.begin(); it != ips.end(); ++it ) { m_conDestIp->insertItem( (*it) ); } m_conDestIp->insertItem(kaps.destIP(), 0 ); } //user m_lblUser = new QLabel(i18n("User:"), m_grpConnection ); m_conUser = new QComboBox(m_grpConnection ); m_conUser->setEditable( TRUE ); m_lblUser->setBuddy( m_conUser ); m_conLayout->addWidget( m_lblUser, 2, 0 ); m_conLayout->addWidget( m_conUser, 2, 1 ); //pass m_lblPass = new QLabel(i18n("Password:"), m_grpConnection ); m_conPass = new QComboBox( m_grpConnection ); m_conPass->setEditable( TRUE ); m_lblPass->setBuddy( m_conPass ); m_conLayout->addWidget( m_lblPass, 2, 3 ); m_conLayout->addWidget( m_conPass, 2, 4 ); if ( kaps.needAuthentication() ) { QValueList<QPair<QString, QString> > list = kaps.userProposals(); QValueList<QPair<QString, QString> >::ConstIterator it; for (it = list.begin(); it != list.end(); ++it ) { m_conUser->insertItem( (*it).first ); m_conPass->insertItem( (*it).second); } m_conUser->insertItem(kaps.user(), 0); m_conPass->insertItem(kaps.password(), 0 ); }else{ m_lblPass->setEnabled( false ); m_conPass->setEnabled( false ); m_lblUser->setEnabled( false ); m_conUser->setEnabled( false ); } // port m_lblPort = new QLabel( i18n("Port:"), m_grpConnection); m_conPort = new QComboBox( m_grpConnection ); m_conPort->setEditable(TRUE); m_lblPort->setBuddy( m_conPort ); m_conLayout->addWidget( m_lblPort, 3, 0 ); m_conLayout->addWidget( m_conPort, 3, 1 ); QArray<int> ints = kaps.ports(); if ( ints.isEmpty() ) { m_lblPort->setEnabled( false ); m_conPort->setEnabled( false ); }else{ for (uint i = 0; i < ints.size(); i++ ) { m_conPort->insertItem( QString::number( ints[i] ) ); } m_conPort->insertItem( QString::number( kaps.currentPort() ), 0 ); } // add the Connection Groupbox m_mainLayout->addWidget( m_grpConnection, 3, 0 ); // Model specific m_grpModel = new QGroupBox( i18n("Model"), this ); m_grpLayout = new QGridLayout( m_grpModel, 5, 2 ); m_grpLayout->setMargin( 12 ); QSpacerItem *iti1c = new QSpacerItem(2, 10, QSizePolicy::Fixed, QSizePolicy::Fixed ); m_grpLayout->addItem( iti1c, 0, 0); // Devices m_lblDevice = new QLabel( i18n("Device: "), m_grpModel ); m_cmbDevice = new QComboBox( m_grpModel ); m_cmbDevice->setEditable( TRUE ); m_lblDevice->setBuddy( m_cmbDevice ); m_grpLayout->addWidget( m_lblDevice, 1, 0 ); m_grpLayout->addWidget( m_cmbDevice, 1, 1 ); QStringList devices = kaps.models(); if ( devices.isEmpty() ) { m_lblDevice->setEnabled( false ); m_cmbDevice->setEnabled( false ); }else{ for ( QStringList::ConstIterator it = devices.begin(); it != devices.end(); ++it ) { m_cmbDevice->insertItem( (*it) ); } m_cmbDevice->insertItem( kaps.currentModel() , 0); } // Connection Mode usb, paralell, net,.... m_lblConnection = new QLabel( i18n("Connection:"), m_grpModel ); m_cmbConnection = new QComboBox( m_grpModel ); m_cmbConnection->setEditable( TRUE ); m_lblConnection->setBuddy( m_cmbConnection ); m_grpLayout->addWidget( m_lblConnection, 2, 0 ); m_grpLayout->addWidget( m_cmbConnection, 2, 1 ); QStringList conList = kaps.connectionModes(); if ( conList.isEmpty() ) { m_lblConnection->setEnabled( false ); m_cmbConnection->setEnabled( false ); }else{ for ( QStringList::ConstIterator it = conList.begin(); it != conList.end(); ++it ) { m_cmbConnection->insertItem( (*it) ); } m_cmbConnection->insertItem( kaps.currentConnectionMode(), 0); } //Mode USER m_grpUser = new QLabel( i18n("User:"), m_grpModel ); m_cmbUser = new QComboBox( m_grpModel ); m_cmbUser->setEditable( TRUE ); m_grpUser->setBuddy( m_cmbUser ); m_grpLayout->addWidget(m_grpUser, 3, 0); m_grpLayout->addWidget(m_cmbUser, 3, 1); m_grpUser->setEnabled( false ); m_cmbUser->setEnabled( false ); // MODE PASS m_grpPass = new QLabel( i18n("Pass:"), m_grpModel ); m_cmbPass = new QComboBox( m_grpModel ); m_grpPass->setBuddy( m_cmbPass ); m_cmbPass->setEditable( TRUE ); m_grpLayout->addWidget( m_grpPass, 4, 0 ); m_grpLayout->addWidget( m_cmbPass, 4, 1 ); m_grpPass->setEnabled( false ); m_cmbPass->setEnabled( false ); m_mainLayout->addWidget( m_grpModel, 4, 0 ); QMap<QString, QString> specs = kaps.extras(); if ( !specs.isEmpty() ) { m_grpDevice = new QGroupBox( i18n("Device specefic"), this ); m_devLay = new QGridLayout(m_grpDevice, specs.count()+1, 2); QSpacerItem *iti1d = new QSpacerItem(4, 14, QSizePolicy::Fixed, QSizePolicy::Fixed ); m_devLay->setMargin( 12 ); m_devLay->addItem( iti1d, 0, 0 ); int i = 0; QLabel *lbl; QLineEdit *edit; m_devGroup.clear(); for ( QMap<QString, QString>::ConstIterator it = specs.begin(); it != specs.end(); ++it ) { lbl = new QLabel(i18n(it.key() ), m_grpDevice ); edit = new QLineEdit(m_grpDevice, it.key().latin1() ); edit->setText( it.data() ); lbl->setBuddy(edit); m_devGroup.insert(it.key(), edit); m_devLay->addWidget( lbl, i, 0 ); m_devLay->addWidget( edit, i, 1 ); ++i; } m_mainLayout->addWidget( m_grpDevice, 5, 0 ); } } Kapabilities ConfigPart::capability() { Kapabilities kaps; kaps.setSupportsPushSync( push ); // ok first read all the extras which is fairly easy if ( !m_devGroup.isEmpty() ) { for ( QMap<QString, QLineEdit*>::ConstIterator it = m_devGroup.begin(); it != m_devGroup.end(); ++it ) { kaps.setExtraOption( it.key(), it.data()->text() ); } } // meta syncing if ( m_ckbMetaSyncing != 0 ) { kaps.setMetaSyncingEnabled( m_ckbMetaSyncing->isChecked() ); } // GRP IPs + User + Password if ( m_grpConnection != 0 && m_grpConnection->isEnabled() ) { if ( m_conSrcIp->isEnabled() ) kaps.setSrcIP( m_conSrcIp->currentText() ); if ( m_conDestIp->isEnabled( ) ) kaps.setDestIP(m_conDestIp->currentText() ); if ( m_conUser->isEnabled() ) kaps.setUser( m_conUser->currentText() ); if ( m_conPass->isEnabled() ) kaps.setPassword( m_conPass->currentText() ); if ( m_conPort->isEnabled() ) kaps.setCurrentPort( m_conPort->currentText().toInt() ); } if ( m_cmbPass != 0 && m_cmbPass->isEnabled() ) ; if ( m_cmbUser != 0 && m_cmbUser->isEnabled() ) ; if ( m_cmbDevice != 0 && m_cmbDevice->isEnabled() ) kaps.setCurrentModel(m_cmbDevice->currentText() ); if ( m_cmbConnection != 0 && m_cmbConnection->isEnabled() ) kaps.setCurrentConnectionMode( m_cmbConnection->currentText() ); return kaps; } void ConfigPart::init() { m_ckbMetaSyncing = 0; m_mainLayout = 0; m_lblAutoHandle = 0; m_grpConnection = 0; m_conLayout = 0; // m_conSpacer = 0; m_conSrcIp = 0; m_conDestIp = 0; m_conUser = 0; m_conPass = 0; m_conPort = 0; m_lblSrcIp = 0; m_lblDestIp = 0; m_lblUser = 0; m_lblPass = 0; m_lblPort = 0; m_grpModel = 0; m_grpLayout = 0; m_lblDevice = 0; m_lblConnection = 0; m_cmbDevice = 0; m_cmbConnection = 0; m_grpDevice = 0; m_devLay = 0; m_grpFetch = 0; m_fetchAdd = 0; m_fetchBrowse = 0; m_fetchRem = 0; m_view = 0; } <commit_msg>CVS_SILENT Style guide fix<commit_after>/* This file is part of the OPIE Project Copyright (c) 2002 Holger Freyther <zecke@handhelds.org> 2002 Maximilian Rei <harlekin@handhelds.org> =. .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. 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 ..}^=.= = ; Library General Public License for more ++= -. .` .: details. : = ...= . :.=- -. .:....=;==+<; You should have received a copy of the GNU -_. . . )=. = Library General Public License along with -- :-=` this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qcheckbox.h> #include <qgroupbox.h> #include <qlabel.h> #include <qvbox.h> #include <qlayout.h> #include <qlineedit.h> #include <qframe.h> //#include <qspacer.h> #include <qcombobox.h> #include <qlistview.h> #include <qpushbutton.h> #include <klocale.h> #include "ksync_configpart.h" using namespace KitchenSync; ConfigPart::ConfigPart(const Kapabilities &kaps, QWidget *parent, const char *name ) : QWidget( parent, name ) { initialize( kaps ); } void ConfigPart::initialize(const Kapabilities &kaps ){ // kaps.dump(); m_mainLayout = new QGridLayout( this, 6, 3 ); if ( kaps.supportsMetaSyncing() ) { m_ckbMetaSyncing = new QCheckBox(i18n( "Enable metasyncing"), this ); m_mainLayout->addWidget(m_ckbMetaSyncing, 0, 0); m_ckbMetaSyncing->setChecked( kaps.isMetaSyncingEnabled() ); } QLabel *lbl; push = false; if ( kaps.supportsPushSync() ) { push = true; lbl = new QLabel(i18n("You can push syncs to this device"), this ); }else lbl = new QLabel(i18n("You need to start the synchronization from your device"), this ); m_mainLayout->addWidget(lbl, 1, 0 ); if ( kaps.canAutoHandle() ) m_lblAutoHandle = new QLabel( i18n("This konnector establishes a connection to the device"), this ); else m_lblAutoHandle = new QLabel( i18n("To function properly you need to establish a connection"), this ); m_mainLayout->addWidget( m_lblAutoHandle, 2, 0 ); // Connection // column 0 = Label, 1= ComboBox, 2 = Space, 3 = Label, 4 = Combo m_grpConnection = new QGroupBox( i18n("Connection"), this ); m_conLayout = new QGridLayout(m_grpConnection, 4, 5); if ( !kaps.needsNetworkConnection() || kaps.canAutoHandle() ) { m_grpConnection->setEnabled( false ); }else{ m_grpConnection->setEnabled( true ); } m_conLayout->setMargin( 12 ); QSpacerItem *iti1b = new QSpacerItem(2, 10, QSizePolicy::Fixed, QSizePolicy::Fixed ); m_conLayout->addItem( iti1b, 0, 0); // Source m_lblSrcIp = new QLabel(i18n("Source Address: "), m_grpConnection); m_conSrcIp = new QComboBox(m_grpConnection); m_conSrcIp->setEditable( TRUE ); m_lblSrcIp->setBuddy( m_conSrcIp ); m_conLayout->addWidget(m_lblSrcIp, 1, 0 ); m_conLayout->addWidget(m_conSrcIp, 1, 1 ); if (!kaps.needsIPs() || !kaps.needsSrcIP() ) { m_lblSrcIp->setEnabled( false ); m_conSrcIp->setEnabled( false ); }else{ m_conSrcIp->insertItem( kaps.srcIP() ); } //Destination m_lblDestIp = new QLabel(i18n("Destination Address: "), m_grpConnection ); m_conDestIp = new QComboBox(m_grpConnection); m_conDestIp->setEditable( TRUE ); m_lblDestIp->setBuddy( m_conDestIp ); m_conLayout->addWidget( m_lblDestIp, 1, 3 ); m_conLayout->addWidget( m_conDestIp, 1, 4 ); if (!kaps.needsIPs() || !kaps.needsDestIP() ) { m_lblDestIp->setEnabled( false ); m_conDestIp->setEnabled( false ); }else{ QStringList ips = kaps.ipProposals(); QStringList::ConstIterator it; for ( it = ips.begin(); it != ips.end(); ++it ) { m_conDestIp->insertItem( (*it) ); } m_conDestIp->insertItem(kaps.destIP(), 0 ); } //user m_lblUser = new QLabel(i18n("User:"), m_grpConnection ); m_conUser = new QComboBox(m_grpConnection ); m_conUser->setEditable( TRUE ); m_lblUser->setBuddy( m_conUser ); m_conLayout->addWidget( m_lblUser, 2, 0 ); m_conLayout->addWidget( m_conUser, 2, 1 ); //pass m_lblPass = new QLabel(i18n("Password:"), m_grpConnection ); m_conPass = new QComboBox( m_grpConnection ); m_conPass->setEditable( TRUE ); m_lblPass->setBuddy( m_conPass ); m_conLayout->addWidget( m_lblPass, 2, 3 ); m_conLayout->addWidget( m_conPass, 2, 4 ); if ( kaps.needAuthentication() ) { QValueList<QPair<QString, QString> > list = kaps.userProposals(); QValueList<QPair<QString, QString> >::ConstIterator it; for (it = list.begin(); it != list.end(); ++it ) { m_conUser->insertItem( (*it).first ); m_conPass->insertItem( (*it).second); } m_conUser->insertItem(kaps.user(), 0); m_conPass->insertItem(kaps.password(), 0 ); }else{ m_lblPass->setEnabled( false ); m_conPass->setEnabled( false ); m_lblUser->setEnabled( false ); m_conUser->setEnabled( false ); } // port m_lblPort = new QLabel( i18n("Port:"), m_grpConnection); m_conPort = new QComboBox( m_grpConnection ); m_conPort->setEditable(TRUE); m_lblPort->setBuddy( m_conPort ); m_conLayout->addWidget( m_lblPort, 3, 0 ); m_conLayout->addWidget( m_conPort, 3, 1 ); QArray<int> ints = kaps.ports(); if ( ints.isEmpty() ) { m_lblPort->setEnabled( false ); m_conPort->setEnabled( false ); }else{ for (uint i = 0; i < ints.size(); i++ ) { m_conPort->insertItem( QString::number( ints[i] ) ); } m_conPort->insertItem( QString::number( kaps.currentPort() ), 0 ); } // add the Connection Groupbox m_mainLayout->addWidget( m_grpConnection, 3, 0 ); // Model specific m_grpModel = new QGroupBox( i18n("Model"), this ); m_grpLayout = new QGridLayout( m_grpModel, 5, 2 ); m_grpLayout->setMargin( 12 ); QSpacerItem *iti1c = new QSpacerItem(2, 10, QSizePolicy::Fixed, QSizePolicy::Fixed ); m_grpLayout->addItem( iti1c, 0, 0); // Devices m_lblDevice = new QLabel( i18n("Device: "), m_grpModel ); m_cmbDevice = new QComboBox( m_grpModel ); m_cmbDevice->setEditable( TRUE ); m_lblDevice->setBuddy( m_cmbDevice ); m_grpLayout->addWidget( m_lblDevice, 1, 0 ); m_grpLayout->addWidget( m_cmbDevice, 1, 1 ); QStringList devices = kaps.models(); if ( devices.isEmpty() ) { m_lblDevice->setEnabled( false ); m_cmbDevice->setEnabled( false ); }else{ for ( QStringList::ConstIterator it = devices.begin(); it != devices.end(); ++it ) { m_cmbDevice->insertItem( (*it) ); } m_cmbDevice->insertItem( kaps.currentModel() , 0); } // Connection Mode usb, paralell, net,.... m_lblConnection = new QLabel( i18n("Connection:"), m_grpModel ); m_cmbConnection = new QComboBox( m_grpModel ); m_cmbConnection->setEditable( TRUE ); m_lblConnection->setBuddy( m_cmbConnection ); m_grpLayout->addWidget( m_lblConnection, 2, 0 ); m_grpLayout->addWidget( m_cmbConnection, 2, 1 ); QStringList conList = kaps.connectionModes(); if ( conList.isEmpty() ) { m_lblConnection->setEnabled( false ); m_cmbConnection->setEnabled( false ); }else{ for ( QStringList::ConstIterator it = conList.begin(); it != conList.end(); ++it ) { m_cmbConnection->insertItem( (*it) ); } m_cmbConnection->insertItem( kaps.currentConnectionMode(), 0); } //Mode USER m_grpUser = new QLabel( i18n("User:"), m_grpModel ); m_cmbUser = new QComboBox( m_grpModel ); m_cmbUser->setEditable( TRUE ); m_grpUser->setBuddy( m_cmbUser ); m_grpLayout->addWidget(m_grpUser, 3, 0); m_grpLayout->addWidget(m_cmbUser, 3, 1); m_grpUser->setEnabled( false ); m_cmbUser->setEnabled( false ); // MODE PASS m_grpPass = new QLabel( i18n("Pass:"), m_grpModel ); m_cmbPass = new QComboBox( m_grpModel ); m_grpPass->setBuddy( m_cmbPass ); m_cmbPass->setEditable( TRUE ); m_grpLayout->addWidget( m_grpPass, 4, 0 ); m_grpLayout->addWidget( m_cmbPass, 4, 1 ); m_grpPass->setEnabled( false ); m_cmbPass->setEnabled( false ); m_mainLayout->addWidget( m_grpModel, 4, 0 ); QMap<QString, QString> specs = kaps.extras(); if ( !specs.isEmpty() ) { m_grpDevice = new QGroupBox( i18n("Device Specific"), this ); m_devLay = new QGridLayout(m_grpDevice, specs.count()+1, 2); QSpacerItem *iti1d = new QSpacerItem(4, 14, QSizePolicy::Fixed, QSizePolicy::Fixed ); m_devLay->setMargin( 12 ); m_devLay->addItem( iti1d, 0, 0 ); int i = 0; QLabel *lbl; QLineEdit *edit; m_devGroup.clear(); for ( QMap<QString, QString>::ConstIterator it = specs.begin(); it != specs.end(); ++it ) { lbl = new QLabel(i18n(it.key() ), m_grpDevice ); edit = new QLineEdit(m_grpDevice, it.key().latin1() ); edit->setText( it.data() ); lbl->setBuddy(edit); m_devGroup.insert(it.key(), edit); m_devLay->addWidget( lbl, i, 0 ); m_devLay->addWidget( edit, i, 1 ); ++i; } m_mainLayout->addWidget( m_grpDevice, 5, 0 ); } } Kapabilities ConfigPart::capability() { Kapabilities kaps; kaps.setSupportsPushSync( push ); // ok first read all the extras which is fairly easy if ( !m_devGroup.isEmpty() ) { for ( QMap<QString, QLineEdit*>::ConstIterator it = m_devGroup.begin(); it != m_devGroup.end(); ++it ) { kaps.setExtraOption( it.key(), it.data()->text() ); } } // meta syncing if ( m_ckbMetaSyncing != 0 ) { kaps.setMetaSyncingEnabled( m_ckbMetaSyncing->isChecked() ); } // GRP IPs + User + Password if ( m_grpConnection != 0 && m_grpConnection->isEnabled() ) { if ( m_conSrcIp->isEnabled() ) kaps.setSrcIP( m_conSrcIp->currentText() ); if ( m_conDestIp->isEnabled( ) ) kaps.setDestIP(m_conDestIp->currentText() ); if ( m_conUser->isEnabled() ) kaps.setUser( m_conUser->currentText() ); if ( m_conPass->isEnabled() ) kaps.setPassword( m_conPass->currentText() ); if ( m_conPort->isEnabled() ) kaps.setCurrentPort( m_conPort->currentText().toInt() ); } if ( m_cmbPass != 0 && m_cmbPass->isEnabled() ) ; if ( m_cmbUser != 0 && m_cmbUser->isEnabled() ) ; if ( m_cmbDevice != 0 && m_cmbDevice->isEnabled() ) kaps.setCurrentModel(m_cmbDevice->currentText() ); if ( m_cmbConnection != 0 && m_cmbConnection->isEnabled() ) kaps.setCurrentConnectionMode( m_cmbConnection->currentText() ); return kaps; } void ConfigPart::init() { m_ckbMetaSyncing = 0; m_mainLayout = 0; m_lblAutoHandle = 0; m_grpConnection = 0; m_conLayout = 0; // m_conSpacer = 0; m_conSrcIp = 0; m_conDestIp = 0; m_conUser = 0; m_conPass = 0; m_conPort = 0; m_lblSrcIp = 0; m_lblDestIp = 0; m_lblUser = 0; m_lblPass = 0; m_lblPort = 0; m_grpModel = 0; m_grpLayout = 0; m_lblDevice = 0; m_lblConnection = 0; m_cmbDevice = 0; m_cmbConnection = 0; m_grpDevice = 0; m_devLay = 0; m_grpFetch = 0; m_fetchAdd = 0; m_fetchBrowse = 0; m_fetchRem = 0; m_view = 0; } <|endoftext|>
<commit_before>/* -*- mode: c++; c-basic-offset:4 -*- uiserver/selectcertificatecommand.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2007 Klarälvdalens Datakonsult AB Kleopatra 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. Kleopatra is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include <config-kleopatra.h> #include "selectcertificatecommand.h" #include <dialogs/certificateselectiondialog.h> #include <utils/exception.h> #include <gpgme++/key.h> #include <gpg-error.h> #include <KLocale> #include <QVariant> #include <QByteArray> #include <QIODevice> #include <QList> #include <QPointer> #include <string> #include <algorithm> using namespace Kleo; using namespace Kleo::Dialogs; using namespace boost; static const char option_prefix[] = "prefix"; class SelectCertificateCommand::Private { friend class ::Kleo::SelectCertificateCommand; SelectCertificateCommand * const q; public: Private( SelectCertificateCommand * qq ) : q( qq ), dialog() { } private: void slotDialogAccepted(); void slotDialogRejected(); private: void ensureDialogCreated() { if ( dialog ) return; dialog = new CertificateSelectionDialog; q->applyWindowID( dialog ); dialog->setAttribute( Qt::WA_DeleteOnClose ); //dialog->setWindowTitle( i18nc( "@title", "Certificate Selection" ) ); connect( dialog, SIGNAL(accepted()), q, SLOT(slotDialogAccepted()) ); connect( dialog, SIGNAL(rejected()), q, SLOT(slotDialogRejected()) ); } void ensureDialogShown() { ensureDialogCreated(); if ( dialog->isVisible() ) dialog->raise(); else dialog->show(); } private: QPointer<CertificateSelectionDialog> dialog; }; SelectCertificateCommand::SelectCertificateCommand() : QObject(), AssuanCommandMixin<SelectCertificateCommand>(), d( new Private( this ) ) {} SelectCertificateCommand::~SelectCertificateCommand() {} static const struct { const char * name; CertificateSelectionDialog::Option option; } option_table[] = { { "multi", CertificateSelectionDialog::MultiSelection }, { "sign-only", CertificateSelectionDialog::SignOnly }, { "encrypt-only", CertificateSelectionDialog::EncryptOnly }, { "openpgp-only", CertificateSelectionDialog::OpenPGPFormat }, { "x509-only", CertificateSelectionDialog::CMSFormat }, { "secret-only", CertificateSelectionDialog::SecretKeys }, }; int SelectCertificateCommand::doStart() { d->ensureDialogCreated(); CertificateSelectionDialog::Options opts; for ( unsigned int i = 0 ; i < sizeof option_table / sizeof *option_table ; ++i ) if ( hasOption( option_table[i].name ) ) opts |= option_table[i].option; d->dialog->setOptions( opts ); d->ensureDialogShown(); return 0; } void SelectCertificateCommand::doCanceled() { if ( d->dialog ) d->dialog->close(); } void SelectCertificateCommand::Private::slotDialogAccepted() { try { QByteArray data; Q_FOREACH( const GpgME::Key & key, dialog->selectedCertificates() ) { data += key.primaryFingerprint(); data += "\n"; } q->sendData( data ); q->done(); } catch ( const Exception & e ) { q->done( e.error(), e.message() ); } catch ( const std::exception & e ) { q->done( makeError( GPG_ERR_UNEXPECTED ), i18n("Caught unexpected exception in SelectCertificateCommand::Private::slotDialogAccepted: %1", QString::fromLocal8Bit( e.what() ) ) ); } catch ( ... ) { q->done( makeError( GPG_ERR_UNEXPECTED ), i18n("Caught unknown exception in SelectCertificateCommand::Private::slotDialogAccepted") ); } } void SelectCertificateCommand::Private::slotDialogRejected() { dialog = 0; q->done( makeError( GPG_ERR_CANCELED ) ); } #include "moc_selectcertificatecommand.cpp" <commit_msg>Krazy fix: single-char QString operations<commit_after>/* -*- mode: c++; c-basic-offset:4 -*- uiserver/selectcertificatecommand.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2007 Klarälvdalens Datakonsult AB Kleopatra 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. Kleopatra is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include <config-kleopatra.h> #include "selectcertificatecommand.h" #include <dialogs/certificateselectiondialog.h> #include <utils/exception.h> #include <gpgme++/key.h> #include <gpg-error.h> #include <KLocale> #include <QVariant> #include <QByteArray> #include <QIODevice> #include <QList> #include <QPointer> #include <string> #include <algorithm> using namespace Kleo; using namespace Kleo::Dialogs; using namespace boost; static const char option_prefix[] = "prefix"; class SelectCertificateCommand::Private { friend class ::Kleo::SelectCertificateCommand; SelectCertificateCommand * const q; public: Private( SelectCertificateCommand * qq ) : q( qq ), dialog() { } private: void slotDialogAccepted(); void slotDialogRejected(); private: void ensureDialogCreated() { if ( dialog ) return; dialog = new CertificateSelectionDialog; q->applyWindowID( dialog ); dialog->setAttribute( Qt::WA_DeleteOnClose ); //dialog->setWindowTitle( i18nc( "@title", "Certificate Selection" ) ); connect( dialog, SIGNAL(accepted()), q, SLOT(slotDialogAccepted()) ); connect( dialog, SIGNAL(rejected()), q, SLOT(slotDialogRejected()) ); } void ensureDialogShown() { ensureDialogCreated(); if ( dialog->isVisible() ) dialog->raise(); else dialog->show(); } private: QPointer<CertificateSelectionDialog> dialog; }; SelectCertificateCommand::SelectCertificateCommand() : QObject(), AssuanCommandMixin<SelectCertificateCommand>(), d( new Private( this ) ) {} SelectCertificateCommand::~SelectCertificateCommand() {} static const struct { const char * name; CertificateSelectionDialog::Option option; } option_table[] = { { "multi", CertificateSelectionDialog::MultiSelection }, { "sign-only", CertificateSelectionDialog::SignOnly }, { "encrypt-only", CertificateSelectionDialog::EncryptOnly }, { "openpgp-only", CertificateSelectionDialog::OpenPGPFormat }, { "x509-only", CertificateSelectionDialog::CMSFormat }, { "secret-only", CertificateSelectionDialog::SecretKeys }, }; int SelectCertificateCommand::doStart() { d->ensureDialogCreated(); CertificateSelectionDialog::Options opts; for ( unsigned int i = 0 ; i < sizeof option_table / sizeof *option_table ; ++i ) if ( hasOption( option_table[i].name ) ) opts |= option_table[i].option; d->dialog->setOptions( opts ); d->ensureDialogShown(); return 0; } void SelectCertificateCommand::doCanceled() { if ( d->dialog ) d->dialog->close(); } void SelectCertificateCommand::Private::slotDialogAccepted() { try { QByteArray data; Q_FOREACH( const GpgME::Key & key, dialog->selectedCertificates() ) { data += key.primaryFingerprint(); data += '\n'; } q->sendData( data ); q->done(); } catch ( const Exception & e ) { q->done( e.error(), e.message() ); } catch ( const std::exception & e ) { q->done( makeError( GPG_ERR_UNEXPECTED ), i18n("Caught unexpected exception in SelectCertificateCommand::Private::slotDialogAccepted: %1", QString::fromLocal8Bit( e.what() ) ) ); } catch ( ... ) { q->done( makeError( GPG_ERR_UNEXPECTED ), i18n("Caught unknown exception in SelectCertificateCommand::Private::slotDialogAccepted") ); } } void SelectCertificateCommand::Private::slotDialogRejected() { dialog = 0; q->done( makeError( GPG_ERR_CANCELED ) ); } #include "moc_selectcertificatecommand.cpp" <|endoftext|>
<commit_before>/* * Copyright (C) LinBox * * ========LICENCE======== * This file is part of the library LinBox. * * LinBox 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 * ========LICENCE======== */ #include <linbox/matrix/random-matrix.h> #include <linbox/solutions/solve.h> using namespace LinBox; namespace { template <class Matrix> struct TypeToString; template <class MatrixArgs> struct TypeToString<DenseMatrix<MatrixArgs>> { static constexpr const char* value = "DenseMatrix"; }; template <class... MatrixArgs> struct TypeToString<SparseMatrix<MatrixArgs...>> { static constexpr const char* value = "SparseMatrix"; }; template <class Matrix> inline const char* type_to_string(const Matrix& A) { return TypeToString<Matrix>::value; } template <class SolveMethod, class ResultVector, class Matrix, class Vector> void print_error(const ResultVector& x, const Matrix& A, const Vector& b, bool verbose, std::string reason) { if (verbose) { A.write(std::cerr << "A: ", Tag::FileFormat::Maple) << std::endl; std::cerr << "b: " << b << std::endl; std::cerr << "x: " << x << std::endl; } std::cerr << "/!\\ " << SolveMethod::name() << " on " << type_to_string(A) << " over "; A.field().write(std::cerr); std::cerr << " of size " << A.rowdim() << "x" << A.coldim() << " FAILS (" << reason << ")" << std::endl; } } template <class SolveMethod, class Matrix, class Domain, class ResultDomain> bool test_solve(Domain& D, ResultDomain& RD, Communicator* pCommunicator, int m, int n, int bitSize, int vectorBitSize, int seed, bool verbose) { using Vector = DenseVector<Domain>; using ResultVector = DenseVector<ResultDomain>; // // Generating data // Matrix A(D, m, n); Vector b(D, m); ResultVector x(RD, n); // @note RandomDenseMatrix can also fill a SparseMatrix, it has just a sparsity of 0. typename Domain::RandIter randIter(D, bitSize, seed); typename Domain::RandIter vectorRandIter(D, vectorBitSize, seed); LinBox::RandomDenseMatrix<typename Domain::RandIter, Domain> RDM(D, randIter); // @note Within our test m == n implies invertible, // but for the rectangular case, we pass whatever. if (m == n) { RDM.randomFullRank(A); if (bitSize != vectorBitSize) { b.random(vectorRandIter); } else { b.random(randIter); } } else { RDM.random(A); // We set b so that the system is not inconsistent Vector x(D, n); x.random(randIter); A.apply(b, x); // b <- Ax } if (verbose) { std::cout << "--- Testing " << SolveMethod::name() << " on " << type_to_string(A) << " over "; D.write(std::cout) << " of size " << m << "x" << n << std::endl; } // // Copying data for final check // using ResultMatrix = typename Matrix::template rebind<ResultDomain>::other; ResultMatrix RA(A, RD); ResultVector Rb(RD, b); // // Solving // SolveMethod method; method.pCommunicator = pCommunicator; try { solve(x, A, b, method); // @fixme Test this result too solveInPlace(x, A, b, method); } catch (...) { print_error<SolveMethod>(x, RA, b, verbose, "throws error"); return false; } // // Checking result is correct // ResultVector RAx(RD, RA.coldim()); RA.apply(RAx, x); VectorDomain<ResultDomain> VD(RD); if (!VD.areEqual(RAx, Rb)) { RA.write(std::cout << "A : ", Tag::FileFormat::Maple) << std::endl; std::cout << "Ax : " << RAx << std::endl; std::cout << "b : " << Rb << std::endl; print_error<SolveMethod>(x, RA, Rb, verbose, "Ax != b"); return false; } return true; } // // Rational solve // template <class SolveMethod, class Matrix> bool test_rational_solve(Communicator& communicator, int m, int n, int bitSize, int vectorBitSize, int seed, bool verbose) { using IntegerDomain = Givaro::ZRing<Integer>; using RationalDomain = Givaro::QField<Givaro::Rational>; IntegerDomain D; RationalDomain RD; bool ok = true; ok &= test_solve<SolveMethod, Matrix>(D, RD, &communicator, m, m, bitSize, vectorBitSize, seed, verbose); ok &= test_solve<SolveMethod, Matrix>(D, RD, &communicator, m, n, bitSize, vectorBitSize, seed, verbose); return ok; } template <class SolveMethod> bool test_all_rational_solve(Communicator& communicator, int m, int n, int bitSize, int vectorBitSize, int seed, bool verbose) { using IntegerDomain = Givaro::ZRing<Integer>; bool ok = true; ok &= test_rational_solve<SolveMethod, DenseMatrix<IntegerDomain>>(communicator, m, n, bitSize, vectorBitSize, seed, verbose); ok &= test_rational_solve<SolveMethod, SparseMatrix<IntegerDomain>>(communicator, m, n, bitSize, vectorBitSize, seed, verbose); return ok; } template <class SolveMethod> bool test_dense_rational_solve(Communicator& communicator, int m, int n, int bitSize, int vectorBitSize, int seed, bool verbose) { using IntegerDomain = Givaro::ZRing<Integer>; return test_rational_solve<SolveMethod, DenseMatrix<IntegerDomain>>(communicator, m, n, bitSize, vectorBitSize, seed, verbose); } template <class SolveMethod> bool test_sparse_rational_solve(Communicator& communicator, int m, int n, int bitSize, int vectorBitSize, int seed, bool verbose) { using IntegerDomain = Givaro::ZRing<Integer>; return test_rational_solve<SolveMethod, SparseMatrix<IntegerDomain>>(communicator, m, n, bitSize, vectorBitSize, seed, verbose); } // // Modular solve // template <class SolveMethod, class Matrix> bool test_modular_solve(Integer& q, int m, int n, int bitSize, int vectorBitSize, int seed, bool verbose) { using ModularDomain = Givaro::Modular<double>; ModularDomain D(q); bool ok = true; ok &= test_solve<SolveMethod, Matrix>(D, D, nullptr, m, m, bitSize, vectorBitSize, seed, verbose); ok &= test_solve<SolveMethod, Matrix>(D, D, nullptr, m, n, bitSize, vectorBitSize, seed, verbose); return ok; } template <class SolveMethod> bool test_all_modular_solve(Integer& q, int m, int n, int bitSize, int vectorBitSize, int seed, bool verbose) { using ModularDomain = Givaro::Modular<double>; bool ok = true; ok &= test_modular_solve<SolveMethod, DenseMatrix<ModularDomain>>(q, m, n, bitSize, vectorBitSize, seed, verbose); ok &= test_modular_solve<SolveMethod, SparseMatrix<ModularDomain>>(q, m, n, bitSize, vectorBitSize, seed, verbose); return ok; } template <class SolveMethod> bool test_dense_modular_solve(Integer& q, int m, int n, int bitSize, int vectorBitSize, int seed, bool verbose) { using ModularDomain = Givaro::Modular<double>; return test_modular_solve<SolveMethod, DenseMatrix<ModularDomain>>(q, m, n, bitSize, vectorBitSize, seed, verbose); } template <class SolveMethod> bool test_sparse_modular_solve(Integer& q, int m, int n, int bitSize, int vectorBitSize, int seed, bool verbose) { using ModularDomain = Givaro::Modular<double>; return test_modular_solve<SolveMethod, SparseMatrix<ModularDomain>>(q, m, n, bitSize, vectorBitSize, seed, verbose); } int main(int argc, char** argv) { Integer q = 101; bool verbose = false; bool loop = false; int seed = -1; int bitSize = 100; int vectorBitSize = -1; int m = 32; int n = 24; static Argument args[] = {{'q', "-q", "Field characteristic.", TYPE_INTEGER, &q}, {'v', "-v", "Enable verbose mode.", TYPE_BOOL, &verbose}, {'l', "-l", "Infinite loop of tests.", TYPE_BOOL, &loop}, {'s', "-s", "Seed for randomness.", TYPE_INT, &seed}, {'b', "-b", "Bit size for rational solve tests.", TYPE_INT, &bitSize}, {'B', "-B", "Vector bit size for rational solve tests (defaults to -b if not specified).", TYPE_INT, &vectorBitSize}, {'m', "-m", "Row dimension of matrices.", TYPE_INT, &m}, {'n', "-n", "Column dimension of matrices.", TYPE_INT, &n}, END_OF_ARGUMENTS}; if (vectorBitSize < 0) { vectorBitSize = bitSize; } if (seed < 0) { seed = time(nullptr); } parseArguments(argc, argv, args); if (verbose) { commentator().setReportStream(std::cout); } bool ok = true; Communicator communicator(0, nullptr); do { ok &= test_all_rational_solve<Method::Auto>(communicator, m, n, bitSize, vectorBitSize, seed, verbose); // @bug When bitSize = 5 and vectorBitSize = 50, CRA fails ok &= test_all_rational_solve<Method::CRAAuto>(communicator, m, n, bitSize, vectorBitSize, seed, verbose); ok &= test_all_rational_solve<Method::Dixon>(communicator, m, n, bitSize, vectorBitSize, seed, verbose); // @note SymbolicNumeric methods are only implemented on DenseMatrix // @fixme Singular case fails // ok &= test_dense_rational_solve<Method::SymbolicNumericOverlap>(communicator, m, n, bitSize, vectorBitSize, seed, verbose); // @fixme Fails // ok &= test_sparse_rational_solve<Method::SymbolicNumericNorm>(communicator, m, n, bitSize, vectorBitSize, seed, verbose); ok &= test_all_modular_solve<Method::Auto>(q, m, n, bitSize, vectorBitSize, seed, verbose); ok &= test_all_modular_solve<Method::Auto>(q, m, n, bitSize, vectorBitSize, seed, verbose); ok &= test_all_modular_solve<Method::DenseElimination>(q, m, n, bitSize, vectorBitSize, seed, verbose); ok &= test_all_modular_solve<Method::SparseElimination>(q, m, n, bitSize, vectorBitSize, seed, verbose); // @fixme Dense does not compile // ok &= test_dense_modular_solve<Method::Wiedemann>(q, m, n, bitSize, vectorBitSize, seed, verbose); ok &= test_sparse_modular_solve<Method::Wiedemann>(q, m, n, bitSize, vectorBitSize, seed, verbose); // @fixme Dense is segfaulting // ok &= test_dense_modular_solve<Method::Lanczos>(q, m, n, bitSize, vectorBitSize, seed, verbose); // @fixme Singular case fails // ok &= test_sparse_modular_solve<Method::Lanczos>(q, m, n, bitSize, vectorBitSize, seed, verbose); // @fixme Dense does not compile // ok &= test_dense_modular_solve<Method::BlockLanczos>(q, m, n, bitSize, vectorBitSize, seed, verbose); // @fixme Sparse is segfaulting // ok &= test_sparse_modular_solve<Method::BlockLanczos>(q, m, n, bitSize, vectorBitSize, seed, verbose); // @deprecated These do not compile anymore // ok &= test_all_modular_solve<Method::BlockWiedemann>(q, m, n, bitSize, vectorBitSize, seed, verbose); // ok &= test_all_modular_solve<Method::Coppersmith>(q, m, n, bitSize, vectorBitSize, seed, verbose); if (!ok) { std::cerr << "Failed with seed: " << seed << std::endl; } seed += 1; } while (ok && loop); return 0; } <commit_msg>Fixed wrong vector size for singular case<commit_after>/* * Copyright (C) LinBox * * ========LICENCE======== * This file is part of the library LinBox. * * LinBox 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 * ========LICENCE======== */ #include <linbox/matrix/random-matrix.h> #include <linbox/solutions/solve.h> using namespace LinBox; namespace { template <class Matrix> struct TypeToString; template <class MatrixArgs> struct TypeToString<DenseMatrix<MatrixArgs>> { static constexpr const char* value = "DenseMatrix"; }; template <class... MatrixArgs> struct TypeToString<SparseMatrix<MatrixArgs...>> { static constexpr const char* value = "SparseMatrix"; }; template <class Matrix> inline const char* type_to_string(const Matrix& A) { return TypeToString<Matrix>::value; } template <class SolveMethod, class ResultVector, class Matrix, class Vector> void print_error(const ResultVector& x, const Matrix& A, const Vector& b, bool verbose, std::string reason) { if (verbose) { A.write(std::cerr << "A: ", Tag::FileFormat::Maple) << std::endl; std::cerr << "b: " << b << std::endl; std::cerr << "x: " << x << std::endl; } std::cerr << "/!\\ " << SolveMethod::name() << " on " << type_to_string(A) << " over "; A.field().write(std::cerr); std::cerr << " of size " << A.rowdim() << "x" << A.coldim() << " FAILS (" << reason << ")" << std::endl; } } template <class SolveMethod, class Matrix, class Domain, class ResultDomain> bool test_solve(Domain& D, ResultDomain& RD, Communicator* pCommunicator, int m, int n, int bitSize, int vectorBitSize, int seed, bool verbose) { using Vector = DenseVector<Domain>; using ResultVector = DenseVector<ResultDomain>; // // Generating data // Matrix A(D, m, n); Vector b(D, m); ResultVector x(RD, n); // @note RandomDenseMatrix can also fill a SparseMatrix, it has just a sparsity of 0. typename Domain::RandIter randIter(D, bitSize, seed); typename Domain::RandIter vectorRandIter(D, vectorBitSize, seed); LinBox::RandomDenseMatrix<typename Domain::RandIter, Domain> RDM(D, randIter); // @note Within our test m == n implies invertible, // but for the rectangular case, we pass whatever. if (m == n) { RDM.randomFullRank(A); if (bitSize != vectorBitSize) { b.random(vectorRandIter); } else { b.random(randIter); } } else { RDM.random(A); // We set b so that the system is not inconsistent Vector x(D, n); x.random(randIter); A.apply(b, x); // b <- Ax } if (verbose) { std::cout << "--- Testing " << SolveMethod::name() << " on " << type_to_string(A) << " over "; D.write(std::cout) << " of size " << m << "x" << n << std::endl; } // // Copying data for final check // using ResultMatrix = typename Matrix::template rebind<ResultDomain>::other; ResultMatrix RA(A, RD); ResultVector Rb(RD, b); // // Solving // SolveMethod method; method.pCommunicator = pCommunicator; try { solve(x, A, b, method); // @fixme Test this result too solveInPlace(x, A, b, method); } catch (...) { print_error<SolveMethod>(x, RA, b, verbose, "throws error"); return false; } // // Checking result is correct // ResultVector RAx(RD, m); RA.apply(RAx, x); VectorDomain<ResultDomain> VD(RD); if (!VD.areEqual(RAx, Rb)) { print_error<SolveMethod>(x, RA, Rb, verbose, "Ax != b"); return false; } return true; } // // Rational solve // template <class SolveMethod, class Matrix> bool test_rational_solve(Communicator& communicator, int m, int n, int bitSize, int vectorBitSize, int seed, bool verbose) { using IntegerDomain = Givaro::ZRing<Integer>; using RationalDomain = Givaro::QField<Givaro::Rational>; IntegerDomain D; RationalDomain RD; bool ok = true; ok &= test_solve<SolveMethod, Matrix>(D, RD, &communicator, m, m, bitSize, vectorBitSize, seed, verbose); ok &= test_solve<SolveMethod, Matrix>(D, RD, &communicator, m, n, bitSize, vectorBitSize, seed, verbose); return ok; } template <class SolveMethod> bool test_all_rational_solve(Communicator& communicator, int m, int n, int bitSize, int vectorBitSize, int seed, bool verbose) { using IntegerDomain = Givaro::ZRing<Integer>; bool ok = true; ok &= test_rational_solve<SolveMethod, DenseMatrix<IntegerDomain>>(communicator, m, n, bitSize, vectorBitSize, seed, verbose); ok &= test_rational_solve<SolveMethod, SparseMatrix<IntegerDomain>>(communicator, m, n, bitSize, vectorBitSize, seed, verbose); return ok; } template <class SolveMethod> bool test_dense_rational_solve(Communicator& communicator, int m, int n, int bitSize, int vectorBitSize, int seed, bool verbose) { using IntegerDomain = Givaro::ZRing<Integer>; return test_rational_solve<SolveMethod, DenseMatrix<IntegerDomain>>(communicator, m, n, bitSize, vectorBitSize, seed, verbose); } template <class SolveMethod> bool test_sparse_rational_solve(Communicator& communicator, int m, int n, int bitSize, int vectorBitSize, int seed, bool verbose) { using IntegerDomain = Givaro::ZRing<Integer>; return test_rational_solve<SolveMethod, SparseMatrix<IntegerDomain>>(communicator, m, n, bitSize, vectorBitSize, seed, verbose); } // // Modular solve // template <class SolveMethod, class Matrix> bool test_modular_solve(Integer& q, int m, int n, int bitSize, int vectorBitSize, int seed, bool verbose) { using ModularDomain = Givaro::Modular<double>; ModularDomain D(q); bool ok = true; ok &= test_solve<SolveMethod, Matrix>(D, D, nullptr, m, m, bitSize, vectorBitSize, seed, verbose); ok &= test_solve<SolveMethod, Matrix>(D, D, nullptr, m, n, bitSize, vectorBitSize, seed, verbose); return ok; } template <class SolveMethod> bool test_all_modular_solve(Integer& q, int m, int n, int bitSize, int vectorBitSize, int seed, bool verbose) { using ModularDomain = Givaro::Modular<double>; bool ok = true; ok &= test_modular_solve<SolveMethod, DenseMatrix<ModularDomain>>(q, m, n, bitSize, vectorBitSize, seed, verbose); ok &= test_modular_solve<SolveMethod, SparseMatrix<ModularDomain>>(q, m, n, bitSize, vectorBitSize, seed, verbose); return ok; } template <class SolveMethod> bool test_dense_modular_solve(Integer& q, int m, int n, int bitSize, int vectorBitSize, int seed, bool verbose) { using ModularDomain = Givaro::Modular<double>; return test_modular_solve<SolveMethod, DenseMatrix<ModularDomain>>(q, m, n, bitSize, vectorBitSize, seed, verbose); } template <class SolveMethod> bool test_sparse_modular_solve(Integer& q, int m, int n, int bitSize, int vectorBitSize, int seed, bool verbose) { using ModularDomain = Givaro::Modular<double>; return test_modular_solve<SolveMethod, SparseMatrix<ModularDomain>>(q, m, n, bitSize, vectorBitSize, seed, verbose); } int main(int argc, char** argv) { Integer q = 101; bool verbose = false; bool loop = false; int seed = -1; int bitSize = 100; int vectorBitSize = -1; int m = 32; int n = 24; static Argument args[] = {{'q', "-q", "Field characteristic.", TYPE_INTEGER, &q}, {'v', "-v", "Enable verbose mode.", TYPE_BOOL, &verbose}, {'l', "-l", "Infinite loop of tests.", TYPE_BOOL, &loop}, {'s', "-s", "Seed for randomness.", TYPE_INT, &seed}, {'b', "-b", "Bit size for rational solve tests.", TYPE_INT, &bitSize}, {'B', "-B", "Vector bit size for rational solve tests (defaults to -b if not specified).", TYPE_INT, &vectorBitSize}, {'m', "-m", "Row dimension of matrices.", TYPE_INT, &m}, {'n', "-n", "Column dimension of matrices.", TYPE_INT, &n}, END_OF_ARGUMENTS}; if (vectorBitSize < 0) { vectorBitSize = bitSize; } if (seed < 0) { seed = time(nullptr); } parseArguments(argc, argv, args); if (verbose) { commentator().setReportStream(std::cout); } bool ok = true; Communicator communicator(0, nullptr); do { ok &= test_all_rational_solve<Method::Auto>(communicator, m, n, bitSize, vectorBitSize, seed, verbose); // @bug When bitSize = 5 and vectorBitSize = 50, CRA fails ok &= test_all_rational_solve<Method::CRAAuto>(communicator, m, n, bitSize, vectorBitSize, seed, verbose); ok &= test_all_rational_solve<Method::Dixon>(communicator, m, n, bitSize, vectorBitSize, seed, verbose); // @note SymbolicNumeric methods are only implemented on DenseMatrix // @fixme Singular case fails // ok &= test_dense_rational_solve<Method::SymbolicNumericOverlap>(communicator, m, n, bitSize, vectorBitSize, seed, verbose); // @fixme Fails // ok &= test_sparse_rational_solve<Method::SymbolicNumericNorm>(communicator, m, n, bitSize, vectorBitSize, seed, verbose); ok &= test_all_modular_solve<Method::Auto>(q, m, n, bitSize, vectorBitSize, seed, verbose); ok &= test_all_modular_solve<Method::Auto>(q, m, n, bitSize, vectorBitSize, seed, verbose); ok &= test_all_modular_solve<Method::DenseElimination>(q, m, n, bitSize, vectorBitSize, seed, verbose); ok &= test_all_modular_solve<Method::SparseElimination>(q, m, n, bitSize, vectorBitSize, seed, verbose); // @fixme Dense does not compile // ok &= test_dense_modular_solve<Method::Wiedemann>(q, m, n, bitSize, vectorBitSize, seed, verbose); ok &= test_sparse_modular_solve<Method::Wiedemann>(q, m, n, bitSize, vectorBitSize, seed, verbose); // @fixme Dense is segfaulting // ok &= test_dense_modular_solve<Method::Lanczos>(q, m, n, bitSize, vectorBitSize, seed, verbose); // @fixme Singular case fails // ok &= test_sparse_modular_solve<Method::Lanczos>(q, m, n, bitSize, vectorBitSize, seed, verbose); // @fixme Dense does not compile // ok &= test_dense_modular_solve<Method::BlockLanczos>(q, m, n, bitSize, vectorBitSize, seed, verbose); // @fixme Sparse is segfaulting // ok &= test_sparse_modular_solve<Method::BlockLanczos>(q, m, n, bitSize, vectorBitSize, seed, verbose); // @deprecated These do not compile anymore // ok &= test_all_modular_solve<Method::BlockWiedemann>(q, m, n, bitSize, vectorBitSize, seed, verbose); // ok &= test_all_modular_solve<Method::Coppersmith>(q, m, n, bitSize, vectorBitSize, seed, verbose); if (!ok) { std::cerr << "Failed with seed: " << seed << std::endl; } seed += 1; } while (ok && loop); return 0; } <|endoftext|>
<commit_before>/* * jcom.push (previously names tl.push) * By Trond Lossius, Copyright 2011 * * Simple physical modelling: Push an object about within a confined space * Can be used for e.g. trajectories * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "Jamoma.h" #include "TTAudioObject.h" // use the Jamoma DSP clipping functions #define nonzero(x) ((x > 0) ? x : 1.) #define MAXDIMENSIONS 10 t_symbol* ps_clip; typedef struct _push{ ///< Data structure for this object t_object ob; ///< Must always be the first field; used by Max float previousPosition[MAXDIMENSIONS]; ///< The previous position float previousVelocity[MAXDIMENSIONS]; ///< The previous velocity float attrFriction; ///< Friction coefficient int attrDimensions; ///< The number of dimensions used float attrSize[MAXDIMENSIONS]; ///< Room size, defined individually for each dimension t_symbol* attrBoundaryMode; ///< Boundary mode float force[MAXDIMENSIONS]; ///< Force applied on the object void *outlet; ///< Pointer to outlet. Need one for each outlet } t_push; // Prototypes for methods: need a method for each incoming message void *push_new(t_symbol *msg, long argc, t_atom *argv); void push_bang(t_push *x); void push_force(t_push *x, t_symbol *s, long argc, t_atom *argv); void push_clear(t_push *x); void push_assist(t_push *x, void *b, long msg, long arg, char *dst); t_max_err push_attr_setdimensions(t_push *x, void *attr, long argc, t_atom *argv); t_max_err push_attr_setfriction(t_push *x, void *attr, long argc, t_atom *argv); t_max_err push_attr_setsize(t_push *x, void *attr, long argc, t_atom *argv); t_max_err push_attr_getsize(t_push *x, void *attr, long *argc, t_atom **argv); t_max_err push_attr_setBoundaryMode(t_push *x, void *attr, long argc, t_atom *argv); // Globals t_class *this_class; // Required. Global pointing to this class /************************************************************************************/ // Main() Function int JAMOMA_EXPORT_MAXOBJ main(void) { t_class *c; jamoma_init(); common_symbols_init(); ps_clip = gensym("clip"); // Define our class c = class_new("jcom.push",(method)push_new, (method)0L, sizeof(t_push), (method)0L, A_GIMME, 0); // Make methods accessible for our class: class_addmethod(c, (method)push_bang, "bang", A_CANT, 0); class_addmethod(c, (method)push_force, "force", A_GIMME, 0); class_addmethod(c, (method)push_clear, "clear", 0); class_addmethod(c, (method)push_assist, "assist", A_CANT, 0); class_addmethod(c, (method)object_obex_dumpout, "dumpout", A_CANT, 0); CLASS_ATTR_FLOAT(c, "friction", 0, t_push, attrFriction); CLASS_ATTR_ACCESSORS(c, "friction", NULL, push_attr_setfriction); // Add attributes to our class: CLASS_ATTR_LONG(c, "dimensions", 0, t_push, attrDimensions); CLASS_ATTR_ACCESSORS(c, "dimensions", NULL, push_attr_setdimensions); CLASS_ATTR_ATOM(c, "size", 0, t_push, attrSize); CLASS_ATTR_ACCESSORS(c, "size", push_attr_getsize, push_attr_setsize); // ATTRIBUTE: boundary mode - options are none, clip, wrap, fold, repel CLASS_ATTR_SYM( c, "boundary", 0, t_push, attrBoundaryMode); CLASS_ATTR_ACCESSORS(c, "boundary", NULL, push_attr_setBoundaryMode); CLASS_ATTR_ENUM(c, "boundary", 0, (char*)"none clip bounce fold repel"); // Finalize our class class_register(CLASS_BOX, c); this_class = c; return 0; } #pragma mark - #pragma mark Object life /************************************************************************************/ // Object Life void *push_new(t_symbol *msg, long argc, t_atom *argv) { t_push *x; int i; x = (t_push *)object_alloc(this_class); // create the new instance and return a pointer to it if (x) { // create inlets and outlets object_obex_store((void *)x, _sym_dumpout, (object *)outlet_new(x,NULL)); // dumpout x->outlet = floatout(x); // velocity x->attrDimensions = 3; x->attrFriction = 0.1; for (i=0; i<MAXDIMENSIONS; i++) x->attrSize[i] = 40.0; // This is the same default as for ViMiC x->attrBoundaryMode = jps_none; push_clear(x); // initilaize instance attr_args_process(x, argc, argv); // handle attribute args } return (x); } /************************************************************************************/ // Methods bound to attributes #pragma mark - #pragma mark attribute accessors // ATTRIBUTE: dimensions t_max_err push_attr_setdimensions(t_push *x, void *attr, long argc, t_atom *argv) { long n; if (argc && argv) { n = atom_getlong(argv); if (n<1) n = 1; if (n>MAXDIMENSIONS) n = MAXDIMENSIONS; x->attrDimensions = n; } push_clear(x); return MAX_ERR_NONE; } // ATTRIBUTE: dimensions (1-3) t_max_err push_attr_setfriction(t_push *x, void *attr, long argc, t_atom *argv) { float f; if (argc && argv) { f = atom_getfloat(argv); if (f<=0.0 || f>=1.0) { error("Invalid argument for friction. Must be in the range (0, 1)"); return MAX_ERR_NONE; } x->attrFriction = f; } return MAX_ERR_NONE; } t_max_err push_attr_setsize(t_push *x, void *attr, long argc, t_atom *argv) { int i; float f; if ((argc==x->attrDimensions) && argv) { for (i=0; i<x->attrDimensions; i++) { f = atom_getfloat(argv); if (f>0.0) { x->attrSize[i] = f; argv++; } else post("jcom.push: Ignored faulty value for size"); } } return MAX_ERR_NONE; } t_max_err push_attr_getsize(t_push *x, void *attr, long *argc, t_atom **argv) { int i; *argc = x->attrDimensions; *argv = (t_atom*)sysmem_newptr((sizeof(t_atom))*x->attrDimensions); for (i=0; i<x->attrDimensions; i++) { atom_setfloat(*argv+i, x->attrSize[i]); } return MAX_ERR_NONE; // TODO: We need to free the memory assigned for argv } t_max_err push_attr_setBoundaryMode(t_push *x, void *attr, long argc, t_atom *argv) { t_symbol* s; if (argc && argv) { s = atom_getsym(argv); if ((s==jps_none) || (s==ps_clip) || (s==jps_wrap) || (s==jps_fold)) x->attrBoundaryMode = s; } return MAX_ERR_NONE; } #pragma mark - #pragma mark methods /************************************************************************************/ // Methods bound to input/inlets // BANG input void push_bang(t_push *x) { int i; float position, rangeLow, rangeHigh; t_atom a[MAXDIMENSIONS]; for (i=0; i<x->attrDimensions; i++) { position = x->previousPosition[i] + (1.0-x->attrFriction)*x->previousVelocity[i] + x->force[i]; x->previousVelocity[i] = position - x->previousPosition[i]; rangeHigh = 0.5*x->attrSize[i]; rangeHigh = - rangeHigh; if (x->attrBoundaryMode == ps_clip) TTLimit(position, rangeLow, rangeHigh); else if (x->attrBoundaryMode == jps_wrap) position = TTInfWrap(position, rangeLow, rangeHigh); else if (x->attrBoundaryMode == jps_fold) position = TTFold(position, rangeLow, rangeHigh); x->previousPosition[i] = position; atom_setfloat(&a[i], position); x->force[i] = 0; // Force is reset to zero when it has been applied } outlet_anything(x->outlet, _sym_list, x->attrDimensions, a); } // FORCE input void push_force(t_push *x, t_symbol *s, long argc, t_atom *argv) { int i; if (argc==x->attrDimensions) { for (i=0; i<x->attrDimensions; i++) { x->force[i] = atom_getfloat(argv); argv++; } } else { post("jcom.push: force vector has wrong dimension"); return; } } // CLEAR input void push_clear(t_push *x) { int i; for (i=0; i< x->attrDimensions; i++) { x->previousPosition[i] = 0.0; x->previousVelocity[i] = 0.0; x->force[i] = 0.0; } push_bang(x); } // Method for Assistance Messages void push_assist(t_push *x, void *b, long msg, long arg, char *dst) // Display assistance messages { if (msg==1) { switch(arg) { case 0: strcpy(dst, "(list) force applied to object"); break; } } else if (msg==2) { switch(arg) { case 0: strcpy(dst, "(list) resulting position of object"); break; case 1: strcpy(dst, "dumpout"); break; } } } <commit_msg>All boundary modes implemented except for repel<commit_after>/* * jcom.push (previously names tl.push) * By Trond Lossius, Copyright 2011 * * Simple physical modelling: Push an object about within a confined space * Can be used for e.g. trajectories * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "Jamoma.h" #include "TTAudioObject.h" // use the Jamoma DSP clipping functions #define nonzero(x) ((x > 0) ? x : 1.) #define MAXDIMENSIONS 10 t_symbol* ps_clip; typedef struct _push{ ///< Data structure for this object t_object ob; ///< Must always be the first field; used by Max float previousPosition[MAXDIMENSIONS]; ///< The previous position float previousVelocity[MAXDIMENSIONS]; ///< The previous velocity float attrFriction; ///< Friction coefficient int attrDimensions; ///< The number of dimensions used float attrSize[MAXDIMENSIONS]; ///< Room size, defined individually for each dimension t_symbol* attrBoundaryMode; ///< Boundary mode float force[MAXDIMENSIONS]; ///< Force applied on the object void *outlet; ///< Pointer to outlet. Need one for each outlet } t_push; // Prototypes for methods: need a method for each incoming message void *push_new(t_symbol *msg, long argc, t_atom *argv); void push_bang(t_push *x); void push_force(t_push *x, t_symbol *s, long argc, t_atom *argv); void push_clear(t_push *x); void push_assist(t_push *x, void *b, long msg, long arg, char *dst); t_max_err push_attr_setdimensions(t_push *x, void *attr, long argc, t_atom *argv); t_max_err push_attr_setfriction(t_push *x, void *attr, long argc, t_atom *argv); t_max_err push_attr_setsize(t_push *x, void *attr, long argc, t_atom *argv); t_max_err push_attr_getsize(t_push *x, void *attr, long *argc, t_atom **argv); t_max_err push_attr_setBoundaryMode(t_push *x, void *attr, long argc, t_atom *argv); // Globals t_class *this_class; // Required. Global pointing to this class /************************************************************************************/ // Main() Function int JAMOMA_EXPORT_MAXOBJ main(void) { t_class *c; jamoma_init(); common_symbols_init(); ps_clip = gensym("clip"); // Define our class c = class_new("jcom.push",(method)push_new, (method)0L, sizeof(t_push), (method)0L, A_GIMME, 0); // Make methods accessible for our class: class_addmethod(c, (method)push_bang, "bang", A_CANT, 0); class_addmethod(c, (method)push_force, "force", A_GIMME, 0); class_addmethod(c, (method)push_clear, "clear", 0); class_addmethod(c, (method)push_assist, "assist", A_CANT, 0); class_addmethod(c, (method)object_obex_dumpout, "dumpout", A_CANT, 0); CLASS_ATTR_FLOAT(c, "friction", 0, t_push, attrFriction); CLASS_ATTR_ACCESSORS(c, "friction", NULL, push_attr_setfriction); // Add attributes to our class: CLASS_ATTR_LONG(c, "dimensions", 0, t_push, attrDimensions); CLASS_ATTR_ACCESSORS(c, "dimensions", NULL, push_attr_setdimensions); CLASS_ATTR_ATOM(c, "size", 0, t_push, attrSize); CLASS_ATTR_ACCESSORS(c, "size", push_attr_getsize, push_attr_setsize); // ATTRIBUTE: boundary mode - options are none, clip, wrap, fold, repel CLASS_ATTR_SYM( c, "boundary", 0, t_push, attrBoundaryMode); CLASS_ATTR_ACCESSORS(c, "boundary", NULL, push_attr_setBoundaryMode); CLASS_ATTR_ENUM(c, "boundary", 0, (char*)"none clip bounce fold repel"); // Finalize our class class_register(CLASS_BOX, c); this_class = c; return 0; } #pragma mark - #pragma mark Object life /************************************************************************************/ // Object Life void *push_new(t_symbol *msg, long argc, t_atom *argv) { t_push *x; int i; x = (t_push *)object_alloc(this_class); // create the new instance and return a pointer to it if (x) { // create inlets and outlets object_obex_store((void *)x, _sym_dumpout, (object *)outlet_new(x,NULL)); // dumpout x->outlet = floatout(x); // velocity x->attrDimensions = 3; x->attrFriction = 0.1; for (i=0; i<MAXDIMENSIONS; i++) x->attrSize[i] = 40.0; // This is the same default as for ViMiC x->attrBoundaryMode = jps_none; push_clear(x); // initilaize instance attr_args_process(x, argc, argv); // handle attribute args } return (x); } /************************************************************************************/ // Methods bound to attributes #pragma mark - #pragma mark attribute accessors // ATTRIBUTE: dimensions t_max_err push_attr_setdimensions(t_push *x, void *attr, long argc, t_atom *argv) { long n; if (argc && argv) { n = atom_getlong(argv); if (n<1) n = 1; if (n>MAXDIMENSIONS) n = MAXDIMENSIONS; x->attrDimensions = n; } push_clear(x); return MAX_ERR_NONE; } // ATTRIBUTE: dimensions (1-3) t_max_err push_attr_setfriction(t_push *x, void *attr, long argc, t_atom *argv) { float f; if (argc && argv) { f = atom_getfloat(argv); if (f<=0.0 || f>=1.0) { error("Invalid argument for friction. Must be in the range (0, 1)"); return MAX_ERR_NONE; } x->attrFriction = f; } return MAX_ERR_NONE; } t_max_err push_attr_setsize(t_push *x, void *attr, long argc, t_atom *argv) { int i; float f; if ((argc==x->attrDimensions) && argv) { for (i=0; i<x->attrDimensions; i++) { f = atom_getfloat(argv); if (f>0.0) { x->attrSize[i] = f; argv++; } else post("jcom.push: Ignored faulty value for size"); } } return MAX_ERR_NONE; } t_max_err push_attr_getsize(t_push *x, void *attr, long *argc, t_atom **argv) { int i; *argc = x->attrDimensions; *argv = (t_atom*)sysmem_newptr((sizeof(t_atom))*x->attrDimensions); for (i=0; i<x->attrDimensions; i++) { atom_setfloat(*argv+i, x->attrSize[i]); } return MAX_ERR_NONE; // TODO: We need to free the memory assigned for argv } t_max_err push_attr_setBoundaryMode(t_push *x, void *attr, long argc, t_atom *argv) { t_symbol* s; if (argc && argv) { s = atom_getsym(argv); if ((s==jps_none) || (s==ps_clip) || (s==jps_wrap) || (s==jps_fold)) x->attrBoundaryMode = s; } return MAX_ERR_NONE; } #pragma mark - #pragma mark methods /************************************************************************************/ // Methods bound to input/inlets // BANG input void push_bang(t_push *x) { int i; float position, rangeLow, rangeHigh; t_atom a[MAXDIMENSIONS]; for (i=0; i<x->attrDimensions; i++) { position = x->previousPosition[i] + (1.0-x->attrFriction)*x->previousVelocity[i] + x->force[i]; x->previousVelocity[i] = position - x->previousPosition[i]; rangeHigh = 0.5*x->attrSize[i]; rangeLow = -rangeHigh; if (x->attrBoundaryMode == ps_clip) TTLimit(position, rangeLow, rangeHigh); else if (x->attrBoundaryMode == jps_wrap) position = TTInfWrap(position, rangeLow, rangeHigh); else if (x->attrBoundaryMode == jps_fold) { // Do we need to fold? The following test works because of symetry while avoiding fabs() if ((position*position) >= (rangeHigh*rangeHigh)) { position = TTFold(position, rangeLow, rangeHigh); // Inverse direction of velocity x->previousVelocity[i] = -x->previousVelocity[i]; } } x->previousPosition[i] = position; atom_setfloat(&a[i], position); x->force[i] = 0; // Force is reset to zero when it has been applied } outlet_anything(x->outlet, _sym_list, x->attrDimensions, a); } // FORCE input void push_force(t_push *x, t_symbol *s, long argc, t_atom *argv) { int i; if (argc==x->attrDimensions) { for (i=0; i<x->attrDimensions; i++) { x->force[i] = atom_getfloat(argv); argv++; } } else { post("jcom.push: force vector has wrong dimension"); return; } } // CLEAR input void push_clear(t_push *x) { int i; for (i=0; i< x->attrDimensions; i++) { x->previousPosition[i] = 0.0; x->previousVelocity[i] = 0.0; x->force[i] = 0.0; } push_bang(x); } // Method for Assistance Messages void push_assist(t_push *x, void *b, long msg, long arg, char *dst) // Display assistance messages { if (msg==1) { switch(arg) { case 0: strcpy(dst, "(list) force applied to object"); break; } } else if (msg==2) { switch(arg) { case 0: strcpy(dst, "(list) resulting position of object"); break; case 1: strcpy(dst, "dumpout"); break; } } } <|endoftext|>
<commit_before>//===-- X86ShuffleDecodeConstantPool.cpp - X86 shuffle decode -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Define several functions to decode x86 specific shuffle semantics using // constants from the constant pool. // //===----------------------------------------------------------------------===// #include "X86ShuffleDecodeConstantPool.h" #include "Utils/X86ShuffleDecode.h" #include "llvm/ADT/APInt.h" #include "llvm/CodeGen/MachineValueType.h" #include "llvm/IR/Constants.h" //===----------------------------------------------------------------------===// // Vector Mask Decoding //===----------------------------------------------------------------------===// namespace llvm { static bool extractConstantMask(const Constant *C, unsigned MaskEltSizeInBits, APInt &UndefElts, SmallVectorImpl<uint64_t> &RawMask) { // It is not an error for shuffle masks to not be a vector of // MaskEltSizeInBits because the constant pool uniques constants by their // bit representation. // e.g. the following take up the same space in the constant pool: // i128 -170141183420855150465331762880109871104 // // <2 x i64> <i64 -9223372034707292160, i64 -9223372034707292160> // // <4 x i32> <i32 -2147483648, i32 -2147483648, // i32 -2147483648, i32 -2147483648> Type *CstTy = C->getType(); if (!CstTy->isVectorTy()) return false; Type *CstEltTy = CstTy->getVectorElementType(); if (!CstEltTy->isIntegerTy()) return false; unsigned CstSizeInBits = CstTy->getPrimitiveSizeInBits(); unsigned CstEltSizeInBits = CstTy->getScalarSizeInBits(); unsigned NumCstElts = CstTy->getVectorNumElements(); // Extract all the undef/constant element data and pack into single bitsets. APInt UndefBits(CstSizeInBits, 0); APInt MaskBits(CstSizeInBits, 0); for (unsigned i = 0; i != NumCstElts; ++i) { Constant *COp = C->getAggregateElement(i); if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp))) return false; unsigned BitOffset = i * CstEltSizeInBits; if (isa<UndefValue>(COp)) { UndefBits.setBits(BitOffset, BitOffset + CstEltSizeInBits); continue; } auto *Elt = cast<ConstantInt>(COp); MaskBits |= Elt->getValue().zextOrTrunc(CstSizeInBits).shl(BitOffset); } // Now extract the undef/constant bit data into the raw shuffle masks. assert((CstSizeInBits % MaskEltSizeInBits) == 0 && "Unaligned shuffle mask size"); unsigned NumMaskElts = CstSizeInBits / MaskEltSizeInBits; UndefElts = APInt(NumMaskElts, 0); RawMask.resize(NumMaskElts, 0); for (unsigned i = 0; i != NumMaskElts; ++i) { unsigned BitOffset = i * MaskEltSizeInBits; APInt EltUndef = UndefBits.extractBits(MaskEltSizeInBits, BitOffset); // Only treat the element as UNDEF if all bits are UNDEF, otherwise // treat it as zero. if (EltUndef.isAllOnesValue()) { UndefElts.setBit(i); RawMask[i] = 0; continue; } APInt EltBits = MaskBits.extractBits(MaskEltSizeInBits, BitOffset); RawMask[i] = EltBits.getZExtValue(); } return true; } void DecodePSHUFBMask(const Constant *C, SmallVectorImpl<int> &ShuffleMask) { Type *MaskTy = C->getType(); unsigned MaskTySize = MaskTy->getPrimitiveSizeInBits(); (void)MaskTySize; assert((MaskTySize == 128 || MaskTySize == 256 || MaskTySize == 512) && "Unexpected vector size."); // The shuffle mask requires a byte vector. APInt UndefElts; SmallVector<uint64_t, 32> RawMask; if (!extractConstantMask(C, 8, UndefElts, RawMask)) return; unsigned NumElts = RawMask.size(); assert((NumElts == 16 || NumElts == 32 || NumElts == 64) && "Unexpected number of vector elements."); for (unsigned i = 0; i != NumElts; ++i) { if (UndefElts[i]) { ShuffleMask.push_back(SM_SentinelUndef); continue; } uint64_t Element = RawMask[i]; // If the high bit (7) of the byte is set, the element is zeroed. if (Element & (1 << 7)) ShuffleMask.push_back(SM_SentinelZero); else { // For AVX vectors with 32 bytes the base of the shuffle is the 16-byte // lane of the vector we're inside. unsigned Base = i & ~0xf; // Only the least significant 4 bits of the byte are used. int Index = Base + (Element & 0xf); ShuffleMask.push_back(Index); } } } void DecodeVPERMILPMask(const Constant *C, unsigned ElSize, SmallVectorImpl<int> &ShuffleMask) { Type *MaskTy = C->getType(); unsigned MaskTySize = MaskTy->getPrimitiveSizeInBits(); (void)MaskTySize; assert((MaskTySize == 128 || MaskTySize == 256 || MaskTySize == 512) && "Unexpected vector size."); assert((ElSize == 32 || ElSize == 64) && "Unexpected vector element size."); // The shuffle mask requires elements the same size as the target. APInt UndefElts; SmallVector<uint64_t, 8> RawMask; if (!extractConstantMask(C, ElSize, UndefElts, RawMask)) return; unsigned NumElts = RawMask.size(); unsigned NumEltsPerLane = 128 / ElSize; assert((NumElts == 2 || NumElts == 4 || NumElts == 8 || NumElts == 16) && "Unexpected number of vector elements."); for (unsigned i = 0; i != NumElts; ++i) { if (UndefElts[i]) { ShuffleMask.push_back(SM_SentinelUndef); continue; } int Index = i & ~(NumEltsPerLane - 1); uint64_t Element = RawMask[i]; if (ElSize == 64) Index += (Element >> 1) & 0x1; else Index += Element & 0x3; ShuffleMask.push_back(Index); } } void DecodeVPERMIL2PMask(const Constant *C, unsigned M2Z, unsigned ElSize, SmallVectorImpl<int> &ShuffleMask) { Type *MaskTy = C->getType(); unsigned MaskTySize = MaskTy->getPrimitiveSizeInBits(); (void)MaskTySize; assert((MaskTySize == 128 || MaskTySize == 256) && "Unexpected vector size."); // The shuffle mask requires elements the same size as the target. APInt UndefElts; SmallVector<uint64_t, 8> RawMask; if (!extractConstantMask(C, ElSize, UndefElts, RawMask)) return; unsigned NumElts = RawMask.size(); unsigned NumEltsPerLane = 128 / ElSize; assert((NumElts == 2 || NumElts == 4 || NumElts == 8) && "Unexpected number of vector elements."); for (unsigned i = 0; i != NumElts; ++i) { if (UndefElts[i]) { ShuffleMask.push_back(SM_SentinelUndef); continue; } // VPERMIL2 Operation. // Bits[3] - Match Bit. // Bits[2:1] - (Per Lane) PD Shuffle Mask. // Bits[2:0] - (Per Lane) PS Shuffle Mask. uint64_t Selector = RawMask[i]; unsigned MatchBit = (Selector >> 3) & 0x1; // M2Z[0:1] MatchBit // 0Xb X Source selected by Selector index. // 10b 0 Source selected by Selector index. // 10b 1 Zero. // 11b 0 Zero. // 11b 1 Source selected by Selector index. if ((M2Z & 0x2) != 0u && MatchBit != (M2Z & 0x1)) { ShuffleMask.push_back(SM_SentinelZero); continue; } int Index = i & ~(NumEltsPerLane - 1); if (ElSize == 64) Index += (Selector >> 1) & 0x1; else Index += Selector & 0x3; int Src = (Selector >> 2) & 0x1; Index += Src * NumElts; ShuffleMask.push_back(Index); } } void DecodeVPPERMMask(const Constant *C, SmallVectorImpl<int> &ShuffleMask) { assert(C->getType()->getPrimitiveSizeInBits() == 128 && "Unexpected vector size."); // The shuffle mask requires a byte vector. APInt UndefElts; SmallVector<uint64_t, 32> RawMask; if (!extractConstantMask(C, 8, UndefElts, RawMask)) return; unsigned NumElts = RawMask.size(); assert(NumElts == 16 && "Unexpected number of vector elements."); for (unsigned i = 0; i != NumElts; ++i) { if (UndefElts[i]) { ShuffleMask.push_back(SM_SentinelUndef); continue; } // VPPERM Operation // Bits[4:0] - Byte Index (0 - 31) // Bits[7:5] - Permute Operation // // Permute Operation: // 0 - Source byte (no logical operation). // 1 - Invert source byte. // 2 - Bit reverse of source byte. // 3 - Bit reverse of inverted source byte. // 4 - 00h (zero - fill). // 5 - FFh (ones - fill). // 6 - Most significant bit of source byte replicated in all bit positions. // 7 - Invert most significant bit of source byte and replicate in all bit // positions. uint64_t Element = RawMask[i]; uint64_t Index = Element & 0x1F; uint64_t PermuteOp = (Element >> 5) & 0x7; if (PermuteOp == 4) { ShuffleMask.push_back(SM_SentinelZero); continue; } if (PermuteOp != 0) { ShuffleMask.clear(); return; } ShuffleMask.push_back((int)Index); } } void DecodeVPERMVMask(const Constant *C, unsigned ElSize, SmallVectorImpl<int> &ShuffleMask) { Type *MaskTy = C->getType(); unsigned MaskTySize = MaskTy->getPrimitiveSizeInBits(); (void)MaskTySize; assert((MaskTySize == 128 || MaskTySize == 256 || MaskTySize == 512) && "Unexpected vector size."); assert((ElSize == 8 || ElSize == 16 || ElSize == 32 || ElSize == 64) && "Unexpected vector element size."); // The shuffle mask requires elements the same size as the target. APInt UndefElts; SmallVector<uint64_t, 8> RawMask; if (!extractConstantMask(C, ElSize, UndefElts, RawMask)) return; unsigned NumElts = RawMask.size(); for (unsigned i = 0; i != NumElts; ++i) { if (UndefElts[i]) { ShuffleMask.push_back(SM_SentinelUndef); continue; } int Index = RawMask[i] & (NumElts - 1); ShuffleMask.push_back(Index); } } void DecodeVPERMV3Mask(const Constant *C, unsigned ElSize, SmallVectorImpl<int> &ShuffleMask) { Type *MaskTy = C->getType(); unsigned MaskTySize = MaskTy->getPrimitiveSizeInBits(); (void)MaskTySize; assert((MaskTySize == 128 || MaskTySize == 256 || MaskTySize == 512) && "Unexpected vector size."); assert((ElSize == 8 || ElSize == 16 || ElSize == 32 || ElSize == 64) && "Unexpected vector element size."); // The shuffle mask requires elements the same size as the target. APInt UndefElts; SmallVector<uint64_t, 8> RawMask; if (!extractConstantMask(C, ElSize, UndefElts, RawMask)) return; unsigned NumElts = RawMask.size(); for (unsigned i = 0; i != NumElts; ++i) { if (UndefElts[i]) { ShuffleMask.push_back(SM_SentinelUndef); continue; } int Index = RawMask[i] & (NumElts*2 - 1); ShuffleMask.push_back(Index); } } } // llvm namespace <commit_msg>[X86] Fix SmallVector sizes in constant pool shuffle decoding to avoid heap allocation<commit_after>//===-- X86ShuffleDecodeConstantPool.cpp - X86 shuffle decode -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Define several functions to decode x86 specific shuffle semantics using // constants from the constant pool. // //===----------------------------------------------------------------------===// #include "X86ShuffleDecodeConstantPool.h" #include "Utils/X86ShuffleDecode.h" #include "llvm/ADT/APInt.h" #include "llvm/CodeGen/MachineValueType.h" #include "llvm/IR/Constants.h" //===----------------------------------------------------------------------===// // Vector Mask Decoding //===----------------------------------------------------------------------===// namespace llvm { static bool extractConstantMask(const Constant *C, unsigned MaskEltSizeInBits, APInt &UndefElts, SmallVectorImpl<uint64_t> &RawMask) { // It is not an error for shuffle masks to not be a vector of // MaskEltSizeInBits because the constant pool uniques constants by their // bit representation. // e.g. the following take up the same space in the constant pool: // i128 -170141183420855150465331762880109871104 // // <2 x i64> <i64 -9223372034707292160, i64 -9223372034707292160> // // <4 x i32> <i32 -2147483648, i32 -2147483648, // i32 -2147483648, i32 -2147483648> Type *CstTy = C->getType(); if (!CstTy->isVectorTy()) return false; Type *CstEltTy = CstTy->getVectorElementType(); if (!CstEltTy->isIntegerTy()) return false; unsigned CstSizeInBits = CstTy->getPrimitiveSizeInBits(); unsigned CstEltSizeInBits = CstTy->getScalarSizeInBits(); unsigned NumCstElts = CstTy->getVectorNumElements(); // Extract all the undef/constant element data and pack into single bitsets. APInt UndefBits(CstSizeInBits, 0); APInt MaskBits(CstSizeInBits, 0); for (unsigned i = 0; i != NumCstElts; ++i) { Constant *COp = C->getAggregateElement(i); if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp))) return false; unsigned BitOffset = i * CstEltSizeInBits; if (isa<UndefValue>(COp)) { UndefBits.setBits(BitOffset, BitOffset + CstEltSizeInBits); continue; } auto *Elt = cast<ConstantInt>(COp); MaskBits |= Elt->getValue().zextOrTrunc(CstSizeInBits).shl(BitOffset); } // Now extract the undef/constant bit data into the raw shuffle masks. assert((CstSizeInBits % MaskEltSizeInBits) == 0 && "Unaligned shuffle mask size"); unsigned NumMaskElts = CstSizeInBits / MaskEltSizeInBits; UndefElts = APInt(NumMaskElts, 0); RawMask.resize(NumMaskElts, 0); for (unsigned i = 0; i != NumMaskElts; ++i) { unsigned BitOffset = i * MaskEltSizeInBits; APInt EltUndef = UndefBits.extractBits(MaskEltSizeInBits, BitOffset); // Only treat the element as UNDEF if all bits are UNDEF, otherwise // treat it as zero. if (EltUndef.isAllOnesValue()) { UndefElts.setBit(i); RawMask[i] = 0; continue; } APInt EltBits = MaskBits.extractBits(MaskEltSizeInBits, BitOffset); RawMask[i] = EltBits.getZExtValue(); } return true; } void DecodePSHUFBMask(const Constant *C, SmallVectorImpl<int> &ShuffleMask) { Type *MaskTy = C->getType(); unsigned MaskTySize = MaskTy->getPrimitiveSizeInBits(); (void)MaskTySize; assert((MaskTySize == 128 || MaskTySize == 256 || MaskTySize == 512) && "Unexpected vector size."); // The shuffle mask requires a byte vector. APInt UndefElts; SmallVector<uint64_t, 64> RawMask; if (!extractConstantMask(C, 8, UndefElts, RawMask)) return; unsigned NumElts = RawMask.size(); assert((NumElts == 16 || NumElts == 32 || NumElts == 64) && "Unexpected number of vector elements."); for (unsigned i = 0; i != NumElts; ++i) { if (UndefElts[i]) { ShuffleMask.push_back(SM_SentinelUndef); continue; } uint64_t Element = RawMask[i]; // If the high bit (7) of the byte is set, the element is zeroed. if (Element & (1 << 7)) ShuffleMask.push_back(SM_SentinelZero); else { // For AVX vectors with 32 bytes the base of the shuffle is the 16-byte // lane of the vector we're inside. unsigned Base = i & ~0xf; // Only the least significant 4 bits of the byte are used. int Index = Base + (Element & 0xf); ShuffleMask.push_back(Index); } } } void DecodeVPERMILPMask(const Constant *C, unsigned ElSize, SmallVectorImpl<int> &ShuffleMask) { Type *MaskTy = C->getType(); unsigned MaskTySize = MaskTy->getPrimitiveSizeInBits(); (void)MaskTySize; assert((MaskTySize == 128 || MaskTySize == 256 || MaskTySize == 512) && "Unexpected vector size."); assert((ElSize == 32 || ElSize == 64) && "Unexpected vector element size."); // The shuffle mask requires elements the same size as the target. APInt UndefElts; SmallVector<uint64_t, 16> RawMask; if (!extractConstantMask(C, ElSize, UndefElts, RawMask)) return; unsigned NumElts = RawMask.size(); unsigned NumEltsPerLane = 128 / ElSize; assert((NumElts == 2 || NumElts == 4 || NumElts == 8 || NumElts == 16) && "Unexpected number of vector elements."); for (unsigned i = 0; i != NumElts; ++i) { if (UndefElts[i]) { ShuffleMask.push_back(SM_SentinelUndef); continue; } int Index = i & ~(NumEltsPerLane - 1); uint64_t Element = RawMask[i]; if (ElSize == 64) Index += (Element >> 1) & 0x1; else Index += Element & 0x3; ShuffleMask.push_back(Index); } } void DecodeVPERMIL2PMask(const Constant *C, unsigned M2Z, unsigned ElSize, SmallVectorImpl<int> &ShuffleMask) { Type *MaskTy = C->getType(); unsigned MaskTySize = MaskTy->getPrimitiveSizeInBits(); (void)MaskTySize; assert((MaskTySize == 128 || MaskTySize == 256) && "Unexpected vector size."); // The shuffle mask requires elements the same size as the target. APInt UndefElts; SmallVector<uint64_t, 8> RawMask; if (!extractConstantMask(C, ElSize, UndefElts, RawMask)) return; unsigned NumElts = RawMask.size(); unsigned NumEltsPerLane = 128 / ElSize; assert((NumElts == 2 || NumElts == 4 || NumElts == 8) && "Unexpected number of vector elements."); for (unsigned i = 0; i != NumElts; ++i) { if (UndefElts[i]) { ShuffleMask.push_back(SM_SentinelUndef); continue; } // VPERMIL2 Operation. // Bits[3] - Match Bit. // Bits[2:1] - (Per Lane) PD Shuffle Mask. // Bits[2:0] - (Per Lane) PS Shuffle Mask. uint64_t Selector = RawMask[i]; unsigned MatchBit = (Selector >> 3) & 0x1; // M2Z[0:1] MatchBit // 0Xb X Source selected by Selector index. // 10b 0 Source selected by Selector index. // 10b 1 Zero. // 11b 0 Zero. // 11b 1 Source selected by Selector index. if ((M2Z & 0x2) != 0u && MatchBit != (M2Z & 0x1)) { ShuffleMask.push_back(SM_SentinelZero); continue; } int Index = i & ~(NumEltsPerLane - 1); if (ElSize == 64) Index += (Selector >> 1) & 0x1; else Index += Selector & 0x3; int Src = (Selector >> 2) & 0x1; Index += Src * NumElts; ShuffleMask.push_back(Index); } } void DecodeVPPERMMask(const Constant *C, SmallVectorImpl<int> &ShuffleMask) { assert(C->getType()->getPrimitiveSizeInBits() == 128 && "Unexpected vector size."); // The shuffle mask requires a byte vector. APInt UndefElts; SmallVector<uint64_t, 16> RawMask; if (!extractConstantMask(C, 8, UndefElts, RawMask)) return; unsigned NumElts = RawMask.size(); assert(NumElts == 16 && "Unexpected number of vector elements."); for (unsigned i = 0; i != NumElts; ++i) { if (UndefElts[i]) { ShuffleMask.push_back(SM_SentinelUndef); continue; } // VPPERM Operation // Bits[4:0] - Byte Index (0 - 31) // Bits[7:5] - Permute Operation // // Permute Operation: // 0 - Source byte (no logical operation). // 1 - Invert source byte. // 2 - Bit reverse of source byte. // 3 - Bit reverse of inverted source byte. // 4 - 00h (zero - fill). // 5 - FFh (ones - fill). // 6 - Most significant bit of source byte replicated in all bit positions. // 7 - Invert most significant bit of source byte and replicate in all bit // positions. uint64_t Element = RawMask[i]; uint64_t Index = Element & 0x1F; uint64_t PermuteOp = (Element >> 5) & 0x7; if (PermuteOp == 4) { ShuffleMask.push_back(SM_SentinelZero); continue; } if (PermuteOp != 0) { ShuffleMask.clear(); return; } ShuffleMask.push_back((int)Index); } } void DecodeVPERMVMask(const Constant *C, unsigned ElSize, SmallVectorImpl<int> &ShuffleMask) { Type *MaskTy = C->getType(); unsigned MaskTySize = MaskTy->getPrimitiveSizeInBits(); (void)MaskTySize; assert((MaskTySize == 128 || MaskTySize == 256 || MaskTySize == 512) && "Unexpected vector size."); assert((ElSize == 8 || ElSize == 16 || ElSize == 32 || ElSize == 64) && "Unexpected vector element size."); // The shuffle mask requires elements the same size as the target. APInt UndefElts; SmallVector<uint64_t, 64> RawMask; if (!extractConstantMask(C, ElSize, UndefElts, RawMask)) return; unsigned NumElts = RawMask.size(); for (unsigned i = 0; i != NumElts; ++i) { if (UndefElts[i]) { ShuffleMask.push_back(SM_SentinelUndef); continue; } int Index = RawMask[i] & (NumElts - 1); ShuffleMask.push_back(Index); } } void DecodeVPERMV3Mask(const Constant *C, unsigned ElSize, SmallVectorImpl<int> &ShuffleMask) { Type *MaskTy = C->getType(); unsigned MaskTySize = MaskTy->getPrimitiveSizeInBits(); (void)MaskTySize; assert((MaskTySize == 128 || MaskTySize == 256 || MaskTySize == 512) && "Unexpected vector size."); assert((ElSize == 8 || ElSize == 16 || ElSize == 32 || ElSize == 64) && "Unexpected vector element size."); // The shuffle mask requires elements the same size as the target. APInt UndefElts; SmallVector<uint64_t, 64> RawMask; if (!extractConstantMask(C, ElSize, UndefElts, RawMask)) return; unsigned NumElts = RawMask.size(); for (unsigned i = 0; i != NumElts; ++i) { if (UndefElts[i]) { ShuffleMask.push_back(SM_SentinelUndef); continue; } int Index = RawMask[i] & (NumElts*2 - 1); ShuffleMask.push_back(Index); } } } // llvm namespace <|endoftext|>
<commit_before>#include "math_util.h" #include "test_util.h" void conv_test_set(vector<scalar>& data, vector<scalar>& filter, vector<scalar>& expected_conv) { data.resize(25); for (int i = 0; i < 25; ++i) data[i] = i; filter = {0, 1, 0, 1, 2, 1, 0, 1, 0}; expected_conv = {6, 10, 15, 20, 20, 26, 36, 42, 48, 44, 51, 66, 72, 78, 69, 76, 96, 102, 108, 94, 76, 100, 105, 110, 90}; } SUITE(convolution) { TEST(naive_conv1) { vector<scalar> data, filter, conv, expected_conv; conv_test_set(data, filter, expected_conv); convolve(5, 5, data, 3, 3, filter, expected_conv); CHECK_ARRAY(conv.data(), expected_conv.data(), 25); } } <commit_msg>fixes convolution test<commit_after>#include "math_util.h" #include "test_util.h" #include <vector> using std::vector; void conv_test_set(vector<scalar>& data, vector<scalar>& filter, vector<scalar>& expected_conv) { data.resize(25); for (int i = 0; i < 25; ++i) data[i] = i; filter = {0, 1, 0, 1, 2, 1, 0, 1, 0}; expected_conv = {6, 10, 15, 20, 20, 26, 36, 42, 48, 44, 51, 66, 72, 78, 69, 76, 96, 102, 108, 94, 76, 100, 105, 110, 90}; } SUITE(convolution) { TEST(naive_conv1) { vector<scalar> data, filter, conv, expected_conv; conv_test_set(data, filter, expected_conv); convolve(5, 5, data, 3, 3, filter, conv); CHECK_ARRAY_CLOSE(conv.data(), expected_conv.data(), 25, EPS); } } <|endoftext|>
<commit_before><commit_msg>Add pickable steering wheel<commit_after><|endoftext|>
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/operators/reduce_op.h" #include "paddle/operators/net_op.h" namespace paddle { namespace operators { using framework::Tensor; class ReduceOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext *ctx) const override { PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) of ReduceOp should not be null."); PADDLE_ENFORCE(ctx->HasOutput("Out"), "Output(Out) of ReduceOp should not be null."); auto x_dims = ctx->GetInputDim("X"); auto x_rank = x_dims.size(); PADDLE_ENFORCE_LE(x_rank, 6, "Tensors with rank at most 6 are supported."); int dim = ctx->Attrs().Get<int>("dim"); if (dim < 0) dim = x_rank + dim; PADDLE_ENFORCE_LT( dim, x_rank, "The dim should be in the range [-rank(input), rank(input))."); bool reduce_all = ctx->Attrs().Get<bool>("reduce_all"); if (reduce_all) { ctx->SetOutputDim("Out", {1}); } else { bool keep_dim = ctx->Attrs().Get<bool>("keep_dim"); auto dims_vector = vectorize(x_dims); if (keep_dim || x_rank == 1) { dims_vector[dim] = 1; } else { dims_vector.erase(dims_vector.begin() + dim); } auto out_dims = framework::make_ddim(dims_vector); ctx->SetOutputDim("Out", out_dims); if (dim != 0) { // Only pass LoD when not reducing on the first dim. ctx->ShareLoD("X", /*->*/ "Out"); } } } }; class ReduceGradOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext *ctx) const override { PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should not be null."); PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Out")), "Input(Out@GRAD) should not be null."); auto x_dims = ctx->GetInputDim("X"); auto x_rank = x_dims.size(); PADDLE_ENFORCE_LE(x_rank, 6, "Tensors with rank at most 6 are supported."); int dim = ctx->Attrs().Get<int>("dim"); if (dim < 0) dim = x_rank + dim; PADDLE_ENFORCE_LT( dim, x_rank, "The dim should be in the range [-rank(input), rank(input))."); auto x_grad_name = framework::GradVarName("X"); if (ctx->HasOutput(x_grad_name)) { ctx->SetOutputDim(x_grad_name, x_dims); ctx->ShareLoD("X", /*->*/ x_grad_name); } } }; class ReduceOpMaker : public framework::OpProtoAndCheckerMaker { public: ReduceOpMaker(OpProto *proto, OpAttrChecker *op_checker) : OpProtoAndCheckerMaker(proto, op_checker) { AddInput("X", "(Tensor) The input tensor. Tensors with rank at most 6 are " "supported."); AddOutput("Out", "(Tensor) The result tensor."); AddAttr<int>( "dim", "(int, default 0) The dimension to reduce. " "Must be in the range [-rank(input), rank(input)). " "If `dim < 0`, the dim to reduce is `rank + dim`. " "Note that reducing on the first dim will make the LoD info lost.") .SetDefault(0); AddAttr<bool>("keep_dim", "(bool, default false) " "If true, retain the reduced dimension with length 1.") .SetDefault(false); AddAttr<bool>("reduce_all", "(bool, default false) " "If true, output a scalar reduced along all dimensions.") .SetDefault(false); comment_ = R"DOC( {ReduceOp} Operator. This operator computes the {reduce} of input tensor along the given dimension. The result tensor has 1 fewer dimension than the input unless keep_dim is true. If reduce_all is true, just reduce along all dimensions and output a scalar. )DOC"; AddComment(comment_); } protected: std::string comment_; void Replace(std::string &src, std::string from, std::string to) { std::size_t len_from = std::strlen(from.c_str()); std::size_t len_to = std::strlen(to.c_str()); for (std::size_t pos = src.find(from); pos != std::string::npos; pos = src.find(from, pos + len_to)) { src.replace(pos, len_from, to); } } void SetComment(std::string name, std::string op) { Replace(comment_, "{ReduceOP}", name); Replace(comment_, "{reduce}", op); } }; class ReduceSumOpMaker : public ReduceOpMaker { public: ReduceSumOpMaker(OpProto *proto, OpAttrChecker *op_checker) : ReduceOpMaker(proto, op_checker) { SetComment("ReduceSum", "sum"); AddComment(comment_); } }; class ReduceMeanOpMaker : public ReduceOpMaker { public: ReduceMeanOpMaker(OpProto *proto, OpAttrChecker *op_checker) : ReduceOpMaker(proto, op_checker) { SetComment("ReduceMean", "mean"); AddComment(comment_); } }; class ReduceMaxOpMaker : public ReduceOpMaker { public: ReduceMaxOpMaker(OpProto *proto, OpAttrChecker *op_checker) : ReduceOpMaker(proto, op_checker) { SetComment("ReduceMax", "max"); AddComment(comment_); } }; class ReduceMinOpMaker : public ReduceOpMaker { public: ReduceMinOpMaker(OpProto *proto, OpAttrChecker *op_checker) : ReduceOpMaker(proto, op_checker) { SetComment("ReduceMin", "min"); AddComment(comment_); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP(reduce_sum, ops::ReduceOp, ops::ReduceSumOpMaker, reduce_sum_grad, ops::ReduceGradOp); REGISTER_OP(reduce_mean, ops::ReduceOp, ops::ReduceMeanOpMaker, reduce_mean_grad, ops::ReduceGradOp); REGISTER_OP(reduce_max, ops::ReduceOp, ops::ReduceMaxOpMaker, reduce_max_grad, ops::ReduceGradOp); REGISTER_OP(reduce_min, ops::ReduceOp, ops::ReduceMinOpMaker, reduce_min_grad, ops::ReduceGradOp); #define REGISTER_REDUCE_CPU_KERNEL(reduce_type, functor, grad_functor) \ REGISTER_OP_CPU_KERNEL(reduce_type, \ ops::ReduceKernel<paddle::platform::CPUDeviceContext, \ float, ops::functor>); \ REGISTER_OP_CPU_KERNEL( \ reduce_type##_grad, \ ops::ReduceGradKernel<paddle::platform::CPUDeviceContext, float, \ ops::grad_functor>); FOR_EACH_KERNEL_FUNCTOR(REGISTER_REDUCE_CPU_KERNEL); <commit_msg>Fixing the rendering for Reduce operators in operator documentation<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/operators/reduce_op.h" #include "paddle/operators/net_op.h" namespace paddle { namespace operators { using framework::Tensor; class ReduceOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext *ctx) const override { PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) of ReduceOp should not be null."); PADDLE_ENFORCE(ctx->HasOutput("Out"), "Output(Out) of ReduceOp should not be null."); auto x_dims = ctx->GetInputDim("X"); auto x_rank = x_dims.size(); PADDLE_ENFORCE_LE(x_rank, 6, "Tensors with rank at most 6 are supported."); int dim = ctx->Attrs().Get<int>("dim"); if (dim < 0) dim = x_rank + dim; PADDLE_ENFORCE_LT( dim, x_rank, "The dim should be in the range [-rank(input), rank(input))."); bool reduce_all = ctx->Attrs().Get<bool>("reduce_all"); if (reduce_all) { ctx->SetOutputDim("Out", {1}); } else { bool keep_dim = ctx->Attrs().Get<bool>("keep_dim"); auto dims_vector = vectorize(x_dims); if (keep_dim || x_rank == 1) { dims_vector[dim] = 1; } else { dims_vector.erase(dims_vector.begin() + dim); } auto out_dims = framework::make_ddim(dims_vector); ctx->SetOutputDim("Out", out_dims); if (dim != 0) { // Only pass LoD when not reducing on the first dim. ctx->ShareLoD("X", /*->*/ "Out"); } } } }; class ReduceGradOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext *ctx) const override { PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should not be null."); PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Out")), "Input(Out@GRAD) should not be null."); auto x_dims = ctx->GetInputDim("X"); auto x_rank = x_dims.size(); PADDLE_ENFORCE_LE(x_rank, 6, "Tensors with rank at most 6 are supported."); int dim = ctx->Attrs().Get<int>("dim"); if (dim < 0) dim = x_rank + dim; PADDLE_ENFORCE_LT( dim, x_rank, "The dim should be in the range [-rank(input), rank(input))."); auto x_grad_name = framework::GradVarName("X"); if (ctx->HasOutput(x_grad_name)) { ctx->SetOutputDim(x_grad_name, x_dims); ctx->ShareLoD("X", /*->*/ x_grad_name); } } }; class ReduceOpMaker : public framework::OpProtoAndCheckerMaker { public: ReduceOpMaker(OpProto *proto, OpAttrChecker *op_checker) : OpProtoAndCheckerMaker(proto, op_checker) { AddInput("X", "(Tensor) The input tensor. Tensors with rank at most 6 are " "supported."); AddOutput("Out", "(Tensor) The result tensor."); AddAttr<int>( "dim", "(int, default 0) The dimension to reduce. " "Must be in the range [-rank(input), rank(input)). " "If `dim < 0`, the dim to reduce is `rank + dim`. " "Note that reducing on the first dim will make the LoD info lost.") .SetDefault(0); AddAttr<bool>("keep_dim", "(bool, default false) " "If true, retain the reduced dimension with length 1.") .SetDefault(false); AddAttr<bool>("reduce_all", "(bool, default false) " "If true, output a scalar reduced along all dimensions.") .SetDefault(false); comment_ = R"DOC( {ReduceOp} Operator. This operator computes the {reduce} of input tensor along the given dimension. The result tensor has 1 fewer dimension than the input unless keep_dim is true. If reduce_all is true, just reduce along all dimensions and output a scalar. )DOC"; AddComment(comment_); } protected: std::string comment_; void Replace(std::string &src, std::string from, std::string to) { std::size_t len_from = std::strlen(from.c_str()); std::size_t len_to = std::strlen(to.c_str()); for (std::size_t pos = src.find(from); pos != std::string::npos; pos = src.find(from, pos + len_to)) { src.replace(pos, len_from, to); } } void SetComment(std::string name, std::string op) { Replace(comment_, "{ReduceOp}", name); Replace(comment_, "{reduce}", op); } }; class ReduceSumOpMaker : public ReduceOpMaker { public: ReduceSumOpMaker(OpProto *proto, OpAttrChecker *op_checker) : ReduceOpMaker(proto, op_checker) { SetComment("ReduceSum", "sum"); AddComment(comment_); } }; class ReduceMeanOpMaker : public ReduceOpMaker { public: ReduceMeanOpMaker(OpProto *proto, OpAttrChecker *op_checker) : ReduceOpMaker(proto, op_checker) { SetComment("ReduceMean", "mean"); AddComment(comment_); } }; class ReduceMaxOpMaker : public ReduceOpMaker { public: ReduceMaxOpMaker(OpProto *proto, OpAttrChecker *op_checker) : ReduceOpMaker(proto, op_checker) { SetComment("ReduceMax", "max"); AddComment(comment_); } }; class ReduceMinOpMaker : public ReduceOpMaker { public: ReduceMinOpMaker(OpProto *proto, OpAttrChecker *op_checker) : ReduceOpMaker(proto, op_checker) { SetComment("ReduceMin", "min"); AddComment(comment_); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP(reduce_sum, ops::ReduceOp, ops::ReduceSumOpMaker, reduce_sum_grad, ops::ReduceGradOp); REGISTER_OP(reduce_mean, ops::ReduceOp, ops::ReduceMeanOpMaker, reduce_mean_grad, ops::ReduceGradOp); REGISTER_OP(reduce_max, ops::ReduceOp, ops::ReduceMaxOpMaker, reduce_max_grad, ops::ReduceGradOp); REGISTER_OP(reduce_min, ops::ReduceOp, ops::ReduceMinOpMaker, reduce_min_grad, ops::ReduceGradOp); #define REGISTER_REDUCE_CPU_KERNEL(reduce_type, functor, grad_functor) \ REGISTER_OP_CPU_KERNEL(reduce_type, \ ops::ReduceKernel<paddle::platform::CPUDeviceContext, \ float, ops::functor>); \ REGISTER_OP_CPU_KERNEL( \ reduce_type##_grad, \ ops::ReduceGradKernel<paddle::platform::CPUDeviceContext, float, \ ops::grad_functor>); FOR_EACH_KERNEL_FUNCTOR(REGISTER_REDUCE_CPU_KERNEL); <|endoftext|>
<commit_before><commit_msg>Added missing stddef.h include<commit_after><|endoftext|>
<commit_before>/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.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 <signal.h> #include <iostream> #include "Util/CMD.h" #include "Util/logger.h" #include "Util/util.h" #include "Network/TcpSession.h" #include "Network/TcpServer.h" using namespace std; using namespace toolkit; /** * 回显会话 */ class EchoSession : public TcpSession { public: EchoSession(const Socket::Ptr &pSock) : TcpSession(pSock){ DebugL; } virtual ~EchoSession(){ DebugL; } void onRecv(const Buffer::Ptr &buffer) override { send(buffer); } void onError(const SockException &err) override{ WarnL << err.what(); } void onManager() override {} }; //命令(http) class CMD_pingpong: public CMD { public: CMD_pingpong(){ _parser.reset(new OptionParser(nullptr)); (*_parser) << Option('l', "listen", Option::ArgRequired, "10000", false, "服务器模式:监听端口", nullptr); //测试客户端个数,默认10个 (*_parser) << Option('c', "count", Option::ArgRequired, to_string(10).data(), false, "客户端模式:测试数据块大小", nullptr); //默认每次发送1MB的数据 (*_parser) << Option('b', "block", Option::ArgRequired, to_string(1024 * 1024).data(), false, "客户端模式:测试数据块大小", nullptr); //默认1秒发送10次,总速度率为1MB/s * 10 * 10 = 100MB/s (*_parser) << Option('i', "interval", Option::ArgRequired, to_string(100).data(), false, "客户端模式:测试数据发送间隔,单位毫秒", nullptr); //指定服务器地址 (*_parser) << Option('s', "server", Option::ArgRequired, "127.0.0.1:10000", false, "客户端模式:测试服务器地址", [] (const std::shared_ptr<ostream> &stream, const string &arg) { if (arg.find(":") == string::npos) { //中断后续选项的解析以及解析完毕回调等操作 throw std::runtime_error("\t地址必须指明端口号."); } //如果返回false则忽略后续选项的解析 return true; }); } ~CMD_pingpong() {} const char *description() const override { return "tcp回显性能测试"; } }; EventPoller::Ptr nextPoller(){ static vector<EventPoller::Ptr> s_poller_vec; static int s_poller_index = 0; if(s_poller_vec.empty()){ EventPollerPool::Instance().for_each([&](TaskExecutor::Ptr &executor){ s_poller_vec.emplace_back(dynamic_pointer_cast<EventPoller>(executor)); }); } auto ret = s_poller_vec[s_poller_index++]; if(s_poller_index == s_poller_vec.size()){ s_poller_index = 0; } return ret; } int main(int argc,char *argv[]){ CMD_pingpong cmd; try{ cmd(argc,argv); }catch (std::exception &ex){ cout << ex.what() << endl; return 0; } //初始化环境 Logger::Instance().add(std::shared_ptr<ConsoleChannel>(new ConsoleChannel())); Logger::Instance().setWriter(std::shared_ptr<LogWriter>(new AsyncLogWriter())); { int interval = cmd["interval"]; int block = cmd["block"]; auto ip = cmd.splitedVal("server")[0]; int port = cmd.splitedVal("server")[1]; BufferRaw::Ptr buffer = std::make_shared<BufferRaw>(block); buffer->setSize(block); TcpServer::Ptr server(new TcpServer); server->start<EchoSession>(cmd["listen"]); for(auto i = 0; i < cmd["count"].as<int>() ; ++i){ auto poller = nextPoller(); auto socket = std::make_shared<Socket>(poller, false); socket->connect(ip,port,[socket,poller,interval,buffer](const SockException &err){ if(err){ WarnL << err.what(); return; } socket->setOnRead([](const Buffer::Ptr &buf, struct sockaddr *addr , int addr_len){}); poller->doDelayTask(interval,[socket,interval,buffer](){ socket->send(buffer); return interval; }); }); } //设置退出信号处理函数 static semaphore sem; signal(SIGINT, [](int) { sem.post(); });// 设置退出信号 sem.wait(); } return 0; }<commit_msg>修正参数说明<commit_after>/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.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 <signal.h> #include <iostream> #include "Util/CMD.h" #include "Util/logger.h" #include "Util/util.h" #include "Network/TcpSession.h" #include "Network/TcpServer.h" using namespace std; using namespace toolkit; /** * 回显会话 */ class EchoSession : public TcpSession { public: EchoSession(const Socket::Ptr &pSock) : TcpSession(pSock){ DebugL; } virtual ~EchoSession(){ DebugL; } void onRecv(const Buffer::Ptr &buffer) override { send(buffer); } void onError(const SockException &err) override{ WarnL << err.what(); } void onManager() override {} }; //命令(http) class CMD_pingpong: public CMD { public: CMD_pingpong(){ _parser.reset(new OptionParser(nullptr)); (*_parser) << Option('l', "listen", Option::ArgRequired, "10000", false, "服务器模式:监听端口", nullptr); //测试客户端个数,默认10个 (*_parser) << Option('c', "count", Option::ArgRequired, to_string(10).data(), false, "客户端模式:测试客户端个数", nullptr); //默认每次发送1MB的数据 (*_parser) << Option('b', "block", Option::ArgRequired, to_string(1024 * 1024).data(), false, "客户端模式:测试数据块大小", nullptr); //默认1秒发送10次,总速度率为1MB/s * 10 * 10 = 100MB/s (*_parser) << Option('i', "interval", Option::ArgRequired, to_string(100).data(), false, "客户端模式:测试数据发送间隔,单位毫秒", nullptr); //指定服务器地址 (*_parser) << Option('s', "server", Option::ArgRequired, "127.0.0.1:10000", false, "客户端模式:测试服务器地址", [] (const std::shared_ptr<ostream> &stream, const string &arg) { if (arg.find(":") == string::npos) { //中断后续选项的解析以及解析完毕回调等操作 throw std::runtime_error("\t地址必须指明端口号."); } //如果返回false则忽略后续选项的解析 return true; }); } ~CMD_pingpong() {} const char *description() const override { return "tcp回显性能测试"; } }; EventPoller::Ptr nextPoller(){ static vector<EventPoller::Ptr> s_poller_vec; static int s_poller_index = 0; if(s_poller_vec.empty()){ EventPollerPool::Instance().for_each([&](TaskExecutor::Ptr &executor){ s_poller_vec.emplace_back(dynamic_pointer_cast<EventPoller>(executor)); }); } auto ret = s_poller_vec[s_poller_index++]; if(s_poller_index == s_poller_vec.size()){ s_poller_index = 0; } return ret; } int main(int argc,char *argv[]){ CMD_pingpong cmd; try{ cmd(argc,argv); }catch (std::exception &ex){ cout << ex.what() << endl; return 0; } //初始化环境 Logger::Instance().add(std::shared_ptr<ConsoleChannel>(new ConsoleChannel())); Logger::Instance().setWriter(std::shared_ptr<LogWriter>(new AsyncLogWriter())); { int interval = cmd["interval"]; int block = cmd["block"]; auto ip = cmd.splitedVal("server")[0]; int port = cmd.splitedVal("server")[1]; BufferRaw::Ptr buffer = std::make_shared<BufferRaw>(block); buffer->setSize(block); TcpServer::Ptr server(new TcpServer); server->start<EchoSession>(cmd["listen"]); for(auto i = 0; i < cmd["count"].as<int>() ; ++i){ auto poller = nextPoller(); auto socket = std::make_shared<Socket>(poller, false); socket->connect(ip,port,[socket,poller,interval,buffer](const SockException &err){ if(err){ WarnL << err.what(); return; } socket->setOnRead([](const Buffer::Ptr &buf, struct sockaddr *addr , int addr_len){}); poller->doDelayTask(interval,[socket,interval,buffer](){ socket->send(buffer); return interval; }); }); } //设置退出信号处理函数 static semaphore sem; signal(SIGINT, [](int) { sem.post(); });// 设置退出信号 sem.wait(); } return 0; }<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: selectionstate.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2006-07-21 15:08:14 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" #ifndef SC_SELECTIONSTATE_HXX #include "selectionstate.hxx" #endif #include <svx/editview.hxx> #ifndef SC_VIEWDATA_HXX #include "viewdata.hxx" #endif // ============================================================================ ScSelectionState::ScSelectionState( ScViewData& rViewData ) : meType( SC_SELECTTYPE_NONE ) { maCursor.SetTab( rViewData.GetTabNo() ); ScSplitPos eWhich = rViewData.GetActivePart(); if( rViewData.HasEditView( eWhich ) ) { meType = SC_SELECTTYPE_EDITCELL; maCursor.SetCol( rViewData.GetEditViewCol() ); maCursor.SetRow( rViewData.GetEditViewRow() ); maEditSel = rViewData.GetEditView( eWhich )->GetSelection(); } else { maCursor.SetCol( rViewData.GetCurX() ); maCursor.SetRow( rViewData.GetCurY() ); ScMarkData& rMarkData = rViewData.GetMarkData(); rMarkData.MarkToMulti(); if( rMarkData.IsMultiMarked() ) { meType = SC_SELECTTYPE_SHEET; rMarkData.FillRangeListWithMarks( &maSheetSel, FALSE ); } // else type is SC_SELECTTYPE_NONE - already initialized } } bool operator==( const ScSelectionState& rL, const ScSelectionState& rR ) { bool bEqual = rL.GetSelectionType() == rR.GetSelectionType(); if( bEqual ) switch( rL.GetSelectionType() ) { case SC_SELECTTYPE_EDITCELL: bEqual &= rL.GetEditSelection().IsEqual( rR.GetEditSelection() ); // run through! case SC_SELECTTYPE_SHEET: bEqual &= (rL.GetSheetSelection() == rR.GetSheetSelection()) == TRUE; // run through! case SC_SELECTTYPE_NONE: bEqual &= rL.GetCellCursor() == rR.GetCellCursor(); break; } return bEqual; } // ============================================================================ <commit_msg>INTEGRATION: CWS calcwarnings (1.4.110); FILE MERGED 2006/12/01 08:53:49 nn 1.4.110.1: #i69284# warning-free: ui, wntmsci10<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: selectionstate.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: vg $ $Date: 2007-02-27 13:56:23 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" #ifndef SC_SELECTIONSTATE_HXX #include "selectionstate.hxx" #endif #include <svx/editview.hxx> #ifndef SC_VIEWDATA_HXX #include "viewdata.hxx" #endif // ============================================================================ ScSelectionState::ScSelectionState( ScViewData& rViewData ) : meType( SC_SELECTTYPE_NONE ) { maCursor.SetTab( rViewData.GetTabNo() ); ScSplitPos eWhich = rViewData.GetActivePart(); if( rViewData.HasEditView( eWhich ) ) { meType = SC_SELECTTYPE_EDITCELL; maCursor.SetCol( rViewData.GetEditViewCol() ); maCursor.SetRow( rViewData.GetEditViewRow() ); maEditSel = rViewData.GetEditView( eWhich )->GetSelection(); } else { maCursor.SetCol( rViewData.GetCurX() ); maCursor.SetRow( rViewData.GetCurY() ); ScMarkData& rMarkData = rViewData.GetMarkData(); rMarkData.MarkToMulti(); if( rMarkData.IsMultiMarked() ) { meType = SC_SELECTTYPE_SHEET; rMarkData.FillRangeListWithMarks( &maSheetSel, FALSE ); } // else type is SC_SELECTTYPE_NONE - already initialized } } bool operator==( const ScSelectionState& rL, const ScSelectionState& rR ) { bool bEqual = rL.GetSelectionType() == rR.GetSelectionType(); if( bEqual ) switch( rL.GetSelectionType() ) { case SC_SELECTTYPE_EDITCELL: bEqual &= ( rL.GetEditSelection().IsEqual( rR.GetEditSelection() ) != FALSE ); // run through! case SC_SELECTTYPE_SHEET: bEqual &= (rL.GetSheetSelection() == rR.GetSheetSelection()) == TRUE; // run through! case SC_SELECTTYPE_NONE: bEqual &= rL.GetCellCursor() == rR.GetCellCursor(); break; default: { // added to avoid warnings } } return bEqual; } // ============================================================================ <|endoftext|>
<commit_before>#define CATCH_CONFIG_MAIN #include "catch.hpp" #include "data/filters.h" #include "yaml-cpp/yaml.h" #include "scene/sceneLoader.h" #include "scene/scene.h" #include "platform.h" using namespace Tangram; SceneLoader sceneLoader; TEST_CASE( "", "[Duktape][init]") { { StyleContext(); } } TEST_CASE( "Test filter without feature being set", "[Duktape][evalFilterFn]") { { StyleContext ctx; ctx.addFunction("fn", R"(function() { return feature.name == undefined; })"); ctx.addAccessor("name"); REQUIRE(ctx.evalFilterFn("fn") == true); ctx.addFunction("fn2", R"(function() { return feature.name == ''; })"); REQUIRE(ctx.evalFilterFn("fn2") == false); } } TEST_CASE( "Test evalFilterFn with feature", "[Duktape][evalFilterFn]") { { Feature feature; feature.props.add("a", "A"); feature.props.add("b", "B"); feature.props.add("n", 42); StyleContext ctx; ctx.setFeature(feature); ctx.addFunction("fn_a", R"(function() { return feature.a == 'A' })"); REQUIRE(ctx.evalFilterFn("fn_a") == true); ctx.addFunction("fn_b", R"(function() { return feature.b == 'B' })"); REQUIRE(ctx.evalFilterFn("fn_b") == true); ctx.addFunction("fn_n", R"(function() { return feature.n == 42 })"); REQUIRE(ctx.evalFilterFn("fn_n") == true); ctx.addFunction("fn_n2", R"(function() { return feature.n == 43 })"); REQUIRE(ctx.evalFilterFn("fn_n2") == false); // OK? ctx.addFunction("fn_n3", R"(function() { return feature.n == '42' })"); REQUIRE(ctx.evalFilterFn("fn_n3") == true); } } TEST_CASE( "Test evalFilterFn with feature and globals", "[Duktape][evalFilterFn]") { { Feature feature; feature.props.add("scalerank", 2); StyleContext ctx; ctx.setFeature(feature); ctx.setGlobal("$zoom", 5); ctx.addFunction("fn", R"(function() { return (feature.scalerank * .5) <= ($zoom - 4); })"); REQUIRE(ctx.evalFilterFn("fn") == true); ctx.setGlobal("$zoom", 4); REQUIRE(ctx.evalFilterFn("fn") == false); } } TEST_CASE( "Test evalFilterFn with different features", "[Duktape][evalFilterFn]") { { StyleContext ctx; ctx.addFunction("fn", R"(function() { return feature.scalerank == 2; })"); Feature feat1; feat1.props.add("scalerank", 2); ctx.setFeature(feat1); REQUIRE(ctx.evalFilterFn("fn") == true); Feature feat2; ctx.setFeature(feat2); REQUIRE(ctx.evalFilterFn("fn") == false); ctx.setFeature(feat1); REQUIRE(ctx.evalFilterFn("fn") == true); } } TEST_CASE( "Test numeric global", "[Duktape][setGlobal]") { { StyleContext ctx; ctx.setGlobal("$zoom", 10); ctx.addFunction("fn", R"(function() { return $zoom == 10 })"); REQUIRE(ctx.evalFilterFn("fn") == true); ctx.setGlobal("$zoom", 0); REQUIRE(ctx.evalFilterFn("fn") == false); } } TEST_CASE( "Test string global", "[Duktape][setGlobal]") { { StyleContext ctx; ctx.setGlobal("$layer", "test"); ctx.addFunction("fn", R"(function() { return $layer == 'test' })"); REQUIRE(ctx.evalFilterFn("fn") == true); ctx.setGlobal("$layer", "none"); REQUIRE(ctx.evalFilterFn("fn") == false); } } TEST_CASE( "Test evalStyleFn - StyleParamKey::order", "[Duktape][evalStyleFn]") { { Feature feat; feat.props.add("sort_key", 2); StyleContext ctx; ctx.setFeature(feat); ctx.addFunction("fn", R"(function () { return feature.sort_key + 5 })"); StyleParam::Value value; REQUIRE(ctx.evalStyleFn("fn", StyleParamKey::order, value) == true); REQUIRE(value.is<int32_t>() == true); REQUIRE(value.get<int32_t>() == 7); } } TEST_CASE( "Test evalStyleFn - StyleParamKey::color", "[Duktape][evalStyleFn]") { { Feature feat; feat.props.add("sort_key", 2); StyleContext ctx; ctx.setFeature(feat); ctx.addFunction("fn", R"(function () { return '#f0f' })"); StyleParam::Value value; REQUIRE(ctx.evalStyleFn("fn", StyleParamKey::color, value) == true); REQUIRE(value.is<Color>() == true); REQUIRE(value.get<Color>().getInt() == 0xffff00ff); } } TEST_CASE( "Test evalStyleFn - StyleParamKey::width", "[Duktape][evalStyleFn]") { { Feature feat; feat.props.add("width", 2.0); StyleContext ctx; ctx.setFeature(feat); ctx.addFunction("fn", R"(function () { return feature.width * 2.3; })"); StyleParam::Value value; REQUIRE(ctx.evalStyleFn("fn", StyleParamKey::width, value) == true); REQUIRE(value.is<float>() == true); REQUIRE(value.get<float>() == 4.6f); } } TEST_CASE( "Test evalFilter - Init filter function from yaml", "[Duktape][evalFilter]") { { Scene scene; YAML::Node n0 = YAML::Load(R"(filter: function() { return feature.sort_key == 2; })"); YAML::Node n1 = YAML::Load(R"(filter: function() { return feature.name == 'test'; })"); Filter filter0 = sceneLoader.generateFilter(n0["filter"], scene); Filter filter1 = sceneLoader.generateFilter(n1["filter"], scene); REQUIRE(scene.functions().size() == 2); REQUIRE(filter0.type == FilterType::function); REQUIRE(filter1.type == FilterType::function); StyleContext ctx; ctx.initFunctions(scene); Feature feat1; feat1.props.add("sort_key", 2); feat1.props.add("name", "test"); ctx.setFeature(feat1); // NB: feature parameter is ignored for Function evaluation REQUIRE(filter0.eval(feat1, ctx) == true); REQUIRE(filter1.eval(feat1, ctx) == true); // This is what happens in the above 'eval' internally REQUIRE(ctx.evalFilter(filter0.data.get<Filter::Function>().id) == true); REQUIRE(ctx.evalFilter(filter1.data.get<Filter::Function>().id) == true); // ... Also check that setFeature updates the ctx Feature feat2; feat2.props.add("name", "nope"); ctx.setFeature(feat2); REQUIRE(filter0.eval(feat2, ctx) == false); REQUIRE(filter1.eval(feat2, ctx) == false); REQUIRE(ctx.evalFilter(filter0.data.get<Filter::Function>().id) == false); REQUIRE(ctx.evalFilter(filter1.data.get<Filter::Function>().id) == false); } } TEST_CASE( "Test evalStyle - Init StyleParam function from yaml", "[Duktape][evalStyle]") { { Scene scene; YAML::Node n0 = YAML::Load(R"( draw: color: function() { return '#ffff00ff'; } width: function() { return 2; } cap: function() { return 'round'; } )"); std::vector<StyleParam> styles(sceneLoader.parseStyleParams(n0["draw"], scene)); REQUIRE(scene.functions().size() == 3); // for (auto& str : scene.functions()) { // logMsg("F: '%s'\n", str.c_str()); // } StyleContext ctx; ctx.initFunctions(scene); for (auto& style : styles) { //logMsg("S: %d - '%s' %d\n", style.key, style.toString().c_str(), style.function); if (style.key == StyleParamKey::color) { StyleParam::Value value; REQUIRE(ctx.evalStyle(style.function, style.key, value) == true); REQUIRE(value.is<Color>() == true); REQUIRE(value.get<Color>().getInt() == 0xffff00ff); } else if (style.key == StyleParamKey::width) { StyleParam::Value value; REQUIRE(ctx.evalStyle(style.function, style.key, value) == true); REQUIRE(value.is<float>() == true); REQUIRE(value.get<float>() == 2); } else if (style.key == StyleParamKey::cap) { StyleParam::Value value; REQUIRE(ctx.evalStyle(style.function, style.key, value) == true); REQUIRE(value.is<CapTypes>() == true); REQUIRE(value.get<CapTypes>() == CapTypes::round); } } } } <commit_msg>remove unnecessary parentheses<commit_after>#define CATCH_CONFIG_MAIN #include "catch.hpp" #include "data/filters.h" #include "yaml-cpp/yaml.h" #include "scene/sceneLoader.h" #include "scene/scene.h" #include "platform.h" using namespace Tangram; SceneLoader sceneLoader; TEST_CASE( "", "[Duktape][init]") { StyleContext(); } TEST_CASE( "Test filter without feature being set", "[Duktape][evalFilterFn]") { StyleContext ctx; ctx.addFunction("fn", R"(function() { return feature.name == undefined; })"); ctx.addAccessor("name"); REQUIRE(ctx.evalFilterFn("fn") == true); ctx.addFunction("fn2", R"(function() { return feature.name == ''; })"); REQUIRE(ctx.evalFilterFn("fn2") == false); } TEST_CASE( "Test evalFilterFn with feature", "[Duktape][evalFilterFn]") { Feature feature; feature.props.add("a", "A"); feature.props.add("b", "B"); feature.props.add("n", 42); StyleContext ctx; ctx.setFeature(feature); ctx.addFunction("fn_a", R"(function() { return feature.a == 'A' })"); REQUIRE(ctx.evalFilterFn("fn_a") == true); ctx.addFunction("fn_b", R"(function() { return feature.b == 'B' })"); REQUIRE(ctx.evalFilterFn("fn_b") == true); ctx.addFunction("fn_n", R"(function() { return feature.n == 42 })"); REQUIRE(ctx.evalFilterFn("fn_n") == true); ctx.addFunction("fn_n2", R"(function() { return feature.n == 43 })"); REQUIRE(ctx.evalFilterFn("fn_n2") == false); // OK? ctx.addFunction("fn_n3", R"(function() { return feature.n == '42' })"); REQUIRE(ctx.evalFilterFn("fn_n3") == true); } TEST_CASE( "Test evalFilterFn with feature and globals", "[Duktape][evalFilterFn]") { Feature feature; feature.props.add("scalerank", 2); StyleContext ctx; ctx.setFeature(feature); ctx.setGlobal("$zoom", 5); ctx.addFunction("fn", R"(function() { return (feature.scalerank * .5) <= ($zoom - 4); })"); REQUIRE(ctx.evalFilterFn("fn") == true); ctx.setGlobal("$zoom", 4); REQUIRE(ctx.evalFilterFn("fn") == false); } TEST_CASE( "Test evalFilterFn with different features", "[Duktape][evalFilterFn]") { StyleContext ctx; ctx.addFunction("fn", R"(function() { return feature.scalerank == 2; })"); Feature feat1; feat1.props.add("scalerank", 2); ctx.setFeature(feat1); REQUIRE(ctx.evalFilterFn("fn") == true); Feature feat2; ctx.setFeature(feat2); REQUIRE(ctx.evalFilterFn("fn") == false); ctx.setFeature(feat1); REQUIRE(ctx.evalFilterFn("fn") == true); } TEST_CASE( "Test numeric global", "[Duktape][setGlobal]") { StyleContext ctx; ctx.setGlobal("$zoom", 10); ctx.addFunction("fn", R"(function() { return $zoom == 10 })"); REQUIRE(ctx.evalFilterFn("fn") == true); ctx.setGlobal("$zoom", 0); REQUIRE(ctx.evalFilterFn("fn") == false); } TEST_CASE( "Test string global", "[Duktape][setGlobal]") { StyleContext ctx; ctx.setGlobal("$layer", "test"); ctx.addFunction("fn", R"(function() { return $layer == 'test' })"); REQUIRE(ctx.evalFilterFn("fn") == true); ctx.setGlobal("$layer", "none"); REQUIRE(ctx.evalFilterFn("fn") == false); } TEST_CASE( "Test evalStyleFn - StyleParamKey::order", "[Duktape][evalStyleFn]") { Feature feat; feat.props.add("sort_key", 2); StyleContext ctx; ctx.setFeature(feat); ctx.addFunction("fn", R"(function () { return feature.sort_key + 5 })"); StyleParam::Value value; REQUIRE(ctx.evalStyleFn("fn", StyleParamKey::order, value) == true); REQUIRE(value.is<int32_t>() == true); REQUIRE(value.get<int32_t>() == 7); } TEST_CASE( "Test evalStyleFn - StyleParamKey::color", "[Duktape][evalStyleFn]") { Feature feat; feat.props.add("sort_key", 2); StyleContext ctx; ctx.setFeature(feat); ctx.addFunction("fn", R"(function () { return '#f0f' })"); StyleParam::Value value; REQUIRE(ctx.evalStyleFn("fn", StyleParamKey::color, value) == true); REQUIRE(value.is<uint32_t>() == true); REQUIRE(value.get<uint32_t>() == 0xffff00ff); } TEST_CASE( "Test evalStyleFn - StyleParamKey::width", "[Duktape][evalStyleFn]") { Feature feat; feat.props.add("width", 2.0); StyleContext ctx; ctx.setFeature(feat); ctx.addFunction("fn", R"(function () { return feature.width * 2.3; })"); StyleParam::Value value; REQUIRE(ctx.evalStyleFn("fn", StyleParamKey::width, value) == true); REQUIRE(value.is<float>() == true); REQUIRE(value.get<float>() == 4.6f); } TEST_CASE( "Test evalFilter - Init filter function from yaml", "[Duktape][evalFilter]") { Scene scene; YAML::Node n0 = YAML::Load(R"(filter: function() { return feature.sort_key == 2; })"); YAML::Node n1 = YAML::Load(R"(filter: function() { return feature.name == 'test'; })"); Filter filter0 = sceneLoader.generateFilter(n0["filter"], scene); Filter filter1 = sceneLoader.generateFilter(n1["filter"], scene); REQUIRE(scene.functions().size() == 2); REQUIRE(filter0.type == FilterType::function); REQUIRE(filter1.type == FilterType::function); StyleContext ctx; ctx.initFunctions(scene); Feature feat1; feat1.props.add("sort_key", 2); feat1.props.add("name", "test"); ctx.setFeature(feat1); // NB: feature parameter is ignored for Function evaluation REQUIRE(filter0.eval(feat1, ctx) == true); REQUIRE(filter1.eval(feat1, ctx) == true); // This is what happens in the above 'eval' internally REQUIRE(ctx.evalFilter(filter0.data.get<Filter::Function>().id) == true); REQUIRE(ctx.evalFilter(filter1.data.get<Filter::Function>().id) == true); // ... Also check that setFeature updates the ctx Feature feat2; feat2.props.add("name", "nope"); ctx.setFeature(feat2); REQUIRE(filter0.eval(feat2, ctx) == false); REQUIRE(filter1.eval(feat2, ctx) == false); REQUIRE(ctx.evalFilter(filter0.data.get<Filter::Function>().id) == false); REQUIRE(ctx.evalFilter(filter1.data.get<Filter::Function>().id) == false); } TEST_CASE( "Test evalStyle - Init StyleParam function from yaml", "[Duktape][evalStyle]") { Scene scene; YAML::Node n0 = YAML::Load(R"( draw: color: function() { return '#ffff00ff'; } width: function() { return 2; } cap: function() { return 'round'; } )"); std::vector<StyleParam> styles(sceneLoader.parseStyleParams(n0["draw"], scene)); REQUIRE(scene.functions().size() == 3); // for (auto& str : scene.functions()) { // logMsg("F: '%s'\n", str.c_str()); // } StyleContext ctx; ctx.initFunctions(scene); for (auto& style : styles) { //logMsg("S: %d - '%s' %d\n", style.key, style.toString().c_str(), style.function); if (style.key == StyleParamKey::color) { StyleParam::Value value; REQUIRE(ctx.evalStyle(style.function, style.key, value) == true); REQUIRE(value.is<uint32_t>() == true); REQUIRE(value.get<uint32_t>() == 0xffff00ff); } else if (style.key == StyleParamKey::width) { StyleParam::Value value; REQUIRE(ctx.evalStyle(style.function, style.key, value) == true); REQUIRE(value.is<float>() == true); REQUIRE(value.get<float>() == 2); } else if (style.key == StyleParamKey::cap) { StyleParam::Value value; REQUIRE(ctx.evalStyle(style.function, style.key, value) == true); REQUIRE(value.is<CapTypes>() == true); REQUIRE(value.get<CapTypes>() == CapTypes::round); } else { REQUIRE(true == false); } } } <|endoftext|>
<commit_before>/* Optimal Read Normalization Algorithm: Developed by : Dilip A Durai and Marcel H Schulz */ //File last modified 28/11/2016 #include <gatb/gatb_core.hpp> #include <iostream> #include <string.h> typedef Kmer<>::Type bloom; int main (int argc, char* argv[]) { try { //Variables required by ORNA int count=0; int t=atoi(argv[3]); int kmer = atoi(argv[4]); const char* filename = argv[1]; const char* out_file= argv[2]; //Multithreading variables test (last modified 23/11/2016) auto nbCores = atoi(argv[5]); Dispatcher dispatcher (nbCores); ISynchronizer* synchro = System::thread().newSynchronizer(); //Locking a section //Variables required for GATB IBank* bank = Bank::open (filename); ProgressIterator<Sequence> itSeq (*bank); IBank* outBank = new BankFasta (out_file); //Creating a graph and an iterator. from the parameters. The threshold value is kept as the minimum abundance parameter of the graph. kmer size is the actual kmer+1 Graph graph = Graph::create (Bank::open(argv[1]), "-kmer-size %s -abundance-min 2", argv[4]); Graph::Iterator<Node> it = graph.iterator(); int node_size= it.size(); int *counter = new int[node_size]; int *flg= new int[node_size]; //Initializing the counter for each node in the de Bruijn graph for(int i=0;i<node_size;i++) { counter[i]=0; flg[i]=0; } //Iterating over sequences dispatcher.iterate (itSeq, [&] (Sequence& seq) //for (itSeq.first(); !itSeq.isDone(); itSeq.next()) { auto acceptance=0; int stretch=0; int position = 0; int numerror=0; //itKmer.setData (itSeq->getData()); int length = seq.getDataSize(); int startkmer = 0; int endkmer = 0; int flag=1; Kmer<>::ModelCanonical model (kmer); Kmer<>::ModelCanonical::Iterator itKmer (model); itKmer.setData (seq.getData()); //Error Correction for(itKmer.first(); !itKmer.isDone(); itKmer.next()) { std::string ts = model.toString (itKmer->value()); const char* tsq = ts.c_str(); Node tnode = graph.buildNode(tsq); if(!(graph.contains(tnode)) && (startkmer==1)) { stretch+=1; position+=1; } else { if(position==0) { startkmer=1; } if(position == (length-kmer)) { endkmer=1; } if(stretch==kmer) { if((startkmer==1)){ numerror=1; } } stretch=0; position+=1; } } if(numerror==1) { if(endkmer==1) { flag=0; } } if(flag==1){ //Iterating over kmers in each sequence for (itKmer.first(); !itKmer.isDone(); itKmer.next()) { std::string s = model.toString (itKmer->value()); const char* sq = s.c_str(); Node node = graph.buildNode(sq); //Checking whether the node exists. if(!(graph.contains(node))) { __sync_fetch_and_add (&acceptance, 1); } else { auto index = graph.nodeMPHFIndex(node); if(counter[index] < t) { //LocalSynchronizer sync (synchro); __sync_fetch_and_add (&acceptance, 1); __sync_fetch_and_add (&counter[index], 1); } } } } if(acceptance > 0) { synchro->lock(); outBank->insert(seq); count++; synchro->unlock(); } }); std::cout << count << std::endl; //Free the memory delete [] counter; delete [] flg; bank->flush(); outBank->flush(); } catch (Exception& e) { std::cerr << "EXCEPTION: " << e.getMessage() << std::endl; } return EXIT_SUCCESS; } <commit_msg>Error_Correction_Modified<commit_after>/* Optimal Read Normalization Algorithm: Developed by : Dilip A Durai and Marcel H Schulz */ //File last modified 28/11/2016 #include <gatb/gatb_core.hpp> #include <iostream> #include <string.h> typedef Kmer<>::Type bloom; int main (int argc, char* argv[]) { try { //Variables required by ORNA int count=0; int t=atoi(argv[3]); int kmer = atoi(argv[4]); const char* filename = argv[1]; const char* out_file= argv[2]; //Multithreading variables test (last modified 23/11/2016) auto nbCores = atoi(argv[5]); Dispatcher dispatcher (nbCores); ISynchronizer* synchro = System::thread().newSynchronizer(); //Locking a section //Variables required for GATB IBank* bank = Bank::open (filename); ProgressIterator<Sequence> itSeq (*bank); IBank* outBank = new BankFasta (out_file); //Creating a graph and an iterator. from the parameters. The threshold value is kept as the minimum abundance parameter of the graph. kmer size is the actual kmer+1 Graph graph = Graph::create (Bank::open(argv[1]), "-kmer-size %s -abundance-min 3", argv[4]); Graph::Iterator<Node> it = graph.iterator(); int node_size= it.size(); int *counter = new int[node_size]; int *flg= new int[node_size]; //Initializing the counter for each node in the de Bruijn graph for(int i=0;i<node_size;i++) { counter[i]=0; flg[i]=0; } //Iterating over sequences dispatcher.iterate (itSeq, [&] (Sequence& seq) { auto acceptance=0; int stretch=0; int position = 0; int numerror=0; int length = seq.getDataSize(); int startkmer = 0; int endkmer = 0; int flag=1; Kmer<>::ModelCanonical model (kmer); Kmer<>::ModelCanonical::Iterator itKmer (model); itKmer.setData (seq.getData()); //Error Correction for(itKmer.first(); !itKmer.isDone(); itKmer.next()) { std::string ts = model.toString (itKmer->value()); const char* tsq = ts.c_str(); Node tnode = graph.buildNode(tsq); if(!(graph.contains(tnode)) && (startkmer==1)) { stretch+=1; position+=1; } else { if(position==0) { startkmer=1; } if(position == (length-kmer)) { endkmer=1; } if(stretch==kmer) { if((startkmer==1)){ numerror=1; } } stretch=0; position+=1; } } if(numerror==1) { if(endkmer==1) { flag=0; } } //checking the thresholding if(flag==1){ //Iterating over kmers in each sequence for (itKmer.first(); !itKmer.isDone(); itKmer.next()) { std::string s = model.toString (itKmer->value()); const char* sq = s.c_str(); Node node = graph.buildNode(sq); //Checking whether the node exists. if(!(graph.contains(node))) { __sync_fetch_and_add (&acceptance, 1); } else { auto index = graph.nodeMPHFIndex(node); if(counter[index] < t) { __sync_fetch_and_add (&acceptance, 1); __sync_fetch_and_add (&counter[index], 1); } } } } if(acceptance > 0) { synchro->lock(); outBank->insert(seq); count++; synchro->unlock(); } }); std::cout << count << std::endl; //Free the memory delete [] counter; delete [] flg; bank->flush(); outBank->flush(); } catch (Exception& e) { std::cerr << "EXCEPTION: " << e.getMessage() << std::endl; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/** * This file is part of the "FnordMetric" project * Copyright (c) 2014 Paul Asmuth, Google Inc. * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. 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 <string.h> #include "fnord-base/bufferutil.h" #include "fnord-base/exception.h" #include "fnord-base/inspect.h" #include "fnord-http/httpparser.h" namespace fnord { namespace http { const char HTTPParser::kContentLengthHeader[] = "Content-Length"; const char HTTPParser::kConnectionHeader[] = "Connection"; HTTPParser::HTTPParser( kParserMode mode, size_t buffer_size /* = kDefaultBufferSize */) : mode_(mode), on_method_cb_(nullptr), on_uri_cb_(nullptr), on_version_cb_(nullptr), on_status_code_cb_(nullptr), on_status_name_cb_(nullptr), on_header_cb_(nullptr), on_headers_complete_cb_(nullptr), on_body_chunk_cb_(nullptr), expect_body_(true), body_bytes_read_(0), body_bytes_expected_(0) { switch (mode) { case PARSE_HTTP_REQUEST: state_ = S_REQ_METHOD; break; case PARSE_HTTP_RESPONSE: state_ = S_RES_VERSION; break; } buf_.reserve(buffer_size); } HTTPParser::kParserState HTTPParser::state() const { return state_; } void HTTPParser::onMethod( std::function<void(HTTPMessage::kHTTPMethod)> callback) { on_method_cb_ = callback; } void HTTPParser::onURI( std::function<void(const char* data, size_t size)> callback) { on_uri_cb_ = callback; } void HTTPParser::onVersion( std::function<void(const char* data, size_t size)> callback) { on_version_cb_ = callback; } void HTTPParser::onStatusCode(std::function<void(int)> callback) { on_status_code_cb_ = callback; } void HTTPParser::onStatusName( std::function<void(const char* data, size_t size)> callback) { on_status_name_cb_ = callback; } void HTTPParser::onHeader(std::function<void( const char* key, size_t key_len, const char* val, size_t val_len)> callback) { on_header_cb_ = callback; } void HTTPParser::onHeadersComplete(std::function<void()> callback) { on_headers_complete_cb_ = callback; } void HTTPParser::onBodyChunk( std::function<void(const char* data, size_t size)> callback) { on_body_chunk_cb_ = callback; } void HTTPParser::parse(const char* data, size_t size) { const char* begin = data; const char* end = data + size; while (begin < end) { switch (state_) { case S_REQ_METHOD: parseMethod(&begin, end); break; case S_REQ_URI: parseURI(&begin, end); break; case S_REQ_VERSION: parseRequestVersion(&begin, end); break; case S_RES_VERSION: parseResponseVersion(&begin, end); break; case S_RES_STATUS_CODE: parseResponseStatusCode(&begin, end); break; case S_RES_STATUS_NAME: parseResponseStatusName(&begin, end); break; case S_HEADER: parseHeader(&begin, end); break; case S_DONE: if (mode_ == PARSE_HTTP_REQUEST) { RAISE(kParseError, "invalid trailing bytes"); } /* fallthrough */ case S_BODY: readBody(&begin, end); break; } } } void HTTPParser::eof() { switch (state_) { case S_REQ_METHOD: case S_REQ_URI: case S_REQ_VERSION: case S_RES_VERSION: case S_RES_STATUS_CODE: case S_RES_STATUS_NAME: case S_HEADER: case S_BODY: if (body_bytes_expected_ != -1 && body_bytes_read_ < body_bytes_expected_) { RAISE(kParseError, "unexpected end of file"); } else { state_ = S_DONE; } return; case S_DONE: return; } } void HTTPParser::parseMethod(const char** begin, const char* end) { if (readUntil(begin, end, ' ')) { state_ = S_REQ_URI; (*begin)++; if (on_method_cb_) { if (buf_ == "CONNECT") { on_method_cb_(HTTPMessage::M_CONNECT); buf_.clear(); return; } if (buf_ == "DELETE") { on_method_cb_(HTTPMessage::M_DELETE); buf_.clear(); return; } if (buf_ == "GET") { on_method_cb_(HTTPMessage::M_GET); buf_.clear(); return; } if (buf_ == "HEAD") { on_method_cb_(HTTPMessage::M_HEAD); buf_.clear(); return; } if (buf_ == "OPTIONS") { on_method_cb_(HTTPMessage::M_OPTIONS); buf_.clear(); return; } if (buf_ == "POST") { on_method_cb_(HTTPMessage::M_POST); buf_.clear(); return; } if (buf_ == "PUT") { on_method_cb_(HTTPMessage::M_PUT); buf_.clear(); return; } if (buf_ == "TRACE"){ on_method_cb_(HTTPMessage::M_TRACE); buf_.clear(); return; } RAISEF(kParseError, "Invalid HTTP method: $0", buf_.toString()); } } if (buf_.size() > kMaxMethodSize) { RAISEF(kParseError, "HTTP method too large, max is $0", kMaxMethodSize); } } void HTTPParser::parseURI(const char** begin, const char* end) { if (readUntil(begin, end, ' ')) { if (on_uri_cb_) { on_uri_cb_((char *) buf_.data(), buf_.size()); } buf_.clear(); state_ = S_REQ_VERSION; (*begin)++; return; } if (buf_.size() > kMaxURISize) { RAISEF(kParseError, "HTTP URI too large, max is $0", kMaxURISize); } } void HTTPParser::parseRequestVersion(const char** begin, const char* end) { if (readUntil(begin, end, '\n')) { BufferUtil::stripTrailingBytes(&buf_, '\r'); if (on_version_cb_) { on_version_cb_((char *) buf_.data(), buf_.size()); } buf_.clear(); state_ = S_HEADER; (*begin)++; return; } if (buf_.size() > kMaxVersionSize) { RAISEF(kParseError, "HTTP version too large, max is $0", kMaxVersionSize); } } void HTTPParser::parseResponseVersion(const char** begin, const char* end) { if (readUntil(begin, end, ' ')) { if (strncasecmp((char *) buf_.data(), "HTTP/1.0", buf_.size()) == 0) { body_bytes_expected_ = -1; } if (on_version_cb_) { on_version_cb_((char *) buf_.data(), buf_.size()); } buf_.clear(); state_ = S_RES_STATUS_CODE; (*begin)++; return; } if (buf_.size() > kMaxVersionSize) { RAISEF(kParseError, "HTTP version too large, max is $0", kMaxVersionSize); } } void HTTPParser::parseResponseStatusCode(const char** begin, const char* end) { if (readUntil(begin, end, ' ')) { std::string status_code_str((char *) buf_.data(), buf_.size()); int status_code = 1; try { status_code = std::stoi(status_code_str); } catch (const std::exception& e) { RAISEF(kParseError, "invalid http status code: $0", status_code_str); } if (on_status_code_cb_) { on_status_code_cb_(status_code); } buf_.clear(); state_ = S_RES_STATUS_NAME; (*begin)++; return; } if (buf_.size() > kMaxURISize) { RAISEF(kParseError, "HTTP URI too large, max is $0", kMaxURISize); } } void HTTPParser::parseResponseStatusName(const char** begin, const char* end) { if (readUntil(begin, end, '\n')) { BufferUtil::stripTrailingBytes(&buf_, '\r'); if (on_status_name_cb_) { on_status_name_cb_((char *) buf_.data(), buf_.size()); } buf_.clear(); state_ = S_HEADER; (*begin)++; return; } if (buf_.size() > kMaxVersionSize) { RAISEF(kParseError, "HTTP version too large, max is $0", kMaxVersionSize); } } void HTTPParser::parseHeader(const char** begin, const char* end) { if (readUntil(begin, end, '\n')) { BufferUtil::stripTrailingBytes(&buf_, '\r'); if (buf_.size() > 0) { auto hkey = (char*) buf_.data(); auto hkey_len = buf_.find(':'); if (hkey_len == Buffer::npos) { RAISEF(kParseError, "invalid HTTP header line: $0", buf_.toString()); } auto hval = hkey + hkey_len + 1; auto hval_len = buf_.size() - hkey_len - 1; while (hval_len > 0 && *hval == ' ') { hval++; hval_len--; } processHeader(hkey, hkey_len, hval, hval_len); buf_.clear(); state_ = S_HEADER; } else { if (body_bytes_expected_ == 0) { state_ = S_DONE; } else { state_ = S_BODY; } if (on_headers_complete_cb_) { on_headers_complete_cb_(); } } (*begin)++; return; } if (buf_.size() > kMaxHeaderSize) { RAISEF(kParseError, "HTTP header too large, max is $0", kMaxHeaderSize); } } void HTTPParser::processHeader( const char* key, size_t key_len, const char* val, size_t val_len) { if (expect_body_ && key_len == strlen(kContentLengthHeader) && strncasecmp(key, kContentLengthHeader, key_len) == 0) { std::string content_length_str(val, val_len); try { body_bytes_expected_ = std::stoul(content_length_str); } catch (const std::exception& e) { RAISEF(kParseError, "invalid content length: $0", content_length_str); } } if (expect_body_ && key_len == strlen(kConnectionHeader) && strncasecmp(key, kConnectionHeader, key_len) == 0 && val_len == strlen("Close") && strncasecmp(val, "Close", key_len) == 0) { body_bytes_expected_ = -1; } if (on_header_cb_) { on_header_cb_(key, key_len, val, val_len); } } void HTTPParser::readBody(const char** begin, const char* end) { body_bytes_read_ += end - *begin; if (body_bytes_read_ == body_bytes_expected_) { state_ = HTTPParser::S_DONE; } //if ((body_bytes_read_ > body_bytes_expected_) && // !(body_bytes_expected_ == 0 && mode_ == PARSE_HTTP_RESPONSE)) { // RAISE(kParseError, "invalid trailing body bytes"); //} if (on_body_chunk_cb_) { on_body_chunk_cb_(*begin, end - *begin); } *begin = end; } bool HTTPParser::readUntil(const char** begin, const char* end, char search) { auto cur = *begin; for (; cur < end && *cur != search; ++cur); buf_.append(*begin, (cur - *begin)); *begin = cur; return cur != end && *cur == search; } void HTTPParser::reset() { switch (mode_) { case PARSE_HTTP_REQUEST: state_ = S_REQ_METHOD; break; case PARSE_HTTP_RESPONSE: state_ = S_RES_VERSION; break; } buf_.clear(); body_bytes_read_ = 0; body_bytes_expected_ = 0; expect_body_ = true; } void HTTPParser::ignoreBody() { expect_body_ = false; } } } <commit_msg>fixes<commit_after>/** * This file is part of the "FnordMetric" project * Copyright (c) 2014 Paul Asmuth, Google Inc. * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. 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 <string.h> #include "fnord-base/bufferutil.h" #include "fnord-base/exception.h" #include "fnord-base/inspect.h" #include "fnord-http/httpparser.h" namespace fnord { namespace http { const char HTTPParser::kContentLengthHeader[] = "Content-Length"; const char HTTPParser::kConnectionHeader[] = "Connection"; HTTPParser::HTTPParser( kParserMode mode, size_t buffer_size /* = kDefaultBufferSize */) : mode_(mode), on_method_cb_(nullptr), on_uri_cb_(nullptr), on_version_cb_(nullptr), on_status_code_cb_(nullptr), on_status_name_cb_(nullptr), on_header_cb_(nullptr), on_headers_complete_cb_(nullptr), on_body_chunk_cb_(nullptr), expect_body_(true), body_bytes_read_(0), body_bytes_expected_(0) { switch (mode) { case PARSE_HTTP_REQUEST: state_ = S_REQ_METHOD; break; case PARSE_HTTP_RESPONSE: state_ = S_RES_VERSION; break; } buf_.reserve(buffer_size); } HTTPParser::kParserState HTTPParser::state() const { return state_; } void HTTPParser::onMethod( std::function<void(HTTPMessage::kHTTPMethod)> callback) { on_method_cb_ = callback; } void HTTPParser::onURI( std::function<void(const char* data, size_t size)> callback) { on_uri_cb_ = callback; } void HTTPParser::onVersion( std::function<void(const char* data, size_t size)> callback) { on_version_cb_ = callback; } void HTTPParser::onStatusCode(std::function<void(int)> callback) { on_status_code_cb_ = callback; } void HTTPParser::onStatusName( std::function<void(const char* data, size_t size)> callback) { on_status_name_cb_ = callback; } void HTTPParser::onHeader(std::function<void( const char* key, size_t key_len, const char* val, size_t val_len)> callback) { on_header_cb_ = callback; } void HTTPParser::onHeadersComplete(std::function<void()> callback) { on_headers_complete_cb_ = callback; } void HTTPParser::onBodyChunk( std::function<void(const char* data, size_t size)> callback) { on_body_chunk_cb_ = callback; } void HTTPParser::parse(const char* data, size_t size) { const char* begin = data; const char* end = data + size; while (begin < end) { switch (state_) { case S_REQ_METHOD: parseMethod(&begin, end); break; case S_REQ_URI: parseURI(&begin, end); break; case S_REQ_VERSION: parseRequestVersion(&begin, end); break; case S_RES_VERSION: parseResponseVersion(&begin, end); break; case S_RES_STATUS_CODE: parseResponseStatusCode(&begin, end); break; case S_RES_STATUS_NAME: parseResponseStatusName(&begin, end); break; case S_HEADER: parseHeader(&begin, end); break; case S_DONE: if (mode_ == PARSE_HTTP_REQUEST) { RAISE(kParseError, "invalid trailing bytes"); } /* fallthrough */ case S_BODY: readBody(&begin, end); break; } } } void HTTPParser::eof() { switch (state_) { case S_REQ_METHOD: case S_REQ_URI: case S_REQ_VERSION: case S_RES_VERSION: case S_RES_STATUS_CODE: case S_RES_STATUS_NAME: case S_HEADER: case S_BODY: if (body_bytes_expected_ != -1 && body_bytes_read_ < body_bytes_expected_) { RAISE(kParseError, "unexpected end of file"); } else { state_ = S_DONE; } return; case S_DONE: return; } } void HTTPParser::parseMethod(const char** begin, const char* end) { if (readUntil(begin, end, ' ')) { state_ = S_REQ_URI; (*begin)++; if (on_method_cb_) { if (buf_ == "CONNECT") { on_method_cb_(HTTPMessage::M_CONNECT); buf_.clear(); return; } if (buf_ == "DELETE") { on_method_cb_(HTTPMessage::M_DELETE); buf_.clear(); return; } if (buf_ == "GET") { on_method_cb_(HTTPMessage::M_GET); buf_.clear(); return; } if (buf_ == "HEAD") { on_method_cb_(HTTPMessage::M_HEAD); buf_.clear(); return; } if (buf_ == "OPTIONS") { on_method_cb_(HTTPMessage::M_OPTIONS); buf_.clear(); return; } if (buf_ == "POST") { on_method_cb_(HTTPMessage::M_POST); buf_.clear(); return; } if (buf_ == "PUT") { on_method_cb_(HTTPMessage::M_PUT); buf_.clear(); return; } if (buf_ == "TRACE"){ on_method_cb_(HTTPMessage::M_TRACE); buf_.clear(); return; } RAISEF(kParseError, "Invalid HTTP method: $0", buf_.toString()); } } if (buf_.size() > kMaxMethodSize) { RAISEF(kParseError, "HTTP method too large, max is $0", kMaxMethodSize); } } void HTTPParser::parseURI(const char** begin, const char* end) { if (readUntil(begin, end, ' ')) { if (on_uri_cb_) { on_uri_cb_((char *) buf_.data(), buf_.size()); } buf_.clear(); state_ = S_REQ_VERSION; (*begin)++; return; } if (buf_.size() > kMaxURISize) { RAISEF(kParseError, "HTTP URI too large, max is $0", kMaxURISize); } } void HTTPParser::parseRequestVersion(const char** begin, const char* end) { if (readUntil(begin, end, '\n')) { BufferUtil::stripTrailingBytes(&buf_, '\r'); if (on_version_cb_) { on_version_cb_((char *) buf_.data(), buf_.size()); } buf_.clear(); state_ = S_HEADER; (*begin)++; return; } if (buf_.size() > kMaxVersionSize) { RAISEF(kParseError, "HTTP version too large, max is $0", kMaxVersionSize); } } void HTTPParser::parseResponseVersion(const char** begin, const char* end) { if (readUntil(begin, end, ' ')) { if (strncasecmp((char *) buf_.data(), "HTTP/1.0", buf_.size()) == 0) { body_bytes_expected_ = -1; } if (on_version_cb_) { on_version_cb_((char *) buf_.data(), buf_.size()); } buf_.clear(); state_ = S_RES_STATUS_CODE; (*begin)++; return; } if (buf_.size() > kMaxVersionSize) { RAISEF(kParseError, "HTTP version too large, max is $0", kMaxVersionSize); } } void HTTPParser::parseResponseStatusCode(const char** begin, const char* end) { if (readUntil(begin, end, ' ')) { std::string status_code_str((char *) buf_.data(), buf_.size()); int status_code = 1; try { status_code = std::stoi(status_code_str); } catch (const std::exception& e) { RAISEF(kParseError, "invalid http status code: $0", status_code_str); } if (on_status_code_cb_) { on_status_code_cb_(status_code); } buf_.clear(); state_ = S_RES_STATUS_NAME; (*begin)++; return; } if (buf_.size() > kMaxURISize) { RAISEF(kParseError, "HTTP URI too large, max is $0", kMaxURISize); } } void HTTPParser::parseResponseStatusName(const char** begin, const char* end) { if (readUntil(begin, end, '\n')) { BufferUtil::stripTrailingBytes(&buf_, '\r'); if (on_status_name_cb_) { on_status_name_cb_((char *) buf_.data(), buf_.size()); } buf_.clear(); state_ = S_HEADER; (*begin)++; return; } if (buf_.size() > kMaxVersionSize) { RAISEF(kParseError, "HTTP version too large, max is $0", kMaxVersionSize); } } void HTTPParser::parseHeader(const char** begin, const char* end) { if (readUntil(begin, end, '\n')) { BufferUtil::stripTrailingBytes(&buf_, '\r'); if (buf_.size() > 0) { auto hkey = (char*) buf_.data(); auto hkey_len = buf_.find(':'); if (hkey_len == Buffer::npos) { RAISEF(kParseError, "invalid HTTP header line: $0", buf_.toString()); } auto hval = hkey + hkey_len + 1; auto hval_len = buf_.size() - hkey_len - 1; while (hval_len > 0 && *hval == ' ') { hval++; hval_len--; } processHeader(hkey, hkey_len, hval, hval_len); buf_.clear(); state_ = S_HEADER; } else { if (body_bytes_expected_ == 0) { state_ = S_DONE; } else { state_ = S_BODY; } if (on_headers_complete_cb_) { on_headers_complete_cb_(); } } (*begin)++; return; } if (buf_.size() > kMaxHeaderSize) { RAISEF(kParseError, "HTTP header too large, max is $0", kMaxHeaderSize); } } void HTTPParser::processHeader( const char* key, size_t key_len, const char* val, size_t val_len) { if (expect_body_ && key_len == strlen(kContentLengthHeader) && strncasecmp(key, kContentLengthHeader, key_len) == 0) { std::string content_length_str(val, val_len); try { body_bytes_expected_ = std::stoul(content_length_str); } catch (const std::exception& e) { RAISEF(kParseError, "invalid content length: $0", content_length_str); } } if (expect_body_ && key_len == strlen(kConnectionHeader) && strncasecmp(key, kConnectionHeader, key_len) == 0 && val_len == strlen("Close") && strncasecmp(val, "Close", val_len) == 0) { body_bytes_expected_ = -1; } if (on_header_cb_) { on_header_cb_(key, key_len, val, val_len); } } void HTTPParser::readBody(const char** begin, const char* end) { body_bytes_read_ += end - *begin; if (body_bytes_read_ == body_bytes_expected_) { state_ = HTTPParser::S_DONE; } //if ((body_bytes_read_ > body_bytes_expected_) && // !(body_bytes_expected_ == 0 && mode_ == PARSE_HTTP_RESPONSE)) { // RAISE(kParseError, "invalid trailing body bytes"); //} if (on_body_chunk_cb_) { on_body_chunk_cb_(*begin, end - *begin); } *begin = end; } bool HTTPParser::readUntil(const char** begin, const char* end, char search) { auto cur = *begin; for (; cur < end && *cur != search; ++cur); buf_.append(*begin, (cur - *begin)); *begin = cur; return cur != end && *cur == search; } void HTTPParser::reset() { switch (mode_) { case PARSE_HTTP_REQUEST: state_ = S_REQ_METHOD; break; case PARSE_HTTP_RESPONSE: state_ = S_RES_VERSION; break; } buf_.clear(); body_bytes_read_ = 0; body_bytes_expected_ = 0; expect_body_ = true; } void HTTPParser::ignoreBody() { expect_body_ = false; } } } <|endoftext|>
<commit_before>#include "GLPKInterface.h" #if HAVE_GLPK #include <utils.h> #include <utils/SignalHandler.h> #include <signal.h> #include <iostream> #include <stdexcept> extern "C" { #include <glpk.h> } using namespace Optimization; using namespace std; #if GLP_MAJOR_VERSION < 4 || GLP_MINOR_VERSION < 40 #error "Require GLPK 4.40 or above" #endif const static Real kZeroTol = 1e-6; GLPKInterface::GLPKInterface() :lp(NULL) {} GLPKInterface::~GLPKInterface() { SafeDeleteProc(lp,glp_delete_prob); } inline int BoundType(Real low,Real high) { if(IsInf(low)==-1) { if(IsInf(high) == 1) return GLP_FR; return GLP_UP; } else if(IsInf(high) == 1) { return GLP_LO; } else { if(low==high) return GLP_FX; else return GLP_DB; } } int BoundTypeToGLP(LinearProgram::BoundType b) { switch(b) { case LinearProgram::Free: return GLP_FR; case LinearProgram::LowerBound: return GLP_LO; case LinearProgram::UpperBound: return GLP_UP; case LinearProgram::Bounded: return GLP_DB; case LinearProgram::Fixed: return GLP_FX; default: abort(); return GLP_FR; } } void GLPKInterface::Set(const LinearProgram& LP) { SafeDeleteProc(lp,glp_delete_prob); lp = glp_create_prob(); if(LP.minimize) glp_set_obj_dir(lp,GLP_MIN); else glp_set_obj_dir(lp,GLP_MAX); glp_add_rows(lp,LP.A.m); for(int i=0;i<LP.A.m;i++) { glp_set_row_bnds(lp,i+1,BoundTypeToGLP(LP.ConstraintType(i)),LP.q(i),LP.p(i)); } glp_add_cols(lp,LP.A.n); for(int i=0;i<LP.A.n;i++) { glp_set_col_bnds(lp,i+1,BoundTypeToGLP(LP.VariableType(i)),LP.l(i),LP.u(i)); } for(int i=0;i<LP.A.n;i++) glp_set_obj_coef(lp,i+1,LP.c(i)); vector<int> itemp(LP.A.n+1); dVector temp(LP.A.n+1); for(int i=0;i<LP.A.m;i++) { //pick nonzero entries int nnz=0; for(int j=0;j<LP.A.n;j++) { if(!FuzzyZero(LP.A(i,j),kZeroTol)) { itemp[nnz+1] = j+1; temp(nnz+1) = LP.A(i,j); nnz++; } } glp_set_mat_row(lp,i+1,nnz,&itemp[0],temp); } } void GLPKInterface::Set(const LinearProgram_Sparse& LP) { SafeDeleteProc(lp,glp_delete_prob); lp = glp_create_prob(); if(LP.minimize) glp_set_obj_dir(lp,GLP_MIN); else glp_set_obj_dir(lp,GLP_MAX); glp_add_rows(lp,LP.A.m); for(int i=0;i<LP.A.m;i++) { glp_set_row_bnds(lp,i+1,BoundTypeToGLP(LP.ConstraintType(i)),LP.q(i),LP.p(i)); } glp_add_cols(lp,LP.A.n); for(int i=0;i<LP.A.n;i++) { glp_set_col_bnds(lp,i+1,BoundTypeToGLP(LP.VariableType(i)),LP.l(i),LP.u(i)); } for(int i=0;i<LP.A.n;i++) glp_set_obj_coef(lp,i+1,LP.c(i)); vector<int> itemp(LP.A.n+1); dVector temp(LP.A.n+1); for(int i=0;i<LP.A.m;i++) { //pick nonzero entries int nnz=0; for(SparseMatrix::RowT::const_iterator j=LP.A.rows[i].begin();j!=LP.A.rows[i].end();j++) { if(!FuzzyZero(j->second,kZeroTol)) { itemp[nnz+1] = j->first+1; temp(nnz+1) = j->second; nnz++; } } glp_set_mat_row(lp,i+1,nnz,&itemp[0],temp); } } void GLPKInterface::Clear() { SafeDeleteProc(lp,glp_delete_prob); } void GLPKInterface::Create(int m,int n) { SafeDeleteProc(lp,glp_delete_prob); lp = glp_create_prob(); glp_add_rows(lp,m); glp_add_cols(lp,n); } void GLPKInterface::SetObjective(const Vector& obj,bool minimize) { for(int i=0;i<obj.n;i++) glp_set_obj_coef(lp,i+1,obj(i)); if(minimize) glp_set_obj_dir(lp,GLP_MIN); else glp_set_obj_dir(lp,GLP_MAX); } void GLPKInterface::SetRow(int i,const Vector& Ai) { vector<int> itemp(Ai.n+1); dVector temp(Ai.n+1); //pick nonzero entries int nnz=0; for(int j=0;j<Ai.n;j++) { if(!FuzzyZero(Ai(j),kZeroTol)) { itemp[nnz+1] = j+1; temp(nnz+1) = Ai(j); nnz++; } } glp_set_mat_row(lp,i+1,nnz,&itemp[0],temp); } void GLPKInterface::SetRowBounds(int i,Real low,Real high) { glp_set_row_bnds(lp,i+1,BoundType(low,high),low,high); } void GLPKInterface::SetVariableBounds(int j,Real low,Real high) { glp_set_col_bnds(lp,j+1,BoundType(low,high),low,high); } void GLPKInterface::SetRowBasic(int i) { glp_set_row_stat(lp,i+1,GLP_BS); } bool GLPKInterface::GetRowBasic(int i) { return glp_get_row_stat(lp,i+1)==GLP_BS; } double GLPKInterface::GetRowDual(int i){ return glp_get_row_dual(lp, i+1); } double GLPKInterface::GetVariableDual(int j){ return glp_get_col_dual(lp, j+1); } void GLPKInterface::SetRowNonBasic(int i,bool upper) { if(upper) glp_set_row_stat(lp,i+1,GLP_NU); else glp_set_row_stat(lp,i+1,GLP_NL); } void GLPKInterface::SetVariableBasic(int j) { glp_set_col_stat(lp,j+1,GLP_BS); } bool GLPKInterface::GetVariableBasic(int j) { return glp_get_col_stat(lp,j+1)==GLP_BS; } void GLPKInterface::SetVariableNonBasic(int j,bool upper) { if(upper) glp_set_col_stat(lp,j+1,GLP_NU); else glp_set_col_stat(lp,j+1,GLP_NL); } int my_gglp_fault_handler(void* info,const char* msg) { printf("GLPK error message %s\n",msg); //printf("GLPK fatal error %s\n",msg); //printf("jumping...\n"); //throw(std::runtime_error(msg)); /* printf("GLPK fatal error, dumping!\n"); GLP* lp=(GLP*)info; glp_write_cpxlp(lp,"temp_lp.txt"); */ return 0; } void my_gglp_fault_handler2(void* info) { printf("GLPK error, quitting\n"); } struct GLPKInterruptHandler : public SignalHandler { public: GLPKInterruptHandler(GLPKInterface* _glpk) :glpk(_glpk) {} virtual void OnRaise(int signum) { printf("Interrupt called during GLPK solve... possible infinite loop\n"); glp_prob* lp=glpk->lp; glp_write_lp(lp,NULL,"temp_lp.txt"); throw(std::runtime_error("Interrupt called during GLPK solve")); //exit(-1); } GLPKInterface* glpk; }; LinearProgram::Result GLPKInterface::Solve(Vector& xopt) { assert(lp != NULL); //glp_write_cpxlp(lp,"temp_lp.txt"); //glp_print_prob(lp,"temp_lp.txt"); #if GLP_MINOR_VERSION >= 43 glp_error_hook(my_gglp_fault_handler2,0); #endif glp_smcp params; glp_init_smcp(&params); params.msg_lev = GLP_MSG_ERR; params.presolve = GLP_OFF; GLPKInterruptHandler handler(this); handler.SetCurrent(SIGINT); //handler.SetCurrent(SIGABRT); int res; try { res=glp_simplex(lp,&params); } catch(const std::exception& e) { printf("GLPK internal error: "); printf(e.what()); return LinearProgram::Error; } catch (...) { printf("Unknown error occurred\n"); return LinearProgram::Error; } #if GLP_MINOR_VERSION >= 43 glp_error_hook(0,0); #endif handler.UnsetCurrent(SIGINT); switch(res) { case 0: break; case GLP_EFAIL: cout<<"Error in matrix construction!"<<endl; return LinearProgram::Error; case GLP_EOBJLL: cout<<"Objective reached lower limit!"<<endl; return LinearProgram::Error; case GLP_EOBJUL: cout<<"Objective reached upper limit!"<<endl; return LinearProgram::Error; case GLP_ENOPFS: cout<<"Linear program has no primary feasible solution!"<<endl; return LinearProgram::Infeasible; case GLP_ENODFS: cout<<"Linear program has no dual feasible solution!"<<endl; return LinearProgram::Infeasible; case GLP_EITLIM: cout<<"Max iterations reached!"<<endl; return LinearProgram::Error; case GLP_ETMLIM: cout<<"Time limit reached!"<<endl; return LinearProgram::Error; case GLP_ESING: cout<<"Singularity reached!"<<endl; return LinearProgram::Error; default: cout<<"Unknown error"<<endl; return LinearProgram::Error; } int stat=glp_get_status(lp); int n=glp_get_num_cols(lp); xopt.resize(n); for(int i=0;i<n;i++) xopt(i) = (Real)glp_get_col_prim(lp,i+1); switch(stat) { case GLP_OPT: case GLP_FEAS: return LinearProgram::Feasible; case GLP_INFEAS: case GLP_NOFEAS: return LinearProgram::Infeasible; case GLP_UNBND: return LinearProgram::Unbounded; case GLP_UNDEF: cout<<"Solution is undefined!"<<endl; return LinearProgram::Error; default: cout<<"Shouldn't get here!"<<endl; return LinearProgram::Error; } } bool GLPKInterface::Enabled() { return true; } #else using namespace Optimization; using namespace std; GLPKInterface::GLPKInterface() { } GLPKInterface::~GLPKInterface() { } void GLPKInterface::Set(const LinearProgram& LP) { cerr<<"Warning, GLPK not defined"<<endl; } void GLPKInterface::Set(const LinearProgram_Sparse& LP) { cerr<<"Warning, GLPK not defined"<<endl; } void GLPKInterface::Create(int m,int n) { cerr<<"Warning, GLPK not defined"<<endl; } void GLPKInterface::Clear() { } void GLPKInterface::SetRow(int i,const Vector& Ai) { cerr<<"Warning, GLPK not defined"<<endl; } void GLPKInterface::SetRowBounds(int i,Real low,Real high) { cerr<<"Warning, GLPK not defined"<<endl; } void GLPKInterface::SetVariableBounds(int j,Real low,Real high) { cerr<<"Warning, GLPK not defined"<<endl; } void GLPKInterface::SetRowBasic(int i) { cerr<<"Warning, GLPK not defined"<<endl; } bool GLPKInterface::GetRowBasic(int i) { cerr<<"Warning, GLPK not defined"<<endl; return false; } double GLPKInterface::GetRowDual(int i){ cerr<<"Warning, GLPK not defined"<<endl; return 0; } void GLPKInterface::SetRowNonBasic(int i,bool upper) { cerr<<"Warning, GLPK not defined"<<endl; } void GLPKInterface::SetVariableBasic(int j) { cerr<<"Warning, GLPK not defined"<<endl; } bool GLPKInterface::GetVariableBasic(int i) { cerr<<"Warning, GLPK not defined"<<endl; return false; } void GLPKInterface::SetVariableNonBasic(int j,bool upper) { cerr<<"Warning, GLPK not defined"<<endl; } void GLPKInterface::SetObjective(const Vector& c,bool minimize) { cerr<<"Warning, GLPK not defined"<<endl; } LinearProgram::Result GLPKInterface::Solve(Vector& xopt) { cerr<<"Warning, GLPK not defined"<<endl; return LinearProgram::Error; } bool GLPKInterface::Enabled() { return false; } void GLPKInterface::SelfTest() { cerr<<"Warning, GLPK not defined"<<endl; } #endif //HAVE_GLPK <commit_msg>Improved compatibility with low versions of GLPK<commit_after>#include "GLPKInterface.h" #if HAVE_GLPK #include <utils.h> #include <utils/SignalHandler.h> #include <signal.h> #include <iostream> #include <stdexcept> extern "C" { #include <glpk.h> } using namespace Optimization; using namespace std; #if GLP_MAJOR_VERSION < 4 || GLP_MINOR_VERSION < 20 #error "Require GLPK 4.20 or above" #endif const static Real kZeroTol = 1e-6; GLPKInterface::GLPKInterface() :lp(NULL) {} GLPKInterface::~GLPKInterface() { SafeDeleteProc(lp,glp_delete_prob); } inline int BoundType(Real low,Real high) { if(IsInf(low)==-1) { if(IsInf(high) == 1) return GLP_FR; return GLP_UP; } else if(IsInf(high) == 1) { return GLP_LO; } else { if(low==high) return GLP_FX; else return GLP_DB; } } int BoundTypeToGLP(LinearProgram::BoundType b) { switch(b) { case LinearProgram::Free: return GLP_FR; case LinearProgram::LowerBound: return GLP_LO; case LinearProgram::UpperBound: return GLP_UP; case LinearProgram::Bounded: return GLP_DB; case LinearProgram::Fixed: return GLP_FX; default: abort(); return GLP_FR; } } void GLPKInterface::Set(const LinearProgram& LP) { SafeDeleteProc(lp,glp_delete_prob); lp = glp_create_prob(); if(LP.minimize) glp_set_obj_dir(lp,GLP_MIN); else glp_set_obj_dir(lp,GLP_MAX); glp_add_rows(lp,LP.A.m); for(int i=0;i<LP.A.m;i++) { glp_set_row_bnds(lp,i+1,BoundTypeToGLP(LP.ConstraintType(i)),LP.q(i),LP.p(i)); } glp_add_cols(lp,LP.A.n); for(int i=0;i<LP.A.n;i++) { glp_set_col_bnds(lp,i+1,BoundTypeToGLP(LP.VariableType(i)),LP.l(i),LP.u(i)); } for(int i=0;i<LP.A.n;i++) glp_set_obj_coef(lp,i+1,LP.c(i)); vector<int> itemp(LP.A.n+1); dVector temp(LP.A.n+1); for(int i=0;i<LP.A.m;i++) { //pick nonzero entries int nnz=0; for(int j=0;j<LP.A.n;j++) { if(!FuzzyZero(LP.A(i,j),kZeroTol)) { itemp[nnz+1] = j+1; temp(nnz+1) = LP.A(i,j); nnz++; } } glp_set_mat_row(lp,i+1,nnz,&itemp[0],temp); } } void GLPKInterface::Set(const LinearProgram_Sparse& LP) { SafeDeleteProc(lp,glp_delete_prob); lp = glp_create_prob(); if(LP.minimize) glp_set_obj_dir(lp,GLP_MIN); else glp_set_obj_dir(lp,GLP_MAX); glp_add_rows(lp,LP.A.m); for(int i=0;i<LP.A.m;i++) { glp_set_row_bnds(lp,i+1,BoundTypeToGLP(LP.ConstraintType(i)),LP.q(i),LP.p(i)); } glp_add_cols(lp,LP.A.n); for(int i=0;i<LP.A.n;i++) { glp_set_col_bnds(lp,i+1,BoundTypeToGLP(LP.VariableType(i)),LP.l(i),LP.u(i)); } for(int i=0;i<LP.A.n;i++) glp_set_obj_coef(lp,i+1,LP.c(i)); vector<int> itemp(LP.A.n+1); dVector temp(LP.A.n+1); for(int i=0;i<LP.A.m;i++) { //pick nonzero entries int nnz=0; for(SparseMatrix::RowT::const_iterator j=LP.A.rows[i].begin();j!=LP.A.rows[i].end();j++) { if(!FuzzyZero(j->second,kZeroTol)) { itemp[nnz+1] = j->first+1; temp(nnz+1) = j->second; nnz++; } } glp_set_mat_row(lp,i+1,nnz,&itemp[0],temp); } } void GLPKInterface::Clear() { SafeDeleteProc(lp,glp_delete_prob); } void GLPKInterface::Create(int m,int n) { SafeDeleteProc(lp,glp_delete_prob); lp = glp_create_prob(); glp_add_rows(lp,m); glp_add_cols(lp,n); } void GLPKInterface::SetObjective(const Vector& obj,bool minimize) { for(int i=0;i<obj.n;i++) glp_set_obj_coef(lp,i+1,obj(i)); if(minimize) glp_set_obj_dir(lp,GLP_MIN); else glp_set_obj_dir(lp,GLP_MAX); } void GLPKInterface::SetRow(int i,const Vector& Ai) { vector<int> itemp(Ai.n+1); dVector temp(Ai.n+1); //pick nonzero entries int nnz=0; for(int j=0;j<Ai.n;j++) { if(!FuzzyZero(Ai(j),kZeroTol)) { itemp[nnz+1] = j+1; temp(nnz+1) = Ai(j); nnz++; } } glp_set_mat_row(lp,i+1,nnz,&itemp[0],temp); } void GLPKInterface::SetRowBounds(int i,Real low,Real high) { glp_set_row_bnds(lp,i+1,BoundType(low,high),low,high); } void GLPKInterface::SetVariableBounds(int j,Real low,Real high) { glp_set_col_bnds(lp,j+1,BoundType(low,high),low,high); } void GLPKInterface::SetRowBasic(int i) { glp_set_row_stat(lp,i+1,GLP_BS); } bool GLPKInterface::GetRowBasic(int i) { return glp_get_row_stat(lp,i+1)==GLP_BS; } double GLPKInterface::GetRowDual(int i){ return glp_get_row_dual(lp, i+1); } double GLPKInterface::GetVariableDual(int j){ return glp_get_col_dual(lp, j+1); } void GLPKInterface::SetRowNonBasic(int i,bool upper) { if(upper) glp_set_row_stat(lp,i+1,GLP_NU); else glp_set_row_stat(lp,i+1,GLP_NL); } void GLPKInterface::SetVariableBasic(int j) { glp_set_col_stat(lp,j+1,GLP_BS); } bool GLPKInterface::GetVariableBasic(int j) { return glp_get_col_stat(lp,j+1)==GLP_BS; } void GLPKInterface::SetVariableNonBasic(int j,bool upper) { if(upper) glp_set_col_stat(lp,j+1,GLP_NU); else glp_set_col_stat(lp,j+1,GLP_NL); } int my_gglp_fault_handler(void* info,const char* msg) { printf("GLPK error message %s\n",msg); //printf("GLPK fatal error %s\n",msg); //printf("jumping...\n"); //throw(std::runtime_error(msg)); /* printf("GLPK fatal error, dumping!\n"); GLP* lp=(GLP*)info; glp_write_cpxlp(lp,"temp_lp.txt"); */ return 0; } void my_gglp_fault_handler2(void* info) { printf("GLPK error, quitting\n"); } struct GLPKInterruptHandler : public SignalHandler { public: GLPKInterruptHandler(GLPKInterface* _glpk) :glpk(_glpk) {} virtual void OnRaise(int signum) { printf("Interrupt called during GLPK solve... possible infinite loop\n"); glp_prob* lp=glpk->lp; #if GLP_MAJOR_VERSION > 4 || (GLP_MAJOR_VERSION == 4 && GLP_MINOR_VERSION >= 40) glp_write_lp(lp,NULL,"temp_lp.txt"); #endif throw(std::runtime_error("Interrupt called during GLPK solve")); //exit(-1); } GLPKInterface* glpk; }; LinearProgram::Result GLPKInterface::Solve(Vector& xopt) { assert(lp != NULL); //glp_write_cpxlp(lp,"temp_lp.txt"); //glp_print_prob(lp,"temp_lp.txt"); #if GLP_MINOR_VERSION >= 43 glp_error_hook(my_gglp_fault_handler2,0); #endif glp_smcp params; glp_init_smcp(&params); params.msg_lev = GLP_MSG_ERR; params.presolve = GLP_OFF; GLPKInterruptHandler handler(this); handler.SetCurrent(SIGINT); //handler.SetCurrent(SIGABRT); int res; try { res=glp_simplex(lp,&params); } catch(const std::exception& e) { printf("GLPK internal error: "); printf(e.what()); return LinearProgram::Error; } catch (...) { printf("Unknown error occurred\n"); return LinearProgram::Error; } #if GLP_MINOR_VERSION >= 43 glp_error_hook(0,0); #endif handler.UnsetCurrent(SIGINT); switch(res) { case 0: break; case GLP_EFAIL: cout<<"Error in matrix construction!"<<endl; return LinearProgram::Error; case GLP_EOBJLL: cout<<"Objective reached lower limit!"<<endl; return LinearProgram::Error; case GLP_EOBJUL: cout<<"Objective reached upper limit!"<<endl; return LinearProgram::Error; case GLP_ENOPFS: cout<<"Linear program has no primary feasible solution!"<<endl; return LinearProgram::Infeasible; case GLP_ENODFS: cout<<"Linear program has no dual feasible solution!"<<endl; return LinearProgram::Infeasible; case GLP_EITLIM: cout<<"Max iterations reached!"<<endl; return LinearProgram::Error; case GLP_ETMLIM: cout<<"Time limit reached!"<<endl; return LinearProgram::Error; case GLP_ESING: cout<<"Singularity reached!"<<endl; return LinearProgram::Error; default: cout<<"Unknown error"<<endl; return LinearProgram::Error; } int stat=glp_get_status(lp); int n=glp_get_num_cols(lp); xopt.resize(n); for(int i=0;i<n;i++) xopt(i) = (Real)glp_get_col_prim(lp,i+1); switch(stat) { case GLP_OPT: case GLP_FEAS: return LinearProgram::Feasible; case GLP_INFEAS: case GLP_NOFEAS: return LinearProgram::Infeasible; case GLP_UNBND: return LinearProgram::Unbounded; case GLP_UNDEF: cout<<"Solution is undefined!"<<endl; return LinearProgram::Error; default: cout<<"Shouldn't get here!"<<endl; return LinearProgram::Error; } } bool GLPKInterface::Enabled() { return true; } #else using namespace Optimization; using namespace std; GLPKInterface::GLPKInterface() { } GLPKInterface::~GLPKInterface() { } void GLPKInterface::Set(const LinearProgram& LP) { cerr<<"Warning, GLPK not defined"<<endl; } void GLPKInterface::Set(const LinearProgram_Sparse& LP) { cerr<<"Warning, GLPK not defined"<<endl; } void GLPKInterface::Create(int m,int n) { cerr<<"Warning, GLPK not defined"<<endl; } void GLPKInterface::Clear() { } void GLPKInterface::SetRow(int i,const Vector& Ai) { cerr<<"Warning, GLPK not defined"<<endl; } void GLPKInterface::SetRowBounds(int i,Real low,Real high) { cerr<<"Warning, GLPK not defined"<<endl; } void GLPKInterface::SetVariableBounds(int j,Real low,Real high) { cerr<<"Warning, GLPK not defined"<<endl; } void GLPKInterface::SetRowBasic(int i) { cerr<<"Warning, GLPK not defined"<<endl; } bool GLPKInterface::GetRowBasic(int i) { cerr<<"Warning, GLPK not defined"<<endl; return false; } double GLPKInterface::GetRowDual(int i){ cerr<<"Warning, GLPK not defined"<<endl; return 0; } void GLPKInterface::SetRowNonBasic(int i,bool upper) { cerr<<"Warning, GLPK not defined"<<endl; } void GLPKInterface::SetVariableBasic(int j) { cerr<<"Warning, GLPK not defined"<<endl; } bool GLPKInterface::GetVariableBasic(int i) { cerr<<"Warning, GLPK not defined"<<endl; return false; } void GLPKInterface::SetVariableNonBasic(int j,bool upper) { cerr<<"Warning, GLPK not defined"<<endl; } void GLPKInterface::SetObjective(const Vector& c,bool minimize) { cerr<<"Warning, GLPK not defined"<<endl; } LinearProgram::Result GLPKInterface::Solve(Vector& xopt) { cerr<<"Warning, GLPK not defined"<<endl; return LinearProgram::Error; } bool GLPKInterface::Enabled() { return false; } void GLPKInterface::SelfTest() { cerr<<"Warning, GLPK not defined"<<endl; } #endif //HAVE_GLPK <|endoftext|>
<commit_before>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include "MeshBufferOGL.h" #include "Engine.h" #include "RendererOGL.h" #include "Utils.h" namespace ouzel { namespace video { MeshBufferOGL::MeshBufferOGL() { } MeshBufferOGL::~MeshBufferOGL() { destroy(); } void MeshBufferOGL::destroy() { if (_vertexArrayId) glDeleteVertexArrays(1, &_vertexArrayId); if (_vertexBufferId) glDeleteBuffers(1, &_vertexBufferId); if (_indexBufferId) glDeleteBuffers(1, &_indexBufferId); } bool MeshBufferOGL::init() { glGenBuffers(1, &_indexBufferId); glGenVertexArrays(1, &_vertexArrayId); if (std::static_pointer_cast<RendererOGL>(sharedEngine->getRenderer())->checkOpenGLErrors()) { return false; } return true; } bool MeshBufferOGL::initFromData(const void* indices, uint32_t indexSize, uint32_t indexCount, bool dynamicIndexBuffer, const void* vertices, uint32_t vertexAttributes, uint32_t vertexCount, bool dynamicVertexBuffer) { if (!MeshBuffer::initFromData(indices, indexSize, indexCount, dynamicIndexBuffer, vertices, vertexAttributes, vertexCount, dynamicVertexBuffer)) { return false; } destroy(); glGenBuffers(1, &_indexBufferId); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indexBufferId); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexSize * indexCount, indices, _dynamicIndexBuffer ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); if (std::static_pointer_cast<RendererOGL>(sharedEngine->getRenderer())->checkOpenGLErrors()) { return false; } if (!updateIndexFormat()) { return false; } glGenVertexArrays(1, &_vertexArrayId); glBindVertexArray(_vertexArrayId); glGenBuffers(1, &_vertexBufferId); glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferId); glBufferData(GL_ARRAY_BUFFER, _vertexSize * vertexCount, vertices, _dynamicVertexBuffer ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); if (std::static_pointer_cast<RendererOGL>(sharedEngine->getRenderer())->checkOpenGLErrors()) { return false; } if (!updateVertexAttributes()) { return false; } return true; } bool MeshBufferOGL::setIndexSize(uint32_t indexSize) { if (!MeshBuffer::setIndexSize(indexSize)) { return false; } return updateIndexFormat(); } bool MeshBufferOGL::setVertexAttributes(uint32_t vertexAttributes) { if (!MeshBuffer::setVertexAttributes(vertexAttributes)) { return false; } return updateVertexAttributes(); } bool MeshBufferOGL::uploadIndices(const void* indices, uint32_t indexCount) { if (!MeshBuffer::uploadIndices(indices, indexCount)) { return false; } glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indexBufferId); glBufferData(GL_ELEMENT_ARRAY_BUFFER, _indexSize * indexCount, indices, _dynamicIndexBuffer ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); if (std::static_pointer_cast<RendererOGL>(sharedEngine->getRenderer())->checkOpenGLErrors()) { return false; } return true; } bool MeshBufferOGL::uploadVertices(const void* vertices, uint32_t vertexCount) { if (!MeshBuffer::uploadVertices(vertices, vertexCount)) { return false; } glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferId); glBufferData(GL_ARRAY_BUFFER, _vertexSize * vertexCount, vertices, _dynamicVertexBuffer ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); if (std::static_pointer_cast<RendererOGL>(sharedEngine->getRenderer())->checkOpenGLErrors()) { return false; } return true; } bool MeshBufferOGL::updateIndexFormat() { switch (_indexSize) { case 1: _indexFormat = GL_UNSIGNED_BYTE; break; case 2: _indexFormat = GL_UNSIGNED_SHORT; break; case 4: _indexFormat = GL_UNSIGNED_INT; break; default: log("Invalid index size"); return false; } return true; } bool MeshBufferOGL::updateVertexAttributes() { glBindVertexArray(_vertexArrayId); GLuint index = 0; GLuint offset = 0; if (_vertexAttributes & VERTEX_POSITION) { glEnableVertexAttribArray(index); glVertexAttribPointer(index, 3, GL_FLOAT, GL_FALSE, static_cast<GLint>(_vertexSize), reinterpret_cast<const GLvoid*>(offset)); offset += 3 * sizeof(float); index++; } if (_vertexAttributes & VERTEX_COLOR) { glEnableVertexAttribArray(index); glVertexAttribPointer(index, 4, GL_UNSIGNED_BYTE, GL_TRUE, static_cast<GLint>(_vertexSize), reinterpret_cast<const GLvoid*>(offset)); offset += 4 * sizeof(uint8_t); index++; } if (_vertexAttributes & VERTEX_NORMAL) { glEnableVertexAttribArray(index); glVertexAttribPointer(index, 3, GL_FLOAT, GL_FALSE, static_cast<GLint>(_vertexSize), reinterpret_cast<const GLvoid*>(offset)); offset += 3 * sizeof(float); index++; } if (_vertexAttributes & VERTEX_TEXCOORD0) { glEnableVertexAttribArray(index); glVertexAttribPointer(index, 2, GL_FLOAT, GL_FALSE, static_cast<GLint>(_vertexSize), reinterpret_cast<const GLvoid*>(offset)); offset += 2 * sizeof(float); index++; } if (_vertexAttributes & VERTEX_TEXCOORD1) { glEnableVertexAttribArray(index); glVertexAttribPointer(index, 2, GL_FLOAT, GL_FALSE, static_cast<GLint>(_vertexSize), reinterpret_cast<const GLvoid*>(offset)); offset += 2 * sizeof(float); index++; } if (offset != _vertexSize) { log("Invalid vertex size"); return false; } if (std::static_pointer_cast<RendererOGL>(sharedEngine->getRenderer())->checkOpenGLErrors()) { return false; } return true; } } // namespace video } // namespace ouzel <commit_msg>Fix OpenGL vertex buffer creation<commit_after>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include "MeshBufferOGL.h" #include "Engine.h" #include "RendererOGL.h" #include "Utils.h" namespace ouzel { namespace video { MeshBufferOGL::MeshBufferOGL() { } MeshBufferOGL::~MeshBufferOGL() { destroy(); } void MeshBufferOGL::destroy() { if (_vertexArrayId) glDeleteVertexArrays(1, &_vertexArrayId); if (_vertexBufferId) glDeleteBuffers(1, &_vertexBufferId); if (_indexBufferId) glDeleteBuffers(1, &_indexBufferId); } bool MeshBufferOGL::init() { glGenBuffers(1, &_indexBufferId); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indexBufferId); glGenVertexArrays(1, &_vertexArrayId); glBindVertexArray(_vertexArrayId); glGenBuffers(1, &_vertexBufferId); glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferId); if (std::static_pointer_cast<RendererOGL>(sharedEngine->getRenderer())->checkOpenGLErrors()) { return false; } return true; } bool MeshBufferOGL::initFromData(const void* indices, uint32_t indexSize, uint32_t indexCount, bool dynamicIndexBuffer, const void* vertices, uint32_t vertexAttributes, uint32_t vertexCount, bool dynamicVertexBuffer) { if (!MeshBuffer::initFromData(indices, indexSize, indexCount, dynamicIndexBuffer, vertices, vertexAttributes, vertexCount, dynamicVertexBuffer)) { return false; } destroy(); glGenBuffers(1, &_indexBufferId); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indexBufferId); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexSize * indexCount, indices, _dynamicIndexBuffer ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); if (std::static_pointer_cast<RendererOGL>(sharedEngine->getRenderer())->checkOpenGLErrors()) { return false; } if (!updateIndexFormat()) { return false; } glGenVertexArrays(1, &_vertexArrayId); glBindVertexArray(_vertexArrayId); glGenBuffers(1, &_vertexBufferId); glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferId); glBufferData(GL_ARRAY_BUFFER, _vertexSize * vertexCount, vertices, _dynamicVertexBuffer ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); if (std::static_pointer_cast<RendererOGL>(sharedEngine->getRenderer())->checkOpenGLErrors()) { return false; } if (!updateVertexAttributes()) { return false; } return true; } bool MeshBufferOGL::setIndexSize(uint32_t indexSize) { if (!MeshBuffer::setIndexSize(indexSize)) { return false; } return updateIndexFormat(); } bool MeshBufferOGL::setVertexAttributes(uint32_t vertexAttributes) { if (!MeshBuffer::setVertexAttributes(vertexAttributes)) { return false; } return updateVertexAttributes(); } bool MeshBufferOGL::uploadIndices(const void* indices, uint32_t indexCount) { if (!MeshBuffer::uploadIndices(indices, indexCount)) { return false; } glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indexBufferId); glBufferData(GL_ELEMENT_ARRAY_BUFFER, _indexSize * indexCount, indices, _dynamicIndexBuffer ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); if (std::static_pointer_cast<RendererOGL>(sharedEngine->getRenderer())->checkOpenGLErrors()) { return false; } return true; } bool MeshBufferOGL::uploadVertices(const void* vertices, uint32_t vertexCount) { if (!MeshBuffer::uploadVertices(vertices, vertexCount)) { return false; } glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferId); glBufferData(GL_ARRAY_BUFFER, _vertexSize * vertexCount, vertices, _dynamicVertexBuffer ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); if (std::static_pointer_cast<RendererOGL>(sharedEngine->getRenderer())->checkOpenGLErrors()) { return false; } return true; } bool MeshBufferOGL::updateIndexFormat() { switch (_indexSize) { case 1: _indexFormat = GL_UNSIGNED_BYTE; break; case 2: _indexFormat = GL_UNSIGNED_SHORT; break; case 4: _indexFormat = GL_UNSIGNED_INT; break; default: log("Invalid index size"); return false; } return true; } bool MeshBufferOGL::updateVertexAttributes() { glBindVertexArray(_vertexArrayId); glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferId); GLuint index = 0; GLuint offset = 0; if (_vertexAttributes & VERTEX_POSITION) { glEnableVertexAttribArray(index); glVertexAttribPointer(index, 3, GL_FLOAT, GL_FALSE, static_cast<GLint>(_vertexSize), reinterpret_cast<const GLvoid*>(offset)); offset += 3 * sizeof(float); index++; } if (_vertexAttributes & VERTEX_COLOR) { glEnableVertexAttribArray(index); glVertexAttribPointer(index, 4, GL_UNSIGNED_BYTE, GL_TRUE, static_cast<GLint>(_vertexSize), reinterpret_cast<const GLvoid*>(offset)); offset += 4 * sizeof(uint8_t); index++; } if (_vertexAttributes & VERTEX_NORMAL) { glEnableVertexAttribArray(index); glVertexAttribPointer(index, 3, GL_FLOAT, GL_FALSE, static_cast<GLint>(_vertexSize), reinterpret_cast<const GLvoid*>(offset)); offset += 3 * sizeof(float); index++; } if (_vertexAttributes & VERTEX_TEXCOORD0) { glEnableVertexAttribArray(index); glVertexAttribPointer(index, 2, GL_FLOAT, GL_FALSE, static_cast<GLint>(_vertexSize), reinterpret_cast<const GLvoid*>(offset)); offset += 2 * sizeof(float); index++; } if (_vertexAttributes & VERTEX_TEXCOORD1) { glEnableVertexAttribArray(index); glVertexAttribPointer(index, 2, GL_FLOAT, GL_FALSE, static_cast<GLint>(_vertexSize), reinterpret_cast<const GLvoid*>(offset)); offset += 2 * sizeof(float); index++; } if (offset != _vertexSize) { log("Invalid vertex size"); return false; } if (std::static_pointer_cast<RendererOGL>(sharedEngine->getRenderer())->checkOpenGLErrors()) { return false; } return true; } } // namespace video } // namespace ouzel <|endoftext|>
<commit_before>#include "FTCharmap.h" #ifdef FTGL_DEBUG #include "mmgr.h" #endif #ifdef FTGL_USE_NAMESPACE namespace ftgl { #endif FTCharmap::FTCharmap( FT_Face face) : ftFace( face), err(0) { // Check that the default is valid if( !face->charmap) { FT_Set_Charmap( ftFace, ftFace->charmaps[0]); } ftEncoding = face->charmap->encoding; } FTCharmap::~FTCharmap() { charMap.clear(); } bool FTCharmap::CharMap( FT_Encoding encoding) { if( ftEncoding == encoding) { return true; } err = FT_Select_Charmap( ftFace, encoding ); if( !err) { ftEncoding = encoding; charMap.clear(); } return !err; } bool FTCharmap::CharMap( FT_UShort platform, FT_UShort encoding) { FT_CharMap found = 0; FT_CharMap charmap; for( int n = 0; n < ftFace->num_charmaps; n++ ) { charmap = ftFace->charmaps[n]; if( charmap->platform_id == platform && charmap->encoding_id == encoding) { found = charmap; break; } } if( !found ) { return false; } if( ftEncoding == found->encoding) { return true; } /* now, select the charmap for the face object */ err = FT_Set_Charmap( ftFace, found ); if( !err) { ftEncoding = found->encoding; charMap.clear(); } return !err; } unsigned int FTCharmap::CharIndex( unsigned int index ) { #ifdef FTGL_DO_NOT_USE_STL const CharacterMap::GlyphIndex *result = charMap.find(index); if (!result) { unsigned int glyph = FT_Get_Char_Index(ftFace, index); charMap.insert(index, glyph); return glyph; } else { return *result; } #else CharacterMap::const_iterator result = charMap.find( index); if( result == charMap.end()) { unsigned int glyph = FT_Get_Char_Index( ftFace, index); charMap.insert( CharacterMap::value_type( index, glyph)); return glyph; } else { return result->second; } #endif } #ifdef FTGL_USE_NAMESPACE } // namespace ftgl #endif <commit_msg>fixed null deref warning in ctor<commit_after>#include "FTCharmap.h" #ifdef FTGL_DEBUG #include "mmgr.h" #endif #ifdef FTGL_USE_NAMESPACE namespace ftgl { #endif FTCharmap::FTCharmap( FT_Face face) : ftFace( face), err(0) { // Check that the default is valid if( !face->charmap) { FT_Set_Charmap( ftFace, ftFace->charmaps[0]); ftEncoding = ft_encoding_none; } else { ftEncoding = face->charmap->encoding; } } FTCharmap::~FTCharmap() { charMap.clear(); } bool FTCharmap::CharMap( FT_Encoding encoding) { if( ftEncoding == encoding) { return true; } err = FT_Select_Charmap( ftFace, encoding ); if( !err) { ftEncoding = encoding; charMap.clear(); } return !err; } bool FTCharmap::CharMap( FT_UShort platform, FT_UShort encoding) { FT_CharMap found = 0; FT_CharMap charmap; for( int n = 0; n < ftFace->num_charmaps; n++ ) { charmap = ftFace->charmaps[n]; if( charmap->platform_id == platform && charmap->encoding_id == encoding) { found = charmap; break; } } if( !found ) { return false; } if( ftEncoding == found->encoding) { return true; } /* now, select the charmap for the face object */ err = FT_Set_Charmap( ftFace, found ); if( !err) { ftEncoding = found->encoding; charMap.clear(); } return !err; } unsigned int FTCharmap::CharIndex( unsigned int index ) { #ifdef FTGL_DO_NOT_USE_STL const CharacterMap::GlyphIndex *result = charMap.find(index); if (!result) { unsigned int glyph = FT_Get_Char_Index(ftFace, index); charMap.insert(index, glyph); return glyph; } else { return *result; } #else CharacterMap::const_iterator result = charMap.find( index); if( result == charMap.end()) { unsigned int glyph = FT_Get_Char_Index( ftFace, index); charMap.insert( CharacterMap::value_type( index, glyph)); return glyph; } else { return result->second; } #endif } #ifdef FTGL_USE_NAMESPACE } // namespace ftgl #endif <|endoftext|>