text
stringlengths
54
60.6k
<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved. #include "unittest/gtest.hpp" #include "arch/timing.hpp" #include "concurrency/pmap.hpp" #include "unittest/unittest_utils.hpp" #include "utils.hpp" namespace unittest { int wait_array[2][10] = { { 1, 1, 2, 3, 5, 13, 20, 30, 40, 8 }, { 5, 3, 2, 40, 30, 20, 8, 13, 1, 1 } }; void walk_wait_times(int i) { ticks_t t = get_ticks(); for (int j = 0; j < 10; ++j) { nap(wait_array[i][j]); const ticks_t t2 = get_ticks(); const int64_t diff = static_cast<int64_t>(t2) - static_cast<int64_t>(t); // Asserts that we're off by less than two milliseconds. ASSERT_LT(llabs(diff - wait_array[i][j] * MILLION), 2 * MILLION); t = t2; } } TPTEST(TimerTest, TestApproximateWaitTimes) { pmap(2, walk_wait_times); } } // namespace unittest <commit_msg>Decrease sensitivity of timer test.<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved. #include "unittest/gtest.hpp" #include "arch/timing.hpp" #include "concurrency/pmap.hpp" #include "unittest/unittest_utils.hpp" #include "utils.hpp" namespace unittest { int wait_array[2][10] = { { 1, 1, 2, 3, 5, 13, 20, 30, 40, 8 }, { 5, 3, 2, 40, 30, 20, 8, 13, 1, 1 } }; void walk_wait_times(int i) { ticks_t t = get_ticks(); for (int j = 0; j < 10; ++j) { nap(wait_array[i][j]); const ticks_t t2 = get_ticks(); const int64_t diff = static_cast<int64_t>(t2) - static_cast<int64_t>(t); // Asserts that we're off by less than 25% of the sleep time // or two milliseconds, whichever is larger. ASSERT_LT(llabs(diff - wait_array[i][j] * MILLION), std::max(diff / 4, 2 * MILLION)); t = t2; } } TPTEST(TimerTest, TestApproximateWaitTimes) { pmap(2, walk_wait_times); } } // namespace unittest <|endoftext|>
<commit_before>#include <zip_longest.hpp> #include "helpers.hpp" #include <vector> #include <tuple> #include <string> #include <iterator> #include <utility> #include <iterator> #include <sstream> #include <iostream> #include "catch.hpp" using iter::zip_longest; // reopening boost is the only way I can find that gets this to print namespace boost { template <typename T> std::ostream& operator<<(std::ostream& out, const optional<T>& opt) { if (opt) { out << "Just " << *opt; } else { out << "Nothing"; } return out; } } template <typename... Ts> using const_opt_tuple = std::tuple<boost::optional<const Ts&>...>; TEST_CASE("zip longest: correctly detects longest at any position", "[zip_longest]") { const std::vector<int> ivec{2, 4, 6, 8, 10, 12}; const std::vector<std::string> svec{"abc", "def", "xyz"}; const std::string str{"hello"}; SECTION("longest first") { using TP = const_opt_tuple<int, std::string, char>; using ResVec = std::vector<TP>; auto zl = zip_longest(ivec, svec, str); ResVec results(std::begin(zl), std::end(zl)); ResVec rc = { TP{{ivec[0]}, {svec[0]}, {str[0]}}, TP{{ivec[1]}, {svec[1]}, {str[1]}}, TP{{ivec[2]}, {svec[2]}, {str[2]}}, TP{{ivec[3]}, {}, {str[3]}}, TP{{ivec[4]}, {}, {str[4]}}, TP{{ivec[5]}, {}, {} } }; REQUIRE( results == rc ); } SECTION("longest in middle") { using TP = const_opt_tuple<std::string, int, char>; using ResVec = std::vector<TP>; auto zl = zip_longest(svec, ivec, str); ResVec results(std::begin(zl), std::end(zl)); ResVec rc = { TP{{svec[0]}, {ivec[0]}, {str[0]}}, TP{{svec[1]}, {ivec[1]}, {str[1]}}, TP{{svec[2]}, {ivec[2]}, {str[2]}}, TP{{}, {ivec[3]}, {str[3]}}, TP{{}, {ivec[4]}, {str[4]}}, TP{{}, {ivec[5]}, {} } }; REQUIRE( results == rc ); } SECTION("longest at end") { using TP = const_opt_tuple<std::string, char, int>; using ResVec = std::vector<TP>; auto zl = zip_longest(svec, str, ivec); ResVec results(std::begin(zl), std::end(zl)); ResVec rc = { TP{{svec[0]}, {str[0]}, {ivec[0]}}, TP{{svec[1]}, {str[1]}, {ivec[1]}}, TP{{svec[2]}, {str[2]}, {ivec[2]}}, TP{{}, {str[3]}, {ivec[3]}}, TP{{}, {str[4]}, {ivec[4]}}, TP{{}, {}, {ivec[5]}} }; REQUIRE( results == rc ); } } <commit_msg>tests that zip_longest'd elements can be modified<commit_after>#include <zip_longest.hpp> #include "helpers.hpp" #include <vector> #include <tuple> #include <string> #include <iterator> #include <utility> #include <iterator> #include <sstream> #include <iostream> #include "catch.hpp" using iter::zip_longest; // reopening boost is the only way I can find that gets this to print namespace boost { template <typename T> std::ostream& operator<<(std::ostream& out, const optional<T>& opt) { if (opt) { out << "Just " << *opt; } else { out << "Nothing"; } return out; } } template <typename... Ts> using const_opt_tuple = std::tuple<boost::optional<const Ts&>...>; TEST_CASE("zip longest: correctly detects longest at any position", "[zip_longest]") { const std::vector<int> ivec{2, 4, 6, 8, 10, 12}; const std::vector<std::string> svec{"abc", "def", "xyz"}; const std::string str{"hello"}; SECTION("longest first") { using TP = const_opt_tuple<int, std::string, char>; using ResVec = std::vector<TP>; auto zl = zip_longest(ivec, svec, str); ResVec results(std::begin(zl), std::end(zl)); ResVec rc = { TP{{ivec[0]}, {svec[0]}, {str[0]}}, TP{{ivec[1]}, {svec[1]}, {str[1]}}, TP{{ivec[2]}, {svec[2]}, {str[2]}}, TP{{ivec[3]}, {}, {str[3]}}, TP{{ivec[4]}, {}, {str[4]}}, TP{{ivec[5]}, {}, {} } }; REQUIRE( results == rc ); } SECTION("longest in middle") { using TP = const_opt_tuple<std::string, int, char>; using ResVec = std::vector<TP>; auto zl = zip_longest(svec, ivec, str); ResVec results(std::begin(zl), std::end(zl)); ResVec rc = { TP{{svec[0]}, {ivec[0]}, {str[0]}}, TP{{svec[1]}, {ivec[1]}, {str[1]}}, TP{{svec[2]}, {ivec[2]}, {str[2]}}, TP{{}, {ivec[3]}, {str[3]}}, TP{{}, {ivec[4]}, {str[4]}}, TP{{}, {ivec[5]}, {} } }; REQUIRE( results == rc ); } SECTION("longest at end") { using TP = const_opt_tuple<std::string, char, int>; using ResVec = std::vector<TP>; auto zl = zip_longest(svec, str, ivec); ResVec results(std::begin(zl), std::end(zl)); ResVec rc = { TP{{svec[0]}, {str[0]}, {ivec[0]}}, TP{{svec[1]}, {str[1]}, {ivec[1]}}, TP{{svec[2]}, {str[2]}, {ivec[2]}}, TP{{}, {str[3]}, {ivec[3]}}, TP{{}, {str[4]}, {ivec[4]}}, TP{{}, {}, {ivec[5]}} }; REQUIRE( results == rc ); } } TEST_CASE("zip longest: when all are empty, terminates right away", "[zip_longest]") { const std::vector<int> ivec{}; const std::vector<std::string> svec{}; const std::string str{}; auto zl = zip_longest(ivec, svec, str); REQUIRE( std::begin(zl) == std::end(zl) ); } TEST_CASE("zip longest: can modify zipped sequences", "[zip_longest]") { std::vector<int> ns1 = {1, 2, 3}; std::vector<int> ns2 = {10, 11, 12}; for (auto&& t : zip_longest(ns1, ns2)) { *std::get<0>(t) = -1; *std::get<1>(t) = -1; } std::vector<int> vc = {-1, -1, -1}; REQUIRE( ns1 == vc ); REQUIRE( ns2 == vc ); } <|endoftext|>
<commit_before>// @(#)root/gpad:$Name: $:$Id: TAttFillCanvas.cxx,v 1.1.1.1 2000/05/16 17:00:41 rdm Exp $ // Author: Rene Brun 04/07/96 // ---------------------------------- AttFillCanvas.C /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TROOT.h" #include "TAttFillCanvas.h" #include "TGroupButton.h" #include "TLine.h" #include "TText.h" ClassImp(TAttFillCanvas) //______________________________________________________________________________ // // An AttFillCanvas is a TDialogCanvas specialized to set fill attributes. //Begin_Html /* <img src="gif/attfillcanvas.gif"> */ //End_Html // //______________________________________________________________________________ TAttFillCanvas::TAttFillCanvas() : TDialogCanvas() { //*-*-*-*-*-*-*-*-*-*-*-*AttFillCanvas default constructor*-*-*-*-*-*-*-*-*-*-* //*-* ================================ } //_____________________________________________________________________________ TAttFillCanvas::TAttFillCanvas(const char *name, const char *title, UInt_t ww, UInt_t wh) : TDialogCanvas(name,title,ww,wh) { //*-*-*-*-*-*-*-*-*-*-*-*AttFillCanvas constructor*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ======================== static Int_t lsty[10] = {1001,3004,3005,3006,3007,0,3013,3010,3014,3012}; TVirtualPad *padsav = gPad; BuildStandardButtons(); //*-*- Fill styles choice buttons TGroupButton *test1 = 0; Float_t xlow, ylow, wpad, hpad; Int_t i,j; wpad = 0.19; hpad = 0.20; char command[64]; Int_t number = 0; for (j=0;j<2;j++) { ylow = 0.12 + j*hpad; for (i=0;i<5;i++) { xlow = 0.05 + i*wpad; sprintf(command,"SetFillStyle(%d)",lsty[number]); test1 = new TGroupButton("Style","",command,xlow, ylow, xlow+0.9*wpad, ylow+0.9*hpad); if (number == 0) { test1->SetBorderMode(-1); test1->SetFillColor(1); } else { test1->SetFillColor(10); } if (number == 5) { test1->SetFillStyle(1001); } else { test1->SetFillStyle(lsty[number]); } test1->SetBorderSize(2); test1->Draw(); number++; } } //*-* draw colortable pads test1->DisplayColorTable("SetFillColor",0.05, 0.60, 0.90, 0.38); Update(); SetEditable(kFALSE); padsav->cd(); } //______________________________________________________________________________ TAttFillCanvas::~TAttFillCanvas() { //*-*-*-*-*-*-*-*-*-*-*AttFillCanvas default destructor*-*-*-*-*-*-*-*-*-*-*-* //*-* =============================== } //______________________________________________________________________________ void TAttFillCanvas::UpdateFillAttributes(Int_t col, Int_t sty) { //*-*-*-*-*-*-*-*-*-*-*Update object attributes*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ======================== TIter next(GetListOfPrimitives()); TGroupButton *button; char cmd[64]; fRefObject = gROOT->GetSelectedPrimitive(); fRefPad = (TPad*)gROOT->GetSelectedPad(); if (fRefObject) { sprintf(cmd,"attfill: %s",fRefObject->GetName()); SetTitle(cmd); } TObject *obj; while ((obj = next())) { if (!obj->InheritsFrom(TGroupButton::Class())) continue; button = (TGroupButton*)obj; if (button->GetBorderMode() < 0) { button->SetBorderMode(1); button->Modified(); } sprintf(cmd,"SetFillColor(%d)",col); if (!strcmp(button->GetTitle(),cmd)) button->SetBorderMode(-1); sprintf(cmd,"SetFillStyle(%d)",sty); if (!strcmp(button->GetTitle(),cmd)) button->SetBorderMode(-1); if (button->GetBorderMode() < 0) { button->Modified(); } } Update(); } <commit_msg>Change the TAttFill panel to display the 25 fill patterns instead of just 8.<commit_after>// @(#)root/gpad:$Name: $:$Id: TAttFillCanvas.cxx,v 1.2 2001/05/28 06:20:52 brun Exp $ // Author: Rene Brun 04/07/96 // ---------------------------------- AttFillCanvas.C /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TROOT.h" #include "TAttFillCanvas.h" #include "TGroupButton.h" #include "TLine.h" #include "TText.h" ClassImp(TAttFillCanvas) //______________________________________________________________________________ // // An AttFillCanvas is a TDialogCanvas specialized to set fill attributes. //Begin_Html /* <img src="gif/attfillcanvas.gif"> */ //End_Html // //______________________________________________________________________________ TAttFillCanvas::TAttFillCanvas() : TDialogCanvas() { //*-*-*-*-*-*-*-*-*-*-*-*AttFillCanvas default constructor*-*-*-*-*-*-*-*-*-*-* //*-* ================================ } //_____________________________________________________________________________ TAttFillCanvas::TAttFillCanvas(const char *name, const char *title, UInt_t ww, UInt_t wh) : TDialogCanvas(name,title,ww,wh) { //*-*-*-*-*-*-*-*-*-*-*-*AttFillCanvas constructor*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ======================== TVirtualPad *padsav = gPad; BuildStandardButtons(); //*-*- Fill styles choice buttons TGroupButton *test1 = 0; Float_t xlow, ylow; Float_t xmin = 0.03; Float_t xmax = 1-xmin; Float_t ymin = 0.12; Float_t ymax = 0.58; Float_t wpad = (xmax-xmin)/7; Float_t hpad = (ymax-ymin)/4; Int_t i,j; char command[64]; Int_t number = 0; for (j=0;j<4;j++) { ylow = ymin + j*hpad; for (i=0;i<7;i++) { if (number == 25) {number++; continue;} xlow = xmin + i*wpad; sprintf(command,"SetFillStyle(%d)",3001+number); test1 = new TGroupButton("Style","",command,xlow, ylow, xlow+0.9*wpad, ylow+0.9*hpad); if (number == 26) { //fill test1->SetBorderMode(-1); test1->SetFillColor(1); test1->SetMethod("SetFillStyle(1001)"); } else if (number == 27) { //hollow test1->SetMethod("SetFillStyle(0)"); test1->SetFillStyle(1001); test1->SetFillColor(10); } else { //pattern test1->SetFillColor(10); test1->SetFillStyle(3001+number); } test1->SetBorderSize(2); test1->Draw(); number++; } } //*-* draw colortable pads test1->DisplayColorTable("SetFillColor",0.05, 0.60, 0.90, 0.38); Update(); SetEditable(kFALSE); padsav->cd(); } //______________________________________________________________________________ TAttFillCanvas::~TAttFillCanvas() { //*-*-*-*-*-*-*-*-*-*-*AttFillCanvas default destructor*-*-*-*-*-*-*-*-*-*-*-* //*-* =============================== } //______________________________________________________________________________ void TAttFillCanvas::UpdateFillAttributes(Int_t col, Int_t sty) { //*-*-*-*-*-*-*-*-*-*-*Update object attributes*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ======================== TIter next(GetListOfPrimitives()); TGroupButton *button; char cmd[64]; fRefObject = gROOT->GetSelectedPrimitive(); fRefPad = (TPad*)gROOT->GetSelectedPad(); if (fRefObject) { sprintf(cmd,"attfill: %s",fRefObject->GetName()); SetTitle(cmd); } TObject *obj; while ((obj = next())) { if (!obj->InheritsFrom(TGroupButton::Class())) continue; button = (TGroupButton*)obj; if (button->GetBorderMode() < 0) { button->SetBorderMode(1); button->Modified(); } sprintf(cmd,"SetFillColor(%d)",col); if (!strcmp(button->GetTitle(),cmd)) button->SetBorderMode(-1); sprintf(cmd,"SetFillStyle(%d)",sty); if (!strcmp(button->GetTitle(),cmd)) button->SetBorderMode(-1); if (button->GetBorderMode() < 0) { button->Modified(); } } Update(); } <|endoftext|>
<commit_before>/* GPIO Example This example code is in the Public Domain (or CC0 licensed, at your option.) Unless required by applicable law or agreed to in writing, this software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/queue.h" #include "driver/gpio.h" #include "Arduino.h" /** * Brief: * Detect button clicks and longclicks. * * GPIO status: * GPIO0: input, pulled up, interrupt from rising edge and falling edge * * Test: * Press GPIO0, this triggers interrupt * */ #define GPIO_INPUT_IO_0 GPIO_NUM_0 #define GPIO_INPUT_PIN_SEL (1<<GPIO_INPUT_IO_0) #define ESP_INTR_FLAG_DEFAULT 0 int _debounceTicks = 50; // number of millisec that have to pass by before a click is assumed as safe. int _longTicks = 600; // number of millisec that have to pass by before a long button press is detected. int _holdDownTicks = 2000; // number of millisec after which we send a release typedef enum { BUTTON_NOCLICK, BUTTON_CLICK, BUTTON_LONGCLICK, // BUTTON_HOLDDOWN, BUTTON_RELEASE } ButtonClickType; static xQueueHandle gpio_evt_queue = NULL; static void IRAM_ATTR gpio_isr_handler(void* arg) { static uint32_t lastPressedTime = 0; gpio_num_t gpioNum = (gpio_num_t) reinterpret_cast<int>(arg); int level = gpio_get_level(gpioNum); uint32_t now = xTaskGetTickCount() * portTICK_PERIOD_MS; int pressDuration = now - lastPressedTime; ButtonClickType click = BUTTON_NOCLICK; // determine type of click when button is released if (level == 1 && lastPressedTime > 0){ if (pressDuration < _debounceTicks) { click = BUTTON_NOCLICK; } else if (pressDuration < _longTicks) { click = BUTTON_CLICK; } else if (pressDuration >= _holdDownTicks) { click = BUTTON_RELEASE; } else if (pressDuration >= _longTicks) { click = BUTTON_LONGCLICK; } } // remember time when button is pressed down else if (level == 0){ lastPressedTime = now; } if (click != BUTTON_NOCLICK){ // clear press memory lastPressedTime = 0; // send out event xQueueSendFromISR(gpio_evt_queue, &click, NULL); } } static void gpio_task_example(void* arg) { ButtonClickType newclick; for(;;) { if(xQueueReceive(gpio_evt_queue, &newclick, portMAX_DELAY)) { if (newclick == BUTTON_CLICK) { printf("--> CLICK\n"); } else if (newclick == BUTTON_LONGCLICK) { printf("--> LONG CLICK\n"); } else if (newclick == BUTTON_RELEASE) { printf("--> BUTTON RELEASED\n"); } else { printf("--> UNKNOWN BUTTON EVENT: %d\n", newclick); } } } } void setup() { gpio_config_t io_conf; //interrupt of rising edge io_conf.intr_type = GPIO_INTR_POSEDGE; //bit mask of the pins, use GPIO0 here io_conf.pin_bit_mask = GPIO_INPUT_PIN_SEL; //set as input mode io_conf.mode = GPIO_MODE_INPUT; //enable pull-up mode io_conf.pull_up_en = GPIO_PULLUP_ENABLE; gpio_config(&io_conf); //change gpio intrrupt type for one pin gpio_set_intr_type(GPIO_INPUT_IO_0, GPIO_INTR_ANYEDGE); //create a queue to handle gpio event from isr gpio_evt_queue = xQueueCreate(10, sizeof(ButtonClickType)); //start gpio task xTaskCreate(gpio_task_example, "gpio_task_example", 2048, NULL, 10, NULL); //install gpio isr service gpio_install_isr_service(ESP_INTR_FLAG_DEFAULT); //hook isr handler for specific gpio pin gpio_isr_handler_add(GPIO_INPUT_IO_0, gpio_isr_handler, (void*) GPIO_INPUT_IO_0); } void loop(){ delay(100000); }<commit_msg>minor<commit_after>/* GPIO Example This example code is in the Public Domain (or CC0 licensed, at your option.) Unless required by applicable law or agreed to in writing, this software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/queue.h" #include "driver/gpio.h" #include "Arduino.h" /** * Brief: * Detect button clicks and longclicks and send it to a queue. * * GPIO status: * GPIO0: input, pulled up, interrupt from rising edge and falling edge * * Test: * Press GPIO0, this triggers interrupt * */ #define GPIO_INPUT_IO_0 GPIO_NUM_0 #define GPIO_INPUT_PIN_SEL (1<<GPIO_INPUT_IO_0) #define ESP_INTR_FLAG_DEFAULT 0 int _debounceTicks = 50; // number of millisec that have to pass by before a click is assumed as safe. int _longTicks = 600; // number of millisec that have to pass by before a long button press is detected. int _holdDownTicks = 2000; // number of millisec after which we send a release typedef enum { BUTTON_NOCLICK, BUTTON_CLICK, BUTTON_LONGCLICK, // BUTTON_HOLDDOWN, BUTTON_RELEASE } ButtonClickType; static xQueueHandle gpio_evt_queue = NULL; static void IRAM_ATTR gpio_isr_handler(void* arg) { static uint32_t lastPressedTime = 0; gpio_num_t gpioNum = (gpio_num_t) reinterpret_cast<int>(arg); int level = gpio_get_level(gpioNum); uint32_t now = xTaskGetTickCount() * portTICK_PERIOD_MS; int pressDuration = now - lastPressedTime; ButtonClickType click = BUTTON_NOCLICK; // determine type of click when button is released if (level == 1 && lastPressedTime > 0){ if (pressDuration < _debounceTicks) { click = BUTTON_NOCLICK; } else if (pressDuration < _longTicks) { click = BUTTON_CLICK; } else if (pressDuration >= _holdDownTicks) { click = BUTTON_RELEASE; } else if (pressDuration >= _longTicks) { click = BUTTON_LONGCLICK; } } // remember time when button is pressed down else if (level == 0){ lastPressedTime = now; } if (click != BUTTON_NOCLICK){ // clear press memory lastPressedTime = 0; // send out event xQueueSendFromISR(gpio_evt_queue, &click, NULL); } } static void gpio_task_example(void* arg) { ButtonClickType newclick; for(;;) { if(xQueueReceive(gpio_evt_queue, &newclick, portMAX_DELAY)) { if (newclick == BUTTON_CLICK) { printf("--> CLICK\n"); } else if (newclick == BUTTON_LONGCLICK) { printf("--> LONG CLICK\n"); } else if (newclick == BUTTON_RELEASE) { printf("--> BUTTON RELEASED\n"); } else { printf("--> UNKNOWN BUTTON EVENT: %d\n", newclick); } } } } void setup() { gpio_config_t io_conf; //interrupt of rising edge io_conf.intr_type = GPIO_INTR_POSEDGE; //bit mask of the pins, use GPIO0 here io_conf.pin_bit_mask = GPIO_INPUT_PIN_SEL; //set as input mode io_conf.mode = GPIO_MODE_INPUT; //enable pull-up mode io_conf.pull_up_en = GPIO_PULLUP_ENABLE; gpio_config(&io_conf); //change gpio intrrupt type for one pin gpio_set_intr_type(GPIO_INPUT_IO_0, GPIO_INTR_ANYEDGE); //create a queue to handle gpio event from isr gpio_evt_queue = xQueueCreate(10, sizeof(ButtonClickType)); //start gpio task xTaskCreate(gpio_task_example, "gpio_task_example", 2048, NULL, 10, NULL); //install gpio isr service gpio_install_isr_service(ESP_INTR_FLAG_DEFAULT); //hook isr handler for specific gpio pin gpio_isr_handler_add(GPIO_INPUT_IO_0, gpio_isr_handler, (void*) GPIO_INPUT_IO_0); } void loop(){ delay(100000); }<|endoftext|>
<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved. #include "unittest/gtest.hpp" #include "arch/timing.hpp" #include "concurrency/pmap.hpp" #include "unittest/unittest_utils.hpp" #include "utils.hpp" namespace unittest { int wait_array[2][10] = { { 1, 1, 2, 3, 5, 13, 20, 30, 40, 8 }, { 5, 3, 2, 40, 30, 20, 8, 13, 1, 1 } }; void walk_wait_times(int i) { ticks_t t = get_ticks(); for (int j = 0; j < 10; ++j) { nap(wait_array[i][j]); const ticks_t t2 = get_ticks(); const int64_t diff = static_cast<int64_t>(t2) - static_cast<int64_t>(t); // Asserts that we're off by less than 25% of the sleep time // or two milliseconds, whichever is larger. ASSERT_LT(llabs(diff - wait_array[i][j] * MILLION), std::max(diff / 4, 2 * MILLION)); t = t2; } } TPTEST(TimerTest, TestApproximateWaitTimes) { pmap(2, walk_wait_times); } } // namespace unittest <commit_msg>Adds a missing include, over the shoulder by @larkost<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved. #include "unittest/gtest.hpp" #include <algorithm> #include "arch/timing.hpp" #include "concurrency/pmap.hpp" #include "unittest/unittest_utils.hpp" #include "utils.hpp" namespace unittest { int wait_array[2][10] = { { 1, 1, 2, 3, 5, 13, 20, 30, 40, 8 }, { 5, 3, 2, 40, 30, 20, 8, 13, 1, 1 } }; void walk_wait_times(int i) { ticks_t t = get_ticks(); for (int j = 0; j < 10; ++j) { nap(wait_array[i][j]); const ticks_t t2 = get_ticks(); const int64_t diff = static_cast<int64_t>(t2) - static_cast<int64_t>(t); // Asserts that we're off by less than 25% of the sleep time // or two milliseconds, whichever is larger. ASSERT_LT( llabs(diff - wait_array[i][j] * MILLION), std::max(diff / 4, static_cast<int64_t>(2 * MILLION))); t = t2; } } TPTEST(TimerTest, TestApproximateWaitTimes) { pmap(2, walk_wait_times); } } // namespace unittest <|endoftext|>
<commit_before>// rdoprocess_shape_terminate_MJ.cpp: implementation of the RPShapeTerminate_MJ class. // ////////////////////////////////////////////////////////////////////// #include "app/rdo_studio_mfc/rdo_process/proc2rdo/stdafx.h" #include "app/rdo_studio_mfc/rdo_process/proc2rdo/rdoprocess_shape_terminate.h" #include "app/rdo_studio_mfc/rdo_process/proc2rdo/rdoprocess_shape_terminate_dlg1.h" #include "app/rdo_studio_mfc/rdo_process/proc2rdo/rdoprocess_method_proc2rdo.h" #include "app/rdo_studio_mfc/src/application.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// RPShapeTerminateMJ::RPShapeTerminateMJ( RPObject* _parent ): RPShape_MJ( _parent, _T("Terminate") ) { m_term_inc=1; m_name=_T("Terminate"); // type ="block"; pa_src.push_back( rp::point(-50, 0) ); pa_src.push_back( rp::point(-25, -25) ); pa_src.push_back( rp::point(50, -25) ); pa_src.push_back( rp::point(50, 25) ); pa_src.push_back( rp::point(-25, 25) ); pa_src.push_back( rp::point(-50, 0) ); docks.push_back( new RPConnectorDock( this, RPConnectorDock::in, rp::point( -50, 0 ), 180, "transact" ) ); } RPShapeTerminateMJ::~RPShapeTerminateMJ() { } RPObject* RPShapeTerminateMJ::newObject( RPObject* parent ) { return new RPShapeTerminateMJ( parent ); } void RPShapeTerminateMJ::onLButtonDblClk( UINT nFlags, CPoint global_chart_pos ) { UNUSED(nFlags ); UNUSED(global_chart_pos); RPShapeTerminateDlg1_MJ dlg( AfxGetMainWnd(), this ); dlg.DoModal(); } void RPShapeTerminateMJ::generate() { m_pParams = rdo::Factory<RPShapeDataBlockTerminate>::create(m_name); m_pParams->setTermInc(m_term_inc); studioApp.studioGUI->sendMessage(kernel->simulator(), RDOThread::RT_PROCGUI_BLOCK_TERMINATE, m_pParams.get()); m_pParams = NULL; } void RPShapeTerminateMJ::saveToXML(REF(pugi::xml_node) parentNode) const { // <RShapeTerminateMJ/>: pugi::xml_node node = parentNode.append_child(getClassName().c_str()); // x : // 1) pugi::xml_attribute nameAttr = node.append_attribute("gname"); nameAttr.set_value(getName().c_str()); pugi::xml_attribute position_X = node.append_attribute("pos_X"); position_X.set_value(getCenter().x); pugi::xml_attribute position_Y = node.append_attribute("pos_Y"); position_Y.set_value(getCenter().y); pugi::xml_attribute scale_X = node.append_attribute("scale_X"); scale_X.set_value(getScaleX()); pugi::xml_attribute scale_Y = node.append_attribute("scale_Y"); scale_Y.set_value(getScaleY()); // 2) pugi::xml_attribute termAttr = node.append_attribute("m_term"); termAttr.set_value(m_term_inc); } void RPShapeTerminateMJ::loadFromXML(CREF(pugi::xml_node) node) { // "Terminate": for(pugi::xml_attribute attr = node.first_attribute(); attr; attr = attr.next_attribute()) { // xml- : // 1) Flowchart' if ( strcmp(attr.name(), "gname") == 0 ) setName (attr.value()); if ( strcmp(attr.name(), "pos_X") == 0 ) setX (attr.as_double()); if ( strcmp(attr.name(), "pos_Y") == 0 ) setY (attr.as_double()); if ( strcmp(attr.name(), "scale_X") == 0 ) setScaleX (attr.as_double()); if ( strcmp(attr.name(), "scale_Y") == 0 ) setScaleY (attr.as_double()); // 2) ( ) if ( strcmp(attr.name(), "m_term") == 0 ) m_term_inc = attr.as_int(); } } <commit_msg> - форматирование<commit_after>// rdoprocess_shape_terminate_MJ.cpp: implementation of the RPShapeTerminate_MJ class. // ////////////////////////////////////////////////////////////////////// #include "app/rdo_studio_mfc/rdo_process/proc2rdo/stdafx.h" #include "app/rdo_studio_mfc/rdo_process/proc2rdo/rdoprocess_shape_terminate.h" #include "app/rdo_studio_mfc/rdo_process/proc2rdo/rdoprocess_shape_terminate_dlg1.h" #include "app/rdo_studio_mfc/rdo_process/proc2rdo/rdoprocess_method_proc2rdo.h" #include "app/rdo_studio_mfc/src/application.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// RPShapeTerminateMJ::RPShapeTerminateMJ( RPObject* _parent ): RPShape_MJ( _parent, _T("Terminate") ) { m_term_inc=1; m_name=_T("Terminate"); // type ="block"; pa_src.push_back( rp::point(-50, 0) ); pa_src.push_back( rp::point(-25, -25) ); pa_src.push_back( rp::point(50, -25) ); pa_src.push_back( rp::point(50, 25) ); pa_src.push_back( rp::point(-25, 25) ); pa_src.push_back( rp::point(-50, 0) ); docks.push_back( new RPConnectorDock( this, RPConnectorDock::in, rp::point( -50, 0 ), 180, "transact" ) ); } RPShapeTerminateMJ::~RPShapeTerminateMJ() { } RPObject* RPShapeTerminateMJ::newObject( RPObject* parent ) { return new RPShapeTerminateMJ( parent ); } void RPShapeTerminateMJ::onLButtonDblClk( UINT nFlags, CPoint global_chart_pos ) { UNUSED(nFlags ); UNUSED(global_chart_pos); RPShapeTerminateDlg1_MJ dlg( AfxGetMainWnd(), this ); dlg.DoModal(); } void RPShapeTerminateMJ::generate() { m_pParams = rdo::Factory<RPShapeDataBlockTerminate>::create(m_name); m_pParams->setTermInc(m_term_inc); studioApp.studioGUI->sendMessage(kernel->simulator(), RDOThread::RT_PROCGUI_BLOCK_TERMINATE, m_pParams.get()); m_pParams = NULL; } void RPShapeTerminateMJ::saveToXML(REF(pugi::xml_node) parentNode) const { // <RShapeTerminateMJ/>: pugi::xml_node node = parentNode.append_child(getClassName().c_str()); // x : // 1) node.append_attribute(_T("gname")) .set_value(getName().c_str()); node.append_attribute(_T("pos_X")) .set_value(getCenter().x ); node.append_attribute(_T("pos_Y")) .set_value(getCenter().y ); node.append_attribute(_T("scale_X")) .set_value(getScaleX() ); node.append_attribute(_T("scale_Y")) .set_value(getScaleY() ); node.append_attribute(_T("terminateCounter")).set_value(m_term_inc ); } void RPShapeTerminateMJ::loadFromXML(CREF(pugi::xml_node) node) { // "Terminate": for (pugi::xml_attribute attr = node.first_attribute(); attr; attr = attr.next_attribute()) { tstring attrName = attr.name(); if (attrName == _T("gname")) { setName(attr.value()); } else if (attrName == _T("pos_X")) { setX(attr.as_double()); } else if (attrName == _T("terminateCounter")) { m_term_inc = attr.as_int(); } // xml- : // 1) Flowchart' if ( strcmp(attr.name(), "pos_Y") == 0 ) setY (attr.as_double()); if ( strcmp(attr.name(), "scale_X") == 0 ) setScaleX (attr.as_double()); if ( strcmp(attr.name(), "scale_Y") == 0 ) setScaleY (attr.as_double()); // 2) ( ) } } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/scom/preopchecks.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2018 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #include <devicefw/driverif.H> #include <errl/errlentry.H> #include <errl/errlmanager.H> #include <scom/scomreasoncodes.H> #include <scom/scomif.H> // Trace definition extern trace_desc_t* g_trac_scom; namespace SCOM { /** * @brief Common routine that verifies input parameters for *scom accesses. * * @param[in] i_opType Operation type, see driverif.H * @param[in] i_target Scom target * @param[in] i_buffer Read: Pointer to output data storage * Write: Pointer to input data storage * @param[in] i_buflen Input: size of io_buffer (in bytes) * @param[in] i_addr Address being accessed (Used for FFDC) * @return errlHndl_t */ errlHndl_t scomOpSanityCheck(const DeviceFW::OperationType i_opType, const TARGETING::Target* i_target, const void* i_buffer, const size_t i_buflen, const uint64_t i_addr, const size_t i_minbufsize) { errlHndl_t l_err = NULL; TRACDCOMP(g_trac_scom, INFO_MRK ">>scomOpSanityCheck: Entering Function"); do { // Verify address is not over 32-bits long if(0 != (i_addr & 0xFFFFFFFF00000000)) { TRACFCOMP(g_trac_scom, ERR_MRK "scomOpSanityCheck: Impossible address. i_addr=0x%.16X", i_addr); /*@ * @errortype * @moduleid SCOM_OP_SANITY_CHECK * @reasoncode SCOM_INVALID_ADDR * @userdata1 Scom address * @userdata2 Scom target * @devdesc The provided address is over 32 bits long * which makes it invalid. */ l_err = new ERRORLOG::ErrlEntry( ERRORLOG::ERRL_SEV_UNRECOVERABLE, SCOM_OP_SANITY_CHECK, SCOM_INVALID_ADDR, i_addr, get_huid(i_target)); l_err->addProcedureCallout(HWAS::EPUB_PRC_HB_CODE, HWAS::SRCI_PRIORITY_HIGH); break; } // Verify data buffer if ( (i_buflen < i_minbufsize) || (i_buffer == NULL) ) { TRACFCOMP(g_trac_scom, ERR_MRK "scomOpSanityCheck: Invalid buffer. i_buflen=0x%X", i_buflen); /*@ * @errortype * @moduleid SCOM_OP_SANITY_CHECK * @reasoncode SCOM_INVALID_DATA_BUFFER * @userdata1[0:31] Buffer size * @userdata1[32:63] Minimum allowed buffer size * @userdata2 Scom address * @devdesc Buffer size is less than allowed * or NULL data buffer */ l_err = new ERRORLOG::ErrlEntry( ERRORLOG::ERRL_SEV_UNRECOVERABLE, SCOM_OP_SANITY_CHECK, SCOM_INVALID_DATA_BUFFER, TWO_UINT32_TO_UINT64( i_buflen, i_minbufsize), i_addr); l_err->addProcedureCallout(HWAS::EPUB_PRC_HB_CODE, HWAS::SRCI_PRIORITY_HIGH); break; } // Verify OP type if ( (i_opType != DeviceFW::READ) && (i_opType != DeviceFW::WRITE) ) { TRACFCOMP(g_trac_scom, ERR_MRK "scomOpSanityCheck: Invalid opType. i_opType=0x%X", i_opType); /*@ * @errortype * @moduleid SCOM_OP_SANITY_CHECK * @reasoncode SCOM_INVALID_OP_TYPE * @userdata1 Operation type * @userdata2 Scom address * @devdesc Scom invalid operation type */ l_err = new ERRORLOG::ErrlEntry( ERRORLOG::ERRL_SEV_UNRECOVERABLE, SCOM_OP_SANITY_CHECK, SCOM_INVALID_OP_TYPE, i_opType, i_addr); l_err->addProcedureCallout(HWAS::EPUB_PRC_HB_CODE, HWAS::SRCI_PRIORITY_HIGH); break; } } while(0); return l_err; } } // end namespace SCOM <commit_msg>Fix indirect scoms at runtime under Opal<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/scom/preopchecks.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2018 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #include <devicefw/driverif.H> #include <errl/errlentry.H> #include <errl/errlmanager.H> #include <scom/scomreasoncodes.H> #include <scom/scomif.H> // Trace definition extern trace_desc_t* g_trac_scom; namespace SCOM { /** * @brief Common routine that verifies input parameters for *scom accesses. * * @param[in] i_opType Operation type, see driverif.H * @param[in] i_target Scom target * @param[in] i_buffer Read: Pointer to output data storage * Write: Pointer to input data storage * @param[in] i_buflen Input: size of io_buffer (in bytes) * @param[in] i_addr Address being accessed (Used for FFDC) * @return errlHndl_t */ errlHndl_t scomOpSanityCheck(const DeviceFW::OperationType i_opType, const TARGETING::Target* i_target, const void* i_buffer, const size_t i_buflen, const uint64_t i_addr, const size_t i_minbufsize) { errlHndl_t l_err = NULL; TRACDCOMP(g_trac_scom, INFO_MRK ">>scomOpSanityCheck: Entering Function"); do { // In HOSTBOOT_RUNTIME we rely on OPAL to perform indirect scoms, // but PHYP wants us to do it ourselves. Therefore we need to // allow 64-bit addresses to flow through in OPAL/Sapphire mode. bool l_allowIndirectScoms = false; #ifdef __HOSTBOOT_RUNTIME if( TARGETING::is_sapphire_load() ) { l_allowIndirectScoms = true; } #endif // __HOSTBOOT_RUNTIME // Verify address is not over 32-bits long if( (0 != (i_addr & 0xFFFFFFFF00000000)) && (!l_allowIndirectScoms) ) { TRACFCOMP(g_trac_scom, ERR_MRK "scomOpSanityCheck: Impossible address. i_addr=0x%.16X", i_addr); /*@ * @errortype * @moduleid SCOM_OP_SANITY_CHECK * @reasoncode SCOM_INVALID_ADDR * @userdata1 Scom address * @userdata2 Scom target * @devdesc The provided address is over 32 bits long * which makes it invalid. */ l_err = new ERRORLOG::ErrlEntry( ERRORLOG::ERRL_SEV_UNRECOVERABLE, SCOM_OP_SANITY_CHECK, SCOM_INVALID_ADDR, i_addr, get_huid(i_target)); l_err->addProcedureCallout(HWAS::EPUB_PRC_HB_CODE, HWAS::SRCI_PRIORITY_HIGH); break; } // Verify data buffer if ( (i_buflen < i_minbufsize) || (i_buffer == NULL) ) { TRACFCOMP(g_trac_scom, ERR_MRK "scomOpSanityCheck: Invalid buffer. i_buflen=0x%X", i_buflen); /*@ * @errortype * @moduleid SCOM_OP_SANITY_CHECK * @reasoncode SCOM_INVALID_DATA_BUFFER * @userdata1[0:31] Buffer size * @userdata1[32:63] Minimum allowed buffer size * @userdata2 Scom address * @devdesc Buffer size is less than allowed * or NULL data buffer */ l_err = new ERRORLOG::ErrlEntry( ERRORLOG::ERRL_SEV_UNRECOVERABLE, SCOM_OP_SANITY_CHECK, SCOM_INVALID_DATA_BUFFER, TWO_UINT32_TO_UINT64( i_buflen, i_minbufsize), i_addr); l_err->addProcedureCallout(HWAS::EPUB_PRC_HB_CODE, HWAS::SRCI_PRIORITY_HIGH); break; } // Verify OP type if ( (i_opType != DeviceFW::READ) && (i_opType != DeviceFW::WRITE) ) { TRACFCOMP(g_trac_scom, ERR_MRK "scomOpSanityCheck: Invalid opType. i_opType=0x%X", i_opType); /*@ * @errortype * @moduleid SCOM_OP_SANITY_CHECK * @reasoncode SCOM_INVALID_OP_TYPE * @userdata1 Operation type * @userdata2 Scom address * @devdesc Scom invalid operation type */ l_err = new ERRORLOG::ErrlEntry( ERRORLOG::ERRL_SEV_UNRECOVERABLE, SCOM_OP_SANITY_CHECK, SCOM_INVALID_OP_TYPE, i_opType, i_addr); l_err->addProcedureCallout(HWAS::EPUB_PRC_HB_CODE, HWAS::SRCI_PRIORITY_HIGH); break; } } while(0); return l_err; } } // end namespace SCOM <|endoftext|>
<commit_before>#pragma once #include "core_configuration/core_configuration.hpp" #include "manipulator/manipulator_factory.hpp" #include "manipulator/manipulator_manager.hpp" #include "manipulator/manipulators/basic/basic.hpp" namespace krbn { namespace grabber { namespace device_grabber_details { class fn_function_keys_manipulator_manager final { public: fn_function_keys_manipulator_manager(void) { manipulator_manager_ = std::make_shared<manipulator::manipulator_manager>(); } std::shared_ptr<manipulator::manipulator_manager> get_manipulator_manager(void) const { return manipulator_manager_; } void update(const core_configuration::details::profile& profile, const pqrs::osx::system_preferences::properties& system_preferences_properties) { manipulator_manager_->invalidate_manipulators(); auto from_mandatory_modifiers = nlohmann::json::array(); auto from_optional_modifiers = nlohmann::json::array(); from_optional_modifiers.push_back("any"); auto to_modifiers = nlohmann::json::array(); if (system_preferences_properties.get_use_fkeys_as_standard_function_keys()) { // f1 -> f1 // fn+f1 -> display_brightness_decrement from_mandatory_modifiers.push_back("fn"); to_modifiers.push_back("fn"); } else { // f1 -> display_brightness_decrement // fn+f1 -> f1 // fn+f1 ... fn+f12 -> f1 .. f12 for (int i = 1; i <= 12; ++i) { auto from_json = nlohmann::json::object({ {"key_code", fmt::format("f{0}", i)}, {"modifiers", nlohmann::json::object({ {"mandatory", nlohmann::json::array({"fn"})}, {"optional", nlohmann::json::array({"any"})}, })}, }); auto to_json = nlohmann::json::object({ {"key_code", fmt::format("f{0}", i)}, {"modifiers", nlohmann::json::array({"fn"})}, }); try { auto manipulator = std::make_shared<manipulator::manipulators::basic::basic>(manipulator::manipulators::basic::from_event_definition(from_json), manipulator::to_event_definition(to_json)); manipulator_manager_->push_back_manipulator(std::shared_ptr<manipulator::manipulators::base>(manipulator)); } catch (const pqrs::json::unmarshal_error& e) { logger::get_logger()->error(fmt::format("karabiner.json error: {0}", e.what())); } catch (const std::exception& e) { logger::get_logger()->error(e.what()); } } } // from_modifiers+f1 -> display_brightness_decrement ... for (const auto& device : profile.get_devices()) { for (const auto& pair : device.get_fn_function_keys().get_pairs()) { try { if (auto m = make_manipulator(pair, from_mandatory_modifiers, from_optional_modifiers, to_modifiers)) { auto c = manipulator::manipulator_factory::make_device_if_condition(device); m->push_back_condition(c); manipulator_manager_->push_back_manipulator(m); } } catch (const pqrs::json::unmarshal_error& e) { logger::get_logger()->error(fmt::format("karabiner.json error: {0}", e.what())); } catch (const std::exception& e) { logger::get_logger()->error(e.what()); } } } for (const auto& pair : profile.get_fn_function_keys().get_pairs()) { if (auto m = make_manipulator(pair, from_mandatory_modifiers, from_optional_modifiers, to_modifiers)) { manipulator_manager_->push_back_manipulator(m); } } // fn+return_or_enter -> keypad_enter ... { nlohmann::json data = nlohmann::json::array(); data.push_back(nlohmann::json::object({ {"from", nlohmann::json::object({{"key_code", "return_or_enter"}})}, {"to", nlohmann::json::object({{"key_code", "keypad_enter"}})}, })); data.push_back(nlohmann::json::object({ {"from", nlohmann::json::object({{"key_code", "delete_or_backspace"}})}, {"to", nlohmann::json::object({{"key_code", "delete_forward"}})}, })); data.push_back(nlohmann::json::object({ {"from", nlohmann::json::object({{"key_code", "right_arrow"}})}, {"to", nlohmann::json::object({{"key_code", "end"}})}, })); data.push_back(nlohmann::json::object({ {"from", nlohmann::json::object({{"key_code", "left_arrow"}})}, {"to", nlohmann::json::object({{"key_code", "home"}})}, })); data.push_back(nlohmann::json::object({ {"from", nlohmann::json::object({{"key_code", "down_arrow"}})}, {"to", nlohmann::json::object({{"key_code", "page_down"}})}, })); data.push_back(nlohmann::json::object({ {"from", nlohmann::json::object({{"key_code", "up_arrow"}})}, {"to", nlohmann::json::object({{"key_code", "page_up"}})}, })); for (const auto& d : data) { auto from_json = d["from"]; from_json["modifiers"]["mandatory"] = nlohmann::json::array({"fn"}); from_json["modifiers"]["optional"] = nlohmann::json::array({"any"}); auto to_json = d["to"]; to_json["modifiers"] = nlohmann::json::array({"fn"}); try { auto manipulator = std::make_shared<manipulator::manipulators::basic::basic>(manipulator::manipulators::basic::from_event_definition(from_json), manipulator::to_event_definition(to_json)); manipulator_manager_->push_back_manipulator(std::shared_ptr<manipulator::manipulators::base>(manipulator)); } catch (const pqrs::json::unmarshal_error& e) { logger::get_logger()->error(fmt::format("karabiner.json error: {0}", e.what())); } catch (const std::exception& e) { logger::get_logger()->error(e.what()); } } } } private: std::shared_ptr<manipulator::manipulators::base> make_manipulator(const std::pair<std::string, std::string>& pair, const nlohmann::json& from_mandatory_modifiers, const nlohmann::json& from_optional_modifiers, const nlohmann::json& to_modifiers) const { try { auto from_json = nlohmann::json::parse(pair.first); if (from_json.empty()) { return nullptr; } from_json["modifiers"]["mandatory"] = from_mandatory_modifiers; from_json["modifiers"]["optional"] = from_optional_modifiers; auto to_json = nlohmann::json::parse(pair.second); if (to_json.empty()) { return nullptr; } to_json["modifiers"] = to_modifiers; return std::make_shared<manipulator::manipulators::basic::basic>(manipulator::manipulators::basic::from_event_definition(from_json), manipulator::to_event_definition(to_json)); } catch (const pqrs::json::unmarshal_error& e) { logger::get_logger()->error(fmt::format("karabiner.json error: {0}", e.what())); } catch (const std::exception& e) { logger::get_logger()->error(e.what()); } return nullptr; } std::shared_ptr<manipulator::manipulator_manager> manipulator_manager_; }; } // namespace device_grabber_details } // namespace grabber } // namespace krbn <commit_msg>ignore fn function key manipulators if the key is already changed<commit_after>#pragma once #include "core_configuration/core_configuration.hpp" #include "manipulator/manipulator_factory.hpp" #include "manipulator/manipulator_manager.hpp" #include "manipulator/manipulators/basic/basic.hpp" namespace krbn { namespace grabber { namespace device_grabber_details { class fn_function_keys_manipulator_manager final { public: fn_function_keys_manipulator_manager(void) { manipulator_manager_ = std::make_shared<manipulator::manipulator_manager>(); } std::shared_ptr<manipulator::manipulator_manager> get_manipulator_manager(void) const { return manipulator_manager_; } void update(const core_configuration::details::profile& profile, const pqrs::osx::system_preferences::properties& system_preferences_properties) { manipulator_manager_->invalidate_manipulators(); auto from_mandatory_modifiers = nlohmann::json::array(); auto from_optional_modifiers = nlohmann::json::array(); from_optional_modifiers.push_back("any"); auto to_modifiers = nlohmann::json::array(); if (system_preferences_properties.get_use_fkeys_as_standard_function_keys()) { // f1 -> f1 // fn+f1 -> display_brightness_decrement from_mandatory_modifiers.push_back("fn"); to_modifiers.push_back("fn"); } else { // f1 -> display_brightness_decrement // fn+f1 -> f1 // fn+f1 ... fn+f12 -> f1 .. f12 for (int i = 1; i <= 12; ++i) { auto from_json = nlohmann::json::object({ {"key_code", fmt::format("f{0}", i)}, {"modifiers", nlohmann::json::object({ {"mandatory", nlohmann::json::array({"fn"})}, {"optional", nlohmann::json::array({"any"})}, })}, }); auto to_json = nlohmann::json::object({ {"key_code", fmt::format("f{0}", i)}, {"modifiers", nlohmann::json::array({"fn"})}, }); try { auto manipulator = std::make_shared<manipulator::manipulators::basic::basic>(manipulator::manipulators::basic::from_event_definition(from_json), manipulator::to_event_definition(to_json)); manipulator_manager_->push_back_manipulator(std::shared_ptr<manipulator::manipulators::base>(manipulator)); } catch (const pqrs::json::unmarshal_error& e) { logger::get_logger()->error(fmt::format("karabiner.json error: {0}", e.what())); } catch (const std::exception& e) { logger::get_logger()->error(e.what()); } } } // from_modifiers+f1 -> display_brightness_decrement ... for (const auto& device : profile.get_devices()) { for (const auto& pair : device.get_fn_function_keys().get_pairs()) { try { if (auto m = make_manipulator(pair, from_mandatory_modifiers, from_optional_modifiers, to_modifiers)) { m->push_back_condition(manipulator::manipulator_factory::make_event_changed_if_condition(false)); auto c = manipulator::manipulator_factory::make_device_if_condition(device); m->push_back_condition(c); manipulator_manager_->push_back_manipulator(m); } } catch (const pqrs::json::unmarshal_error& e) { logger::get_logger()->error(fmt::format("karabiner.json error: {0}", e.what())); } catch (const std::exception& e) { logger::get_logger()->error(e.what()); } } } for (const auto& pair : profile.get_fn_function_keys().get_pairs()) { if (auto m = make_manipulator(pair, from_mandatory_modifiers, from_optional_modifiers, to_modifiers)) { m->push_back_condition(manipulator::manipulator_factory::make_event_changed_if_condition(false)); manipulator_manager_->push_back_manipulator(m); } } // fn+return_or_enter -> keypad_enter ... { nlohmann::json data = nlohmann::json::array(); data.push_back(nlohmann::json::object({ {"from", nlohmann::json::object({{"key_code", "return_or_enter"}})}, {"to", nlohmann::json::object({{"key_code", "keypad_enter"}})}, })); data.push_back(nlohmann::json::object({ {"from", nlohmann::json::object({{"key_code", "delete_or_backspace"}})}, {"to", nlohmann::json::object({{"key_code", "delete_forward"}})}, })); data.push_back(nlohmann::json::object({ {"from", nlohmann::json::object({{"key_code", "right_arrow"}})}, {"to", nlohmann::json::object({{"key_code", "end"}})}, })); data.push_back(nlohmann::json::object({ {"from", nlohmann::json::object({{"key_code", "left_arrow"}})}, {"to", nlohmann::json::object({{"key_code", "home"}})}, })); data.push_back(nlohmann::json::object({ {"from", nlohmann::json::object({{"key_code", "down_arrow"}})}, {"to", nlohmann::json::object({{"key_code", "page_down"}})}, })); data.push_back(nlohmann::json::object({ {"from", nlohmann::json::object({{"key_code", "up_arrow"}})}, {"to", nlohmann::json::object({{"key_code", "page_up"}})}, })); for (const auto& d : data) { auto from_json = d["from"]; from_json["modifiers"]["mandatory"] = nlohmann::json::array({"fn"}); from_json["modifiers"]["optional"] = nlohmann::json::array({"any"}); auto to_json = d["to"]; to_json["modifiers"] = nlohmann::json::array({"fn"}); try { auto manipulator = std::make_shared<manipulator::manipulators::basic::basic>(manipulator::manipulators::basic::from_event_definition(from_json), manipulator::to_event_definition(to_json)); manipulator_manager_->push_back_manipulator(std::shared_ptr<manipulator::manipulators::base>(manipulator)); } catch (const pqrs::json::unmarshal_error& e) { logger::get_logger()->error(fmt::format("karabiner.json error: {0}", e.what())); } catch (const std::exception& e) { logger::get_logger()->error(e.what()); } } } } private: std::shared_ptr<manipulator::manipulators::base> make_manipulator(const std::pair<std::string, std::string>& pair, const nlohmann::json& from_mandatory_modifiers, const nlohmann::json& from_optional_modifiers, const nlohmann::json& to_modifiers) const { try { auto from_json = nlohmann::json::parse(pair.first); if (from_json.empty()) { return nullptr; } from_json["modifiers"]["mandatory"] = from_mandatory_modifiers; from_json["modifiers"]["optional"] = from_optional_modifiers; auto to_json = nlohmann::json::parse(pair.second); if (to_json.empty()) { return nullptr; } to_json["modifiers"] = to_modifiers; return std::make_shared<manipulator::manipulators::basic::basic>(manipulator::manipulators::basic::from_event_definition(from_json), manipulator::to_event_definition(to_json)); } catch (const pqrs::json::unmarshal_error& e) { logger::get_logger()->error(fmt::format("karabiner.json error: {0}", e.what())); } catch (const std::exception& e) { logger::get_logger()->error(e.what()); } return nullptr; } std::shared_ptr<manipulator::manipulator_manager> manipulator_manager_; }; } // namespace device_grabber_details } // namespace grabber } // namespace krbn <|endoftext|>
<commit_before>#ifdef _WIN32 #include <io.h> #else #include <unistd.h> #endif #include "context.hpp" #include "sass_functions.h" extern "C" { using namespace std; // Struct to hold custom function callback struct Sass_C_Function_Descriptor { const char* signature; Sass_C_Function function; void* cookie; }; Sass_C_Function_List sass_make_function_list(size_t length) { return (Sass_C_Function_List) calloc(length + 1, sizeof(Sass_C_Function_Callback)); } Sass_C_Function_Callback sass_make_function(const char* signature, Sass_C_Function function, void* cookie) { Sass_C_Function_Callback cb = (Sass_C_Function_Callback) calloc(1, sizeof(Sass_C_Function_Descriptor)); if (cb == 0) return 0; cb->signature = signature; cb->function = function; cb->cookie = cookie; return cb; } // Setters and getters for callbacks on function lists Sass_C_Function_Callback sass_function_get_list_entry(Sass_C_Function_List* list, size_t pos) { return *list[pos]; } void sass_function_set_list_entry(Sass_C_Function_List* list, Sass_C_Function_Callback cb, size_t pos) { *list[pos] = cb; } const char* sass_function_get_signature(Sass_C_Function_Callback fn) { return fn->signature; } Sass_C_Function sass_function_get_function(Sass_C_Function_Callback fn) { return fn->function; } void* sass_function_get_cookie(Sass_C_Function_Callback fn) { return fn->cookie; } // External import entry struct Sass_Import { char* path; char* base; char* source; char* srcmap; }; // Struct to hold importer callback struct Sass_C_Import_Descriptor { Sass_C_Import_Fn function; void* cookie; }; Sass_C_Import_Callback sass_make_importer(Sass_C_Import_Fn function, void* cookie) { Sass_C_Import_Callback cb = (Sass_C_Import_Callback) calloc(1, sizeof(Sass_C_Import_Descriptor)); if (cb == 0) return 0; cb->function = function; cb->cookie = cookie; return cb; } Sass_C_Import_Fn sass_import_get_function(Sass_C_Import_Callback fn) { return fn->function; } void* sass_import_get_cookie(Sass_C_Import_Callback fn) { return fn->cookie; } // Creator for sass custom importer return argument list struct Sass_Import** sass_make_import_list(size_t length) { return (Sass_Import**) calloc(length + 1, sizeof(Sass_Import*)); } // Creator for a single import entry returned by the custom importer inside the list // We take ownership of the memory for source and srcmap (freed when context is destroyd) struct Sass_Import* sass_make_import(const char* path, const char* base, char* source, char* srcmap) { Sass_Import* v = (Sass_Import*) calloc(1, sizeof(Sass_Import)); if (v == 0) return 0; v->path = strdup(path); v->base = strdup(base); v->source = source; v->srcmap = srcmap; return v; } // Older style, but somehow still valid - keep around or deprecate? struct Sass_Import* sass_make_import_entry(const char* path, char* source, char* srcmap) { return sass_make_import(path, path, source, srcmap); } // Setters and getters for entries on the import list void sass_import_set_list_entry(struct Sass_Import** list, size_t idx, struct Sass_Import* entry) { list[idx] = entry; } struct Sass_Import* sass_import_get_list_entry(struct Sass_Import** list, size_t idx) { return list[idx]; } // Deallocator for the allocated memory void sass_delete_import_list(struct Sass_Import** list) { struct Sass_Import** it = list; if (list == 0) return; while(*list) { sass_delete_import(*list); ++list; } free(it); } // Just in case we have some stray import structs void sass_delete_import(struct Sass_Import* import) { free(import->path); free(import->base); free(import->source); free(import->srcmap); free(import); } // Getter for import entry const char* sass_import_get_path(struct Sass_Import* entry) { return entry->path; } const char* sass_import_get_base(struct Sass_Import* entry) { return entry->base; } const char* sass_import_get_source(struct Sass_Import* entry) { return entry->source; } const char* sass_import_get_srcmap(struct Sass_Import* entry) { return entry->srcmap; } // Explicit functions to take ownership of the memory // Resets our own property since we do not know if it is still alive char* sass_import_take_source(struct Sass_Import* entry) { char* ptr = entry->source; entry->source = 0; return ptr; } char* sass_import_take_srcmap(struct Sass_Import* entry) { char* ptr = entry->srcmap; entry->srcmap = 0; return ptr; } } <commit_msg>Fix bug with custom importer and undefined behavior<commit_after>#ifdef _WIN32 #include <io.h> #else #include <unistd.h> #endif #include "context.hpp" #include "sass_functions.h" extern "C" { using namespace std; // Struct to hold custom function callback struct Sass_C_Function_Descriptor { const char* signature; Sass_C_Function function; void* cookie; }; Sass_C_Function_List sass_make_function_list(size_t length) { return (Sass_C_Function_List) calloc(length + 1, sizeof(Sass_C_Function_Callback)); } Sass_C_Function_Callback sass_make_function(const char* signature, Sass_C_Function function, void* cookie) { Sass_C_Function_Callback cb = (Sass_C_Function_Callback) calloc(1, sizeof(Sass_C_Function_Descriptor)); if (cb == 0) return 0; cb->signature = signature; cb->function = function; cb->cookie = cookie; return cb; } // Setters and getters for callbacks on function lists Sass_C_Function_Callback sass_function_get_list_entry(Sass_C_Function_List* list, size_t pos) { return *list[pos]; } void sass_function_set_list_entry(Sass_C_Function_List* list, Sass_C_Function_Callback cb, size_t pos) { *list[pos] = cb; } const char* sass_function_get_signature(Sass_C_Function_Callback fn) { return fn->signature; } Sass_C_Function sass_function_get_function(Sass_C_Function_Callback fn) { return fn->function; } void* sass_function_get_cookie(Sass_C_Function_Callback fn) { return fn->cookie; } // External import entry struct Sass_Import { char* path; char* base; char* source; char* srcmap; }; // Struct to hold importer callback struct Sass_C_Import_Descriptor { Sass_C_Import_Fn function; void* cookie; }; Sass_C_Import_Callback sass_make_importer(Sass_C_Import_Fn function, void* cookie) { Sass_C_Import_Callback cb = (Sass_C_Import_Callback) calloc(1, sizeof(Sass_C_Import_Descriptor)); if (cb == 0) return 0; cb->function = function; cb->cookie = cookie; return cb; } Sass_C_Import_Fn sass_import_get_function(Sass_C_Import_Callback fn) { return fn->function; } void* sass_import_get_cookie(Sass_C_Import_Callback fn) { return fn->cookie; } // Creator for sass custom importer return argument list struct Sass_Import** sass_make_import_list(size_t length) { return (Sass_Import**) calloc(length + 1, sizeof(Sass_Import*)); } // Creator for a single import entry returned by the custom importer inside the list // We take ownership of the memory for source and srcmap (freed when context is destroyd) struct Sass_Import* sass_make_import(const char* path, const char* base, char* source, char* srcmap) { Sass_Import* v = (Sass_Import*) calloc(1, sizeof(Sass_Import)); if (v == 0) return 0; v->path = path ? strdup(path) : 0; v->base = base ? strdup(base) : 0; v->source = source; v->srcmap = srcmap; return v; } // Older style, but somehow still valid - keep around or deprecate? struct Sass_Import* sass_make_import_entry(const char* path, char* source, char* srcmap) { return sass_make_import(path, path, source, srcmap); } // Setters and getters for entries on the import list void sass_import_set_list_entry(struct Sass_Import** list, size_t idx, struct Sass_Import* entry) { list[idx] = entry; } struct Sass_Import* sass_import_get_list_entry(struct Sass_Import** list, size_t idx) { return list[idx]; } // Deallocator for the allocated memory void sass_delete_import_list(struct Sass_Import** list) { struct Sass_Import** it = list; if (list == 0) return; while(*list) { sass_delete_import(*list); ++list; } free(it); } // Just in case we have some stray import structs void sass_delete_import(struct Sass_Import* import) { free(import->path); free(import->base); free(import->source); free(import->srcmap); free(import); } // Getter for import entry const char* sass_import_get_path(struct Sass_Import* entry) { return entry->path; } const char* sass_import_get_base(struct Sass_Import* entry) { return entry->base; } const char* sass_import_get_source(struct Sass_Import* entry) { return entry->source; } const char* sass_import_get_srcmap(struct Sass_Import* entry) { return entry->srcmap; } // Explicit functions to take ownership of the memory // Resets our own property since we do not know if it is still alive char* sass_import_take_source(struct Sass_Import* entry) { char* ptr = entry->source; entry->source = 0; return ptr; } char* sass_import_take_srcmap(struct Sass_Import* entry) { char* ptr = entry->srcmap; entry->srcmap = 0; return ptr; } } <|endoftext|>
<commit_before>// @(#)root/test:$Id$ // Author: Rene Brun 19/01/97 //////////////////////////////////////////////////////////////////////// // // A simple example with a ROOT tree // ================================= // // This program creates : // - a ROOT file // - a tree // Additional arguments can be passed to the program to control the flow // of execution. (see comments describing the arguments in the code). // Event nevent comp split fill // All arguments are optional. Default is: // Event 400 1 1 1 // // In this example, the tree consists of one single "super branch" // The statement ***tree->Branch("event", &event, 64000,split);*** below // will parse the structure described in Event.h and will make // a new branch for each data member of the class if split is set to 1. // - 9 branches corresponding to the basic types fType, fNtrack,fNseg, // fNvertex,fFlag,fTemperature,fMeasures,fMatrix,fClosesDistance. // - 3 branches corresponding to the members of the subobject EventHeader. // - one branch for each data member of the class Track of TClonesArray. // - one branch for the TRefArray of high Pt tracks // - one branch for the TRefArray of muon tracks // - one branch for the reference pointer to the last track // - one branch for the object fH (histogram of class TH1F). // // if split = 0 only one single branch is created and the complete event // is serialized in one single buffer. // if split = -2 the event is split using the old TBranchObject mechanism // if split = -1 the event is streamed using the old TBranchObject mechanism // if split > 0 the event is split using the new TBranchElement mechanism. // if split > 90 the branch buffer sizes are optimized once 10 MBytes written to the file // // if comp = 0 no compression at all. // if comp = 1 event is compressed. // if comp = 2 same as 1. In addition branches with floats in the TClonesArray // are also compressed. // The 4th argument fill can be set to 0 if one wants to time // the percentage of time spent in creating the event structure and // not write the event in the file. // In this example, one loops over nevent events. // The branch "event" is created at the first event. // The branch address is set for all other events. // For each event, the event header is filled and ntrack tracks // are generated and added to the TClonesArray list. // For each event the event histogram is saved as well as the list // of all tracks. // // The two TRefArray contain only references to the original tracks owned by // the TClonesArray fTracks. // // The number of events can be given as the first argument to the program. // By default 400 events are generated. // The compression option can be activated/deactivated via the second argument. // // ---Running/Linking instructions---- // This program consists of the following files and procedures. // - Event.h event class description // - Event.C event class implementation // - MainEvent.C the main program to demo this class might be used (this file) // - EventCint.C the CINT dictionary for the event and Track classes // this file is automatically generated by rootcint (see Makefile), // when the class definition in Event.h is modified. // // ---Analyzing the Event.root file with the interactive root // example of a simple session // Root > TFile f("Event.root") // Root > T.Draw("fNtrack") //histogram the number of tracks per event // Root > T.Draw("fPx") //histogram fPx for all tracks in all events // Root > T.Draw("fXfirst:fYfirst","fNtrack>600") // //scatter-plot for x versus y of first point of each track // Root > T.Draw("fH.GetRMS()") //histogram of the RMS of the event histogram // // Look also in the same directory at the following macros: // - eventa.C an example how to read the tree // - eventb.C how to read events conditionally // //////////////////////////////////////////////////////////////////////// #include <stdlib.h> #include "Riostream.h" #include "TROOT.h" #include "TFile.h" #include "TNetFile.h" #include "TRandom.h" #include "TTree.h" #include "TTreeCache.h" #include "TBranch.h" #include "TClonesArray.h" #include "TStopwatch.h" #include "TTreeCacheUnzip.h" #include "Event.h" //______________________________________________________________________________ int main(int argc, char **argv) { Int_t nevent = 400; // by default create 400 events Int_t comp = 1; // by default file is compressed Int_t split = 1; // by default, split Event in sub branches Int_t write = 1; // by default the tree is filled Int_t hfill = 0; // by default histograms are not filled Int_t read = 0; Int_t arg4 = 1; Int_t arg5 = 600; //default number of tracks per event Int_t netf = 0; Int_t punzip = 0; if (argc > 1) nevent = atoi(argv[1]); if (argc > 2) comp = atoi(argv[2]); if (argc > 3) split = atoi(argv[3]); if (argc > 4) arg4 = atoi(argv[4]); if (argc > 5) arg5 = atoi(argv[5]); if (arg4 == 0) { write = 0; hfill = 0; read = 1;} if (arg4 == 1) { write = 1; hfill = 0;} if (arg4 == 2) { write = 0; hfill = 0;} if (arg4 == 10) { write = 0; hfill = 1;} if (arg4 == 11) { write = 1; hfill = 1;} if (arg4 == 20) { write = 0; read = 1;} //read sequential if (arg4 == 21) { write = 0; read = 1; punzip = 1;} //read sequential + parallel unzipping if (arg4 == 25) { write = 0; read = 2;} //read random if (arg4 >= 30) { netf = 1; } //use TNetFile if (arg4 == 30) { write = 0; read = 1;} //netfile + read sequential if (arg4 == 35) { write = 0; read = 2;} //netfile + read random if (arg4 == 36) { write = 1; } //netfile + write sequential Int_t branchStyle = 1; //new style by default if (split < 0) {branchStyle = 0; split = -1-split;} TFile *hfile; TTree *tree; Event *event = 0; // Fill event, header and tracks with some random numbers // Create a timer object to benchmark this loop TStopwatch timer; timer.Start(); Long64_t nb = 0; Int_t ev; Int_t bufsize; Double_t told = 0; Double_t tnew = 0; Int_t printev = 100; if (arg5 < 100) printev = 1000; if (arg5 < 10) printev = 10000; //Authorize Trees up to 2 Terabytes (if the system can do it) TTree::SetMaxTreeSize(1000*Long64_t(2000000000)); // Read case if (read) { if (netf) { hfile = new TNetFile("root://localhost/root/test/EventNet.root"); } else hfile = new TFile("Event.root"); if(punzip) TTreeCacheUnzip::SetParallelUnzip(TTreeCacheUnzip::kEnable); tree = (TTree*)hfile->Get("T"); TBranch *branch = tree->GetBranch("event"); branch->SetAddress(&event); Int_t nentries = (Int_t)tree->GetEntries(); nevent = TMath::Min(nevent,nentries); if (read == 1) { //read sequential //set the read cache Int_t cachesize = 10000000; //this is the default value: 10 MBytes tree->SetCacheSize(cachesize); TTreeCache::SetLearnEntries(1); //one entry is sufficient to learn TTreeCache *tc = (TTreeCache*)hfile->GetCacheRead(); tc->SetEntryRange(0,nevent); for (ev = 0; ev < nevent; ev++) { tree->LoadTree(ev); //this call is required when using the cache if (ev%printev == 0) { tnew = timer.RealTime(); printf("event:%d, rtime=%f s\n",ev,tnew-told); told=tnew; timer.Continue(); } nb += tree->GetEntry(ev); //read complete event in memory } } else { //read random Int_t evrandom; for (ev = 0; ev < nevent; ev++) { if (ev%printev == 0) cout<<"event="<<ev<<endl; evrandom = Int_t(nevent*gRandom->Rndm(1)); nb += tree->GetEntry(evrandom); //read complete event in memory } } } else { // Write case // Create a new ROOT binary machine independent file. // Note that this file may contain any kind of ROOT objects, histograms, // pictures, graphics objects, detector geometries, tracks, events, etc.. // This file is now becoming the current directory. if (netf) { hfile = new TNetFile("root://localhost/root/test/EventNet.root","RECREATE","TTree benchmark ROOT file"); } else hfile = new TFile("Event.root","RECREATE","TTree benchmark ROOT file"); hfile->SetCompressionLevel(comp); // Create histogram to show write_time in function of time Float_t curtime = -0.5; Int_t ntime = nevent/printev; TH1F *htime = new TH1F("htime","Real-Time to write versus time",ntime,0,ntime); HistogramManager *hm = 0; if (hfill) { TDirectory *hdir = new TDirectory("histograms", "all histograms"); hm = new HistogramManager(hdir); } // Create a ROOT Tree and one superbranch tree = new TTree("T","An example of a ROOT tree"); tree->SetAutoSave(1000000000); // autosave when 1 Gbyte written tree->SetCacheSize(10000000); //set a 10 MBytes cache (useless when writing local files) bufsize = 64000; if (split) bufsize /= 4; event = new Event(); TTree::SetBranchStyle(branchStyle); TBranch *branch = tree->Branch("event", &event, bufsize,split); branch->SetAutoDelete(kFALSE); if(split >= 0 && branchStyle) tree->BranchRef(); Float_t ptmin = 1; Bool_t optimize = kTRUE; if (split < 90) optimize = kFALSE; for (ev = 0; ev < nevent; ev++) { if (ev%printev == 0) { tnew = timer.RealTime(); printf("event:%d, rtime=%f s\n",ev,tnew-told); htime->Fill(curtime,tnew-told); curtime += 1; told=tnew; timer.Continue(); } event->Build(ev, arg5, ptmin); if (write) nb += tree->Fill(); //fill the tree if (optimize) { //optimize baskets sizes once we have written 10 MBytes if (tree->GetZipBytes() > 10000000) { tree->OptimizeBaskets(5000000,1); // 5Mbytes for basket buffers optimize = kFALSE; } } if (hm) hm->Hfill(event); //fill histograms } if (write) { hfile = tree->GetCurrentFile(); //just in case we switched to a new file hfile->Write(); tree->Print(); } } // Stop timer and print results timer.Stop(); Float_t mbytes = 0.000001*nb; Double_t rtime = timer.RealTime(); Double_t ctime = timer.CpuTime(); printf("\n%d events and %lld bytes processed.\n",nevent,nb); printf("RealTime=%f seconds, CpuTime=%f seconds\n",rtime,ctime); if (read) { printf("You read %f Mbytes/Realtime seconds\n",mbytes/rtime); printf("You read %f Mbytes/Cputime seconds\n",mbytes/ctime); } else { printf("compression level=%d, split=%d, arg4=%d\n",comp,split,arg4); printf("You write %f Mbytes/Realtime seconds\n",mbytes/rtime); printf("You write %f Mbytes/Cputime seconds\n",mbytes/ctime); //printf("file compression factor = %f\n",hfile.GetCompressionFactor()); } hfile->Close(); return 0; } <commit_msg>Use new interface to the TreeCache<commit_after>// @(#)root/test:$Id$ // Author: Rene Brun 19/01/97 //////////////////////////////////////////////////////////////////////// // // A simple example with a ROOT tree // ================================= // // This program creates : // - a ROOT file // - a tree // Additional arguments can be passed to the program to control the flow // of execution. (see comments describing the arguments in the code). // Event nevent comp split fill // All arguments are optional. Default is: // Event 400 1 1 1 // // In this example, the tree consists of one single "super branch" // The statement ***tree->Branch("event", &event, 64000,split);*** below // will parse the structure described in Event.h and will make // a new branch for each data member of the class if split is set to 1. // - 9 branches corresponding to the basic types fType, fNtrack,fNseg, // fNvertex,fFlag,fTemperature,fMeasures,fMatrix,fClosesDistance. // - 3 branches corresponding to the members of the subobject EventHeader. // - one branch for each data member of the class Track of TClonesArray. // - one branch for the TRefArray of high Pt tracks // - one branch for the TRefArray of muon tracks // - one branch for the reference pointer to the last track // - one branch for the object fH (histogram of class TH1F). // // if split = 0 only one single branch is created and the complete event // is serialized in one single buffer. // if split = -2 the event is split using the old TBranchObject mechanism // if split = -1 the event is streamed using the old TBranchObject mechanism // if split > 0 the event is split using the new TBranchElement mechanism. // if split > 90 the branch buffer sizes are optimized once 10 MBytes written to the file // // if comp = 0 no compression at all. // if comp = 1 event is compressed. // if comp = 2 same as 1. In addition branches with floats in the TClonesArray // are also compressed. // The 4th argument fill can be set to 0 if one wants to time // the percentage of time spent in creating the event structure and // not write the event in the file. // In this example, one loops over nevent events. // The branch "event" is created at the first event. // The branch address is set for all other events. // For each event, the event header is filled and ntrack tracks // are generated and added to the TClonesArray list. // For each event the event histogram is saved as well as the list // of all tracks. // // The two TRefArray contain only references to the original tracks owned by // the TClonesArray fTracks. // // The number of events can be given as the first argument to the program. // By default 400 events are generated. // The compression option can be activated/deactivated via the second argument. // // ---Running/Linking instructions---- // This program consists of the following files and procedures. // - Event.h event class description // - Event.C event class implementation // - MainEvent.C the main program to demo this class might be used (this file) // - EventCint.C the CINT dictionary for the event and Track classes // this file is automatically generated by rootcint (see Makefile), // when the class definition in Event.h is modified. // // ---Analyzing the Event.root file with the interactive root // example of a simple session // Root > TFile f("Event.root") // Root > T.Draw("fNtrack") //histogram the number of tracks per event // Root > T.Draw("fPx") //histogram fPx for all tracks in all events // Root > T.Draw("fXfirst:fYfirst","fNtrack>600") // //scatter-plot for x versus y of first point of each track // Root > T.Draw("fH.GetRMS()") //histogram of the RMS of the event histogram // // Look also in the same directory at the following macros: // - eventa.C an example how to read the tree // - eventb.C how to read events conditionally // //////////////////////////////////////////////////////////////////////// #include <stdlib.h> #include "Riostream.h" #include "TROOT.h" #include "TFile.h" #include "TNetFile.h" #include "TRandom.h" #include "TTree.h" #include "TBranch.h" #include "TClonesArray.h" #include "TStopwatch.h" #include "Event.h" //______________________________________________________________________________ int main(int argc, char **argv) { Int_t nevent = 400; // by default create 400 events Int_t comp = 1; // by default file is compressed Int_t split = 1; // by default, split Event in sub branches Int_t write = 1; // by default the tree is filled Int_t hfill = 0; // by default histograms are not filled Int_t read = 0; Int_t arg4 = 1; Int_t arg5 = 600; //default number of tracks per event Int_t netf = 0; Int_t punzip = 0; if (argc > 1) nevent = atoi(argv[1]); if (argc > 2) comp = atoi(argv[2]); if (argc > 3) split = atoi(argv[3]); if (argc > 4) arg4 = atoi(argv[4]); if (argc > 5) arg5 = atoi(argv[5]); if (arg4 == 0) { write = 0; hfill = 0; read = 1;} if (arg4 == 1) { write = 1; hfill = 0;} if (arg4 == 2) { write = 0; hfill = 0;} if (arg4 == 10) { write = 0; hfill = 1;} if (arg4 == 11) { write = 1; hfill = 1;} if (arg4 == 20) { write = 0; read = 1;} //read sequential if (arg4 == 21) { write = 0; read = 1; punzip = 1;} //read sequential + parallel unzipping if (arg4 == 25) { write = 0; read = 2;} //read random if (arg4 >= 30) { netf = 1; } //use TNetFile if (arg4 == 30) { write = 0; read = 1;} //netfile + read sequential if (arg4 == 35) { write = 0; read = 2;} //netfile + read random if (arg4 == 36) { write = 1; } //netfile + write sequential Int_t branchStyle = 1; //new style by default if (split < 0) {branchStyle = 0; split = -1-split;} TFile *hfile; TTree *tree; Event *event = 0; // Fill event, header and tracks with some random numbers // Create a timer object to benchmark this loop TStopwatch timer; timer.Start(); Long64_t nb = 0; Int_t ev; Int_t bufsize; Double_t told = 0; Double_t tnew = 0; Int_t printev = 100; if (arg5 < 100) printev = 1000; if (arg5 < 10) printev = 10000; //Authorize Trees up to 2 Terabytes (if the system can do it) TTree::SetMaxTreeSize(1000*Long64_t(2000000000)); // Read case if (read) { if (netf) { hfile = new TNetFile("root://localhost/root/test/EventNet.root"); } else hfile = new TFile("Event.root"); tree = (TTree*)hfile->Get("T"); TBranch *branch = tree->GetBranch("event"); branch->SetAddress(&event); Int_t nentries = (Int_t)tree->GetEntries(); nevent = TMath::Min(nevent,nentries); if (read == 1) { //read sequential //set the read cache Int_t cachesize = 10000000; //this is the default value: 10 MBytes tree->SetCacheSize(cachesize); tree->SetCacheLearnEntries(1); //one entry is sufficient to learn tree->SetCacheEntryRange(0,nevent); if(punzip) tree->SetParallelUnzip(); for (ev = 0; ev < nevent; ev++) { tree->LoadTree(ev); //this call is required when using the cache if (ev%printev == 0) { tnew = timer.RealTime(); printf("event:%d, rtime=%f s\n",ev,tnew-told); told=tnew; timer.Continue(); } nb += tree->GetEntry(ev); //read complete event in memory } } else { //read random Int_t evrandom; for (ev = 0; ev < nevent; ev++) { if (ev%printev == 0) cout<<"event="<<ev<<endl; evrandom = Int_t(nevent*gRandom->Rndm(1)); nb += tree->GetEntry(evrandom); //read complete event in memory } } } else { // Write case // Create a new ROOT binary machine independent file. // Note that this file may contain any kind of ROOT objects, histograms, // pictures, graphics objects, detector geometries, tracks, events, etc.. // This file is now becoming the current directory. if (netf) { hfile = new TNetFile("root://localhost/root/test/EventNet.root","RECREATE","TTree benchmark ROOT file"); } else hfile = new TFile("Event.root","RECREATE","TTree benchmark ROOT file"); hfile->SetCompressionLevel(comp); // Create histogram to show write_time in function of time Float_t curtime = -0.5; Int_t ntime = nevent/printev; TH1F *htime = new TH1F("htime","Real-Time to write versus time",ntime,0,ntime); HistogramManager *hm = 0; if (hfill) { TDirectory *hdir = new TDirectory("histograms", "all histograms"); hm = new HistogramManager(hdir); } // Create a ROOT Tree and one superbranch tree = new TTree("T","An example of a ROOT tree"); tree->SetAutoSave(1000000000); // autosave when 1 Gbyte written tree->SetCacheSize(10000000); //set a 10 MBytes cache (useless when writing local files) bufsize = 64000; if (split) bufsize /= 4; event = new Event(); TTree::SetBranchStyle(branchStyle); TBranch *branch = tree->Branch("event", &event, bufsize,split); branch->SetAutoDelete(kFALSE); if(split >= 0 && branchStyle) tree->BranchRef(); Float_t ptmin = 1; Bool_t optimize = kTRUE; if (split < 90) optimize = kFALSE; for (ev = 0; ev < nevent; ev++) { if (ev%printev == 0) { tnew = timer.RealTime(); printf("event:%d, rtime=%f s\n",ev,tnew-told); htime->Fill(curtime,tnew-told); curtime += 1; told=tnew; timer.Continue(); } event->Build(ev, arg5, ptmin); if (write) nb += tree->Fill(); //fill the tree if (optimize) { //optimize baskets sizes once we have written 10 MBytes if (tree->GetZipBytes() > 10000000) { tree->OptimizeBaskets(5000000,1); // 5Mbytes for basket buffers optimize = kFALSE; } } if (hm) hm->Hfill(event); //fill histograms } if (write) { hfile = tree->GetCurrentFile(); //just in case we switched to a new file hfile->Write(); tree->Print(); } } // Stop timer and print results timer.Stop(); Float_t mbytes = 0.000001*nb; Double_t rtime = timer.RealTime(); Double_t ctime = timer.CpuTime(); printf("\n%d events and %lld bytes processed.\n",nevent,nb); printf("RealTime=%f seconds, CpuTime=%f seconds\n",rtime,ctime); if (read) { printf("You read %f Mbytes/Realtime seconds\n",mbytes/rtime); printf("You read %f Mbytes/Cputime seconds\n",mbytes/ctime); } else { printf("compression level=%d, split=%d, arg4=%d\n",comp,split,arg4); printf("You write %f Mbytes/Realtime seconds\n",mbytes/rtime); printf("You write %f Mbytes/Cputime seconds\n",mbytes/ctime); //printf("file compression factor = %f\n",hfile.GetCompressionFactor()); } hfile->Close(); return 0; } <|endoftext|>
<commit_before>// // Created by dar on 1/23/16. // #include "Game.h" #include "../core/Core.h" #include "render/RenderManager.h" #include "InputManager.h" #include "../core/map/TiledTxtMapLoader.h" #include "../logging.h" #include <gui/GuiText.h> #include <gui/GuiButton.h> Game::Game(const std::function<bool(Window *window)> &switchWindow) : Window(switchWindow) { MapLoader *mapLoader = new TiledTxtMapLoader("test_map"); Map *bmap = mapLoader->loadMap(); this->core = new Core(bmap); delete mapLoader; controller = new GuiButton(GUI_TOP_LEFT, 0, 0, 200, 200, 0); joystick = new GuiButton(GUI_TOP_LEFT, 0, 0, 200, 200, 1); controller->setVisible(false); joystick->setVisible(false); auto moveController = [&](const TouchPoint *const touchPoint) { return true; }; controller->setOnClickListener(moveController); this->guiElements.push_back(controller); this->guiElements.push_back(joystick); possessButton = new GuiButton(GUI_BOTTOM_RIGHT, 50, 50, 125, 125, new int[2]{2, 10}, 2); possessButton->setVisible(false); auto possessAction = [&](const TouchPoint *const p) { if (p->state == 1) { if (possessButton->canBeClicked(p)) { if (this->core->getPlayer()->getToy() == nullptr) { this->core->getPlayer()->setToy(); } else { this->core->getPlayer()->eject(); } } return false; } return true; }; possessButton->setOnClickListener(possessAction); this->guiElements.push_back(possessButton); GuiButton *backButton = new GuiButton(GUI_TOP_LEFT, 25, 25, 100, 100, new int[2]{8, 16}, 2); auto backAction = [=](const TouchPoint *const p) { if (p->state == 1) { if (backButton->canBeClicked(p)) { this->switchWindow(new MainMenu(switchWindow)); } return false; } return true; }; backButton->setOnClickListener(backAction); this->guiElements.push_back(backButton); GuiText *t = new GuiText(string("Dev Build: ") + __DATE__ + " " + __TIME__, 15, 15, GUI_BOTTOM_LEFT, 32, 0, 0); this->guiElements.push_back(t); } void Game::reload(unsigned int windowWidth, unsigned int windowHeight) { for (GuiElement *e : this->guiElements) { e->reinit(windowWidth, windowHeight); } this->resetButtons(nullptr); this->windowWidth = windowWidth; this->windowHeight = windowHeight; } void Game::tick(double deltaTime) { this->core->getMap()->update(); this->core->getMap()->getWorld()->Step(deltaTime, 8, 3); for (int i = 0; i < this->core->getMap()->getEntities().size(); i++) { Entity *entity = this->core->getMap()->getEntities().at(i); if (entity->isToBeDeleted()) { this->core->getMap()->removeEntity(entity); i--; } } possessButton->setVisible(this->core->getPlayer()->getToyToMerge() != nullptr || this->core->getPlayer()->getToy() != nullptr); if (controller->isVisible()) { double playerSpeed = this->core->getPlayer()->getSpeed(); double x = (joystick->getX() - controller->getX()) / 100.0f * playerSpeed; double y = (joystick->getY() - controller->getY()) / 100.0f * playerSpeed; double angle = atan2(y, x); this->core->getPlayer()->applyImpulse(x, y); this->core->getPlayer()->setAngle(angle); } double dx = (this->core->getPlayer()->getX() + this->core->getPlayer()->getWidth() / 2 - 1) * this->core->getBlockSize() * this->core->getGeneralScale() + this->core->getCamX(); double dy = (this->core->getPlayer()->getY() + this->core->getPlayer()->getHeight() / 2 - 1) * this->core->getBlockSize() * this->core->getGeneralScale() + this->core->getCamY(); if (abs(dx) > 2) this->core->setCamX(-this->core->getCamX() + (dx) * 0.05); if (abs(dy) > 2) this->core->setCamY(-this->core->getCamY() + (dy) * 0.05); double camX = this->core->getCamX(), camY = this->core->getCamY(); if (-camX < this->windowWidth/2 - this->core->getBlockSize() * this->core->getGeneralScale()) { this->core->setCamX(this->windowWidth/2 - this->core->getBlockSize() * this->core->getGeneralScale()); } if (-camY < this->windowHeight/2 - this->core->getBlockSize() * this->core->getGeneralScale()) { this->core->setCamY(this->windowHeight/2 - this->core->getBlockSize() * this->core->getGeneralScale()); } if (-camX > -(signed)this->windowWidth/2 + (this->core->getMap()->getWidth() - 1) * this->core->getBlockSize() * this->core->getGeneralScale()) { this->core->setCamX(-(signed)this->windowWidth/2 + (this->core->getMap()->getWidth() - 1) * this->core->getBlockSize() * this->core->getGeneralScale()); } if (-camY > -(signed)this->windowHeight/2 + (this->core->getMap()->getHeight() - 1) * this->core->getBlockSize() * this->core->getGeneralScale()) { this->core->setCamY(-(signed)this->windowHeight/2 + (this->core->getMap()->getHeight() - 1) * this->core->getBlockSize() * this->core->getGeneralScale()); } } void Game::handleClick(const TouchPoint *const p) { bool clicked = false; for (GuiElement *e : this->guiElements) { if (GuiButton *b = dynamic_cast<GuiButton *>(e)) { if (b->canBeClicked(p)) { if (p->state == 1) this->resetButtons(p, b); if ((p->state == 0 && (!b->isPressed()) || b->getTouchedBy() == p->id) || (b->getTouchedBy() == p->id && p->state == 2)) { if (b->onClick(p)) { clicked = true; break; } } } } } if (!clicked) { if (p->state == 0) { if (!controller->isVisible()) { controller->setVisible(true), joystick->setVisible(true); controller->setX(p->x - controller->getWidth() / 2); controller->setY(p->y - controller->getHeight() / 2); joystick->setX(p->x - joystick->getWidth() / 2); joystick->setY(p->y - joystick->getHeight() / 2); controller->onClick(p); } } else if (p->state == 1) { this->resetButtons(p); } } if (p->state == 2) { if (controller->isVisible() && controller->getTouchedBy() == p->id) { double x = p->x - controller->getX() - controller->getWidth() / 2; double y = p->y - controller->getY() - controller->getHeight() / 2; if (std::sqrt(x * x + y * y) > joystick->getWidth() / 2) { double angle = atan2(y, x); x = cos(angle) * controller->getWidth() / 2; y = sin(angle) * controller->getHeight() / 2; } joystick->setX(controller->getX() + x), joystick->setY(controller->getY() + y); } } } void Game::resetButtons(const TouchPoint *const p, const GuiButton *const b) { for (GuiElement *e : this->guiElements) { if (GuiButton *b1 = dynamic_cast<GuiButton *>(e)) { if (b1 != b) { if (p == nullptr) { b1->setPressed(false); } else if (b1->getTouchedBy() == p->id) { b1->onClick(p); } } } } if (p == nullptr || controller->getTouchedBy() == p->id) { joystick->setX(controller->getX()), joystick->setY(controller->getY()); controller->setVisible(false), joystick->setVisible(false); } } void Game::handleKeyboard(const Keypress *const keypress) { LOGW("Keyboard input is unsupported on current platform\n"); } Game::~Game() { delete this->core; }<commit_msg>Added missing include<commit_after>// // Created by dar on 1/23/16. // #include "Game.h" #include "../core/Core.h" #include "render/RenderManager.h" #include "InputManager.h" #include "../core/map/TiledTxtMapLoader.h" #include "../logging.h" #include <gui/GuiText.h> #include <gui/GuiButton.h> #include <window/MainMenu.h> Game::Game(const std::function<bool(Window *window)> &switchWindow) : Window(switchWindow) { MapLoader *mapLoader = new TiledTxtMapLoader("test_map"); Map *bmap = mapLoader->loadMap(); this->core = new Core(bmap); delete mapLoader; controller = new GuiButton(GUI_TOP_LEFT, 0, 0, 200, 200, 0); joystick = new GuiButton(GUI_TOP_LEFT, 0, 0, 200, 200, 1); controller->setVisible(false); joystick->setVisible(false); auto moveController = [&](const TouchPoint *const touchPoint) { return true; }; controller->setOnClickListener(moveController); this->guiElements.push_back(controller); this->guiElements.push_back(joystick); possessButton = new GuiButton(GUI_BOTTOM_RIGHT, 50, 50, 125, 125, new int[2]{2, 10}, 2); possessButton->setVisible(false); auto possessAction = [&](const TouchPoint *const p) { if (p->state == 1) { if (possessButton->canBeClicked(p)) { if (this->core->getPlayer()->getToy() == nullptr) { this->core->getPlayer()->setToy(); } else { this->core->getPlayer()->eject(); } } return false; } return true; }; possessButton->setOnClickListener(possessAction); this->guiElements.push_back(possessButton); GuiButton *backButton = new GuiButton(GUI_TOP_LEFT, 25, 25, 100, 100, new int[2]{8, 16}, 2); auto backAction = [=](const TouchPoint *const p) { if (p->state == 1) { if (backButton->canBeClicked(p)) { this->switchWindow(new MainMenu(switchWindow)); } return false; } return true; }; backButton->setOnClickListener(backAction); this->guiElements.push_back(backButton); GuiText *t = new GuiText(string("Dev Build: ") + __DATE__ + " " + __TIME__, 15, 15, GUI_BOTTOM_LEFT, 32, 0, 0); this->guiElements.push_back(t); } void Game::reload(unsigned int windowWidth, unsigned int windowHeight) { for (GuiElement *e : this->guiElements) { e->reinit(windowWidth, windowHeight); } this->resetButtons(nullptr); this->windowWidth = windowWidth; this->windowHeight = windowHeight; } void Game::tick(double deltaTime) { this->core->getMap()->update(); this->core->getMap()->getWorld()->Step(deltaTime, 8, 3); for (int i = 0; i < this->core->getMap()->getEntities().size(); i++) { Entity *entity = this->core->getMap()->getEntities().at(i); if (entity->isToBeDeleted()) { this->core->getMap()->removeEntity(entity); i--; } } possessButton->setVisible(this->core->getPlayer()->getToyToMerge() != nullptr || this->core->getPlayer()->getToy() != nullptr); if (controller->isVisible()) { double playerSpeed = this->core->getPlayer()->getSpeed(); double x = (joystick->getX() - controller->getX()) / 100.0f * playerSpeed; double y = (joystick->getY() - controller->getY()) / 100.0f * playerSpeed; double angle = atan2(y, x); this->core->getPlayer()->applyImpulse(x, y); this->core->getPlayer()->setAngle(angle); } double dx = (this->core->getPlayer()->getX() + this->core->getPlayer()->getWidth() / 2 - 1) * this->core->getBlockSize() * this->core->getGeneralScale() + this->core->getCamX(); double dy = (this->core->getPlayer()->getY() + this->core->getPlayer()->getHeight() / 2 - 1) * this->core->getBlockSize() * this->core->getGeneralScale() + this->core->getCamY(); if (abs(dx) > 2) this->core->setCamX(-this->core->getCamX() + (dx) * 0.05); if (abs(dy) > 2) this->core->setCamY(-this->core->getCamY() + (dy) * 0.05); double camX = this->core->getCamX(), camY = this->core->getCamY(); if (-camX < this->windowWidth/2 - this->core->getBlockSize() * this->core->getGeneralScale()) { this->core->setCamX(this->windowWidth/2 - this->core->getBlockSize() * this->core->getGeneralScale()); } if (-camY < this->windowHeight/2 - this->core->getBlockSize() * this->core->getGeneralScale()) { this->core->setCamY(this->windowHeight/2 - this->core->getBlockSize() * this->core->getGeneralScale()); } if (-camX > -(signed)this->windowWidth/2 + (this->core->getMap()->getWidth() - 1) * this->core->getBlockSize() * this->core->getGeneralScale()) { this->core->setCamX(-(signed)this->windowWidth/2 + (this->core->getMap()->getWidth() - 1) * this->core->getBlockSize() * this->core->getGeneralScale()); } if (-camY > -(signed)this->windowHeight/2 + (this->core->getMap()->getHeight() - 1) * this->core->getBlockSize() * this->core->getGeneralScale()) { this->core->setCamY(-(signed)this->windowHeight/2 + (this->core->getMap()->getHeight() - 1) * this->core->getBlockSize() * this->core->getGeneralScale()); } } void Game::handleClick(const TouchPoint *const p) { bool clicked = false; for (GuiElement *e : this->guiElements) { if (GuiButton *b = dynamic_cast<GuiButton *>(e)) { if (b->canBeClicked(p)) { if (p->state == 1) this->resetButtons(p, b); if ((p->state == 0 && (!b->isPressed()) || b->getTouchedBy() == p->id) || (b->getTouchedBy() == p->id && p->state == 2)) { if (b->onClick(p)) { clicked = true; break; } } } } } if (!clicked) { if (p->state == 0) { if (!controller->isVisible()) { controller->setVisible(true), joystick->setVisible(true); controller->setX(p->x - controller->getWidth() / 2); controller->setY(p->y - controller->getHeight() / 2); joystick->setX(p->x - joystick->getWidth() / 2); joystick->setY(p->y - joystick->getHeight() / 2); controller->onClick(p); } } else if (p->state == 1) { this->resetButtons(p); } } if (p->state == 2) { if (controller->isVisible() && controller->getTouchedBy() == p->id) { double x = p->x - controller->getX() - controller->getWidth() / 2; double y = p->y - controller->getY() - controller->getHeight() / 2; if (std::sqrt(x * x + y * y) > joystick->getWidth() / 2) { double angle = atan2(y, x); x = cos(angle) * controller->getWidth() / 2; y = sin(angle) * controller->getHeight() / 2; } joystick->setX(controller->getX() + x), joystick->setY(controller->getY() + y); } } } void Game::resetButtons(const TouchPoint *const p, const GuiButton *const b) { for (GuiElement *e : this->guiElements) { if (GuiButton *b1 = dynamic_cast<GuiButton *>(e)) { if (b1 != b) { if (p == nullptr) { b1->setPressed(false); } else if (b1->getTouchedBy() == p->id) { b1->onClick(p); } } } } if (p == nullptr || controller->getTouchedBy() == p->id) { joystick->setX(controller->getX()), joystick->setY(controller->getY()); controller->setVisible(false), joystick->setVisible(false); } } void Game::handleKeyboard(const Keypress *const keypress) { LOGW("Keyboard input is unsupported on current platform\n"); } Game::~Game() { delete this->core; }<|endoftext|>
<commit_before>//https://code.google.com/p/nya-engine/ #include "material.h" namespace nya_scene { void material::set() const { m_shader.set(); for(int i=0;i<(int)m_params.size();++i) { const param_proxy &p=m_params[i].p; if(!p.is_valid()) { const param_array_proxy &a=m_params[i].a; if(a.is_valid()) { m_shader.set_uniform4_array(i,a->m_params[0].f,a->get_count()); continue; } m_shader.set_uniform_value(i,0,0,0,0); continue; } const param_proxy &m=m_params[i].m; if(m.is_valid()) m_shader.set_uniform_value(i,p->f[0]*m->f[0],p->f[1]*m->f[1],p->f[2]*m->f[2],p->f[3]*m->f[3]); else m_shader.set_uniform_value(i,p->f[0],p->f[1],p->f[2],p->f[3]); } if(m_blend) nya_render::blend::enable(m_blend_src,m_blend_dst); else nya_render::blend::disable(); if(m_color_write) nya_render::color_write::enable(); else nya_render::color_write::disable(); if(m_zwrite) nya_render::zwrite::enable(); else nya_render::zwrite::disable(); if(m_cull_face) nya_render::cull_face::enable(m_cull_order); else nya_render::cull_face::disable(); for(size_t i=0;i<m_textures.size();++i) { if(m_textures[i].slot<0) continue; if(!m_textures[i].proxy.is_valid()) { nya_render::texture::select_multitex_slot(m_textures[i].slot); nya_render::texture::unbind(); continue; } m_textures[i].proxy->set(m_textures[i].slot); } } void material::unset() const { m_shader.unset(); if(m_blend) nya_render::blend::disable(); if(!m_zwrite) nya_render::zwrite::enable(); if(!m_color_write) nya_render::color_write::enable(); for(size_t i=0;i<m_textures.size();++i) { if(m_textures[i].slot<0 || !m_textures[i].proxy.is_valid()) continue; m_textures[i].proxy->unset(); } } void material::set_shader(const shader &shdr) { m_shader.unload(); m_shader=shdr; for(size_t i=0;i<m_textures.size();++i) m_textures[i].slot=m_shader.get_texture_slot(m_textures[i].semantics.c_str()); m_params.clear(); m_params.resize(m_shader.get_uniforms_count()); } void material::set_texture(const char *semantics,const texture &tex) { if(!semantics) return; set_texture(semantics,texture_proxy(tex)); } void material::set_texture(const char *semantics,const texture_proxy &proxy) { if(!semantics) return; for(size_t i=0;i<m_textures.size();++i) { material_texture &t=m_textures[i]; if(t.semantics!=semantics) continue; t.proxy=proxy; t.slot=m_shader.get_texture_slot(semantics); return; } m_textures.resize(m_textures.size()+1); m_textures.back().proxy=proxy; m_textures.back().semantics.assign(semantics); m_textures.back().slot=m_shader.get_texture_slot(semantics); } void material::set_blend(bool enabled,blend_mode src,blend_mode dst) { m_blend=enabled; m_blend_src=src; m_blend_dst=dst; } const char *material::get_texture_name(int idx) const { if(idx<0 || idx>=(int)m_textures.size()) return 0; if(!m_textures[idx].proxy.is_valid()) return 0; return m_textures[idx].proxy->get_name(); } const char *material::get_texture_semantics(int idx) const { if(idx<0 || idx>=(int)m_textures.size()) return 0; return m_textures[idx].semantics.c_str(); } const char *material::get_param_name(int idx) const { if(idx<0 || idx>=(int)m_params.size()) return 0; return m_shader.get_uniform(idx).name.c_str(); } int material::get_param_idx(const char *name) const { if(!name) return -1; for(int i=0;i<m_shader.get_uniforms_count();++i) { if(m_shader.get_uniform(i).name.compare(name)==0) return i; } return -1; } void material::set_param(int idx,float f0,float f1,float f2,float f3) { set_param(idx,param(f0,f1,f2,f3)); } void material::set_param(int idx,const param &p) { set_param(idx,param_proxy(p)); } void material::set_param(int idx,const param_proxy &p) { if(idx<0 || idx>=(int)m_params.size()) return; m_params[idx].p=p; m_params[idx].m.free(); m_params[idx].a.free(); } void material::set_param(int idx,const param_proxy &p,const param &m) { set_param(idx,p,param_proxy(m)); } void material::set_param(int idx,const param_proxy &p,const param_proxy &m) { if(idx<0 || idx>=(int)m_params.size()) return; m_params[idx].p=p; m_params[idx].m=m; m_params[idx].a.free(); } void material::set_param_array(int idx,const param_array & a) { set_param_array(idx,param_array_proxy(a)); } void material::set_param_array(int idx,const param_array_proxy & p) { if(idx<0 || idx>=(int)m_params.size()) return; m_params[idx].p.free(); m_params[idx].m.free(); m_params[idx].a=p; } const material::param_proxy &material::get_param(int idx) { if(idx<0 || idx>=(int)m_params.size()) { static param_proxy invalid; return invalid; } return m_params[idx].p; } const material::param_proxy &material::get_param_multiplier(int idx) { if(idx<0 || idx>=(int)m_params.size()) { static param_proxy invalid; return invalid; } return m_params[idx].m; } const material::param_array_proxy &material::get_param_array(int idx) { if(idx<0 || idx>=(int)m_params.size()) { static param_array_proxy invalid; return invalid; } return m_params[idx].a; } void material::release() { for(size_t i=0;i<m_textures.size();++i) m_textures[i].proxy.free(); m_textures.clear(); m_params.clear(); m_shader.unload(); m_name.clear(); } } <commit_msg>material param_array fix<commit_after>//https://code.google.com/p/nya-engine/ #include "material.h" namespace nya_scene { void material::set() const { m_shader.set(); for(int i=0;i<(int)m_params.size();++i) { const param_proxy &p=m_params[i].p; if(!p.is_valid()) { const param_array_proxy &a=m_params[i].a; if(a.is_valid() && a->get_count()>0) { m_shader.set_uniform4_array(i,a->m_params[0].f,a->get_count()); continue; } m_shader.set_uniform_value(i,0,0,0,0); continue; } const param_proxy &m=m_params[i].m; if(m.is_valid()) m_shader.set_uniform_value(i,p->f[0]*m->f[0],p->f[1]*m->f[1],p->f[2]*m->f[2],p->f[3]*m->f[3]); else m_shader.set_uniform_value(i,p->f[0],p->f[1],p->f[2],p->f[3]); } if(m_blend) nya_render::blend::enable(m_blend_src,m_blend_dst); else nya_render::blend::disable(); if(m_color_write) nya_render::color_write::enable(); else nya_render::color_write::disable(); if(m_zwrite) nya_render::zwrite::enable(); else nya_render::zwrite::disable(); if(m_cull_face) nya_render::cull_face::enable(m_cull_order); else nya_render::cull_face::disable(); for(size_t i=0;i<m_textures.size();++i) { if(m_textures[i].slot<0) continue; if(!m_textures[i].proxy.is_valid()) { nya_render::texture::select_multitex_slot(m_textures[i].slot); nya_render::texture::unbind(); continue; } m_textures[i].proxy->set(m_textures[i].slot); } } void material::unset() const { m_shader.unset(); if(m_blend) nya_render::blend::disable(); if(!m_zwrite) nya_render::zwrite::enable(); if(!m_color_write) nya_render::color_write::enable(); for(size_t i=0;i<m_textures.size();++i) { if(m_textures[i].slot<0 || !m_textures[i].proxy.is_valid()) continue; m_textures[i].proxy->unset(); } } void material::set_shader(const shader &shdr) { m_shader.unload(); m_shader=shdr; for(size_t i=0;i<m_textures.size();++i) m_textures[i].slot=m_shader.get_texture_slot(m_textures[i].semantics.c_str()); m_params.clear(); m_params.resize(m_shader.get_uniforms_count()); } void material::set_texture(const char *semantics,const texture &tex) { if(!semantics) return; set_texture(semantics,texture_proxy(tex)); } void material::set_texture(const char *semantics,const texture_proxy &proxy) { if(!semantics) return; for(size_t i=0;i<m_textures.size();++i) { material_texture &t=m_textures[i]; if(t.semantics!=semantics) continue; t.proxy=proxy; t.slot=m_shader.get_texture_slot(semantics); return; } m_textures.resize(m_textures.size()+1); m_textures.back().proxy=proxy; m_textures.back().semantics.assign(semantics); m_textures.back().slot=m_shader.get_texture_slot(semantics); } void material::set_blend(bool enabled,blend_mode src,blend_mode dst) { m_blend=enabled; m_blend_src=src; m_blend_dst=dst; } const char *material::get_texture_name(int idx) const { if(idx<0 || idx>=(int)m_textures.size()) return 0; if(!m_textures[idx].proxy.is_valid()) return 0; return m_textures[idx].proxy->get_name(); } const char *material::get_texture_semantics(int idx) const { if(idx<0 || idx>=(int)m_textures.size()) return 0; return m_textures[idx].semantics.c_str(); } const char *material::get_param_name(int idx) const { if(idx<0 || idx>=(int)m_params.size()) return 0; return m_shader.get_uniform(idx).name.c_str(); } int material::get_param_idx(const char *name) const { if(!name) return -1; for(int i=0;i<m_shader.get_uniforms_count();++i) { if(m_shader.get_uniform(i).name.compare(name)==0) return i; } return -1; } void material::set_param(int idx,float f0,float f1,float f2,float f3) { set_param(idx,param(f0,f1,f2,f3)); } void material::set_param(int idx,const param &p) { set_param(idx,param_proxy(p)); } void material::set_param(int idx,const param_proxy &p) { if(idx<0 || idx>=(int)m_params.size()) return; m_params[idx].p=p; m_params[idx].m.free(); m_params[idx].a.free(); } void material::set_param(int idx,const param_proxy &p,const param &m) { set_param(idx,p,param_proxy(m)); } void material::set_param(int idx,const param_proxy &p,const param_proxy &m) { if(idx<0 || idx>=(int)m_params.size()) return; m_params[idx].p=p; m_params[idx].m=m; m_params[idx].a.free(); } void material::set_param_array(int idx,const param_array & a) { set_param_array(idx,param_array_proxy(a)); } void material::set_param_array(int idx,const param_array_proxy & p) { if(idx<0 || idx>=(int)m_params.size()) return; m_params[idx].p.free(); m_params[idx].m.free(); m_params[idx].a=p; } const material::param_proxy &material::get_param(int idx) { if(idx<0 || idx>=(int)m_params.size()) { static param_proxy invalid; return invalid; } return m_params[idx].p; } const material::param_proxy &material::get_param_multiplier(int idx) { if(idx<0 || idx>=(int)m_params.size()) { static param_proxy invalid; return invalid; } return m_params[idx].m; } const material::param_array_proxy &material::get_param_array(int idx) { if(idx<0 || idx>=(int)m_params.size()) { static param_array_proxy invalid; return invalid; } return m_params[idx].a; } void material::release() { for(size_t i=0;i<m_textures.size();++i) m_textures[i].proxy.free(); m_textures.clear(); m_params.clear(); m_shader.unload(); m_name.clear(); } } <|endoftext|>
<commit_before>/* * Copyright 2006-2008 The FLWOR Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "zorbautils/fatal.h" #include "zorbautils/stemmer.h" using namespace std; using namespace zorba::locale; namespace zorba { /////////////////////////////////////////////////////////////////////////////// Stemmer::Stemmer( iso639_1::type lang ) : stemmer_( sb_stemmer_new( iso639_1::string_of[ lang ], NULL ) ) { ZORBA_FATAL( stemmer_, "out of memory" ); } Stemmer::~Stemmer() { sb_stemmer_delete( stemmer_ ); } Stemmer const* Stemmer::get( iso639_1::type lang ) { static Stemmer* cached_stemmers[ iso639_1::NUM_ENTRIES ]; static Mutex mutex; if ( !lang ) lang = get_host_lang(); AutoMutex const lock( &mutex ); Stemmer *&ptr = cached_stemmers[ lang ]; if ( !ptr ) ptr = new Stemmer( lang ); return ptr; } void Stemmer::stem( string const &word, string &result ) const { // // We need a mutex since the libstemmer library is not thread-safe. // AutoMutex const lock( &mutex_ ); sb_symbol const *const sb_word = sb_stemmer_stem( stemmer_, reinterpret_cast<sb_symbol const*>( word.c_str() ), word.length() ); ZORBA_FATAL( sb_word, "out of memory" ); result = reinterpret_cast<char const*>( sb_word ); } /////////////////////////////////////////////////////////////////////////////// } // namespace zorba /* vim:set et sw=2 ts=2: */ <commit_msg>Now using auto_ptr.<commit_after>/* * Copyright 2006-2008 The FLWOR Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <memory> #include "zorbautils/fatal.h" #include "zorbautils/stemmer.h" using namespace std; using namespace zorba::locale; namespace zorba { /////////////////////////////////////////////////////////////////////////////// Stemmer::Stemmer( iso639_1::type lang ) : stemmer_( sb_stemmer_new( iso639_1::string_of[ lang ], NULL ) ) { ZORBA_FATAL( stemmer_, "out of memory" ); } Stemmer::~Stemmer() { sb_stemmer_delete( stemmer_ ); } Stemmer const* Stemmer::get( iso639_1::type lang ) { static auto_ptr<Stemmer> cached_stemmers[ iso639_1::NUM_ENTRIES ]; static Mutex mutex; if ( !lang ) lang = get_host_lang(); AutoMutex const lock( &mutex ); auto_ptr<Stemmer> &ptr = cached_stemmers[ lang ]; if ( !ptr.get() ) ptr.reset( new Stemmer( lang ) ); return ptr.get(); } void Stemmer::stem( string const &word, string &result ) const { // // We need a mutex since the libstemmer library is not thread-safe. // AutoMutex const lock( &mutex_ ); sb_symbol const *const sb_word = sb_stemmer_stem( stemmer_, reinterpret_cast<sb_symbol const*>( word.c_str() ), word.length() ); ZORBA_FATAL( sb_word, "out of memory" ); result = reinterpret_cast<char const*>( sb_word ); } /////////////////////////////////////////////////////////////////////////////// } // namespace zorba /* vim:set et sw=2 ts=2: */ <|endoftext|>
<commit_before>/*////////////////////////////////////////////////////////////////// //// SKIRT -- an advanced radiative transfer code //// //// © Astronomical Observatory, Ghent University //// ///////////////////////////////////////////////////////////////// */ #include "FatalError.hpp" #include "NR.hpp" #include "Random.hpp" #include "SpecialFunctions.hpp" #include "SpiralStructureGeometry.hpp" //////////////////////////////////////////////////////////////////// SpiralStructureGeometry::SpiralStructureGeometry() : GenGeometry(), _geometry(0), _m(0), _p(0), _R0(0), _phi0(0), _w(0), _N(0), _tanp(0), _CN(0), _c(0) { } ////////////////////////////////////////////////////////////////////// void SpiralStructureGeometry::setupSelfBefore() { GenGeometry::setupSelfBefore(); // verify property values if (_m <= 0) throw FATALERROR("The number of spiral arms should be positive"); if (_p <= 0 || _p >= M_PI/2.) throw FATALERROR("The pitch angle should be between 0 and 90 degrees"); if (_R0 <= 0) throw FATALERROR("The radius zero-point should be positive"); if (_phi0 < 0 || _phi0 > 2.0*M_PI) throw FATALERROR("The phase zero-point should be between 0 and 360 degrees"); if (_w <= 0 || _w > 1.) throw FATALERROR("The weight of the spiral perturbation should be between 0 and 1"); if (_N < 0 || _N > 10) throw FATALERROR("The arm-interarm size ratio index should be between 0 and 10"); // cache frequently used values _tanp = tan(_p); _CN = sqrt(M_PI) * SpecialFunctions::gamma(_N+1.0) / SpecialFunctions::gamma(_N+0.5); _c = 1.0+(_CN-1.0)*_w; } //////////////////////////////////////////////////////////////////// void SpiralStructureGeometry::setGeometry(AxGeometry* value) { if (_geometry) delete _geometry; _geometry = value; if (_geometry) _geometry->setParent(this); } //////////////////////////////////////////////////////////////////// AxGeometry* SpiralStructureGeometry::geometry() const { return _geometry; } //////////////////////////////////////////////////////////////////// void SpiralStructureGeometry::setArms(int value) { _m = value; } //////////////////////////////////////////////////////////////////// int SpiralStructureGeometry::arms() const { return _m; } //////////////////////////////////////////////////////////////////// void SpiralStructureGeometry::setPitch(double value) { _p = value; } //////////////////////////////////////////////////////////////////// double SpiralStructureGeometry::pitch() const { return _p; } //////////////////////////////////////////////////////////////////// void SpiralStructureGeometry::setRadius(double value) { _R0 = value; } //////////////////////////////////////////////////////////////////// double SpiralStructureGeometry::radius() const { return _R0; } //////////////////////////////////////////////////////////////////// void SpiralStructureGeometry::setPhase(double value) { _phi0 = value; } //////////////////////////////////////////////////////////////////// double SpiralStructureGeometry::phase() const { return _phi0; } //////////////////////////////////////////////////////////////////// void SpiralStructureGeometry::setPerturbWeight(double value) { _w = value; } //////////////////////////////////////////////////////////////////// double SpiralStructureGeometry::perturbWeight() const { return _w; } //////////////////////////////////////////////////////////////////// void SpiralStructureGeometry::setIndex(int value) { _N = value; } //////////////////////////////////////////////////////////////////// int SpiralStructureGeometry::index() const { return _N; } //////////////////////////////////////////////////////////////////// double SpiralStructureGeometry::density(Position bfr) const { double R, phi, z; bfr.cylindrical(R,phi,z); return _geometry->density(R,z) * perturbation(R,z); } //////////////////////////////////////////////////////////////////// Position SpiralStructureGeometry::generatePosition() const { Position bfr = _geometry->generatePosition(); double R, dummyphi, z; bfr.cylindrical(R,dummyphi,z); double c = 1.0+(_CN-1.0)*_w; double phi, t; do { phi = 2.0*M_PI*_random->uniform(); t = _random->uniform()*c/perturbation(R,phi); } while (t>1); return Position(R,phi,z,Position::CYLINDRICAL); } //////////////////////////////////////////////////////////////////// double SpiralStructureGeometry::SigmaX() const { return _geometry->SigmaX(); } //////////////////////////////////////////////////////////////////// double SpiralStructureGeometry::SigmaY() const { return _geometry->SigmaY(); } //////////////////////////////////////////////////////////////////// double SpiralStructureGeometry::SigmaZ() const { return _geometry->SigmaZ(); } //////////////////////////////////////////////////////////////////// double SpiralStructureGeometry::perturbation(double R, double phi) const { double gamma = log(R/_R0)/_tanp + _phi0 + 0.5*M_PI/_m; return (1.0-_w) + _w*_CN*pow(sin(0.5*_m*(gamma-phi)),2*_N); } //////////////////////////////////////////////////////////////////// <commit_msg>Cures a stupid bug in SpiralStructureGeometry<commit_after>/*////////////////////////////////////////////////////////////////// //// SKIRT -- an advanced radiative transfer code //// //// © Astronomical Observatory, Ghent University //// ///////////////////////////////////////////////////////////////// */ #include "FatalError.hpp" #include "NR.hpp" #include "Random.hpp" #include "SpecialFunctions.hpp" #include "SpiralStructureGeometry.hpp" //////////////////////////////////////////////////////////////////// SpiralStructureGeometry::SpiralStructureGeometry() : GenGeometry(), _geometry(0), _m(0), _p(0), _R0(0), _phi0(0), _w(0), _N(0), _tanp(0), _CN(0), _c(0) { } ////////////////////////////////////////////////////////////////////// void SpiralStructureGeometry::setupSelfBefore() { GenGeometry::setupSelfBefore(); // verify property values if (_m <= 0) throw FATALERROR("The number of spiral arms should be positive"); if (_p <= 0 || _p >= M_PI/2.) throw FATALERROR("The pitch angle should be between 0 and 90 degrees"); if (_R0 <= 0) throw FATALERROR("The radius zero-point should be positive"); if (_phi0 < 0 || _phi0 > 2.0*M_PI) throw FATALERROR("The phase zero-point should be between 0 and 360 degrees"); if (_w <= 0 || _w > 1.) throw FATALERROR("The weight of the spiral perturbation should be between 0 and 1"); if (_N < 0 || _N > 10) throw FATALERROR("The arm-interarm size ratio index should be between 0 and 10"); // cache frequently used values _tanp = tan(_p); _CN = sqrt(M_PI) * SpecialFunctions::gamma(_N+1.0) / SpecialFunctions::gamma(_N+0.5); _c = 1.0+(_CN-1.0)*_w; } //////////////////////////////////////////////////////////////////// void SpiralStructureGeometry::setGeometry(AxGeometry* value) { if (_geometry) delete _geometry; _geometry = value; if (_geometry) _geometry->setParent(this); } //////////////////////////////////////////////////////////////////// AxGeometry* SpiralStructureGeometry::geometry() const { return _geometry; } //////////////////////////////////////////////////////////////////// void SpiralStructureGeometry::setArms(int value) { _m = value; } //////////////////////////////////////////////////////////////////// int SpiralStructureGeometry::arms() const { return _m; } //////////////////////////////////////////////////////////////////// void SpiralStructureGeometry::setPitch(double value) { _p = value; } //////////////////////////////////////////////////////////////////// double SpiralStructureGeometry::pitch() const { return _p; } //////////////////////////////////////////////////////////////////// void SpiralStructureGeometry::setRadius(double value) { _R0 = value; } //////////////////////////////////////////////////////////////////// double SpiralStructureGeometry::radius() const { return _R0; } //////////////////////////////////////////////////////////////////// void SpiralStructureGeometry::setPhase(double value) { _phi0 = value; } //////////////////////////////////////////////////////////////////// double SpiralStructureGeometry::phase() const { return _phi0; } //////////////////////////////////////////////////////////////////// void SpiralStructureGeometry::setPerturbWeight(double value) { _w = value; } //////////////////////////////////////////////////////////////////// double SpiralStructureGeometry::perturbWeight() const { return _w; } //////////////////////////////////////////////////////////////////// void SpiralStructureGeometry::setIndex(int value) { _N = value; } //////////////////////////////////////////////////////////////////// int SpiralStructureGeometry::index() const { return _N; } //////////////////////////////////////////////////////////////////// double SpiralStructureGeometry::density(Position bfr) const { double R, phi, z; bfr.cylindrical(R,phi,z); return _geometry->density(R,z) * perturbation(R,phi); } //////////////////////////////////////////////////////////////////// Position SpiralStructureGeometry::generatePosition() const { Position bfr = _geometry->generatePosition(); double R, dummyphi, z; bfr.cylindrical(R,dummyphi,z); double c = 1.0+(_CN-1.0)*_w; double phi, t; do { phi = 2.0*M_PI*_random->uniform(); t = _random->uniform()*c/perturbation(R,phi); } while (t>1); return Position(R,phi,z,Position::CYLINDRICAL); } //////////////////////////////////////////////////////////////////// double SpiralStructureGeometry::SigmaX() const { return _geometry->SigmaX(); } //////////////////////////////////////////////////////////////////// double SpiralStructureGeometry::SigmaY() const { return _geometry->SigmaY(); } //////////////////////////////////////////////////////////////////// double SpiralStructureGeometry::SigmaZ() const { return _geometry->SigmaZ(); } //////////////////////////////////////////////////////////////////// double SpiralStructureGeometry::perturbation(double R, double phi) const { double gamma = log(R/_R0)/_tanp + _phi0 + 0.5*M_PI/_m; return (1.0-_w) + _w*_CN*pow(sin(0.5*_m*(gamma-phi)),2*_N); } //////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>#include "ins_sdk.h" #include <stdlib.h> #include <algorithm> using namespace galaxy::ins::sdk; extern "C" { typedef void (*SessionTimeoutCallback)(void*); typedef void (*CWatchCallback)(WatchParam*, long, SDKError); typedef void (*CTimeoutCallback)(long, void*); struct CallbackPack { void* callback_wrapper; long callback_id; void* ctx; }; void WatchCallbackWrapper(const WatchParam& param, SDKError error) { CallbackPack* pack = static_cast<CallbackPack*>(param.context); CWatchCallback cb = (CWatchCallback)pack->callback_wrapper; long callback_id = pack->callback_id; void* ctx = pack->ctx; delete pack; WatchParam p = param; p.context = ctx; cb(&p, callback_id, error); } void TimeoutWrapper(void* ctx) { CallbackPack* pack = static_cast<CallbackPack*>(ctx); CTimeoutCallback cb = (CTimeoutCallback)pack->callback_wrapper; long callback_id = pack->callback_id; void* context = pack->ctx; delete pack; cb(callback_id, context); } // ----- InsSDK Wrappers ----- InsSDK* GetSDK(const char* server_list) { return new InsSDK(server_list); } InsSDK* GetSDKFromArray(int count, const char* members[]) { std::vector<std::string> member_vec; for (int i = 0; i < count; ++i) { member_vec.push_back(members[i]); } return new InsSDK(member_vec); } void DeleteSDK(InsSDK* sdk) { if (sdk != NULL) { delete sdk; } } void DeleteClusterArray(ClusterNodeInfo* pointer) { if (pointer != NULL) { delete[] pointer; } } ClusterNodeInfo* SDKShowCluster(InsSDK* sdk, int* count) { if (sdk == NULL) { return NULL; } std::vector<ClusterNodeInfo> cluster_info; sdk->ShowCluster(&cluster_info); *count = cluster_info.size(); ClusterNodeInfo* cluster_arr = new ClusterNodeInfo[*count]; std::copy(cluster_info.begin(), cluster_info.end(), cluster_arr); return cluster_arr; } bool SDKPut(InsSDK* sdk, const char* key, const char* value, SDKError* error) { if (sdk == NULL) { *error = kPermissionDenied; return false; } return sdk->Put(key, value, error); } const char* SDKGet(InsSDK* sdk, const char* key, SDKError* error) { if (sdk == NULL) { *error = kPermissionDenied; return ""; } std::string value; sdk->Get(key, &value, error); return value.c_str(); } bool SDKDelete(InsSDK* sdk, const char* key, SDKError* error) { if (sdk == NULL) { *error = kPermissionDenied; return false; } return sdk->Delete(key, error); } ScanResult* SDKScan(InsSDK* sdk, const char* start_key, const char* end_key) { if (sdk == NULL) { return NULL; } return sdk->Scan(start_key, end_key); } // NOTE: This interface is customized for python sdk. // For other purpose, please implement another watch interface bool SDKWatch(InsSDK* sdk, const char* key, CWatchCallback wrapper, long callback_id, void* context, SDKError* error) { if (sdk == NULL) { return false; } CallbackPack* pack = new CallbackPack; pack->callback_wrapper = (void*)(wrapper); pack->callback_id = callback_id; pack->ctx = context; return sdk->Watch(key, WatchCallbackWrapper, pack, error); } bool SDKLock(InsSDK* sdk, const char* key, SDKError* error) { if (sdk == NULL) { *error = kPermissionDenied; return false; } return sdk->Lock(key, error); } bool SDKTryLock(InsSDK* sdk, const char* key, SDKError* error) { if (sdk == NULL) { *error = kPermissionDenied; return false; } return sdk->TryLock(key, error); } bool SDKUnLock(InsSDK* sdk, const char* key, SDKError* error) { if (sdk == NULL) { *error = kPermissionDenied; return false; } return sdk->UnLock(key, error); } bool SDKLogin(InsSDK* sdk, const char* username, const char* password, SDKError* error) { if (sdk == NULL) { *error = kPermissionDenied; return false; } return sdk->Login(username, password, error); } bool SDKLogout(InsSDK* sdk, SDKError* error) { if (sdk == NULL) { *error = kPermissionDenied; return false; } return sdk->Logout(error); } bool SDKRegister(InsSDK* sdk, const char* username, const char* password, SDKError* error) { if (sdk == NULL) { *error = kPermissionDenied; return false; } return sdk->Register(username, password, error); } const char* SDKGetSessionID(InsSDK* sdk) { if (sdk == NULL) { return ""; } return sdk->GetSessionID().c_str(); } const char* SDKGetCurrentUserID(InsSDK* sdk) { if (sdk == NULL) { return ""; } return sdk->GetCurrentUserID().c_str(); } bool SDKIsLoggedIn(InsSDK* sdk) { if (sdk == NULL) { return false; } return sdk->IsLoggedIn(); } // NOTE: This interface is customized for python sdk. // For other purpose, please implement another interface void SDKRegisterSessionTimeout(InsSDK* sdk, SessionTimeoutCallback handle_session_timeout, long callback_id, void* ctx) { if (sdk == NULL) { return; } CallbackPack* pack = new CallbackPack(); pack->callback_wrapper = (void*)(handle_session_timeout); pack->callback_id = callback_id; pack->ctx = ctx; sdk->RegisterSessionTimeout(handle_session_timeout, ctx); } // ----- ScanResult Wrappers ----- void DeleteScanResult(ScanResult* result) { if (result != NULL) { delete result; } } bool ScanResultDone(ScanResult* result) { if (result == NULL) { return false; } return result->Done(); } SDKError ScanResultError(ScanResult* result) { if (result == NULL) { return kPermissionDenied; } return result->Error(); } const char* ScanResultKey(ScanResult* result) { if (result == NULL) { return ""; } return result->Key().c_str(); } const char* ScanResultValue(ScanResult* result) { if (result == NULL) { return ""; } return result->Value().c_str(); } void ScanResultNext(ScanResult* result) { if (result == NULL) { return; } result->Next(); } } <commit_msg>Use abstract function pointer instead of c-style casting<commit_after>#include "ins_sdk.h" #include <stdlib.h> #include <algorithm> using namespace galaxy::ins::sdk; extern "C" { typedef void (*SessionTimeoutCallback)(void*); typedef void (*CWatchCallback)(WatchParam*, long, SDKError); typedef void (*CTimeoutCallback)(long, void*); typedef void (*AbstractFunc)(); struct CallbackPack { AbstractFunc callback_wrapper; long callback_id; void* ctx; }; void WatchCallbackWrapper(const WatchParam& param, SDKError error) { CallbackPack* pack = static_cast<CallbackPack*>(param.context); CWatchCallback cb = (CWatchCallback)pack->callback_wrapper; long callback_id = pack->callback_id; void* ctx = pack->ctx; delete pack; WatchParam p = param; p.context = ctx; cb(&p, callback_id, error); } void TimeoutWrapper(void* ctx) { CallbackPack* pack = static_cast<CallbackPack*>(ctx); CTimeoutCallback cb = (CTimeoutCallback)pack->callback_wrapper; long callback_id = pack->callback_id; void* context = pack->ctx; delete pack; cb(callback_id, context); } // ----- InsSDK Wrappers ----- InsSDK* GetSDK(const char* server_list) { return new InsSDK(server_list); } InsSDK* GetSDKFromArray(int count, const char* members[]) { std::vector<std::string> member_vec; for (int i = 0; i < count; ++i) { member_vec.push_back(members[i]); } return new InsSDK(member_vec); } void DeleteSDK(InsSDK* sdk) { if (sdk != NULL) { delete sdk; } } void DeleteClusterArray(ClusterNodeInfo* pointer) { if (pointer != NULL) { delete[] pointer; } } ClusterNodeInfo* SDKShowCluster(InsSDK* sdk, int* count) { if (sdk == NULL) { return NULL; } std::vector<ClusterNodeInfo> cluster_info; sdk->ShowCluster(&cluster_info); *count = cluster_info.size(); ClusterNodeInfo* cluster_arr = new ClusterNodeInfo[*count]; std::copy(cluster_info.begin(), cluster_info.end(), cluster_arr); return cluster_arr; } bool SDKPut(InsSDK* sdk, const char* key, const char* value, SDKError* error) { if (sdk == NULL) { *error = kPermissionDenied; return false; } return sdk->Put(key, value, error); } const char* SDKGet(InsSDK* sdk, const char* key, SDKError* error) { if (sdk == NULL) { *error = kPermissionDenied; return ""; } std::string value; sdk->Get(key, &value, error); return value.c_str(); } bool SDKDelete(InsSDK* sdk, const char* key, SDKError* error) { if (sdk == NULL) { *error = kPermissionDenied; return false; } return sdk->Delete(key, error); } ScanResult* SDKScan(InsSDK* sdk, const char* start_key, const char* end_key) { if (sdk == NULL) { return NULL; } return sdk->Scan(start_key, end_key); } // NOTE: This interface is customized for python sdk. // For other purpose, please implement another watch interface bool SDKWatch(InsSDK* sdk, const char* key, CWatchCallback wrapper, long callback_id, void* context, SDKError* error) { if (sdk == NULL) { return false; } CallbackPack* pack = new CallbackPack; pack->callback_wrapper = reinterpret_cast<AbstractFunc>(wrapper); pack->callback_id = callback_id; pack->ctx = context; return sdk->Watch(key, WatchCallbackWrapper, pack, error); } bool SDKLock(InsSDK* sdk, const char* key, SDKError* error) { if (sdk == NULL) { *error = kPermissionDenied; return false; } return sdk->Lock(key, error); } bool SDKTryLock(InsSDK* sdk, const char* key, SDKError* error) { if (sdk == NULL) { *error = kPermissionDenied; return false; } return sdk->TryLock(key, error); } bool SDKUnLock(InsSDK* sdk, const char* key, SDKError* error) { if (sdk == NULL) { *error = kPermissionDenied; return false; } return sdk->UnLock(key, error); } bool SDKLogin(InsSDK* sdk, const char* username, const char* password, SDKError* error) { if (sdk == NULL) { *error = kPermissionDenied; return false; } return sdk->Login(username, password, error); } bool SDKLogout(InsSDK* sdk, SDKError* error) { if (sdk == NULL) { *error = kPermissionDenied; return false; } return sdk->Logout(error); } bool SDKRegister(InsSDK* sdk, const char* username, const char* password, SDKError* error) { if (sdk == NULL) { *error = kPermissionDenied; return false; } return sdk->Register(username, password, error); } const char* SDKGetSessionID(InsSDK* sdk) { if (sdk == NULL) { return ""; } return sdk->GetSessionID().c_str(); } const char* SDKGetCurrentUserID(InsSDK* sdk) { if (sdk == NULL) { return ""; } return sdk->GetCurrentUserID().c_str(); } bool SDKIsLoggedIn(InsSDK* sdk) { if (sdk == NULL) { return false; } return sdk->IsLoggedIn(); } // NOTE: This interface is customized for python sdk. // For other purpose, please implement another interface void SDKRegisterSessionTimeout(InsSDK* sdk, SessionTimeoutCallback handle_session_timeout, long callback_id, void* ctx) { if (sdk == NULL) { return; } CallbackPack* pack = new CallbackPack(); pack->callback_wrapper = reinterpret_cast<AbstractFunc>(handle_session_timeout); pack->callback_id = callback_id; pack->ctx = ctx; sdk->RegisterSessionTimeout(handle_session_timeout, ctx); } // ----- ScanResult Wrappers ----- void DeleteScanResult(ScanResult* result) { if (result != NULL) { delete result; } } bool ScanResultDone(ScanResult* result) { if (result == NULL) { return false; } return result->Done(); } SDKError ScanResultError(ScanResult* result) { if (result == NULL) { return kPermissionDenied; } return result->Error(); } const char* ScanResultKey(ScanResult* result) { if (result == NULL) { return ""; } return result->Key().c_str(); } const char* ScanResultValue(ScanResult* result) { if (result == NULL) { return ""; } return result->Value().c_str(); } void ScanResultNext(ScanResult* result) { if (result == NULL) { return; } result->Next(); } } <|endoftext|>
<commit_before>#include "core.h" #include "trim.h" #include "instruction_list.h" #include "window.h" #include "logger.h" #include "threaded_queue.h" #include <ncurses.h> #include <unistd.h> #include <string> #include <iomanip> #include <sstream> #include <iostream> #include <fstream> #include <bitset> #include <chrono> #include <thread> #include "osc/OscReceivedElements.h" #include "osc/OscPacketListener.h" #include "ip/UdpSocket.h" using namespace std; string machine_word(uint32_t word) { stringstream ss; ss << setfill('0') << setw(8) << hex << word; return ss.str(); } struct StatusDisplay { virtual void draw(const InstructionList &il, const Core &core, const vector<Instruction> &memory) const = 0; }; template <typename T> class BoxedWindow : public Window, public StatusDisplay { public: BoxedWindow(const string &title, WINDOW *parent, int height, int starty, int startx) : Window(parent, height, get_width(), starty, startx) , contents(*this, height - 2, 1, 1) { box(0, 0); w_attron(A_BOLD); print(0, (get_width() - title.size()) / 2, title); w_attroff(A_BOLD); } void draw(const InstructionList &il, const Core &core, const vector<Instruction> &memory) const override { contents.draw(il, core, memory); refresh(); } static int get_width() { return 2 + T::get_width(); } private: T contents; }; class MachineCodeWindow : public Window, public StatusDisplay { public: MachineCodeWindow(WINDOW *parent, int height, int starty, int startx) : Window(parent, height, get_width(), starty, startx) { } void draw(const InstructionList &il, const Core &core, const vector<Instruction> &memory) const { erase(); for (auto i = 0; i != memory.size(); ++i) { auto attr = i == core.ip; if (attr) w_attron(A_BOLD | COLOR_PAIR(1)); print(i, 0, machine_word(memory[i].raw)); if (attr) w_attroff(A_BOLD | COLOR_PAIR(1)); } refresh(); } static int get_width() { return 8; } }; class MnemonicWindow : public Window, public StatusDisplay { public: MnemonicWindow(WINDOW *parent, int height, int starty, int startx) : Window(parent, height, get_width(), starty, startx) { } void draw(const InstructionList &il, const Core &core, const vector<Instruction> &memory) const { erase(); auto line = 0; for (const auto &i : memory) { auto attr = line == core.ip; if (attr) w_attron(A_BOLD | COLOR_PAIR(1)); print(line, 0, il.disassemble(i)); if (attr) w_attroff(A_BOLD | COLOR_PAIR(1)); line += 1; } refresh(); } static int get_width() { return 32; } }; class TooltipWindow : public Window, public StatusDisplay { public: TooltipWindow(WINDOW *parent, int height, int starty, int startx) : Window(parent, height, get_width(), starty, startx) { } void draw(const InstructionList &il, const Core &core, const vector<Instruction> &memory) const { erase(); auto line = 0; for (const auto &i : memory) { auto attr = line == core.ip; if (attr) w_attron(A_BOLD | COLOR_PAIR(1)); print(line, 0, il.tooltip(i)); if (attr) w_attroff(A_BOLD | COLOR_PAIR(1)); line += 1; } refresh(); } static int get_width() { return 50; } }; class CoreCoreWindow : public Window, public StatusDisplay { public: CoreCoreWindow(WINDOW *parent, int height, int starty, int startx) : Window(parent, height, get_width(), starty, startx) { } void draw(const InstructionList &il, const Core &core, const vector<Instruction> &memory) const { erase(); auto register_string = [](auto i) { stringstream ss; ss << "R" << i; return ss.str(); }; auto line = 0; auto print_register = [this, &line](auto reg_id, auto value) { stringstream ss; ss << setw(3) << reg_id << ": " << machine_word(value); print(line, 0, ss.str()); line += 1; }; for (auto i = 0; i != 30; ++i) { print_register(register_string(i), core.reg[i]); } print_register("SP", core.sp); print_register("IP", core.ip); refresh(); } static int get_width() { return 5 + 8; } }; class CoreWindow : public Window { public: CoreWindow(WINDOW *parent, const InstructionList &il, int starty, int startx) : Window(parent, HEIGHT, BoxedWindow<MachineCodeWindow>::get_width() + BoxedWindow<MnemonicWindow>::get_width() + BoxedWindow<TooltipWindow>::get_width() + BoxedWindow<CoreCoreWindow>::get_width(), starty, startx) , il(il) , window_machine_code("ram", *this, HEIGHT, 0, 0) , window_mnemonic("code", *this, HEIGHT, 0, BoxedWindow<MachineCodeWindow>::get_width()) , window_tooltip("tooltips", *this, HEIGHT, 0, BoxedWindow<MachineCodeWindow>::get_width() + BoxedWindow<MnemonicWindow>::get_width()) , window_core("status", *this, HEIGHT, 0, BoxedWindow<MachineCodeWindow>::get_width() + BoxedWindow<MnemonicWindow>::get_width() + BoxedWindow<TooltipWindow>::get_width()) , memory(MEMORY_LOCATIONS) { } void set_memory(const vector<Instruction> &m) { auto limit = min(memory.size(), m.size()); copy(m.begin(), m.begin() + limit, memory.begin()); } void draw() { for (auto i : vector<StatusDisplay *>{&window_machine_code, &window_mnemonic, &window_tooltip, &window_core}) { i->draw(il, core, memory); } refresh(); } void execute() { il.execute(core, memory); core.ip = core.ip % MEMORY_LOCATIONS; } private: const InstructionList &il; static const int MEMORY_LOCATIONS = 32; static const int HEIGHT = 2 + MEMORY_LOCATIONS; BoxedWindow<MachineCodeWindow> window_machine_code; BoxedWindow<MnemonicWindow> window_mnemonic; BoxedWindow<TooltipWindow> window_tooltip; BoxedWindow<CoreCoreWindow> window_core; Core core; vector<Instruction> memory; }; class Input { public: enum class Type { TICK, KEY, }; Input(Type type = Type::TICK, int value = 0) : type(type), value(value) { } Type get_type() const {return type;} int get_value() const {return value;} private: Type type; int value; }; class OscReceiver : public osc::OscPacketListener { public: OscReceiver(ThreadedQueue<Input> &tq) : tq(tq) { } protected: void ProcessMessage(const osc::ReceivedMessage &m, const IpEndpointName &ip) override { try { if (m.AddressPattern() == string("/time_server")) { osc::ReceivedMessageArgumentStream args = m.ArgumentStream(); const char *str; args >> str >> osc::EndMessage; if (str == string("tick")) { tq.push(Input(Input::Type::TICK)); } } } catch (const osc::Exception &e) { cout << "error parsing message: " << m.AddressPattern() << ": " << e.what() << endl; } } private: ThreadedQueue<Input> &tq; }; // input queue // handles keyboard and osc input // osc receipt is done on a different thread, which pushes messages to the // queue on the main thread // keyboard input is done on main thread, messages pushed to queue // then, somewhere else, we can pull messages off the queue one at a time int main(int argc, char **argv) { auto clean_up = [] { echo(); keypad(stdscr, 0); nocbreak(); endwin(); }; Logger::restart(); InstructionList instruction_list; vector<Instruction> memory(32); try { initscr(); start_color(); cbreak(); keypad(stdscr, 1); noecho(); init_pair(1, COLOR_BLUE, COLOR_BLACK); if (argc != 2) { throw runtime_error("expected one argument"); } ifstream infile(argv[1]); auto index = 0; for (string line; getline(infile, line);) { if (!trim(line).empty()) { auto instr = instruction_list.assemble(line); memory[index++] = instr; } } } catch (const runtime_error &re) { clean_up(); cout << "Exception: " << re.what() << endl; return EXIT_FAILURE; } CoreWindow cw(stdscr, instruction_list, 0, 0); mutex global_mutex; ThreadedQueue<Input> inputs; OscReceiver receiver(inputs); UdpListeningReceiveSocket s( IpEndpointName(IpEndpointName::ANY_ADDRESS, 7000), &receiver); thread osc_thread([&s] { s.Run(); }); atomic_bool run_keyboard_thread(true); thread keyboard_thread([&run_keyboard_thread, &global_mutex, &inputs] { // set up file descriptor set with just stdin entry fd_set fd; FD_ZERO(&fd); FD_SET(fileno(stdin), &fd); // set up timeout struct struct timeval tv; tv.tv_sec = 1; tv.tv_usec = 0; // we keep running select with a short timeout // so essentially we check whether to keep polling input every // second, or after every stdin event while (run_keyboard_thread) { auto sav = fd; if (select(fileno(stdin) + 1, &sav, nullptr, nullptr, &tv) > 0) { // if there is some input to fetch, we lock the 'curses' mutex // and then use getch to find out what the key is lock_guard<mutex> lock(global_mutex); inputs.push(Input(Input::Type::KEY, getch())); } } }); auto clean_up_threads = [&s, &osc_thread, &run_keyboard_thread, &keyboard_thread] { s.AsynchronousBreak(); osc_thread.join(); run_keyboard_thread = false; keyboard_thread.join(); // no need to lock here because all other threads have been killed echo(); keypad(stdscr, 0); nocbreak(); endwin(); }; auto threaded_draw_refresh = [&global_mutex, &cw] { lock_guard<mutex> lock(global_mutex); cw.draw(); cw.refresh(); }; try { cw.set_memory(memory); threaded_draw_refresh(); auto quit = false; while (!quit) { Input popped; inputs.pop(popped); switch (popped.get_type()) { case Input::Type::TICK: cw.execute(); break; case Input::Type::KEY: auto key = popped.get_value(); // editing stuff goes here break; } // for the time being we assume that any input event will // require a redraw threaded_draw_refresh(); } clean_up_threads(); return EXIT_SUCCESS; } catch (const runtime_error &re) { clean_up_threads(); cout << "Exception: " << re.what() << endl; return EXIT_FAILURE; } } <commit_msg>trying to implement command queue for undo/redo<commit_after>#include "core.h" #include "trim.h" #include "instruction_list.h" #include "window.h" #include "logger.h" #include "threaded_queue.h" #include <ncurses.h> #include <unistd.h> #include <string> #include <iomanip> #include <sstream> #include <iostream> #include <fstream> #include <bitset> #include <chrono> #include <thread> #include "osc/OscReceivedElements.h" #include "osc/OscPacketListener.h" #include "ip/UdpSocket.h" using namespace std; string machine_word(uint32_t word) { stringstream ss; ss << setfill('0') << setw(8) << hex << word; return ss.str(); } struct StatusDisplay { virtual void draw(const InstructionList &il, const Core &core, const vector<Instruction> &memory) const = 0; }; template <typename T> class BoxedWindow : public Window, public StatusDisplay { public: BoxedWindow(const string &title, WINDOW *parent, int height, int starty, int startx) : Window(parent, height, get_width(), starty, startx) , contents(*this, height - 2, 1, 1) { box(0, 0); w_attron(A_BOLD); print(0, (get_width() - title.size()) / 2, title); w_attroff(A_BOLD); } void draw(const InstructionList &il, const Core &core, const vector<Instruction> &memory) const override { contents.draw(il, core, memory); } static int get_width() { return 2 + T::get_width(); } private: T contents; }; class MachineCodeWindow : public Window, public StatusDisplay { public: MachineCodeWindow(WINDOW *parent, int height, int starty, int startx) : Window(parent, height, get_width(), starty, startx) { } void draw(const InstructionList &il, const Core &core, const vector<Instruction> &memory) const { erase(); for (auto i = 0; i != memory.size(); ++i) { auto attr = i == core.ip; if (attr) w_attron(A_BOLD | COLOR_PAIR(1)); print(i, 0, machine_word(memory[i].raw)); if (attr) w_attroff(A_BOLD | COLOR_PAIR(1)); } refresh(); } static int get_width() { return 8; } }; class MnemonicWindow : public Window, public StatusDisplay { public: MnemonicWindow(WINDOW *parent, int height, int starty, int startx) : Window(parent, height, get_width(), starty, startx) { } void draw(const InstructionList &il, const Core &core, const vector<Instruction> &memory) const { erase(); auto line = 0; for (const auto &i : memory) { auto attr = line == core.ip; if (attr) w_attron(A_BOLD | COLOR_PAIR(1)); print(line, 0, il.disassemble(i)); if (attr) w_attroff(A_BOLD | COLOR_PAIR(1)); line += 1; } refresh(); } static int get_width() { return 32; } }; class TooltipWindow : public Window, public StatusDisplay { public: TooltipWindow(WINDOW *parent, int height, int starty, int startx) : Window(parent, height, get_width(), starty, startx) { } void draw(const InstructionList &il, const Core &core, const vector<Instruction> &memory) const { erase(); auto line = 0; for (const auto &i : memory) { auto attr = line == core.ip; if (attr) w_attron(A_BOLD | COLOR_PAIR(1)); print(line, 0, il.tooltip(i)); if (attr) w_attroff(A_BOLD | COLOR_PAIR(1)); line += 1; } refresh(); } static int get_width() { return 50; } }; class CoreCoreWindow : public Window, public StatusDisplay { public: CoreCoreWindow(WINDOW *parent, int height, int starty, int startx) : Window(parent, height, get_width(), starty, startx) { } void draw(const InstructionList &il, const Core &core, const vector<Instruction> &memory) const { erase(); auto register_string = [](auto i) { stringstream ss; ss << "R" << i; return ss.str(); }; auto line = 0; auto print_register = [this, &line](auto reg_id, auto value) { stringstream ss; ss << setw(3) << reg_id << ": " << machine_word(value); print(line, 0, ss.str()); line += 1; }; for (auto i = 0; i != 30; ++i) { print_register(register_string(i), core.reg[i]); } print_register("SP", core.sp); print_register("IP", core.ip); refresh(); } static int get_width() { return 5 + 8; } }; class CoreWindow : public Window { public: CoreWindow(WINDOW *parent, const InstructionList &il, int starty, int startx) : Window(parent, HEIGHT, decltype(window_machine_code)::get_width() + decltype(window_mnemonic)::get_width() + decltype(window_tooltip)::get_width() + decltype(window_core)::get_width(), starty, startx) , il(il) , window_machine_code("ram", *this, HEIGHT, 0, 0) , window_mnemonic("code", *this, HEIGHT, 0, decltype(window_machine_code)::get_width()) , window_tooltip("tooltips", *this, HEIGHT, 0, decltype(window_machine_code)::get_width() + decltype(window_mnemonic)::get_width()) , window_core("status", *this, HEIGHT, 0, decltype(window_machine_code)::get_width() + decltype(window_mnemonic)::get_width() + decltype(window_tooltip)::get_width()) , memory(MEMORY_LOCATIONS) { } void set_memory(const vector<Instruction> &m) { auto limit = min(memory.size(), m.size()); copy(m.begin(), m.begin() + limit, memory.begin()); } void draw() { for (auto i : vector<StatusDisplay *>{&window_machine_code, &window_mnemonic, &window_tooltip, &window_core}) { i->draw(il, core, memory); } refresh(); } void execute() { il.execute(core, memory); core.ip = core.ip % MEMORY_LOCATIONS; } private: const InstructionList &il; static const int MEMORY_LOCATIONS = 32; static const int HEIGHT = 2 + MEMORY_LOCATIONS; BoxedWindow<MachineCodeWindow> window_machine_code; BoxedWindow<MnemonicWindow> window_mnemonic; BoxedWindow<TooltipWindow> window_tooltip; BoxedWindow<CoreCoreWindow> window_core; Core core; vector<Instruction> memory; }; class Input { public: enum class Type { TICK, KEY, }; Input(Type type = Type::TICK, int value = 0) : type(type) , value(value) { } Type get_type() const { return type; } int get_value() const { return value; } private: Type type; int value; }; class OscReceiver : public osc::OscPacketListener { public: OscReceiver(ThreadedQueue<Input> &tq) : tq(tq) { } protected: void ProcessMessage(const osc::ReceivedMessage &m, const IpEndpointName &ip) override { try { if (m.AddressPattern() == string("/time_server")) { osc::ReceivedMessageArgumentStream args = m.ArgumentStream(); const char *str; args >> str >> osc::EndMessage; if (str == string("tick")) { tq.push(Input(Input::Type::TICK)); } } } catch (const osc::Exception &e) { cout << "error parsing message: " << m.AddressPattern() << ": " << e.what() << endl; } } private: ThreadedQueue<Input> &tq; }; class Editor; struct EditorCommand { virtual void do_command(Editor &e) = 0; virtual void undo_command(Editor &e) = 0; }; class Editor { public: Editor(const InstructionList &instruction_list) : instruction_list(instruction_list) , memory(32) { } void load_from_file(const string &fname) { ifstream infile(fname); auto index = 0; for (string line; getline(infile, line);) { if (!trim(line).empty()) { memory[index++] = instruction_list.assemble(line); } } } void do_command(unique_ptr<EditorCommand> &&command) { command->do_command(*this); commands.push(move(command)); } void undo_command() { if (!commands.empty()) { auto i = move(commands.front()); commands.pop(); i->undo_command(*this); } } void sync_from_memory() { transform(begin(memory), end(memory), begin(mnemonics), [this](auto i) { return instruction_list.disassemble(i); }); } void sync_from_mnemonics() { transform(begin(mnemonics), end(mnemonics), begin(memory), [this](auto i) { return instruction_list.assemble(i); }); } private: const InstructionList &instruction_list; queue<unique_ptr<EditorCommand>> commands; public: vector<Instruction> memory; vector<string> mnemonics; }; // Data required for do_command should be invariant/const // somehow it should be fed to the constructor class InsertCommand : public EditorCommand { public: InsertCommand(int character) : character(character) { } void do_command(Editor &e) override { // go to (y, x) and insert the character } void undo_command(Editor &e) override { // go to (y, x) and remove the character } private: const int character; }; class BackspaceCommand : public EditorCommand { public: void do_command(Editor &e) override { // go to (y, x) and insert the character } void undo_command(Editor &e) override { // go to (y, x) and remove the character } private: }; // input queue // handles keyboard and osc input // osc receipt is done on a different thread, which pushes messages to the // queue on the main thread // keyboard input is done on main thread, messages pushed to queue // then, somewhere else, we can pull messages off the queue one at a time int main(int argc, char **argv) { auto clean_up = [] { echo(); keypad(stdscr, 0); nocbreak(); endwin(); }; Logger::restart(); InstructionList instruction_list; Editor editor(instruction_list); try { initscr(); start_color(); cbreak(); keypad(stdscr, 1); noecho(); init_pair(1, COLOR_BLUE, COLOR_BLACK); if (argc != 2) { throw runtime_error("expected one argument"); } editor.load_from_file(argv[1]); } catch (const runtime_error &re) { clean_up(); cout << "Exception: " << re.what() << endl; return EXIT_FAILURE; } CoreWindow cw(stdscr, instruction_list, 0, 0); mutex global_mutex; ThreadedQueue<Input> inputs; OscReceiver receiver(inputs); UdpListeningReceiveSocket s( IpEndpointName(IpEndpointName::ANY_ADDRESS, 7000), &receiver); thread osc_thread([&s] { s.Run(); }); atomic_bool run_keyboard_thread(true); thread keyboard_thread([&run_keyboard_thread, &global_mutex, &inputs] { // set up file descriptor set with just stdin entry fd_set fd; FD_ZERO(&fd); FD_SET(fileno(stdin), &fd); // set up timeout struct struct timeval tv; tv.tv_sec = 1; tv.tv_usec = 0; // we keep running select with a short timeout // so essentially we check whether to keep polling input every // second, or after every stdin event while (run_keyboard_thread) { auto sav = fd; if (select(fileno(stdin) + 1, &sav, nullptr, nullptr, &tv) > 0) { // if there is some input to fetch, we lock the 'curses' mutex // and then use getch to find out what the key is lock_guard<mutex> lock(global_mutex); inputs.push(Input(Input::Type::KEY, getch())); } } }); auto clean_up_threads = [&s, &osc_thread, &run_keyboard_thread, &keyboard_thread] { s.AsynchronousBreak(); osc_thread.join(); run_keyboard_thread = false; keyboard_thread.join(); // no need to lock here because all other threads have been killed echo(); keypad(stdscr, 0); nocbreak(); endwin(); }; auto threaded_draw_refresh = [&global_mutex, &cw] { lock_guard<mutex> lock(global_mutex); cw.draw(); cw.refresh(); }; try { cw.set_memory(editor.memory); threaded_draw_refresh(); auto quit = false; while (!quit) { Input popped; inputs.pop(popped); switch (popped.get_type()) { case Input::Type::TICK: cw.execute(); break; case Input::Type::KEY: auto key = popped.get_value(); if (key < 127) { // int y, x; // getyx(stdscr, y, x); editor.do_command(make_unique<InsertCommand>(key)); } if (key == KEY_BACKSPACE) { editor.do_command(make_unique<BackspaceCommand>()); } /* if (key == UNDO) { editor.undo_command(); } */ break; } // for the time being we assume that any input event will // require a redraw threaded_draw_refresh(); } clean_up_threads(); return EXIT_SUCCESS; } catch (const runtime_error &re) { clean_up_threads(); cout << "Exception: " << re.what() << endl; return EXIT_FAILURE; } } <|endoftext|>
<commit_before>//#define CATCH_CONFIG_MAIN #include "catch.hpp" #include <regex.h> #include <shl_exception.h> using namespace shl; TEST_CASE("Range Test") { SECTION("default constructs a (0,0) Range") { Range range; REQUIRE(range.position == 0); REQUIRE(range.length == 0); } SECTION("constructs a Range by specify position&length") { Range range(100, 23); REQUIRE(range.position == 100); REQUIRE(range.length == 23); } SECTION("constructs by copy a range") { Range range2(10,20); Range range(range2); REQUIRE(range.position == 10); REQUIRE(range.length == 20); } SECTION("the Range object is assignable") { Range range, range2(10,20); range = range2; REQUIRE(range.position == 10); REQUIRE(range.length == 20); } SECTION("the end of Range is position plus length") { Range range(25, 456); REQUIRE(range.end() == (range.position + range.length)); } SECTION("Range can be compared equal/inequal") { Range range1(25, 30), range2(25, 30), range3(25, 31), range4(24, 30); REQUIRE(range1 == range2); REQUIRE(range1 == range1); REQUIRE_FALSE(range1 == range3); REQUIRE_FALSE(range1 == range4); REQUIRE(range1 != range3); REQUIRE(range1 != range4); } } TEST_CASE("Match Tests") { SECTION("match can be checked equality with MatcheRsult") { Match match; REQUIRE(match == Match::NOT_MATCHED); REQUIRE(Match::NOT_MATCHED == match); REQUIRE_FALSE(Match::MATCHED == match); REQUIRE(Match::MATCHED != match); REQUIRE(match != Match::MATCHED); } SECTION("default constructor creates a no match object") { Match match; REQUIRE( match == Match::NOT_MATCHED ); REQUIRE(match.size() == 0); } SECTION("dummy Match object can be created by make_dummy") { Match match = Match::make_dummy(0, 10); REQUIRE(match == Match::MATCHED); REQUIRE(match.size() == 1); REQUIRE(match[0] == Range(0, 10)); } } TEST_CASE("Regex can find matchs") { SECTION("find a simple match") { Regex r("\\d{3}-\\d{4}"); auto result = r.match("hello my Tel. is 322-0592", 0); REQUIRE( result == Match::MATCHED ); } SECTION("capture whole regex by default") { Regex r("\\d{3}-\\d{4}"); string target = "hello my Tel. is 322-0592"; auto result = r.match(target, 0); REQUIRE(result.size() == 1); REQUIRE(result[0] == Range(17, 8)); REQUIRE(result[0].substr(target) == "322-0592"); } SECTION("regex can capture groups") { Regex r("(\\d{3})-(\\d{4})"); string target = "hello my Tel. is 322-0592"; auto result = r.match(target, 0); REQUIRE(result.size() == 3); REQUIRE(result[0].substr(target) == "322-0592"); REQUIRE(result[1].substr(target) == "322"); REQUIRE(result[2].substr(target) == "0592"); } SECTION("regex can retrieve the source") { Regex r("\\d{3}-\\d{4}"); REQUIRE(r.source() == "\\d{3}-\\d{4}"); } SECTION("invalid regex will throw") { REQUIRE_THROWS_AS(Regex r("[}"), InvalidRegexException); } SECTION("default contructor create a empty regex") { Regex regex; REQUIRE(regex.empty()); } SECTION("empty regex match will throw") { Regex regex; REQUIRE_THROWS_AS(regex.match("hello world", 0), InvalidRegexException); } SECTION("regex can search from a position") { Regex r("abc"); auto result = r.match("abcdefg", 0); REQUIRE(result == Match::MATCHED); auto result2 = r.match("abcdefg", 2); REQUIRE(result2 == Match::NOT_MATCHED); } SECTION("\\G means matching start position") { Regex r("\\Gabc"); auto result1 = r.match("abcdef", 0); REQUIRE(result1 == Match::MATCHED); auto result2 = r.match(" abcdef", 0); REQUIRE(result2 == Match::NOT_MATCHED); auto result3 = r.match(" abcdef", 1); REQUIRE(result3 == Match::MATCHED); Regex r2("(?<=123)\\Gabc"); auto result4 = r2.match("123abc", 3); REQUIRE(result4 == Match::MATCHED); } SECTION("\\G means last match end, perl compatible") { Regex r("\\Gabc"); auto result1 = r.match("bstabcdef", 3, 3); REQUIRE(result1 == Match::MATCHED); auto result2 = r.match("bstabcdef", 3, 0); REQUIRE(result2 == Match::NOT_MATCHED); auto result3 = r.match("bstabcdef", 0, 3); REQUIRE(result2 == Match::NOT_MATCHED); Regex r2("(?<=bst)\\Gabc"); auto result4 = r2.match("bstabcdef", 3, 3); REQUIRE(result4 == Match::MATCHED); auto result5 = r2.match("bstabcdef", 0, 3); REQUIRE(result5 == Match::NOT_MATCHED); Regex r3("\\Gabc"); auto result6 = r3.match("bstabcdef", 0, 3); REQUIRE(result6 == Match::NOT_MATCHED); } } <commit_msg>add test for EndPatternRegex<commit_after>//#define CATCH_CONFIG_MAIN #include "catch.hpp" #include <regex.h> #include <shl_exception.h> using namespace shl; TEST_CASE("Range Test") { SECTION("default constructs a (0,0) Range") { Range range; REQUIRE(range.position == 0); REQUIRE(range.length == 0); } SECTION("constructs a Range by specify position&length") { Range range(100, 23); REQUIRE(range.position == 100); REQUIRE(range.length == 23); } SECTION("constructs by copy a range") { Range range2(10,20); Range range(range2); REQUIRE(range.position == 10); REQUIRE(range.length == 20); } SECTION("the Range object is assignable") { Range range, range2(10,20); range = range2; REQUIRE(range.position == 10); REQUIRE(range.length == 20); } SECTION("the end of Range is position plus length") { Range range(25, 456); REQUIRE(range.end() == (range.position + range.length)); } SECTION("Range can be compared equal/inequal") { Range range1(25, 30), range2(25, 30), range3(25, 31), range4(24, 30); REQUIRE(range1 == range2); REQUIRE(range1 == range1); REQUIRE_FALSE(range1 == range3); REQUIRE_FALSE(range1 == range4); REQUIRE(range1 != range3); REQUIRE(range1 != range4); } } TEST_CASE("Match Tests") { SECTION("match can be checked equality with MatcheRsult") { Match match; REQUIRE(match == Match::NOT_MATCHED); REQUIRE(Match::NOT_MATCHED == match); REQUIRE_FALSE(Match::MATCHED == match); REQUIRE(Match::MATCHED != match); REQUIRE(match != Match::MATCHED); } SECTION("default constructor creates a no match object") { Match match; REQUIRE( match == Match::NOT_MATCHED ); REQUIRE(match.size() == 0); } SECTION("dummy Match object can be created by make_dummy") { Match match = Match::make_dummy(0, 10); REQUIRE(match == Match::MATCHED); REQUIRE(match.size() == 1); REQUIRE(match[0] == Range(0, 10)); } } TEST_CASE("Regex can find matchs") { SECTION("find a simple match") { Regex r("\\d{3}-\\d{4}"); auto result = r.match("hello my Tel. is 322-0592", 0); REQUIRE( result == Match::MATCHED ); } SECTION("capture whole regex by default") { Regex r("\\d{3}-\\d{4}"); string target = "hello my Tel. is 322-0592"; auto result = r.match(target, 0); REQUIRE(result.size() == 1); REQUIRE(result[0] == Range(17, 8)); REQUIRE(result[0].substr(target) == "322-0592"); } SECTION("regex can capture groups") { Regex r("(\\d{3})-(\\d{4})"); string target = "hello my Tel. is 322-0592"; auto result = r.match(target, 0); REQUIRE(result.size() == 3); REQUIRE(result[0].substr(target) == "322-0592"); REQUIRE(result[1].substr(target) == "322"); REQUIRE(result[2].substr(target) == "0592"); } SECTION("regex can retrieve the source") { Regex r("\\d{3}-\\d{4}"); REQUIRE(r.source() == "\\d{3}-\\d{4}"); } SECTION("invalid regex will throw") { REQUIRE_THROWS_AS(Regex r("[}"), InvalidRegexException); } SECTION("default contructor create a empty regex") { Regex regex; REQUIRE(regex.empty()); } SECTION("empty regex match will throw") { Regex regex; REQUIRE_THROWS_AS(regex.match("hello world", 0), InvalidRegexException); } SECTION("regex can search from a position") { Regex r("abc"); auto result = r.match("abcdefg", 0); REQUIRE(result == Match::MATCHED); auto result2 = r.match("abcdefg", 2); REQUIRE(result2 == Match::NOT_MATCHED); } SECTION("\\G means matching start position") { Regex r("\\Gabc"); auto result1 = r.match("abcdef", 0); REQUIRE(result1 == Match::MATCHED); auto result2 = r.match(" abcdef", 0); REQUIRE(result2 == Match::NOT_MATCHED); auto result3 = r.match(" abcdef", 1); REQUIRE(result3 == Match::MATCHED); Regex r2("(?<=123)\\Gabc"); auto result4 = r2.match("123abc", 3); REQUIRE(result4 == Match::MATCHED); } SECTION("\\G means last match end, perl compatible") { Regex r("\\Gabc"); auto result1 = r.match("bstabcdef", 3, 3); REQUIRE(result1 == Match::MATCHED); auto result2 = r.match("bstabcdef", 3, 0); REQUIRE(result2 == Match::NOT_MATCHED); auto result3 = r.match("bstabcdef", 0, 3); REQUIRE(result2 == Match::NOT_MATCHED); Regex r2("(?<=bst)\\Gabc"); auto result4 = r2.match("bstabcdef", 3, 3); REQUIRE(result4 == Match::MATCHED); auto result5 = r2.match("bstabcdef", 0, 3); REQUIRE(result5 == Match::NOT_MATCHED); Regex r3("\\Gabc"); auto result6 = r3.match("bstabcdef", 0, 3); REQUIRE(result6 == Match::NOT_MATCHED); } } TEST_CASE("EndPatternRegex Test") { SECTION("EndPatternRegex can do everything Regex can do") { EndPatternRegex r("^(\\d{3})-(\\d{4})"); string str = "123-3456"; auto match = r.match(Match::make_dummy(0,0), str, 0); REQUIRE( match.size() == 3 ); } SECTION("EndPatternRegex will throw when invalid regex is passed") { REQUIRE_THROWS_AS(EndPatternRegex r("[}"), InvalidRegexException); } SECTION("EndPatternRegex will recgonize regex that has back references") { EndPatternRegex r("</\\1>"); REQUIRE( r.has_backref() ); EndPatternRegex r1("^(\\d{3})-(\\d{4})"); REQUIRE_FALSE( r1.has_backref() ); EndPatternRegex r2("^(\\d{3})-(\\\\\\\\1{4})"); REQUIRE_FALSE( r2.has_backref() ); EndPatternRegex r3("^(\\d{3})-(\\\\\\1{4})"); REQUIRE( r3.has_backref() ); } SECTION("can capture external back reference") { Regex r1("<(\\w+)>"); EndPatternRegex r2("</\\1>"); string str = "<div>hello</div>"; REQUIRE( r2.has_backref()); auto begin = r1.match(str, 0); auto end = r2.match(begin, str, 0); REQUIRE( begin.size() == 2 ); REQUIRE( end == Match::MATCHED ); REQUIRE( end.size() == 1 ); REQUIRE( end[0].substr(str) == "</div>" ); } SECTION("can capture many back reference") { Regex r1("(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(\\d*)"); EndPatternRegex r2("\\13haha"); string src = "abcdefghijkl12345hahaend"; REQUIRE( r2.has_backref() ); auto begin = r1.match(src, 0); REQUIRE( begin.size() == 14 ); auto end = r2.match(begin, src, 0); REQUIRE( end == Match::MATCHED ); REQUIRE( end.size() == 1 ); REQUIRE( end[0].substr(src) == "12345haha" ); } } <|endoftext|>
<commit_before>//#define CATCH_CONFIG_MAIN #include "catch.hpp" #include <regex.h> #include <shl_exception.h> using namespace shl; TEST_CASE("Range Test") { SECTION("default constructs a (0,0) Range") { Range range; REQUIRE(range.position == 0); REQUIRE(range.length == 0); } SECTION("constructs a Range by specify position&length") { Range range(100, 23); REQUIRE(range.position == 100); REQUIRE(range.length == 23); } SECTION("constructs by copy a range") { Range range2(10,20); Range range(range2); REQUIRE(range.position == 10); REQUIRE(range.length == 20); } SECTION("the Range object is assignable") { Range range, range2(10,20); range = range2; REQUIRE(range.position == 10); REQUIRE(range.length == 20); } SECTION("the end of Range is position plus length") { Range range(25, 456); REQUIRE(range.end() == (range.position + range.length)); } SECTION("Range can be compared equal/inequal") { Range range1(25, 30), range2(25, 30), range3(25, 31), range4(24, 30); REQUIRE(range1 == range2); REQUIRE(range1 == range1); REQUIRE_FALSE(range1 == range3); REQUIRE_FALSE(range1 == range4); REQUIRE(range1 != range3); REQUIRE(range1 != range4); } } TEST_CASE("Match Tests") { SECTION("default constructor creates a no match object") { Match match; REQUIRE_FALSE((bool)match); REQUIRE( match == Match::NOT_MATCHED ); REQUIRE(match.size() == 0); } SECTION("dummy Match object can be created by make_dummy") { Match match = Match::make_dummy(0, 10); REQUIRE((bool)match); REQUIRE(match == Match::MATCHED); REQUIRE(match.size() == 1); REQUIRE(match[0] == Range(0, 10)); } } TEST_CASE("Regex can find matchs") { SECTION("find a simple match") { Regex r("\\d{3}-\\d{4}"); auto result = r.match("hello my Tel. is 322-0592", 0); REQUIRE((bool)result); REQUIRE( result == Match::MATCHED ); } SECTION("capture whole regex by default") { Regex r("\\d{3}-\\d{4}"); string target = "hello my Tel. is 322-0592"; auto result = r.match(target, 0); REQUIRE(result.size() == 1); REQUIRE(result[0] == Range(17, 8)); REQUIRE(result[0].substr(target) == "322-0592"); } SECTION("regex can capture groups") { Regex r("(\\d{3})-(\\d{4})"); string target = "hello my Tel. is 322-0592"; auto result = r.match(target, 0); REQUIRE(result.size() == 3); REQUIRE(result[0].substr(target) == "322-0592"); REQUIRE(result[1].substr(target) == "322"); REQUIRE(result[2].substr(target) == "0592"); } SECTION("regex can retrieve the source") { Regex r("\\d{3}-\\d{4}"); REQUIRE(r.source() == "\\d{3}-\\d{4}"); } SECTION("invalid regex will throw") { REQUIRE_THROWS_AS(Regex r("[}"), InvalidRegexException); } SECTION("default contructor create a empty regex") { Regex regex; REQUIRE(regex.empty()); } SECTION("empty regex match will throw") { Regex regex; REQUIRE_THROWS_AS(regex.match("hello world", 0), InvalidRegexException); } SECTION("regex can search from a position") { Regex r("abc"); auto result = r.match("abcdefg", 0); REQUIRE(result == Match::MATCHED); auto result2 = r.match("abcdefg", 2); REQUIRE(result2 == Match::NOT_MATCHED); } SECTION("\\G means matching start position") { Regex r("\\Gabc"); auto result1 = r.match("abcdef", 0); REQUIRE(result1 == Match::MATCHED); auto result2 = r.match(" abcdef", 0); REQUIRE(result2 == Match::NOT_MATCHED); auto result3 = r.match(" abcdef", 1); REQUIRE(result3 == Match::MATCHED); Regex r2("(?<=123)\\Gabc"); auto result4 = r2.match("123abc", 3); REQUIRE(result4 == Match::MATCHED); } SECTION("\\G means last match end, perl compatible") { Regex r("\\Gabc"); auto result1 = r.match("bstabcdef", 3, 3); REQUIRE(result1 == Match::MATCHED); auto result2 = r.match("bstabcdef", 3, 0); REQUIRE(result2 == Match::NOT_MATCHED); auto result3 = r.match("bstabcdef", 0, 3); REQUIRE(result2 == Match::NOT_MATCHED); Regex r2("(?<=bst)\\Gabc"); auto result4 = r2.match("bstabcdef", 3, 3); REQUIRE(result4 == Match::MATCHED); auto result5 = r2.match("bstabcdef", 0, 3); REQUIRE(result5 == Match::NOT_MATCHED); Regex r3("\\Gabc"); auto result6 = r3.match("bstabcdef", 0, 3); REQUIRE(result6 == Match::MATCHED); } } <commit_msg>change the results<commit_after>//#define CATCH_CONFIG_MAIN #include "catch.hpp" #include <regex.h> #include <shl_exception.h> using namespace shl; TEST_CASE("Range Test") { SECTION("default constructs a (0,0) Range") { Range range; REQUIRE(range.position == 0); REQUIRE(range.length == 0); } SECTION("constructs a Range by specify position&length") { Range range(100, 23); REQUIRE(range.position == 100); REQUIRE(range.length == 23); } SECTION("constructs by copy a range") { Range range2(10,20); Range range(range2); REQUIRE(range.position == 10); REQUIRE(range.length == 20); } SECTION("the Range object is assignable") { Range range, range2(10,20); range = range2; REQUIRE(range.position == 10); REQUIRE(range.length == 20); } SECTION("the end of Range is position plus length") { Range range(25, 456); REQUIRE(range.end() == (range.position + range.length)); } SECTION("Range can be compared equal/inequal") { Range range1(25, 30), range2(25, 30), range3(25, 31), range4(24, 30); REQUIRE(range1 == range2); REQUIRE(range1 == range1); REQUIRE_FALSE(range1 == range3); REQUIRE_FALSE(range1 == range4); REQUIRE(range1 != range3); REQUIRE(range1 != range4); } } TEST_CASE("Match Tests") { SECTION("default constructor creates a no match object") { Match match; REQUIRE_FALSE((bool)match); REQUIRE( match == Match::NOT_MATCHED ); REQUIRE(match.size() == 0); } SECTION("dummy Match object can be created by make_dummy") { Match match = Match::make_dummy(0, 10); REQUIRE((bool)match); REQUIRE(match == Match::MATCHED); REQUIRE(match.size() == 1); REQUIRE(match[0] == Range(0, 10)); } } TEST_CASE("Regex can find matchs") { SECTION("find a simple match") { Regex r("\\d{3}-\\d{4}"); auto result = r.match("hello my Tel. is 322-0592", 0); REQUIRE((bool)result); REQUIRE( result == Match::MATCHED ); } SECTION("capture whole regex by default") { Regex r("\\d{3}-\\d{4}"); string target = "hello my Tel. is 322-0592"; auto result = r.match(target, 0); REQUIRE(result.size() == 1); REQUIRE(result[0] == Range(17, 8)); REQUIRE(result[0].substr(target) == "322-0592"); } SECTION("regex can capture groups") { Regex r("(\\d{3})-(\\d{4})"); string target = "hello my Tel. is 322-0592"; auto result = r.match(target, 0); REQUIRE(result.size() == 3); REQUIRE(result[0].substr(target) == "322-0592"); REQUIRE(result[1].substr(target) == "322"); REQUIRE(result[2].substr(target) == "0592"); } SECTION("regex can retrieve the source") { Regex r("\\d{3}-\\d{4}"); REQUIRE(r.source() == "\\d{3}-\\d{4}"); } SECTION("invalid regex will throw") { REQUIRE_THROWS_AS(Regex r("[}"), InvalidRegexException); } SECTION("default contructor create a empty regex") { Regex regex; REQUIRE(regex.empty()); } SECTION("empty regex match will throw") { Regex regex; REQUIRE_THROWS_AS(regex.match("hello world", 0), InvalidRegexException); } SECTION("regex can search from a position") { Regex r("abc"); auto result = r.match("abcdefg", 0); REQUIRE(result == Match::MATCHED); auto result2 = r.match("abcdefg", 2); REQUIRE(result2 == Match::NOT_MATCHED); } SECTION("\\G means matching start position") { Regex r("\\Gabc"); auto result1 = r.match("abcdef", 0); REQUIRE(result1 == Match::MATCHED); auto result2 = r.match(" abcdef", 0); REQUIRE(result2 == Match::NOT_MATCHED); auto result3 = r.match(" abcdef", 1); REQUIRE(result3 == Match::MATCHED); Regex r2("(?<=123)\\Gabc"); auto result4 = r2.match("123abc", 3); REQUIRE(result4 == Match::MATCHED); } SECTION("\\G means last match end, perl compatible") { Regex r("\\Gabc"); auto result1 = r.match("bstabcdef", 3, 3); REQUIRE(result1 == Match::MATCHED); auto result2 = r.match("bstabcdef", 3, 0); REQUIRE(result2 == Match::NOT_MATCHED); auto result3 = r.match("bstabcdef", 0, 3); REQUIRE(result2 == Match::NOT_MATCHED); Regex r2("(?<=bst)\\Gabc"); auto result4 = r2.match("bstabcdef", 3, 3); REQUIRE(result4 == Match::MATCHED); auto result5 = r2.match("bstabcdef", 0, 3); REQUIRE(result5 == Match::NOT_MATCHED); Regex r3("\\Gabc"); auto result6 = r3.match("bstabcdef", 0, 3); REQUIRE(result6 == Match::NOT_MATCHED); } } <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "build/build_config.h" #include "chrome/browser/browser_list.h" #include "base/logging.h" #include "base/message_loop.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_shutdown.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/profile_manager.h" #include "chrome/common/notification_service.h" #include "chrome/common/result_codes.h" #if defined(OS_WIN) // TODO(port): these can probably all go away, even on win #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #endif BrowserList::list_type BrowserList::browsers_; std::vector<BrowserList::Observer*> BrowserList::observers_; // static void BrowserList::AddBrowser(Browser* browser) { DCHECK(browser); browsers_.push_back(browser); g_browser_process->AddRefModule(); NotificationService::current()->Notify( NotificationType::BROWSER_OPENED, Source<Browser>(browser), NotificationService::NoDetails()); // Send out notifications after add has occurred. Do some basic checking to // try to catch evil observers that change the list from under us. std::vector<Observer*>::size_type original_count = observers_.size(); for (int i = 0; i < static_cast<int>(observers_.size()); i++) observers_[i]->OnBrowserAdded(browser); DCHECK_EQ(original_count, observers_.size()) << "observer list modified during notification"; } // static void BrowserList::RemoveBrowser(Browser* browser) { RemoveBrowserFrom(browser, &last_active_browsers_); bool close_app = (browsers_.size() == 1); NotificationService::current()->Notify( NotificationType::BROWSER_CLOSED, Source<Browser>(browser), Details<bool>(&close_app)); // Send out notifications before anything changes. Do some basic checking to // try to catch evil observers that change the list from under us. std::vector<Observer*>::size_type original_count = observers_.size(); for (int i = 0; i < static_cast<int>(observers_.size()); i++) observers_[i]->OnBrowserRemoving(browser); DCHECK_EQ(original_count, observers_.size()) << "observer list modified during notification"; RemoveBrowserFrom(browser, &browsers_); // If the last Browser object was destroyed, make sure we try to close any // remaining dependent windows too. if (browsers_.empty()) AllBrowsersClosed(); g_browser_process->ReleaseModule(); } // static void BrowserList::AddObserver(BrowserList::Observer* observer) { DCHECK(std::find(observers_.begin(), observers_.end(), observer) == observers_.end()) << "Adding an observer twice"; observers_.push_back(observer); } // static void BrowserList::RemoveObserver(BrowserList::Observer* observer) { std::vector<Observer*>::iterator place = std::find(observers_.begin(), observers_.end(), observer); if (place == observers_.end()) { NOTREACHED() << "Removing an observer that isn't registered."; return; } observers_.erase(place); } // static void BrowserList::CloseAllBrowsers(bool use_post) { // Before we close the browsers shutdown all session services. That way an // exit can restore all browsers open before exiting. ProfileManager::ShutdownSessionServices(); BrowserList::const_iterator iter; for (iter = BrowserList::begin(); iter != BrowserList::end();) { if (use_post) { (*iter)->window()->Close(); ++iter; } else { // This path is hit during logoff/power-down. In this case we won't get // a final message and so we force the browser to be deleted. Browser* browser = *iter; browser->window()->Close(); // Close doesn't immediately destroy the browser // (Browser::TabStripEmpty() uses invoke later) but when we're ending the // session we need to make sure the browser is destroyed now. So, invoke // DestroyBrowser to make sure the browser is deleted and cleanup can // happen. browser->window()->DestroyBrowser(); iter = BrowserList::begin(); if (iter != BrowserList::end() && browser == *iter) { // Destroying the browser should have removed it from the browser list. // We should never get here. NOTREACHED(); return; } } } } // static void BrowserList::WindowsSessionEnding() { // EndSession is invoked once per frame. Only do something the first time. static bool already_ended = false; if (already_ended) return; already_ended = true; browser_shutdown::OnShutdownStarting(browser_shutdown::END_SESSION); // Write important data first. g_browser_process->EndSession(); // Close all the browsers. BrowserList::CloseAllBrowsers(false); // Send out notification. This is used during testing so that the test harness // can properly shutdown before we exit. NotificationService::current()->Notify( NotificationType::SESSION_END, NotificationService::AllSources(), NotificationService::NoDetails()); // And shutdown. browser_shutdown::Shutdown(); #if defined(OS_WIN) // At this point the message loop is still running yet we've shut everything // down. If any messages are processed we'll likely crash. Exit now. ExitProcess(ResultCodes::NORMAL_EXIT); #else NOTIMPLEMENTED(); #endif } // static bool BrowserList::HasBrowserWithProfile(Profile* profile) { BrowserList::const_iterator iter; for (size_t i = 0; i < browsers_.size(); ++i) { if (browsers_[i]->profile() == profile) return true; } return false; } // static BrowserList::list_type BrowserList::last_active_browsers_; // static void BrowserList::SetLastActive(Browser* browser) { RemoveBrowserFrom(browser, &last_active_browsers_); last_active_browsers_.push_back(browser); for (int i = 0; i < static_cast<int>(observers_.size()); i++) observers_[i]->OnBrowserSetLastActive(browser); } // static Browser* BrowserList::GetLastActive() { if (!last_active_browsers_.empty()) return *(last_active_browsers_.rbegin()); return NULL; } // static Browser* BrowserList::GetLastActiveWithProfile(Profile* p) { list_type::reverse_iterator browser = last_active_browsers_.rbegin(); for (; browser != last_active_browsers_.rend(); ++browser) { if ((*browser)->profile() == p) { return *browser; } } return NULL; } // static Browser* BrowserList::FindBrowserWithType(Profile* p, Browser::Type t) { Browser* last_active = GetLastActive(); if (last_active && last_active->profile() == p && last_active->type() == t) return last_active; BrowserList::const_iterator i; for (i = BrowserList::begin(); i != BrowserList::end(); ++i) { if (*i == last_active) continue; if ((*i)->profile() == p && (*i)->type() == t) return *i; } return NULL; } // static Browser* BrowserList::FindBrowserWithProfile(Profile* p) { Browser* last_active = GetLastActive(); if (last_active && last_active->profile() == p) return last_active; BrowserList::const_iterator i; for (i = BrowserList::begin(); i != BrowserList::end(); ++i) { if (*i == last_active) continue; if ((*i)->profile() == p) return *i; } return NULL; } // static Browser* BrowserList::FindBrowserWithID(SessionID::id_type desired_id) { BrowserList::const_iterator i; for (i = BrowserList::begin(); i != BrowserList::end(); ++i) { if ((*i)->session_id().id() == desired_id) return *i; } return NULL; } // static size_t BrowserList::GetBrowserCountForType(Profile* p, Browser::Type type) { BrowserList::const_iterator i; size_t result = 0; for (i = BrowserList::begin(); i != BrowserList::end(); ++i) { if ((*i)->profile() == p && (*i)->type() == type) result++; } return result; } // static size_t BrowserList::GetBrowserCount(Profile* p) { BrowserList::const_iterator i; size_t result = 0; for (i = BrowserList::begin(); i != BrowserList::end(); ++i) { if ((*i)->profile() == p) result++; } return result; } // static bool BrowserList::IsOffTheRecordSessionActive() { BrowserList::const_iterator i; for (i = BrowserList::begin(); i != BrowserList::end(); ++i) { if ((*i)->profile()->IsOffTheRecord()) return true; } return false; } // static void BrowserList::RemoveBrowserFrom(Browser* browser, list_type* browser_list) { const iterator remove_browser = find(browser_list->begin(), browser_list->end(), browser); if (remove_browser != browser_list->end()) browser_list->erase(remove_browser); } TabContentsIterator::TabContentsIterator() : browser_iterator_(BrowserList::begin()), web_view_index_(-1), cur_(NULL) { Advance(); } void TabContentsIterator::Advance() { // Unless we're at the beginning (index = -1) or end (iterator = end()), // then the current TabContents should be valid. DCHECK(web_view_index_ || browser_iterator_ == BrowserList::end() || cur_) << "Trying to advance past the end"; // Update cur_ to the next TabContents in the list. for (;;) { web_view_index_++; while (web_view_index_ >= (*browser_iterator_)->tab_count()) { // advance browsers ++browser_iterator_; web_view_index_ = 0; if (browser_iterator_ == BrowserList::end()) { cur_ = NULL; return; } } TabContents* next_tab = (*browser_iterator_)->GetTabContentsAt(web_view_index_); if (next_tab) { cur_ = next_tab; return; } } } <commit_msg>Handling a case where the browser_iterator_ would be NULL. The DCHECK was fine but the code itself was missing the check.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "build/build_config.h" #include "chrome/browser/browser_list.h" #include "base/logging.h" #include "base/message_loop.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_shutdown.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/profile_manager.h" #include "chrome/common/notification_service.h" #include "chrome/common/result_codes.h" #if defined(OS_WIN) // TODO(port): these can probably all go away, even on win #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #endif BrowserList::list_type BrowserList::browsers_; std::vector<BrowserList::Observer*> BrowserList::observers_; // static void BrowserList::AddBrowser(Browser* browser) { DCHECK(browser); browsers_.push_back(browser); g_browser_process->AddRefModule(); NotificationService::current()->Notify( NotificationType::BROWSER_OPENED, Source<Browser>(browser), NotificationService::NoDetails()); // Send out notifications after add has occurred. Do some basic checking to // try to catch evil observers that change the list from under us. std::vector<Observer*>::size_type original_count = observers_.size(); for (int i = 0; i < static_cast<int>(observers_.size()); i++) observers_[i]->OnBrowserAdded(browser); DCHECK_EQ(original_count, observers_.size()) << "observer list modified during notification"; } // static void BrowserList::RemoveBrowser(Browser* browser) { RemoveBrowserFrom(browser, &last_active_browsers_); bool close_app = (browsers_.size() == 1); NotificationService::current()->Notify( NotificationType::BROWSER_CLOSED, Source<Browser>(browser), Details<bool>(&close_app)); // Send out notifications before anything changes. Do some basic checking to // try to catch evil observers that change the list from under us. std::vector<Observer*>::size_type original_count = observers_.size(); for (int i = 0; i < static_cast<int>(observers_.size()); i++) observers_[i]->OnBrowserRemoving(browser); DCHECK_EQ(original_count, observers_.size()) << "observer list modified during notification"; RemoveBrowserFrom(browser, &browsers_); // If the last Browser object was destroyed, make sure we try to close any // remaining dependent windows too. if (browsers_.empty()) AllBrowsersClosed(); g_browser_process->ReleaseModule(); } // static void BrowserList::AddObserver(BrowserList::Observer* observer) { DCHECK(std::find(observers_.begin(), observers_.end(), observer) == observers_.end()) << "Adding an observer twice"; observers_.push_back(observer); } // static void BrowserList::RemoveObserver(BrowserList::Observer* observer) { std::vector<Observer*>::iterator place = std::find(observers_.begin(), observers_.end(), observer); if (place == observers_.end()) { NOTREACHED() << "Removing an observer that isn't registered."; return; } observers_.erase(place); } // static void BrowserList::CloseAllBrowsers(bool use_post) { // Before we close the browsers shutdown all session services. That way an // exit can restore all browsers open before exiting. ProfileManager::ShutdownSessionServices(); BrowserList::const_iterator iter; for (iter = BrowserList::begin(); iter != BrowserList::end();) { if (use_post) { (*iter)->window()->Close(); ++iter; } else { // This path is hit during logoff/power-down. In this case we won't get // a final message and so we force the browser to be deleted. Browser* browser = *iter; browser->window()->Close(); // Close doesn't immediately destroy the browser // (Browser::TabStripEmpty() uses invoke later) but when we're ending the // session we need to make sure the browser is destroyed now. So, invoke // DestroyBrowser to make sure the browser is deleted and cleanup can // happen. browser->window()->DestroyBrowser(); iter = BrowserList::begin(); if (iter != BrowserList::end() && browser == *iter) { // Destroying the browser should have removed it from the browser list. // We should never get here. NOTREACHED(); return; } } } } // static void BrowserList::WindowsSessionEnding() { // EndSession is invoked once per frame. Only do something the first time. static bool already_ended = false; if (already_ended) return; already_ended = true; browser_shutdown::OnShutdownStarting(browser_shutdown::END_SESSION); // Write important data first. g_browser_process->EndSession(); // Close all the browsers. BrowserList::CloseAllBrowsers(false); // Send out notification. This is used during testing so that the test harness // can properly shutdown before we exit. NotificationService::current()->Notify( NotificationType::SESSION_END, NotificationService::AllSources(), NotificationService::NoDetails()); // And shutdown. browser_shutdown::Shutdown(); #if defined(OS_WIN) // At this point the message loop is still running yet we've shut everything // down. If any messages are processed we'll likely crash. Exit now. ExitProcess(ResultCodes::NORMAL_EXIT); #else NOTIMPLEMENTED(); #endif } // static bool BrowserList::HasBrowserWithProfile(Profile* profile) { BrowserList::const_iterator iter; for (size_t i = 0; i < browsers_.size(); ++i) { if (browsers_[i]->profile() == profile) return true; } return false; } // static BrowserList::list_type BrowserList::last_active_browsers_; // static void BrowserList::SetLastActive(Browser* browser) { RemoveBrowserFrom(browser, &last_active_browsers_); last_active_browsers_.push_back(browser); for (int i = 0; i < static_cast<int>(observers_.size()); i++) observers_[i]->OnBrowserSetLastActive(browser); } // static Browser* BrowserList::GetLastActive() { if (!last_active_browsers_.empty()) return *(last_active_browsers_.rbegin()); return NULL; } // static Browser* BrowserList::GetLastActiveWithProfile(Profile* p) { list_type::reverse_iterator browser = last_active_browsers_.rbegin(); for (; browser != last_active_browsers_.rend(); ++browser) { if ((*browser)->profile() == p) { return *browser; } } return NULL; } // static Browser* BrowserList::FindBrowserWithType(Profile* p, Browser::Type t) { Browser* last_active = GetLastActive(); if (last_active && last_active->profile() == p && last_active->type() == t) return last_active; BrowserList::const_iterator i; for (i = BrowserList::begin(); i != BrowserList::end(); ++i) { if (*i == last_active) continue; if ((*i)->profile() == p && (*i)->type() == t) return *i; } return NULL; } // static Browser* BrowserList::FindBrowserWithProfile(Profile* p) { Browser* last_active = GetLastActive(); if (last_active && last_active->profile() == p) return last_active; BrowserList::const_iterator i; for (i = BrowserList::begin(); i != BrowserList::end(); ++i) { if (*i == last_active) continue; if ((*i)->profile() == p) return *i; } return NULL; } // static Browser* BrowserList::FindBrowserWithID(SessionID::id_type desired_id) { BrowserList::const_iterator i; for (i = BrowserList::begin(); i != BrowserList::end(); ++i) { if ((*i)->session_id().id() == desired_id) return *i; } return NULL; } // static size_t BrowserList::GetBrowserCountForType(Profile* p, Browser::Type type) { BrowserList::const_iterator i; size_t result = 0; for (i = BrowserList::begin(); i != BrowserList::end(); ++i) { if ((*i)->profile() == p && (*i)->type() == type) result++; } return result; } // static size_t BrowserList::GetBrowserCount(Profile* p) { BrowserList::const_iterator i; size_t result = 0; for (i = BrowserList::begin(); i != BrowserList::end(); ++i) { if ((*i)->profile() == p) result++; } return result; } // static bool BrowserList::IsOffTheRecordSessionActive() { BrowserList::const_iterator i; for (i = BrowserList::begin(); i != BrowserList::end(); ++i) { if ((*i)->profile()->IsOffTheRecord()) return true; } return false; } // static void BrowserList::RemoveBrowserFrom(Browser* browser, list_type* browser_list) { const iterator remove_browser = find(browser_list->begin(), browser_list->end(), browser); if (remove_browser != browser_list->end()) browser_list->erase(remove_browser); } TabContentsIterator::TabContentsIterator() : browser_iterator_(BrowserList::begin()), web_view_index_(-1), cur_(NULL) { Advance(); } void TabContentsIterator::Advance() { // Unless we're at the beginning (index = -1) or end (iterator = end()), // then the current TabContents should be valid. DCHECK(web_view_index_ || browser_iterator_ == BrowserList::end() || cur_) << "Trying to advance past the end"; // Update cur_ to the next TabContents in the list. while (browser_iterator_ != BrowserList::end()) { web_view_index_++; while (web_view_index_ >= (*browser_iterator_)->tab_count()) { // advance browsers ++browser_iterator_; web_view_index_ = 0; if (browser_iterator_ == BrowserList::end()) { cur_ = NULL; return; } } TabContents* next_tab = (*browser_iterator_)->GetTabContentsAt(web_view_index_); if (next_tab) { cur_ = next_tab; return; } } } <|endoftext|>
<commit_before><commit_msg>Mac: turn on file access checks for the UI thread.<commit_after><|endoftext|>
<commit_before><commit_msg>Mac: Register for keychain notifications on the main thread. Fixes issues where SSL doesn't notice changes made to keychains, like plugging in a crypto-card after Chrome launches. BUG=37766,34767 TEST=None (manual testing)<commit_after><|endoftext|>
<commit_before><commit_msg>Move WinSock initialize earlier in the startup process. I ran into a case where my extension used the network; but because extensions are initialized earlier than WinSock init, the extension failed when trying to do a dns lookup. This only fails because it was in conjunction with the --single-process flag, so it is unlikely to effect others.<commit_after><|endoftext|>
<commit_before><commit_msg>Mac: Register for keychain notifications on the main thread. Fixes issues where SSL doesn't notice changes made to keychains, like plugging in a crypto-card after Chrome launches. BUG=37766,34767 TEST=None (manual testing)<commit_after><|endoftext|>
<commit_before><commit_msg>Add menu shortcuts on linux instead of & everywhere.<commit_after><|endoftext|>
<commit_before><commit_msg>Add missing ALLOW_THIS_IN_INITIALIZER_LIST...<commit_after><|endoftext|>
<commit_before><commit_msg>fix for bug: http://code.google.com/p/chromium/issues/detail?id=15547 There are cases where DidFinishDocumentLoadForFrame() and DidFinishLoadForFrame() can be called with no navigation_state.<commit_after><|endoftext|>
<commit_before><commit_msg>Revert 111004 - ASAN timeout on OutOfProcessPPAPITest.Crypto<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/path_service.h" #include "base/test/test_timeouts.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/test/test_server.h" #include "webkit/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace // In-process plugin test runner. See OutOfProcessPPAPITest below for the // out-of-process version. class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); FilePath::StringType pepper_plugin = plugin_lib.value(); pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests")); launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); // Give unlimited quota for files to Pepper tests. // TODO(dumi): remove this switch once we have a quota management // system in place. launch_arguments_.AppendSwitch(switches::kUnlimitedQuotaForFiles); } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; std::string query("testcase="); query += test_case; replacements.SetQuery(query.c_str(), url_parse::Component(0, query.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { net::TestServer test_server( net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("ppapi/tests"))); ASSERT_TRUE(test_server.Start()); RunTestURL( test_server.GetURL("files/test_case.html?testcase=" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); // See comment above TestingInstance in ppapi/test/testing_instance.h. // Basically it sets a series of numbered cookies. The value of "..." means // it's still working and we should continue to wait, any other value // indicates completion (in this case it will start with "PASS" or "FAIL"). // This keeps us from timing out on cookie waits for long tests. int progress_number = 0; std::string progress; while (true) { std::string cookie_name = StringPrintf("PPAPI_PROGRESS_%d", progress_number); progress = WaitUntilCookieNonEmpty(tab.get(), test_url, cookie_name.c_str(), TestTimeouts::large_test_timeout_ms()); if (progress != "...") break; progress_number++; } if (progress_number == 0) { // Failing the first time probably means the plugin wasn't loaded. ASSERT_FALSE(progress.empty()) << "Plugin couldn't be loaded. Make sure the PPAPI test plugin is " << "built, in the right place, and doesn't have any missing symbols."; } else { ASSERT_FALSE(progress.empty()) << "Test timed out."; } EXPECT_STREQ("PASS", progress.c_str()); } }; // Variant of PPAPITest that runs plugins out-of-process to test proxy // codepaths. class OutOfProcessPPAPITest : public PPAPITest { public: OutOfProcessPPAPITest() { // Run PPAPI out-of-process to exercise proxy implementations. launch_arguments_.AppendSwitch(switches::kPpapiOutOfProcess); } }; // Use these macros to run the tests for a specific interface. // Most interfaces should be tested with both macros. #define TEST_PPAPI_IN_PROCESS(test_name) \ TEST_F(PPAPITest, test_name) { \ RunTest(#test_name); \ } #define TEST_PPAPI_OUT_OF_PROCESS(test_name) \ TEST_F(OutOfProcessPPAPITest, test_name) { \ RunTest(#test_name); \ } // Similar macros that test over HTTP. #define TEST_PPAPI_IN_PROCESS_VIA_HTTP(test_name) \ TEST_F(PPAPITest, test_name) { \ RunTestViaHTTP(#test_name); \ } #define TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(test_name) \ TEST_F(OutOfProcessPPAPITest, test_name) { \ RunTestViaHTTP(#test_name); \ } // // Interface tests. // TEST_PPAPI_IN_PROCESS(Broker) TEST_PPAPI_OUT_OF_PROCESS(Broker) TEST_PPAPI_IN_PROCESS(Core) TEST_PPAPI_OUT_OF_PROCESS(Core) TEST_PPAPI_IN_PROCESS(CursorControl) TEST_PPAPI_OUT_OF_PROCESS(CursorControl) TEST_PPAPI_IN_PROCESS(Instance) // http://crbug.com/91729 TEST_PPAPI_OUT_OF_PROCESS(DISABLED_Instance) TEST_PPAPI_IN_PROCESS(Graphics2D) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS(Graphics2D) TEST_PPAPI_IN_PROCESS(ImageData) TEST_PPAPI_OUT_OF_PROCESS(ImageData) TEST_PPAPI_IN_PROCESS(Buffer) TEST_PPAPI_OUT_OF_PROCESS(Buffer) TEST_PPAPI_IN_PROCESS_VIA_HTTP(URLLoader) // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_URLLoader) { RunTestViaHTTP("URLLoader"); } TEST_PPAPI_IN_PROCESS(PaintAggregator) TEST_PPAPI_OUT_OF_PROCESS(PaintAggregator) TEST_PPAPI_IN_PROCESS(Scrollbar) // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Scrollbar) { RunTest("Scrollbar"); } TEST_PPAPI_IN_PROCESS(URLUtil) TEST_PPAPI_OUT_OF_PROCESS(URLUtil) TEST_PPAPI_IN_PROCESS(CharSet) TEST_PPAPI_OUT_OF_PROCESS(CharSet) TEST_PPAPI_IN_PROCESS(Var) // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Var) { RunTest("Var"); } TEST_PPAPI_IN_PROCESS(VarDeprecated) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS(VarDeprecated) // Windows defines 'PostMessage', so we have to undef it. #ifdef PostMessage #undef PostMessage #endif TEST_PPAPI_IN_PROCESS(PostMessage) // Times out: http://crbug.com/93260 TEST_F(OutOfProcessPPAPITest, FAILS_PostMessage) { RunTest("PostMessage"); } TEST_PPAPI_IN_PROCESS(Memory) TEST_PPAPI_OUT_OF_PROCESS(Memory) TEST_PPAPI_IN_PROCESS(QueryPolicy) //TEST_PPAPI_OUT_OF_PROCESS(QueryPolicy) TEST_PPAPI_IN_PROCESS(VideoDecoder) TEST_PPAPI_OUT_OF_PROCESS(VideoDecoder) // http://crbug.com/90039 and http://crbug.com/83443 (Mac) TEST_F(PPAPITest, FAILS_FileIO) { RunTestViaHTTP("FileIO"); } TEST_F(OutOfProcessPPAPITest, FAILS_FileIO) { RunTestViaHTTP("FileIO"); } TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileRef) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(FileRef) TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileSystem) // http://crbug.com/90040 TEST_F(OutOfProcessPPAPITest, FLAKY_FileSystem) { RunTestViaHTTP("FileSystem"); } #if defined(OS_POSIX) #define MAYBE_DirectoryReader FLAKY_DirectoryReader #else #define MAYBE_DirectoryReader DirectoryReader #endif // Flaky on Mac + Linux, maybe http://codereview.chromium.org/7094008 TEST_F(PPAPITest, MAYBE_DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } #if defined(ENABLE_P2P_APIS) // Flaky. http://crbug.com/84295 TEST_F(PPAPITest, FLAKY_Transport) { RunTest("Transport"); } // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Transport) { RunTestViaHTTP("Transport"); } #endif // ENABLE_P2P_APIS TEST_PPAPI_IN_PROCESS(UMA) // There is no proxy. TEST_F(OutOfProcessPPAPITest, FAILS_UMA) { RunTest("UMA"); } <commit_msg>Disables OutOfProcessPPAPITest.URLLoader on Windows as it often takes too long time<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 "base/file_util.h" #include "base/path_service.h" #include "base/test/test_timeouts.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/test/test_server.h" #include "webkit/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace // In-process plugin test runner. See OutOfProcessPPAPITest below for the // out-of-process version. class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); FilePath::StringType pepper_plugin = plugin_lib.value(); pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests")); launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); // Give unlimited quota for files to Pepper tests. // TODO(dumi): remove this switch once we have a quota management // system in place. launch_arguments_.AppendSwitch(switches::kUnlimitedQuotaForFiles); } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; std::string query("testcase="); query += test_case; replacements.SetQuery(query.c_str(), url_parse::Component(0, query.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { net::TestServer test_server( net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("ppapi/tests"))); ASSERT_TRUE(test_server.Start()); RunTestURL( test_server.GetURL("files/test_case.html?testcase=" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); // See comment above TestingInstance in ppapi/test/testing_instance.h. // Basically it sets a series of numbered cookies. The value of "..." means // it's still working and we should continue to wait, any other value // indicates completion (in this case it will start with "PASS" or "FAIL"). // This keeps us from timing out on cookie waits for long tests. int progress_number = 0; std::string progress; while (true) { std::string cookie_name = StringPrintf("PPAPI_PROGRESS_%d", progress_number); progress = WaitUntilCookieNonEmpty(tab.get(), test_url, cookie_name.c_str(), TestTimeouts::large_test_timeout_ms()); if (progress != "...") break; progress_number++; } if (progress_number == 0) { // Failing the first time probably means the plugin wasn't loaded. ASSERT_FALSE(progress.empty()) << "Plugin couldn't be loaded. Make sure the PPAPI test plugin is " << "built, in the right place, and doesn't have any missing symbols."; } else { ASSERT_FALSE(progress.empty()) << "Test timed out."; } EXPECT_STREQ("PASS", progress.c_str()); } }; // Variant of PPAPITest that runs plugins out-of-process to test proxy // codepaths. class OutOfProcessPPAPITest : public PPAPITest { public: OutOfProcessPPAPITest() { // Run PPAPI out-of-process to exercise proxy implementations. launch_arguments_.AppendSwitch(switches::kPpapiOutOfProcess); } }; // Use these macros to run the tests for a specific interface. // Most interfaces should be tested with both macros. #define TEST_PPAPI_IN_PROCESS(test_name) \ TEST_F(PPAPITest, test_name) { \ RunTest(#test_name); \ } #define TEST_PPAPI_OUT_OF_PROCESS(test_name) \ TEST_F(OutOfProcessPPAPITest, test_name) { \ RunTest(#test_name); \ } // Similar macros that test over HTTP. #define TEST_PPAPI_IN_PROCESS_VIA_HTTP(test_name) \ TEST_F(PPAPITest, test_name) { \ RunTestViaHTTP(#test_name); \ } #define TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(test_name) \ TEST_F(OutOfProcessPPAPITest, test_name) { \ RunTestViaHTTP(#test_name); \ } // // Interface tests. // TEST_PPAPI_IN_PROCESS(Broker) TEST_PPAPI_OUT_OF_PROCESS(Broker) TEST_PPAPI_IN_PROCESS(Core) TEST_PPAPI_OUT_OF_PROCESS(Core) TEST_PPAPI_IN_PROCESS(CursorControl) TEST_PPAPI_OUT_OF_PROCESS(CursorControl) TEST_PPAPI_IN_PROCESS(Instance) // http://crbug.com/91729 TEST_PPAPI_OUT_OF_PROCESS(DISABLED_Instance) TEST_PPAPI_IN_PROCESS(Graphics2D) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS(Graphics2D) TEST_PPAPI_IN_PROCESS(ImageData) TEST_PPAPI_OUT_OF_PROCESS(ImageData) TEST_PPAPI_IN_PROCESS(Buffer) TEST_PPAPI_OUT_OF_PROCESS(Buffer) TEST_PPAPI_IN_PROCESS_VIA_HTTP(URLLoader) // http://crbug.com/89961 #if defined(OS_WIN) // It often takes too long time (and fails otherwise) on Windows. #define MAYBE_URLLoader DISABLED_URLLoader #else #define MAYBE_URLLoader FAILS_URLLoader #endif TEST_F(OutOfProcessPPAPITest, MAYBE_URLLoader) { RunTestViaHTTP("URLLoader"); } TEST_PPAPI_IN_PROCESS(PaintAggregator) TEST_PPAPI_OUT_OF_PROCESS(PaintAggregator) TEST_PPAPI_IN_PROCESS(Scrollbar) // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Scrollbar) { RunTest("Scrollbar"); } TEST_PPAPI_IN_PROCESS(URLUtil) TEST_PPAPI_OUT_OF_PROCESS(URLUtil) TEST_PPAPI_IN_PROCESS(CharSet) TEST_PPAPI_OUT_OF_PROCESS(CharSet) TEST_PPAPI_IN_PROCESS(Var) // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Var) { RunTest("Var"); } TEST_PPAPI_IN_PROCESS(VarDeprecated) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS(VarDeprecated) // Windows defines 'PostMessage', so we have to undef it. #ifdef PostMessage #undef PostMessage #endif TEST_PPAPI_IN_PROCESS(PostMessage) // Times out: http://crbug.com/93260 TEST_F(OutOfProcessPPAPITest, FAILS_PostMessage) { RunTest("PostMessage"); } TEST_PPAPI_IN_PROCESS(Memory) TEST_PPAPI_OUT_OF_PROCESS(Memory) TEST_PPAPI_IN_PROCESS(QueryPolicy) //TEST_PPAPI_OUT_OF_PROCESS(QueryPolicy) TEST_PPAPI_IN_PROCESS(VideoDecoder) TEST_PPAPI_OUT_OF_PROCESS(VideoDecoder) // http://crbug.com/90039 and http://crbug.com/83443 (Mac) TEST_F(PPAPITest, FAILS_FileIO) { RunTestViaHTTP("FileIO"); } TEST_F(OutOfProcessPPAPITest, FAILS_FileIO) { RunTestViaHTTP("FileIO"); } TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileRef) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(FileRef) TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileSystem) // http://crbug.com/90040 TEST_F(OutOfProcessPPAPITest, FLAKY_FileSystem) { RunTestViaHTTP("FileSystem"); } #if defined(OS_POSIX) #define MAYBE_DirectoryReader FLAKY_DirectoryReader #else #define MAYBE_DirectoryReader DirectoryReader #endif // Flaky on Mac + Linux, maybe http://codereview.chromium.org/7094008 TEST_F(PPAPITest, MAYBE_DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } #if defined(ENABLE_P2P_APIS) // Flaky. http://crbug.com/84295 TEST_F(PPAPITest, FLAKY_Transport) { RunTest("Transport"); } // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Transport) { RunTestViaHTTP("Transport"); } #endif // ENABLE_P2P_APIS TEST_PPAPI_IN_PROCESS(UMA) // There is no proxy. TEST_F(OutOfProcessPPAPITest, FAILS_UMA) { RunTest("UMA"); } <|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 "base/file_util.h" #include "base/path_service.h" #include "base/test/test_timeouts.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/test/test_server.h" #include "webkit/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); FilePath::StringType pepper_plugin = plugin_lib.value(); pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests")); launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); // Give unlimited quota for files to Pepper tests. // TODO(dumi): remove this switch once we have a quota management // system in place. launch_arguments_.AppendSwitch(switches::kUnlimitedQuotaForFiles); #if defined(ENABLE_P2P_APIS) // Enable P2P API. launch_arguments_.AppendSwitch(switches::kEnableP2PApi); #endif // ENABLE_P2P_APIS } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; std::string query("testcase="); query += test_case; replacements.SetQuery(query.c_str(), url_parse::Component(0, query.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { net::TestServer test_server( net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("ppapi/tests"))); ASSERT_TRUE(test_server.Start()); RunTestURL( test_server.GetURL("files/test_case.html?testcase=" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); // First wait for the "starting" signal. This cookie is set at the start // of every test. Waiting for this separately allows us to avoid a single // long timeout. Instead, we can have two timeouts which allow startup + // test execution time to take a while on a loaded computer, while also // making sure we're making forward progress. std::string startup_cookie = WaitUntilCookieNonEmpty(tab.get(), test_url, "STARTUP_COOKIE", TestTimeouts::action_max_timeout_ms()); // If this fails, the plugin couldn't be loaded in the given amount of // time. This may mean the plugin was not found or possibly the system // can't load it due to missing symbols, etc. ASSERT_STREQ("STARTED", startup_cookie.c_str()) << "Plugin couldn't be loaded. Make sure the PPAPI test plugin is " << "built, in the right place, and doesn't have any missing symbols."; std::string escaped_value = WaitUntilCookieNonEmpty(tab.get(), test_url, "COMPLETION_COOKIE", TestTimeouts::large_test_timeout_ms()); EXPECT_STREQ("PASS", escaped_value.c_str()); } }; TEST_F(PPAPITest, Broker) { RunTest("Broker"); } TEST_F(PPAPITest, CursorControl) { RunTest("CursorControl"); } TEST_F(PPAPITest, FAILS_Instance) { RunTest("Instance"); } TEST_F(PPAPITest, Graphics2D) { RunTest("Graphics2D"); } TEST_F(PPAPITest, ImageData) { RunTest("ImageData"); } TEST_F(PPAPITest, Buffer) { RunTest("Buffer"); } TEST_F(PPAPITest, URLLoader) { RunTestViaHTTP("URLLoader"); } TEST_F(PPAPITest,PaintAggregator) { RunTestViaHTTP("PaintAggregator"); } TEST_F(PPAPITest, Scrollbar) { RunTest("Scrollbar"); } TEST_F(PPAPITest, URLUtil) { RunTest("URLUtil"); } TEST_F(PPAPITest, CharSet) { RunTest("CharSet"); } TEST_F(PPAPITest, VarDeprecated) { RunTest("VarDeprecated"); } TEST_F(PPAPITest, PostMessage) { RunTest("PostMessage"); } // http://crbug.com/83443 TEST_F(PPAPITest, FAILS_FileIO) { RunTestViaHTTP("FileIO"); } TEST_F(PPAPITest, FileRef) { RunTestViaHTTP("FileRef"); } TEST_F(PPAPITest, DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } #if defined(ENABLE_P2P_APIS) TEST_F(PPAPITest, Transport) { RunTest("Transport"); } #endif // ENABLE_P2P_APIS <commit_msg>Mark DirectoryReader test flaky on Mac.<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 "base/file_util.h" #include "base/path_service.h" #include "base/test/test_timeouts.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/test/test_server.h" #include "webkit/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); FilePath::StringType pepper_plugin = plugin_lib.value(); pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests")); launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); // Give unlimited quota for files to Pepper tests. // TODO(dumi): remove this switch once we have a quota management // system in place. launch_arguments_.AppendSwitch(switches::kUnlimitedQuotaForFiles); #if defined(ENABLE_P2P_APIS) // Enable P2P API. launch_arguments_.AppendSwitch(switches::kEnableP2PApi); #endif // ENABLE_P2P_APIS } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; std::string query("testcase="); query += test_case; replacements.SetQuery(query.c_str(), url_parse::Component(0, query.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { net::TestServer test_server( net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("ppapi/tests"))); ASSERT_TRUE(test_server.Start()); RunTestURL( test_server.GetURL("files/test_case.html?testcase=" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); // First wait for the "starting" signal. This cookie is set at the start // of every test. Waiting for this separately allows us to avoid a single // long timeout. Instead, we can have two timeouts which allow startup + // test execution time to take a while on a loaded computer, while also // making sure we're making forward progress. std::string startup_cookie = WaitUntilCookieNonEmpty(tab.get(), test_url, "STARTUP_COOKIE", TestTimeouts::action_max_timeout_ms()); // If this fails, the plugin couldn't be loaded in the given amount of // time. This may mean the plugin was not found or possibly the system // can't load it due to missing symbols, etc. ASSERT_STREQ("STARTED", startup_cookie.c_str()) << "Plugin couldn't be loaded. Make sure the PPAPI test plugin is " << "built, in the right place, and doesn't have any missing symbols."; std::string escaped_value = WaitUntilCookieNonEmpty(tab.get(), test_url, "COMPLETION_COOKIE", TestTimeouts::large_test_timeout_ms()); EXPECT_STREQ("PASS", escaped_value.c_str()); } }; TEST_F(PPAPITest, Broker) { RunTest("Broker"); } TEST_F(PPAPITest, CursorControl) { RunTest("CursorControl"); } TEST_F(PPAPITest, FAILS_Instance) { RunTest("Instance"); } TEST_F(PPAPITest, Graphics2D) { RunTest("Graphics2D"); } TEST_F(PPAPITest, ImageData) { RunTest("ImageData"); } TEST_F(PPAPITest, Buffer) { RunTest("Buffer"); } TEST_F(PPAPITest, URLLoader) { RunTestViaHTTP("URLLoader"); } TEST_F(PPAPITest,PaintAggregator) { RunTestViaHTTP("PaintAggregator"); } TEST_F(PPAPITest, Scrollbar) { RunTest("Scrollbar"); } TEST_F(PPAPITest, URLUtil) { RunTest("URLUtil"); } TEST_F(PPAPITest, CharSet) { RunTest("CharSet"); } TEST_F(PPAPITest, VarDeprecated) { RunTest("VarDeprecated"); } TEST_F(PPAPITest, PostMessage) { RunTest("PostMessage"); } // http://crbug.com/83443 TEST_F(PPAPITest, FAILS_FileIO) { RunTestViaHTTP("FileIO"); } TEST_F(PPAPITest, FileRef) { RunTestViaHTTP("FileRef"); } #if defined(OS_MACOSX) #define MAYBE_DirectoryReader FLAKY_DirectoryReader #else #define MAYBE_DirectoryReader DirectoryReader #endif // Flaky on Mac, http://crbug.com/7094008. TEST_F(PPAPITest, MAYBE_DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } #if defined(ENABLE_P2P_APIS) TEST_F(PPAPITest, Transport) { RunTest("Transport"); } #endif // ENABLE_P2P_APIS <|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/file_util.h" #include "base/path_service.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/test/test_server.h" #include "webkit/glue/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); FilePath::StringType pepper_plugin = plugin_lib.value(); pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests")); launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); // Give unlimited quota for files to Pepper tests. // TODO(dumi): remove this switch once we have a quota management // system in place. launch_arguments_.AppendSwitch(switches::kUnlimitedQuotaForFiles); } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; replacements.SetQuery(test_case.c_str(), url_parse::Component(0, test_case.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { net::TestServer test_server( net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("ppapi/tests"))); ASSERT_TRUE(test_server.Start()); RunTestURL(test_server.GetURL("files/test_case.html?" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); std::string escaped_value = WaitUntilCookieNonEmpty(tab.get(), test_url, "COMPLETION_COOKIE", action_max_timeout_ms()); EXPECT_STREQ("PASS", escaped_value.c_str()); } }; TEST_F(PPAPITest, FAILS_Instance) { RunTest("Instance"); } TEST_F(PPAPITest, Graphics2D) { RunTest("Graphics2D"); } // TODO(brettw) bug 51344: this is flaky on bots. Seems to timeout navigating. // Possibly all the image allocations slow things down on a loaded bot too much. TEST_F(PPAPITest, FLAKY_ImageData) { RunTest("ImageData"); } TEST_F(PPAPITest, Buffer) { RunTest("Buffer"); } // Flakey, http:L//crbug.com/57053 TEST_F(PPAPITest, FLAKY_URLLoader) { RunTestViaHTTP("URLLoader"); } // Flaky, http://crbug.com/51012 TEST_F(PPAPITest, FLAKY_PaintAggregator) { RunTestViaHTTP("PaintAggregator"); } // Flaky, http://crbug.com/48544. TEST_F(PPAPITest, FLAKY_Scrollbar) { RunTest("Scrollbar"); } TEST_F(PPAPITest, UrlUtil) { RunTest("UrlUtil"); } TEST_F(PPAPITest, CharSet) { RunTest("CharSet"); } TEST_F(PPAPITest, Var) { RunTest("Var"); } // TODO(dumi): figure out why this test is flaky on Mac and Win XP (dbg). #if defined(OS_MACOSX) || defined(OS_WIN) #define DISABLED_ON_MAC_AND_WIN(test_name) DISABLED_##test_name #else #define DISABLED_ON_MAC_AND_WIN(test_name) test_name #endif TEST_F(PPAPITest, DISABLED_ON_MAC_AND_WIN(FileIO)) { RunTestViaHTTP("FileIO"); } TEST_F(PPAPITest, FileRef) { RunTestViaHTTP("FileRef"); } TEST_F(PPAPITest, DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } <commit_msg>Disable crashy PPAPITest.FileIO/FileRef.<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/file_util.h" #include "base/path_service.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/test/test_server.h" #include "webkit/glue/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); FilePath::StringType pepper_plugin = plugin_lib.value(); pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests")); launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); // Give unlimited quota for files to Pepper tests. // TODO(dumi): remove this switch once we have a quota management // system in place. launch_arguments_.AppendSwitch(switches::kUnlimitedQuotaForFiles); } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; replacements.SetQuery(test_case.c_str(), url_parse::Component(0, test_case.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { net::TestServer test_server( net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("ppapi/tests"))); ASSERT_TRUE(test_server.Start()); RunTestURL(test_server.GetURL("files/test_case.html?" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); std::string escaped_value = WaitUntilCookieNonEmpty(tab.get(), test_url, "COMPLETION_COOKIE", action_max_timeout_ms()); EXPECT_STREQ("PASS", escaped_value.c_str()); } }; TEST_F(PPAPITest, FAILS_Instance) { RunTest("Instance"); } TEST_F(PPAPITest, Graphics2D) { RunTest("Graphics2D"); } // TODO(brettw) bug 51344: this is flaky on bots. Seems to timeout navigating. // Possibly all the image allocations slow things down on a loaded bot too much. TEST_F(PPAPITest, FLAKY_ImageData) { RunTest("ImageData"); } TEST_F(PPAPITest, Buffer) { RunTest("Buffer"); } // Flakey, http:L//crbug.com/57053 TEST_F(PPAPITest, FLAKY_URLLoader) { RunTestViaHTTP("URLLoader"); } // Flaky, http://crbug.com/51012 TEST_F(PPAPITest, FLAKY_PaintAggregator) { RunTestViaHTTP("PaintAggregator"); } // Flaky, http://crbug.com/48544. TEST_F(PPAPITest, FLAKY_Scrollbar) { RunTest("Scrollbar"); } TEST_F(PPAPITest, UrlUtil) { RunTest("UrlUtil"); } TEST_F(PPAPITest, CharSet) { RunTest("CharSet"); } TEST_F(PPAPITest, Var) { RunTest("Var"); } // TODO(dumi): figure out why this test is flaky / crashing. TEST_F(PPAPITest, DISABLED_FileIO) { RunTestViaHTTP("FileIO"); } // TODO(dumi): figure out why this test is flaky / crashing. TEST_F(PPAPITest, DISABLED_FileRef) { RunTestViaHTTP("FileRef"); } TEST_F(PPAPITest, DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } <|endoftext|>
<commit_before>#include <primitiv/config.h> #include <iostream> #include <vector> #include <primitiv/error.h> #include <test_utils.h> #include <primitiv/naive_device.h> using primitiv::devices::Naive; #ifdef PRIMITIV_USE_EIGEN #include <primitiv/eigen_device.h> using primitiv::devices::Eigen; #endif // PRIMITIV_USE_EIGEN #ifdef PRIMITIV_USE_CUDA #include <primitiv/cuda_device.h> using primitiv::devices::CUDA; using primitiv::devices::CUDA16; #endif // PRIMITIV_USE_CUDA #ifdef PRIMITIV_USE_OPENCL #include <primitiv/opencl_device.h> using primitiv::devices::OpenCL; #endif // PRIMITIV_USE_OPENCL #define MAYBE_USED(x) static_cast<void>(x) namespace { void add_device(std::vector<primitiv::Device *> &devs, primitiv::Device *dev) { devs.emplace_back(dev); dev->dump_description(); } } // namespace namespace test_utils { std::uint32_t get_default_ulps(const primitiv::Device &dev) { switch (dev.type()) { case primitiv::Device::DeviceType::CUDA16: // NOTE(odashi): // Returns the half of the difference of the resolution between // float (23 bits) and half (10 bits). return 1 << (13 - 1); default: // NOTE(odashi): // 4-ULPs test is identical with the ASSERT(EXPECT)_FLOAT_EQ directives in // the Google Test. return 4; } } void add_available_devices(std::vector<primitiv::Device *> &devs) { add_available_naive_devices(devs); add_available_eigen_devices(devs); add_available_cuda_devices(devs); add_available_cuda16_devices(devs); add_available_opencl_devices(devs); } void add_available_naive_devices(std::vector<primitiv::Device *> &devs) { // We can always add Naive devices. ::add_device(devs, new Naive()); ::add_device(devs, new Naive()); } void add_available_eigen_devices(std::vector<primitiv::Device *> &devs) { MAYBE_USED(devs); #ifdef PRIMITIV_USE_EIGEN ::add_device(devs, new Eigen()); ::add_device(devs, new Eigen()); #endif // PRIMITIV_USE_EIGEN } void add_available_cuda_devices(std::vector<primitiv::Device *> &devs) { MAYBE_USED(devs); #ifdef PRIMITIV_USE_CUDA const std::uint32_t num_devs = CUDA::num_devices(); std::uint32_t num_avail_devs = 0; for (std::uint32_t dev_id = 0; dev_id < num_devs; ++dev_id) { if (CUDA::check_support(dev_id)) { ++num_avail_devs; ::add_device(devs, new CUDA(dev_id)); if (num_avail_devs == 1) { // Add another device object on the first device. ::add_device(devs, new CUDA(dev_id)); } } } if (num_avail_devs != num_devs) { std::cerr << (num_devs - num_avail_devs) << " device(s) are not supported by primitiv::devices::CUDA." << std::endl; } if (num_avail_devs == 0) { std::cerr << "No available CUDA devices." << std::endl; } #endif // PRIMITIV_USE_CUDA } void add_available_cuda16_devices(std::vector<primitiv::Device *> &devs) { #ifdef PRIMITIV_USE_CUDA const std::uint32_t num_devs = CUDA16::num_devices(); std::uint32_t num_avail_devs = 0; for (std::uint32_t dev_id = 0; dev_id < num_devs; ++dev_id) { if (CUDA16::check_support(dev_id)) { ++num_avail_devs; ::add_device(devs, new CUDA16(dev_id)); if (num_avail_devs == 1) { // Add another device object on the first device. ::add_device(devs, new CUDA16(dev_id)); } } } if (num_avail_devs != num_devs) { std::cerr << (num_devs - num_avail_devs) << " device(s) are not supported by primitiv::devices::CUDA16." << std::endl; } if (num_avail_devs == 0) { std::cerr << "No available CUDA16 devices." << std::endl; } #endif // PRIMITIV_USE_CUDA } void add_available_opencl_devices(std::vector<primitiv::Device *> &devs) { MAYBE_USED(devs); #ifdef PRIMITIV_USE_OPENCL const std::uint32_t num_pfs = OpenCL::num_platforms(); if (num_pfs > 0) { for (std::uint32_t pf_id = 0; pf_id < num_pfs; ++pf_id) { const std::uint32_t num_devs = OpenCL::num_devices(pf_id); std::uint32_t num_avail_devs = 0; for (std::uint32_t dev_id = 0; dev_id < num_devs; ++dev_id) { if (OpenCL::check_support(pf_id, dev_id)) { ++num_avail_devs; ::add_device(devs, new OpenCL(pf_id, dev_id)); if (num_avail_devs == 1) { // Add another device object on the device 0. ::add_device(devs, new OpenCL(pf_id, dev_id)); } } } if (num_avail_devs != num_devs) { std::cerr << (num_devs - num_avail_devs) << " OpenCL device(s) are not supported." << std::endl; } if (num_avail_devs == 0) { std::cerr << "No available OpenCL devices." << std::endl; } } } else { std::cerr << "No OpenCL platforms are installed." << std::endl; } #endif // PRIMITIV_USE_OPENCL } } // namespace test_utils #undef MAYBE_USED <commit_msg>Add MAYBE_USED.<commit_after>#include <primitiv/config.h> #include <iostream> #include <vector> #include <primitiv/error.h> #include <test_utils.h> #include <primitiv/naive_device.h> using primitiv::devices::Naive; #ifdef PRIMITIV_USE_EIGEN #include <primitiv/eigen_device.h> using primitiv::devices::Eigen; #endif // PRIMITIV_USE_EIGEN #ifdef PRIMITIV_USE_CUDA #include <primitiv/cuda_device.h> using primitiv::devices::CUDA; using primitiv::devices::CUDA16; #endif // PRIMITIV_USE_CUDA #ifdef PRIMITIV_USE_OPENCL #include <primitiv/opencl_device.h> using primitiv::devices::OpenCL; #endif // PRIMITIV_USE_OPENCL #define MAYBE_USED(x) static_cast<void>(x) namespace { void add_device(std::vector<primitiv::Device *> &devs, primitiv::Device *dev) { devs.emplace_back(dev); dev->dump_description(); } } // namespace namespace test_utils { std::uint32_t get_default_ulps(const primitiv::Device &dev) { switch (dev.type()) { case primitiv::Device::DeviceType::CUDA16: // NOTE(odashi): // Returns the half of the difference of the resolution between // float (23 bits) and half (10 bits). return 1 << (13 - 1); default: // NOTE(odashi): // 4-ULPs test is identical with the ASSERT(EXPECT)_FLOAT_EQ directives in // the Google Test. return 4; } } void add_available_devices(std::vector<primitiv::Device *> &devs) { add_available_naive_devices(devs); add_available_eigen_devices(devs); add_available_cuda_devices(devs); add_available_cuda16_devices(devs); add_available_opencl_devices(devs); } void add_available_naive_devices(std::vector<primitiv::Device *> &devs) { // We can always add Naive devices. ::add_device(devs, new Naive()); ::add_device(devs, new Naive()); } void add_available_eigen_devices(std::vector<primitiv::Device *> &devs) { MAYBE_USED(devs); #ifdef PRIMITIV_USE_EIGEN ::add_device(devs, new Eigen()); ::add_device(devs, new Eigen()); #endif // PRIMITIV_USE_EIGEN } void add_available_cuda_devices(std::vector<primitiv::Device *> &devs) { MAYBE_USED(devs); #ifdef PRIMITIV_USE_CUDA const std::uint32_t num_devs = CUDA::num_devices(); std::uint32_t num_avail_devs = 0; for (std::uint32_t dev_id = 0; dev_id < num_devs; ++dev_id) { if (CUDA::check_support(dev_id)) { ++num_avail_devs; ::add_device(devs, new CUDA(dev_id)); if (num_avail_devs == 1) { // Add another device object on the first device. ::add_device(devs, new CUDA(dev_id)); } } } if (num_avail_devs != num_devs) { std::cerr << (num_devs - num_avail_devs) << " device(s) are not supported by primitiv::devices::CUDA." << std::endl; } if (num_avail_devs == 0) { std::cerr << "No available CUDA devices." << std::endl; } #endif // PRIMITIV_USE_CUDA } void add_available_cuda16_devices(std::vector<primitiv::Device *> &devs) { MAYBE_USED(devs); #ifdef PRIMITIV_USE_CUDA const std::uint32_t num_devs = CUDA16::num_devices(); std::uint32_t num_avail_devs = 0; for (std::uint32_t dev_id = 0; dev_id < num_devs; ++dev_id) { if (CUDA16::check_support(dev_id)) { ++num_avail_devs; ::add_device(devs, new CUDA16(dev_id)); if (num_avail_devs == 1) { // Add another device object on the first device. ::add_device(devs, new CUDA16(dev_id)); } } } if (num_avail_devs != num_devs) { std::cerr << (num_devs - num_avail_devs) << " device(s) are not supported by primitiv::devices::CUDA16." << std::endl; } if (num_avail_devs == 0) { std::cerr << "No available CUDA16 devices." << std::endl; } #endif // PRIMITIV_USE_CUDA } void add_available_opencl_devices(std::vector<primitiv::Device *> &devs) { MAYBE_USED(devs); #ifdef PRIMITIV_USE_OPENCL const std::uint32_t num_pfs = OpenCL::num_platforms(); if (num_pfs > 0) { for (std::uint32_t pf_id = 0; pf_id < num_pfs; ++pf_id) { const std::uint32_t num_devs = OpenCL::num_devices(pf_id); std::uint32_t num_avail_devs = 0; for (std::uint32_t dev_id = 0; dev_id < num_devs; ++dev_id) { if (OpenCL::check_support(pf_id, dev_id)) { ++num_avail_devs; ::add_device(devs, new OpenCL(pf_id, dev_id)); if (num_avail_devs == 1) { // Add another device object on the device 0. ::add_device(devs, new OpenCL(pf_id, dev_id)); } } } if (num_avail_devs != num_devs) { std::cerr << (num_devs - num_avail_devs) << " OpenCL device(s) are not supported." << std::endl; } if (num_avail_devs == 0) { std::cerr << "No available OpenCL devices." << std::endl; } } } else { std::cerr << "No OpenCL platforms are installed." << std::endl; } #endif // PRIMITIV_USE_OPENCL } } // namespace test_utils #undef MAYBE_USED <|endoftext|>
<commit_before>#include <rtosc/ports.h> #include <rtosc/port-sugar.h> #include <rtosc/undo-history.h> #include <cstdarg> #include <cassert> using namespace rtosc; class Object { public: Object(void) :x(0),b(0),i(0) {} float x; char b; int i; }; #define rObject Object Ports ports = { rParam(b, "b"), rParamF(x, "x"), rParamI(i, "i"), }; char reply_buf[256]; struct Rt:public RtData { Rt(Object *o, UndoHistory *uh_) { memset(reply_buf, 0, sizeof(reply_buf)); loc = new char[128]; memset(loc, 0, 128); loc_size = 128; obj = o; uh = uh_; enable = true; } void reply(const char *path, const char *args, ...) { if(strcmp(path, "undo_change") || !enable) return; va_list va; va_start(va, args); rtosc_vmessage(reply_buf, sizeof(reply_buf), path, args, va); uh->recordEvent(reply_buf); } bool enable; UndoHistory *uh; }; char message_buff[256]; int main() { memset(message_buff, 0, sizeof(reply_buf)); //Initialize structures Object o; UndoHistory hist; Rt rt(&o, &hist); hist.setCallback([&rt](const char*msg) {ports.dispatch(msg+1, rt);}); assert(o.b == 0); rt.matches = 0; int len = rtosc_message(message_buff, 128, "b", "c", 7); for(int i=0; i<len; ++i) printf("%hx",message_buff[i]); printf("\n"); ports.dispatch(message_buff, rt); assert(rt.matches == 1); printf("rt.matches == '%d'\n", rt.matches); assert(o.b == 7); rt.enable = false; hist.showHistory(); hist.seekHistory(-1); assert(o.b == 0); hist.showHistory(); hist.seekHistory(+1); printf("the result is '%d'\n", o.b); assert(o.b == 7); return 0; } <commit_msg>Fix printf type error<commit_after>#include <rtosc/ports.h> #include <rtosc/port-sugar.h> #include <rtosc/undo-history.h> #include <cstdarg> #include <cassert> using namespace rtosc; class Object { public: Object(void) :x(0),b(0),i(0) {} float x; char b; int i; }; #define rObject Object Ports ports = { rParam(b, "b"), rParamF(x, "x"), rParamI(i, "i"), }; char reply_buf[256]; struct Rt:public RtData { Rt(Object *o, UndoHistory *uh_) { memset(reply_buf, 0, sizeof(reply_buf)); loc = new char[128]; memset(loc, 0, 128); loc_size = 128; obj = o; uh = uh_; enable = true; } void reply(const char *path, const char *args, ...) { if(strcmp(path, "undo_change") || !enable) return; va_list va; va_start(va, args); rtosc_vmessage(reply_buf, sizeof(reply_buf), path, args, va); uh->recordEvent(reply_buf); } bool enable; UndoHistory *uh; }; char message_buff[256]; int main() { memset(message_buff, 0, sizeof(reply_buf)); //Initialize structures Object o; UndoHistory hist; Rt rt(&o, &hist); hist.setCallback([&rt](const char*msg) {ports.dispatch(msg+1, rt);}); assert(o.b == 0); rt.matches = 0; int len = rtosc_message(message_buff, 128, "b", "c", 7); for(int i=0; i<len; ++i) printf("%hhx",message_buff[i]); printf("\n"); ports.dispatch(message_buff, rt); assert(rt.matches == 1); printf("rt.matches == '%d'\n", rt.matches); assert(o.b == 7); rt.enable = false; hist.showHistory(); hist.seekHistory(-1); assert(o.b == 0); hist.showHistory(); hist.seekHistory(+1); printf("the result is '%d'\n", o.b); assert(o.b == 7); return 0; } <|endoftext|>
<commit_before>#include "peanoclaw/configurations/PeanoClawConfigurationForSpacetreeGrid.h" #include "peanoclaw/runners/PeanoClawLibraryRunner.h" #include "tarch/logging/CommandLineLogger.h" tarch::logging::Log peanoclaw::configurations::PeanoClawConfigurationForSpacetreeGrid::_log("peanoclaw::configurations::PeanoClawConfigurationForSpacetreeGrid"); peanoclaw::configurations::PeanoClawConfigurationForSpacetreeGrid::PeanoClawConfigurationForSpacetreeGrid(): _isValid(true), _plotAtOutputTimes(true), _plotSubsteps(false), _plotSubstepsAfterOutputTime(-1), _additionalLevelsForPredefinedRefinement(1), _disableDimensionalSplittingOptimization(false) { } peanoclaw::configurations::PeanoClawConfigurationForSpacetreeGrid::~PeanoClawConfigurationForSpacetreeGrid() { } bool peanoclaw::configurations::PeanoClawConfigurationForSpacetreeGrid::isValid() const { return true; } bool peanoclaw::configurations::PeanoClawConfigurationForSpacetreeGrid::plotAtOutputTimes() const { return _plotAtOutputTimes; } bool peanoclaw::configurations::PeanoClawConfigurationForSpacetreeGrid::plotSubsteps() const { return _plotSubsteps; } int peanoclaw::configurations::PeanoClawConfigurationForSpacetreeGrid::plotSubstepsAfterOutputTime() const { return _plotSubstepsAfterOutputTime; } int peanoclaw::configurations::PeanoClawConfigurationForSpacetreeGrid::getAdditionalLevelsForPredefinedRefinement() const { return _additionalLevelsForPredefinedRefinement; } bool peanoclaw::configurations::PeanoClawConfigurationForSpacetreeGrid::disableDimensionalSplittingOptimization() const { return _disableDimensionalSplittingOptimization; } <commit_msg>disabled plotting<commit_after>#include "peanoclaw/configurations/PeanoClawConfigurationForSpacetreeGrid.h" #include "peanoclaw/runners/PeanoClawLibraryRunner.h" #include "tarch/logging/CommandLineLogger.h" tarch::logging::Log peanoclaw::configurations::PeanoClawConfigurationForSpacetreeGrid::_log("peanoclaw::configurations::PeanoClawConfigurationForSpacetreeGrid"); peanoclaw::configurations::PeanoClawConfigurationForSpacetreeGrid::PeanoClawConfigurationForSpacetreeGrid(): _isValid(true), _plotAtOutputTimes(false), _plotSubsteps(false), _plotSubstepsAfterOutputTime(-1), _additionalLevelsForPredefinedRefinement(1), _disableDimensionalSplittingOptimization(false) { } peanoclaw::configurations::PeanoClawConfigurationForSpacetreeGrid::~PeanoClawConfigurationForSpacetreeGrid() { } bool peanoclaw::configurations::PeanoClawConfigurationForSpacetreeGrid::isValid() const { return true; } bool peanoclaw::configurations::PeanoClawConfigurationForSpacetreeGrid::plotAtOutputTimes() const { return _plotAtOutputTimes; } bool peanoclaw::configurations::PeanoClawConfigurationForSpacetreeGrid::plotSubsteps() const { return _plotSubsteps; } int peanoclaw::configurations::PeanoClawConfigurationForSpacetreeGrid::plotSubstepsAfterOutputTime() const { return _plotSubstepsAfterOutputTime; } int peanoclaw::configurations::PeanoClawConfigurationForSpacetreeGrid::getAdditionalLevelsForPredefinedRefinement() const { return _additionalLevelsForPredefinedRefinement; } bool peanoclaw::configurations::PeanoClawConfigurationForSpacetreeGrid::disableDimensionalSplittingOptimization() const { return _disableDimensionalSplittingOptimization; } <|endoftext|>
<commit_before>// Copyright (c) 2012 Toby Ealden. // Copyright (c) 2014 Martin Man. // vim: ts=2 sw=2 et #include "socket_watcher.hpp" #include <string.h> using namespace v8; #if NODE_VERSION_AT_LEAST(0, 7, 8) // Nothing #else namespace node { Handle<Value> MakeCallback(Isolate *isolate, const Handle<Object> object, const Handle<Function> callback, int argc, Handle<Value> argv[]) { HandleScope scope(isolate); // TODO Hook for long stack traces to be made here. TryCatch try_catch; Local<Value> ret = callback->Call(object, argc, argv); if (try_catch.HasCaught()) { FatalException(try_catch); return Undefined(); } return scope.Escape(ret); } } // namespace node #endif Persistent<String> callback_symbol; Persistent<Function> constructor; // mman, why is this here? // Handle<Value> Calleback(const Arguments& args) { // return Undefined(); // }; SocketWatcher::SocketWatcher() : poll_(NULL), fd_(0), events_(0) { } void SocketWatcher::Initialize(Handle<Object> exports) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); Local<FunctionTemplate> t = FunctionTemplate::New(isolate, New); t->SetClassName(String::NewFromUtf8(isolate, "SocketWatcher")); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "set", SocketWatcher::Set); NODE_SET_PROTOTYPE_METHOD(t, "start", SocketWatcher::Start); NODE_SET_PROTOTYPE_METHOD(t, "stop", SocketWatcher::Stop); exports->Set(String::NewFromUtf8(isolate, "SocketWatcher"), t->GetFunction()); constructor.Reset(isolate, t->GetFunction()); Local<String> c = String::NewFromUtf8(isolate, "callback"); callback_symbol.Reset(isolate, c); } void SocketWatcher::Start(const v8::FunctionCallbackInfo<v8::Value>& args) { Isolate* isolate = args.GetIsolate(); HandleScope scope(isolate); SocketWatcher *watcher = ObjectWrap::Unwrap<SocketWatcher>(args.This()); watcher->StartInternal(); } void SocketWatcher::StartInternal() { if (poll_ == NULL) { poll_ = new uv_poll_t; memset(poll_,0,sizeof(uv_poll_t)); poll_->data = this; uv_poll_init_socket(uv_default_loop(), poll_, fd_); Ref(); } if (!uv_is_active((uv_handle_t*)poll_)) { uv_poll_start(poll_, events_, &SocketWatcher::Callback); } } void SocketWatcher::Callback(uv_poll_t *w, int status, int revents) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); SocketWatcher *watcher = static_cast<SocketWatcher*>(w->data); assert(w == watcher->poll_); Local<String> symbol = Local<String>::New(isolate, callback_symbol); Local<Value> callback_v = watcher->handle()->Get(symbol); if(!callback_v->IsFunction()) { watcher->StopInternal(); return; } Local<Function> callback = Local<Function>::Cast(callback_v); Local<Value> argv[2]; argv[0] = Local<Value>::New(isolate, revents & UV_READABLE ? True(isolate) : False(isolate)); argv[1] = Local<Value>::New(isolate, revents & UV_WRITABLE ? True(isolate) : False(isolate)); node::MakeCallback(isolate, watcher->handle(), callback, 2, argv); } void SocketWatcher::Stop(const v8::FunctionCallbackInfo<v8::Value>& args) { Isolate* isolate = args.GetIsolate(); HandleScope scope(isolate); SocketWatcher *watcher = ObjectWrap::Unwrap<SocketWatcher>(args.This()); watcher->StopInternal(); } void SocketWatcher::StopInternal() { if (poll_ != NULL) { uv_poll_stop(poll_); Unref(); } } void SocketWatcher::New(const v8::FunctionCallbackInfo<v8::Value>& args) { Isolate* isolate = args.GetIsolate(); HandleScope scope(isolate); SocketWatcher *s = new SocketWatcher(); s->Wrap(args.This()); args.GetReturnValue().Set(args.This()); } void SocketWatcher::Set(const v8::FunctionCallbackInfo<v8::Value>& args) { Isolate* isolate = args.GetIsolate(); HandleScope scope(isolate); SocketWatcher *watcher = ObjectWrap::Unwrap<SocketWatcher>(args.This()); if(!args[0]->IsInt32()) { isolate->ThrowException(Exception::TypeError( String::NewFromUtf8(isolate, "First arg should be a file descriptor."))); return; } int fd = args[0]->Int32Value(); int events = 0; if(!args[1]->IsBoolean()) { isolate->ThrowException(Exception::TypeError( String::NewFromUtf8(isolate, "Second arg should boolean (readable)."))); return; } if(args[1]->IsTrue()) events |= UV_READABLE; if(!args[2]->IsBoolean()) { isolate->ThrowException(Exception::TypeError( String::NewFromUtf8(isolate, "Third arg should boolean (writable)."))); return; } if (args[2]->IsTrue()) events |= UV_WRITABLE; assert(watcher->poll_ == NULL); watcher->fd_ = fd; watcher->events_ = events; } void Init(Handle<Object> exports) { SocketWatcher::Initialize(exports); } NODE_MODULE(socketwatcher, Init) <commit_msg>make it build<commit_after>// Copyright (c) 2012 Toby Ealden. // Copyright (c) 2014 Martin Man. // vim: ts=2 sw=2 et #include "socket_watcher.hpp" #include <string.h> using namespace v8; #if NODE_VERSION_AT_LEAST(0, 7, 8) // Nothing #else namespace node { Handle<Value> MakeCallback(Isolate *isolate, const Handle<Object> object, const Handle<Function> callback, int argc, Handle<Value> argv[]) { HandleScope scope(isolate); // TODO Hook for long stack traces to be made here. TryCatch try_catch; Local<Value> ret = callback->Call(object, argc, argv); if (try_catch.HasCaught()) { FatalException(try_catch); return Undefined(); } return scope.Escape(ret); } } // namespace node #endif Persistent<String> callback_symbol; Persistent<Function> constructor; // mman, why is this here? // Handle<Value> Calleback(const Arguments& args) { // return Undefined(); // }; SocketWatcher::SocketWatcher() : poll_(NULL), fd_(0), events_(0) { } void SocketWatcher::Initialize(Handle<Object> exports) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); Local<FunctionTemplate> t = FunctionTemplate::New(New); t->SetClassName(String::NewFromUtf8(isolate, "SocketWatcher")); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "set", SocketWatcher::Set); NODE_SET_PROTOTYPE_METHOD(t, "start", SocketWatcher::Start); NODE_SET_PROTOTYPE_METHOD(t, "stop", SocketWatcher::Stop); exports->Set(String::NewFromUtf8(isolate, "SocketWatcher"), t->GetFunction()); constructor.Reset(isolate, t->GetFunction()); Local<String> c = String::NewFromUtf8(isolate, "callback"); callback_symbol.Reset(isolate, c); } void SocketWatcher::Start(const v8::FunctionCallbackInfo<v8::Value>& args) { Isolate* isolate = args.GetIsolate(); HandleScope scope(isolate); SocketWatcher *watcher = ObjectWrap::Unwrap<SocketWatcher>(args.This()); watcher->StartInternal(); } void SocketWatcher::StartInternal() { if (poll_ == NULL) { poll_ = new uv_poll_t; memset(poll_,0,sizeof(uv_poll_t)); poll_->data = this; uv_poll_init_socket(uv_default_loop(), poll_, fd_); Ref(); } if (!uv_is_active((uv_handle_t*)poll_)) { uv_poll_start(poll_, events_, &SocketWatcher::Callback); } } void SocketWatcher::Callback(uv_poll_t *w, int status, int revents) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); SocketWatcher *watcher = static_cast<SocketWatcher*>(w->data); assert(w == watcher->poll_); Local<String> symbol = Local<String>::New(isolate, callback_symbol); Local<Value> callback_v = watcher->handle()->Get(symbol); if(!callback_v->IsFunction()) { watcher->StopInternal(); return; } Local<Function> callback = Local<Function>::Cast(callback_v); Local<Value> argv[2]; argv[0] = Local<Value>::New(isolate, revents & UV_READABLE ? True(isolate) : False(isolate)); argv[1] = Local<Value>::New(isolate, revents & UV_WRITABLE ? True(isolate) : False(isolate)); node::MakeCallback(watcher->handle(), callback, 2, argv); } void SocketWatcher::Stop(const v8::FunctionCallbackInfo<v8::Value>& args) { Isolate* isolate = args.GetIsolate(); HandleScope scope(isolate); SocketWatcher *watcher = ObjectWrap::Unwrap<SocketWatcher>(args.This()); watcher->StopInternal(); } void SocketWatcher::StopInternal() { if (poll_ != NULL) { uv_poll_stop(poll_); Unref(); } } void SocketWatcher::New(const v8::FunctionCallbackInfo<v8::Value>& args) { Isolate* isolate = args.GetIsolate(); HandleScope scope(isolate); SocketWatcher *s = new SocketWatcher(); s->Wrap(args.This()); args.GetReturnValue().Set(args.This()); } void SocketWatcher::Set(const v8::FunctionCallbackInfo<v8::Value>& args) { Isolate* isolate = args.GetIsolate(); HandleScope scope(isolate); SocketWatcher *watcher = ObjectWrap::Unwrap<SocketWatcher>(args.This()); if(!args[0]->IsInt32()) { isolate->ThrowException(Exception::TypeError( String::NewFromUtf8(isolate, "First arg should be a file descriptor."))); return; } int fd = args[0]->Int32Value(); int events = 0; if(!args[1]->IsBoolean()) { isolate->ThrowException(Exception::TypeError( String::NewFromUtf8(isolate, "Second arg should boolean (readable)."))); return; } if(args[1]->IsTrue()) events |= UV_READABLE; if(!args[2]->IsBoolean()) { isolate->ThrowException(Exception::TypeError( String::NewFromUtf8(isolate, "Third arg should boolean (writable)."))); return; } if (args[2]->IsTrue()) events |= UV_WRITABLE; assert(watcher->poll_ == NULL); watcher->fd_ = fd; watcher->events_ = events; } void Init(Handle<Object> exports) { SocketWatcher::Initialize(exports); } NODE_MODULE(socketwatcher, Init) <|endoftext|>
<commit_before>#include <ase/ase.hpp> #include <cstdint> #include <fstream> #if defined(_MSC_VER) #include <intrin.h> #define SWAP32(x) _byteswap_ulong(x) #define SWAP16(x) _byteswap_ushort(x) #elif defined(__GNUC__) || defined(__clang__) #define SWAP32(x) __builtin_bswap32(x) #define SWAP16(x) __builtin_bswap16(x) #else inline std::uint16_t SWAP16(std::uint16_t x) { return ( ((x & 0x00FF) << 8) | ((x & 0xFF00) >> 8) ); } inline std::uint32_t SWAP32(std::uint32_t x) { return( ((x & 0x000000FF) << 24) | ((x & 0x0000FF00) << 8) | ((x & 0x00FF0000) >> 8) | ((x & 0xFF000000) >> 24) ); } #endif namespace ase { enum BlockClass : std::uint16_t { ColorEntry = 0x0001, GroupBegin = 0xC001, GroupEnd = 0xC002 }; enum ColorModel : std::uint32_t { // Big Endian CMYK = 'CMYK', RGB = 'RGB ', LAB = 'LAB ', GRAY = 'Gray' }; enum ColorCategory : std::uint16_t { Global = 0, Spot = 1, Normal = 2 }; void IColorCallback::GroupBegin(const std::u16string& Name) { } void IColorCallback::GroupEnd() { } void IColorCallback::ColorGray(const std::u16string& Name, ColorType::Gray Lightness) { } void IColorCallback::ColorRGB(const std::u16string& Name, ColorType::RGB Color) { } void IColorCallback::ColorLAB(const std::u16string& Name, ColorType::LAB Color) { } void IColorCallback::ColorCMYK(const std::u16string& Name, ColorType::CMYK Color) { } bool LoadFromFile( IColorCallback& Callback, const char* FileName ) { std::ifstream SwatchFile; SwatchFile.open( FileName, std::ios::binary ); return LoadFromStream(Callback, SwatchFile); } bool LoadFromStream( IColorCallback& Callback, std::istream& Stream ) { if( !Stream ) { return false; } std::uint32_t Magic; Stream.read( reinterpret_cast<char*>(&Magic), sizeof(std::uint32_t) ); Magic = SWAP32(Magic); if( Magic != 'ASEF' ) { return false; } std::uint16_t Version[2]; std::uint32_t BlockCount; Stream.read( reinterpret_cast<char*>(&Version[0]), sizeof(std::uint16_t) ); Stream.read( reinterpret_cast<char*>(&Version[1]), sizeof(std::uint16_t) ); Stream.read( reinterpret_cast<char*>(&BlockCount), sizeof(std::uint32_t) ); Version[0] = SWAP16(Version[0]); Version[1] = SWAP16(Version[1]); BlockCount = SWAP32(BlockCount); std::uint16_t CurBlockClass; std::uint32_t CurBlockSize; // Process stream while( BlockCount-- ) { Stream.read( reinterpret_cast<char*>(&CurBlockClass), sizeof(std::uint16_t) ); CurBlockClass = SWAP16(CurBlockClass); switch( CurBlockClass ) { case BlockClass::ColorEntry: case BlockClass::GroupBegin: { Stream.read( reinterpret_cast<char*>(&CurBlockSize), sizeof(std::uint32_t) ); CurBlockSize = SWAP32(CurBlockSize); std::u16string EntryName; std::uint16_t EntryNameLength; Stream.read( reinterpret_cast<char*>(&EntryNameLength), sizeof(std::uint16_t) ); EntryNameLength = SWAP16(EntryNameLength); EntryName.clear(); EntryName.resize(EntryNameLength); Stream.read( reinterpret_cast<char*>(&EntryName[0]), EntryNameLength * 2 ); // Endian swap each character for( std::size_t i = 0; i < EntryNameLength; i++ ) { EntryName[i] = SWAP16(EntryName[i]); } if( CurBlockClass == BlockClass::GroupBegin ) { Callback.GroupBegin( EntryName ); } else if( CurBlockClass == BlockClass::ColorEntry ) { std::uint32_t ColorModel; Stream.read( reinterpret_cast<char*>(&ColorModel), sizeof(std::uint32_t) ); ColorModel = SWAP32(ColorModel); switch( ColorModel ) { case ColorModel::CMYK: { ColorType::CMYK CurColor; Stream.read( reinterpret_cast<char*>(&CurColor), sizeof(ColorType::CMYK) ); *reinterpret_cast<std::uint32_t*>(&CurColor[0]) = SWAP32(*reinterpret_cast<std::uint32_t*>(&CurColor[0])); *reinterpret_cast<std::uint32_t*>(&CurColor[1]) = SWAP32(*reinterpret_cast<std::uint32_t*>(&CurColor[1])); *reinterpret_cast<std::uint32_t*>(&CurColor[2]) = SWAP32(*reinterpret_cast<std::uint32_t*>(&CurColor[2])); *reinterpret_cast<std::uint32_t*>(&CurColor[3]) = SWAP32(*reinterpret_cast<std::uint32_t*>(&CurColor[3])); Callback.ColorCMYK( EntryName, CurColor ); break; } case ColorModel::RGB: { ColorType::RGB CurColor; Stream.read( reinterpret_cast<char*>(&CurColor), sizeof(ColorType::RGB) ); *reinterpret_cast<std::uint32_t*>(&CurColor[0]) = SWAP32(*reinterpret_cast<std::uint32_t*>(&CurColor[0])); *reinterpret_cast<std::uint32_t*>(&CurColor[1]) = SWAP32(*reinterpret_cast<std::uint32_t*>(&CurColor[1])); *reinterpret_cast<std::uint32_t*>(&CurColor[2]) = SWAP32(*reinterpret_cast<std::uint32_t*>(&CurColor[2])); Callback.ColorRGB( EntryName, CurColor ); break; } case ColorModel::LAB: { ColorType::LAB CurColor; Stream.read( reinterpret_cast<char*>(&CurColor), sizeof(ColorType::LAB) ); *reinterpret_cast<std::uint32_t*>(&CurColor[0]) = SWAP32(*reinterpret_cast<std::uint32_t*>(&CurColor[0])); *reinterpret_cast<std::uint32_t*>(&CurColor[1]) = SWAP32(*reinterpret_cast<std::uint32_t*>(&CurColor[1])); *reinterpret_cast<std::uint32_t*>(&CurColor[2]) = SWAP32(*reinterpret_cast<std::uint32_t*>(&CurColor[2])); Callback.ColorLAB( EntryName, CurColor ); break; } case ColorModel::GRAY: { ColorType::Gray CurColor; Stream.read( reinterpret_cast<char*>(&CurColor), sizeof(ColorType::Gray) ); *reinterpret_cast<std::uint32_t*>(&CurColor[0]) = SWAP32(*reinterpret_cast<std::uint32_t*>(&CurColor[0])); Callback.ColorGray( EntryName, CurColor ); break; } } std::uint16_t ColorCategory; Stream.read( reinterpret_cast<char*>(&ColorCategory), sizeof(std::uint16_t) ); ColorCategory = SWAP16(ColorCategory); } break; } case BlockClass::GroupEnd: { Callback.GroupEnd(); break; } } } return true; } template< typename T > inline T ReadType(const void* & Pointer) { const T* Temp = static_cast<const T*>(Pointer); Pointer = static_cast<const T*>(Pointer) + static_cast<std::ptrdiff_t>(1); return *Temp; } template<> inline std::uint32_t ReadType<std::uint32_t>(const void* & Pointer) { const std::uint32_t* Temp = static_cast<const std::uint32_t*>(Pointer); Pointer = static_cast<const std::uint32_t*>(Pointer) + static_cast<std::ptrdiff_t>(1); return SWAP32(*Temp); } template<> inline std::uint16_t ReadType<std::uint16_t>(const void* & Pointer) { const std::uint16_t* Temp = static_cast<const std::uint16_t*>(Pointer); Pointer = static_cast<const std::uint16_t*>(Pointer) + static_cast<std::ptrdiff_t>(1); return SWAP16(*Temp); } template<> inline float ReadType<float>(const void* & Pointer) { std::uint32_t Temp = SWAP32(*static_cast<const std::uint32_t*>(Pointer)); Pointer = static_cast<const float*>(Pointer) + static_cast<std::ptrdiff_t>(1); return *reinterpret_cast<float*>(&Temp); } inline void Read(const void* & Pointer, void* Dest, std::size_t Count) { memcpy(Dest, Pointer, Count); Pointer = static_cast<const std::uint8_t*>(Pointer) + Count; } bool LoadFromMemory( IColorCallback& Callback, const void* Buffer, std::size_t Size ) { if( Buffer == nullptr ) { return false; } const void* ReadPoint = Buffer; const std::uint32_t Magic = ReadType<std::uint32_t>(ReadPoint); if( Magic != 'ASEF' ) { return false; } std::uint16_t Version[2]; Version[0] = ReadType<std::uint16_t>(ReadPoint); Version[1] = ReadType<std::uint16_t>(ReadPoint); std::uint32_t BlockCount = ReadType<std::uint32_t>(ReadPoint); // Process stream while( BlockCount-- ) { const std::uint16_t CurBlockClass = ReadType<std::uint16_t>(ReadPoint); switch( CurBlockClass ) { case BlockClass::ColorEntry: case BlockClass::GroupBegin: { std::uint32_t CurBlockSize = ReadType<std::uint32_t>(ReadPoint); const std::uint16_t EntryNameLength = ReadType<std::uint16_t>(ReadPoint); std::u16string EntryName; EntryName.resize(EntryNameLength); // Endian swap each character for( std::size_t i = 0; i < EntryNameLength; i++ ) { EntryName[i] = ReadType<std::uint16_t>(ReadPoint); } if( CurBlockClass == BlockClass::GroupBegin ) { Callback.GroupBegin( EntryName ); } else if( CurBlockClass == BlockClass::ColorEntry ) { const std::uint32_t ColorModel = ReadType<std::uint32_t>(ReadPoint); switch( ColorModel ) { case ColorModel::CMYK: { ColorType::CMYK CurColor; CurColor[0] = ReadType<float>(ReadPoint); CurColor[1] = ReadType<float>(ReadPoint); CurColor[2] = ReadType<float>(ReadPoint); CurColor[3] = ReadType<float>(ReadPoint); Callback.ColorCMYK( EntryName, CurColor ); break; } case ColorModel::RGB: { ColorType::RGB CurColor; CurColor[0] = ReadType<float>(ReadPoint); CurColor[1] = ReadType<float>(ReadPoint); CurColor[2] = ReadType<float>(ReadPoint); Callback.ColorRGB( EntryName, CurColor ); break; } case ColorModel::LAB: { ColorType::LAB CurColor; CurColor[0] = ReadType<float>(ReadPoint); CurColor[1] = ReadType<float>(ReadPoint); CurColor[2] = ReadType<float>(ReadPoint); Callback.ColorLAB( EntryName, CurColor ); break; } case ColorModel::GRAY: { ColorType::Gray CurColor; CurColor[0] = ReadType<float>(ReadPoint); Callback.ColorGray( EntryName, CurColor ); break; } } std::uint16_t ColorCategory = ReadType<std::uint16_t>(ReadPoint); } break; } case BlockClass::GroupEnd: { Callback.GroupEnd(); break; } } } return true; } } <commit_msg>Fix missing header for std::memcpy<commit_after>#include <ase/ase.hpp> #include <cstdint> #include <cstring> #include <fstream> #if defined(_MSC_VER) #include <intrin.h> #define SWAP32(x) _byteswap_ulong(x) #define SWAP16(x) _byteswap_ushort(x) #elif defined(__GNUC__) || defined(__clang__) #define SWAP32(x) __builtin_bswap32(x) #define SWAP16(x) __builtin_bswap16(x) #else inline std::uint16_t SWAP16(std::uint16_t x) { return ( ((x & 0x00FF) << 8) | ((x & 0xFF00) >> 8) ); } inline std::uint32_t SWAP32(std::uint32_t x) { return( ((x & 0x000000FF) << 24) | ((x & 0x0000FF00) << 8) | ((x & 0x00FF0000) >> 8) | ((x & 0xFF000000) >> 24) ); } #endif namespace ase { enum BlockClass : std::uint16_t { ColorEntry = 0x0001, GroupBegin = 0xC001, GroupEnd = 0xC002 }; enum ColorModel : std::uint32_t { // Big Endian CMYK = 'CMYK', RGB = 'RGB ', LAB = 'LAB ', GRAY = 'Gray' }; enum ColorCategory : std::uint16_t { Global = 0, Spot = 1, Normal = 2 }; void IColorCallback::GroupBegin(const std::u16string& Name) { } void IColorCallback::GroupEnd() { } void IColorCallback::ColorGray(const std::u16string& Name, ColorType::Gray Lightness) { } void IColorCallback::ColorRGB(const std::u16string& Name, ColorType::RGB Color) { } void IColorCallback::ColorLAB(const std::u16string& Name, ColorType::LAB Color) { } void IColorCallback::ColorCMYK(const std::u16string& Name, ColorType::CMYK Color) { } bool LoadFromFile( IColorCallback& Callback, const char* FileName ) { std::ifstream SwatchFile; SwatchFile.open( FileName, std::ios::binary ); return LoadFromStream(Callback, SwatchFile); } bool LoadFromStream( IColorCallback& Callback, std::istream& Stream ) { if( !Stream ) { return false; } std::uint32_t Magic; Stream.read( reinterpret_cast<char*>(&Magic), sizeof(std::uint32_t) ); Magic = SWAP32(Magic); if( Magic != 'ASEF' ) { return false; } std::uint16_t Version[2]; std::uint32_t BlockCount; Stream.read( reinterpret_cast<char*>(&Version[0]), sizeof(std::uint16_t) ); Stream.read( reinterpret_cast<char*>(&Version[1]), sizeof(std::uint16_t) ); Stream.read( reinterpret_cast<char*>(&BlockCount), sizeof(std::uint32_t) ); Version[0] = SWAP16(Version[0]); Version[1] = SWAP16(Version[1]); BlockCount = SWAP32(BlockCount); std::uint16_t CurBlockClass; std::uint32_t CurBlockSize; // Process stream while( BlockCount-- ) { Stream.read( reinterpret_cast<char*>(&CurBlockClass), sizeof(std::uint16_t) ); CurBlockClass = SWAP16(CurBlockClass); switch( CurBlockClass ) { case BlockClass::ColorEntry: case BlockClass::GroupBegin: { Stream.read( reinterpret_cast<char*>(&CurBlockSize), sizeof(std::uint32_t) ); CurBlockSize = SWAP32(CurBlockSize); std::u16string EntryName; std::uint16_t EntryNameLength; Stream.read( reinterpret_cast<char*>(&EntryNameLength), sizeof(std::uint16_t) ); EntryNameLength = SWAP16(EntryNameLength); EntryName.clear(); EntryName.resize(EntryNameLength); Stream.read( reinterpret_cast<char*>(&EntryName[0]), EntryNameLength * 2 ); // Endian swap each character for( std::size_t i = 0; i < EntryNameLength; i++ ) { EntryName[i] = SWAP16(EntryName[i]); } if( CurBlockClass == BlockClass::GroupBegin ) { Callback.GroupBegin( EntryName ); } else if( CurBlockClass == BlockClass::ColorEntry ) { std::uint32_t ColorModel; Stream.read( reinterpret_cast<char*>(&ColorModel), sizeof(std::uint32_t) ); ColorModel = SWAP32(ColorModel); switch( ColorModel ) { case ColorModel::CMYK: { ColorType::CMYK CurColor; Stream.read( reinterpret_cast<char*>(&CurColor), sizeof(ColorType::CMYK) ); *reinterpret_cast<std::uint32_t*>(&CurColor[0]) = SWAP32(*reinterpret_cast<std::uint32_t*>(&CurColor[0])); *reinterpret_cast<std::uint32_t*>(&CurColor[1]) = SWAP32(*reinterpret_cast<std::uint32_t*>(&CurColor[1])); *reinterpret_cast<std::uint32_t*>(&CurColor[2]) = SWAP32(*reinterpret_cast<std::uint32_t*>(&CurColor[2])); *reinterpret_cast<std::uint32_t*>(&CurColor[3]) = SWAP32(*reinterpret_cast<std::uint32_t*>(&CurColor[3])); Callback.ColorCMYK( EntryName, CurColor ); break; } case ColorModel::RGB: { ColorType::RGB CurColor; Stream.read( reinterpret_cast<char*>(&CurColor), sizeof(ColorType::RGB) ); *reinterpret_cast<std::uint32_t*>(&CurColor[0]) = SWAP32(*reinterpret_cast<std::uint32_t*>(&CurColor[0])); *reinterpret_cast<std::uint32_t*>(&CurColor[1]) = SWAP32(*reinterpret_cast<std::uint32_t*>(&CurColor[1])); *reinterpret_cast<std::uint32_t*>(&CurColor[2]) = SWAP32(*reinterpret_cast<std::uint32_t*>(&CurColor[2])); Callback.ColorRGB( EntryName, CurColor ); break; } case ColorModel::LAB: { ColorType::LAB CurColor; Stream.read( reinterpret_cast<char*>(&CurColor), sizeof(ColorType::LAB) ); *reinterpret_cast<std::uint32_t*>(&CurColor[0]) = SWAP32(*reinterpret_cast<std::uint32_t*>(&CurColor[0])); *reinterpret_cast<std::uint32_t*>(&CurColor[1]) = SWAP32(*reinterpret_cast<std::uint32_t*>(&CurColor[1])); *reinterpret_cast<std::uint32_t*>(&CurColor[2]) = SWAP32(*reinterpret_cast<std::uint32_t*>(&CurColor[2])); Callback.ColorLAB( EntryName, CurColor ); break; } case ColorModel::GRAY: { ColorType::Gray CurColor; Stream.read( reinterpret_cast<char*>(&CurColor), sizeof(ColorType::Gray) ); *reinterpret_cast<std::uint32_t*>(&CurColor[0]) = SWAP32(*reinterpret_cast<std::uint32_t*>(&CurColor[0])); Callback.ColorGray( EntryName, CurColor ); break; } } std::uint16_t ColorCategory; Stream.read( reinterpret_cast<char*>(&ColorCategory), sizeof(std::uint16_t) ); ColorCategory = SWAP16(ColorCategory); } break; } case BlockClass::GroupEnd: { Callback.GroupEnd(); break; } } } return true; } template< typename T > inline T ReadType(const void* & Pointer) { const T* Temp = static_cast<const T*>(Pointer); Pointer = static_cast<const T*>(Pointer) + static_cast<std::ptrdiff_t>(1); return *Temp; } template<> inline std::uint32_t ReadType<std::uint32_t>(const void* & Pointer) { const std::uint32_t* Temp = static_cast<const std::uint32_t*>(Pointer); Pointer = static_cast<const std::uint32_t*>(Pointer) + static_cast<std::ptrdiff_t>(1); return SWAP32(*Temp); } template<> inline std::uint16_t ReadType<std::uint16_t>(const void* & Pointer) { const std::uint16_t* Temp = static_cast<const std::uint16_t*>(Pointer); Pointer = static_cast<const std::uint16_t*>(Pointer) + static_cast<std::ptrdiff_t>(1); return SWAP16(*Temp); } template<> inline float ReadType<float>(const void* & Pointer) { std::uint32_t Temp = SWAP32(*static_cast<const std::uint32_t*>(Pointer)); Pointer = static_cast<const float*>(Pointer) + static_cast<std::ptrdiff_t>(1); return *reinterpret_cast<float*>(&Temp); } inline void Read(const void* & Pointer, void* Dest, std::size_t Count) { std::memcpy(Dest, Pointer, Count); Pointer = static_cast<const std::uint8_t*>(Pointer) + Count; } bool LoadFromMemory( IColorCallback& Callback, const void* Buffer, std::size_t Size ) { if( Buffer == nullptr ) { return false; } const void* ReadPoint = Buffer; const std::uint32_t Magic = ReadType<std::uint32_t>(ReadPoint); if( Magic != 'ASEF' ) { return false; } std::uint16_t Version[2]; Version[0] = ReadType<std::uint16_t>(ReadPoint); Version[1] = ReadType<std::uint16_t>(ReadPoint); std::uint32_t BlockCount = ReadType<std::uint32_t>(ReadPoint); // Process stream while( BlockCount-- ) { const std::uint16_t CurBlockClass = ReadType<std::uint16_t>(ReadPoint); switch( CurBlockClass ) { case BlockClass::ColorEntry: case BlockClass::GroupBegin: { std::uint32_t CurBlockSize = ReadType<std::uint32_t>(ReadPoint); const std::uint16_t EntryNameLength = ReadType<std::uint16_t>(ReadPoint); std::u16string EntryName; EntryName.resize(EntryNameLength); // Endian swap each character for( std::size_t i = 0; i < EntryNameLength; i++ ) { EntryName[i] = ReadType<std::uint16_t>(ReadPoint); } if( CurBlockClass == BlockClass::GroupBegin ) { Callback.GroupBegin( EntryName ); } else if( CurBlockClass == BlockClass::ColorEntry ) { const std::uint32_t ColorModel = ReadType<std::uint32_t>(ReadPoint); switch( ColorModel ) { case ColorModel::CMYK: { ColorType::CMYK CurColor; CurColor[0] = ReadType<float>(ReadPoint); CurColor[1] = ReadType<float>(ReadPoint); CurColor[2] = ReadType<float>(ReadPoint); CurColor[3] = ReadType<float>(ReadPoint); Callback.ColorCMYK( EntryName, CurColor ); break; } case ColorModel::RGB: { ColorType::RGB CurColor; CurColor[0] = ReadType<float>(ReadPoint); CurColor[1] = ReadType<float>(ReadPoint); CurColor[2] = ReadType<float>(ReadPoint); Callback.ColorRGB( EntryName, CurColor ); break; } case ColorModel::LAB: { ColorType::LAB CurColor; CurColor[0] = ReadType<float>(ReadPoint); CurColor[1] = ReadType<float>(ReadPoint); CurColor[2] = ReadType<float>(ReadPoint); Callback.ColorLAB( EntryName, CurColor ); break; } case ColorModel::GRAY: { ColorType::Gray CurColor; CurColor[0] = ReadType<float>(ReadPoint); Callback.ColorGray( EntryName, CurColor ); break; } } std::uint16_t ColorCategory = ReadType<std::uint16_t>(ReadPoint); } break; } case BlockClass::GroupEnd: { Callback.GroupEnd(); break; } } } return true; } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkCudaHierarchicalMaxFlowSegmentation2Worker.cxx Copyright (c) John SH Baxter, Robarts Research Institute This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /** @file vtkCudaHierarchicalMaxFlowSegmentation2Worker.cxx * * @brief Implementation file with class that runs each individual GPU for GHMF. * * @author John Stuart Haberl Baxter (Dr. Peters' Lab (VASST) at Robarts Research Institute) * * @note August 27th 2013 - Documentation first compiled. * * @note This is not a front-end class. Header details are in vtkCudaHierarchicalMaxFlowSegmentation2.h * */ #include "vtkCudaHierarchicalMaxFlowSegmentation2.h" #include "vtkCudaHierarchicalMaxFlowSegmentation2Task.h" #include <assert.h> #include <math.h> #include <float.h> #include <limits.h> #include <set> #include <list> #include <vector> #include "CUDA_hierarchicalmaxflow.h" #include "vtkCudaObject.h" //-----------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------// vtkCudaHierarchicalMaxFlowSegmentation2::Worker::Worker(int g, double usage, vtkCudaHierarchicalMaxFlowSegmentation2* p ) : Parent(p), GPU(g), vtkCudaObject(g) { //if verbose, print progress if( Parent->Debug ) vtkDebugWithObjectMacro(Parent,<<"Starting GPU buffer acquisition"); //Get GPU buffers int BuffersAcquired = 0; double PercentAcquired = 0.0; UnusedGPUBuffers.clear(); CPU2GPUMap.clear(); GPU2CPUMap.clear(); CPU2GPUMap.insert(std::pair<float*,float*>((float*)0,(float*)0)); GPU2CPUMap.insert(std::pair<float*,float*>((float*)0,(float*)0)); while(true) { //try acquiring some new buffers float* NewAcquiredBuffers = 0; int NewNumberAcquired = 0; int Pad = Parent->VX*Parent->VY; double NewPercentAcquired = 0; CUDA_GetGPUBuffers( Parent->TotalNumberOfBuffers-BuffersAcquired, usage-PercentAcquired, &NewAcquiredBuffers, Pad, Parent->VolumeSize, &NewNumberAcquired, &NewPercentAcquired ); BuffersAcquired += NewNumberAcquired; PercentAcquired += NewPercentAcquired; //if no new buffers were acquired, exit the loop if( NewNumberAcquired == 0 ) break; //else, load the new buffers into the list of unused buffers AllGPUBufferBlocks.push_back(NewAcquiredBuffers); NewAcquiredBuffers += Pad; for(int i = 0; i < NewNumberAcquired; i++){ UnusedGPUBuffers.push_back(NewAcquiredBuffers); NewAcquiredBuffers += Parent->VolumeSize; } } NumBuffers = BuffersAcquired; } vtkCudaHierarchicalMaxFlowSegmentation2::Worker::~Worker(){ this->CallSyncThreads(); //Return all GPU buffers ReturnLeafLabels(); while( AllGPUBufferBlocks.size() > 0 ){ CUDA_ReturnGPUBuffers( AllGPUBufferBlocks.front() ); AllGPUBufferBlocks.pop_front(); } //take down stack structure TakeDownPriorityStacks(); //clear remaining mappings CPU2GPUMap.clear(); GPU2CPUMap.clear(); UnusedGPUBuffers.clear(); AllGPUBufferBlocks.clear(); CPUInUse.clear(); } void vtkCudaHierarchicalMaxFlowSegmentation2::Worker::ReturnLeafLabels(){ //Copy back any uncopied leaf label buffers (others don't matter anymore) for( int i = 0; i < Parent->NumLeaves; i++ ) if( CPU2GPUMap.find(Parent->leafLabelBuffers[i]) != CPU2GPUMap.end() ){ Parent->ReturnBufferGPU2CPU(this,Parent->leafLabelBuffers[i], CPU2GPUMap[Parent->leafLabelBuffers[i]],GetStream()); GPU2CPUMap.erase(GPU2CPUMap.find(CPU2GPUMap[Parent->leafLabelBuffers[i]])); CPU2GPUMap.erase(CPU2GPUMap.find(Parent->leafLabelBuffers[i])); } } void vtkCudaHierarchicalMaxFlowSegmentation2::Worker::ReturnBuffer(float* CPUBuffer){ if( !CPUBuffer ) return; if( CPU2GPUMap.find(CPUBuffer) != CPU2GPUMap.end() ){ Parent->ReturnBufferGPU2CPU(this,CPUBuffer, CPU2GPUMap[CPUBuffer],GetStream()); UnusedGPUBuffers.push_front(CPU2GPUMap[CPUBuffer]); GPU2CPUMap.erase(GPU2CPUMap.find(CPU2GPUMap[CPUBuffer])); CPU2GPUMap.erase(CPU2GPUMap.find(CPUBuffer)); RemoveFromStack(CPUBuffer); } } void vtkCudaHierarchicalMaxFlowSegmentation2::Worker::UpdateBuffersInUse(){ for( std::set<float*>::iterator iterator = CPUInUse.begin(); iterator != CPUInUse.end(); iterator++ ){ //check if this buffer needs to be assigned if( !(*iterator) ) continue; if( CPU2GPUMap.find( *iterator ) != CPU2GPUMap.end() ) continue; //start assigning from the list of unused buffers if( UnusedGPUBuffers.size() > 0 ){ float* NewGPUBuffer = UnusedGPUBuffers.front(); UnusedGPUBuffers.pop_front(); CPU2GPUMap.insert( std::pair<float*,float*>(*iterator, NewGPUBuffer) ); GPU2CPUMap.insert( std::pair<float*,float*>(NewGPUBuffer, *iterator) ); Parent->MoveBufferCPU2GPU(this,*iterator,NewGPUBuffer,GetStream()); //update the priority stacks AddToStack(*iterator); continue; } //see if there is some garbage we can deallocate first bool flag = false; for( std::set<float*>::iterator iterator2 = Parent->NoCopyBack.begin(); iterator2 != Parent->NoCopyBack.end(); iterator2++ ){ if( CPUInUse.find(*iterator2) != CPUInUse.end() ) continue; if( CPU2GPUMap.find(*iterator2) == CPU2GPUMap.end() ) continue; float* NewGPUBuffer = CPU2GPUMap[*iterator2]; CPU2GPUMap.erase( CPU2GPUMap.find(*iterator2) ); GPU2CPUMap.erase( GPU2CPUMap.find(NewGPUBuffer) ); CPU2GPUMap.insert( std::pair<float*,float*>(*iterator, NewGPUBuffer) ); GPU2CPUMap.insert( std::pair<float*,float*>(NewGPUBuffer, *iterator) ); Parent->MoveBufferCPU2GPU(this,*iterator,NewGPUBuffer,GetStream()); //update the priority stacks RemoveFromStack(*iterator2); AddToStack(*iterator); flag = true; break; } if( flag ) continue; //else, we have to move something in use back to the CPU flag = false; std::vector< std::list< float* > >::iterator stackIterator = PriorityStacks.begin(); for( ; !flag && stackIterator != PriorityStacks.end(); stackIterator++ ){ for(std::list< float* >::iterator subIterator = stackIterator->begin(); subIterator != stackIterator->end(); subIterator++ ){ //can't remove this one because it is in use or null if( !(*subIterator) ) continue; if( CPUInUse.find( *subIterator ) != CPUInUse.end() ) continue; //else, find it and move it back to the CPU float* NewGPUBuffer = CPU2GPUMap.find(*subIterator)->second; CPU2GPUMap.erase( CPU2GPUMap.find(*subIterator) ); GPU2CPUMap.erase( GPU2CPUMap.find(NewGPUBuffer) ); CPU2GPUMap.insert( std::pair<float*,float*>(*iterator, NewGPUBuffer) ); GPU2CPUMap.insert( std::pair<float*,float*>(NewGPUBuffer, *iterator) ); Parent->ReturnBufferGPU2CPU(this,*subIterator,NewGPUBuffer,GetStream()); Parent->MoveBufferCPU2GPU(this,*iterator,NewGPUBuffer,GetStream()); //update the priority stack and leave immediately since our iterators //no longer have a valid contract (changed container) RemoveFromStack(*subIterator); AddToStack(*iterator); flag = true; break; } } } } //Add a CPU-GPU buffer pair from this workers collection void vtkCudaHierarchicalMaxFlowSegmentation2::Worker::AddToStack( float* CPUBuffer ){ int neededPriority = Parent->CPU2PriorityMap.find(CPUBuffer)->second; BuildStackUpToPriority( neededPriority ); std::vector< std::list< float* > >::iterator stackIterator = PriorityStacks.begin(); for(int count = 1; count < neededPriority; count++, stackIterator++); stackIterator->push_front(CPUBuffer); } //Remove a CPU-GPU buffer pair from this workers collection void vtkCudaHierarchicalMaxFlowSegmentation2::Worker::RemoveFromStack( float* CPUBuffer ){ int neededPriority = Parent->CPU2PriorityMap.find(CPUBuffer)->second; std::vector< std::list< float* > >::iterator stackIterator = PriorityStacks.begin(); for(int count = 1; count < neededPriority; count++, stackIterator++); for(std::list< float* >::iterator subIterator = stackIterator->begin(); subIterator != stackIterator->end(); subIterator++ ){ if( *subIterator == CPUBuffer ){ stackIterator->erase(subIterator); return; } } } //Make sure that this buffers collection can handle the stack size void vtkCudaHierarchicalMaxFlowSegmentation2::Worker::BuildStackUpToPriority( int priority ){ while( PriorityStacks.size() < priority ) PriorityStacks.push_back( std::list<float*>() ); } //take down the stacks void vtkCudaHierarchicalMaxFlowSegmentation2::Worker::TakeDownPriorityStacks(){ std::vector< std::list< float* > >::iterator stackIterator = PriorityStacks.begin(); for( ; stackIterator != PriorityStacks.end(); stackIterator++ ) stackIterator->clear(); PriorityStacks.clear(); } int vtkCudaHierarchicalMaxFlowSegmentation2::Worker::LowestBufferShift(int n){ int retVal = 0; n -= (int) this->UnusedGPUBuffers.size(); std::vector< std::list< float* > >::iterator stackIterator = PriorityStacks.begin(); for(int count = 1; stackIterator != PriorityStacks.end(); count++, stackIterator++){ if( n > (*stackIterator).size() ){ n -= (int) (*stackIterator).size(); retVal += count * (int) (*stackIterator).size(); }else{ retVal += count*n; break; } } return (n>0) ? n: 0; } <commit_msg>FIX: Odd crash in the last condition for swapping buffers. Put in a small fix which appears to work, but more investigation is necessary to find out what is the problem and how to fix it better.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkCudaHierarchicalMaxFlowSegmentation2Worker.cxx Copyright (c) John SH Baxter, Robarts Research Institute This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /** @file vtkCudaHierarchicalMaxFlowSegmentation2Worker.cxx * * @brief Implementation file with class that runs each individual GPU for GHMF. * * @author John Stuart Haberl Baxter (Dr. Peters' Lab (VASST) at Robarts Research Institute) * * @note August 27th 2013 - Documentation first compiled. * * @note This is not a front-end class. Header details are in vtkCudaHierarchicalMaxFlowSegmentation2.h * */ #include "vtkCudaHierarchicalMaxFlowSegmentation2.h" #include "vtkCudaHierarchicalMaxFlowSegmentation2Task.h" #include <assert.h> #include <math.h> #include <float.h> #include <limits.h> #include <set> #include <list> #include <vector> #include "CUDA_hierarchicalmaxflow.h" #include "vtkCudaObject.h" //-----------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------// vtkCudaHierarchicalMaxFlowSegmentation2::Worker::Worker(int g, double usage, vtkCudaHierarchicalMaxFlowSegmentation2* p ) : Parent(p), GPU(g), vtkCudaObject(g) { //if verbose, print progress if( Parent->Debug ) vtkDebugWithObjectMacro(Parent,<<"Starting GPU buffer acquisition"); //Get GPU buffers int BuffersAcquired = 0; double PercentAcquired = 0.0; UnusedGPUBuffers.clear(); CPU2GPUMap.clear(); GPU2CPUMap.clear(); CPU2GPUMap.insert(std::pair<float*,float*>((float*)0,(float*)0)); GPU2CPUMap.insert(std::pair<float*,float*>((float*)0,(float*)0)); while(true) { //try acquiring some new buffers float* NewAcquiredBuffers = 0; int NewNumberAcquired = 0; int Pad = Parent->VX*Parent->VY; double NewPercentAcquired = 0; CUDA_GetGPUBuffers( Parent->TotalNumberOfBuffers-BuffersAcquired, usage-PercentAcquired, &NewAcquiredBuffers, Pad, Parent->VolumeSize, &NewNumberAcquired, &NewPercentAcquired ); BuffersAcquired += NewNumberAcquired; PercentAcquired += NewPercentAcquired; //if no new buffers were acquired, exit the loop if( NewNumberAcquired == 0 ) break; //else, load the new buffers into the list of unused buffers AllGPUBufferBlocks.push_back(NewAcquiredBuffers); NewAcquiredBuffers += Pad; for(int i = 0; i < NewNumberAcquired; i++){ UnusedGPUBuffers.push_back(NewAcquiredBuffers); NewAcquiredBuffers += Parent->VolumeSize; } } NumBuffers = BuffersAcquired; } vtkCudaHierarchicalMaxFlowSegmentation2::Worker::~Worker(){ this->CallSyncThreads(); //Return all GPU buffers ReturnLeafLabels(); while( AllGPUBufferBlocks.size() > 0 ){ CUDA_ReturnGPUBuffers( AllGPUBufferBlocks.front() ); AllGPUBufferBlocks.pop_front(); } //take down stack structure TakeDownPriorityStacks(); //clear remaining mappings CPU2GPUMap.clear(); GPU2CPUMap.clear(); UnusedGPUBuffers.clear(); AllGPUBufferBlocks.clear(); CPUInUse.clear(); } void vtkCudaHierarchicalMaxFlowSegmentation2::Worker::ReturnLeafLabels(){ //Copy back any uncopied leaf label buffers (others don't matter anymore) for( int i = 0; i < Parent->NumLeaves; i++ ) if( CPU2GPUMap.find(Parent->leafLabelBuffers[i]) != CPU2GPUMap.end() ){ Parent->ReturnBufferGPU2CPU(this,Parent->leafLabelBuffers[i], CPU2GPUMap[Parent->leafLabelBuffers[i]],GetStream()); GPU2CPUMap.erase(GPU2CPUMap.find(CPU2GPUMap[Parent->leafLabelBuffers[i]])); CPU2GPUMap.erase(CPU2GPUMap.find(Parent->leafLabelBuffers[i])); } } void vtkCudaHierarchicalMaxFlowSegmentation2::Worker::ReturnBuffer(float* CPUBuffer){ if( !CPUBuffer ) return; if( CPU2GPUMap.find(CPUBuffer) != CPU2GPUMap.end() ){ Parent->ReturnBufferGPU2CPU(this,CPUBuffer, CPU2GPUMap[CPUBuffer],GetStream()); UnusedGPUBuffers.push_front(CPU2GPUMap[CPUBuffer]); GPU2CPUMap.erase(GPU2CPUMap.find(CPU2GPUMap[CPUBuffer])); CPU2GPUMap.erase(CPU2GPUMap.find(CPUBuffer)); RemoveFromStack(CPUBuffer); } } void vtkCudaHierarchicalMaxFlowSegmentation2::Worker::UpdateBuffersInUse(){ for( std::set<float*>::iterator iterator = CPUInUse.begin(); iterator != CPUInUse.end(); iterator++ ){ //check if this buffer needs to be assigned if( !(*iterator) ) continue; if( CPU2GPUMap.find( *iterator ) != CPU2GPUMap.end() ) continue; //start assigning from the list of unused buffers if( UnusedGPUBuffers.size() > 0 ){ float* NewGPUBuffer = UnusedGPUBuffers.front(); UnusedGPUBuffers.pop_front(); CPU2GPUMap.insert( std::pair<float*,float*>(*iterator, NewGPUBuffer) ); GPU2CPUMap.insert( std::pair<float*,float*>(NewGPUBuffer, *iterator) ); Parent->MoveBufferCPU2GPU(this,*iterator,NewGPUBuffer,GetStream()); //update the priority stacks AddToStack(*iterator); continue; } //see if there is some garbage we can deallocate first bool flag = false; for( std::set<float*>::iterator iterator2 = Parent->NoCopyBack.begin(); iterator2 != Parent->NoCopyBack.end(); iterator2++ ){ if( CPUInUse.find(*iterator2) != CPUInUse.end() ) continue; if( CPU2GPUMap.find(*iterator2) == CPU2GPUMap.end() ) continue; float* NewGPUBuffer = CPU2GPUMap[*iterator2]; CPU2GPUMap.erase( CPU2GPUMap.find(*iterator2) ); GPU2CPUMap.erase( GPU2CPUMap.find(NewGPUBuffer) ); CPU2GPUMap.insert( std::pair<float*,float*>(*iterator, NewGPUBuffer) ); GPU2CPUMap.insert( std::pair<float*,float*>(NewGPUBuffer, *iterator) ); Parent->MoveBufferCPU2GPU(this,*iterator,NewGPUBuffer,GetStream()); //update the priority stacks RemoveFromStack(*iterator2); AddToStack(*iterator); flag = true; break; } if( flag ) continue; //else, we have to move something in use back to the CPU flag = false; std::vector< std::list< float* > >::iterator stackIterator = PriorityStacks.begin(); for( ; !flag && stackIterator != PriorityStacks.end(); stackIterator++ ){ for(std::list< float* >::iterator subIterator = stackIterator->begin(); subIterator != stackIterator->end(); subIterator++ ){ //can't remove this one because it is in use or null if( !(*subIterator) ) continue; if( CPUInUse.find( *subIterator ) != CPUInUse.end() ) continue; //else, find it and move it back to the CPU float* NewGPUBuffer = CPU2GPUMap.find(*subIterator)->second; CPU2GPUMap.erase( CPU2GPUMap.find(*subIterator) ); GPU2CPUMap.erase( GPU2CPUMap.find(NewGPUBuffer) ); CPU2GPUMap.insert( std::pair<float*,float*>(*iterator, NewGPUBuffer) ); GPU2CPUMap.insert( std::pair<float*,float*>(NewGPUBuffer, *iterator) ); Parent->ReturnBufferGPU2CPU(this,*subIterator,NewGPUBuffer,GetStream()); Parent->MoveBufferCPU2GPU(this,*iterator,NewGPUBuffer,GetStream()); //update the priority stack and leave immediately since our iterators //no longer have a valid contract (changed container) RemoveFromStack(*subIterator); AddToStack(*iterator); flag = true; break; } if( flag ) break; } } } //Add a CPU-GPU buffer pair from this workers collection void vtkCudaHierarchicalMaxFlowSegmentation2::Worker::AddToStack( float* CPUBuffer ){ int neededPriority = Parent->CPU2PriorityMap.find(CPUBuffer)->second; BuildStackUpToPriority( neededPriority ); std::vector< std::list< float* > >::iterator stackIterator = PriorityStacks.begin(); for(int count = 1; count < neededPriority; count++, stackIterator++); stackIterator->push_front(CPUBuffer); } //Remove a CPU-GPU buffer pair from this workers collection void vtkCudaHierarchicalMaxFlowSegmentation2::Worker::RemoveFromStack( float* CPUBuffer ){ int neededPriority = Parent->CPU2PriorityMap.find(CPUBuffer)->second; std::vector< std::list< float* > >::iterator stackIterator = PriorityStacks.begin(); for(int count = 1; count < neededPriority; count++, stackIterator++); for(std::list< float* >::iterator subIterator = stackIterator->begin(); subIterator != stackIterator->end(); subIterator++ ){ if( *subIterator == CPUBuffer ){ stackIterator->erase(subIterator); return; } } } //Make sure that this buffers collection can handle the stack size void vtkCudaHierarchicalMaxFlowSegmentation2::Worker::BuildStackUpToPriority( int priority ){ while( PriorityStacks.size() < priority ) PriorityStacks.push_back( std::list<float*>() ); } //take down the stacks void vtkCudaHierarchicalMaxFlowSegmentation2::Worker::TakeDownPriorityStacks(){ std::vector< std::list< float* > >::iterator stackIterator = PriorityStacks.begin(); for( ; stackIterator != PriorityStacks.end(); stackIterator++ ) stackIterator->clear(); PriorityStacks.clear(); } int vtkCudaHierarchicalMaxFlowSegmentation2::Worker::LowestBufferShift(int n){ int retVal = 0; n -= (int) this->UnusedGPUBuffers.size(); std::vector< std::list< float* > >::iterator stackIterator = PriorityStacks.begin(); for(int count = 1; stackIterator != PriorityStacks.end(); count++, stackIterator++){ if( n > (*stackIterator).size() ){ n -= (int) (*stackIterator).size(); retVal += count * (int) (*stackIterator).size(); }else{ retVal += count*n; break; } } return (n>0) ? n: 0; } <|endoftext|>
<commit_before>/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions * * This file is part of WATCHER. * * WATCHER is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WATCHER is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Watcher. If not, see <http://www.gnu.org/licenses/>. */ /** * @file backgroundImage.cpp * @author Geoff Lawler <geoff.lawler@cobham.com> * @date 2009-07-15 */ #include <GL/gl.h> #include <GL/glu.h> #include <boost/filesystem.hpp> #include <SDL_image.h> #include <string.h> #include <errno.h> #include <stdlib.h> #include <stdio.h> #include "backgroundImage.h" #include "bitmap.h" #include "logger.h" using namespace watcher; INIT_LOGGER(BackgroundImage, "BackgroundImage"); BackgroundImage &BackgroundImage::getInstance() { TRACE_ENTER(); static BackgroundImage theoneandonlybgimageinstanceyoubetcha; TRACE_EXIT(); return theoneandonlybgimageinstanceyoubetcha; } BackgroundImage::BackgroundImage() : imageLoaded(false), imageCenter(false), minx(0.0), miny(0.0), xoffset(0.0), // use image defaults yoffset(0.0), // use image defaults z(0.0), imageWidth(0), imageHeight(0), imageFile("") { TRACE_ENTER(); envColor[0]=0.0; envColor[1]=0.0; envColor[2]=0.0; envColor[3]=0.0; borderColor[0]=0.0; borderColor[1]=0.0; borderColor[2]=0.0; borderColor[3]=0.0; TRACE_EXIT(); } BackgroundImage::~BackgroundImage() { TRACE_ENTER(); TRACE_EXIT(); } bool BackgroundImage::loadImageFile(const std::string &filename) { TRACE_ENTER(); loadSDLSurfaceTexture(filename); TRACE_EXIT(); return true; } void BackgroundImage::loadSDLSurfaceTexture(const std::string &filename) { TRACE_ENTER(); if (!boost::filesystem::exists(filename)) { LOG_WARN("Unable to load backgroun image " << filename << " as the file does not exist."); imageWidth=0; imageHeight=0; imageFile=""; imageLoaded=false; return; } LOG_INFO("Loading background image from file: " << filename); SDL_Surface* surface = IMG_Load(filename.c_str()); glGenTextures(1, &textureIntID); glBindTexture(GL_TEXTURE_2D, textureIntID); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); GLenum textureFormat=GL_RGBA; /* Set the color mode */ switch (surface->format->BytesPerPixel) { case 4: if (SDL_BYTEORDER == SDL_BIG_ENDIAN) textureFormat = GL_BGRA; else textureFormat = GL_RGBA; break; case 3: if (SDL_BYTEORDER == SDL_BIG_ENDIAN) textureFormat = GL_BGR; else textureFormat = GL_RGB; break; } glTexImage2D(GL_TEXTURE_2D, 0, surface->format->BytesPerPixel, surface->w, surface->h, 0, textureFormat, GL_UNSIGNED_BYTE, surface->pixels); imageWidth=surface->w; imageHeight=surface->h; imageFile=filename; imageLoaded=true; SDL_FreeSurface(surface); TRACE_EXIT(); } void BackgroundImage::drawImage() { TRACE_ENTER(); if (!imageLoaded) { TRACE_EXIT(); return; } glPushMatrix(); glTranslatef(0,0,z); glPushAttrib(GL_ALL_ATTRIB_BITS); glEnable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glDisable(GL_BLEND); // glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glBegin(GL_QUADS); glTexCoord2f(0,0); glVertex2f(minx ,miny+yoffset); glTexCoord2f(1,0); glVertex2f(minx+xoffset,miny+yoffset); glTexCoord2f(1,1); glVertex2f(minx+xoffset,miny); glTexCoord2f(0,1); glVertex2f(minx ,miny); glEnd(); glPopAttrib(); glPopMatrix(); glEndList(); TRACE_EXIT(); } void BackgroundImage::setDrawingCoords(GLfloat minx_, GLfloat width_, GLfloat miny_, GLfloat height_, GLfloat z_) { TRACE_ENTER(); minx=minx_; xoffset=width_==0?imageWidth:width_; // if not set, use image width as offset miny=miny_; yoffset=height_==0?miny+imageHeight:height_; // If not set, use image height as offset. z=z_; TRACE_EXIT(); } void BackgroundImage::getDrawingCoords(GLfloat &minx_, GLfloat &width_, GLfloat &miny_, GLfloat &height_, GLfloat &z_) { TRACE_ENTER(); minx_=minx; width_=xoffset; miny_=miny; height_=yoffset; z_=z; TRACE_EXIT(); } void BackgroundImage::centerImage(bool val) { TRACE_ENTER(); imageCenter=val; TRACE_EXIT(); } bool BackgroundImage::centerImage() const { TRACE_ENTER(); TRACE_EXIT_RET( (imageCenter?"true":"false") ); return imageCenter; } <commit_msg>remove old line of code and bind texture correctly<commit_after>/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions * * This file is part of WATCHER. * * WATCHER is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WATCHER is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Watcher. If not, see <http://www.gnu.org/licenses/>. */ /** * @file backgroundImage.cpp * @author Geoff Lawler <geoff.lawler@cobham.com> * @date 2009-07-15 */ #include <GL/gl.h> #include <GL/glu.h> #include <boost/filesystem.hpp> #include <SDL_image.h> #include <string.h> #include <errno.h> #include <stdlib.h> #include <stdio.h> #include "backgroundImage.h" #include "bitmap.h" #include "logger.h" using namespace watcher; INIT_LOGGER(BackgroundImage, "BackgroundImage"); BackgroundImage &BackgroundImage::getInstance() { TRACE_ENTER(); static BackgroundImage theoneandonlybgimageinstanceyoubetcha; TRACE_EXIT(); return theoneandonlybgimageinstanceyoubetcha; } BackgroundImage::BackgroundImage() : imageLoaded(false), imageCenter(false), minx(0.0), miny(0.0), xoffset(0.0), // use image defaults yoffset(0.0), // use image defaults z(0.0), imageWidth(0), imageHeight(0), imageFile("") { TRACE_ENTER(); envColor[0]=0.0; envColor[1]=0.0; envColor[2]=0.0; envColor[3]=0.0; borderColor[0]=0.0; borderColor[1]=0.0; borderColor[2]=0.0; borderColor[3]=0.0; TRACE_EXIT(); } BackgroundImage::~BackgroundImage() { TRACE_ENTER(); TRACE_EXIT(); } bool BackgroundImage::loadImageFile(const std::string &filename) { TRACE_ENTER(); loadSDLSurfaceTexture(filename); TRACE_EXIT(); return true; } void BackgroundImage::loadSDLSurfaceTexture(const std::string &filename) { TRACE_ENTER(); if (!boost::filesystem::exists(filename)) { LOG_WARN("Unable to load backgroun image " << filename << " as the file does not exist."); imageWidth=0; imageHeight=0; imageFile=""; imageLoaded=false; return; } LOG_INFO("Loading background image from file: " << filename); SDL_Surface* surface = IMG_Load(filename.c_str()); glGenTextures(1, &textureIntID); glBindTexture(GL_TEXTURE_2D, textureIntID); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); GLenum textureFormat=GL_RGBA; /* Set the color mode */ switch (surface->format->BytesPerPixel) { case 4: if (SDL_BYTEORDER == SDL_BIG_ENDIAN) textureFormat = GL_BGRA; else textureFormat = GL_RGBA; break; case 3: if (SDL_BYTEORDER == SDL_BIG_ENDIAN) textureFormat = GL_BGR; else textureFormat = GL_RGB; break; } glTexImage2D(GL_TEXTURE_2D, 0, surface->format->BytesPerPixel, surface->w, surface->h, 0, textureFormat, GL_UNSIGNED_BYTE, surface->pixels); imageWidth=surface->w; imageHeight=surface->h; imageFile=filename; imageLoaded=true; SDL_FreeSurface(surface); TRACE_EXIT(); } void BackgroundImage::drawImage() { TRACE_ENTER(); if (!imageLoaded) { TRACE_EXIT(); return; } glPushMatrix(); glTranslatef(0,0,z); glPushAttrib(GL_ALL_ATTRIB_BITS); glEnable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glDisable(GL_BLEND); // glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glBindTexture(GL_TEXTURE_2D, textureIntID); glBegin(GL_QUADS); glTexCoord2f(0,0); glVertex2f(minx ,miny+yoffset); glTexCoord2f(1,0); glVertex2f(minx+xoffset,miny+yoffset); glTexCoord2f(1,1); glVertex2f(minx+xoffset,miny); glTexCoord2f(0,1); glVertex2f(minx ,miny); glEnd(); glPopAttrib(); glPopMatrix(); TRACE_EXIT(); } void BackgroundImage::setDrawingCoords(GLfloat minx_, GLfloat width_, GLfloat miny_, GLfloat height_, GLfloat z_) { TRACE_ENTER(); minx=minx_; xoffset=width_==0?imageWidth:width_; // if not set, use image width as offset miny=miny_; yoffset=height_==0?miny+imageHeight:height_; // If not set, use image height as offset. z=z_; TRACE_EXIT(); } void BackgroundImage::getDrawingCoords(GLfloat &minx_, GLfloat &width_, GLfloat &miny_, GLfloat &height_, GLfloat &z_) { TRACE_ENTER(); minx_=minx; width_=xoffset; miny_=miny; height_=yoffset; z_=z; TRACE_EXIT(); } void BackgroundImage::centerImage(bool val) { TRACE_ENTER(); imageCenter=val; TRACE_EXIT(); } bool BackgroundImage::centerImage() const { TRACE_ENTER(); TRACE_EXIT_RET( (imageCenter?"true":"false") ); return imageCenter; } <|endoftext|>
<commit_before>#ifndef CMDSTAN_ARGUMENTS_ARG_OUTPUT_SIG_FIGS_HPP #define CMDSTAN_ARGUMENTS_ARG_OUTPUT_SIG_FIGS_HPP #include <cmdstan/arguments/singleton_argument.hpp> namespace cmdstan { class arg_output_sig_figs : public int_argument { public: arg_output_sig_figs() : int_argument() { _name = "sig_figs"; _description = "The number of significant figures used for the output CSV files."; _validity = "0 <= integer <= 18 or -1 to use the default number of significant " "figures"; _default = "-1"; _default_value = -1; _constrained = true; _good_value = 8; _bad_value = -2; _value = _default_value; } bool is_valid(int value) { return (value >= 0 && value <= 18) || value == _default_value; } }; } // namespace cmdstan #endif <commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags/RELEASE_600/final)<commit_after>#ifndef CMDSTAN_ARGUMENTS_ARG_OUTPUT_SIG_FIGS_HPP #define CMDSTAN_ARGUMENTS_ARG_OUTPUT_SIG_FIGS_HPP #include <cmdstan/arguments/singleton_argument.hpp> namespace cmdstan { class arg_output_sig_figs : public int_argument { public: arg_output_sig_figs() : int_argument() { _name = "sig_figs"; _description = "The number of significant figures used for the output CSV files."; _validity = "0 <= integer <= 18 or -1 to use the default number of significant " "figures"; _default = "-1"; _default_value = -1; _constrained = true; _good_value = 8; _bad_value = -2; _value = _default_value; } bool is_valid(int value) { return (value >= 0 && value <= 18) || value == _default_value; } }; } // namespace cmdstan #endif <|endoftext|>
<commit_before><commit_msg>Lua API - getActiveGlobalLight, getGlobalLightEntity<commit_after><|endoftext|>
<commit_before><commit_msg>fix RC cal bug<commit_after><|endoftext|>
<commit_before>#include "Thermostat.h" #include "Andersen.h" #include "Lowe_Andersen.h" #include "Gaussian.h" #include "Nose_Hoover.h" #include "Thermostat_None.h" #include "consts.h" using namespace consts; #include <iostream> #include <fstream> #include <algorithm> #include <cmath> #include <stdlib.h> // atof #include <cstring> //strcmp using namespace std; inline bool is_number(const std::string &str) { return str.find_first_not_of(".eE-0123456789") == std::string::npos; } double set_param(double def, char *array[], int length, int pos) { if ( pos >= length ) return def; if ( is_number( array[pos] ) ) return stod( array[pos] ); return def; } ostream& operator<<(ostream& os, const Polymer & poly) { poly.print(os); return os; } /* ######################### */ int main(int argc, char* argv[]) { double a_para[]{4, 20, 1E-15, 1E6}; //default für p,Temp,dtime,runs int i_para{1}; string s_para{}, s_therm{}; string s_temp{}, s_pos_vel{}; ofstream dat_temp{}, dat_pos_vel{}; Thermostat *thermostat{}; // Bestimmen der Parameter zur Initialisierung von Poly und Thermostat for (i_para=1; i_para<min(5,argc); ++i_para) { if ( is_number(argv[i_para]) ) a_para[i_para-1]=stod(argv[i_para]); else break; } while ( i_para < argc - 1 && is_number( argv[i_para] ) ) ++i_para; a_para[2] /= ref_time; Polymer poly{static_cast<unsigned> (a_para[0]), a_para[1]}; poly.initiate_monomers_random(); s_para = "_p"; s_para += to_string( (int)a_para[0] ); s_para += "_T"; s_para += to_string( a_para[1] ); // Initialisieren aller Thermostate double nu{ set_param( 1./a_para[2]/a_para[0], argv, argc, i_para+1 ) }; Andersen andersen_therm{poly, a_para[2], nu}; Lowe_Andersen lowe_andersen_therm{poly, a_para[2], nu}; Gaussian gaussian_therm{poly, a_para[2]}; double q_def{poly.monomers.size()*poly.temp()*ref_time / 1E-14}; double q{set_param (q_def, argv, argc, i_para+1) }; Nose_Hoover nose_hoover_therm{poly, a_para[2], q}; Thermostat_None none_therm{poly, a_para[2]}; // Auswählen des Thermostats if ( argc > 1 && i_para < argc ) { if ( strcmp( argv[i_para] , "Andersen" ) == 0 ) { thermostat = & andersen_therm; s_therm = "Andersen"; } else if ( strcmp( argv[i_para] , "Lowe_Andersen" ) == 0 ) { thermostat = & lowe_andersen_therm; s_therm = "Lowe_Andersen"; } else if ( strcmp( argv[i_para] , "Gaussian" ) == 0 ) { thermostat = & gaussian_therm; s_therm = "Gaussian"; } else if ( strcmp( argv[i_para] , "Nose_Hoover" ) == 0 ) { thermostat = & nose_hoover_therm; s_therm = "Nose_Hoover"; } else { thermostat = & none_therm; s_therm = "None"; } } else { thermostat = & none_therm; s_therm = "None"; } s_temp = s_therm + "_temp" + s_para + ".dat"; dat_temp.open(s_temp, ios::out | ios::trunc); s_pos_vel = s_therm + "_pos_vel" + s_para + ".dat"; dat_pos_vel.open(s_pos_vel, ios::out | ios::trunc); int index_print{a_para[3]*1E-1*4}; for (int i = 0; i < a_para[3]; i++) { dat_temp << i*a_para[2] << " " << poly.calculate_temp() << endl; dat_pos_vel << poly << endl; if ( !( i % index_print ) ) { cout << i*a_para[2] << endl; cout << "Ekin: " << poly.update_ekin() << endl; cout << "T: " << poly.calculate_temp() << endl; } thermostat->propagate(); } cout << "Die Datei '" << s_temp << "' wurde erstellt." << endl; cout << "Die Datei '" << s_pos_vel << "' wurde erstellt." << endl; dat_temp.close(); dat_pos_vel.close(); return 0; } <commit_msg>_T20.0000 auf int _T20 geändert<commit_after>#include "Thermostat.h" #include "Andersen.h" #include "Lowe_Andersen.h" #include "Gaussian.h" #include "Nose_Hoover.h" #include "Thermostat_None.h" #include "consts.h" using namespace consts; #include <iostream> #include <fstream> #include <algorithm> #include <cmath> #include <stdlib.h> // atof #include <cstring> //strcmp using namespace std; inline bool is_number(const std::string &str) { return str.find_first_not_of(".eE-0123456789") == std::string::npos; } double set_param(double def, char *array[], int length, int pos) { if ( pos >= length ) return def; if ( is_number( array[pos] ) ) return stod( array[pos] ); return def; } ostream& operator<<(ostream& os, const Polymer & poly) { poly.print(os); return os; } /* ######################### */ int main(int argc, char* argv[]) { double a_para[]{4, 20, 1E-15, 1E6}; //default für p,Temp,dtime,runs int i_para{1}; string s_para{}, s_therm{}; string s_temp{}, s_pos_vel{}; ofstream dat_temp{}, dat_pos_vel{}; Thermostat *thermostat{}; // Bestimmen der Parameter zur Initialisierung von Poly und Thermostat for (i_para=1; i_para<min(5,argc); ++i_para) { if ( is_number(argv[i_para]) ) a_para[i_para-1]=stod(argv[i_para]); else break; } while ( i_para < argc - 1 && is_number( argv[i_para] ) ) ++i_para; a_para[2] /= ref_time; Polymer poly{static_cast<unsigned> (a_para[0]), a_para[1]}; poly.initiate_monomers_random(); s_para = "_p"; s_para += to_string( (int)a_para[0] ); s_para += "_T"; s_para += to_string( (int)a_para[1] ); // Initialisieren aller Thermostate double nu{ set_param( 1./a_para[2]/a_para[0], argv, argc, i_para+1 ) }; Andersen andersen_therm{poly, a_para[2], nu}; Lowe_Andersen lowe_andersen_therm{poly, a_para[2], nu}; Gaussian gaussian_therm{poly, a_para[2]}; double q_def{poly.monomers.size()*poly.temp()*ref_time / 1E-14}; double q{set_param (q_def, argv, argc, i_para+1) }; Nose_Hoover nose_hoover_therm{poly, a_para[2], q}; Thermostat_None none_therm{poly, a_para[2]}; // Auswählen des Thermostats if ( argc > 1 && i_para < argc ) { if ( strcmp( argv[i_para] , "Andersen" ) == 0 ) { thermostat = & andersen_therm; s_therm = "Andersen"; } else if ( strcmp( argv[i_para] , "Lowe_Andersen" ) == 0 ) { thermostat = & lowe_andersen_therm; s_therm = "Lowe_Andersen"; } else if ( strcmp( argv[i_para] , "Gaussian" ) == 0 ) { thermostat = & gaussian_therm; s_therm = "Gaussian"; } else if ( strcmp( argv[i_para] , "Nose_Hoover" ) == 0 ) { thermostat = & nose_hoover_therm; s_therm = "Nose_Hoover"; } else { thermostat = & none_therm; s_therm = "None"; } } else { thermostat = & none_therm; s_therm = "None"; } s_temp = s_therm + "_temp" + s_para + ".dat"; dat_temp.open(s_temp, ios::out | ios::trunc); s_pos_vel = s_therm + "_pos_vel" + s_para + ".dat"; dat_pos_vel.open(s_pos_vel, ios::out | ios::trunc); int index_print{a_para[3]*1E-1*4}; for (int i = 0; i < a_para[3]; i++) { dat_temp << i*a_para[2] << " " << poly.calculate_temp() << endl; dat_pos_vel << poly; if ( !( i % index_print ) ) { cout << i*a_para[2] << endl; cout << "Ekin: " << poly.update_ekin() << endl; cout << "T: " << poly.calculate_temp() << endl; } thermostat->propagate(); } cout << "Die Datei '" << s_temp << "' wurde erstellt." << endl; cout << "Die Datei '" << s_pos_vel << "' wurde erstellt." << endl; dat_temp.close(); dat_pos_vel.close(); return 0; } <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010, 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "msnapshotitem.h" #include <mgraphicssystemhelper.h> #include <QGraphicsScene> #include <QImage> #include <QPainter> #include <QApplication> #include <QGraphicsView> #include <QGLFramebufferObject> #ifdef HAVE_MEEGOGRAPHICSSYSTEM #include <QtMeeGoGraphicsSystemHelper> #endif MSnapshotItem::MSnapshotItem(const QRectF &sceneTargetRect, QGraphicsItem *parent) : QGraphicsObject(parent), m_boundingRect(sceneTargetRect), pixmap(), framebufferObject(0) { } MSnapshotItem::~MSnapshotItem() { delete framebufferObject; framebufferObject = 0; } QRectF MSnapshotItem::boundingRect() const { return m_boundingRect; } void MSnapshotItem::updateSnapshot() { pixmap = QPixmap(); delete framebufferObject; framebufferObject = 0; if (scene() && scene()->views().count() == 0) return; QGraphicsView *graphicsView = scene()->views().at(0); Q_ASSERT(graphicsView); bool grabContent = true; if (MGraphicsSystemHelper::isRunningMeeGoGraphicsSystem() && QGLContext::currentContext()) { #ifdef HAVE_MEEGOGRAPHICSSYSTEM graphicsView->installEventFilter(this); #endif const QRect rect = m_boundingRect.toRect(); framebufferObject = new QGLFramebufferObject(rect.size(), QGLFramebufferObject::CombinedDepthStencil); if (framebufferObject->isValid()) { QPainter painter(framebufferObject); graphicsView->render(&painter, QRectF(), rect); grabContent = false; } } if (grabContent) { #if defined(Q_WS_MAC) || defined(Q_WS_WIN) pixmap = QPixmap::grabWidget(graphicsView); #else pixmap = QPixmap::grabWindow(graphicsView->effectiveWinId()); #endif } } void MSnapshotItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(option); Q_UNUSED(widget); if (framebufferObject && framebufferObject->isValid()) { framebufferObject->drawTexture(m_boundingRect, framebufferObject->texture()); } else if (!pixmap.isNull()) { painter->drawPixmap(0,0, pixmap); } } #ifdef HAVE_MEEGOGRAPHICSSYSTEM bool MSnapshotItem::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QMeeGoSwitchEvent::eventNumber()) { QMeeGoSwitchEvent* switchEvent = static_cast<QMeeGoSwitchEvent*>(event); if (switchEvent->state() == QMeeGoSwitchEvent::WillSwitch) { delete framebufferObject; framebufferObject = 0; } } return QGraphicsObject::eventFilter(obj, event); } #endif <commit_msg>Fixes: Orientation change animation in scratchbox/desktop.<commit_after>/*************************************************************************** ** ** Copyright (C) 2010, 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "msnapshotitem.h" #include <mgraphicssystemhelper.h> #include <QGraphicsScene> #include <QImage> #include <QPainter> #include <QApplication> #include <QGraphicsView> #include <QGLFramebufferObject> #ifdef HAVE_MEEGOGRAPHICSSYSTEM #include <QtMeeGoGraphicsSystemHelper> #endif MSnapshotItem::MSnapshotItem(const QRectF &sceneTargetRect, QGraphicsItem *parent) : QGraphicsObject(parent), m_boundingRect(sceneTargetRect), pixmap(), framebufferObject(0) { } MSnapshotItem::~MSnapshotItem() { delete framebufferObject; framebufferObject = 0; } QRectF MSnapshotItem::boundingRect() const { return m_boundingRect; } void MSnapshotItem::updateSnapshot() { pixmap = QPixmap(); delete framebufferObject; framebufferObject = 0; if (scene() && scene()->views().count() == 0) return; QGraphicsView *graphicsView = scene()->views().at(0); Q_ASSERT(graphicsView); bool grabContent = true; if (MGraphicsSystemHelper::isRunningMeeGoGraphicsSystem() && QGLContext::currentContext()) { #ifdef HAVE_MEEGOGRAPHICSSYSTEM graphicsView->installEventFilter(this); #endif const QRect rect = m_boundingRect.toRect(); framebufferObject = new QGLFramebufferObject(rect.size(), QGLFramebufferObject::CombinedDepthStencil); if (framebufferObject->isValid()) { QPainter painter(framebufferObject); graphicsView->render(&painter, QRectF(), rect); grabContent = false; } } if (grabContent) { pixmap = QPixmap::grabWidget(graphicsView); } } void MSnapshotItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(option); Q_UNUSED(widget); if (framebufferObject && framebufferObject->isValid()) { framebufferObject->drawTexture(m_boundingRect, framebufferObject->texture()); } else if (!pixmap.isNull()) { painter->drawPixmap(0,0, pixmap); } } #ifdef HAVE_MEEGOGRAPHICSSYSTEM bool MSnapshotItem::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QMeeGoSwitchEvent::eventNumber()) { QMeeGoSwitchEvent* switchEvent = static_cast<QMeeGoSwitchEvent*>(event); if (switchEvent->state() == QMeeGoSwitchEvent::WillSwitch) { delete framebufferObject; framebufferObject = 0; } } return QGraphicsObject::eventFilter(obj, event); } #endif <|endoftext|>
<commit_before>/* * RGraphicsUtils.cpp * * Copyright (C) 2009-12 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "RGraphicsUtils.hpp" #include <boost/format.hpp> #include <core/Log.hpp> #include <core/Error.hpp> #include <r/RExec.hpp> #include <Rinternals.h> #define R_USE_PROTOTYPES 1 #include <R_ext/GraphicsEngine.h> #include <R_ext/GraphicsDevice.h> #ifdef __APPLE__ #include <R_ext/QuartzDevice.h> #endif #include <r/RErrorCategory.hpp> using namespace core; namespace r { namespace session { namespace graphics { namespace { int s_compatibleEngineVersion = 8; #ifdef __APPLE__ class QuartzStatus : boost::noncopyable { public: QuartzStatus() : checked_(false), installed_(false) {} bool isInstalled() { if (!checked_) { checked_ = true; QuartzFunctions_t* pQuartzFunctions = NULL; Error error = r::exec::executeSafely<QuartzFunctions_t*>( &getQuartzFunctions, &pQuartzFunctions); if (error) LOG_ERROR(error); installed_ = pQuartzFunctions != NULL; } return installed_; } private: bool checked_; bool installed_; }; bool hasRequiredGraphicsDevices(std::string* pMessage) { static QuartzStatus s_quartzStatus; if (!s_quartzStatus.isInstalled()) { if (pMessage != NULL) { *pMessage = "\nWARNING: The version of R you are running against " "does not support the quartz graphics device (which is " "required by RStudio for graphics). The Plots tab will " "be disabled until a version of R that supports quartz " "is installed."; } return false; } else { return true; } } #else bool hasRequiredGraphicsDevices(std::string* pMessage) { return true; } #endif } // anonymous namespace void setCompatibleEngineVersion(int version) { s_compatibleEngineVersion = version; } bool validateRequirements(std::string* pMessage) { // get engineVersion int engineVersion = R_GE_getVersion(); // version too old if (engineVersion < 5) { if (pMessage != NULL) { boost::format fmt( "R graphics engine version %1% is not supported by RStudio. " "The Plots tab will be disabled until a newer version of " "R is installed."); *pMessage = boost::str(fmt % engineVersion); } return false; } // version too new else if (engineVersion > s_compatibleEngineVersion) { if (pMessage != NULL) { boost::format fmt( "R graphics engine version %1% is not supported by this " "version of RStudio. The Plots tab will be disabled until " "a newer version of RStudio is installed."); *pMessage = boost::str(fmt % engineVersion); } return false; } // check for required devices else { return hasRequiredGraphicsDevices(pMessage); } } struct RestorePreviousGraphicsDeviceScope::Impl { Impl() : pPreviousDevice(NULL) {} pGEDevDesc pPreviousDevice; }; RestorePreviousGraphicsDeviceScope::RestorePreviousGraphicsDeviceScope() : pImpl_(new Impl()) { // save ptr to previously selected device (if there is one) pImpl_->pPreviousDevice = Rf_NoDevices() ? NULL : GEcurrentDevice(); } RestorePreviousGraphicsDeviceScope::~RestorePreviousGraphicsDeviceScope() { try { // reslect the previously selected device if we had one if (pImpl_->pPreviousDevice != NULL) Rf_selectDevice(Rf_ndevNumber(pImpl_->pPreviousDevice->dev)); } catch(...) { } } void reportError(const core::Error& error) { std::string endUserMessage = r::endUserErrorMessage(error); std::string errmsg = ("Graphics error: " + endUserMessage + "\n"); REprintf(errmsg.c_str()); } void logAndReportError(const Error& error, const ErrorLocation& location) { // log core::log::logError(error, location); // report to user reportError(error); } } // namespace graphics } // namespace session } // namesapce r <commit_msg>improved detection of quartz on OSX<commit_after>/* * RGraphicsUtils.cpp * * Copyright (C) 2009-12 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "RGraphicsUtils.hpp" #include <boost/format.hpp> #include <core/Log.hpp> #include <core/Error.hpp> #include <r/RExec.hpp> #include <Rinternals.h> #define R_USE_PROTOTYPES 1 #include <R_ext/GraphicsEngine.h> #include <R_ext/GraphicsDevice.h> #include <r/RErrorCategory.hpp> using namespace core; namespace r { namespace session { namespace graphics { namespace { int s_compatibleEngineVersion = 8; #ifdef __APPLE__ class QuartzStatus : boost::noncopyable { public: QuartzStatus() : checked_(false), installed_(false) {} bool isInstalled() { if (!checked_) { checked_ = true; Error error = r::exec::RFunction("capabilities", "aqua").call(&installed_); if (error) LOG_ERROR(error); } return installed_; } private: bool checked_; bool installed_; }; bool hasRequiredGraphicsDevices(std::string* pMessage) { static QuartzStatus s_quartzStatus; if (!s_quartzStatus.isInstalled()) { if (pMessage != NULL) { *pMessage = "\nWARNING: The version of R you are running against " "does not support the quartz graphics device (which is " "required by RStudio for graphics). The Plots tab will " "be disabled until a version of R that supports quartz " "is installed."; } return false; } else { return true; } } #else bool hasRequiredGraphicsDevices(std::string* pMessage) { return true; } #endif } // anonymous namespace void setCompatibleEngineVersion(int version) { s_compatibleEngineVersion = version; } bool validateRequirements(std::string* pMessage) { // get engineVersion int engineVersion = R_GE_getVersion(); // version too old if (engineVersion < 5) { if (pMessage != NULL) { boost::format fmt( "R graphics engine version %1% is not supported by RStudio. " "The Plots tab will be disabled until a newer version of " "R is installed."); *pMessage = boost::str(fmt % engineVersion); } return false; } // version too new else if (engineVersion > s_compatibleEngineVersion) { if (pMessage != NULL) { boost::format fmt( "R graphics engine version %1% is not supported by this " "version of RStudio. The Plots tab will be disabled until " "a newer version of RStudio is installed."); *pMessage = boost::str(fmt % engineVersion); } return false; } // check for required devices else { return hasRequiredGraphicsDevices(pMessage); } } struct RestorePreviousGraphicsDeviceScope::Impl { Impl() : pPreviousDevice(NULL) {} pGEDevDesc pPreviousDevice; }; RestorePreviousGraphicsDeviceScope::RestorePreviousGraphicsDeviceScope() : pImpl_(new Impl()) { // save ptr to previously selected device (if there is one) pImpl_->pPreviousDevice = Rf_NoDevices() ? NULL : GEcurrentDevice(); } RestorePreviousGraphicsDeviceScope::~RestorePreviousGraphicsDeviceScope() { try { // reslect the previously selected device if we had one if (pImpl_->pPreviousDevice != NULL) Rf_selectDevice(Rf_ndevNumber(pImpl_->pPreviousDevice->dev)); } catch(...) { } } void reportError(const core::Error& error) { std::string endUserMessage = r::endUserErrorMessage(error); std::string errmsg = ("Graphics error: " + endUserMessage + "\n"); REprintf(errmsg.c_str()); } void logAndReportError(const Error& error, const ErrorLocation& location) { // log core::log::logError(error, location); // report to user reportError(error); } } // namespace graphics } // namespace session } // namesapce r <|endoftext|>
<commit_before>// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban, Justin Madsen // ============================================================================= // // Main driver function for the HMMWV 9-body model. // // The vehicle reference frame has Z up, X towards the front of the vehicle, and // Y pointing to the left. // // ============================================================================= #include "chrono/core/ChFileutils.h" #include "chrono/core/ChStream.h" #include "chrono/core/ChRealtimeStep.h" #include "chrono/physics/ChSystem.h" #include "chrono/utils/ChUtilsInputOutput.h" #include "chrono_vehicle/ChConfigVehicle.h" #include "chrono_vehicle/ChVehicleModelData.h" #include "chrono_vehicle/terrain/RigidTerrain.h" #include "chrono_vehicle/driver/ChIrrGuiDriver.h" #include "chrono_vehicle/wheeled_vehicle/utils/ChwheeledVehicleIrrApp.h" #include "hmmwv/HMMWV.h" using namespace chrono; using namespace chrono::vehicle; using namespace hmmwv; // ============================================================================= // Initial vehicle location and orientation ChVector<> initLoc(0, 0, 1.0); ChQuaternion<> initRot(1, 0, 0, 0); // ChQuaternion<> initRot(0.866025, 0, 0, 0.5); // ChQuaternion<> initRot(0.7071068, 0, 0, 0.7071068); // ChQuaternion<> initRot(0.25882, 0, 0, 0.965926); // ChQuaternion<> initRot(0, 0, 0, 1); // Type of powertrain model (SHAFTS, SIMPLE) PowertrainModelType powertrain_model = SIMPLE; // Type of tire model (RIGID, PACEJKA, LUGRE, or FIALA) TireModelType tire_model = RIGID; // Rigid terrain dimensions double terrainHeight = 0; double terrainLength = 200.0; // size in X direction double terrainWidth = 100.0; // size in Y direction // Point on chassis tracked by the camera ChVector<> trackPoint(0.0, 0.0, .75); // Simulation step sizes double step_size = 0.001; double tire_step_size = step_size; // Time interval between two render frames int FPS = 50; double render_step_size = 1.0 / FPS; // FPS = 50 // POV-Ray output bool povray_output = false; const std::string out_dir = "../HMMWV9"; const std::string pov_dir = out_dir + "/POVRAY"; // ============================================================================= int main(int argc, char* argv[]) { // -------------- // Create systems // -------------- // Create the HMMWV vehicle, set parameters, and initialize HMMWV_Reduced my_hmmwv; my_hmmwv.SetChassisFixed(false); my_hmmwv.SetChassisVis(PRIMITIVES); my_hmmwv.SetWheelVis(PRIMITIVES); my_hmmwv.SetInitPosition(ChCoordsys<>(initLoc, initRot)); my_hmmwv.SetPowertrainType(powertrain_model); my_hmmwv.SetDriveType(RWD); my_hmmwv.SetTireType(tire_model); my_hmmwv.SetTireStepSize(tire_step_size); my_hmmwv.Initialize(); // Create the terrain RigidTerrain terrain(my_hmmwv.GetSystem()); terrain.SetContactMaterial(0.9f, 0.01f, 2e7f, 0.3f); terrain.SetColor(ChColor(0.8f, 0.8f, 0.5f)); terrain.SetTexture(vehicle::GetDataFile("terrain/textures/tile4.jpg"), 200, 200); terrain.Initialize(terrainHeight, terrainLength, terrainWidth); // Create the vehicle Irrlicht interface ChWheeledVehicleIrrApp app(&my_hmmwv.GetVehicle(), &my_hmmwv.GetPowertrain(), L"HMMWV Demo"); app.SetSkyBox(); app.AddTypicalLights(irr::core::vector3df(30.f, -30.f, 100.f), irr::core::vector3df(30.f, 50.f, 100.f), 250, 130); app.SetChaseCamera(trackPoint, 6.0, 0.5); app.SetTimestep(step_size); app.AssetBindAll(); app.AssetUpdateAll(); // Create the interactive driver system ChIrrGuiDriver driver(app); // Set the time response for steering and throttle keyboard inputs. double steering_time = 1.0; // time to go from 0 to +1 (or from 0 to -1) double throttle_time = 1.0; // time to go from 0 to +1 double braking_time = 0.3; // time to go from 0 to +1 driver.SetSteeringDelta(render_step_size / steering_time); driver.SetThrottleDelta(render_step_size / throttle_time); driver.SetBrakingDelta(render_step_size / braking_time); // ----------------- // Initialize output // ----------------- if (povray_output) { // Create output directories (if not already present) if (ChFileutils::MakeDirectory(out_dir.c_str()) < 0) { std::cout << "Error creating directory " << out_dir << std::endl; return 1; } if (ChFileutils::MakeDirectory(pov_dir.c_str()) < 0) { std::cout << "Error creating directory " << pov_dir << std::endl; return 1; } // Export vehicle mesh to POV-Ray format my_hmmwv.ExportMeshPovray(out_dir); } // --------------- // Simulation loop // --------------- // Number of simulation steps between two 3D view render frames int render_steps = (int)std::ceil(render_step_size / step_size); // Initialize simulation frame counter and simulation time ChRealtimeStepTimer realtime_timer; int step_number = 0; int render_frame = 0; double time = 0; while (app.GetDevice()->run()) { time = my_hmmwv.GetSystem()->GetChTime(); // Render scene and output POV-Ray data if (step_number % render_steps == 0) { app.BeginScene(true, true, irr::video::SColor(255, 140, 161, 192)); app.DrawAll(); app.EndScene(); if (povray_output) { char filename[100]; sprintf(filename, "%s/data_%03d.dat", pov_dir.c_str(), render_frame + 1); utils::WriteShapesPovray(my_hmmwv.GetSystem(), filename); } render_frame++; } // Collect output data from modules (for inter-module communication) double throttle_input = driver.GetThrottle(); double steering_input = driver.GetSteering(); double braking_input = driver.GetBraking(); // Update modules (process inputs from other modules) driver.Update(time); terrain.Update(time); my_hmmwv.Update(time, steering_input, braking_input, throttle_input, terrain); app.Update(driver.GetInputModeAsString(), steering_input, throttle_input, braking_input); // Advance simulation for one timestep for all modules double step = realtime_timer.SuggestSimulationStep(step_size); driver.Advance(step); terrain.Advance(step); my_hmmwv.Advance(step); app.Advance(step); // Increment frame number step_number++; } return 0; } <commit_msg>Fix case in name of included header<commit_after>// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban, Justin Madsen // ============================================================================= // // Main driver function for the HMMWV 9-body model. // // The vehicle reference frame has Z up, X towards the front of the vehicle, and // Y pointing to the left. // // ============================================================================= #include "chrono/core/ChFileutils.h" #include "chrono/core/ChStream.h" #include "chrono/core/ChRealtimeStep.h" #include "chrono/physics/ChSystem.h" #include "chrono/utils/ChUtilsInputOutput.h" #include "chrono_vehicle/ChConfigVehicle.h" #include "chrono_vehicle/ChVehicleModelData.h" #include "chrono_vehicle/terrain/RigidTerrain.h" #include "chrono_vehicle/driver/ChIrrGuiDriver.h" #include "chrono_vehicle/wheeled_vehicle/utils/ChWheeledVehicleIrrApp.h" #include "hmmwv/HMMWV.h" using namespace chrono; using namespace chrono::vehicle; using namespace hmmwv; // ============================================================================= // Initial vehicle location and orientation ChVector<> initLoc(0, 0, 1.0); ChQuaternion<> initRot(1, 0, 0, 0); // ChQuaternion<> initRot(0.866025, 0, 0, 0.5); // ChQuaternion<> initRot(0.7071068, 0, 0, 0.7071068); // ChQuaternion<> initRot(0.25882, 0, 0, 0.965926); // ChQuaternion<> initRot(0, 0, 0, 1); // Type of powertrain model (SHAFTS, SIMPLE) PowertrainModelType powertrain_model = SIMPLE; // Type of tire model (RIGID, PACEJKA, LUGRE, or FIALA) TireModelType tire_model = RIGID; // Rigid terrain dimensions double terrainHeight = 0; double terrainLength = 200.0; // size in X direction double terrainWidth = 100.0; // size in Y direction // Point on chassis tracked by the camera ChVector<> trackPoint(0.0, 0.0, .75); // Simulation step sizes double step_size = 0.001; double tire_step_size = step_size; // Time interval between two render frames int FPS = 50; double render_step_size = 1.0 / FPS; // FPS = 50 // POV-Ray output bool povray_output = false; const std::string out_dir = "../HMMWV9"; const std::string pov_dir = out_dir + "/POVRAY"; // ============================================================================= int main(int argc, char* argv[]) { // -------------- // Create systems // -------------- // Create the HMMWV vehicle, set parameters, and initialize HMMWV_Reduced my_hmmwv; my_hmmwv.SetChassisFixed(false); my_hmmwv.SetChassisVis(PRIMITIVES); my_hmmwv.SetWheelVis(PRIMITIVES); my_hmmwv.SetInitPosition(ChCoordsys<>(initLoc, initRot)); my_hmmwv.SetPowertrainType(powertrain_model); my_hmmwv.SetDriveType(RWD); my_hmmwv.SetTireType(tire_model); my_hmmwv.SetTireStepSize(tire_step_size); my_hmmwv.Initialize(); // Create the terrain RigidTerrain terrain(my_hmmwv.GetSystem()); terrain.SetContactMaterial(0.9f, 0.01f, 2e7f, 0.3f); terrain.SetColor(ChColor(0.8f, 0.8f, 0.5f)); terrain.SetTexture(vehicle::GetDataFile("terrain/textures/tile4.jpg"), 200, 200); terrain.Initialize(terrainHeight, terrainLength, terrainWidth); // Create the vehicle Irrlicht interface ChWheeledVehicleIrrApp app(&my_hmmwv.GetVehicle(), &my_hmmwv.GetPowertrain(), L"HMMWV Demo"); app.SetSkyBox(); app.AddTypicalLights(irr::core::vector3df(30.f, -30.f, 100.f), irr::core::vector3df(30.f, 50.f, 100.f), 250, 130); app.SetChaseCamera(trackPoint, 6.0, 0.5); app.SetTimestep(step_size); app.AssetBindAll(); app.AssetUpdateAll(); // Create the interactive driver system ChIrrGuiDriver driver(app); // Set the time response for steering and throttle keyboard inputs. double steering_time = 1.0; // time to go from 0 to +1 (or from 0 to -1) double throttle_time = 1.0; // time to go from 0 to +1 double braking_time = 0.3; // time to go from 0 to +1 driver.SetSteeringDelta(render_step_size / steering_time); driver.SetThrottleDelta(render_step_size / throttle_time); driver.SetBrakingDelta(render_step_size / braking_time); // ----------------- // Initialize output // ----------------- if (povray_output) { // Create output directories (if not already present) if (ChFileutils::MakeDirectory(out_dir.c_str()) < 0) { std::cout << "Error creating directory " << out_dir << std::endl; return 1; } if (ChFileutils::MakeDirectory(pov_dir.c_str()) < 0) { std::cout << "Error creating directory " << pov_dir << std::endl; return 1; } // Export vehicle mesh to POV-Ray format my_hmmwv.ExportMeshPovray(out_dir); } // --------------- // Simulation loop // --------------- // Number of simulation steps between two 3D view render frames int render_steps = (int)std::ceil(render_step_size / step_size); // Initialize simulation frame counter and simulation time ChRealtimeStepTimer realtime_timer; int step_number = 0; int render_frame = 0; double time = 0; while (app.GetDevice()->run()) { time = my_hmmwv.GetSystem()->GetChTime(); // Render scene and output POV-Ray data if (step_number % render_steps == 0) { app.BeginScene(true, true, irr::video::SColor(255, 140, 161, 192)); app.DrawAll(); app.EndScene(); if (povray_output) { char filename[100]; sprintf(filename, "%s/data_%03d.dat", pov_dir.c_str(), render_frame + 1); utils::WriteShapesPovray(my_hmmwv.GetSystem(), filename); } render_frame++; } // Collect output data from modules (for inter-module communication) double throttle_input = driver.GetThrottle(); double steering_input = driver.GetSteering(); double braking_input = driver.GetBraking(); // Update modules (process inputs from other modules) driver.Update(time); terrain.Update(time); my_hmmwv.Update(time, steering_input, braking_input, throttle_input, terrain); app.Update(driver.GetInputModeAsString(), steering_input, throttle_input, braking_input); // Advance simulation for one timestep for all modules double step = realtime_timer.SuggestSimulationStep(step_size); driver.Advance(step); terrain.Advance(step); my_hmmwv.Advance(step); app.Advance(step); // Increment frame number step_number++; } return 0; } <|endoftext|>
<commit_before>/* * Randpool * (C) 1999-2009 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/randpool.h> #include <botan/loadstor.h> #include <botan/xor_buf.h> #include <botan/timer.h> #include <botan/stl_util.h> #include <algorithm> namespace Botan { namespace { /** * PRF based on a MAC */ enum RANDPOOL_PRF_TAG { CIPHER_KEY = 0, MAC_KEY = 1, GEN_OUTPUT = 2 }; } /** * Generate a buffer of random bytes */ void Randpool::randomize(byte out[], u32bit length) { if(!is_seeded()) throw PRNG_Unseeded(name()); update_buffer(); while(length) { const u32bit copied = std::min(length, buffer.size()); copy_mem(out, buffer.begin(), copied); out += copied; length -= copied; update_buffer(); } } /** * Refill the output buffer */ void Randpool::update_buffer() { const u64bit timestamp = system_time(); for(u32bit i = 0; i != counter.size(); ++i) if(++counter[i]) break; store_be(timestamp, counter + 4); mac->update(static_cast<byte>(GEN_OUTPUT)); mac->update(counter, counter.size()); SecureVector<byte> mac_val = mac->final(); for(u32bit i = 0; i != mac_val.size(); ++i) buffer[i % buffer.size()] ^= mac_val[i]; cipher->encrypt(buffer); if(counter[0] % ITERATIONS_BEFORE_RESEED == 0) mix_pool(); } /** * Mix the entropy pool */ void Randpool::mix_pool() { const u32bit BLOCK_SIZE = cipher->BLOCK_SIZE; mac->update(static_cast<byte>(MAC_KEY)); mac->update(pool, pool.size()); mac->set_key(mac->final()); mac->update(static_cast<byte>(CIPHER_KEY)); mac->update(pool, pool.size()); cipher->set_key(mac->final()); xor_buf(pool, buffer, BLOCK_SIZE); cipher->encrypt(pool); for(u32bit i = 1; i != POOL_BLOCKS; ++i) { const byte* previous_block = pool + BLOCK_SIZE*(i-1); byte* this_block = pool + BLOCK_SIZE*i; xor_buf(this_block, previous_block, BLOCK_SIZE); cipher->encrypt(this_block); } update_buffer(); } /** * Reseed the internal state */ void Randpool::reseed(u32bit poll_bits) { Entropy_Accumulator_BufferedComputation accum(*mac, poll_bits); if(!entropy_sources.empty()) { u32bit poll_attempt = 0; while(!accum.polling_goal_achieved() && poll_attempt < poll_bits) { entropy_sources[poll_attempt % entropy_sources.size()]->poll(accum); ++poll_attempt; } } SecureVector<byte> mac_val = mac->final(); xor_buf(pool, mac_val, mac_val.size()); mix_pool(); if(accum.bits_collected() >= poll_bits) seeded = true; } /** * Add user-supplied entropy */ void Randpool::add_entropy(const byte input[], u32bit length) { SecureVector<byte> mac_val = mac->process(input, length); xor_buf(pool, mac_val, mac_val.size()); mix_pool(); if(length) seeded = true; } /** * Add another entropy source to the list */ void Randpool::add_entropy_source(EntropySource* src) { entropy_sources.push_back(src); } /** * Clear memory of sensitive data */ void Randpool::clear() throw() { cipher->clear(); mac->clear(); pool.clear(); buffer.clear(); counter.clear(); seeded = false; } /** * Return the name of this type */ std::string Randpool::name() const { return "Randpool(" + cipher->name() + "," + mac->name() + ")"; } /** * Randpool Constructor */ Randpool::Randpool(BlockCipher* cipher_in, MessageAuthenticationCode* mac_in, u32bit pool_blocks, u32bit iter_before_reseed) : ITERATIONS_BEFORE_RESEED(iter_before_reseed), POOL_BLOCKS(pool_blocks), cipher(cipher_in), mac(mac_in) { const u32bit BLOCK_SIZE = cipher->BLOCK_SIZE; const u32bit OUTPUT_LENGTH = mac->OUTPUT_LENGTH; if(OUTPUT_LENGTH < BLOCK_SIZE || !cipher->valid_keylength(OUTPUT_LENGTH) || !mac->valid_keylength(OUTPUT_LENGTH)) { delete cipher; delete mac; throw Internal_Error("Randpool: Invalid algorithm combination " + cipher->name() + "/" + mac->name()); } buffer.create(BLOCK_SIZE); pool.create(POOL_BLOCKS * BLOCK_SIZE); counter.create(12); seeded = false; } /** * Randpool Destructor */ Randpool::~Randpool() { delete cipher; delete mac; std::for_each(entropy_sources.begin(), entropy_sources.end(), del_fun<EntropySource>()); } } <commit_msg>Change call to system_time to use std::chrono<commit_after>/* * Randpool * (C) 1999-2009 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/randpool.h> #include <botan/loadstor.h> #include <botan/xor_buf.h> #include <botan/stl_util.h> #include <algorithm> #include <chrono> namespace Botan { namespace { /** * PRF based on a MAC */ enum RANDPOOL_PRF_TAG { CIPHER_KEY = 0, MAC_KEY = 1, GEN_OUTPUT = 2 }; } /** * Generate a buffer of random bytes */ void Randpool::randomize(byte out[], u32bit length) { if(!is_seeded()) throw PRNG_Unseeded(name()); update_buffer(); while(length) { const u32bit copied = std::min(length, buffer.size()); copy_mem(out, buffer.begin(), copied); out += copied; length -= copied; update_buffer(); } } /** * Refill the output buffer */ void Randpool::update_buffer() { const u64bit timestamp = std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch()).count(); for(u32bit i = 0; i != counter.size(); ++i) if(++counter[i]) break; store_be(timestamp, counter + 4); mac->update(static_cast<byte>(GEN_OUTPUT)); mac->update(counter, counter.size()); SecureVector<byte> mac_val = mac->final(); for(u32bit i = 0; i != mac_val.size(); ++i) buffer[i % buffer.size()] ^= mac_val[i]; cipher->encrypt(buffer); if(counter[0] % ITERATIONS_BEFORE_RESEED == 0) mix_pool(); } /** * Mix the entropy pool */ void Randpool::mix_pool() { const u32bit BLOCK_SIZE = cipher->BLOCK_SIZE; mac->update(static_cast<byte>(MAC_KEY)); mac->update(pool, pool.size()); mac->set_key(mac->final()); mac->update(static_cast<byte>(CIPHER_KEY)); mac->update(pool, pool.size()); cipher->set_key(mac->final()); xor_buf(pool, buffer, BLOCK_SIZE); cipher->encrypt(pool); for(u32bit i = 1; i != POOL_BLOCKS; ++i) { const byte* previous_block = pool + BLOCK_SIZE*(i-1); byte* this_block = pool + BLOCK_SIZE*i; xor_buf(this_block, previous_block, BLOCK_SIZE); cipher->encrypt(this_block); } update_buffer(); } /** * Reseed the internal state */ void Randpool::reseed(u32bit poll_bits) { Entropy_Accumulator_BufferedComputation accum(*mac, poll_bits); if(!entropy_sources.empty()) { u32bit poll_attempt = 0; while(!accum.polling_goal_achieved() && poll_attempt < poll_bits) { entropy_sources[poll_attempt % entropy_sources.size()]->poll(accum); ++poll_attempt; } } SecureVector<byte> mac_val = mac->final(); xor_buf(pool, mac_val, mac_val.size()); mix_pool(); if(accum.bits_collected() >= poll_bits) seeded = true; } /** * Add user-supplied entropy */ void Randpool::add_entropy(const byte input[], u32bit length) { SecureVector<byte> mac_val = mac->process(input, length); xor_buf(pool, mac_val, mac_val.size()); mix_pool(); if(length) seeded = true; } /** * Add another entropy source to the list */ void Randpool::add_entropy_source(EntropySource* src) { entropy_sources.push_back(src); } /** * Clear memory of sensitive data */ void Randpool::clear() throw() { cipher->clear(); mac->clear(); pool.clear(); buffer.clear(); counter.clear(); seeded = false; } /** * Return the name of this type */ std::string Randpool::name() const { return "Randpool(" + cipher->name() + "," + mac->name() + ")"; } /** * Randpool Constructor */ Randpool::Randpool(BlockCipher* cipher_in, MessageAuthenticationCode* mac_in, u32bit pool_blocks, u32bit iter_before_reseed) : ITERATIONS_BEFORE_RESEED(iter_before_reseed), POOL_BLOCKS(pool_blocks), cipher(cipher_in), mac(mac_in) { const u32bit BLOCK_SIZE = cipher->BLOCK_SIZE; const u32bit OUTPUT_LENGTH = mac->OUTPUT_LENGTH; if(OUTPUT_LENGTH < BLOCK_SIZE || !cipher->valid_keylength(OUTPUT_LENGTH) || !mac->valid_keylength(OUTPUT_LENGTH)) { delete cipher; delete mac; throw Internal_Error("Randpool: Invalid algorithm combination " + cipher->name() + "/" + mac->name()); } buffer.create(BLOCK_SIZE); pool.create(POOL_BLOCKS * BLOCK_SIZE); counter.create(12); seeded = false; } /** * Randpool Destructor */ Randpool::~Randpool() { delete cipher; delete mac; std::for_each(entropy_sources.begin(), entropy_sources.end(), del_fun<EntropySource>()); } } <|endoftext|>
<commit_before>/****************************************************************************** ** ** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com> ** ** This file is part of chemkit. For more information see ** <http://www.chemkit.org>. ** ** chemkit is free software: you can redistribute it and/or modify ** it under the terms of the GNU Lesser General Public License as published by ** the Free Software Foundation, either version 3 of the License, or ** (at your option) any later version. ** ** chemkit 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 chemkit. If not, see <http://www.gnu.org/licenses/>. ** ******************************************************************************/ #include "graphicsmolecularsurfaceitem.h" #include <chemkit/molecule.h> #include <chemkit/alphashape.h> #include <chemkit/quaternion.h> #include "graphicsscene.h" #include "graphicssphere.h" #include "graphicspainter.h" #include "graphicsmaterial.h" #include "graphicsmoleculeitem.h" #include "graphicsvertexbuffer.h" namespace chemkit { namespace { // === ClippedSphere ======================================================= // class ClippedSphere { public: ClippedSphere(float radius); void addClipPlane(const Point3f &point, const Vector3f &normal); GraphicsVertexBuffer* tesselate() const; private: float m_radius; QList<QPair<Point3f, Vector3f> > m_clipPlanes; }; ClippedSphere::ClippedSphere(float radius) : m_radius(radius) { } void ClippedSphere::addClipPlane(const Point3f &point, const Vector3f &normal) { m_clipPlanes.append(qMakePair(point, normal)); } GraphicsVertexBuffer* ClippedSphere::tesselate() const { GraphicsVertexBuffer *buffer = GraphicsSphere(m_radius).tesselate(); QVector<Point3f> verticies = buffer->verticies(); QVector<Vector3f> normals = buffer->normals(); QVector<unsigned short> indicies = buffer->indicies(); QVector<unsigned short> clippedIndicies; for(int triangleIndex = 0; triangleIndex < indicies.size() / 3; triangleIndex++){ unsigned short ia = indicies[triangleIndex*3+0]; unsigned short ib = indicies[triangleIndex*3+1]; unsigned short ic = indicies[triangleIndex*3+2]; const Point3f &a = verticies[ia]; const Point3f &b = verticies[ib]; const Point3f &c = verticies[ic]; // check triangle against each clipping plane bool clipTriangle = false; for(int clipPlaneIndex = 0; clipPlaneIndex < m_clipPlanes.size(); clipPlaneIndex++){ const Point3f &planePoint = m_clipPlanes[clipPlaneIndex].first; const Vector3f &planeNormal = m_clipPlanes[clipPlaneIndex].second; QList<unsigned short> invalidVerticies; if((planePoint - a).dot(planeNormal) < 0){ invalidVerticies.append(ia); } if((planePoint - b).dot(planeNormal) < 0){ invalidVerticies.append(ib); } if((planePoint - c).dot(planeNormal) < 0){ invalidVerticies.append(ic); } // keep entire triangle if(invalidVerticies.isEmpty()){ continue; } // clip entire triangle else if(invalidVerticies.size() == 3){ clipTriangle = true; break; } // clip part of the triangle else{ foreach(unsigned short vertexIndex, invalidVerticies){ Point3f invalidPoint = verticies[vertexIndex]; float d = -(planePoint - invalidPoint).dot(planeNormal); float theta = acos(planePoint.norm() / m_radius) - acos((planePoint.norm() + d) / m_radius); Vector3f up = invalidPoint.cross(planeNormal).normalized(); // set new vertex position verticies[vertexIndex] = Quaternionf::rotateRadians(invalidPoint, up, -theta); // update normal normals[vertexIndex] = verticies[vertexIndex].normalized(); } } } if(!clipTriangle){ clippedIndicies.append(ia); clippedIndicies.append(ib); clippedIndicies.append(ic); } } buffer->setVerticies(verticies); buffer->setNormals(normals); buffer->setIndicies(clippedIndicies); return buffer; } // === ContactPatchItem ==================================================== // class ContactPatchItem : public GraphicsItem { public: ContactPatchItem(GraphicsMolecularSurfaceItem *parent, const Point3f &center, float radius); ~ContactPatchItem(); Point3f center() const; float radius() const; void setColor(const QColor &color); void addIntersection(const ContactPatchItem *item); void paint(GraphicsPainter *painter); private: GraphicsMolecularSurfaceItem *m_parent; Point3f m_center; float m_radius; QColor m_color; GraphicsVertexBuffer *m_buffer; QList<const ContactPatchItem *> m_intersections; }; ContactPatchItem::ContactPatchItem(GraphicsMolecularSurfaceItem *parent, const Point3f &center, float radius) : GraphicsItem(), m_parent(parent), m_center(center), m_radius(radius) { m_buffer = 0; m_color = Qt::red; translate(center); } ContactPatchItem::~ContactPatchItem() { delete m_buffer; } Point3f ContactPatchItem::center() const { return m_center; } float ContactPatchItem::radius() const { return m_radius; } void ContactPatchItem::setColor(const QColor &color) { m_color = color; } void ContactPatchItem::addIntersection(const ContactPatchItem *item) { m_intersections.append(item); } void ContactPatchItem::paint(GraphicsPainter *painter) { if(!m_buffer){ ClippedSphere clippedSphere(m_radius); // calculate and add clip plane for each intersection foreach(const ContactPatchItem *item, m_intersections){ const Point3f &a = m_center; float ra = m_radius; const Point3f &b = item->center(); float rb = item->radius(); const float d = a.distance(b); const float x = (d*d - rb*rb + ra*ra) / (2 * d); Vector3f planeNormal = (b - a).normalized(); const Point3f planeCenter = planeNormal * x; clippedSphere.addClipPlane(planeCenter, planeNormal); } m_buffer = clippedSphere.tesselate(); } QColor color = m_color; color.setAlphaF(opacity()); painter->setColor(color); painter->setMaterial(m_parent->material()); painter->draw(m_buffer); } } // end anonymous namespace // === GraphicsMolecularSurfaceItemPrivate ================================= // class GraphicsMolecularSurfaceItemPrivate { public: MolecularSurface *surface; QColor color; GraphicsMolecularSurfaceItem::ColorMode colorMode; QList<ContactPatchItem *> contactPatches; }; // === GraphicsMolecularSurfaceItem ======================================== // /// \class GraphicsMolecularSurfaceItem graphicsmolecularsurfaceitem.h chemkit/graphicsmolecularsurfaceitem.h /// \ingroup chemkit-graphics /// \brief The GraphicsMolecularSurfaceItem displays a molecular /// surface. /// /// The image below shows a molecular surface item on top of a /// guanine molecule: /// \image html molecular-surface-item.png /// /// \see MolecularSurface // --- Construction and Destruction ---------------------------------------- // /// Creates a new molecular surface item for \p molecule. GraphicsMolecularSurfaceItem::GraphicsMolecularSurfaceItem(const Molecule *molecule) : GraphicsItem(), d(new GraphicsMolecularSurfaceItemPrivate) { d->surface = new MolecularSurface(molecule, MolecularSurface::SolventExcluded); d->color = Qt::red; d->colorMode = AtomColor; setMolecule(molecule); } /// Creates a new molecular surface item for \p surface. GraphicsMolecularSurfaceItem::GraphicsMolecularSurfaceItem(const MolecularSurface *surface) : GraphicsItem(), d(new GraphicsMolecularSurfaceItemPrivate) { d->surface = new MolecularSurface(surface->molecule(), MolecularSurface::SolventExcluded); d->color = Qt::red; d->colorMode = AtomColor; setSurface(surface); } /// Destroys the molecular surface item. GraphicsMolecularSurfaceItem::~GraphicsMolecularSurfaceItem() { delete d->surface; delete d; } // --- Properties ---------------------------------------------------------- // /// Sets the surface to display to \p surface. void GraphicsMolecularSurfaceItem::setSurface(const MolecularSurface *surface) { if(surface){ d->surface->setMolecule(surface->molecule()); d->surface->setSurfaceType(surface->surfaceType()); d->surface->setProbeRadius(surface->probeRadius()); } else{ d->surface->setMolecule(0); } recalculate(); } /// Returns the surface that the item is displaying. const MolecularSurface* GraphicsMolecularSurfaceItem::surface() const { return d->surface; } /// Sets the molecule for the surface to \p molecule. void GraphicsMolecularSurfaceItem::setMolecule(const Molecule *molecule) { d->surface->setMolecule(molecule); recalculate(); } /// Returns the molecule for the surface. const Molecule* GraphicsMolecularSurfaceItem::molecule() const { return d->surface->molecule(); } /// Sets the surface type to \p type. void GraphicsMolecularSurfaceItem::setSurfaceType(MolecularSurface::SurfaceType type) { d->surface->setSurfaceType(type); recalculate(); } /// Returns the surface type. MolecularSurface::SurfaceType GraphicsMolecularSurfaceItem::surfaceType() const { return d->surface->surfaceType(); } /// Sets the probe radius for the surface to \p radius. void GraphicsMolecularSurfaceItem::setProbeRadius(float radius) { d->surface->setProbeRadius(radius); if(surfaceType() == MolecularSurface::SolventAccessible || surfaceType() == MolecularSurface::SolventExcluded){ recalculate(); } } /// Returns the probe radius for the surface. float GraphicsMolecularSurfaceItem::probeRadius() const { return d->surface->probeRadius(); } /// Sets the color for the surface to \p color. void GraphicsMolecularSurfaceItem::setColor(const QColor &color) { d->color = color; if(d->colorMode == SolidColor){ foreach(ContactPatchItem *item, d->contactPatches){ item->setColor(d->color); } } } /// Returns the color for the surface. QColor GraphicsMolecularSurfaceItem::color() const { return d->color; } /// Sets the color mode for the surface item to \p mode. void GraphicsMolecularSurfaceItem::setColorMode(ColorMode mode) { d->colorMode = mode; if(d->colorMode == SolidColor){ foreach(ContactPatchItem *item, d->contactPatches){ item->setColor(d->color); } } else if(d->colorMode == AtomColor){ for(int i = 0; i < d->contactPatches.size(); i++){ ContactPatchItem *item = d->contactPatches[i]; item->setColor(GraphicsMoleculeItem::atomColor(molecule()->atom(i))); } } } /// Returns the color mode for the surface item. GraphicsMolecularSurfaceItem::ColorMode GraphicsMolecularSurfaceItem::colorMode() const { return d->colorMode; } // --- Internal Methods ---------------------------------------------------- // void GraphicsMolecularSurfaceItem::itemChanged(ItemChange change) { if(change == ItemVisiblityChanged){ foreach(ContactPatchItem *item, d->contactPatches){ item->setVisible(isVisible()); } } else if(change == ItemOpacityChanged){ foreach(ContactPatchItem *item, d->contactPatches){ item->setOpacity(opacity()); } if(isOpaque()){ material()->setSpecularColor(QColor::fromRgbF(0.3, 0.3, 0.3)); } else{ material()->setSpecularColor(Qt::transparent); } } else if(change == ItemSceneChanged){ foreach(ContactPatchItem *item, d->contactPatches){ if(scene()){ scene()->addItem(item); } } } } void GraphicsMolecularSurfaceItem::recalculate() { qDeleteAll(d->contactPatches); d->contactPatches.clear(); const Molecule *molecule = this->molecule(); if(!molecule){ return; } // create contact patches foreach(const Atom *atom, molecule->atoms()){ float radius = atom->vanDerWaalsRadius(); if(surfaceType() == MolecularSurface::SolventAccessible){ radius += probeRadius(); } ContactPatchItem *item = new ContactPatchItem(this, atom->position(), radius); d->contactPatches.append(item); if(d->colorMode == AtomColor){ item->setColor(GraphicsMoleculeItem::atomColor(atom)); } else{ item->setColor(d->color); } item->setOpacity(opacity()); if(scene()){ scene()->addItem(item); } } // add intersections from alpha shape edges const AlphaShape *alphaShape = d->surface->alphaShape(); foreach(const QVector<int> &edge, alphaShape->edges()){ ContactPatchItem *itemA = d->contactPatches[edge[0]]; ContactPatchItem *itemB = d->contactPatches[edge[1]]; itemA->addIntersection(itemB); itemB->addIntersection(itemA); } } } // end chemkit namespace <commit_msg>Add documentation for GraphicsMolecularSurfaceItem::ColorMode<commit_after>/****************************************************************************** ** ** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com> ** ** This file is part of chemkit. For more information see ** <http://www.chemkit.org>. ** ** chemkit is free software: you can redistribute it and/or modify ** it under the terms of the GNU Lesser General Public License as published by ** the Free Software Foundation, either version 3 of the License, or ** (at your option) any later version. ** ** chemkit 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 chemkit. If not, see <http://www.gnu.org/licenses/>. ** ******************************************************************************/ #include "graphicsmolecularsurfaceitem.h" #include <chemkit/molecule.h> #include <chemkit/alphashape.h> #include <chemkit/quaternion.h> #include "graphicsscene.h" #include "graphicssphere.h" #include "graphicspainter.h" #include "graphicsmaterial.h" #include "graphicsmoleculeitem.h" #include "graphicsvertexbuffer.h" namespace chemkit { namespace { // === ClippedSphere ======================================================= // class ClippedSphere { public: ClippedSphere(float radius); void addClipPlane(const Point3f &point, const Vector3f &normal); GraphicsVertexBuffer* tesselate() const; private: float m_radius; QList<QPair<Point3f, Vector3f> > m_clipPlanes; }; ClippedSphere::ClippedSphere(float radius) : m_radius(radius) { } void ClippedSphere::addClipPlane(const Point3f &point, const Vector3f &normal) { m_clipPlanes.append(qMakePair(point, normal)); } GraphicsVertexBuffer* ClippedSphere::tesselate() const { GraphicsVertexBuffer *buffer = GraphicsSphere(m_radius).tesselate(); QVector<Point3f> verticies = buffer->verticies(); QVector<Vector3f> normals = buffer->normals(); QVector<unsigned short> indicies = buffer->indicies(); QVector<unsigned short> clippedIndicies; for(int triangleIndex = 0; triangleIndex < indicies.size() / 3; triangleIndex++){ unsigned short ia = indicies[triangleIndex*3+0]; unsigned short ib = indicies[triangleIndex*3+1]; unsigned short ic = indicies[triangleIndex*3+2]; const Point3f &a = verticies[ia]; const Point3f &b = verticies[ib]; const Point3f &c = verticies[ic]; // check triangle against each clipping plane bool clipTriangle = false; for(int clipPlaneIndex = 0; clipPlaneIndex < m_clipPlanes.size(); clipPlaneIndex++){ const Point3f &planePoint = m_clipPlanes[clipPlaneIndex].first; const Vector3f &planeNormal = m_clipPlanes[clipPlaneIndex].second; QList<unsigned short> invalidVerticies; if((planePoint - a).dot(planeNormal) < 0){ invalidVerticies.append(ia); } if((planePoint - b).dot(planeNormal) < 0){ invalidVerticies.append(ib); } if((planePoint - c).dot(planeNormal) < 0){ invalidVerticies.append(ic); } // keep entire triangle if(invalidVerticies.isEmpty()){ continue; } // clip entire triangle else if(invalidVerticies.size() == 3){ clipTriangle = true; break; } // clip part of the triangle else{ foreach(unsigned short vertexIndex, invalidVerticies){ Point3f invalidPoint = verticies[vertexIndex]; float d = -(planePoint - invalidPoint).dot(planeNormal); float theta = acos(planePoint.norm() / m_radius) - acos((planePoint.norm() + d) / m_radius); Vector3f up = invalidPoint.cross(planeNormal).normalized(); // set new vertex position verticies[vertexIndex] = Quaternionf::rotateRadians(invalidPoint, up, -theta); // update normal normals[vertexIndex] = verticies[vertexIndex].normalized(); } } } if(!clipTriangle){ clippedIndicies.append(ia); clippedIndicies.append(ib); clippedIndicies.append(ic); } } buffer->setVerticies(verticies); buffer->setNormals(normals); buffer->setIndicies(clippedIndicies); return buffer; } // === ContactPatchItem ==================================================== // class ContactPatchItem : public GraphicsItem { public: ContactPatchItem(GraphicsMolecularSurfaceItem *parent, const Point3f &center, float radius); ~ContactPatchItem(); Point3f center() const; float radius() const; void setColor(const QColor &color); void addIntersection(const ContactPatchItem *item); void paint(GraphicsPainter *painter); private: GraphicsMolecularSurfaceItem *m_parent; Point3f m_center; float m_radius; QColor m_color; GraphicsVertexBuffer *m_buffer; QList<const ContactPatchItem *> m_intersections; }; ContactPatchItem::ContactPatchItem(GraphicsMolecularSurfaceItem *parent, const Point3f &center, float radius) : GraphicsItem(), m_parent(parent), m_center(center), m_radius(radius) { m_buffer = 0; m_color = Qt::red; translate(center); } ContactPatchItem::~ContactPatchItem() { delete m_buffer; } Point3f ContactPatchItem::center() const { return m_center; } float ContactPatchItem::radius() const { return m_radius; } void ContactPatchItem::setColor(const QColor &color) { m_color = color; } void ContactPatchItem::addIntersection(const ContactPatchItem *item) { m_intersections.append(item); } void ContactPatchItem::paint(GraphicsPainter *painter) { if(!m_buffer){ ClippedSphere clippedSphere(m_radius); // calculate and add clip plane for each intersection foreach(const ContactPatchItem *item, m_intersections){ const Point3f &a = m_center; float ra = m_radius; const Point3f &b = item->center(); float rb = item->radius(); const float d = a.distance(b); const float x = (d*d - rb*rb + ra*ra) / (2 * d); Vector3f planeNormal = (b - a).normalized(); const Point3f planeCenter = planeNormal * x; clippedSphere.addClipPlane(planeCenter, planeNormal); } m_buffer = clippedSphere.tesselate(); } QColor color = m_color; color.setAlphaF(opacity()); painter->setColor(color); painter->setMaterial(m_parent->material()); painter->draw(m_buffer); } } // end anonymous namespace // === GraphicsMolecularSurfaceItemPrivate ================================= // class GraphicsMolecularSurfaceItemPrivate { public: MolecularSurface *surface; QColor color; GraphicsMolecularSurfaceItem::ColorMode colorMode; QList<ContactPatchItem *> contactPatches; }; // === GraphicsMolecularSurfaceItem ======================================== // /// \class GraphicsMolecularSurfaceItem graphicsmolecularsurfaceitem.h chemkit/graphicsmolecularsurfaceitem.h /// \ingroup chemkit-graphics /// \brief The GraphicsMolecularSurfaceItem displays a molecular /// surface. /// /// The image below shows a molecular surface item on top of a /// guanine molecule: /// \image html molecular-surface-item.png /// /// \see MolecularSurface /// \enum GraphicsMolecularSurfaceItem::ColorMode /// Provides different modes for coloring the surface. /// - \c SolidColor /// - \c AtomColor // --- Construction and Destruction ---------------------------------------- // /// Creates a new molecular surface item for \p molecule. GraphicsMolecularSurfaceItem::GraphicsMolecularSurfaceItem(const Molecule *molecule) : GraphicsItem(), d(new GraphicsMolecularSurfaceItemPrivate) { d->surface = new MolecularSurface(molecule, MolecularSurface::SolventExcluded); d->color = Qt::red; d->colorMode = AtomColor; setMolecule(molecule); } /// Creates a new molecular surface item for \p surface. GraphicsMolecularSurfaceItem::GraphicsMolecularSurfaceItem(const MolecularSurface *surface) : GraphicsItem(), d(new GraphicsMolecularSurfaceItemPrivate) { d->surface = new MolecularSurface(surface->molecule(), MolecularSurface::SolventExcluded); d->color = Qt::red; d->colorMode = AtomColor; setSurface(surface); } /// Destroys the molecular surface item. GraphicsMolecularSurfaceItem::~GraphicsMolecularSurfaceItem() { delete d->surface; delete d; } // --- Properties ---------------------------------------------------------- // /// Sets the surface to display to \p surface. void GraphicsMolecularSurfaceItem::setSurface(const MolecularSurface *surface) { if(surface){ d->surface->setMolecule(surface->molecule()); d->surface->setSurfaceType(surface->surfaceType()); d->surface->setProbeRadius(surface->probeRadius()); } else{ d->surface->setMolecule(0); } recalculate(); } /// Returns the surface that the item is displaying. const MolecularSurface* GraphicsMolecularSurfaceItem::surface() const { return d->surface; } /// Sets the molecule for the surface to \p molecule. void GraphicsMolecularSurfaceItem::setMolecule(const Molecule *molecule) { d->surface->setMolecule(molecule); recalculate(); } /// Returns the molecule for the surface. const Molecule* GraphicsMolecularSurfaceItem::molecule() const { return d->surface->molecule(); } /// Sets the surface type to \p type. void GraphicsMolecularSurfaceItem::setSurfaceType(MolecularSurface::SurfaceType type) { d->surface->setSurfaceType(type); recalculate(); } /// Returns the surface type. MolecularSurface::SurfaceType GraphicsMolecularSurfaceItem::surfaceType() const { return d->surface->surfaceType(); } /// Sets the probe radius for the surface to \p radius. void GraphicsMolecularSurfaceItem::setProbeRadius(float radius) { d->surface->setProbeRadius(radius); if(surfaceType() == MolecularSurface::SolventAccessible || surfaceType() == MolecularSurface::SolventExcluded){ recalculate(); } } /// Returns the probe radius for the surface. float GraphicsMolecularSurfaceItem::probeRadius() const { return d->surface->probeRadius(); } /// Sets the color for the surface to \p color. void GraphicsMolecularSurfaceItem::setColor(const QColor &color) { d->color = color; if(d->colorMode == SolidColor){ foreach(ContactPatchItem *item, d->contactPatches){ item->setColor(d->color); } } } /// Returns the color for the surface. QColor GraphicsMolecularSurfaceItem::color() const { return d->color; } /// Sets the color mode for the surface item to \p mode. void GraphicsMolecularSurfaceItem::setColorMode(ColorMode mode) { d->colorMode = mode; if(d->colorMode == SolidColor){ foreach(ContactPatchItem *item, d->contactPatches){ item->setColor(d->color); } } else if(d->colorMode == AtomColor){ for(int i = 0; i < d->contactPatches.size(); i++){ ContactPatchItem *item = d->contactPatches[i]; item->setColor(GraphicsMoleculeItem::atomColor(molecule()->atom(i))); } } } /// Returns the color mode for the surface item. GraphicsMolecularSurfaceItem::ColorMode GraphicsMolecularSurfaceItem::colorMode() const { return d->colorMode; } // --- Internal Methods ---------------------------------------------------- // void GraphicsMolecularSurfaceItem::itemChanged(ItemChange change) { if(change == ItemVisiblityChanged){ foreach(ContactPatchItem *item, d->contactPatches){ item->setVisible(isVisible()); } } else if(change == ItemOpacityChanged){ foreach(ContactPatchItem *item, d->contactPatches){ item->setOpacity(opacity()); } if(isOpaque()){ material()->setSpecularColor(QColor::fromRgbF(0.3, 0.3, 0.3)); } else{ material()->setSpecularColor(Qt::transparent); } } else if(change == ItemSceneChanged){ foreach(ContactPatchItem *item, d->contactPatches){ if(scene()){ scene()->addItem(item); } } } } void GraphicsMolecularSurfaceItem::recalculate() { qDeleteAll(d->contactPatches); d->contactPatches.clear(); const Molecule *molecule = this->molecule(); if(!molecule){ return; } // create contact patches foreach(const Atom *atom, molecule->atoms()){ float radius = atom->vanDerWaalsRadius(); if(surfaceType() == MolecularSurface::SolventAccessible){ radius += probeRadius(); } ContactPatchItem *item = new ContactPatchItem(this, atom->position(), radius); d->contactPatches.append(item); if(d->colorMode == AtomColor){ item->setColor(GraphicsMoleculeItem::atomColor(atom)); } else{ item->setColor(d->color); } item->setOpacity(opacity()); if(scene()){ scene()->addItem(item); } } // add intersections from alpha shape edges const AlphaShape *alphaShape = d->surface->alphaShape(); foreach(const QVector<int> &edge, alphaShape->edges()){ ContactPatchItem *itemA = d->contactPatches[edge[0]]; ContactPatchItem *itemB = d->contactPatches[edge[1]]; itemA->addIntersection(itemB); itemB->addIntersection(itemA); } } } // end chemkit namespace <|endoftext|>
<commit_before>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // GRINS - General Reacting Incompressible Navier-Stokes // // Copyright (C) 2010-2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- // C++ #include <iostream> // This class #include "grins/grins_enums.h" #include "grins/mesh_builder.h" // libMesh #include "libmesh/getpot.h" #include "libmesh/string_to_enum.h" #include "libmesh/mesh_generation.h" #include "libmesh/mesh_refinement.h" #include "libmesh/parallel_mesh.h" #include "libmesh/parsed_function.h" #include "libmesh/serial_mesh.h" namespace GRINS { MeshBuilder::MeshBuilder() { return; } MeshBuilder::~MeshBuilder() { return; } std::tr1::shared_ptr<libMesh::UnstructuredMesh> MeshBuilder::build (const GetPot& input, const libMesh::Parallel::Communicator &comm) { // First, read all needed variables std::string mesh_option = input("mesh-options/mesh_option", "NULL"); std::string mesh_filename = input("mesh-options/mesh_filename", "NULL"); libMesh::Real domain_x1_min = input("mesh-options/domain_x1_min", 0.0); libMesh::Real domain_x2_min = input("mesh-options/domain_x2_min", 0.0); libMesh::Real domain_x3_min = input("mesh-options/domain_x3_min", 0.0); libMesh::Real domain_x1_max = input("mesh-options/domain_x1_max", 1.0); libMesh::Real domain_x2_max = input("mesh-options/domain_x2_max", 1.0); libMesh::Real domain_x3_max = input("mesh-options/domain_x3_max", 1.0); int mesh_nx1 = input("mesh-options/mesh_nx1", -1); int mesh_nx2 = input("mesh-options/mesh_nx2", -1); int mesh_nx3 = input("mesh-options/mesh_nx3", -1); std::string element_type = input("mesh-options/element_type", "NULL"); // Make sure the user told us what to do if(mesh_option == "NULL") { std::cerr << " MeshBuilder::read_input_options :" << " mesh-options/mesh_option NOT specified " << std::endl; libmesh_error(); } // Create UnstructuredMesh object (defaults to dimension 1). libMesh::UnstructuredMesh* mesh; // Were we specifically asked to use a ParallelMesh or SerialMesh? std::string mesh_class = input("mesh-options/mesh_class", "default"); if (mesh_class == "parallel") mesh = new libMesh::ParallelMesh(comm); else if (mesh_class == "serial") mesh = new libMesh::SerialMesh(comm); else if (mesh_class == "default") mesh = new libMesh::Mesh(comm); else { std::cerr << " MeshBuilder::build:" << " mesh-options/mesh_class had invalid value " << mesh_class << std::endl; libmesh_error(); } if(mesh_option=="read_mesh_from_file") { // According to Roy Stogner, the only read format // that won't properly reset the dimension is gmsh. /*! \todo Need to a check a GMSH meshes */ mesh->read(mesh_filename); } else if(mesh_option=="create_1D_mesh") { if(element_type=="NULL") { element_type = "EDGE3"; } GRINSEnums::ElemType element_enum_type = libMesh::Utility::string_to_enum<GRINSEnums::ElemType>(element_type); libMesh::MeshTools::Generation::build_line(*mesh, mesh_nx1, domain_x1_min, domain_x1_max, element_enum_type); } else if(mesh_option=="create_2D_mesh") { if(element_type=="NULL") { element_type = "TRI6"; } // Reset mesh dimension to 2. mesh->set_mesh_dimension(2); GRINSEnums::ElemType element_enum_type = libMesh::Utility::string_to_enum<GRINSEnums::ElemType>(element_type); libMesh::MeshTools::Generation::build_square(*mesh, mesh_nx1, mesh_nx2, domain_x1_min, domain_x1_max, domain_x2_min, domain_x2_max, element_enum_type); } else if(mesh_option=="create_3D_mesh") { if(element_type=="NULL") { element_type = "TET10"; } // Reset mesh dimension to 3. mesh->set_mesh_dimension(3); GRINSEnums::ElemType element_enum_type = libMesh::Utility::string_to_enum<GRINSEnums::ElemType>(element_type); libMesh::MeshTools::Generation::build_cube(*mesh, mesh_nx1, mesh_nx2, mesh_nx3, domain_x1_min, domain_x1_max, domain_x2_min, domain_x2_max, domain_x3_min, domain_x3_max, element_enum_type); } else { std::cerr << " MeshBuilder::build_mesh :" << " mesh-options/mesh_option [" << mesh_option << "] NOT supported " << std::endl; libmesh_error(); } int uniformly_refine = input("mesh-options/uniformly_refine", 0); if( uniformly_refine > 0 ) { libMesh::MeshRefinement(*mesh).uniformly_refine(uniformly_refine); } std::string h_refinement_function_string = input("mesh-options/locally_h_refine", std::string("0")); if (h_refinement_function_string != "0") { libMesh::ParsedFunction<Real> h_refinement_function(h_refinement_function_string); MeshRefinement mesh_refinement(*mesh); dof_id_type found_refinements = 0; do { found_refinements = 0; MeshBase::element_iterator elem_it = mesh->active_local_elements_begin(); MeshBase::element_iterator elem_end = mesh->active_local_elements_end(); for (; elem_it != elem_end; ++elem_it) { Elem *elem = *elem_it; const Real refinement_val = h_refinement_function(elem->centroid()); const unsigned int n_refinements = refinement_val > 0 ? refinement_val : 0; if (elem->level() - uniformly_refine < n_refinements) { elem->set_refinement_flag(Elem::REFINE); found_refinements++; } } if (found_refinements) { std::cout << "Found " << found_refinements << " elements to locally refine" << std::endl; mesh_refinement.refine_and_coarsen_elements(); } } while(found_refinements); } return std::tr1::shared_ptr<libMesh::UnstructuredMesh>(mesh); } } // namespace GRINS <commit_msg>Add mesh-options/redistribute option<commit_after>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // GRINS - General Reacting Incompressible Navier-Stokes // // Copyright (C) 2010-2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- // C++ #include <iostream> // This class #include "grins/grins_enums.h" #include "grins/mesh_builder.h" // libMesh #include "libmesh/getpot.h" #include "libmesh/string_to_enum.h" #include "libmesh/mesh_generation.h" #include "libmesh/mesh_modification.h" #include "libmesh/mesh_refinement.h" #include "libmesh/parallel_mesh.h" #include "libmesh/parsed_function.h" #include "libmesh/serial_mesh.h" namespace GRINS { MeshBuilder::MeshBuilder() { return; } MeshBuilder::~MeshBuilder() { return; } std::tr1::shared_ptr<libMesh::UnstructuredMesh> MeshBuilder::build (const GetPot& input, const libMesh::Parallel::Communicator &comm) { // First, read all needed variables std::string mesh_option = input("mesh-options/mesh_option", "NULL"); std::string mesh_filename = input("mesh-options/mesh_filename", "NULL"); libMesh::Real domain_x1_min = input("mesh-options/domain_x1_min", 0.0); libMesh::Real domain_x2_min = input("mesh-options/domain_x2_min", 0.0); libMesh::Real domain_x3_min = input("mesh-options/domain_x3_min", 0.0); libMesh::Real domain_x1_max = input("mesh-options/domain_x1_max", 1.0); libMesh::Real domain_x2_max = input("mesh-options/domain_x2_max", 1.0); libMesh::Real domain_x3_max = input("mesh-options/domain_x3_max", 1.0); int mesh_nx1 = input("mesh-options/mesh_nx1", -1); int mesh_nx2 = input("mesh-options/mesh_nx2", -1); int mesh_nx3 = input("mesh-options/mesh_nx3", -1); std::string element_type = input("mesh-options/element_type", "NULL"); // Make sure the user told us what to do if(mesh_option == "NULL") { std::cerr << " MeshBuilder::read_input_options :" << " mesh-options/mesh_option NOT specified " << std::endl; libmesh_error(); } // Create UnstructuredMesh object (defaults to dimension 1). libMesh::UnstructuredMesh* mesh; // Were we specifically asked to use a ParallelMesh or SerialMesh? std::string mesh_class = input("mesh-options/mesh_class", "default"); if (mesh_class == "parallel") mesh = new libMesh::ParallelMesh(comm); else if (mesh_class == "serial") mesh = new libMesh::SerialMesh(comm); else if (mesh_class == "default") mesh = new libMesh::Mesh(comm); else { std::cerr << " MeshBuilder::build:" << " mesh-options/mesh_class had invalid value " << mesh_class << std::endl; libmesh_error(); } if(mesh_option=="read_mesh_from_file") { // According to Roy Stogner, the only read format // that won't properly reset the dimension is gmsh. /*! \todo Need to a check a GMSH meshes */ mesh->read(mesh_filename); } else if(mesh_option=="create_1D_mesh") { if(element_type=="NULL") { element_type = "EDGE3"; } GRINSEnums::ElemType element_enum_type = libMesh::Utility::string_to_enum<GRINSEnums::ElemType>(element_type); libMesh::MeshTools::Generation::build_line(*mesh, mesh_nx1, domain_x1_min, domain_x1_max, element_enum_type); } else if(mesh_option=="create_2D_mesh") { if(element_type=="NULL") { element_type = "TRI6"; } // Reset mesh dimension to 2. mesh->set_mesh_dimension(2); GRINSEnums::ElemType element_enum_type = libMesh::Utility::string_to_enum<GRINSEnums::ElemType>(element_type); libMesh::MeshTools::Generation::build_square(*mesh, mesh_nx1, mesh_nx2, domain_x1_min, domain_x1_max, domain_x2_min, domain_x2_max, element_enum_type); } else if(mesh_option=="create_3D_mesh") { if(element_type=="NULL") { element_type = "TET10"; } // Reset mesh dimension to 3. mesh->set_mesh_dimension(3); GRINSEnums::ElemType element_enum_type = libMesh::Utility::string_to_enum<GRINSEnums::ElemType>(element_type); libMesh::MeshTools::Generation::build_cube(*mesh, mesh_nx1, mesh_nx2, mesh_nx3, domain_x1_min, domain_x1_max, domain_x2_min, domain_x2_max, domain_x3_min, domain_x3_max, element_enum_type); } else { std::cerr << " MeshBuilder::build_mesh :" << " mesh-options/mesh_option [" << mesh_option << "] NOT supported " << std::endl; libmesh_error(); } std::string redistribution_function_string = input("mesh-options/redistribute", std::string("0")); if (redistribution_function_string != "0") { libMesh::ParsedFunction<Real> redistribution_function(redistribution_function_string); MeshTools::Modification::transform (*mesh, redistribution_function); } int uniformly_refine = input("mesh-options/uniformly_refine", 0); if( uniformly_refine > 0 ) { libMesh::MeshRefinement(*mesh).uniformly_refine(uniformly_refine); } std::string h_refinement_function_string = input("mesh-options/locally_h_refine", std::string("0")); if (h_refinement_function_string != "0") { libMesh::ParsedFunction<Real> h_refinement_function(h_refinement_function_string); MeshRefinement mesh_refinement(*mesh); dof_id_type found_refinements = 0; do { found_refinements = 0; MeshBase::element_iterator elem_it = mesh->active_local_elements_begin(); MeshBase::element_iterator elem_end = mesh->active_local_elements_end(); for (; elem_it != elem_end; ++elem_it) { Elem *elem = *elem_it; const Real refinement_val = h_refinement_function(elem->centroid()); const unsigned int n_refinements = refinement_val > 0 ? refinement_val : 0; if (elem->level() - uniformly_refine < n_refinements) { elem->set_refinement_flag(Elem::REFINE); found_refinements++; } } if (found_refinements) { std::cout << "Found " << found_refinements << " elements to locally refine" << std::endl; mesh_refinement.refine_and_coarsen_elements(); } } while(found_refinements); } return std::tr1::shared_ptr<libMesh::UnstructuredMesh>(mesh); } } // namespace GRINS <|endoftext|>
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp: /* Copyright (c) 2008 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld 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 "flusspferd/importer.hpp" #include "flusspferd/create.hpp" #include "flusspferd/string.hpp" #include "flusspferd/tracer.hpp" #include "flusspferd/security.hpp" #include <boost/filesystem.hpp> #include <boost/unordered_map.hpp> #include <iostream> #include <fstream> #include <string> #include <sstream> #include <errno.h> #include <dlfcn.h> #define DIRSEP1 "/" #define DIRSEP2 "" #define SHLIBPREFIX "lib" #ifdef APPLE #define SHLIBSUFFIX ".dylib" #else #define SHLIBSUFFIX ".so" #endif using namespace flusspferd; object importer::class_info::create_prototype() { object proto = create_object(); return proto; } void importer::class_info::augment_constructor(object &ctor) { ctor.define_property("preload", create_object(), permanent_property); ctor.define_property("defaultPaths", create_array(), permanent_property); } void importer::add_preloaded(std::string const &name, object const &obj) { local_root_scope scope; object ctor = constructor<importer>(); object preload = ctor.get_property("preload").to_object(); preload.set_property(name, obj); } void importer::add_preloaded( std::string const &name, boost::function<object (object const &)> const &fun) { add_preloaded(name, create_native_function(fun, name)); } class importer::impl { public: typedef std::pair<std::string, bool> key_type; typedef boost::unordered_map<key_type, value> module_cache_map; module_cache_map module_cache; }; importer::importer(object const &obj, call_context &) : native_object_base(obj), p(new impl) { local_root_scope scope; // Create the load method on the actual object itself, not on the prototype // That way the following works: // // i.load('foo'); // Assume foo module defines this.foo = 'abc' // print(i.foo); // abc // // without the problem of load being overridden to do bad things by a module add_native_method("load", 2); register_native_method("load", &importer::load); object constructor = flusspferd::constructor<importer>(); // Store search paths array arr = constructor.get_property("defaultPaths").to_object(); arr = arr.call("concat").to_object(); set_property("paths", arr); // Create a context object, which is the object on which all modules are // evaluated object context = create_object(); set_property("context", context); // this.contexnt.__proto__ = this.__proto__; // Not sure we actually want to do this, but we can for now. context.set_prototype(prototype()); set_prototype(context); } importer::~importer() {} void importer::trace(tracer &trc) { for (impl::module_cache_map::iterator it = p->module_cache.begin(); it != p->module_cache.end(); ++it) trc("module-cache-item", it->second); } value importer::load(string const &f_name, bool binary_only) { security &sec = security::get(); //TODO use security std::string name = f_name.to_string(); std::transform(name.begin(), name.end(), name.begin(), tolower); impl::key_type key(name, binary_only); impl::module_cache_map::iterator it = p->module_cache.find(key); if (it != p->module_cache.end()) return it->second; object ctx = get_property("context").to_object(); ctx.define_property("$importer", *this); ctx.define_property("$security", sec); object constructor = flusspferd::constructor<importer>(); value preload = constructor.get_property("preload"); if (preload.is_object()) { value loader = preload.get_object().get_property(name); if (loader.is_object()) { value result; if (!loader.is_null()) { local_root_scope scope; object x = loader.get_object(); result = x.call(ctx); } return result; } } std::string so_name, js_name; so_name = process_name(name); js_name = process_name(name, true); //TODO: I'd like a version that throws an exception instead of assert traps value paths_v = get_property("paths").to_object(); if (!paths_v.is_object()) throw exception("Unable to get search paths or its not an object"); array paths = paths_v.get_object(); // TODO: We could probably do with an array class. size_t len = paths.get_length(); for (size_t i=0; i < len; i++) { std::string path = paths.get_element(i).to_string().to_string(); std::string fullpath = path + js_name; if (!binary_only) if (sec.check_path(fullpath, security::READ)) if (boost::filesystem::exists(fullpath)) { value val = current_context().execute( fullpath.c_str(), ctx); p->module_cache[key] = val; return val; } fullpath = path + so_name; if (!sec.check_path(fullpath, security::READ)) continue; if (boost::filesystem::exists(fullpath)) { // Load the .so void *module = dlopen(fullpath.c_str(), RTLD_LAZY); if (!module) { std::stringstream ss; ss << "Unable to load library '" << fullpath.c_str() << "': " << dlerror(); throw exception(ss.str().c_str()); } void *symbol = dlsym(module, "flusspferd_load"); if (!symbol) { std::stringstream ss; ss << "Unable to load library '" << fullpath.c_str() << "': " << dlerror(); throw exception(ss.str().c_str()); } flusspferd_load_t func = *(flusspferd_load_t*) &symbol; value val = func(ctx); p->module_cache[key] = val; return val; } } // We probably want to throw an exception here. std::stringstream ss; ss << "Unable to find library '"; ss << name.c_str(); ss << "' in ["; ss << paths_v.to_string().c_str() << "]"; throw exception(ss.str().c_str()); } // Take 'foo.bar' as a flusspferd::string, check no path sep in it, and // return '/foo/bar.js' or '/foo/libbar.so', etc. as a std::string std::string importer::process_name(std::string const &name, bool for_script) { std::string p = name; if (p.find(DIRSEP1, 0) != std::string::npos && p.find(DIRSEP2, 0) != std::string::npos) { throw exception("Path seperator not allowed in module name"); } std::size_t pos = 0; while ( (pos = p.find('.', pos)) != std::string::npos) { p.replace(pos, 1, DIRSEP1); pos++; } if (!for_script && SHLIBPREFIX) { // stick the lib on the front as needed pos = p.rfind(DIRSEP1, 0); if (pos == std::string::npos) pos = 0; p.insert(pos, SHLIBPREFIX); } p = DIRSEP1 + p; if (for_script) p += ".js"; else p += SHLIBSUFFIX; return p; } <commit_msg>core/importer: don't lowercase modules, be case sensitive<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp: /* Copyright (c) 2008 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld 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 "flusspferd/importer.hpp" #include "flusspferd/create.hpp" #include "flusspferd/string.hpp" #include "flusspferd/tracer.hpp" #include "flusspferd/security.hpp" #include <boost/filesystem.hpp> #include <boost/unordered_map.hpp> #include <iostream> #include <fstream> #include <string> #include <sstream> #include <errno.h> #include <dlfcn.h> #define DIRSEP1 "/" #define DIRSEP2 "" #define SHLIBPREFIX "lib" #ifdef APPLE #define SHLIBSUFFIX ".dylib" #else #define SHLIBSUFFIX ".so" #endif using namespace flusspferd; object importer::class_info::create_prototype() { object proto = create_object(); return proto; } void importer::class_info::augment_constructor(object &ctor) { ctor.define_property("preload", create_object(), permanent_property); ctor.define_property("defaultPaths", create_array(), permanent_property); } void importer::add_preloaded(std::string const &name, object const &obj) { local_root_scope scope; object ctor = constructor<importer>(); object preload = ctor.get_property("preload").to_object(); preload.set_property(name, obj); } void importer::add_preloaded( std::string const &name, boost::function<object (object const &)> const &fun) { add_preloaded(name, create_native_function(fun, name)); } class importer::impl { public: typedef std::pair<std::string, bool> key_type; typedef boost::unordered_map<key_type, value> module_cache_map; module_cache_map module_cache; }; importer::importer(object const &obj, call_context &) : native_object_base(obj), p(new impl) { local_root_scope scope; // Create the load method on the actual object itself, not on the prototype // That way the following works: // // i.load('foo'); // Assume foo module defines this.foo = 'abc' // print(i.foo); // abc // // without the problem of load being overridden to do bad things by a module add_native_method("load", 2); register_native_method("load", &importer::load); object constructor = flusspferd::constructor<importer>(); // Store search paths array arr = constructor.get_property("defaultPaths").to_object(); arr = arr.call("concat").to_object(); set_property("paths", arr); // Create a context object, which is the object on which all modules are // evaluated object context = create_object(); set_property("context", context); // this.contexnt.__proto__ = this.__proto__; // Not sure we actually want to do this, but we can for now. context.set_prototype(prototype()); set_prototype(context); } importer::~importer() {} void importer::trace(tracer &trc) { for (impl::module_cache_map::iterator it = p->module_cache.begin(); it != p->module_cache.end(); ++it) trc("module-cache-item", it->second); } value importer::load(string const &f_name, bool binary_only) { security &sec = security::get(); std::string name = f_name.to_string(); impl::key_type key(name, binary_only); impl::module_cache_map::iterator it = p->module_cache.find(key); if (it != p->module_cache.end()) return it->second; object ctx = get_property("context").to_object(); ctx.define_property("$importer", *this); ctx.define_property("$security", sec); object constructor = flusspferd::constructor<importer>(); value preload = constructor.get_property("preload"); if (preload.is_object()) { value loader = preload.get_object().get_property(name); if (loader.is_object()) { value result; if (!loader.is_null()) { local_root_scope scope; object x = loader.get_object(); result = x.call(ctx); } return result; } } std::string so_name, js_name; so_name = process_name(name); js_name = process_name(name, true); //TODO: I'd like a version that throws an exception instead of assert traps value paths_v = get_property("paths").to_object(); if (!paths_v.is_object()) throw exception("Unable to get search paths or its not an object"); array paths = paths_v.get_object(); // TODO: We could probably do with an array class. size_t len = paths.get_length(); for (size_t i=0; i < len; i++) { std::string path = paths.get_element(i).to_string().to_string(); std::string fullpath = path + js_name; if (!binary_only) if (sec.check_path(fullpath, security::READ)) if (boost::filesystem::exists(fullpath)) { value val = current_context().execute( fullpath.c_str(), ctx); p->module_cache[key] = val; return val; } fullpath = path + so_name; if (!sec.check_path(fullpath, security::READ)) continue; if (boost::filesystem::exists(fullpath)) { // Load the .so void *module = dlopen(fullpath.c_str(), RTLD_LAZY); if (!module) { std::stringstream ss; ss << "Unable to load library '" << fullpath.c_str() << "': " << dlerror(); throw exception(ss.str().c_str()); } void *symbol = dlsym(module, "flusspferd_load"); if (!symbol) { std::stringstream ss; ss << "Unable to load library '" << fullpath.c_str() << "': " << dlerror(); throw exception(ss.str().c_str()); } flusspferd_load_t func = *(flusspferd_load_t*) &symbol; value val = func(ctx); p->module_cache[key] = val; return val; } } // We probably want to throw an exception here. std::stringstream ss; ss << "Unable to find library '"; ss << name.c_str(); ss << "' in ["; ss << paths_v.to_string().c_str() << "]"; throw exception(ss.str().c_str()); } // Take 'foo.bar' as a flusspferd::string, check no path sep in it, and // return '/foo/bar.js' or '/foo/libbar.so', etc. as a std::string std::string importer::process_name(std::string const &name, bool for_script) { std::string p = name; if (p.find(DIRSEP1, 0) != std::string::npos && p.find(DIRSEP2, 0) != std::string::npos) { throw exception("Path seperator not allowed in module name"); } std::size_t pos = 0; while ( (pos = p.find('.', pos)) != std::string::npos) { p.replace(pos, 1, DIRSEP1); pos++; } if (!for_script && SHLIBPREFIX) { // stick the lib on the front as needed pos = p.rfind(DIRSEP1, 0); if (pos == std::string::npos) pos = 0; p.insert(pos, SHLIBPREFIX); } p = DIRSEP1 + p; if (for_script) p += ".js"; else p += SHLIBSUFFIX; return p; } <|endoftext|>
<commit_before>#include <QStandardPaths> #include <QtEndian> #include "MainWindow.h" #ifndef NO_SERIAL_LINK #include "SerialLink.h" #endif #include "QGCMAVLinkLogPlayer.h" #include "QGC.h" #include "ui_QGCMAVLinkLogPlayer.h" #include "QGCApplication.h" #include "LinkManager.h" #include "QGCQFileDialog.h" #include "QGCMessageBox.h" QGCMAVLinkLogPlayer::QGCMAVLinkLogPlayer(QWidget *parent) : QWidget(parent), _replayLink(NULL), _ui(new Ui::QGCMAVLinkLogPlayer) { _ui->setupUi(this); _ui->horizontalLayout->setAlignment(Qt::AlignTop); // Setup buttons connect(_ui->selectFileButton, &QPushButton::clicked, this, &QGCMAVLinkLogPlayer::_selectLogFileForPlayback); connect(_ui->playButton, &QPushButton::clicked, this, &QGCMAVLinkLogPlayer::_playPauseToggle); connect(_ui->positionSlider, &QSlider::valueChanged, this, &QGCMAVLinkLogPlayer::_setPlayheadFromSlider); connect(_ui->positionSlider, &QSlider::sliderPressed, this, &QGCMAVLinkLogPlayer::_pause); #if 0 // Speed slider is removed from 3.0 release. Too broken to fix. connect(_ui->speedSlider, &QSlider::valueChanged, this, &QGCMAVLinkLogPlayer::_setAccelerationFromSlider); _ui->speedSlider->setMinimum(-100); _ui->speedSlider->setMaximum(100); _ui->speedSlider->setValue(0); #endif _enablePlaybackControls(false); _ui->positionSlider->setMinimum(0); _ui->positionSlider->setMaximum(100); } QGCMAVLinkLogPlayer::~QGCMAVLinkLogPlayer() { delete _ui; } void QGCMAVLinkLogPlayer::_playPauseToggle(void) { if (_replayLink->isPlaying()) { _pause(); } else { _replayLink->play(); } } void QGCMAVLinkLogPlayer::_pause(void) { _replayLink->pause(); } void QGCMAVLinkLogPlayer::_selectLogFileForPlayback(void) { // Disallow replay when any links are connected if (qgcApp()->toolbox()->multiVehicleManager()->activeVehicle()) { QGCMessageBox::information(tr("Log Replay"), tr("You must close all connections prior to replaying a log.")); return; } QString logFilename = QGCQFileDialog::getOpenFileName( this, tr("Load MAVLink Log File"), QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation), tr("MAVLink Log Files (*.tlog);;All Files (*)")); if (logFilename.isEmpty()) { return; } LinkInterface* createConnectedLink(LinkConfiguration* config); LogReplayLinkConfiguration* linkConfig = new LogReplayLinkConfiguration(QString("Log Replay")); linkConfig->setLogFilename(logFilename); linkConfig->setName(linkConfig->logFilenameShort()); _ui->logFileNameLabel->setText(linkConfig->logFilenameShort()); LinkManager* linkMgr = qgcApp()->toolbox()->linkManager(); SharedLinkConfigurationPointer sharedConfig = linkMgr->addConfiguration(linkConfig); _replayLink = (LogReplayLink*)qgcApp()->toolbox()->linkManager()->createConnectedLink(sharedConfig); connect(_replayLink, &LogReplayLink::logFileStats, this, &QGCMAVLinkLogPlayer::_logFileStats); connect(_replayLink, &LogReplayLink::playbackStarted, this, &QGCMAVLinkLogPlayer::_playbackStarted); connect(_replayLink, &LogReplayLink::playbackPaused, this, &QGCMAVLinkLogPlayer::_playbackPaused); connect(_replayLink, &LogReplayLink::playbackPercentCompleteChanged, this, &QGCMAVLinkLogPlayer::_playbackPercentCompleteChanged); connect(_replayLink, &LogReplayLink::disconnected, this, &QGCMAVLinkLogPlayer::_replayLinkDisconnected); _ui->positionSlider->setValue(0); #if 0 _ui->speedSlider->setValue(0); #endif } void QGCMAVLinkLogPlayer::_playbackError(void) { _ui->logFileNameLabel->setText("Error"); _enablePlaybackControls(false); } QString QGCMAVLinkLogPlayer::_secondsToHMS(int seconds) { int secondsPart = seconds; int minutesPart = secondsPart / 60; int hoursPart = minutesPart / 60; secondsPart -= 60 * minutesPart; minutesPart -= 60 * hoursPart; return QString("%1h:%2m:%3s").arg(hoursPart, 2).arg(minutesPart, 2).arg(secondsPart, 2); } /// Signalled from LogReplayLink once log file information is known void QGCMAVLinkLogPlayer::_logFileStats(bool logTimestamped, ///< true: timestamped log int logDurationSeconds, ///< Log duration int binaryBaudRate) ///< Baud rate for non-timestamped log { Q_UNUSED(logTimestamped); Q_UNUSED(binaryBaudRate); _logDurationSeconds = logDurationSeconds; _ui->logStatsLabel->setText(_secondsToHMS(logDurationSeconds)); } /// Signalled from LogReplayLink when replay starts void QGCMAVLinkLogPlayer::_playbackStarted(void) { _enablePlaybackControls(true); _ui->playButton->setChecked(true); _ui->playButton->setIcon(QIcon(":/res/Pause")); } /// Signalled from LogReplayLink when replay is paused void QGCMAVLinkLogPlayer::_playbackPaused(void) { _ui->playButton->setIcon(QIcon(":/res/Play")); _ui->playButton->setChecked(false); } void QGCMAVLinkLogPlayer::_playbackPercentCompleteChanged(int percentComplete) { _ui->positionSlider->blockSignals(true); _ui->positionSlider->setValue(percentComplete); _ui->positionSlider->blockSignals(false); } void QGCMAVLinkLogPlayer::_setPlayheadFromSlider(int value) { if (_replayLink) { _replayLink->movePlayhead(value); } } void QGCMAVLinkLogPlayer::_enablePlaybackControls(bool enabled) { _ui->playButton->setEnabled(enabled); #if 0 _ui->speedSlider->setEnabled(enabled); #endif _ui->positionSlider->setEnabled(enabled); } #if 0 void QGCMAVLinkLogPlayer::_setAccelerationFromSlider(int value) { //qDebug() << value; if (_replayLink) { _replayLink->setAccelerationFactor(value); } // Factor: -100: 0.01x, 0: 1.0x, 100: 100x float accelerationFactor; if (value < 0) { accelerationFactor = 0.01f; value -= -100; if (value > 0) { accelerationFactor *= (float)value; } } else if (value > 0) { accelerationFactor = 1.0f * (float)value; } else { accelerationFactor = 1.0f; } _ui->speedLabel->setText(QString("Speed: %1X").arg(accelerationFactor, 5, 'f', 2, '0')); } #endif void QGCMAVLinkLogPlayer::_replayLinkDisconnected(void) { _enablePlaybackControls(false); _replayLink = NULL; } <commit_msg>Some simple fixes<commit_after>#include <QStandardPaths> #include <QtEndian> #include "MainWindow.h" #ifndef NO_SERIAL_LINK #include "SerialLink.h" #endif #include "QGCMAVLinkLogPlayer.h" #include "QGC.h" #include "ui_QGCMAVLinkLogPlayer.h" #include "QGCApplication.h" #include "SettingsManager.h" #include "AppSettings.h" #include "LinkManager.h" #include "QGCQFileDialog.h" #include "QGCMessageBox.h" QGCMAVLinkLogPlayer::QGCMAVLinkLogPlayer(QWidget *parent) : QWidget(parent), _replayLink(NULL), _ui(new Ui::QGCMAVLinkLogPlayer) { _ui->setupUi(this); _ui->horizontalLayout->setAlignment(Qt::AlignTop); // Setup buttons connect(_ui->selectFileButton, &QPushButton::clicked, this, &QGCMAVLinkLogPlayer::_selectLogFileForPlayback); connect(_ui->playButton, &QPushButton::clicked, this, &QGCMAVLinkLogPlayer::_playPauseToggle); connect(_ui->positionSlider, &QSlider::valueChanged, this, &QGCMAVLinkLogPlayer::_setPlayheadFromSlider); connect(_ui->positionSlider, &QSlider::sliderPressed, this, &QGCMAVLinkLogPlayer::_pause); #if 0 // Speed slider is removed from 3.0 release. Too broken to fix. connect(_ui->speedSlider, &QSlider::valueChanged, this, &QGCMAVLinkLogPlayer::_setAccelerationFromSlider); _ui->speedSlider->setMinimum(-100); _ui->speedSlider->setMaximum(100); _ui->speedSlider->setValue(0); #endif _enablePlaybackControls(false); _ui->positionSlider->setMinimum(0); _ui->positionSlider->setMaximum(100); } QGCMAVLinkLogPlayer::~QGCMAVLinkLogPlayer() { delete _ui; } void QGCMAVLinkLogPlayer::_playPauseToggle(void) { if (_replayLink->isPlaying()) { _pause(); } else { _replayLink->play(); } } void QGCMAVLinkLogPlayer::_pause(void) { _replayLink->pause(); } void QGCMAVLinkLogPlayer::_selectLogFileForPlayback(void) { // Disallow replay when any links are connected if (qgcApp()->toolbox()->multiVehicleManager()->activeVehicle()) { QGCMessageBox::information(tr("Log Replay"), tr("You must close all connections prior to replaying a log.")); return; } QString logFilename = QGCQFileDialog::getOpenFileName( this, tr("Load Telemetry Log File"), qgcApp()->toolbox()->settingsManager()->appSettings()->telemetrySavePath(), tr("MAVLink Log Files (*.tlog);;All Files (*)")); if (logFilename.isEmpty()) { return; } LinkInterface* createConnectedLink(LinkConfiguration* config); LogReplayLinkConfiguration* linkConfig = new LogReplayLinkConfiguration(QString("Log Replay")); linkConfig->setLogFilename(logFilename); linkConfig->setName(linkConfig->logFilenameShort()); _ui->logFileNameLabel->setText(linkConfig->logFilenameShort()); LinkManager* linkMgr = qgcApp()->toolbox()->linkManager(); SharedLinkConfigurationPointer sharedConfig = linkMgr->addConfiguration(linkConfig); _replayLink = (LogReplayLink*)qgcApp()->toolbox()->linkManager()->createConnectedLink(sharedConfig); connect(_replayLink, &LogReplayLink::logFileStats, this, &QGCMAVLinkLogPlayer::_logFileStats); connect(_replayLink, &LogReplayLink::playbackStarted, this, &QGCMAVLinkLogPlayer::_playbackStarted); connect(_replayLink, &LogReplayLink::playbackPaused, this, &QGCMAVLinkLogPlayer::_playbackPaused); connect(_replayLink, &LogReplayLink::playbackPercentCompleteChanged, this, &QGCMAVLinkLogPlayer::_playbackPercentCompleteChanged); connect(_replayLink, &LogReplayLink::disconnected, this, &QGCMAVLinkLogPlayer::_replayLinkDisconnected); _ui->positionSlider->setValue(0); #if 0 _ui->speedSlider->setValue(0); #endif } void QGCMAVLinkLogPlayer::_playbackError(void) { _ui->logFileNameLabel->setText("Error"); _enablePlaybackControls(false); } QString QGCMAVLinkLogPlayer::_secondsToHMS(int seconds) { int secondsPart = seconds; int minutesPart = secondsPart / 60; int hoursPart = minutesPart / 60; secondsPart -= 60 * minutesPart; minutesPart -= 60 * hoursPart; return QString("%1h:%2m:%3s").arg(hoursPart, 2).arg(minutesPart, 2).arg(secondsPart, 2); } /// Signalled from LogReplayLink once log file information is known void QGCMAVLinkLogPlayer::_logFileStats(bool logTimestamped, ///< true: timestamped log int logDurationSeconds, ///< Log duration int binaryBaudRate) ///< Baud rate for non-timestamped log { Q_UNUSED(logTimestamped); Q_UNUSED(binaryBaudRate); _logDurationSeconds = logDurationSeconds; _ui->logStatsLabel->setText(_secondsToHMS(logDurationSeconds)); } /// Signalled from LogReplayLink when replay starts void QGCMAVLinkLogPlayer::_playbackStarted(void) { _enablePlaybackControls(true); _ui->playButton->setChecked(true); _ui->playButton->setIcon(QIcon(":/res/Pause")); _ui->positionSlider->setEnabled(false); } /// Signalled from LogReplayLink when replay is paused void QGCMAVLinkLogPlayer::_playbackPaused(void) { _ui->playButton->setIcon(QIcon(":/res/Play")); _ui->playButton->setChecked(false); _ui->positionSlider->setEnabled(true); } void QGCMAVLinkLogPlayer::_playbackPercentCompleteChanged(int percentComplete) { _ui->positionSlider->blockSignals(true); _ui->positionSlider->setValue(percentComplete); _ui->positionSlider->blockSignals(false); } void QGCMAVLinkLogPlayer::_setPlayheadFromSlider(int value) { if (_replayLink) { _replayLink->movePlayhead(value); } } void QGCMAVLinkLogPlayer::_enablePlaybackControls(bool enabled) { _ui->playButton->setEnabled(enabled); #if 0 _ui->speedSlider->setEnabled(enabled); #endif _ui->positionSlider->setEnabled(enabled); } #if 0 void QGCMAVLinkLogPlayer::_setAccelerationFromSlider(int value) { //qDebug() << value; if (_replayLink) { _replayLink->setAccelerationFactor(value); } // Factor: -100: 0.01x, 0: 1.0x, 100: 100x float accelerationFactor; if (value < 0) { accelerationFactor = 0.01f; value -= -100; if (value > 0) { accelerationFactor *= (float)value; } } else if (value > 0) { accelerationFactor = 1.0f * (float)value; } else { accelerationFactor = 1.0f; } _ui->speedLabel->setText(QString("Speed: %1X").arg(accelerationFactor, 5, 'f', 2, '0')); } #endif void QGCMAVLinkLogPlayer::_replayLinkDisconnected(void) { _enablePlaybackControls(false); _replayLink = NULL; } <|endoftext|>
<commit_before>// // Created by Derek van Vliet on 2014-12-10. // Copyright (c) 2015 Get Set Games Inc. All rights reserved. // #include "FusePrivatePCH.h" #if PLATFORM_IOS @interface FuseDelegateImpl : NSObject <FuseDelegate> @end static FuseDelegateImpl* FuseDelegateImplSingleton = [[FuseDelegateImpl alloc] init]; #endif void UFuseFunctions::FuseStartSession(FString AppId) { const UFuseSettings* DefaultSettings = GetDefault<UFuseSettings>(); #if PLATFORM_IOS dispatch_sync(dispatch_get_main_queue(), ^{ NSDictionary* options = @{ kFuseSDKOptionKey_RegisterForPush : @(DefaultSettings->bRegisterForPush), kFuseSDKOptionKey_DisableCrashReporting : @(DefaultSettings->bDisableCrashReporting), }; [FuseSDK startSession:AppId.GetNSString() delegate:FuseDelegateImplSingleton withOptions:options]; }); #endif } bool UFuseFunctions::FuseIsAdAvailableForZoneId(FString ZoneId) { #if PLATFORM_IOS return [FuseSDK isAdAvailableForZoneID:ZoneId.GetNSString()]; #endif return false; } void UFuseFunctions::FuseShowAdForZoneId(FString ZoneId) { #if PLATFORM_IOS dispatch_sync(dispatch_get_main_queue(), ^{ [FuseSDK showAdForZoneID:ZoneId.GetNSString() options:nil]; }); #endif } void UFuseFunctions::FusePreloadAdForZoneId(FString ZoneId) { #if PLATFORM_IOS dispatch_sync(dispatch_get_main_queue(), ^{ [FuseSDK preloadAdForZoneID:ZoneId.GetNSString()]; }); #endif } void UFuseFunctions::FuseRegisterInAppPurchase(EInAppPurchaseState::Type PurchaseState, FInAppPurchaseProductInfo PurchaseInfo) { #if PLATFORM_IOS dispatch_sync(dispatch_get_main_queue(), ^{ NSData* ReceiptData = [[[NSData alloc] initWithBase64EncodedString:PurchaseInfo.ReceiptData.GetNSString() options:NSDataBase64EncodingEndLineWithLineFeed] autorelease]; NSInteger TransactionState = PurchaseState == EInAppPurchaseState::Success ? SKPaymentTransactionStatePurchased : SKPaymentTransactionStateFailed; NSString* CurrencyCode = [[NSLocale currentLocale] objectForKey:NSLocaleCurrencyCode]; NSString* CurrencySymbol = [[NSLocale currentLocale] objectForKey:NSLocaleCurrencySymbol]; NSString* Price = [PurchaseInfo.DisplayPrice.GetNSString() stringByReplacingOccurrencesOfString:CurrencySymbol withString:@""]; //UE_LOG(LogFuse, Log, TEXT("ReceiptData: %s, Purchase State: %i, Price: %s, Currency Code: %s, Purchase Identifier: %s, Transaction Identifier: %s"), *PurchaseInfo.ReceiptData, TransactionState, *FString(Price), *FString(CurrencyCode), *PurchaseInfo.Identifier, *PurchaseInfo.TransactionIdentifier); [FuseSDK registerInAppPurchase:ReceiptData TxState:TransactionState Price:Price Currency:CurrencyCode ProductID:PurchaseInfo.Identifier.GetNSString() TransactionID:PurchaseInfo.TransactionIdentifier.GetNSString()]; }); #endif } #if PLATFORM_IOS @implementation FuseDelegateImpl -(void) sessionStartReceived { UFuseComponent::SessionStartReceivedDelegate.Broadcast(); } -(void) sessionLoginError:(NSError*)_error { UFuseComponent::SessionLoginErrorDelegate.Broadcast((EBPFuseError::Error)[_error code]); } -(void) timeUpdated:(NSNumber*)_utcTimeStamp { UFuseComponent::TimeUpdatedDelegate.Broadcast([_utcTimeStamp intValue]); } -(void) accountLoginComplete:(NSNumber*)_type Account:(NSString*)_account_id { UFuseComponent::AccountLoginCompleteDelegate.Broadcast([_type intValue],FString(_account_id)); } -(void) account:(NSString*)_account_id loginError:(NSError*)_error { UFuseComponent::AccountLoginErrorDelegate.Broadcast(FString(_account_id),(EBPFuseError::Error)[_error code]); } -(void) notificationAction:(NSString*)_action { UFuseComponent::NotificationActionDelegate.Broadcast(FString(_action)); } -(void) notficationWillClose { UFuseComponent::NotificationWillCloseDelegate.Broadcast(); } -(void) gameConfigurationReceived { UFuseComponent::GameConfigurationReceivedDelegate.Broadcast(); } -(void) friendAdded:(NSString*)_fuse_id Error:(NSError*)_error { UFuseComponent::FriendAddedDelegate.Broadcast(FString(_fuse_id),(EBPFuseError::Error)[_error code]); } -(void) friendRemoved:(NSString*)_fuse_id Error:(NSError*)_error { UFuseComponent::FriendRemovedDelegate.Broadcast(FString(_fuse_id),(EBPFuseError::Error)[_error code]); } -(void) friendAccepted:(NSString*)_fuse_id Error:(NSError*)_error { UFuseComponent::FriendAcceptedDelegate.Broadcast(FString(_fuse_id),(EBPFuseError::Error)[_error code]); } -(void) friendRejected:(NSString*)_fuse_id Error:(NSError*)_error { UFuseComponent::FriendRejectedDelegate.Broadcast(FString(_fuse_id),(EBPFuseError::Error)[_error code]); } -(void) friendsMigrated:(NSString*)_fuse_id Error:(NSError*)_error { UFuseComponent::FriendsMigratedDelegate.Broadcast(FString(_fuse_id),(EBPFuseError::Error)[_error code]); } -(void) friendsListUpdated:(NSDictionary*)_friendsList { } -(void) friendsListError:(NSError*)_error { UFuseComponent::FriendsListErrorDelegate.Broadcast((EBPFuseError::Error)[_error code]); } -(void) purchaseVerification:(NSNumber*)_verified TransactionID:(NSString*)_tx_id OriginalTransactionID:(NSString*)_o_tx_id { UFuseComponent::PurchaseVerificationDelegate.Broadcast([_verified boolValue],FString(_tx_id),FString(_o_tx_id)); } -(void) adAvailabilityResponse:(NSNumber*)_available Error:(NSError*)_error { UFuseComponent::AdAvailabilityResponseDelegate.Broadcast([_available boolValue],(EBPFuseError::Error)[_error code]); } -(void) rewardedAdCompleteWithObject:(FuseRewardedObject*) _reward { UFuseComponent::RewardedAdCompleteDelegate.Broadcast(FFuseRewardedObject(FString(_reward.preRollMessage), FString(_reward.rewardMessage), FString(_reward.rewardItem), [_reward.rewardAmount intValue])); } -(void) IAPOfferAcceptedWithObject:(FuseIAPOfferObject*) _offer { UFuseComponent::IAPOfferAcceptedDelegate.Broadcast(FFuseIAPOfferObject(FString(_offer.productID), [_offer.productPrice floatValue], FString(_offer.itemName), [_offer.itemAmount intValue])); } -(void) virtualGoodsOfferAcceptedWithObject:(FuseVirtualGoodsOfferObject*) _offer { UFuseComponent::VirtualGoodsOfferAcceptedDelegate.Broadcast(FFuseVirtualGoodsOfferObject(FString(_offer.purchaseCurrency), [_offer.purchasePrice floatValue], FString(_offer.itemName), [_offer.itemAmount intValue])); } -(void) adFailedToDisplay { UFuseComponent::AdFailedToDisplayDelegate.Broadcast(); } -(void) adWillClose { UFuseComponent::AdWillCloseDelegate.Broadcast(); } @end #endif<commit_msg>removed some uses of dispatch_sync, replaced others with dispatch_async<commit_after>// // Created by Derek van Vliet on 2014-12-10. // Copyright (c) 2015 Get Set Games Inc. All rights reserved. // #include "FusePrivatePCH.h" #if PLATFORM_IOS @interface FuseDelegateImpl : NSObject <FuseDelegate> @end static FuseDelegateImpl* FuseDelegateImplSingleton = [[FuseDelegateImpl alloc] init]; #endif void UFuseFunctions::FuseStartSession(FString AppId) { const UFuseSettings* DefaultSettings = GetDefault<UFuseSettings>(); #if PLATFORM_IOS dispatch_async(dispatch_get_main_queue(), ^{ NSDictionary* options = @{ kFuseSDKOptionKey_RegisterForPush : @(DefaultSettings->bRegisterForPush), kFuseSDKOptionKey_DisableCrashReporting : @(DefaultSettings->bDisableCrashReporting), }; [FuseSDK startSession:AppId.GetNSString() delegate:FuseDelegateImplSingleton withOptions:options]; }); #endif } bool UFuseFunctions::FuseIsAdAvailableForZoneId(FString ZoneId) { #if PLATFORM_IOS return [FuseSDK isAdAvailableForZoneID:ZoneId.GetNSString()]; #endif return false; } void UFuseFunctions::FuseShowAdForZoneId(FString ZoneId) { #if PLATFORM_IOS dispatch_async(dispatch_get_main_queue(), ^{ [FuseSDK showAdForZoneID:ZoneId.GetNSString() options:nil]; }); #endif } void UFuseFunctions::FusePreloadAdForZoneId(FString ZoneId) { #if PLATFORM_IOS dispatch_async(dispatch_get_main_queue(), ^{ [FuseSDK preloadAdForZoneID:ZoneId.GetNSString()]; }); #endif } void UFuseFunctions::FuseRegisterInAppPurchase(EInAppPurchaseState::Type PurchaseState, FInAppPurchaseProductInfo PurchaseInfo) { #if PLATFORM_IOS dispatch_async(dispatch_get_main_queue(), ^{ NSData* ReceiptData = [[[NSData alloc] initWithBase64EncodedString:PurchaseInfo.ReceiptData.GetNSString() options:NSDataBase64EncodingEndLineWithLineFeed] autorelease]; NSInteger TransactionState = PurchaseState == EInAppPurchaseState::Success ? SKPaymentTransactionStatePurchased : SKPaymentTransactionStateFailed; NSString* CurrencyCode = [[NSLocale currentLocale] objectForKey:NSLocaleCurrencyCode]; NSString* CurrencySymbol = [[NSLocale currentLocale] objectForKey:NSLocaleCurrencySymbol]; NSString* Price = [PurchaseInfo.DisplayPrice.GetNSString() stringByReplacingOccurrencesOfString:CurrencySymbol withString:@""]; //UE_LOG(LogFuse, Log, TEXT("ReceiptData: %s, Purchase State: %i, Price: %s, Currency Code: %s, Purchase Identifier: %s, Transaction Identifier: %s"), *PurchaseInfo.ReceiptData, TransactionState, *FString(Price), *FString(CurrencyCode), *PurchaseInfo.Identifier, *PurchaseInfo.TransactionIdentifier); [FuseSDK registerInAppPurchase:ReceiptData TxState:TransactionState Price:Price Currency:CurrencyCode ProductID:PurchaseInfo.Identifier.GetNSString() TransactionID:PurchaseInfo.TransactionIdentifier.GetNSString()]; }); #endif } #if PLATFORM_IOS @implementation FuseDelegateImpl -(void) sessionStartReceived { UFuseComponent::SessionStartReceivedDelegate.Broadcast(); } -(void) sessionLoginError:(NSError*)_error { UFuseComponent::SessionLoginErrorDelegate.Broadcast((EBPFuseError::Error)[_error code]); } -(void) timeUpdated:(NSNumber*)_utcTimeStamp { UFuseComponent::TimeUpdatedDelegate.Broadcast([_utcTimeStamp intValue]); } -(void) accountLoginComplete:(NSNumber*)_type Account:(NSString*)_account_id { UFuseComponent::AccountLoginCompleteDelegate.Broadcast([_type intValue],FString(_account_id)); } -(void) account:(NSString*)_account_id loginError:(NSError*)_error { UFuseComponent::AccountLoginErrorDelegate.Broadcast(FString(_account_id),(EBPFuseError::Error)[_error code]); } -(void) notificationAction:(NSString*)_action { UFuseComponent::NotificationActionDelegate.Broadcast(FString(_action)); } -(void) notficationWillClose { UFuseComponent::NotificationWillCloseDelegate.Broadcast(); } -(void) gameConfigurationReceived { UFuseComponent::GameConfigurationReceivedDelegate.Broadcast(); } -(void) friendAdded:(NSString*)_fuse_id Error:(NSError*)_error { UFuseComponent::FriendAddedDelegate.Broadcast(FString(_fuse_id),(EBPFuseError::Error)[_error code]); } -(void) friendRemoved:(NSString*)_fuse_id Error:(NSError*)_error { UFuseComponent::FriendRemovedDelegate.Broadcast(FString(_fuse_id),(EBPFuseError::Error)[_error code]); } -(void) friendAccepted:(NSString*)_fuse_id Error:(NSError*)_error { UFuseComponent::FriendAcceptedDelegate.Broadcast(FString(_fuse_id),(EBPFuseError::Error)[_error code]); } -(void) friendRejected:(NSString*)_fuse_id Error:(NSError*)_error { UFuseComponent::FriendRejectedDelegate.Broadcast(FString(_fuse_id),(EBPFuseError::Error)[_error code]); } -(void) friendsMigrated:(NSString*)_fuse_id Error:(NSError*)_error { UFuseComponent::FriendsMigratedDelegate.Broadcast(FString(_fuse_id),(EBPFuseError::Error)[_error code]); } -(void) friendsListUpdated:(NSDictionary*)_friendsList { } -(void) friendsListError:(NSError*)_error { UFuseComponent::FriendsListErrorDelegate.Broadcast((EBPFuseError::Error)[_error code]); } -(void) purchaseVerification:(NSNumber*)_verified TransactionID:(NSString*)_tx_id OriginalTransactionID:(NSString*)_o_tx_id { UFuseComponent::PurchaseVerificationDelegate.Broadcast([_verified boolValue],FString(_tx_id),FString(_o_tx_id)); } -(void) adAvailabilityResponse:(NSNumber*)_available Error:(NSError*)_error { UFuseComponent::AdAvailabilityResponseDelegate.Broadcast([_available boolValue],(EBPFuseError::Error)[_error code]); } -(void) rewardedAdCompleteWithObject:(FuseRewardedObject*) _reward { UFuseComponent::RewardedAdCompleteDelegate.Broadcast(FFuseRewardedObject(FString(_reward.preRollMessage), FString(_reward.rewardMessage), FString(_reward.rewardItem), [_reward.rewardAmount intValue])); } -(void) IAPOfferAcceptedWithObject:(FuseIAPOfferObject*) _offer { UFuseComponent::IAPOfferAcceptedDelegate.Broadcast(FFuseIAPOfferObject(FString(_offer.productID), [_offer.productPrice floatValue], FString(_offer.itemName), [_offer.itemAmount intValue])); } -(void) virtualGoodsOfferAcceptedWithObject:(FuseVirtualGoodsOfferObject*) _offer { UFuseComponent::VirtualGoodsOfferAcceptedDelegate.Broadcast(FFuseVirtualGoodsOfferObject(FString(_offer.purchaseCurrency), [_offer.purchasePrice floatValue], FString(_offer.itemName), [_offer.itemAmount intValue])); } -(void) adFailedToDisplay { UFuseComponent::AdFailedToDisplayDelegate.Broadcast(); } -(void) adWillClose { UFuseComponent::AdWillCloseDelegate.Broadcast(); } @end #endif<|endoftext|>
<commit_before>#include <plugins/interactive/InteractiveObject.h> namespace beliefstate { InteractiveObject::InteractiveObject(string strName) { m_imsServer = NULL; m_imMarker.header.frame_id = "/map"; m_imMarker.scale = 1; m_imMarker.name = strName; m_mkrMarker.type = Marker::CUBE; m_mkrMarker.scale.x = m_imMarker.scale * 0.45; m_mkrMarker.scale.y = m_imMarker.scale * 0.45; m_mkrMarker.scale.z = m_imMarker.scale * 0.45; m_mkrMarker.color.r = 0.5; m_mkrMarker.color.g = 0.5; m_mkrMarker.color.b = 0.5; m_mkrMarker.color.a = 1.0; } InteractiveObject::~InteractiveObject() { } void InteractiveObject::setSize(float fWidth, float fDepth, float fHeight) { m_mkrMarker.scale.x = m_imMarker.scale * fWidth; m_mkrMarker.scale.y = m_imMarker.scale * fDepth; m_mkrMarker.scale.z = m_imMarker.scale * fHeight; this->insertIntoServer(m_imsServer); } void InteractiveObject::setPose(string strFixedFrame, geometry_msgs::Pose posPose) { m_imMarker.header.frame_id = strFixedFrame; m_imMarker.pose = posPose; this->insertIntoServer(m_imsServer); } void InteractiveObject::setPose(geometry_msgs::Pose posPose) { this->setPose(m_imMarker.header.frame_id, posPose); } void InteractiveObject::setMarker(visualization_msgs::Marker mkrMarker) { m_mkrMarker = mkrMarker; this->insertIntoServer(m_imsServer); } void InteractiveObject::clickCallback(const visualization_msgs::InteractiveMarkerFeedbackConstPtr &feedback) { MenuHandler::EntryHandle entHandle = feedback->menu_entry_id; bool bFound = false; InteractiveMenuEntry imeEntry; for(list<InteractiveMenuEntry>::iterator itIME = m_lstMenuEntries.begin(); itIME != m_lstMenuEntries.end(); itIME++) { if((*itIME).unMenuEntryID == entHandle) { imeEntry = *itIME; bFound = true; break; } } if(bFound) { // Send out the symbolic event containing the callback result. InteractiveObjectCallbackResult iocrResult; iocrResult.strObject = feedback->marker_name; iocrResult.strCommand = imeEntry.strIdentifier; iocrResult.strParameter = imeEntry.strParameter; m_mtxCallbackResults.lock(); m_lstCallbackResults.push_back(iocrResult); m_mtxCallbackResults.unlock(); } } bool InteractiveObject::insertIntoServer(InteractiveMarkerServer* imsServer) { if(ros::ok()) { if(imsServer) { m_imcControl.interaction_mode = InteractiveMarkerControl::BUTTON; m_imcControl.always_visible = true; m_imcControl.markers.clear(); m_imcControl.markers.push_back(m_mkrMarker); m_imMarker.controls.clear(); m_imMarker.controls.push_back(m_imcControl); imsServer->insert(m_imMarker); m_mhMenu.apply(*imsServer, m_imMarker.name); imsServer->applyChanges(); m_imsServer = imsServer; return true; } } return false; } bool InteractiveObject::removeFromServer() { if(m_imsServer) { m_imsServer->erase(m_imMarker.name); m_imsServer->applyChanges(); return true; } return false; } string InteractiveObject::name() { return m_imMarker.name; } void InteractiveObject::addMenuEntry(string strLabel, string strIdentifier, string strParameter) { InteractiveMenuEntry imeEntry; imeEntry.strLabel = strLabel; imeEntry.strIdentifier = strIdentifier; imeEntry.strParameter = strParameter; MenuHandler::EntryHandle entEntry = m_mhMenu.insert(strLabel, boost::bind(&InteractiveObject::clickCallback, this, _1)); m_mhMenu.setCheckState(entEntry, MenuHandler::NO_CHECKBOX); imeEntry.unMenuEntryID = entEntry; m_lstMenuEntries.push_back(imeEntry); if(m_imsServer) { this->insertIntoServer(m_imsServer); } } void InteractiveObject::clearMenuEntries() { MenuHandler mhMenu; m_lstMenuEntries.clear(); m_mhMenu = mhMenu; if(m_imsServer) { this->insertIntoServer(m_imsServer); } } void InteractiveObject::removeMenuEntry(string strIdentifier, string strParameter) { MenuHandler mhMenu; for(list<InteractiveMenuEntry>::iterator itIME = m_lstMenuEntries.begin(); itIME != m_lstMenuEntries.end(); itIME++) { if((*itIME).strIdentifier == strIdentifier && (*itIME).strParameter == strParameter) { m_lstMenuEntries.erase(itIME); break; } } for(list<InteractiveMenuEntry>::iterator itIME = m_lstMenuEntries.begin(); itIME != m_lstMenuEntries.end(); itIME++) { MenuHandler::EntryHandle entEntry = m_mhMenu.insert((*itIME).strLabel, boost::bind(&InteractiveObject::clickCallback, this, _1)); m_mhMenu.setCheckState(entEntry, MenuHandler::NO_CHECKBOX); } m_mhMenu = mhMenu; if(m_imsServer) { this->insertIntoServer(m_imsServer); } } list<InteractiveObjectCallbackResult> InteractiveObject::callbackResults() { list<InteractiveObjectCallbackResult> lstResults; m_mtxCallbackResults.lock(); lstResults = m_lstCallbackResults; m_lstCallbackResults.clear(); m_mtxCallbackResults.unlock(); return lstResults; } } <commit_msg>Check for ROS availability before removing interactive objects from the server<commit_after>#include <plugins/interactive/InteractiveObject.h> namespace beliefstate { InteractiveObject::InteractiveObject(string strName) { m_imsServer = NULL; m_imMarker.header.frame_id = "/map"; m_imMarker.scale = 1; m_imMarker.name = strName; m_mkrMarker.type = Marker::CUBE; m_mkrMarker.scale.x = m_imMarker.scale * 0.45; m_mkrMarker.scale.y = m_imMarker.scale * 0.45; m_mkrMarker.scale.z = m_imMarker.scale * 0.45; m_mkrMarker.color.r = 0.5; m_mkrMarker.color.g = 0.5; m_mkrMarker.color.b = 0.5; m_mkrMarker.color.a = 1.0; } InteractiveObject::~InteractiveObject() { } void InteractiveObject::setSize(float fWidth, float fDepth, float fHeight) { m_mkrMarker.scale.x = m_imMarker.scale * fWidth; m_mkrMarker.scale.y = m_imMarker.scale * fDepth; m_mkrMarker.scale.z = m_imMarker.scale * fHeight; this->insertIntoServer(m_imsServer); } void InteractiveObject::setPose(string strFixedFrame, geometry_msgs::Pose posPose) { m_imMarker.header.frame_id = strFixedFrame; m_imMarker.pose = posPose; this->insertIntoServer(m_imsServer); } void InteractiveObject::setPose(geometry_msgs::Pose posPose) { this->setPose(m_imMarker.header.frame_id, posPose); } void InteractiveObject::setMarker(visualization_msgs::Marker mkrMarker) { m_mkrMarker = mkrMarker; this->insertIntoServer(m_imsServer); } void InteractiveObject::clickCallback(const visualization_msgs::InteractiveMarkerFeedbackConstPtr &feedback) { MenuHandler::EntryHandle entHandle = feedback->menu_entry_id; bool bFound = false; InteractiveMenuEntry imeEntry; for(list<InteractiveMenuEntry>::iterator itIME = m_lstMenuEntries.begin(); itIME != m_lstMenuEntries.end(); itIME++) { if((*itIME).unMenuEntryID == entHandle) { imeEntry = *itIME; bFound = true; break; } } if(bFound) { // Send out the symbolic event containing the callback result. InteractiveObjectCallbackResult iocrResult; iocrResult.strObject = feedback->marker_name; iocrResult.strCommand = imeEntry.strIdentifier; iocrResult.strParameter = imeEntry.strParameter; m_mtxCallbackResults.lock(); m_lstCallbackResults.push_back(iocrResult); m_mtxCallbackResults.unlock(); } } bool InteractiveObject::insertIntoServer(InteractiveMarkerServer* imsServer) { if(ros::ok()) { if(imsServer) { m_imcControl.interaction_mode = InteractiveMarkerControl::BUTTON; m_imcControl.always_visible = true; m_imcControl.markers.clear(); m_imcControl.markers.push_back(m_mkrMarker); m_imMarker.controls.clear(); m_imMarker.controls.push_back(m_imcControl); imsServer->insert(m_imMarker); m_mhMenu.apply(*imsServer, m_imMarker.name); imsServer->applyChanges(); m_imsServer = imsServer; return true; } } return false; } bool InteractiveObject::removeFromServer() { if(ros::ok()) { if(m_imsServer) { m_imsServer->erase(m_imMarker.name); m_imsServer->applyChanges(); return true; } } return false; } string InteractiveObject::name() { return m_imMarker.name; } void InteractiveObject::addMenuEntry(string strLabel, string strIdentifier, string strParameter) { InteractiveMenuEntry imeEntry; imeEntry.strLabel = strLabel; imeEntry.strIdentifier = strIdentifier; imeEntry.strParameter = strParameter; MenuHandler::EntryHandle entEntry = m_mhMenu.insert(strLabel, boost::bind(&InteractiveObject::clickCallback, this, _1)); m_mhMenu.setCheckState(entEntry, MenuHandler::NO_CHECKBOX); imeEntry.unMenuEntryID = entEntry; m_lstMenuEntries.push_back(imeEntry); if(m_imsServer) { this->insertIntoServer(m_imsServer); } } void InteractiveObject::clearMenuEntries() { MenuHandler mhMenu; m_lstMenuEntries.clear(); m_mhMenu = mhMenu; if(m_imsServer) { this->insertIntoServer(m_imsServer); } } void InteractiveObject::removeMenuEntry(string strIdentifier, string strParameter) { MenuHandler mhMenu; for(list<InteractiveMenuEntry>::iterator itIME = m_lstMenuEntries.begin(); itIME != m_lstMenuEntries.end(); itIME++) { if((*itIME).strIdentifier == strIdentifier && (*itIME).strParameter == strParameter) { m_lstMenuEntries.erase(itIME); break; } } for(list<InteractiveMenuEntry>::iterator itIME = m_lstMenuEntries.begin(); itIME != m_lstMenuEntries.end(); itIME++) { MenuHandler::EntryHandle entEntry = m_mhMenu.insert((*itIME).strLabel, boost::bind(&InteractiveObject::clickCallback, this, _1)); m_mhMenu.setCheckState(entEntry, MenuHandler::NO_CHECKBOX); } m_mhMenu = mhMenu; if(m_imsServer) { this->insertIntoServer(m_imsServer); } } list<InteractiveObjectCallbackResult> InteractiveObject::callbackResults() { list<InteractiveObjectCallbackResult> lstResults; m_mtxCallbackResults.lock(); lstResults = m_lstCallbackResults; m_lstCallbackResults.clear(); m_mtxCallbackResults.unlock(); return lstResults; } } <|endoftext|>
<commit_before>/******************************************************************************* * Copyright 2016 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #ifndef _XOPEN_SOURCE_EXTENDED #define _XOPEN_SOURCE_EXTENDED 1 #endif #if defined(_ZOS) #include <unistd.h> #endif #include "ibmras/monitoring/AgentExtensions.h" #include "Typesdef.h" #include "v8.h" #include "nan.h" #include <cstring> #include <sstream> #include <string> #include <sys/time.h> #define DEFAULT_CAPACITY 10240 #define NODEZMEMPLUGIN_DECL #define MEMORY_INTERVAL 2000 namespace plugin { agentCoreFunctions api; uint32 provid = 0; bool timingOK; uv_timer_t *timer; } using namespace v8; // Constant strings for message composition const std::string COMMA = ","; const std::string EQUALS = "="; const std::string MEMORY_SOURCE = "MemorySource"; const std::string TOTAL_MEMORY = "totalphysicalmemory"; const std::string PHYSICAL_MEMORY = "physicalmemory"; const std::string PRIVATE_MEMORY = "privatememory"; const std::string VIRTUAL_MEMORY = "virtualmemory"; const std::string FREE_PHYSICAL_MEMORY = "freephysicalmemory"; const std::string TOTAL_PHYSICAL_MEMORY = "totalphysicalmemory"; static std::string asciiString(std::string s) { #if defined(_ZOS) char* cp = new char[s.length() + 1]; std::strcpy(cp, s.c_str()); __etoa(cp); std::string returnString (cp); delete[] cp; return returnString; #else return s; #endif } static std::string nativeString(std::string s) { #if defined(_ZOS) char* cp = new char[s.length() + 1]; std::strcpy(cp, s.c_str()); __atoe(cp); std::string returnString (cp); delete[] cp; return returnString; #else return s; #endif } static char* NewCString(const std::string& s) { char *result = new char[s.length() + 1]; std::strcpy(result, s.c_str()); return result; } static void cleanupHandle(uv_handle_t *handle) { delete handle; } static int64 getTime() { struct timeval tv; gettimeofday(&tv, NULL); return ((int64) tv.tv_sec)*1000 + tv.tv_usec/1000; } static int64 getTotalPhysicalMemorySize() { plugin::api.logMessage(loggingLevel::debug, "[memory_node] >>getTotalPhysicalMemorySize()"); Nan::HandleScope scope; Local<Object> global = Nan::GetCurrentContext()->Global(); Local<Object> appmetObject = global->Get(Nan::New<String>(asciiString("Appmetrics")).ToLocalChecked())->ToObject(); Local<Value> totalMemValue = appmetObject->Get(Nan::New<String>(asciiString("getTotalPhysicalMemorySize")).ToLocalChecked()); if (totalMemValue->IsFunction()) { plugin::api.logMessage(loggingLevel::debug, "[memory_node] getTotalPhysicalMemorySize is a function"); } else { plugin::api.logMessage(loggingLevel::debug, "[memory_node] getTotalPhysicalMemorySize is NOT a function"); return -1; } Local<Function> totalMemFunc = Local<Function>::Cast(totalMemValue); Local<Value> args[0]; Local<Value> result = totalMemFunc->Call(global, 0, args); if (result->IsNumber()) { plugin::api.logMessage(loggingLevel::debug, "[memory_node] result of calling getTotalPhysicalMemorySize is a number"); return result->IntegerValue(); } else { plugin::api.logMessage(loggingLevel::debug, "[memory_node] result of calling getTotalPhysicalMemorySize is NOT a number"); return -1; } } static int64 getProcessPhysicalMemorySize() { //TODO: see if we can improve this on z/OS return -1; } static int64 getProcessPrivateMemorySize() { //TODO: see if we can improve this on z/OS return -1; } static int64 getProcessVirtualMemorySize() { //TODO: see if we can improve this on z/OS return -1; } static int64 getFreePhysicalMemorySize() { //TODO: see if we can improve this on z/OS return -1; } static void GetMemoryInformation(uv_timer_s *data) { plugin::api.logMessage(fine, "[memory_node] Getting memory information"); std::stringstream contentss; contentss << MEMORY_SOURCE << COMMA; contentss << getTime() << COMMA; contentss << TOTAL_MEMORY << EQUALS << getTotalPhysicalMemorySize() << COMMA; contentss << PHYSICAL_MEMORY << EQUALS << getProcessPhysicalMemorySize() << COMMA; contentss << PRIVATE_MEMORY << EQUALS << getProcessPrivateMemorySize() << COMMA; contentss << VIRTUAL_MEMORY << EQUALS << getProcessVirtualMemorySize() << COMMA; contentss << FREE_PHYSICAL_MEMORY << EQUALS << getFreePhysicalMemorySize() << std::endl; std::string content = contentss.str(); // Send data plugin::api.logMessage(loggingLevel::debug, "[memory_node] Content of message:"); plugin::api.logMessage(loggingLevel::debug, content.c_str()); plugin::api.logMessage(loggingLevel::debug, "[memory_node] Constructing message object"); monitordata mdata; mdata.persistent = false; mdata.provID = plugin::provid; mdata.sourceID = 0; mdata.size = static_cast<uint32>(content.length()); mdata.data = content.c_str(); plugin::api.agentPushData(&mdata); } pushsource* createPushSource(uint32 srcid, const char* name) { pushsource *src = new pushsource(); src->header.name = name; std::string desc("Memory plugin for Application Metrics for Node.js"); desc.append(name); src->header.description = NewCString(desc); src->header.sourceID = srcid; src->next = NULL; src->header.capacity = DEFAULT_CAPACITY; return src; } extern "C" { NODEZMEMPLUGIN_DECL pushsource* ibmras_monitoring_registerPushSource(agentCoreFunctions api, uint32 provID) { plugin::api = api; plugin::api.logMessage(loggingLevel::debug, "[memory_node] Registering push sources"); pushsource *head = createPushSource(0, "memory_node"); plugin::provid = provID; return head; } NODEZMEMPLUGIN_DECL int ibmras_monitoring_plugin_init(const char* properties) { return 0; } NODEZMEMPLUGIN_DECL int ibmras_monitoring_plugin_start() { plugin::api.logMessage(fine, "[memory_node] Starting"); plugin::timer = new uv_timer_t; uv_timer_init(uv_default_loop(), plugin::timer); uv_unref((uv_handle_t*) plugin::timer); // don't prevent event loop exit uv_timer_start(plugin::timer, GetMemoryInformation, MEMORY_INTERVAL, MEMORY_INTERVAL); return 0; } NODEZMEMPLUGIN_DECL int ibmras_monitoring_plugin_stop() { plugin::api.logMessage(fine, "[memory_node] Stopping"); uv_timer_stop(plugin::timer); uv_close((uv_handle_t*) plugin::timer, cleanupHandle); return 0; } NODEZMEMPLUGIN_DECL const char* ibmras_monitoring_getVersion() { return "1.0"; } } <commit_msg>calculate physical memory used on z/OS (#507)<commit_after>/******************************************************************************* * Copyright 2016 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #ifndef _XOPEN_SOURCE_EXTENDED #define _XOPEN_SOURCE_EXTENDED 1 #endif #if defined(_ZOS) #include <unistd.h> #endif #include "ibmras/monitoring/AgentExtensions.h" #include "Typesdef.h" #include "v8.h" #include "nan.h" #include <cstring> #include <sstream> #include <string> #include <sys/time.h> #define DEFAULT_CAPACITY 10240 #define NODEZMEMPLUGIN_DECL #define MEMORY_INTERVAL 2000 namespace plugin { agentCoreFunctions api; uint32 provid = 0; bool timingOK; uv_timer_t *timer; } using namespace v8; // Constant strings for message composition const std::string COMMA = ","; const std::string EQUALS = "="; const std::string MEMORY_SOURCE = "MemorySource"; const std::string TOTAL_MEMORY = "totalphysicalmemory"; const std::string PHYSICAL_MEMORY = "physicalmemory"; const std::string PRIVATE_MEMORY = "privatememory"; const std::string VIRTUAL_MEMORY = "virtualmemory"; const std::string FREE_PHYSICAL_MEMORY = "freephysicalmemory"; const std::string TOTAL_PHYSICAL_MEMORY = "totalphysicalmemory"; static std::string asciiString(std::string s) { #if defined(_ZOS) char* cp = new char[s.length() + 1]; std::strcpy(cp, s.c_str()); __etoa(cp); std::string returnString (cp); delete[] cp; return returnString; #else return s; #endif } static std::string nativeString(std::string s) { #if defined(_ZOS) char* cp = new char[s.length() + 1]; std::strcpy(cp, s.c_str()); __atoe(cp); std::string returnString (cp); delete[] cp; return returnString; #else return s; #endif } static char* NewCString(const std::string& s) { char *result = new char[s.length() + 1]; std::strcpy(result, s.c_str()); return result; } static void cleanupHandle(uv_handle_t *handle) { delete handle; } static int64 getTime() { struct timeval tv; gettimeofday(&tv, NULL); return ((int64) tv.tv_sec)*1000 + tv.tv_usec/1000; } static int64 getTotalPhysicalMemorySize() { plugin::api.logMessage(loggingLevel::debug, "[memory_node] >>getTotalPhysicalMemorySize()"); Nan::HandleScope scope; Local<Object> global = Nan::GetCurrentContext()->Global(); Local<Object> appmetObject = global->Get(Nan::New<String>(asciiString("Appmetrics")).ToLocalChecked())->ToObject(); Local<Value> totalMemValue = appmetObject->Get(Nan::New<String>(asciiString("getTotalPhysicalMemorySize")).ToLocalChecked()); if (totalMemValue->IsFunction()) { plugin::api.logMessage(loggingLevel::debug, "[memory_node] getTotalPhysicalMemorySize is a function"); } else { plugin::api.logMessage(loggingLevel::debug, "[memory_node] getTotalPhysicalMemorySize is NOT a function"); return -1; } Local<Function> totalMemFunc = Local<Function>::Cast(totalMemValue); Local<Value> args[0]; Local<Value> result = totalMemFunc->Call(global, 0, args); if (result->IsNumber()) { plugin::api.logMessage(loggingLevel::debug, "[memory_node] result of calling getTotalPhysicalMemorySize is a number"); return result->IntegerValue(); } else { plugin::api.logMessage(loggingLevel::debug, "[memory_node] result of calling getTotalPhysicalMemorySize is NOT a number"); return -1; } } static int64 getProcessPhysicalMemorySize() { size_t size; uv_resident_set_memory(&size); return size; } static int64 getProcessPrivateMemorySize() { //TODO: see if we can improve this on z/OS return -1; } static int64 getProcessVirtualMemorySize() { //TODO: see if we can improve this on z/OS return -1; } static int64 getFreePhysicalMemorySize() { //TODO: see if we can improve this on z/OS return -1; } static void GetMemoryInformation(uv_timer_s *data) { plugin::api.logMessage(fine, "[memory_node] Getting memory information"); std::stringstream contentss; contentss << MEMORY_SOURCE << COMMA; contentss << getTime() << COMMA; contentss << TOTAL_MEMORY << EQUALS << getTotalPhysicalMemorySize() << COMMA; contentss << PHYSICAL_MEMORY << EQUALS << getProcessPhysicalMemorySize() << COMMA; contentss << PRIVATE_MEMORY << EQUALS << getProcessPrivateMemorySize() << COMMA; contentss << VIRTUAL_MEMORY << EQUALS << getProcessVirtualMemorySize() << COMMA; contentss << FREE_PHYSICAL_MEMORY << EQUALS << getFreePhysicalMemorySize() << std::endl; std::string content = contentss.str(); // Send data plugin::api.logMessage(loggingLevel::debug, "[memory_node] Content of message:"); plugin::api.logMessage(loggingLevel::debug, content.c_str()); plugin::api.logMessage(loggingLevel::debug, "[memory_node] Constructing message object"); monitordata mdata; mdata.persistent = false; mdata.provID = plugin::provid; mdata.sourceID = 0; mdata.size = static_cast<uint32>(content.length()); mdata.data = content.c_str(); plugin::api.agentPushData(&mdata); } pushsource* createPushSource(uint32 srcid, const char* name) { pushsource *src = new pushsource(); src->header.name = name; std::string desc("Memory plugin for Application Metrics for Node.js"); desc.append(name); src->header.description = NewCString(desc); src->header.sourceID = srcid; src->next = NULL; src->header.capacity = DEFAULT_CAPACITY; return src; } extern "C" { NODEZMEMPLUGIN_DECL pushsource* ibmras_monitoring_registerPushSource(agentCoreFunctions api, uint32 provID) { plugin::api = api; plugin::api.logMessage(loggingLevel::debug, "[memory_node] Registering push sources"); pushsource *head = createPushSource(0, "memory_node"); plugin::provid = provID; return head; } NODEZMEMPLUGIN_DECL int ibmras_monitoring_plugin_init(const char* properties) { return 0; } NODEZMEMPLUGIN_DECL int ibmras_monitoring_plugin_start() { plugin::api.logMessage(fine, "[memory_node] Starting"); plugin::timer = new uv_timer_t; uv_timer_init(uv_default_loop(), plugin::timer); uv_unref((uv_handle_t*) plugin::timer); // don't prevent event loop exit uv_timer_start(plugin::timer, GetMemoryInformation, MEMORY_INTERVAL, MEMORY_INTERVAL); return 0; } NODEZMEMPLUGIN_DECL int ibmras_monitoring_plugin_stop() { plugin::api.logMessage(fine, "[memory_node] Stopping"); uv_timer_stop(plugin::timer); uv_close((uv_handle_t*) plugin::timer, cleanupHandle); return 0; } NODEZMEMPLUGIN_DECL const char* ibmras_monitoring_getVersion() { return "1.0"; } } <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2013, Institute for Artificial Intelligence, * Universität Bremen. * 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 Institute for Artificial Intelligence, * Universität Bremen, nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /** \author Jan Winkler */ #include <plugins/owlexporter/PluginOWLExporter.h> namespace semrec { namespace plugins { PLUGIN_CLASS::PLUGIN_CLASS() { this->setPluginVersion("0.93"); } PLUGIN_CLASS::~PLUGIN_CLASS() { } Result PLUGIN_CLASS::init(int argc, char** argv) { Result resInit = defaultResult(); this->setSubscribedToEvent("set-experiment-meta-data", true); this->setSubscribedToEvent("export-planlog", true); this->setSubscribedToEvent("experiment-start", true); this->setSubscribedToEvent("experiment-shutdown", true); this->setSubscribedToEvent("register-owl-namespace", true); this->setSubscribedToEvent("update-absolute-experiment-start-time", true); this->setSubscribedToEvent("update-absolute-experiment-end-time", true); return resInit; } Result PLUGIN_CLASS::deinit() { return defaultResult(); } Result PLUGIN_CLASS::cycle() { Result resCycle = defaultResult(); this->deployCycleData(resCycle); return resCycle; } void PLUGIN_CLASS::consumeEvent(Event evEvent) { if(evEvent.strEventName == "export-planlog") { if(evEvent.cdDesignator) { std::string strFormat = evEvent.cdDesignator->stringValue("format"); transform(strFormat.begin(), strFormat.end(), strFormat.begin(), ::tolower); if(strFormat == "owl") { if(m_mapMetaData.find("time-end") == m_mapMetaData.end()) { //m_mapMetaData["time-end"] = this->getTimeStampStr(); } ServiceEvent seGetPlanTree = defaultServiceEvent("symbolic-plan-tree"); seGetPlanTree.cdDesignator = new Designator(evEvent.cdDesignator); this->deployServiceEvent(seGetPlanTree); } } } else if(evEvent.strEventName == "experiment-start") { Event evSendOwlExporterVersion = defaultEvent("set-experiment-meta-data"); evSendOwlExporterVersion.cdDesignator = new Designator(); evSendOwlExporterVersion.cdDesignator->setType(Designator::DesignatorType::ACTION); evSendOwlExporterVersion.cdDesignator->setValue("field", "owl-exporter-version"); evSendOwlExporterVersion.cdDesignator->setValue("value", this->pluginVersion()); //m_mapRegisteredOWLNamespaces.clear(); this->deployEvent(evSendOwlExporterVersion); //m_mapMetaData["time-start"] = this->getTimeStampStr(); } else if(evEvent.strEventName == "experiment-shutdown") { //m_mapMetaData["time-end"] = this->getTimeStampStr(); } else if(evEvent.strEventName == "set-experiment-meta-data") { if(evEvent.cdDesignator) { std::string strField = evEvent.cdDesignator->stringValue("field"); std::string strValue = evEvent.cdDesignator->stringValue("value"); if(strField != "") { this->info("Set meta data field '" + strField + "' to '" + strValue + "'"); m_mapMetaData[strField] = strValue; } } } else if(evEvent.strEventName == "register-owl-namespace") { if(evEvent.cdDesignator) { std::string strShortcut = evEvent.cdDesignator->stringValue("shortcut"); std::string strIRI = evEvent.cdDesignator->stringValue("iri"); if(strIRI != "" && strShortcut != "") { m_mapRegisteredOWLNamespaces[strShortcut] = strIRI; this->info("Registered OWL namespace: '" + strShortcut + "' = '" + strIRI + "'"); } else { this->warn("Did not register OWL namespace. Insufficient information: '" + strShortcut + "' = '" + strIRI + "'"); } } } else if(evEvent.strEventName == "update-absolute-experiment-start-time") { if(evEvent.lstNodes.size() > 0) { if(m_mapMetaData.find("time-start") == m_mapMetaData.end()) { // First entry m_mapMetaData["time-start"] = evEvent.lstNodes.front()->metaInformation()->stringValue("time-start"); } else { // Update if necessary std::string strOld = m_mapMetaData["time-start"]; std::string strNew = evEvent.lstNodes.front()->metaInformation()->stringValue("time-start"); float fOld, fNew; sscanf(strOld.c_str(), "%f", &fOld); sscanf(strNew.c_str(), "%f", &fNew); if(fNew < fOld) { m_mapMetaData["time-start"] = strNew; } } } } else if(evEvent.strEventName == "update-absolute-experiment-end-time") { if(evEvent.lstNodes.size() > 0) { // Every end time overwrites any already existing value, as // it always happens after. if(m_mapMetaData.find("time-end") == m_mapMetaData.end()) { m_mapMetaData["time-end"] = evEvent.lstNodes.front()->metaInformation()->stringValue("time-end"); } else { // Update if necessary std::string strOld = m_mapMetaData["time-end"]; std::string strNew = evEvent.lstNodes.front()->metaInformation()->stringValue("time-end"); float fOld, fNew; sscanf(strOld.c_str(), "%f", &fOld); sscanf(strNew.c_str(), "%f", &fNew); if(fNew > fOld) { m_mapMetaData["time-end"] = strNew; } } } } } Event PLUGIN_CLASS::consumeServiceEvent(ServiceEvent seServiceEvent) { Event evResult = defaultEvent(); if(seServiceEvent.siServiceIdentifier == SI_RESPONSE) { if(seServiceEvent.strServiceName == "symbolic-plan-tree") { if(seServiceEvent.cdDesignator) { if(seServiceEvent.lstResultEvents.size() > 0) { Event evCar = seServiceEvent.lstResultEvents.front(); std::string strFormat = seServiceEvent.cdDesignator->stringValue("format"); transform(strFormat.begin(), strFormat.end(), strFormat.begin(), ::tolower); if(strFormat == "owl") { this->info("OWLExporter Plugin received plan log data. Exporting symbolic log."); CExporterOwl* expOwl = new CExporterOwl(); expOwl->setMetaData(m_mapMetaData); Designator* cdConfig = this->getIndividualConfig(); std::string strSemanticsDescriptorFile = cdConfig->stringValue("semantics-descriptor-file"); if(strSemanticsDescriptorFile != "") { this->info("Loading semantics descriptor file '" + strSemanticsDescriptorFile + "'"); if(expOwl->loadSemanticsDescriptorFile(strSemanticsDescriptorFile) == false) { this->warn("Failed to load semantics descriptor file '" + strSemanticsDescriptorFile + "'."); } } else { this->warn("No semantics descriptor file was specified."); } expOwl->configuration()->setValue(std::string("display-successes"), (int)seServiceEvent.cdDesignator->floatValue("show-successes")); expOwl->configuration()->setValue(std::string("display-failures"), (int)seServiceEvent.cdDesignator->floatValue("show-fails")); expOwl->configuration()->setValue(std::string("max-detail-level"), (int)seServiceEvent.cdDesignator->floatValue("max-detail-level")); expOwl->setRootNodes(evCar.lstRootNodes); bool bFailed = false; for(Node* ndNode : evCar.lstNodes) { if(ndNode) { expOwl->addNode(ndNode); } else { this->fail("One of the nodes received in the plan log data contains invalid data. Cancelling export. Try again at will."); bFailed = true; break; } } if(!bFailed) { this->info("Parameterizing exporter"); expOwl->setDesignatorIDs(evCar.lstDesignatorIDs); expOwl->setDesignatorEquations(evCar.lstEquations); expOwl->setDesignatorEquationTimes(evCar.lstEquationTimes); ConfigSettings cfgsetCurrent = configSettings(); expOwl->setOutputFilename(cfgsetCurrent.strExperimentDirectory + seServiceEvent.cdDesignator->stringValue("filename")); expOwl->setRegisteredOWLNamespaces(m_mapRegisteredOWLNamespaces); this->info("Exporting OWL file to '" + expOwl->outputFilename() + "'", true); if(expOwl->runExporter(NULL)) { this->info("Successfully exported OWL file '" + expOwl->outputFilename() + "'", true); } else { this->warn("Failed to export to OWL file '" + expOwl->outputFilename() + "'", true); } } else { this->warn("Failed to export to OWL file '" + expOwl->outputFilename() + "'", true); } delete expOwl; } } } } } return evResult; } } extern "C" plugins::PLUGIN_CLASS* createInstance() { return new plugins::PLUGIN_CLASS(); } extern "C" void destroyInstance(plugins::PLUGIN_CLASS* icDestroy) { delete icDestroy; } } <commit_msg>Remove old timestamps from OWL exporter when starting a new experiment<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2013, Institute for Artificial Intelligence, * Universität Bremen. * 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 Institute for Artificial Intelligence, * Universität Bremen, nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /** \author Jan Winkler */ #include <plugins/owlexporter/PluginOWLExporter.h> namespace semrec { namespace plugins { PLUGIN_CLASS::PLUGIN_CLASS() { this->setPluginVersion("0.93"); } PLUGIN_CLASS::~PLUGIN_CLASS() { } Result PLUGIN_CLASS::init(int argc, char** argv) { Result resInit = defaultResult(); this->setSubscribedToEvent("set-experiment-meta-data", true); this->setSubscribedToEvent("export-planlog", true); this->setSubscribedToEvent("experiment-start", true); this->setSubscribedToEvent("experiment-shutdown", true); this->setSubscribedToEvent("register-owl-namespace", true); this->setSubscribedToEvent("update-absolute-experiment-start-time", true); this->setSubscribedToEvent("update-absolute-experiment-end-time", true); this->setSubscribedToEvent("start-new-experiment", true); return resInit; } Result PLUGIN_CLASS::deinit() { return defaultResult(); } Result PLUGIN_CLASS::cycle() { Result resCycle = defaultResult(); this->deployCycleData(resCycle); return resCycle; } void PLUGIN_CLASS::consumeEvent(Event evEvent) { if(evEvent.strEventName == "export-planlog") { if(evEvent.cdDesignator) { std::string strFormat = evEvent.cdDesignator->stringValue("format"); transform(strFormat.begin(), strFormat.end(), strFormat.begin(), ::tolower); if(strFormat == "owl") { if(m_mapMetaData.find("time-end") == m_mapMetaData.end()) { //m_mapMetaData["time-end"] = this->getTimeStampStr(); } ServiceEvent seGetPlanTree = defaultServiceEvent("symbolic-plan-tree"); seGetPlanTree.cdDesignator = new Designator(evEvent.cdDesignator); this->deployServiceEvent(seGetPlanTree); } } } else if(evEvent.strEventName == "experiment-start") { Event evSendOwlExporterVersion = defaultEvent("set-experiment-meta-data"); evSendOwlExporterVersion.cdDesignator = new Designator(); evSendOwlExporterVersion.cdDesignator->setType(Designator::DesignatorType::ACTION); evSendOwlExporterVersion.cdDesignator->setValue("field", "owl-exporter-version"); evSendOwlExporterVersion.cdDesignator->setValue("value", this->pluginVersion()); //m_mapRegisteredOWLNamespaces.clear(); this->deployEvent(evSendOwlExporterVersion); //m_mapMetaData["time-start"] = this->getTimeStampStr(); } else if(evEvent.strEventName == "experiment-shutdown") { //m_mapMetaData["time-end"] = this->getTimeStampStr(); } else if(evEvent.strEventName == "set-experiment-meta-data") { if(evEvent.cdDesignator) { std::string strField = evEvent.cdDesignator->stringValue("field"); std::string strValue = evEvent.cdDesignator->stringValue("value"); if(strField != "") { this->info("Set meta data field '" + strField + "' to '" + strValue + "'"); m_mapMetaData[strField] = strValue; } } } else if(evEvent.strEventName == "register-owl-namespace") { if(evEvent.cdDesignator) { std::string strShortcut = evEvent.cdDesignator->stringValue("shortcut"); std::string strIRI = evEvent.cdDesignator->stringValue("iri"); if(strIRI != "" && strShortcut != "") { m_mapRegisteredOWLNamespaces[strShortcut] = strIRI; this->info("Registered OWL namespace: '" + strShortcut + "' = '" + strIRI + "'"); } else { this->warn("Did not register OWL namespace. Insufficient information: '" + strShortcut + "' = '" + strIRI + "'"); } } } else if(evEvent.strEventName == "update-absolute-experiment-start-time") { if(evEvent.lstNodes.size() > 0) { if(m_mapMetaData.find("time-start") == m_mapMetaData.end()) { // First entry m_mapMetaData["time-start"] = evEvent.lstNodes.front()->metaInformation()->stringValue("time-start"); } else { // Update if necessary std::string strOld = m_mapMetaData["time-start"]; std::string strNew = evEvent.lstNodes.front()->metaInformation()->stringValue("time-start"); float fOld, fNew; sscanf(strOld.c_str(), "%f", &fOld); sscanf(strNew.c_str(), "%f", &fNew); if(fNew < fOld) { m_mapMetaData["time-start"] = strNew; } } } } else if(evEvent.strEventName == "update-absolute-experiment-end-time") { if(evEvent.lstNodes.size() > 0) { // Every end time overwrites any already existing value, as // it always happens after. if(m_mapMetaData.find("time-end") == m_mapMetaData.end()) { m_mapMetaData["time-end"] = evEvent.lstNodes.front()->metaInformation()->stringValue("time-end"); } else { // Update if necessary std::string strOld = m_mapMetaData["time-end"]; std::string strNew = evEvent.lstNodes.front()->metaInformation()->stringValue("time-end"); float fOld, fNew; sscanf(strOld.c_str(), "%f", &fOld); sscanf(strNew.c_str(), "%f", &fNew); if(fNew > fOld) { m_mapMetaData["time-end"] = strNew; } } } } else if(evEvent.strEventName == "start-new-experiment") { m_mapMetaData.clear(); } } Event PLUGIN_CLASS::consumeServiceEvent(ServiceEvent seServiceEvent) { Event evResult = defaultEvent(); if(seServiceEvent.siServiceIdentifier == SI_RESPONSE) { if(seServiceEvent.strServiceName == "symbolic-plan-tree") { if(seServiceEvent.cdDesignator) { if(seServiceEvent.lstResultEvents.size() > 0) { Event evCar = seServiceEvent.lstResultEvents.front(); std::string strFormat = seServiceEvent.cdDesignator->stringValue("format"); transform(strFormat.begin(), strFormat.end(), strFormat.begin(), ::tolower); if(strFormat == "owl") { this->info("OWLExporter Plugin received plan log data. Exporting symbolic log."); CExporterOwl* expOwl = new CExporterOwl(); expOwl->setMetaData(m_mapMetaData); Designator* cdConfig = this->getIndividualConfig(); std::string strSemanticsDescriptorFile = cdConfig->stringValue("semantics-descriptor-file"); if(strSemanticsDescriptorFile != "") { this->info("Loading semantics descriptor file '" + strSemanticsDescriptorFile + "'"); if(expOwl->loadSemanticsDescriptorFile(strSemanticsDescriptorFile) == false) { this->warn("Failed to load semantics descriptor file '" + strSemanticsDescriptorFile + "'."); } } else { this->warn("No semantics descriptor file was specified."); } expOwl->configuration()->setValue(std::string("display-successes"), (int)seServiceEvent.cdDesignator->floatValue("show-successes")); expOwl->configuration()->setValue(std::string("display-failures"), (int)seServiceEvent.cdDesignator->floatValue("show-fails")); expOwl->configuration()->setValue(std::string("max-detail-level"), (int)seServiceEvent.cdDesignator->floatValue("max-detail-level")); expOwl->setRootNodes(evCar.lstRootNodes); bool bFailed = false; for(Node* ndNode : evCar.lstNodes) { if(ndNode) { expOwl->addNode(ndNode); } else { this->fail("One of the nodes received in the plan log data contains invalid data. Cancelling export. Try again at will."); bFailed = true; break; } } if(!bFailed) { this->info("Parameterizing exporter"); expOwl->setDesignatorIDs(evCar.lstDesignatorIDs); expOwl->setDesignatorEquations(evCar.lstEquations); expOwl->setDesignatorEquationTimes(evCar.lstEquationTimes); ConfigSettings cfgsetCurrent = configSettings(); expOwl->setOutputFilename(cfgsetCurrent.strExperimentDirectory + seServiceEvent.cdDesignator->stringValue("filename")); expOwl->setRegisteredOWLNamespaces(m_mapRegisteredOWLNamespaces); this->info("Exporting OWL file to '" + expOwl->outputFilename() + "'", true); if(expOwl->runExporter(NULL)) { this->info("Successfully exported OWL file '" + expOwl->outputFilename() + "'", true); } else { this->warn("Failed to export to OWL file '" + expOwl->outputFilename() + "'", true); } } else { this->warn("Failed to export to OWL file '" + expOwl->outputFilename() + "'", true); } delete expOwl; } } } } } return evResult; } } extern "C" plugins::PLUGIN_CLASS* createInstance() { return new plugins::PLUGIN_CLASS(); } extern "C" void destroyInstance(plugins::PLUGIN_CLASS* icDestroy) { delete icDestroy; } } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "qmljseditorplugin.h" #include "qmljshighlighter.h" #include "qmljseditor.h" #include "qmljseditorconstants.h" #include "qmljseditorfactory.h" #include "qmljscodecompletion.h" #include "qmljshoverhandler.h" #include "qmljsmodelmanager.h" #include "qmlfilewizard.h" #include "qmljsoutline.h" #include "qmljspreviewrunner.h" #include "qmljsquickfix.h" #include "qmljs/qmljsicons.h" #include "qmltaskmanager.h" #include "quicktoolbar.h" #include "quicktoolbarsettingspage.h" #include <qmldesigner/qmldesignerconstants.h> #include <coreplugin/icore.h> #include <coreplugin/coreconstants.h> #include <coreplugin/mimedatabase.h> #include <coreplugin/uniqueidmanager.h> #include <coreplugin/fileiconprovider.h> #include <coreplugin/actionmanager/actionmanager.h> #include <coreplugin/actionmanager/actioncontainer.h> #include <coreplugin/actionmanager/command.h> #include <coreplugin/editormanager/editormanager.h> #include <projectexplorer/taskhub.h> #include <extensionsystem/pluginmanager.h> #include <texteditor/fontsettings.h> #include <texteditor/storagesettings.h> #include <texteditor/texteditorconstants.h> #include <texteditor/texteditorsettings.h> #include <texteditor/textfilewizard.h> #include <texteditor/texteditoractionhandler.h> #include <texteditor/completionsupport.h> #include <utils/qtcassert.h> #include <QtCore/QtPlugin> #include <QtCore/QDebug> #include <QtCore/QSettings> #include <QtCore/QDir> #include <QtCore/QCoreApplication> #include <QtCore/QTimer> #include <QtGui/QMenu> #include <QtGui/QAction> using namespace QmlJSEditor; using namespace QmlJSEditor::Internal; using namespace QmlJSEditor::Constants; enum { QUICKFIX_INTERVAL = 20 }; QmlJSEditorPlugin *QmlJSEditorPlugin::m_instance = 0; QmlJSEditorPlugin::QmlJSEditorPlugin() : m_modelManager(0), m_wizard(0), m_editor(0), m_actionHandler(0) { m_instance = this; m_quickFixCollector = 0; m_quickFixTimer = new QTimer(this); m_quickFixTimer->setInterval(20); m_quickFixTimer->setSingleShot(true); connect(m_quickFixTimer, SIGNAL(timeout()), this, SLOT(quickFixNow())); } QmlJSEditorPlugin::~QmlJSEditorPlugin() { removeObject(m_editor); delete m_actionHandler; m_instance = 0; } /*! Copied from cppplugin.cpp */ static inline Core::Command *createSeparator(Core::ActionManager *am, QObject *parent, Core::Context &context, const char *id) { QAction *separator = new QAction(parent); separator->setSeparator(true); return am->registerAction(separator, Core::Id(id), context); } bool QmlJSEditorPlugin::initialize(const QStringList & /*arguments*/, QString *error_message) { Core::ICore *core = Core::ICore::instance(); if (!core->mimeDatabase()->addMimeTypes(QLatin1String(":/qmljseditor/QmlJSEditor.mimetypes.xml"), error_message)) return false; m_modelManager = new ModelManager(this); addAutoReleasedObject(m_modelManager); Core::Context context(QmlJSEditor::Constants::C_QMLJSEDITOR_ID); m_editor = new QmlJSEditorFactory(this); addObject(m_editor); Core::BaseFileWizardParameters wizardParameters(Core::IWizard::FileWizard); wizardParameters.setCategory(QLatin1String(Constants::WIZARD_CATEGORY_QML)); wizardParameters.setDisplayCategory(QCoreApplication::translate("QmlJsEditor", Constants::WIZARD_TR_CATEGORY_QML)); wizardParameters.setDescription(tr("Creates a QML file.")); wizardParameters.setDisplayName(tr("QML File")); wizardParameters.setId(QLatin1String("Q.Qml")); addAutoReleasedObject(new QmlFileWizard(wizardParameters, core)); m_actionHandler = new TextEditor::TextEditorActionHandler(QmlJSEditor::Constants::C_QMLJSEDITOR_ID, TextEditor::TextEditorActionHandler::Format | TextEditor::TextEditorActionHandler::UnCommentSelection | TextEditor::TextEditorActionHandler::UnCollapseAll); m_actionHandler->initializeActions(); Core::ActionManager *am = core->actionManager(); Core::ActionContainer *contextMenu = am->createMenu(QmlJSEditor::Constants::M_CONTEXT); Core::ActionContainer *qmlToolsMenu = am->createMenu(Core::Id(Constants::M_TOOLS_QML)); QMenu *menu = qmlToolsMenu->menu(); //: QML sub-menu in the Tools menu menu->setTitle(tr("QML")); menu->setEnabled(true); am->actionContainer(Core::Constants::M_TOOLS)->addMenu(qmlToolsMenu); Core::Command *cmd; QAction *followSymbolUnderCursorAction = new QAction(tr("Follow Symbol Under Cursor"), this); cmd = am->registerAction(followSymbolUnderCursorAction, Constants::FOLLOW_SYMBOL_UNDER_CURSOR, context); cmd->setDefaultKeySequence(QKeySequence(Qt::Key_F2)); connect(followSymbolUnderCursorAction, SIGNAL(triggered()), this, SLOT(followSymbolUnderCursor())); contextMenu->addAction(cmd); qmlToolsMenu->addAction(cmd); QAction *findUsagesAction = new QAction(tr("Find Usages"), this); cmd = am->registerAction(findUsagesAction, Constants::FIND_USAGES, context); cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+Shift+U"))); connect(findUsagesAction, SIGNAL(triggered()), this, SLOT(findUsages())); contextMenu->addAction(cmd); qmlToolsMenu->addAction(cmd); QAction *showQuickToolbar = new QAction(tr("Show Qt Quick Toolbar"), this); cmd = am->registerAction(showQuickToolbar, Constants::SHOW_QT_QUICK_HELPER, context); cmd->setDefaultKeySequence(QKeySequence(Qt::CTRL + Qt::ALT + Qt::Key_Space)); connect(showQuickToolbar, SIGNAL(triggered()), this, SLOT(showContextPane())); contextMenu->addAction(cmd); qmlToolsMenu->addAction(cmd); // Insert marker for "Refactoring" menu: Core::Context globalContext(Core::Constants::C_GLOBAL); Core::Command *sep = createSeparator(am, this, globalContext, Constants::SEPARATOR1); sep->action()->setObjectName(Constants::M_REFACTORING_MENU_INSERTION_POINT); contextMenu->addAction(sep); contextMenu->addAction(createSeparator(am, this, globalContext, Constants::SEPARATOR2)); cmd = am->command(TextEditor::Constants::AUTO_INDENT_SELECTION); contextMenu->addAction(cmd); cmd = am->command(TextEditor::Constants::UN_COMMENT_SELECTION); contextMenu->addAction(cmd); CodeCompletion *completion = new CodeCompletion(m_modelManager); addAutoReleasedObject(completion); addAutoReleasedObject(new HoverHandler); // Set completion settings and keep them up to date TextEditor::TextEditorSettings *textEditorSettings = TextEditor::TextEditorSettings::instance(); completion->setCompletionSettings(textEditorSettings->completionSettings()); connect(textEditorSettings, SIGNAL(completionSettingsChanged(TextEditor::CompletionSettings)), completion, SLOT(setCompletionSettings(TextEditor::CompletionSettings))); error_message->clear(); Core::FileIconProvider *iconProvider = Core::FileIconProvider::instance(); iconProvider->registerIconOverlayForSuffix(QIcon(QLatin1String(":/qmljseditor/images/qmlfile.png")), "qml"); m_quickFixCollector = new QmlJSQuickFixCollector; addAutoReleasedObject(m_quickFixCollector); QmlJSQuickFixCollector::registerQuickFixes(this); addAutoReleasedObject(new QmlJSOutlineWidgetFactory); m_qmlTaskManager = new QmlTaskManager; addAutoReleasedObject(m_qmlTaskManager); connect(m_modelManager, SIGNAL(documentChangedOnDisk(QmlJS::Document::Ptr)), m_qmlTaskManager, SLOT(documentChangedOnDisk(QmlJS::Document::Ptr))); connect(m_modelManager, SIGNAL(aboutToRemoveFiles(QStringList)), m_qmlTaskManager, SLOT(documentsRemoved(QStringList))); addAutoReleasedObject(new QuickToolBar); addAutoReleasedObject(new Internal::QuickToolBarSettingsPage); return true; } void QmlJSEditorPlugin::extensionsInitialized() { ProjectExplorer::TaskHub *taskHub = ExtensionSystem::PluginManager::instance()->getObject<ProjectExplorer::TaskHub>(); taskHub->addCategory(Constants::TASK_CATEGORY_QML, tr("QML")); } ExtensionSystem::IPlugin::ShutdownFlag QmlJSEditorPlugin::aboutToShutdown() { delete QmlJS::Icons::instance(); // delete object held by singleton return IPlugin::aboutToShutdown(); } void QmlJSEditorPlugin::initializeEditor(QmlJSEditor::Internal::QmlJSTextEditor *editor) { QTC_ASSERT(m_instance, /**/); m_actionHandler->setupActions(editor); TextEditor::TextEditorSettings::instance()->initializeEditor(editor); // auto completion connect(editor, SIGNAL(requestAutoCompletion(TextEditor::ITextEditable*, bool)), TextEditor::Internal::CompletionSupport::instance(), SLOT(autoComplete(TextEditor::ITextEditable*, bool))); // quick fix connect(editor, SIGNAL(requestQuickFix(TextEditor::ITextEditable*)), this, SLOT(quickFix(TextEditor::ITextEditable*))); } void QmlJSEditorPlugin::followSymbolUnderCursor() { Core::EditorManager *em = Core::EditorManager::instance(); if (QmlJSTextEditor *editor = qobject_cast<QmlJSTextEditor*>(em->currentEditor()->widget())) editor->followSymbolUnderCursor(); } void QmlJSEditorPlugin::findUsages() { Core::EditorManager *em = Core::EditorManager::instance(); if (QmlJSTextEditor *editor = qobject_cast<QmlJSTextEditor*>(em->currentEditor()->widget())) editor->findUsages(); } void QmlJSEditorPlugin::showContextPane() { Core::EditorManager *em = Core::EditorManager::instance(); if (QmlJSTextEditor *editor = qobject_cast<QmlJSTextEditor*>(em->currentEditor()->widget())) editor->showContextPane(); } Core::Command *QmlJSEditorPlugin::addToolAction(QAction *a, Core::ActionManager *am, Core::Context &context, const QString &name, Core::ActionContainer *c1, const QString &keySequence) { Core::Command *command = am->registerAction(a, name, context); if (!keySequence.isEmpty()) command->setDefaultKeySequence(QKeySequence(keySequence)); c1->addAction(command); return command; } QmlJSQuickFixCollector *QmlJSEditorPlugin::quickFixCollector() const { return m_quickFixCollector; } void QmlJSEditorPlugin::quickFix(TextEditor::ITextEditable *editable) { m_currentTextEditable = editable; quickFixNow(); } void QmlJSEditorPlugin::quickFixNow() { if (! m_currentTextEditable) return; Core::EditorManager *em = Core::EditorManager::instance(); QmlJSTextEditor *currentEditor = qobject_cast<QmlJSTextEditor*>(em->currentEditor()->widget()); if (QmlJSTextEditor *editor = qobject_cast<QmlJSTextEditor*>(m_currentTextEditable->widget())) { if (currentEditor == editor) { if (editor->isOutdated()) { // qDebug() << "TODO: outdated document" << editor->editorRevision() << editor->semanticInfo().revision(); // ### FIXME: m_quickFixTimer->start(QUICKFIX_INTERVAL); m_quickFixTimer->stop(); } else { TextEditor::Internal::CompletionSupport::instance()->quickFix(m_currentTextEditable); } } } } Q_EXPORT_PLUGIN(QmlJSEditorPlugin) <commit_msg>QuickToolbar: fix keyboard shortcut for OS X<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "qmljseditorplugin.h" #include "qmljshighlighter.h" #include "qmljseditor.h" #include "qmljseditorconstants.h" #include "qmljseditorfactory.h" #include "qmljscodecompletion.h" #include "qmljshoverhandler.h" #include "qmljsmodelmanager.h" #include "qmlfilewizard.h" #include "qmljsoutline.h" #include "qmljspreviewrunner.h" #include "qmljsquickfix.h" #include "qmljs/qmljsicons.h" #include "qmltaskmanager.h" #include "quicktoolbar.h" #include "quicktoolbarsettingspage.h" #include <qmldesigner/qmldesignerconstants.h> #include <coreplugin/icore.h> #include <coreplugin/coreconstants.h> #include <coreplugin/mimedatabase.h> #include <coreplugin/uniqueidmanager.h> #include <coreplugin/fileiconprovider.h> #include <coreplugin/actionmanager/actionmanager.h> #include <coreplugin/actionmanager/actioncontainer.h> #include <coreplugin/actionmanager/command.h> #include <coreplugin/editormanager/editormanager.h> #include <projectexplorer/taskhub.h> #include <extensionsystem/pluginmanager.h> #include <texteditor/fontsettings.h> #include <texteditor/storagesettings.h> #include <texteditor/texteditorconstants.h> #include <texteditor/texteditorsettings.h> #include <texteditor/textfilewizard.h> #include <texteditor/texteditoractionhandler.h> #include <texteditor/completionsupport.h> #include <utils/qtcassert.h> #include <QtCore/QtPlugin> #include <QtCore/QDebug> #include <QtCore/QSettings> #include <QtCore/QDir> #include <QtCore/QCoreApplication> #include <QtCore/QTimer> #include <QtGui/QMenu> #include <QtGui/QAction> using namespace QmlJSEditor; using namespace QmlJSEditor::Internal; using namespace QmlJSEditor::Constants; enum { QUICKFIX_INTERVAL = 20 }; QmlJSEditorPlugin *QmlJSEditorPlugin::m_instance = 0; QmlJSEditorPlugin::QmlJSEditorPlugin() : m_modelManager(0), m_wizard(0), m_editor(0), m_actionHandler(0) { m_instance = this; m_quickFixCollector = 0; m_quickFixTimer = new QTimer(this); m_quickFixTimer->setInterval(20); m_quickFixTimer->setSingleShot(true); connect(m_quickFixTimer, SIGNAL(timeout()), this, SLOT(quickFixNow())); } QmlJSEditorPlugin::~QmlJSEditorPlugin() { removeObject(m_editor); delete m_actionHandler; m_instance = 0; } /*! Copied from cppplugin.cpp */ static inline Core::Command *createSeparator(Core::ActionManager *am, QObject *parent, Core::Context &context, const char *id) { QAction *separator = new QAction(parent); separator->setSeparator(true); return am->registerAction(separator, Core::Id(id), context); } bool QmlJSEditorPlugin::initialize(const QStringList & /*arguments*/, QString *error_message) { Core::ICore *core = Core::ICore::instance(); if (!core->mimeDatabase()->addMimeTypes(QLatin1String(":/qmljseditor/QmlJSEditor.mimetypes.xml"), error_message)) return false; m_modelManager = new ModelManager(this); addAutoReleasedObject(m_modelManager); Core::Context context(QmlJSEditor::Constants::C_QMLJSEDITOR_ID); m_editor = new QmlJSEditorFactory(this); addObject(m_editor); Core::BaseFileWizardParameters wizardParameters(Core::IWizard::FileWizard); wizardParameters.setCategory(QLatin1String(Constants::WIZARD_CATEGORY_QML)); wizardParameters.setDisplayCategory(QCoreApplication::translate("QmlJsEditor", Constants::WIZARD_TR_CATEGORY_QML)); wizardParameters.setDescription(tr("Creates a QML file.")); wizardParameters.setDisplayName(tr("QML File")); wizardParameters.setId(QLatin1String("Q.Qml")); addAutoReleasedObject(new QmlFileWizard(wizardParameters, core)); m_actionHandler = new TextEditor::TextEditorActionHandler(QmlJSEditor::Constants::C_QMLJSEDITOR_ID, TextEditor::TextEditorActionHandler::Format | TextEditor::TextEditorActionHandler::UnCommentSelection | TextEditor::TextEditorActionHandler::UnCollapseAll); m_actionHandler->initializeActions(); Core::ActionManager *am = core->actionManager(); Core::ActionContainer *contextMenu = am->createMenu(QmlJSEditor::Constants::M_CONTEXT); Core::ActionContainer *qmlToolsMenu = am->createMenu(Core::Id(Constants::M_TOOLS_QML)); QMenu *menu = qmlToolsMenu->menu(); //: QML sub-menu in the Tools menu menu->setTitle(tr("QML")); menu->setEnabled(true); am->actionContainer(Core::Constants::M_TOOLS)->addMenu(qmlToolsMenu); Core::Command *cmd; QAction *followSymbolUnderCursorAction = new QAction(tr("Follow Symbol Under Cursor"), this); cmd = am->registerAction(followSymbolUnderCursorAction, Constants::FOLLOW_SYMBOL_UNDER_CURSOR, context); cmd->setDefaultKeySequence(QKeySequence(Qt::Key_F2)); connect(followSymbolUnderCursorAction, SIGNAL(triggered()), this, SLOT(followSymbolUnderCursor())); contextMenu->addAction(cmd); qmlToolsMenu->addAction(cmd); QAction *findUsagesAction = new QAction(tr("Find Usages"), this); cmd = am->registerAction(findUsagesAction, Constants::FIND_USAGES, context); cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+Shift+U"))); connect(findUsagesAction, SIGNAL(triggered()), this, SLOT(findUsages())); contextMenu->addAction(cmd); qmlToolsMenu->addAction(cmd); QAction *showQuickToolbar = new QAction(tr("Show Qt Quick Toolbar"), this); cmd = am->registerAction(showQuickToolbar, Constants::SHOW_QT_QUICK_HELPER, context); #ifdef Q_WS_MACX cmd->setDefaultKeySequence(QKeySequence(Qt::META + Qt::ALT + Qt::Key_Space)); #else cmd->setDefaultKeySequence(QKeySequence(Qt::CTRL + Qt::ALT + Qt::Key_Space)); #endif connect(showQuickToolbar, SIGNAL(triggered()), this, SLOT(showContextPane())); contextMenu->addAction(cmd); qmlToolsMenu->addAction(cmd); // Insert marker for "Refactoring" menu: Core::Context globalContext(Core::Constants::C_GLOBAL); Core::Command *sep = createSeparator(am, this, globalContext, Constants::SEPARATOR1); sep->action()->setObjectName(Constants::M_REFACTORING_MENU_INSERTION_POINT); contextMenu->addAction(sep); contextMenu->addAction(createSeparator(am, this, globalContext, Constants::SEPARATOR2)); cmd = am->command(TextEditor::Constants::AUTO_INDENT_SELECTION); contextMenu->addAction(cmd); cmd = am->command(TextEditor::Constants::UN_COMMENT_SELECTION); contextMenu->addAction(cmd); CodeCompletion *completion = new CodeCompletion(m_modelManager); addAutoReleasedObject(completion); addAutoReleasedObject(new HoverHandler); // Set completion settings and keep them up to date TextEditor::TextEditorSettings *textEditorSettings = TextEditor::TextEditorSettings::instance(); completion->setCompletionSettings(textEditorSettings->completionSettings()); connect(textEditorSettings, SIGNAL(completionSettingsChanged(TextEditor::CompletionSettings)), completion, SLOT(setCompletionSettings(TextEditor::CompletionSettings))); error_message->clear(); Core::FileIconProvider *iconProvider = Core::FileIconProvider::instance(); iconProvider->registerIconOverlayForSuffix(QIcon(QLatin1String(":/qmljseditor/images/qmlfile.png")), "qml"); m_quickFixCollector = new QmlJSQuickFixCollector; addAutoReleasedObject(m_quickFixCollector); QmlJSQuickFixCollector::registerQuickFixes(this); addAutoReleasedObject(new QmlJSOutlineWidgetFactory); m_qmlTaskManager = new QmlTaskManager; addAutoReleasedObject(m_qmlTaskManager); connect(m_modelManager, SIGNAL(documentChangedOnDisk(QmlJS::Document::Ptr)), m_qmlTaskManager, SLOT(documentChangedOnDisk(QmlJS::Document::Ptr))); connect(m_modelManager, SIGNAL(aboutToRemoveFiles(QStringList)), m_qmlTaskManager, SLOT(documentsRemoved(QStringList))); addAutoReleasedObject(new QuickToolBar); addAutoReleasedObject(new Internal::QuickToolBarSettingsPage); return true; } void QmlJSEditorPlugin::extensionsInitialized() { ProjectExplorer::TaskHub *taskHub = ExtensionSystem::PluginManager::instance()->getObject<ProjectExplorer::TaskHub>(); taskHub->addCategory(Constants::TASK_CATEGORY_QML, tr("QML")); } ExtensionSystem::IPlugin::ShutdownFlag QmlJSEditorPlugin::aboutToShutdown() { delete QmlJS::Icons::instance(); // delete object held by singleton return IPlugin::aboutToShutdown(); } void QmlJSEditorPlugin::initializeEditor(QmlJSEditor::Internal::QmlJSTextEditor *editor) { QTC_ASSERT(m_instance, /**/); m_actionHandler->setupActions(editor); TextEditor::TextEditorSettings::instance()->initializeEditor(editor); // auto completion connect(editor, SIGNAL(requestAutoCompletion(TextEditor::ITextEditable*, bool)), TextEditor::Internal::CompletionSupport::instance(), SLOT(autoComplete(TextEditor::ITextEditable*, bool))); // quick fix connect(editor, SIGNAL(requestQuickFix(TextEditor::ITextEditable*)), this, SLOT(quickFix(TextEditor::ITextEditable*))); } void QmlJSEditorPlugin::followSymbolUnderCursor() { Core::EditorManager *em = Core::EditorManager::instance(); if (QmlJSTextEditor *editor = qobject_cast<QmlJSTextEditor*>(em->currentEditor()->widget())) editor->followSymbolUnderCursor(); } void QmlJSEditorPlugin::findUsages() { Core::EditorManager *em = Core::EditorManager::instance(); if (QmlJSTextEditor *editor = qobject_cast<QmlJSTextEditor*>(em->currentEditor()->widget())) editor->findUsages(); } void QmlJSEditorPlugin::showContextPane() { Core::EditorManager *em = Core::EditorManager::instance(); if (QmlJSTextEditor *editor = qobject_cast<QmlJSTextEditor*>(em->currentEditor()->widget())) editor->showContextPane(); } Core::Command *QmlJSEditorPlugin::addToolAction(QAction *a, Core::ActionManager *am, Core::Context &context, const QString &name, Core::ActionContainer *c1, const QString &keySequence) { Core::Command *command = am->registerAction(a, name, context); if (!keySequence.isEmpty()) command->setDefaultKeySequence(QKeySequence(keySequence)); c1->addAction(command); return command; } QmlJSQuickFixCollector *QmlJSEditorPlugin::quickFixCollector() const { return m_quickFixCollector; } void QmlJSEditorPlugin::quickFix(TextEditor::ITextEditable *editable) { m_currentTextEditable = editable; quickFixNow(); } void QmlJSEditorPlugin::quickFixNow() { if (! m_currentTextEditable) return; Core::EditorManager *em = Core::EditorManager::instance(); QmlJSTextEditor *currentEditor = qobject_cast<QmlJSTextEditor*>(em->currentEditor()->widget()); if (QmlJSTextEditor *editor = qobject_cast<QmlJSTextEditor*>(m_currentTextEditable->widget())) { if (currentEditor == editor) { if (editor->isOutdated()) { // qDebug() << "TODO: outdated document" << editor->editorRevision() << editor->semanticInfo().revision(); // ### FIXME: m_quickFixTimer->start(QUICKFIX_INTERVAL); m_quickFixTimer->stop(); } else { TextEditor::Internal::CompletionSupport::instance()->quickFix(m_currentTextEditable); } } } } Q_EXPORT_PLUGIN(QmlJSEditorPlugin) <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "refactoringchanges.h" #include <coreplugin/editormanager/editormanager.h> #include <extensionsystem/pluginmanager.h> #include <QtCore/QFile> #include <QtCore/QSet> #include <QtGui/QTextBlock> using namespace TextEditor; RefactoringChanges::~RefactoringChanges() {} void RefactoringChanges::createFile(const QString &fileName, const QString &contents) { m_contentsByCreatedFile.insert(fileName, contents); } void RefactoringChanges::changeFile(const QString &fileName, const Utils::ChangeSet &changeSet) { m_changesByFile.insert(fileName, changeSet); } void RefactoringChanges::reindent(const QString &fileName, const Range &range) { m_indentRangesByFile[fileName].append(range); } QStringList RefactoringChanges::apply() { QSet<QString> changed; { // create files foreach (const QString &fileName, m_contentsByCreatedFile.keys()) { BaseTextEditor *editor = editorForNewFile(fileName); if (editor == 0) continue; QTextCursor tc = editor->textCursor(); tc.beginEditBlock(); tc.setPosition(0); tc.insertText(m_contentsByCreatedFile.value(fileName)); foreach (const Range &range, m_indentRangesByFile.value(fileName, QList<Range>())) { QTextCursor indentCursor = editor->textCursor(); indentCursor.setPosition(range.start); indentCursor.setPosition(range.end, QTextCursor::KeepAnchor); editor->indentInsertedText(indentCursor); } tc.endEditBlock(); changed.insert(fileName); } } { // change and indent files foreach (const QString &fileName, m_changesByFile.keys()) { BaseTextEditor *editor = editorForFile(fileName, true); if (editor == 0) continue; QTextCursor tc = editor->textCursor(); tc.beginEditBlock(); typedef QPair<QTextCursor, QTextCursor> CursorPair; QList<CursorPair> cursorPairs; foreach (const Range &range, m_indentRangesByFile.value(fileName, QList<Range>())) { QTextCursor start = editor->textCursor(); QTextCursor end = editor->textCursor(); start.setPosition(range.start); end.setPosition(range.end); cursorPairs.append(qMakePair(start, end)); } QTextCursor changeSetCursor = editor->textCursor(); Utils::ChangeSet changeSet = m_changesByFile.value(fileName); changeSet.apply(&changeSetCursor); foreach (const CursorPair &cursorPair, cursorPairs) { QTextCursor indentCursor = cursorPair.first; indentCursor.setPosition(cursorPair.second.position(), QTextCursor::KeepAnchor); editor->indentInsertedText(indentCursor); } tc.endEditBlock(); changed.insert(fileName); } } { // Indent files which are not changed foreach (const QString &fileName, m_indentRangesByFile.keys()) { BaseTextEditor *editor = editorForFile(fileName); if (editor == 0) continue; if (changed.contains(fileName)) continue; QTextCursor tc = editor->textCursor(); tc.beginEditBlock(); foreach (const Range &range, m_indentRangesByFile.value(fileName, QList<Range>())) { QTextCursor indentCursor = editor->textCursor(); indentCursor.setPosition(range.start); indentCursor.setPosition(range.end, QTextCursor::KeepAnchor); editor->indentInsertedText(indentCursor); } tc.endEditBlock(); changed.insert(fileName); } } { // Delete files // ### } return changed.toList(); } int RefactoringChanges::positionInFile(const QString &fileName, int line, int column) const { if (BaseTextEditor *editor = editorForFile(fileName)) { return editor->document()->findBlockByNumber(line).position() + column; } else { return -1; } } BaseTextEditor *RefactoringChanges::editorForFile(const QString &fileName, bool openIfClosed) { Core::EditorManager *editorManager = Core::EditorManager::instance(); const QList<Core::IEditor *> editors = editorManager->editorsForFileName(fileName); foreach (Core::IEditor *editor, editors) { BaseTextEditor *textEditor = qobject_cast<BaseTextEditor *>(editor->widget()); if (textEditor != 0) return textEditor; } if (!openIfClosed) return 0; Core::IEditor *editor = editorManager->openEditor(fileName, QString(), Core::EditorManager::NoActivate | Core::EditorManager::IgnoreNavigationHistory | Core::EditorManager::NoModeSwitch); return qobject_cast<BaseTextEditor *>(editor->widget()); } BaseTextEditor *RefactoringChanges::editorForNewFile(const QString &fileName) { QFile f(fileName); if (f.exists()) return 0; if (!f.open(QIODevice::Append)) return 0; f.close(); return editorForFile(fileName, true); } <commit_msg>Added workaround for indentation not working when inserting text at the beginning of a range.<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "refactoringchanges.h" #include <coreplugin/editormanager/editormanager.h> #include <extensionsystem/pluginmanager.h> #include <QtCore/QFile> #include <QtCore/QSet> #include <QtGui/QTextBlock> #include <QtCore/QDebug> using namespace TextEditor; RefactoringChanges::~RefactoringChanges() {} void RefactoringChanges::createFile(const QString &fileName, const QString &contents) { m_contentsByCreatedFile.insert(fileName, contents); } void RefactoringChanges::changeFile(const QString &fileName, const Utils::ChangeSet &changeSet) { m_changesByFile.insert(fileName, changeSet); } void RefactoringChanges::reindent(const QString &fileName, const Range &range) { m_indentRangesByFile[fileName].append(range); } QStringList RefactoringChanges::apply() { QSet<QString> changed; { // create files foreach (const QString &fileName, m_contentsByCreatedFile.keys()) { BaseTextEditor *editor = editorForNewFile(fileName); if (editor == 0) continue; QTextCursor tc = editor->textCursor(); tc.beginEditBlock(); tc.setPosition(0); tc.insertText(m_contentsByCreatedFile.value(fileName)); foreach (const Range &range, m_indentRangesByFile.value(fileName, QList<Range>())) { QTextCursor indentCursor = editor->textCursor(); indentCursor.setPosition(range.start); indentCursor.setPosition(range.end, QTextCursor::KeepAnchor); editor->indentInsertedText(indentCursor); } tc.endEditBlock(); changed.insert(fileName); } } { // change and indent files foreach (const QString &fileName, m_changesByFile.keys()) { BaseTextEditor *editor = editorForFile(fileName, true); if (editor == 0) continue; QTextCursor tc = editor->textCursor(); tc.beginEditBlock(); typedef QPair<QTextCursor, QTextCursor> CursorPair; QList<CursorPair> cursorPairs; foreach (const Range &range, m_indentRangesByFile.value(fileName, QList<Range>())) { QTextCursor start = editor->textCursor(); QTextCursor end = editor->textCursor(); // ### workaround for moving the textcursor when inserting text at the beginning of the range. start.setPosition(qMax(0, range.start - 1)); end.setPosition(range.end); cursorPairs.append(qMakePair(start, end)); } QTextCursor changeSetCursor = editor->textCursor(); Utils::ChangeSet changeSet = m_changesByFile.value(fileName); changeSet.apply(&changeSetCursor); foreach (const CursorPair &cursorPair, cursorPairs) { QTextCursor indentCursor = cursorPair.first; indentCursor.setPosition(cursorPair.second.position(), QTextCursor::KeepAnchor); editor->indentInsertedText(indentCursor); } tc.endEditBlock(); changed.insert(fileName); } } { // Indent files which are not changed foreach (const QString &fileName, m_indentRangesByFile.keys()) { BaseTextEditor *editor = editorForFile(fileName); if (editor == 0) continue; if (changed.contains(fileName)) continue; QTextCursor tc = editor->textCursor(); tc.beginEditBlock(); foreach (const Range &range, m_indentRangesByFile.value(fileName, QList<Range>())) { QTextCursor indentCursor = editor->textCursor(); indentCursor.setPosition(range.start); indentCursor.setPosition(range.end, QTextCursor::KeepAnchor); editor->indentInsertedText(indentCursor); } tc.endEditBlock(); changed.insert(fileName); } } { // Delete files // ### } return changed.toList(); } int RefactoringChanges::positionInFile(const QString &fileName, int line, int column) const { if (BaseTextEditor *editor = editorForFile(fileName)) { return editor->document()->findBlockByNumber(line).position() + column; } else { return -1; } } BaseTextEditor *RefactoringChanges::editorForFile(const QString &fileName, bool openIfClosed) { Core::EditorManager *editorManager = Core::EditorManager::instance(); const QList<Core::IEditor *> editors = editorManager->editorsForFileName(fileName); foreach (Core::IEditor *editor, editors) { BaseTextEditor *textEditor = qobject_cast<BaseTextEditor *>(editor->widget()); if (textEditor != 0) return textEditor; } if (!openIfClosed) return 0; Core::IEditor *editor = editorManager->openEditor(fileName, QString(), Core::EditorManager::NoActivate | Core::EditorManager::IgnoreNavigationHistory | Core::EditorManager::NoModeSwitch); return qobject_cast<BaseTextEditor *>(editor->widget()); } BaseTextEditor *RefactoringChanges::editorForNewFile(const QString &fileName) { QFile f(fileName); if (f.exists()) return 0; if (!f.open(QIODevice::Append)) return 0; f.close(); return editorForFile(fileName, true); } <|endoftext|>
<commit_before>// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "SurgSim/Devices/Leap/LeapScaffold.h" #include <boost/thread/mutex.hpp> #include <Leap.h> #include <list> #include "SurgSim/DataStructures/DataGroup.h" #include "SurgSim/DataStructures/DataGroupBuilder.h" #include "SurgSim/Framework/Log.h" #include "SurgSim/Framework/SharedInstance.h" #include "SurgSim/Math/Matrix.h" #include "SurgSim/Math/RigidTransform.h" #include "SurgSim/Math/Vector.h" using SurgSim::Math::RigidTransform3d; using SurgSim::Math::Vector3d; namespace { RigidTransform3d makeRigidTransform(const Leap::Matrix& rotation, const Leap::Vector& translation, bool isRightHanded = true) { Leap::Matrix matrix = rotation; if (!isRightHanded) { matrix.zBasis *= -1.0; } // Convert milimeters to meters matrix.origin = translation * 0.001f; SurgSim::Math::Matrix44d transform; matrix.toArray4x4(transform.data()); return RigidTransform3d(transform.transpose()); } void updateDataGroup(const Leap::Hand& hand, SurgSim::DataStructures::DataGroup* inputData) { static const std::array<std::string, 5> fingerNames = {"Thumb", "IndexFinger", "MiddleFinger", "RingFinger", "SmallFinger"}; static const std::array<std::string, 4> boneNames = {"Metacarpal", "Proximal", "Intermediate", "Distal"}; inputData->poses().set("pose", makeRigidTransform(hand.basis(), hand.palmPosition(), hand.isRight())); std::string name; const Leap::FingerList fingers = hand.fingers(); for (const Leap::Finger& finger : fingers) { for (int boneType = Leap::Bone::TYPE_PROXIMAL; boneType <= Leap::Bone::TYPE_DISTAL; ++boneType) { Leap::Bone bone = finger.bone(static_cast<Leap::Bone::Type>(boneType)); name = fingerNames[finger.type()] + boneNames[boneType]; inputData->poses().set(name, makeRigidTransform(bone.basis(), bone.prevJoint(), hand.isRight())); inputData->scalars().set(name + "Length", bone.length() / 1000.0); inputData->scalars().set(name + "Width", bone.width() / 1000.0); } } } }; namespace SurgSim { namespace Device { class LeapScaffold::Listener : public Leap::Listener { public: Listener() : m_scaffold(LeapScaffold::getOrCreateSharedInstance()), m_logger(SurgSim::Framework::Logger::getLogger("Leap")) { } void onConnect(const Leap::Controller&) override { SURGSIM_LOG_INFO(m_logger) << "Connected to Leap Motion camera"; } void onDisconnect(const Leap::Controller&) override { SURGSIM_LOG_INFO(m_logger) << "Diconnected from Leap Motion camera"; } void onFrame(const Leap::Controller&) override { auto scaffold = m_scaffold.lock(); if (scaffold != nullptr) { scaffold->handleFrame(); } } private: std::weak_ptr<SurgSim::Device::LeapScaffold> m_scaffold; std::shared_ptr<SurgSim::Framework::Logger> m_logger; }; struct LeapScaffold::DeviceData { explicit DeviceData(LeapDevice* device) : deviceObject(device), handId(std::numeric_limits<int32_t>::quiet_NaN()) { } /// The corresponding device object. LeapDevice* const deviceObject; /// A unique id for the hand, assigned by the Leap SDK int32_t handId; }; struct LeapScaffold::StateData { // The SDK's interface to a single Leap Motion Camera Leap::Controller controller; /// A listener that receives updates from the Leap SDK std::unique_ptr<Listener> listener; /// The list of known devices. std::list<std::unique_ptr<DeviceData>> activeDevices; /// The mutex that protects the list of known devices. boost::mutex mutex; }; LeapScaffold::LeapScaffold() : m_state(new StateData), m_trackingMode(LEAP_TRACKING_MODE_DESKTOP), m_logger(SurgSim::Framework::Logger::getLogger("Leap")) { } LeapScaffold::~LeapScaffold() { if (m_state->listener != nullptr) { m_state->controller.removeListener(*m_state->listener); } } bool LeapScaffold::registerDevice(LeapDevice* device) { bool success = true; boost::lock_guard<boost::mutex> lock(m_state->mutex); const std::string deviceName = device->getName(); auto sameName = [&deviceName](const std::unique_ptr<DeviceData>& info) { return info->deviceObject->getName() == deviceName; }; auto found = std::find_if(m_state->activeDevices.cbegin(), m_state->activeDevices.cend(), sameName); if (found == m_state->activeDevices.end()) { std::unique_ptr<DeviceData> info(new DeviceData(device)); success = doRegisterDevice(info.get()); if (success) { SURGSIM_LOG_INFO(m_logger) << "Device " << device->getName() << ": Registered"; m_state->activeDevices.emplace_back(std::move(info)); } else { SURGSIM_LOG_SEVERE(m_logger) << "Device " << device->getName() << ": Not registered"; } } else { SURGSIM_LOG_SEVERE(m_logger) << "Tried to register a device when the same name, '" << device->getName() << "', is already present!"; success = false; } return success; } bool LeapScaffold::doRegisterDevice(DeviceData* info) { if (m_state->listener == nullptr) { m_state->listener = std::unique_ptr<Listener>(new Listener); m_state->controller.addListener(*m_state->listener); } if (info->deviceObject->isProvidingImages()) { m_state->controller.setPolicy(Leap::Controller::PolicyFlag::POLICY_IMAGES); } return true; } bool LeapScaffold::unregisterDevice(const LeapDevice* device) { bool success = true; boost::lock_guard<boost::mutex> lock(m_state->mutex); auto& devices = m_state->activeDevices; if (device->isProvidingImages()) { auto providingImages = [device](const std::unique_ptr<DeviceData>& info) { return info->deviceObject->isProvidingImages(); }; if (std::find_if(devices.begin(), devices.end(), providingImages) == devices.end()) { m_state->controller.clearPolicy(Leap::Controller::PolicyFlag::POLICY_IMAGES); } } auto sameDevice = [device](const std::unique_ptr<DeviceData>& info) { return info->deviceObject == device; }; auto info = std::find_if(devices.begin(), devices.end(), sameDevice); if (info != devices.end()) { devices.erase(info); SURGSIM_LOG_INFO(m_logger) << "Device " << device->getName() << ": Unregistered"; } else { SURGSIM_LOG_SEVERE(m_logger) << "Attempted to release a non-registered device named '" << device->getName() << "."; success = false; } return success; } void LeapScaffold::handleFrame() { updateHandData(); updateImageData(); for (auto& device : m_state->activeDevices) { device->deviceObject->pushInput(); } } void LeapScaffold::updateHandData() { std::list<DeviceData*> unassignedDevices; for (auto& device : m_state->activeDevices) { unassignedDevices.push_back(device.get()); } std::list<Leap::HandList::const_iterator> newHands; Leap::HandList hands = m_state->controller.frame().hands(); for (auto hand = hands.begin(); hand != hands.end(); ++hand) { auto sameHandId = [hand](const std::unique_ptr<DeviceData>& info) { return info->handId == (*hand).id(); }; auto assignedDevice = std::find_if(m_state->activeDevices.begin(), m_state->activeDevices.end(), sameHandId); if (assignedDevice != m_state->activeDevices.end()) { updateDataGroup(*hand, &(*assignedDevice)->deviceObject->getInputData()); unassignedDevices.remove(assignedDevice->get()); } else { newHands.push_back(hand); } } static auto higherConfidence = [](const Leap::HandList::const_iterator &a, const Leap::HandList::const_iterator &b) { return (*a).confidence() > (*b).confidence(); }; newHands.sort(higherConfidence); for (auto& newHand : newHands) { auto sameHandType = [newHand](DeviceData* info) { return (info->deviceObject->getHandType() == HANDTYPE_LEFT) == (*newHand).isLeft(); }; auto unassignedDevice = std::find_if(unassignedDevices.begin(), unassignedDevices.end(), sameHandType); if (unassignedDevice != unassignedDevices.end()) { (*unassignedDevice)->handId = (*newHand).id(); updateDataGroup(*newHand, &(*unassignedDevice)->deviceObject->getInputData()); unassignedDevices.remove(*unassignedDevice); } } for(auto& unassignedDevice : unassignedDevices) { unassignedDevice->deviceObject->getInputData().poses().resetAll(); } } void LeapScaffold::updateImageData() { Leap::ImageList images = m_state->controller.frame().images(); if (!images.isEmpty()) { typedef SurgSim::DataStructures::DataGroup::ImageType ImageType; ImageType leftImage(images[0].width(), images[0].height(), 1, images[0].data()); ImageType rightImage(images[1].width(), images[1].height(), 1, images[1].data()); // scale values to 0..1 leftImage.getAsVector() *= (1.0f / 255.0f); rightImage.getAsVector() *= (1.0f / 255.0f); for (auto& device : m_state->activeDevices) { if (device->deviceObject->isProvidingImages()) { device->deviceObject->getInputData().images().set("left", leftImage); device->deviceObject->getInputData().images().set("right", rightImage); } else { device->deviceObject->getInputData().images().resetAll(); } } } else { for (auto& device : m_state->activeDevices) { device->deviceObject->getInputData().images().resetAll(); } } } std::shared_ptr<LeapScaffold> LeapScaffold::getOrCreateSharedInstance() { static auto creator = []() { return std::shared_ptr<LeapScaffold>(new LeapScaffold); }; static SurgSim::Framework::SharedInstance<LeapScaffold> sharedInstance(creator); return sharedInstance.get(); } SurgSim::DataStructures::DataGroup LeapScaffold::buildDeviceInputData() { SurgSim::DataStructures::DataGroupBuilder builder; builder.addImage("left"); builder.addImage("right"); builder.addPose("pose"); builder.addPose("ThumbProximal"); builder.addPose("ThumbIntermediate"); builder.addPose("ThumbDistal"); builder.addPose("IndexFingerProximal"); builder.addPose("IndexFingerIntermediate"); builder.addPose("IndexFingerDistal"); builder.addPose("MiddleFingerProximal"); builder.addPose("MiddleFingerIntermediate"); builder.addPose("MiddleFingerDistal"); builder.addPose("RingFingerProximal"); builder.addPose("RingFingerIntermediate"); builder.addPose("RingFingerDistal"); builder.addPose("SmallFingerProximal"); builder.addPose("SmallFingerIntermediate"); builder.addPose("SmallFingerDistal"); builder.addScalar("ThumbProximalWidth"); builder.addScalar("ThumbIntermediateWidth"); builder.addScalar("ThumbDistalWidth"); builder.addScalar("IndexFingerProximalWidth"); builder.addScalar("IndexFingerIntermediateWidth"); builder.addScalar("IndexFingerDistalWidth"); builder.addScalar("MiddleFingerProximalWidth"); builder.addScalar("MiddleFingerIntermediateWidth"); builder.addScalar("MiddleFingerDistalWidth"); builder.addScalar("RingFingerProximalWidth"); builder.addScalar("RingFingerIntermediateWidth"); builder.addScalar("RingFingerDistalWidth"); builder.addScalar("SmallFingerProximalWidth"); builder.addScalar("SmallFingerIntermediateWidth"); builder.addScalar("SmallFingerDistalWidth"); builder.addScalar("ThumbProximalLength"); builder.addScalar("ThumbIntermediateLength"); builder.addScalar("ThumbDistalLength"); builder.addScalar("IndexFingerProximalLength"); builder.addScalar("IndexFingerIntermediateLength"); builder.addScalar("IndexFingerDistalLength"); builder.addScalar("MiddleFingerProximalLength"); builder.addScalar("MiddleFingerIntermediateLength"); builder.addScalar("MiddleFingerDistalLength"); builder.addScalar("RingFingerProximalLength"); builder.addScalar("RingFingerIntermediateLength"); builder.addScalar("RingFingerDistalLength"); builder.addScalar("SmallFingerProximalLength"); builder.addScalar("SmallFingerIntermediateLength"); builder.addScalar("SmallFingerDistalLength"); return builder.createData(); } void LeapScaffold::setTrackingMode(LeapTrackingMode mode) { m_trackingMode = mode; if (mode == LEAP_TRACKING_MODE_HMD) { m_state->controller.setPolicy(Leap::Controller::PolicyFlag::POLICY_OPTIMIZE_HMD); } else { m_state->controller.clearPolicy(Leap::Controller::PolicyFlag::POLICY_OPTIMIZE_HMD); } } LeapTrackingMode LeapScaffold::getTrackingMode() const { return(m_trackingMode); } }; // namespace Device }; // namespace SurgSim <commit_msg>Remove unneeded lamda capture in LeapScaffold<commit_after>// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "SurgSim/Devices/Leap/LeapScaffold.h" #include <boost/thread/mutex.hpp> #include <Leap.h> #include <list> #include "SurgSim/DataStructures/DataGroup.h" #include "SurgSim/DataStructures/DataGroupBuilder.h" #include "SurgSim/Framework/Log.h" #include "SurgSim/Framework/SharedInstance.h" #include "SurgSim/Math/Matrix.h" #include "SurgSim/Math/RigidTransform.h" #include "SurgSim/Math/Vector.h" using SurgSim::Math::RigidTransform3d; using SurgSim::Math::Vector3d; namespace { RigidTransform3d makeRigidTransform(const Leap::Matrix& rotation, const Leap::Vector& translation, bool isRightHanded = true) { Leap::Matrix matrix = rotation; if (!isRightHanded) { matrix.zBasis *= -1.0; } // Convert milimeters to meters matrix.origin = translation * 0.001f; SurgSim::Math::Matrix44d transform; matrix.toArray4x4(transform.data()); return RigidTransform3d(transform.transpose()); } void updateDataGroup(const Leap::Hand& hand, SurgSim::DataStructures::DataGroup* inputData) { static const std::array<std::string, 5> fingerNames = {"Thumb", "IndexFinger", "MiddleFinger", "RingFinger", "SmallFinger"}; static const std::array<std::string, 4> boneNames = {"Metacarpal", "Proximal", "Intermediate", "Distal"}; inputData->poses().set("pose", makeRigidTransform(hand.basis(), hand.palmPosition(), hand.isRight())); std::string name; const Leap::FingerList fingers = hand.fingers(); for (const Leap::Finger& finger : fingers) { for (int boneType = Leap::Bone::TYPE_PROXIMAL; boneType <= Leap::Bone::TYPE_DISTAL; ++boneType) { Leap::Bone bone = finger.bone(static_cast<Leap::Bone::Type>(boneType)); name = fingerNames[finger.type()] + boneNames[boneType]; inputData->poses().set(name, makeRigidTransform(bone.basis(), bone.prevJoint(), hand.isRight())); inputData->scalars().set(name + "Length", bone.length() / 1000.0); inputData->scalars().set(name + "Width", bone.width() / 1000.0); } } } }; namespace SurgSim { namespace Device { class LeapScaffold::Listener : public Leap::Listener { public: Listener() : m_scaffold(LeapScaffold::getOrCreateSharedInstance()), m_logger(SurgSim::Framework::Logger::getLogger("Leap")) { } void onConnect(const Leap::Controller&) override { SURGSIM_LOG_INFO(m_logger) << "Connected to Leap Motion camera"; } void onDisconnect(const Leap::Controller&) override { SURGSIM_LOG_INFO(m_logger) << "Diconnected from Leap Motion camera"; } void onFrame(const Leap::Controller&) override { auto scaffold = m_scaffold.lock(); if (scaffold != nullptr) { scaffold->handleFrame(); } } private: std::weak_ptr<SurgSim::Device::LeapScaffold> m_scaffold; std::shared_ptr<SurgSim::Framework::Logger> m_logger; }; struct LeapScaffold::DeviceData { explicit DeviceData(LeapDevice* device) : deviceObject(device), handId(std::numeric_limits<int32_t>::quiet_NaN()) { } /// The corresponding device object. LeapDevice* const deviceObject; /// A unique id for the hand, assigned by the Leap SDK int32_t handId; }; struct LeapScaffold::StateData { // The SDK's interface to a single Leap Motion Camera Leap::Controller controller; /// A listener that receives updates from the Leap SDK std::unique_ptr<Listener> listener; /// The list of known devices. std::list<std::unique_ptr<DeviceData>> activeDevices; /// The mutex that protects the list of known devices. boost::mutex mutex; }; LeapScaffold::LeapScaffold() : m_state(new StateData), m_trackingMode(LEAP_TRACKING_MODE_DESKTOP), m_logger(SurgSim::Framework::Logger::getLogger("Leap")) { } LeapScaffold::~LeapScaffold() { if (m_state->listener != nullptr) { m_state->controller.removeListener(*m_state->listener); } } bool LeapScaffold::registerDevice(LeapDevice* device) { bool success = true; boost::lock_guard<boost::mutex> lock(m_state->mutex); const std::string deviceName = device->getName(); auto sameName = [&deviceName](const std::unique_ptr<DeviceData>& info) { return info->deviceObject->getName() == deviceName; }; auto found = std::find_if(m_state->activeDevices.cbegin(), m_state->activeDevices.cend(), sameName); if (found == m_state->activeDevices.end()) { std::unique_ptr<DeviceData> info(new DeviceData(device)); success = doRegisterDevice(info.get()); if (success) { SURGSIM_LOG_INFO(m_logger) << "Device " << device->getName() << ": Registered"; m_state->activeDevices.emplace_back(std::move(info)); } else { SURGSIM_LOG_SEVERE(m_logger) << "Device " << device->getName() << ": Not registered"; } } else { SURGSIM_LOG_SEVERE(m_logger) << "Tried to register a device when the same name, '" << device->getName() << "', is already present!"; success = false; } return success; } bool LeapScaffold::doRegisterDevice(DeviceData* info) { if (m_state->listener == nullptr) { m_state->listener = std::unique_ptr<Listener>(new Listener); m_state->controller.addListener(*m_state->listener); } if (info->deviceObject->isProvidingImages()) { m_state->controller.setPolicy(Leap::Controller::PolicyFlag::POLICY_IMAGES); } return true; } bool LeapScaffold::unregisterDevice(const LeapDevice* device) { bool success = true; boost::lock_guard<boost::mutex> lock(m_state->mutex); auto& devices = m_state->activeDevices; if (device->isProvidingImages()) { auto providingImages = [](const std::unique_ptr<DeviceData>& info) { return info->deviceObject->isProvidingImages(); }; if (std::find_if(devices.begin(), devices.end(), providingImages) == devices.end()) { m_state->controller.clearPolicy(Leap::Controller::PolicyFlag::POLICY_IMAGES); } } auto sameDevice = [device](const std::unique_ptr<DeviceData>& info) { return info->deviceObject == device; }; auto info = std::find_if(devices.begin(), devices.end(), sameDevice); if (info != devices.end()) { devices.erase(info); SURGSIM_LOG_INFO(m_logger) << "Device " << device->getName() << ": Unregistered"; } else { SURGSIM_LOG_SEVERE(m_logger) << "Attempted to release a non-registered device named '" << device->getName() << "."; success = false; } return success; } void LeapScaffold::handleFrame() { updateHandData(); updateImageData(); for (auto& device : m_state->activeDevices) { device->deviceObject->pushInput(); } } void LeapScaffold::updateHandData() { std::list<DeviceData*> unassignedDevices; for (auto& device : m_state->activeDevices) { unassignedDevices.push_back(device.get()); } std::list<Leap::HandList::const_iterator> newHands; Leap::HandList hands = m_state->controller.frame().hands(); for (auto hand = hands.begin(); hand != hands.end(); ++hand) { auto sameHandId = [hand](const std::unique_ptr<DeviceData>& info) { return info->handId == (*hand).id(); }; auto assignedDevice = std::find_if(m_state->activeDevices.begin(), m_state->activeDevices.end(), sameHandId); if (assignedDevice != m_state->activeDevices.end()) { updateDataGroup(*hand, &(*assignedDevice)->deviceObject->getInputData()); unassignedDevices.remove(assignedDevice->get()); } else { newHands.push_back(hand); } } static auto higherConfidence = [](const Leap::HandList::const_iterator &a, const Leap::HandList::const_iterator &b) { return (*a).confidence() > (*b).confidence(); }; newHands.sort(higherConfidence); for (auto& newHand : newHands) { auto sameHandType = [newHand](DeviceData* info) { return (info->deviceObject->getHandType() == HANDTYPE_LEFT) == (*newHand).isLeft(); }; auto unassignedDevice = std::find_if(unassignedDevices.begin(), unassignedDevices.end(), sameHandType); if (unassignedDevice != unassignedDevices.end()) { (*unassignedDevice)->handId = (*newHand).id(); updateDataGroup(*newHand, &(*unassignedDevice)->deviceObject->getInputData()); unassignedDevices.remove(*unassignedDevice); } } for(auto& unassignedDevice : unassignedDevices) { unassignedDevice->deviceObject->getInputData().poses().resetAll(); } } void LeapScaffold::updateImageData() { Leap::ImageList images = m_state->controller.frame().images(); if (!images.isEmpty()) { typedef SurgSim::DataStructures::DataGroup::ImageType ImageType; ImageType leftImage(images[0].width(), images[0].height(), 1, images[0].data()); ImageType rightImage(images[1].width(), images[1].height(), 1, images[1].data()); // scale values to 0..1 leftImage.getAsVector() *= (1.0f / 255.0f); rightImage.getAsVector() *= (1.0f / 255.0f); for (auto& device : m_state->activeDevices) { if (device->deviceObject->isProvidingImages()) { device->deviceObject->getInputData().images().set("left", leftImage); device->deviceObject->getInputData().images().set("right", rightImage); } else { device->deviceObject->getInputData().images().resetAll(); } } } else { for (auto& device : m_state->activeDevices) { device->deviceObject->getInputData().images().resetAll(); } } } std::shared_ptr<LeapScaffold> LeapScaffold::getOrCreateSharedInstance() { static auto creator = []() { return std::shared_ptr<LeapScaffold>(new LeapScaffold); }; static SurgSim::Framework::SharedInstance<LeapScaffold> sharedInstance(creator); return sharedInstance.get(); } SurgSim::DataStructures::DataGroup LeapScaffold::buildDeviceInputData() { SurgSim::DataStructures::DataGroupBuilder builder; builder.addImage("left"); builder.addImage("right"); builder.addPose("pose"); builder.addPose("ThumbProximal"); builder.addPose("ThumbIntermediate"); builder.addPose("ThumbDistal"); builder.addPose("IndexFingerProximal"); builder.addPose("IndexFingerIntermediate"); builder.addPose("IndexFingerDistal"); builder.addPose("MiddleFingerProximal"); builder.addPose("MiddleFingerIntermediate"); builder.addPose("MiddleFingerDistal"); builder.addPose("RingFingerProximal"); builder.addPose("RingFingerIntermediate"); builder.addPose("RingFingerDistal"); builder.addPose("SmallFingerProximal"); builder.addPose("SmallFingerIntermediate"); builder.addPose("SmallFingerDistal"); builder.addScalar("ThumbProximalWidth"); builder.addScalar("ThumbIntermediateWidth"); builder.addScalar("ThumbDistalWidth"); builder.addScalar("IndexFingerProximalWidth"); builder.addScalar("IndexFingerIntermediateWidth"); builder.addScalar("IndexFingerDistalWidth"); builder.addScalar("MiddleFingerProximalWidth"); builder.addScalar("MiddleFingerIntermediateWidth"); builder.addScalar("MiddleFingerDistalWidth"); builder.addScalar("RingFingerProximalWidth"); builder.addScalar("RingFingerIntermediateWidth"); builder.addScalar("RingFingerDistalWidth"); builder.addScalar("SmallFingerProximalWidth"); builder.addScalar("SmallFingerIntermediateWidth"); builder.addScalar("SmallFingerDistalWidth"); builder.addScalar("ThumbProximalLength"); builder.addScalar("ThumbIntermediateLength"); builder.addScalar("ThumbDistalLength"); builder.addScalar("IndexFingerProximalLength"); builder.addScalar("IndexFingerIntermediateLength"); builder.addScalar("IndexFingerDistalLength"); builder.addScalar("MiddleFingerProximalLength"); builder.addScalar("MiddleFingerIntermediateLength"); builder.addScalar("MiddleFingerDistalLength"); builder.addScalar("RingFingerProximalLength"); builder.addScalar("RingFingerIntermediateLength"); builder.addScalar("RingFingerDistalLength"); builder.addScalar("SmallFingerProximalLength"); builder.addScalar("SmallFingerIntermediateLength"); builder.addScalar("SmallFingerDistalLength"); return builder.createData(); } void LeapScaffold::setTrackingMode(LeapTrackingMode mode) { m_trackingMode = mode; if (mode == LEAP_TRACKING_MODE_HMD) { m_state->controller.setPolicy(Leap::Controller::PolicyFlag::POLICY_OPTIMIZE_HMD); } else { m_state->controller.clearPolicy(Leap::Controller::PolicyFlag::POLICY_OPTIMIZE_HMD); } } LeapTrackingMode LeapScaffold::getTrackingMode() const { return(m_trackingMode); } }; // namespace Device }; // namespace SurgSim <|endoftext|>
<commit_before>/* * linuxWaitingSlot.cpp * * Created on: 12. 10. 2017 * Author: ondra */ #include <fcntl.h> #include <sys/socket.h> #include <unistd.h> #include "../exceptions.h" #include "../mt.h" #include "netEventDispatcher.h" #include "../defer.h" namespace simpleServer { using ondra_shared::defer; static LinuxEventDispatcher::Task empty_task([](AsyncState){},asyncOK); LinuxEventDispatcher::LinuxEventDispatcher() { int fds[2]; if (pipe2(fds, O_CLOEXEC)!=0) { int err = errno; throw SystemException(err,"Failed to call pipe2 (LinuxEventDispatcher)"); } intrHandle = fds[1]; intrWaitHandle = fds[0]; addIntrWaitHandle(); exitFlag = false; } LinuxEventDispatcher::~LinuxEventDispatcher() noexcept { close(intrHandle); close(intrWaitHandle); } template<typename T> void ignore_variable(T) {} LinuxEventDispatcher::Task LinuxEventDispatcher::runQueue() { std::lock_guard<std::mutex> _(queueLock); char b; ignore_variable(::read(intrWaitHandle, &b, 1)); if (!queue.empty()) { const RegReq &r = queue.front(); if (r.ares.socket == 0 && r.ares.socket == 0) { return Task(r.extra.completionFn,asyncOK); } else if (r.extra.completionFn == nullptr) { return findAndCancel(r.ares); } else { addResource(r); queue.pop(); } } return Task(); } LinuxEventDispatcher::Task LinuxEventDispatcher::findAndCancel(const AsyncResource &res) { CompletionFn curFn = nullptr; int cnt = (int)fdmap.size(); for (int i = 0; i < cnt; i++) { if (fdmap[i].fd == res.socket && fdmap[i].events == res.op) { if (curFn ==nullptr) curFn = fdextramap[i].completionFn; else { CompletionFn otherFn = fdextramap[i].completionFn; curFn = [curFn,otherFn](AsyncState st) { curFn(st); otherFn(st); }; } deleteResource(i); --i; --cnt; } } return Task(curFn,asyncCancel); } void LinuxEventDispatcher::addIntrWaitHandle() { RegReq rq; rq.ares = AsyncResource(intrWaitHandle, POLLIN); rq.extra.completionFn = empty_task; rq.extra.timeout = TimePoint::max(); addResource(rq); } void LinuxEventDispatcher::runAsync(const AsyncResource &resource, int timeout, const CompletionFn &complfn) { if (exitFlag || complfn == nullptr) { defer >> std::bind(complfn, asyncCancel); return; } RegReq req; req.ares = resource; req.extra.completionFn = complfn; if (timeout < 0) req.extra.timeout = TimePoint::max(); else req.extra.timeout = TimePoint::clock::now() + std::chrono::milliseconds(timeout); std::lock_guard<std::mutex> _(queueLock); queue.push(req); sendIntr(); } void LinuxEventDispatcher::runAsync(const CustomFn &completion) { if (exitFlag || completion == nullptr) { defer >> completion; return; } RegReq req; req.extra.completionFn = [fn=CustomFn(completion)](AsyncState){fn();}; std::lock_guard<std::mutex> _(queueLock); queue.push(req); sendIntr(); } void LinuxEventDispatcher::addResource(const RegReq &req) { pollfd pfd; pfd.events = req.ares.op; pfd.fd = req.ares.socket; pfd.revents = 0; fdmap.push_back(pfd); fdextramap.push_back(req.extra); if (req.extra.timeout < nextTimeout) nextTimeout = req.extra.timeout; } void LinuxEventDispatcher::deleteResource(int index) { int last = fdmap.size()-1; if (index < last) { std::swap(fdmap[index],fdmap[last]); std::swap(fdextramap[index],fdextramap[last]); } fdmap.resize(last); fdextramap.resize(last); } LinuxEventDispatcher::Task LinuxEventDispatcher::checkEvents(const TimePoint &now, bool finish) { int sz = static_cast<int>(fdmap.size()); if (last_checked >= sz) { if (finish) return Task(); last_checked = 0; nextTimeout = TimePoint::max(); } while (last_checked < sz) { int idx = last_checked++; if (fdmap[idx].revents) { if (fdmap[idx].fd == intrWaitHandle) { Task t = runQueue(); fdmap[idx].revents = 0; if (t != nullptr) return t; } else { Task t(fdextramap[idx].completionFn, asyncOK); deleteResource(idx); --last_checked; return t; } } else if (fdextramap[idx].timeout<=now) { Task t(fdextramap[idx].completionFn, asyncTimeout); deleteResource(idx); --last_checked; return t; } else if (fdextramap[idx].timeout<nextTimeout) { nextTimeout = fdextramap[idx].timeout; } } return Task(); } ///returns true, if the listener doesn't contain any asynchronous task bool LinuxEventDispatcher::empty() const { return fdmap.empty(); } void LinuxEventDispatcher::stop() { exitFlag = true; sendIntr(); } unsigned int LinuxEventDispatcher::getPendingCount() const { return fdmap.size(); } void LinuxEventDispatcher::cancel(const AsyncResource& resource) { RegReq req; req.ares = resource; req.extra.completionFn = nullptr; std::lock_guard<std::mutex> _(queueLock); queue.push(req); sendIntr(); } LinuxEventDispatcher::Task LinuxEventDispatcher::cleanup() { if (!fdmap.empty()) { int idx = fdmap.size()-1; Task t(fdextramap[idx].completionFn, asyncCancel); deleteResource(idx); return t; } else { return Task(); } } LinuxEventDispatcher::Task LinuxEventDispatcher::wait() { if (exitFlag) { return cleanup(); } TimePoint now = std::chrono::steady_clock::now(); Task x = checkEvents(now,true); if (x != nullptr) return x; auto int_ms = std::chrono::duration_cast<std::chrono::milliseconds>(nextTimeout - now); int r = poll(fdmap.data(),fdmap.size(),int_ms.count()); if (r < 0) { int e = errno; if (e != EINTR && e != EAGAIN) throw SystemException(e, "Failed to call poll()"); } else { now = std::chrono::steady_clock::now(); x = checkEvents(now,false); if (x != nullptr) return x; } return empty_task; } void LinuxEventDispatcher::sendIntr() { unsigned char b = 1; int r = ::write(intrHandle, &b, 1); if (r < 0) { throw SystemException(errno); } } PStreamEventDispatcher AbstractStreamEventDispatcher::create() { return new LinuxEventDispatcher; } } /* namespace simpleServer */ <commit_msg>fix bug on dispatcher's queue<commit_after>/* * linuxWaitingSlot.cpp * * Created on: 12. 10. 2017 * Author: ondra */ #include <fcntl.h> #include <sys/socket.h> #include <unistd.h> #include "../exceptions.h" #include "../mt.h" #include "netEventDispatcher.h" #include "../defer.h" namespace simpleServer { using ondra_shared::defer; static LinuxEventDispatcher::Task empty_task([](AsyncState){},asyncOK); LinuxEventDispatcher::LinuxEventDispatcher() { int fds[2]; if (pipe2(fds, O_CLOEXEC)!=0) { int err = errno; throw SystemException(err,"Failed to call pipe2 (LinuxEventDispatcher)"); } intrHandle = fds[1]; intrWaitHandle = fds[0]; addIntrWaitHandle(); exitFlag = false; } LinuxEventDispatcher::~LinuxEventDispatcher() noexcept { close(intrHandle); close(intrWaitHandle); } template<typename T> void ignore_variable(T) {} LinuxEventDispatcher::Task LinuxEventDispatcher::runQueue() { std::lock_guard<std::mutex> _(queueLock); char b; ignore_variable(::read(intrWaitHandle, &b, 1)); if (!queue.empty()) { const RegReq &r = queue.front(); if (r.ares.socket == 0 && r.ares.op == 0) { Task t(r.extra.completionFn,asyncOK); queue.pop(); return t; } else if (r.extra.completionFn == nullptr) { auto q = r.ares; queue.pop(); return findAndCancel(q); } else { addResource(r); queue.pop(); } } return Task(); } LinuxEventDispatcher::Task LinuxEventDispatcher::findAndCancel(const AsyncResource &res) { CompletionFn curFn = nullptr; int cnt = (int)fdmap.size(); for (int i = 0; i < cnt; i++) { if (fdmap[i].fd == res.socket && fdmap[i].events == res.op) { if (curFn ==nullptr) curFn = fdextramap[i].completionFn; else { CompletionFn otherFn = fdextramap[i].completionFn; curFn = [curFn,otherFn](AsyncState st) { curFn(st); otherFn(st); }; } deleteResource(i); --i; --cnt; } } return Task(curFn,asyncCancel); } void LinuxEventDispatcher::addIntrWaitHandle() { RegReq rq; rq.ares = AsyncResource(intrWaitHandle, POLLIN); rq.extra.completionFn = empty_task; rq.extra.timeout = TimePoint::max(); addResource(rq); } void LinuxEventDispatcher::runAsync(const AsyncResource &resource, int timeout, const CompletionFn &complfn) { if (exitFlag || complfn == nullptr) { defer >> std::bind(complfn, asyncCancel); return; } RegReq req; req.ares = resource; req.extra.completionFn = complfn; if (timeout < 0) req.extra.timeout = TimePoint::max(); else req.extra.timeout = TimePoint::clock::now() + std::chrono::milliseconds(timeout); std::lock_guard<std::mutex> _(queueLock); queue.push(req); sendIntr(); } void LinuxEventDispatcher::runAsync(const CustomFn &completion) { if (exitFlag || completion == nullptr) { defer >> completion; return; } RegReq req; req.extra.completionFn = [fn=CustomFn(completion)](AsyncState){fn();}; std::lock_guard<std::mutex> _(queueLock); queue.push(req); sendIntr(); } void LinuxEventDispatcher::addResource(const RegReq &req) { pollfd pfd; pfd.events = req.ares.op; pfd.fd = req.ares.socket; pfd.revents = 0; fdmap.push_back(pfd); fdextramap.push_back(req.extra); if (req.extra.timeout < nextTimeout) nextTimeout = req.extra.timeout; } void LinuxEventDispatcher::deleteResource(int index) { int last = fdmap.size()-1; if (index < last) { std::swap(fdmap[index],fdmap[last]); std::swap(fdextramap[index],fdextramap[last]); } fdmap.resize(last); fdextramap.resize(last); } LinuxEventDispatcher::Task LinuxEventDispatcher::checkEvents(const TimePoint &now, bool finish) { int sz = static_cast<int>(fdmap.size()); if (last_checked >= sz) { if (finish) return Task(); last_checked = 0; nextTimeout = TimePoint::max(); } while (last_checked < sz) { int idx = last_checked++; if (fdmap[idx].revents) { if (fdmap[idx].fd == intrWaitHandle) { Task t = runQueue(); fdmap[idx].revents = 0; if (t != nullptr) return t; } else { Task t(fdextramap[idx].completionFn, asyncOK); deleteResource(idx); --last_checked; return t; } } else if (fdextramap[idx].timeout<=now) { Task t(fdextramap[idx].completionFn, asyncTimeout); deleteResource(idx); --last_checked; return t; } else if (fdextramap[idx].timeout<nextTimeout) { nextTimeout = fdextramap[idx].timeout; } } return Task(); } ///returns true, if the listener doesn't contain any asynchronous task bool LinuxEventDispatcher::empty() const { return fdmap.empty(); } void LinuxEventDispatcher::stop() { exitFlag = true; sendIntr(); } unsigned int LinuxEventDispatcher::getPendingCount() const { return fdmap.size(); } void LinuxEventDispatcher::cancel(const AsyncResource& resource) { RegReq req; req.ares = resource; req.extra.completionFn = nullptr; std::lock_guard<std::mutex> _(queueLock); queue.push(req); sendIntr(); } LinuxEventDispatcher::Task LinuxEventDispatcher::cleanup() { if (!fdmap.empty()) { int idx = fdmap.size()-1; Task t(fdextramap[idx].completionFn, asyncCancel); deleteResource(idx); return t; } else { return Task(); } } LinuxEventDispatcher::Task LinuxEventDispatcher::wait() { if (exitFlag) { return cleanup(); } TimePoint now = std::chrono::steady_clock::now(); Task x = checkEvents(now,true); if (x != nullptr) return x; auto int_ms = std::chrono::duration_cast<std::chrono::milliseconds>(nextTimeout - now); int r = poll(fdmap.data(),fdmap.size(),int_ms.count()); if (r < 0) { int e = errno; if (e != EINTR && e != EAGAIN) throw SystemException(e, "Failed to call poll()"); } else { now = std::chrono::steady_clock::now(); x = checkEvents(now,false); if (x != nullptr) return x; } return empty_task; } void LinuxEventDispatcher::sendIntr() { unsigned char b = 1; int r = ::write(intrHandle, &b, 1); if (r < 0) { throw SystemException(errno); } } PStreamEventDispatcher AbstractStreamEventDispatcher::create() { return new LinuxEventDispatcher; } } /* namespace simpleServer */ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: viewcontactofgroup.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2003-11-24 16:45:24 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SDR_CONTACT_VIEWCONTACTOFGROUP_HXX #include <svx/sdr/contact/viewcontactofgroup.hxx> #endif #ifndef _SVDOGRP_HXX #include <svdogrp.hxx> #endif #ifndef _SVDPAGE_HXX #include <svdpage.hxx> #endif ////////////////////////////////////////////////////////////////////////////// namespace sdr { namespace contact { // method to recalculate the PaintRectangle if the validity flag shows that // it is invalid. The flag is set from GetPaintRectangle, thus the implementation // only needs to refresh maPaintRectangle itself. void ViewContactOfGroup::CalcPaintRectangle() { maPaintRectangle = GetSdrObjGroup().GetCurrentBoundRect(); } ViewContactOfGroup::ViewContactOfGroup(SdrObjGroup& rGroup) : ViewContactOfSdrObj(rGroup) { } ViewContactOfGroup::~ViewContactOfGroup() { } // When ShouldPaintObject() returns sal_True, the object itself is painted and // PaintObject() is called. sal_Bool ViewContactOfGroup::ShouldPaintObject(DisplayInfo& rDisplayInfo, const ViewObjectContact& rAssociatedVOC) { // Do not paint groups themthelves only when they are empty if(!GetSdrObjGroup().GetSubList() || !GetSdrObjGroup().GetSubList()->GetObjCount()) { // Paint empty group to get a replacement visualisation return sal_True; } return sal_False; } // Paint this object. This is before evtl. SubObjects get painted. It needs to return // sal_True when something was pained and the paint output rectangle in rPaintRectangle. sal_Bool ViewContactOfGroup::PaintObject(DisplayInfo& rDisplayInfo, Rectangle& rPaintRectangle, const ViewObjectContact& rAssociatedVOC) { // Paint the object. If this is called, the group is empty. // Paint a replacement object. return PaintReplacementObject(rDisplayInfo, rPaintRectangle); } } // end of namespace contact } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// // eof <commit_msg>INTEGRATION: CWS ooo19126 (1.2.1096); FILE MERGED 2005/09/05 14:26:29 rt 1.2.1096.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: viewcontactofgroup.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 00:04:50 $ * * 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 _SDR_CONTACT_VIEWCONTACTOFGROUP_HXX #include <svx/sdr/contact/viewcontactofgroup.hxx> #endif #ifndef _SVDOGRP_HXX #include <svdogrp.hxx> #endif #ifndef _SVDPAGE_HXX #include <svdpage.hxx> #endif ////////////////////////////////////////////////////////////////////////////// namespace sdr { namespace contact { // method to recalculate the PaintRectangle if the validity flag shows that // it is invalid. The flag is set from GetPaintRectangle, thus the implementation // only needs to refresh maPaintRectangle itself. void ViewContactOfGroup::CalcPaintRectangle() { maPaintRectangle = GetSdrObjGroup().GetCurrentBoundRect(); } ViewContactOfGroup::ViewContactOfGroup(SdrObjGroup& rGroup) : ViewContactOfSdrObj(rGroup) { } ViewContactOfGroup::~ViewContactOfGroup() { } // When ShouldPaintObject() returns sal_True, the object itself is painted and // PaintObject() is called. sal_Bool ViewContactOfGroup::ShouldPaintObject(DisplayInfo& rDisplayInfo, const ViewObjectContact& rAssociatedVOC) { // Do not paint groups themthelves only when they are empty if(!GetSdrObjGroup().GetSubList() || !GetSdrObjGroup().GetSubList()->GetObjCount()) { // Paint empty group to get a replacement visualisation return sal_True; } return sal_False; } // Paint this object. This is before evtl. SubObjects get painted. It needs to return // sal_True when something was pained and the paint output rectangle in rPaintRectangle. sal_Bool ViewContactOfGroup::PaintObject(DisplayInfo& rDisplayInfo, Rectangle& rPaintRectangle, const ViewObjectContact& rAssociatedVOC) { // Paint the object. If this is called, the group is empty. // Paint a replacement object. return PaintReplacementObject(rDisplayInfo, rPaintRectangle); } } // end of namespace contact } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// // eof <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: UnoForbiddenCharsTable.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: cl $ $Date: 2001-04-05 16:46:12 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SVX_UNOFORBIDDENCHARSTABLE_HXX_ #include "UnoForbiddenCharsTable.hxx" #endif #ifndef _FORBIDDENCHARACTERSTABLE_HXX #include "forbiddencharacterstable.hxx" #endif #ifndef _UNO_LINGU_HXX #include "unolingu.hxx" #endif using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::i18n; using namespace ::rtl; using namespace ::vos; using namespace ::cppu; SvxUnoForbiddenCharsTable::SvxUnoForbiddenCharsTable(ORef<SvxForbiddenCharactersTable> xForbiddenChars) : mxForbiddenChars( xForbiddenChars ) { } SvxUnoForbiddenCharsTable::~SvxUnoForbiddenCharsTable() { } void SvxUnoForbiddenCharsTable::onChange() { } ForbiddenCharacters SvxUnoForbiddenCharsTable::getForbiddenCharacters( const Locale& rLocale ) throw(NoSuchElementException, RuntimeException) { if(!mxForbiddenChars.isValid()) throw RuntimeException(); const LanguageType eLang = SvxLocaleToLanguage( rLocale ); const ForbiddenCharacters* pForbidden = mxForbiddenChars->GetForbiddenCharacters( eLang, FALSE ); if(!pForbidden) throw NoSuchElementException(); return *pForbidden; } sal_Bool SvxUnoForbiddenCharsTable::hasForbiddenCharacters( const Locale& rLocale ) throw(RuntimeException) { if(!mxForbiddenChars.isValid()) return sal_False; const LanguageType eLang = SvxLocaleToLanguage( rLocale ); const ForbiddenCharacters* pForbidden = mxForbiddenChars->GetForbiddenCharacters( eLang, FALSE ); return NULL != pForbidden; } void SvxUnoForbiddenCharsTable::setForbiddenCharacters(const Locale& rLocale, const ForbiddenCharacters& rForbiddenCharacters ) throw(RuntimeException) { if(!mxForbiddenChars.isValid()) throw RuntimeException(); const LanguageType eLang = SvxLocaleToLanguage( rLocale ); mxForbiddenChars->SetForbiddenCharacters( eLang, rForbiddenCharacters ); onChange(); } void SvxUnoForbiddenCharsTable::removeForbiddenCharacters( const Locale& rLocale ) throw(RuntimeException) { if(!mxForbiddenChars.isValid()) throw RuntimeException(); const LanguageType eLang = SvxLocaleToLanguage( rLocale ); mxForbiddenChars->ClearForbiddenCharacters( eLang ); onChange(); } // XSupportedLocales Sequence< Locale > SAL_CALL SvxUnoForbiddenCharsTable::getLocales() throw(RuntimeException) { const sal_Int32 nCount = mxForbiddenChars.isValid() ? mxForbiddenChars->Count() : 0; Sequence< Locale > aLocales( nCount ); if( nCount ) { Locale* pLocales = aLocales.getArray(); for( sal_Int32 nIndex = 0; nIndex < nCount; nIndex++ ) { const ULONG nLanguage = mxForbiddenChars->GetObjectKey( nIndex ); SvxLanguageToLocale ( *pLocales++, static_cast < LanguageType > (nLanguage) ); } } return aLocales; } sal_Bool SAL_CALL SvxUnoForbiddenCharsTable::hasLocale( const Locale& aLocale ) throw(RuntimeException) { return hasForbiddenCharacters( aLocale ); } <commit_msg>#98472# use solarmutex to guard the implementation<commit_after>/************************************************************************* * * $RCSfile: UnoForbiddenCharsTable.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: cl $ $Date: 2002-04-04 11:00:13 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SVX_UNOFORBIDDENCHARSTABLE_HXX_ #include "UnoForbiddenCharsTable.hxx" #endif #ifndef _FORBIDDENCHARACTERSTABLE_HXX #include "forbiddencharacterstable.hxx" #endif #ifndef _VOS_MUTEX_HXX_ #include <vos/mutex.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef _UNO_LINGU_HXX #include "unolingu.hxx" #endif using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::i18n; using namespace ::rtl; using namespace ::vos; using namespace ::cppu; SvxUnoForbiddenCharsTable::SvxUnoForbiddenCharsTable(ORef<SvxForbiddenCharactersTable> xForbiddenChars) : mxForbiddenChars( xForbiddenChars ) { } SvxUnoForbiddenCharsTable::~SvxUnoForbiddenCharsTable() { } void SvxUnoForbiddenCharsTable::onChange() { } ForbiddenCharacters SvxUnoForbiddenCharsTable::getForbiddenCharacters( const Locale& rLocale ) throw(NoSuchElementException, RuntimeException) { OGuard aGuard( Application::GetSolarMutex() ); if(!mxForbiddenChars.isValid()) throw RuntimeException(); const LanguageType eLang = SvxLocaleToLanguage( rLocale ); const ForbiddenCharacters* pForbidden = mxForbiddenChars->GetForbiddenCharacters( eLang, FALSE ); if(!pForbidden) throw NoSuchElementException(); return *pForbidden; } sal_Bool SvxUnoForbiddenCharsTable::hasForbiddenCharacters( const Locale& rLocale ) throw(RuntimeException) { OGuard aGuard( Application::GetSolarMutex() ); if(!mxForbiddenChars.isValid()) return sal_False; const LanguageType eLang = SvxLocaleToLanguage( rLocale ); const ForbiddenCharacters* pForbidden = mxForbiddenChars->GetForbiddenCharacters( eLang, FALSE ); return NULL != pForbidden; } void SvxUnoForbiddenCharsTable::setForbiddenCharacters(const Locale& rLocale, const ForbiddenCharacters& rForbiddenCharacters ) throw(RuntimeException) { OGuard aGuard( Application::GetSolarMutex() ); if(!mxForbiddenChars.isValid()) throw RuntimeException(); const LanguageType eLang = SvxLocaleToLanguage( rLocale ); mxForbiddenChars->SetForbiddenCharacters( eLang, rForbiddenCharacters ); onChange(); } void SvxUnoForbiddenCharsTable::removeForbiddenCharacters( const Locale& rLocale ) throw(RuntimeException) { OGuard aGuard( Application::GetSolarMutex() ); if(!mxForbiddenChars.isValid()) throw RuntimeException(); const LanguageType eLang = SvxLocaleToLanguage( rLocale ); mxForbiddenChars->ClearForbiddenCharacters( eLang ); onChange(); } // XSupportedLocales Sequence< Locale > SAL_CALL SvxUnoForbiddenCharsTable::getLocales() throw(RuntimeException) { OGuard aGuard( Application::GetSolarMutex() ); const sal_Int32 nCount = mxForbiddenChars.isValid() ? mxForbiddenChars->Count() : 0; Sequence< Locale > aLocales( nCount ); if( nCount ) { Locale* pLocales = aLocales.getArray(); for( sal_Int32 nIndex = 0; nIndex < nCount; nIndex++ ) { const ULONG nLanguage = mxForbiddenChars->GetObjectKey( nIndex ); SvxLanguageToLocale ( *pLocales++, static_cast < LanguageType > (nLanguage) ); } } return aLocales; } sal_Bool SAL_CALL SvxUnoForbiddenCharsTable::hasLocale( const Locale& aLocale ) throw(RuntimeException) { OGuard aGuard( Application::GetSolarMutex() ); return hasForbiddenCharacters( aLocale ); } <|endoftext|>
<commit_before>/* Copyright 2017 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/core/framework/common_shape_fns.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/shape_inference.h" namespace tensorflow { using shape_inference::InferenceContext; using shape_inference::ShapeHandle; REGISTER_OP("TPUReplicateMetadata") .Attr("num_replicas: int >= 0") .Attr("topology: string = \"\"") .Attr("use_tpu: bool = true") .Attr("device_assignment: list(int) = []") .Attr("computation_shape: list(int) = []") .Attr("host_compute_core: list(string) = []") .SetShapeFn(shape_inference::UnknownShape); REGISTER_OP("TPUReplicatedInput") .Input("inputs: N * T") .Output("output: T") .Attr("N: int >= 1") .Attr("T: type") .SetShapeFn([](InferenceContext* c) { ShapeHandle cur = c->input(c->num_inputs() - 1); for (int i = c->num_inputs() - 2; i >= 0; --i) { TF_RETURN_WITH_CONTEXT_IF_ERROR(c->Merge(c->input(i), cur, &cur), "From merging shape ", i, " with other shapes."); } c->set_output(0, cur); return Status::OK(); }) .Doc( "Operator that connects N unreplicated inputs to an N-way " "replicated TPU computation."); REGISTER_OP("TPUReplicatedOutput") .Input("input: T") .Output("outputs: num_replicas * T") .Attr("num_replicas: int >= 1") .Attr("T: type") .SetShapeFn([](InferenceContext* c) { for (int i = 0; i < c->num_outputs(); ++i) { c->set_output(i, c->input(0)); } return Status::OK(); }) .Doc( "Operator that connects the output of an N-way replicated TPU " "computation to N separate outputs."); REGISTER_OP("TPUCompilationResult") .Output("output: string") .SetShapeFn(shape_inference::ScalarShape); REGISTER_OP("TPUReplicate") .Attr("computation: func") .Attr("num_replicas: int >= 1") .Attr("topology: string = \"\"") .Attr("use_tpu: bool = true") .Attr("device_assignment: list(int) = []") .Attr("host_compute_core: list(string) = []") .Attr("computation_shape: list(int) = []") .Attr("Tinputs: list(type) >= 0") .Attr("Tbroadcast_inputs: list(type) >= 0") .Attr("NumVariables: int >= 0") .Attr("Tguaranteed_constants: list(type) >= 0") .Attr("output_types: list(type) >= 0") .Input("inputs: Tinputs") .Input("broadcast_inputs: Tbroadcast_inputs") .Input("variables: NumVariables * resource") .Input("guaranteed_constants: Tguaranteed_constants") .Output("outputs: output_types") .SetShapeFn(shape_inference::UnknownShape) .Doc(R"doc( Runs replicated computations on a distributed TPU system. computation: a function containing the computation to run. num_replicas: the number of replicas of the computation to run. topology: A serialized tensorflow.tpu.TopologyProto that describes the TPU topology. use_tpu: a bool indicating if this computation will run on TPU or CPU/GPU. Currently, only supports a default placement (computation is placed on GPU if one is available, and on CPU if not). computation_shape: a [mesh_dimension] array describing the shape of each computation replica in numbers of cores in the TPU mesh. device_assignment: a flattened array with shape [replica] + computation_shape + [mesh_dimension] that maps the coordinates of logical cores in each replica of a computation to physical coordinates in the TPU topology. Tinputs: the types of the arguments to 'computation'. inputs: the inputs to 'computation', flattened, in replica-major order. Tbroadcast_inputs: the types of the additional arguments to broadcast to all replicas. Tguaranteed_constants: the types of the arguments to 'guaranteed_constants'. broadcast_inputs: additional arguments to broadcast to all replicas. The broadcast inputs are appended to the per-replica inputs when calling computation. guaranteed_constants: arguments which have been guaranteed to not change their values during the session lifetime. These contain tensors marked as constant using the GuaranteeConstOp. output_types: the types of the outputs of 'computation'. outputs: the outputs of 'computation'. )doc"); } // namespace tensorflow <commit_msg>Add support for propagating resource shapes via the TPUReplicatedInput operator's shape inference function.<commit_after>/* Copyright 2017 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/core/framework/common_shape_fns.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/shape_inference.h" namespace tensorflow { using shape_inference::InferenceContext; using shape_inference::ShapeHandle; REGISTER_OP("TPUReplicateMetadata") .Attr("num_replicas: int >= 0") .Attr("topology: string = \"\"") .Attr("use_tpu: bool = true") .Attr("device_assignment: list(int) = []") .Attr("computation_shape: list(int) = []") .Attr("host_compute_core: list(string) = []") .SetShapeFn(shape_inference::UnknownShape); REGISTER_OP("TPUReplicatedInput") .Input("inputs: N * T") .Output("output: T") .Attr("N: int >= 1") .Attr("T: type") .SetShapeFn([](InferenceContext* c) { ShapeHandle cur = c->input(c->num_inputs() - 1); for (int i = c->num_inputs() - 2; i >= 0; --i) { TF_RETURN_WITH_CONTEXT_IF_ERROR(c->Merge(c->input(i), cur, &cur), "From merging shape ", i, " with other shapes."); } c->set_output(0, cur); // If this is a resource, unify the resource shapes. DataType dtype; TF_RETURN_IF_ERROR(c->GetAttr("T", &dtype)); if (dtype == DT_RESOURCE) { const std::vector<shape_inference::ShapeAndType>* shapes_and_types = nullptr; for (int i = c->num_inputs() - 1; i >= 0; --i) { if (shapes_and_types) { if (!c->MergeInputHandleShapesAndTypes(i, *shapes_and_types)) { return errors::InvalidArgument( "Incompatible resource shapes for replicated TPU input."); } } else { shapes_and_types = c->input_handle_shapes_and_types(i); } } if (shapes_and_types) { c->set_output_handle_shapes_and_types(0, *shapes_and_types); } } return Status::OK(); }) .Doc( "Operator that connects N unreplicated inputs to an N-way " "replicated TPU computation."); REGISTER_OP("TPUReplicatedOutput") .Input("input: T") .Output("outputs: num_replicas * T") .Attr("num_replicas: int >= 1") .Attr("T: type") .SetShapeFn([](InferenceContext* c) { for (int i = 0; i < c->num_outputs(); ++i) { c->set_output(i, c->input(0)); } return Status::OK(); }) .Doc( "Operator that connects the output of an N-way replicated TPU " "computation to N separate outputs."); REGISTER_OP("TPUCompilationResult") .Output("output: string") .SetShapeFn(shape_inference::ScalarShape); REGISTER_OP("TPUReplicate") .Attr("computation: func") .Attr("num_replicas: int >= 1") .Attr("topology: string = \"\"") .Attr("use_tpu: bool = true") .Attr("device_assignment: list(int) = []") .Attr("host_compute_core: list(string) = []") .Attr("computation_shape: list(int) = []") .Attr("Tinputs: list(type) >= 0") .Attr("Tbroadcast_inputs: list(type) >= 0") .Attr("NumVariables: int >= 0") .Attr("Tguaranteed_constants: list(type) >= 0") .Attr("output_types: list(type) >= 0") .Input("inputs: Tinputs") .Input("broadcast_inputs: Tbroadcast_inputs") .Input("variables: NumVariables * resource") .Input("guaranteed_constants: Tguaranteed_constants") .Output("outputs: output_types") .SetShapeFn(shape_inference::UnknownShape) .Doc(R"doc( Runs replicated computations on a distributed TPU system. computation: a function containing the computation to run. num_replicas: the number of replicas of the computation to run. topology: A serialized tensorflow.tpu.TopologyProto that describes the TPU topology. use_tpu: a bool indicating if this computation will run on TPU or CPU/GPU. Currently, only supports a default placement (computation is placed on GPU if one is available, and on CPU if not). computation_shape: a [mesh_dimension] array describing the shape of each computation replica in numbers of cores in the TPU mesh. device_assignment: a flattened array with shape [replica] + computation_shape + [mesh_dimension] that maps the coordinates of logical cores in each replica of a computation to physical coordinates in the TPU topology. Tinputs: the types of the arguments to 'computation'. inputs: the inputs to 'computation', flattened, in replica-major order. Tbroadcast_inputs: the types of the additional arguments to broadcast to all replicas. Tguaranteed_constants: the types of the arguments to 'guaranteed_constants'. broadcast_inputs: additional arguments to broadcast to all replicas. The broadcast inputs are appended to the per-replica inputs when calling computation. guaranteed_constants: arguments which have been guaranteed to not change their values during the session lifetime. These contain tensors marked as constant using the GuaranteeConstOp. output_types: the types of the outputs of 'computation'. outputs: the outputs of 'computation'. )doc"); } // namespace tensorflow <|endoftext|>
<commit_before>#include "runner.hh" #include "channel.hh" #include <boost/bind.hpp> void generate(channel<int> out) { for (int i=2; ; ++i) { out.send(i); } } void filter(channel<int> in, channel<int> out, int prime) { for (;;) { int i = in.recv(); if (i % prime != 0) { out.send(i); } } } void primes() { channel<int> ch; task::spawn(boost::bind(generate, ch)); for (int i=0; i<100; ++i) { int prime = ch.recv(); printf("%i\n", prime); channel<int> out; task::spawn(boost::bind(filter, ch, out, prime)); ch = out; } exit(0); } int main(int argc, char *argv[]) { task::spawn(primes); runner::self()->schedule(); }<commit_msg>credit source<commit_after>#include "runner.hh" #include "channel.hh" #include <boost/bind.hpp> #include <iostream> // adapted from http://golang.org/doc/go_tutorial.html#tmp_360 void generate(channel<int> out) { for (int i=2; ; ++i) { out.send(i); } } void filter(channel<int> in, channel<int> out, int prime) { for (;;) { int i = in.recv(); if (i % prime != 0) { out.send(i); } } } void primes() { channel<int> ch; task::spawn(boost::bind(generate, ch)); for (int i=0; i<100; ++i) { int prime = ch.recv(); std::cout << prime << "\n"; channel<int> out; task::spawn(boost::bind(filter, ch, out, prime)); ch = out; } exit(0); } int main(int argc, char *argv[]) { task::spawn(primes); runner::self()->schedule(); }<|endoftext|>
<commit_before>// Copyright 2017 Google Inc. 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 <iostream> #include <map> #include "CodeObject.h" #include "InstructionDecoder.h" #include "pecodesource.hpp" #include "disassembly.hpp" using namespace std; using namespace Dyninst; using namespace ParseAPI; using namespace InstructionAPI; Disassembly::Disassembly(const std::string& filetype, const std::string& inputfile) : type_(filetype), inputfile_(inputfile) { code_object_ = nullptr; code_source_ = nullptr; } Disassembly::~Disassembly() { delete code_object_; if (type_ == "ELF") { SymtabCodeSource* symtab_code_source = static_cast<SymtabCodeSource*>(code_source_); delete symtab_code_source; } else { PECodeSource* pe_code_source = static_cast<PECodeSource*>(code_source_); delete pe_code_source; } } bool Disassembly::Load(bool perform_parsing) { Instruction::Ptr instruction; if (type_ == "ELF") { SymtabAPI::Symtab* sym_tab = nullptr; SymtabCodeSource* symtab_code_source = nullptr; bool is_parseable = SymtabAPI::Symtab::openFile(sym_tab, inputfile_); if (is_parseable == false) { printf("Error: ELF File cannot be parsed.\n"); return false; } // Brutal C-style cast because SymtabCodeSource for some reason wants a // char * instead of a const char*. symtab_code_source = new SymtabCodeSource((char *)inputfile_.c_str()); code_source_ = static_cast<CodeSource*>(symtab_code_source); } else if (type_ == "PE") { PECodeSource* pe_code_source = new PECodeSource(inputfile_); if (pe_code_source->parsed() == false) { printf("Error: PE File cannot be parsed.\n"); return false; } code_source_ = static_cast<CodeSource*>(pe_code_source); } else { printf("Error: Unknown filetype specified.\n"); return false; } code_object_ = new CodeObject(code_source_); if (perform_parsing) { // Parse the obvious function entries. code_object_->parse(); // Parse the gaps. for (CodeRegion* region : code_source_->regions()) { code_object_->parseGaps(region, GapParsingType::IdiomMatching); code_object_->parseGaps(region, GapParsingType::PreambleMatching); } } return true; } void Disassembly::DisassembleFromAddress(uint64_t address, bool recursive) { code_object_->parse(address, recursive); } <commit_msg>add condition to deletion of code_source_ in case filetype is not ELF<commit_after>// Copyright 2017 Google Inc. 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 <iostream> #include <map> #include "CodeObject.h" #include "InstructionDecoder.h" #include "pecodesource.hpp" #include "disassembly.hpp" using namespace std; using namespace Dyninst; using namespace ParseAPI; using namespace InstructionAPI; Disassembly::Disassembly(const std::string& filetype, const std::string& inputfile) : type_(filetype), inputfile_(inputfile) { code_object_ = nullptr; code_source_ = nullptr; } Disassembly::~Disassembly() { delete code_object_; if (type_ == "ELF") { SymtabCodeSource* symtab_code_source = static_cast<SymtabCodeSource*>(code_source_); delete symtab_code_source; } else if (type_ == "PE") { PECodeSource* pe_code_source = static_cast<PECodeSource*>(code_source_); delete pe_code_source; } } bool Disassembly::Load(bool perform_parsing) { Instruction::Ptr instruction; if (type_ == "ELF") { SymtabAPI::Symtab* sym_tab = nullptr; SymtabCodeSource* symtab_code_source = nullptr; bool is_parseable = SymtabAPI::Symtab::openFile(sym_tab, inputfile_); if (is_parseable == false) { printf("Error: ELF File cannot be parsed.\n"); return false; } // Brutal C-style cast because SymtabCodeSource for some reason wants a // char * instead of a const char*. symtab_code_source = new SymtabCodeSource((char *)inputfile_.c_str()); code_source_ = static_cast<CodeSource*>(symtab_code_source); } else if (type_ == "PE") { PECodeSource* pe_code_source = new PECodeSource(inputfile_); if (pe_code_source->parsed() == false) { printf("Error: PE File cannot be parsed.\n"); return false; } code_source_ = static_cast<CodeSource*>(pe_code_source); } else { printf("Error: Unknown filetype specified.\n"); return false; } code_object_ = new CodeObject(code_source_); if (perform_parsing) { // Parse the obvious function entries. code_object_->parse(); // Parse the gaps. for (CodeRegion* region : code_source_->regions()) { code_object_->parseGaps(region, GapParsingType::IdiomMatching); code_object_->parseGaps(region, GapParsingType::PreambleMatching); } } return true; } void Disassembly::DisassembleFromAddress(uint64_t address, bool recursive) { code_object_->parse(address, recursive); } <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief コマンド入力クラス @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include <cstring> extern "C" { void sci_putch(char ch); void sci_puts(const char *str); char sci_getch(void); uint16_t sci_length(void); }; namespace utils { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief command class @param[in] buffsize バッファサイズ(最小でも9) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <int16_t buffsize> class command { char buff_[buffsize]; int16_t bpos_; int16_t pos_; int16_t len_; int16_t tab_top_; const char* prompt_; bool tab_; // VT-100 ESC シーケンス static void clear_line_() { sci_putch(0x1b); sci_putch('['); sci_putch('0'); sci_putch('J'); } static void save_cursor_() { sci_putch(0x1b); sci_putch('7'); } static void load_cursor_() { sci_putch(0x1b); sci_putch('8'); } static void crlf_() { sci_putch('\r'); ///< CR sci_putch('\n'); ///< LF } public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// command() : bpos_(-1), pos_(0), len_(0), tab_top_(-1), prompt_(nullptr), tab_(false) { buff_[0] = 0; } //-----------------------------------------------------------------// /*! @brief プロムプト文字列を設定 @param[in] text 文字列 */ //-----------------------------------------------------------------// void set_prompt(const char* text) { prompt_ = text; } //-----------------------------------------------------------------// /*! @brief サービス @n 定期的に呼び出す @return 「Enter」キーが押されたら「true」 */ //-----------------------------------------------------------------// bool service() { if(bpos_ < 0 && pos_ == 0) { if(prompt_) sci_puts(prompt_); } bpos_ = pos_; tab_ = false; while(sci_length()) { if(pos_ >= (buffsize - 1)) { ///< バッファが溢れた・・ sci_putch('\\'); ///< バックスラッシュ buff_[buffsize - 1] = 0; pos_ = 0; bpos_ = -1; crlf_(); return false; } else if(pos_ >= (buffsize - 8)) { ///< バッファが溢れそうな警告 sci_putch('G' - 0x40); ///< Ctrl-G } char ch = sci_getch(); switch(ch) { case '\r': // Enter キー buff_[pos_] = 0; len_ = pos_; clear_line_(); crlf_(); pos_ = 0; bpos_ = -1; tab_top_ = -1; return true; case 0x08: // バックスペース if(pos_) { --pos_; sci_putch(0x08); if(buff_[pos_] < 0x20) { sci_putch(0x08); } } else { pos_ = 0; bpos_ = -1; crlf_(); } break; case '\t': // TAB キー if(tab_top_ < 0) { tab_top_ = pos_; save_cursor_(); } tab_ = true; break; default: if(ch < 0x20) { ///< 他の ctrl コード buff_[pos_] = ch; ++pos_; sci_putch('^'); sci_putch(ch + 0x40); } else { buff_[pos_] = ch; ++pos_; sci_putch(ch); } buff_[pos_] = 0; break; } } return false; } //-----------------------------------------------------------------// /*! @brief コマンド行を取得 @return コマンド行 */ //-----------------------------------------------------------------// const char* get_command() const { return buff_; } //-----------------------------------------------------------------// /*! @brief ワード数を取得 @return ワード数を返す */ //-----------------------------------------------------------------// uint8_t get_words() const { const char* p = buff_; char bc = ' '; uint8_t n = 0; while(1) { char ch = *p++; if(ch == 0) break; if(bc == ' ' && ch != ' ') { ++n; } bc = ch; } return n; } //-----------------------------------------------------------------// /*! @brief ワードを取得 @param[in] argc ワード位置 @param[in] limit ワード文字列リミット数 @param[out] word ワード文字列格納ポインター @return 取得できたら「true」を返す */ //-----------------------------------------------------------------// bool get_word(uint8_t argc, uint8_t limit, char* word) const { const char* p = buff_; char bc = ' '; const char* wd = p; while(1) { char ch = *p; if(bc == ' ' && ch != ' ') { wd = p; } if(bc != ' ' && (ch == ' ' || ch == 0)) { if(argc == 0) { uint8_t i; for(i = 0; i < (p - wd); ++i) { --limit; if(limit == 0) break; word[i] = wd[i]; } word[i] = 0; return true; } --argc; } if(ch == 0) break; bc = ch; ++p; } return false; } //-----------------------------------------------------------------// /*! @brief ワードを比較 @param[in] argc ワード位置 @param[in] key 比較文字列 @return */ //-----------------------------------------------------------------// bool cmp_word(uint8_t argc, const char* key) const { if(key == nullptr) return false; const char* p = buff_; char bc = ' '; uint32_t keylen = std::strlen(key); while(1) { const char* top; char ch = *p; if(bc == ' ' && ch != ' ') { top = p; } if(bc != ' ' && (ch == ' ' || ch == 0)) { uint32_t len = p - top; if(argc == 0 && len == keylen) { return std::strncmp(key, top, keylen) == 0; } --argc; } if(ch == 0) break; bc = ch; ++p; } return false; } //-----------------------------------------------------------------// /*! @brief TAB キーが押されたか @return 押されたら「true」 */ //-----------------------------------------------------------------// bool probe_tab() const { return tab_; } //-----------------------------------------------------------------// /*! @brief TAB 注入位置のリセット */ //-----------------------------------------------------------------// void reset_tab() { tab_top_ = -1; } //-----------------------------------------------------------------// /*! @brief TAB キーの候補を注入 @param[in] key 注入文字列 */ //-----------------------------------------------------------------// void injection_tab(const char* key) { if(tab_top_ < 0) return; std::strcpy(&buff_[tab_top_], key); load_cursor_(); sci_puts(key); } }; } <commit_msg>update uint32_t to int<commit_after>#pragma once //=====================================================================// /*! @file @brief コマンド入力クラス @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include <cstring> extern "C" { void sci_putch(char ch); void sci_puts(const char *str); char sci_getch(void); uint16_t sci_length(void); }; namespace utils { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief command class @param[in] buffsize バッファサイズ(最小でも9) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <int16_t buffsize> class command { char buff_[buffsize]; int16_t bpos_; int16_t pos_; int16_t len_; int16_t tab_top_; const char* prompt_; bool tab_; // VT-100 ESC シーケンス static void clear_line_() { sci_putch(0x1b); sci_putch('['); sci_putch('0'); sci_putch('J'); } static void save_cursor_() { sci_putch(0x1b); sci_putch('7'); } static void load_cursor_() { sci_putch(0x1b); sci_putch('8'); } static void crlf_() { sci_putch('\r'); ///< CR sci_putch('\n'); ///< LF } public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// command() : bpos_(-1), pos_(0), len_(0), tab_top_(-1), prompt_(nullptr), tab_(false) { buff_[0] = 0; } //-----------------------------------------------------------------// /*! @brief プロムプト文字列を設定 @param[in] text 文字列 */ //-----------------------------------------------------------------// void set_prompt(const char* text) { prompt_ = text; } //-----------------------------------------------------------------// /*! @brief サービス @n 定期的に呼び出す @return 「Enter」キーが押されたら「true」 */ //-----------------------------------------------------------------// bool service() { if(bpos_ < 0 && pos_ == 0) { if(prompt_) sci_puts(prompt_); } bpos_ = pos_; tab_ = false; while(sci_length()) { if(pos_ >= (buffsize - 1)) { ///< バッファが溢れた・・ sci_putch('\\'); ///< バックスラッシュ buff_[buffsize - 1] = 0; pos_ = 0; bpos_ = -1; crlf_(); return false; } else if(pos_ >= (buffsize - 8)) { ///< バッファが溢れそうな警告 sci_putch('G' - 0x40); ///< Ctrl-G } char ch = sci_getch(); switch(ch) { case '\r': // Enter キー buff_[pos_] = 0; len_ = pos_; clear_line_(); crlf_(); pos_ = 0; bpos_ = -1; tab_top_ = -1; return true; case 0x08: // バックスペース if(pos_) { --pos_; sci_putch(0x08); if(buff_[pos_] < 0x20) { sci_putch(0x08); } } else { pos_ = 0; bpos_ = -1; crlf_(); } break; case '\t': // TAB キー if(tab_top_ < 0) { tab_top_ = pos_; save_cursor_(); } tab_ = true; break; default: if(ch < 0x20) { ///< 他の ctrl コード buff_[pos_] = ch; ++pos_; sci_putch('^'); sci_putch(ch + 0x40); } else { buff_[pos_] = ch; ++pos_; sci_putch(ch); } buff_[pos_] = 0; break; } } return false; } //-----------------------------------------------------------------// /*! @brief コマンド行を取得 @return コマンド行 */ //-----------------------------------------------------------------// const char* get_command() const { return buff_; } //-----------------------------------------------------------------// /*! @brief ワード数を取得 @return ワード数を返す */ //-----------------------------------------------------------------// uint8_t get_words() const { const char* p = buff_; char bc = ' '; uint8_t n = 0; while(1) { char ch = *p++; if(ch == 0) break; if(bc == ' ' && ch != ' ') { ++n; } bc = ch; } return n; } //-----------------------------------------------------------------// /*! @brief ワードを取得 @param[in] argc ワード位置 @param[in] limit ワード文字列リミット数 @param[out] word ワード文字列格納ポインター @return 取得できたら「true」を返す */ //-----------------------------------------------------------------// bool get_word(uint8_t argc, uint8_t limit, char* word) const { const char* p = buff_; char bc = ' '; const char* wd = p; while(1) { char ch = *p; if(bc == ' ' && ch != ' ') { wd = p; } if(bc != ' ' && (ch == ' ' || ch == 0)) { if(argc == 0) { uint8_t i; for(i = 0; i < (p - wd); ++i) { --limit; if(limit == 0) break; word[i] = wd[i]; } word[i] = 0; return true; } --argc; } if(ch == 0) break; bc = ch; ++p; } return false; } //-----------------------------------------------------------------// /*! @brief ワードを比較 @param[in] argc ワード位置 @param[in] key 比較文字列 @return */ //-----------------------------------------------------------------// bool cmp_word(uint8_t argc, const char* key) const { if(key == nullptr) return false; const char* p = buff_; char bc = ' '; int keylen = std::strlen(key); while(1) { const char* top; char ch = *p; if(bc == ' ' && ch != ' ') { top = p; } if(bc != ' ' && (ch == ' ' || ch == 0)) { int len = p - top; if(argc == 0 && len == keylen) { return std::strncmp(key, top, keylen) == 0; } --argc; } if(ch == 0) break; bc = ch; ++p; } return false; } //-----------------------------------------------------------------// /*! @brief TAB キーが押されたか @return 押されたら「true」 */ //-----------------------------------------------------------------// bool probe_tab() const { return tab_; } //-----------------------------------------------------------------// /*! @brief TAB 注入位置のリセット */ //-----------------------------------------------------------------// void reset_tab() { tab_top_ = -1; } //-----------------------------------------------------------------// /*! @brief TAB キーの候補を注入 @param[in] key 注入文字列 */ //-----------------------------------------------------------------// void injection_tab(const char* key) { if(tab_top_ < 0) return; std::strcpy(&buff_[tab_top_], key); load_cursor_(); sci_puts(key); } }; } <|endoftext|>
<commit_before>// main.cpp - Copyright 2013-2015 Will Cassella, All Rights Reserved #include <Core/Core.h> #include <Core/Containers/StaticBuffer.h> #include <Math/Vec3.h> int main() { Console::WriteLine(test); test.DeleteAll("Oh"); Console::WriteLine(test); Console::Prompt(); }<commit_msg>Should have included this with the last changeset<commit_after>// main.cpp - Copyright 2013-2015 Will Cassella, All Rights Reserved #include <Core/Core.h> #include <Core/Containers/StaticBuffer.h> #include <Math/Vec3.h> int main() { Console::WriteLine(TypeOf<Vec3>()); Console::Prompt(); }<|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome_frame/http_negotiate.h" #include <atlbase.h> #include <atlcom.h> #include <htiframe.h> #include "base/logging.h" #include "base/scoped_ptr.h" #include "base/string_util.h" #include "base/stringprintf.h" #include "base/utf_string_conversions.h" #include "chrome_frame/bho.h" #include "chrome_frame/exception_barrier.h" #include "chrome_frame/html_utils.h" #include "chrome_frame/urlmon_url_request.h" #include "chrome_frame/urlmon_moniker.h" #include "chrome_frame/utils.h" #include "chrome_frame/vtable_patch_manager.h" #include "net/http/http_response_headers.h" #include "net/http/http_util.h" bool HttpNegotiatePatch::modify_user_agent_ = true; const char kUACompatibleHttpHeader[] = "x-ua-compatible"; const char kLowerCaseUserAgent[] = "user-agent"; // From the latest urlmon.h. Symbol name prepended with LOCAL_ to // avoid conflict (and therefore build errors) for those building with // a newer Windows SDK. // TODO(robertshield): Remove this once we update our SDK version. const int LOCAL_BINDSTATUS_SERVER_MIMETYPEAVAILABLE = 54; static const int kHttpNegotiateBeginningTransactionIndex = 3; BEGIN_VTABLE_PATCHES(IHttpNegotiate) VTABLE_PATCH_ENTRY(kHttpNegotiateBeginningTransactionIndex, HttpNegotiatePatch::BeginningTransaction) END_VTABLE_PATCHES() namespace { class SimpleBindStatusCallback : public CComObjectRootEx<CComSingleThreadModel>, public IBindStatusCallback { public: BEGIN_COM_MAP(SimpleBindStatusCallback) COM_INTERFACE_ENTRY(IBindStatusCallback) END_COM_MAP() // IBindStatusCallback implementation STDMETHOD(OnStartBinding)(DWORD reserved, IBinding* binding) { return E_NOTIMPL; } STDMETHOD(GetPriority)(LONG* priority) { return E_NOTIMPL; } STDMETHOD(OnLowResource)(DWORD reserved) { return E_NOTIMPL; } STDMETHOD(OnProgress)(ULONG progress, ULONG max_progress, ULONG status_code, LPCWSTR status_text) { return E_NOTIMPL; } STDMETHOD(OnStopBinding)(HRESULT result, LPCWSTR error) { return E_NOTIMPL; } STDMETHOD(GetBindInfo)(DWORD* bind_flags, BINDINFO* bind_info) { return E_NOTIMPL; } STDMETHOD(OnDataAvailable)(DWORD flags, DWORD size, FORMATETC* formatetc, STGMEDIUM* storage) { return E_NOTIMPL; } STDMETHOD(OnObjectAvailable)(REFIID iid, IUnknown* object) { return E_NOTIMPL; } }; } // end namespace std::string AppendCFUserAgentString(LPCWSTR headers, LPCWSTR additional_headers) { using net::HttpUtil; std::string ascii_headers; if (additional_headers) { ascii_headers = WideToASCII(additional_headers); } // Extract "User-Agent" from |additional_headers| or |headers|. HttpUtil::HeadersIterator headers_iterator(ascii_headers.begin(), ascii_headers.end(), "\r\n"); std::string user_agent_value; if (headers_iterator.AdvanceTo(kLowerCaseUserAgent)) { user_agent_value = headers_iterator.values(); } else if (headers != NULL) { // See if there's a user-agent header specified in the original headers. std::string original_headers(WideToASCII(headers)); HttpUtil::HeadersIterator original_it(original_headers.begin(), original_headers.end(), "\r\n"); if (original_it.AdvanceTo(kLowerCaseUserAgent)) user_agent_value = original_it.values(); } // Use the default "User-Agent" if none was provided. if (user_agent_value.empty()) user_agent_value = http_utils::GetDefaultUserAgent(); // Now add chromeframe to it. user_agent_value = http_utils::AddChromeFrameToUserAgentValue( user_agent_value); // Build new headers, skip the existing user agent value from // existing headers. std::string new_headers; headers_iterator.Reset(); while (headers_iterator.GetNext()) { std::string name(headers_iterator.name()); if (!LowerCaseEqualsASCII(name, kLowerCaseUserAgent)) { new_headers += name + ": " + headers_iterator.values() + "\r\n"; } } new_headers += "User-Agent: " + user_agent_value; new_headers += "\r\n"; return new_headers; } std::string ReplaceOrAddUserAgent(LPCWSTR headers, const std::string& user_agent_value) { DCHECK(headers); using net::HttpUtil; std::string new_headers; if (headers) { std::string ascii_headers(WideToASCII(headers)); // Extract "User-Agent" from the headers. HttpUtil::HeadersIterator headers_iterator(ascii_headers.begin(), ascii_headers.end(), "\r\n"); // Build new headers, skip the existing user agent value from // existing headers. while (headers_iterator.GetNext()) { std::string name(headers_iterator.name()); if (!LowerCaseEqualsASCII(name, kLowerCaseUserAgent)) { new_headers += name + ": " + headers_iterator.values() + "\r\n"; } } } new_headers += "User-Agent: " + user_agent_value; new_headers += "\r\n"; return new_headers; } HttpNegotiatePatch::HttpNegotiatePatch() { } HttpNegotiatePatch::~HttpNegotiatePatch() { } // static bool HttpNegotiatePatch::Initialize() { if (IS_PATCHED(IHttpNegotiate)) { DLOG(WARNING) << __FUNCTION__ << " called more than once."; return true; } // Use our SimpleBindStatusCallback class as we need a temporary object that // implements IBindStatusCallback. CComObjectStackEx<SimpleBindStatusCallback> request; ScopedComPtr<IBindCtx> bind_ctx; HRESULT hr = CreateAsyncBindCtx(0, &request, NULL, bind_ctx.Receive()); DCHECK(SUCCEEDED(hr)) << "CreateAsyncBindCtx"; if (bind_ctx) { ScopedComPtr<IUnknown> bscb_holder; bind_ctx->GetObjectParam(L"_BSCB_Holder_", bscb_holder.Receive()); if (bscb_holder) { hr = PatchHttpNegotiate(bscb_holder); } else { NOTREACHED() << "Failed to get _BSCB_Holder_"; hr = E_UNEXPECTED; } bind_ctx.Release(); } return SUCCEEDED(hr); } // static void HttpNegotiatePatch::Uninitialize() { vtable_patch::UnpatchInterfaceMethods(IHttpNegotiate_PatchInfo); } // static HRESULT HttpNegotiatePatch::PatchHttpNegotiate(IUnknown* to_patch) { DCHECK(to_patch); DCHECK_IS_NOT_PATCHED(IHttpNegotiate); ScopedComPtr<IHttpNegotiate> http; HRESULT hr = http.QueryFrom(to_patch); if (FAILED(hr)) { hr = DoQueryService(IID_IHttpNegotiate, to_patch, http.Receive()); } if (http) { hr = vtable_patch::PatchInterfaceMethods(http, IHttpNegotiate_PatchInfo); DLOG_IF(ERROR, FAILED(hr)) << base::StringPrintf("HttpNegotiate patch failed 0x%08X", hr); } else { DLOG(WARNING) << base::StringPrintf("IHttpNegotiate not supported 0x%08X", hr); } return hr; } // static HRESULT HttpNegotiatePatch::BeginningTransaction( IHttpNegotiate_BeginningTransaction_Fn original, IHttpNegotiate* me, LPCWSTR url, LPCWSTR headers, DWORD reserved, LPWSTR* additional_headers) { DVLOG(1) << __FUNCTION__ << " " << url << " headers:\n" << headers; HRESULT hr = original(me, url, headers, reserved, additional_headers); if (FAILED(hr)) { DLOG(WARNING) << __FUNCTION__ << " Delegate returned an error"; return hr; } if (modify_user_agent_) { std::string updated_headers; if (IsGcfDefaultRenderer() && RendererTypeForUrl(url) == RENDERER_TYPE_CHROME_DEFAULT_RENDERER) { // Replace the user-agent header with Chrome's. updated_headers = ReplaceOrAddUserAgent(*additional_headers, http_utils::GetChromeUserAgent()); } else { updated_headers = AppendCFUserAgentString(headers, *additional_headers); } *additional_headers = reinterpret_cast<wchar_t*>(::CoTaskMemRealloc( *additional_headers, (updated_headers.length() + 1) * sizeof(wchar_t))); lstrcpyW(*additional_headers, ASCIIToWide(updated_headers).c_str()); } return S_OK; } <commit_msg>Remove DCHECK for an argument that may be NULL.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome_frame/http_negotiate.h" #include <atlbase.h> #include <atlcom.h> #include <htiframe.h> #include "base/logging.h" #include "base/scoped_ptr.h" #include "base/string_util.h" #include "base/stringprintf.h" #include "base/utf_string_conversions.h" #include "chrome_frame/bho.h" #include "chrome_frame/exception_barrier.h" #include "chrome_frame/html_utils.h" #include "chrome_frame/urlmon_url_request.h" #include "chrome_frame/urlmon_moniker.h" #include "chrome_frame/utils.h" #include "chrome_frame/vtable_patch_manager.h" #include "net/http/http_response_headers.h" #include "net/http/http_util.h" bool HttpNegotiatePatch::modify_user_agent_ = true; const char kUACompatibleHttpHeader[] = "x-ua-compatible"; const char kLowerCaseUserAgent[] = "user-agent"; // From the latest urlmon.h. Symbol name prepended with LOCAL_ to // avoid conflict (and therefore build errors) for those building with // a newer Windows SDK. // TODO(robertshield): Remove this once we update our SDK version. const int LOCAL_BINDSTATUS_SERVER_MIMETYPEAVAILABLE = 54; static const int kHttpNegotiateBeginningTransactionIndex = 3; BEGIN_VTABLE_PATCHES(IHttpNegotiate) VTABLE_PATCH_ENTRY(kHttpNegotiateBeginningTransactionIndex, HttpNegotiatePatch::BeginningTransaction) END_VTABLE_PATCHES() namespace { class SimpleBindStatusCallback : public CComObjectRootEx<CComSingleThreadModel>, public IBindStatusCallback { public: BEGIN_COM_MAP(SimpleBindStatusCallback) COM_INTERFACE_ENTRY(IBindStatusCallback) END_COM_MAP() // IBindStatusCallback implementation STDMETHOD(OnStartBinding)(DWORD reserved, IBinding* binding) { return E_NOTIMPL; } STDMETHOD(GetPriority)(LONG* priority) { return E_NOTIMPL; } STDMETHOD(OnLowResource)(DWORD reserved) { return E_NOTIMPL; } STDMETHOD(OnProgress)(ULONG progress, ULONG max_progress, ULONG status_code, LPCWSTR status_text) { return E_NOTIMPL; } STDMETHOD(OnStopBinding)(HRESULT result, LPCWSTR error) { return E_NOTIMPL; } STDMETHOD(GetBindInfo)(DWORD* bind_flags, BINDINFO* bind_info) { return E_NOTIMPL; } STDMETHOD(OnDataAvailable)(DWORD flags, DWORD size, FORMATETC* formatetc, STGMEDIUM* storage) { return E_NOTIMPL; } STDMETHOD(OnObjectAvailable)(REFIID iid, IUnknown* object) { return E_NOTIMPL; } }; } // end namespace std::string AppendCFUserAgentString(LPCWSTR headers, LPCWSTR additional_headers) { using net::HttpUtil; std::string ascii_headers; if (additional_headers) { ascii_headers = WideToASCII(additional_headers); } // Extract "User-Agent" from |additional_headers| or |headers|. HttpUtil::HeadersIterator headers_iterator(ascii_headers.begin(), ascii_headers.end(), "\r\n"); std::string user_agent_value; if (headers_iterator.AdvanceTo(kLowerCaseUserAgent)) { user_agent_value = headers_iterator.values(); } else if (headers != NULL) { // See if there's a user-agent header specified in the original headers. std::string original_headers(WideToASCII(headers)); HttpUtil::HeadersIterator original_it(original_headers.begin(), original_headers.end(), "\r\n"); if (original_it.AdvanceTo(kLowerCaseUserAgent)) user_agent_value = original_it.values(); } // Use the default "User-Agent" if none was provided. if (user_agent_value.empty()) user_agent_value = http_utils::GetDefaultUserAgent(); // Now add chromeframe to it. user_agent_value = http_utils::AddChromeFrameToUserAgentValue( user_agent_value); // Build new headers, skip the existing user agent value from // existing headers. std::string new_headers; headers_iterator.Reset(); while (headers_iterator.GetNext()) { std::string name(headers_iterator.name()); if (!LowerCaseEqualsASCII(name, kLowerCaseUserAgent)) { new_headers += name + ": " + headers_iterator.values() + "\r\n"; } } new_headers += "User-Agent: " + user_agent_value; new_headers += "\r\n"; return new_headers; } std::string ReplaceOrAddUserAgent(LPCWSTR headers, const std::string& user_agent_value) { using net::HttpUtil; std::string new_headers; if (headers) { std::string ascii_headers(WideToASCII(headers)); // Extract "User-Agent" from the headers. HttpUtil::HeadersIterator headers_iterator(ascii_headers.begin(), ascii_headers.end(), "\r\n"); // Build new headers, skip the existing user agent value from // existing headers. while (headers_iterator.GetNext()) { std::string name(headers_iterator.name()); if (!LowerCaseEqualsASCII(name, kLowerCaseUserAgent)) { new_headers += name + ": " + headers_iterator.values() + "\r\n"; } } } new_headers += "User-Agent: " + user_agent_value; new_headers += "\r\n"; return new_headers; } HttpNegotiatePatch::HttpNegotiatePatch() { } HttpNegotiatePatch::~HttpNegotiatePatch() { } // static bool HttpNegotiatePatch::Initialize() { if (IS_PATCHED(IHttpNegotiate)) { DLOG(WARNING) << __FUNCTION__ << " called more than once."; return true; } // Use our SimpleBindStatusCallback class as we need a temporary object that // implements IBindStatusCallback. CComObjectStackEx<SimpleBindStatusCallback> request; ScopedComPtr<IBindCtx> bind_ctx; HRESULT hr = CreateAsyncBindCtx(0, &request, NULL, bind_ctx.Receive()); DCHECK(SUCCEEDED(hr)) << "CreateAsyncBindCtx"; if (bind_ctx) { ScopedComPtr<IUnknown> bscb_holder; bind_ctx->GetObjectParam(L"_BSCB_Holder_", bscb_holder.Receive()); if (bscb_holder) { hr = PatchHttpNegotiate(bscb_holder); } else { NOTREACHED() << "Failed to get _BSCB_Holder_"; hr = E_UNEXPECTED; } bind_ctx.Release(); } return SUCCEEDED(hr); } // static void HttpNegotiatePatch::Uninitialize() { vtable_patch::UnpatchInterfaceMethods(IHttpNegotiate_PatchInfo); } // static HRESULT HttpNegotiatePatch::PatchHttpNegotiate(IUnknown* to_patch) { DCHECK(to_patch); DCHECK_IS_NOT_PATCHED(IHttpNegotiate); ScopedComPtr<IHttpNegotiate> http; HRESULT hr = http.QueryFrom(to_patch); if (FAILED(hr)) { hr = DoQueryService(IID_IHttpNegotiate, to_patch, http.Receive()); } if (http) { hr = vtable_patch::PatchInterfaceMethods(http, IHttpNegotiate_PatchInfo); DLOG_IF(ERROR, FAILED(hr)) << base::StringPrintf("HttpNegotiate patch failed 0x%08X", hr); } else { DLOG(WARNING) << base::StringPrintf("IHttpNegotiate not supported 0x%08X", hr); } return hr; } // static HRESULT HttpNegotiatePatch::BeginningTransaction( IHttpNegotiate_BeginningTransaction_Fn original, IHttpNegotiate* me, LPCWSTR url, LPCWSTR headers, DWORD reserved, LPWSTR* additional_headers) { DVLOG(1) << __FUNCTION__ << " " << url << " headers:\n" << headers; HRESULT hr = original(me, url, headers, reserved, additional_headers); if (FAILED(hr)) { DLOG(WARNING) << __FUNCTION__ << " Delegate returned an error"; return hr; } if (modify_user_agent_) { std::string updated_headers; if (IsGcfDefaultRenderer() && RendererTypeForUrl(url) == RENDERER_TYPE_CHROME_DEFAULT_RENDERER) { // Replace the user-agent header with Chrome's. updated_headers = ReplaceOrAddUserAgent(*additional_headers, http_utils::GetChromeUserAgent()); } else { updated_headers = AppendCFUserAgentString(headers, *additional_headers); } *additional_headers = reinterpret_cast<wchar_t*>(::CoTaskMemRealloc( *additional_headers, (updated_headers.length() + 1) * sizeof(wchar_t))); lstrcpyW(*additional_headers, ASCIIToWide(updated_headers).c_str()); } return S_OK; } <|endoftext|>
<commit_before>/******************************************************************************\ * File: tool.cpp * Purpose: Implementation of wxExTool class * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/config.h> #include <wx/stdpaths.h> #include <wx/textfile.h> #include <wx/extension/tool.h> #include <wx/extension/frame.h> #include <wx/extension/log.h> #include <wx/extension/statistics.h> #include <wx/extension/svn.h> wxExTool* wxExTool::m_Self = NULL; wxExTool::wxExTool(int type) : m_Id(type) { } wxExTool* wxExTool::Get(bool createOnDemand) { if (m_Self == NULL && createOnDemand) { m_Self = new wxExTool(0); if (!wxExSVN::Get()->Use()) { m_Self->AddInfo(ID_TOOL_REVISION_RECENT, _("Recent revision from")); m_Self->AddInfo(ID_TOOL_REPORT_REVISION, _("Reported %ld revisions in"), _("Report &Revision")); } m_Self->AddInfo(ID_TOOL_LINE_CODE, _("Parsed code lines")); m_Self->AddInfo(ID_TOOL_LINE_COMMENT, _("Parsed comment lines")); m_Self->AddInfo(ID_TOOL_REPORT_COUNT, _("Counted"), _("Report &Count")); m_Self->AddInfo(ID_TOOL_REPORT_FIND, _("Found %ld matches in")); m_Self->AddInfo(ID_TOOL_REPORT_REPLACE, _("Replaced %ld matches in")); m_Self->AddInfo(ID_TOOL_REPORT_KEYWORD, _("Reported %ld keywords in"), _("Report &Keyword")); } return m_Self; } const wxString wxExTool::Info() const { std::map < int, wxExToolInfo >::const_iterator it = m_Self->m_ToolInfo.find(m_Id); if (it != m_Self->m_ToolInfo.end()) { return it->second.GetInfo(); } wxFAIL; return wxEmptyString; } void wxExTool::Log( wxExStatistics<long>* stat, const wxString& caption, bool log_to_file) const { // This is no error, if you run a tool and you cancelled everything, // the elements will be empty, so just quit. if (stat->GetItems().empty()) { return; } wxString logtext(Info()); if (logtext.Contains("%ld")) { logtext = logtext.Format(logtext, stat->Get(_("Actions Completed"))); } logtext << " " << stat->Get(_("Files Passed")) << " " << _("file(s)") << (!caption.empty() ? ": " + caption: ""); #if wxUSE_STATUSBAR wxExFrame::StatusText(logtext); #endif if (log_to_file && stat->Get(_("Files Passed")) != 0) { wxExLog::Get()->Log(logtext); if (IsCount()) { wxString logtext; logtext << caption << stat->Get() << wxTextFile::GetEOL(); wxExLog log(GetLogfileName()); log.Log(logtext); } } } const wxFileName wxExTool::GetLogfileName() const { wxFileName filename( #ifdef wxExUSE_PORTABLE wxPathOnly(wxStandardPaths::Get().GetExecutablePath()) #else wxStandardPaths::Get().GetUserDataDir() #endif + wxFileName::GetPathSeparator() + _("statistics.log")); return filename; } wxExTool* wxExTool::Set(wxExTool* tool) { wxExTool* old = m_Self; m_Self = tool; return old; } <commit_msg>removed check on empty statistics<commit_after>/******************************************************************************\ * File: tool.cpp * Purpose: Implementation of wxExTool class * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/config.h> #include <wx/stdpaths.h> #include <wx/textfile.h> #include <wx/extension/tool.h> #include <wx/extension/frame.h> #include <wx/extension/log.h> #include <wx/extension/statistics.h> #include <wx/extension/svn.h> wxExTool* wxExTool::m_Self = NULL; wxExTool::wxExTool(int type) : m_Id(type) { } wxExTool* wxExTool::Get(bool createOnDemand) { if (m_Self == NULL && createOnDemand) { m_Self = new wxExTool(0); if (!wxExSVN::Get()->Use()) { m_Self->AddInfo(ID_TOOL_REVISION_RECENT, _("Recent revision from")); m_Self->AddInfo(ID_TOOL_REPORT_REVISION, _("Reported %ld revisions in"), _("Report &Revision")); } m_Self->AddInfo(ID_TOOL_LINE_CODE, _("Parsed code lines")); m_Self->AddInfo(ID_TOOL_LINE_COMMENT, _("Parsed comment lines")); m_Self->AddInfo(ID_TOOL_REPORT_COUNT, _("Counted"), _("Report &Count")); m_Self->AddInfo(ID_TOOL_REPORT_FIND, _("Found %ld matches in")); m_Self->AddInfo(ID_TOOL_REPORT_REPLACE, _("Replaced %ld matches in")); m_Self->AddInfo(ID_TOOL_REPORT_KEYWORD, _("Reported %ld keywords in"), _("Report &Keyword")); } return m_Self; } const wxString wxExTool::Info() const { std::map < int, wxExToolInfo >::const_iterator it = m_Self->m_ToolInfo.find(m_Id); if (it != m_Self->m_ToolInfo.end()) { return it->second.GetInfo(); } wxFAIL; return wxEmptyString; } void wxExTool::Log( wxExStatistics<long>* stat, const wxString& caption, bool log_to_file) const { wxString logtext(Info()); if (logtext.Contains("%ld")) { logtext = logtext.Format(logtext, stat->Get(_("Actions Completed"))); } logtext << " " << stat->Get(_("Files Passed")) << " " << _("file(s)") << (!caption.empty() ? ": " + caption: ""); #if wxUSE_STATUSBAR wxExFrame::StatusText(logtext); #endif if (log_to_file && stat->Get(_("Files Passed")) != 0) { wxExLog::Get()->Log(logtext); if (IsCount()) { wxString logtext; logtext << caption << stat->Get() << wxTextFile::GetEOL(); wxExLog log(GetLogfileName()); log.Log(logtext); } } } const wxFileName wxExTool::GetLogfileName() const { wxFileName filename( #ifdef wxExUSE_PORTABLE wxPathOnly(wxStandardPaths::Get().GetExecutablePath()) #else wxStandardPaths::Get().GetUserDataDir() #endif + wxFileName::GetPathSeparator() + _("statistics.log")); return filename; } wxExTool* wxExTool::Set(wxExTool* tool) { wxExTool* old = m_Self; m_Self = tool; return old; } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ #if !defined(__CINT__) || defined(__MAKECINT__) //#include "iostream.h" #include <TClassTable.h> #include <TClonesArray.h> #include <TFile.h> #include <TParticle.h> #include <TROOT.h> #include <TTree.h> #include "AliHeader.h" #include "AliRun.h" #include "AliRunLoader.h" #include "AliMagF.h" #include "AliMUON.h" #include "AliMUONDisplay.h" #endif void MUONdisplay (Int_t nevent=0, TString fileName="galice.root", TString fileNameSim="galice_sim.root") { // set off mag field AliMagF::SetReadField(kFALSE); // Getting runloader AliRunLoader * RunLoaderSim = AliRunLoader::Open(fileNameSim.Data(),"MUONFolderSim","READ"); if (RunLoaderSim == 0x0) { Error("MUONdisplay","Inut file %s error!",fileName.Data()); return; } RunLoaderSim->LoadHeader(); RunLoaderSim->LoadKinematics("READ"); // if (RunLoader->GetAliRun() == 0x0) RunLoaderSim->LoadgAlice(); gAlice = RunLoaderSim->GetAliRun(); // Getting MUONloader AliLoader * MUONLoaderSim = RunLoaderSim->GetLoader("MUONLoader"); MUONLoaderSim->LoadHits("READ"); MUONLoaderSim->LoadDigits("READ"); // Getting runloader AliRunLoader * RunLoaderRec = AliRunLoader::Open(fileName.Data(),"MUONFolder","READ"); if (RunLoaderRec == 0x0) { Error("MUONdisplay","Inut file %s error!",fileName.Data()); return; } AliLoader * MUONLoaderRec = RunLoaderRec->GetLoader("MUONLoader"); MUONLoaderRec->LoadRecPoints("READ"); MUONLoaderRec->LoadTracks("READ"); // Create Event Display object AliMUONDisplay *muondisplay = new AliMUONDisplay(750, MUONLoaderSim, MUONLoaderRec); // Display first event RunLoaderSim->GetEvent(nevent); RunLoaderRec->GetEvent(nevent); muondisplay->ShowNextEvent(0); } <commit_msg>Removing macro with removal of AliMUONDisplay class<commit_after><|endoftext|>
<commit_before>// // Copyright (C) 2013 // Alessio Sclocco <a.sclocco@vu.nl> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // 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, see <http://www.gnu.org/licenses/>. // #include <iostream> using std::cout; using std::cerr; using std::endl; using std::fixed; #include <string> using std::string; #include <vector> using std::vector; #include <exception> using std::exception; #include <fstream> using std::ofstream; #include <iomanip> using std::setprecision; #include <limits> using std::numeric_limits; #include <cmath> #include <ArgumentList.hpp> using isa::utils::ArgumentList; #include <Observation.hpp> using AstroData::Observation; #include <InitializeOpenCL.hpp> using isa::OpenCL::initializeOpenCL; #include <CLData.hpp> using isa::OpenCL::CLData; #include <utils.hpp> using isa::utils::toStringValue; #include <SNR.hpp> using PulsarSearch::SNR; #include <Timer.hpp> using isa::utils::Timer; typedef float dataType; const string typeName("float"); int main(int argc, char * argv[]) { unsigned int nrIterations = 0; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; unsigned int minThreads = 0; unsigned int maxThreadsPerBlock = 0; unsigned int maxRows = 0; Observation< dataType > observation("SNRTuning", typeName); CLData< dataType > * foldedData = new CLData< dataType >("FoldedData", true); CLData< dataType > * SNRData = new CLData< dataType >("SNRData", true); try { ArgumentList args(argc, argv); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); nrIterations = args.getSwitchArgument< unsigned int >("-iterations"); observation.setPadding(args.getSwitchArgument< unsigned int >("-padding")); minThreads = args.getSwitchArgument< unsigned int >("-min_threads"); maxThreadsPerBlock = args.getSwitchArgument< unsigned int >("-max_threads"); maxRows = args.getSwitchArgument< unsigned int >("-max_rows"); observation.setNrDMs(args.getSwitchArgument< unsigned int >("-dms")); observation.setNrPeriods(args.getSwitchArgument< unsigned int >("-periods")); observation.setNrBins(args.getSwitchArgument< unsigned int >("-bins")); } catch ( EmptyCommandLine err ) { cerr << argv[0] << " -iterations ... -opencl_platform ... -opencl_device ... -padding ... -min_threads ... -max_threads ... -max_rows ... -dms ... -periods ... -bins ..." << endl; return 1; } catch ( exception & err ) { cerr << err.what() << endl; return 1; } cl::Context * clContext = new cl::Context(); vector< cl::Platform > * clPlatforms = new vector< cl::Platform >(); vector< cl::Device > * clDevices = new vector< cl::Device >(); vector< vector< cl::CommandQueue > > * clQueues = new vector< vector < cl::CommandQueue > >(); initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues); cout << fixed << endl; cout << "# nrDMs nrPeriods nrBins nrDMsPerBlock nrPeriodsPerBlock GFLOP/s err time err GB/s err " << endl << endl; // Allocate memory foldedData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods()); SNRData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrPeriods()); foldedData->setCLContext(clContext); foldedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); SNRData->setCLContext(clContext); SNRData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); try { foldedData->allocateDeviceData(); foldedData->copyHostToDevice(); SNRData->allocateDeviceData(); } catch ( OpenCLError err ) { cerr << err.what() << endl; } // Find the parameters vector< unsigned int > DMsPerBlock; for ( unsigned int DMs = minThreads; DMs <= maxThreadsPerBlock; DMs += minThreads ) { if ( (observation.getNrPaddedDMs() % DMs) == 0 ) { DMsPerBlock.push_back(DMs); } } vector< unsigned int > periodsPerBlock; for ( unsigned int periods = 1; periods <= maxThreadsPerBlock; periods++ ) { if ( (observation.getNrPeriods() % periods) == 0 ) { periodsPerBlock.push_back(periods); } } for ( vector< unsigned int >::iterator DMs = DMsPerBlock.begin(); DMs != DMsPerBlock.end(); DMs++ ) { for ( vector< unsigned int >::iterator periods = periodsPerBlock.begin(); periods != periodsPerBlock.end(); periods++ ) { if ( (*DMs * *periods) > maxThreadsPerBlock ) { break; } double Acur[2] = {0.0, 0.0}; double Aold[2] = {0.0, 0.0}; double Vcur[2] = {0.0, 0.0}; double Vold[2] = {0.0, 0.0}; try { // Generate kernel SNR< dataType > clSNR("clSNR", typeName); clSNR.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0))); clSNR.setObservation(&observation); clSNR.setNrDMsPerBlock(*DMs); clSNR.setNrPeriodsPerBlock(*periods); clSNR.setPulsarPipeline(); clSNR.generateCode(); // Warming up clSNR(foldedData, SNRData); (clSNR.getTimer()).reset(); // Measurements for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) { clSNR(foldedData, SNRData); if ( iteration == 0 ) { Acur[0] = clSNR.getGFLOP() / clSNR.getTimer().getLastRunTime(); Acur[1] = clSNR.getGB() / clSNR.getTimer().getLastRunTime(); } else { Aold[0] = Acur[0]; Vold[0] = Vcur[0]; Acur[0] = Aold[0] + (((clSNR.getGFLOP() / clSNR.getTimer().getLastRunTime()) - Aold[0]) / (iteration + 1)); Vcur[0] = Vold[0] + (((clSNR.getGFLOP() / clSNR.getTimer().getLastRunTime()) - Aold[0]) * ((clSNR.getGFLOP() / clSNR.getTimer().getLastRunTime()) - Acur[0])); Aold[1] = Acur[1]; Vold[1] = Vcur[1]; Acur[1] = Aold[1] + (((clSNR.getGB() / clSNR.getTimer().getLastRunTime()) - Aold[1]) / (iteration + 1)); Vcur[1] = Vold[1] + (((clSNR.getGB() / clSNR.getTimer().getLastRunTime()) - Aold[1]) * ((clSNR.getGB() / clSNR.getTimer().getLastRunTime()) - Acur[1])); } } Vcur[0] = sqrt(Vcur[0] / nrIterations); Vcur[1] = sqrt(Vcur[1] / nrIterations); cout << observation.getNrDMs() << " " << observation.getNrPeriods() << " " << observation.getNrBins() << " " << *DMs << " " << *periods << " " << setprecision(3) << Acur[0] << " " << Vcur[0] << " " << setprecision(6) << clSNR.getTimer().getAverageTime() << " " << clSNR.getTimer().getStdDev() << " " << setprecision(3) << Acur[1] << " " << Vcur[1] << endl; } catch ( OpenCLError err ) { cerr << err.what() << endl; continue; } } } cout << endl; return 0; } <commit_msg>Average GFLOP/s GB/s and errors are computed in the kernel.<commit_after>// // Copyright (C) 2013 // Alessio Sclocco <a.sclocco@vu.nl> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // 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, see <http://www.gnu.org/licenses/>. // #include <iostream> using std::cout; using std::cerr; using std::endl; using std::fixed; #include <string> using std::string; #include <vector> using std::vector; #include <exception> using std::exception; #include <fstream> using std::ofstream; #include <iomanip> using std::setprecision; #include <limits> using std::numeric_limits; #include <cmath> #include <ArgumentList.hpp> using isa::utils::ArgumentList; #include <Observation.hpp> using AstroData::Observation; #include <InitializeOpenCL.hpp> using isa::OpenCL::initializeOpenCL; #include <CLData.hpp> using isa::OpenCL::CLData; #include <utils.hpp> using isa::utils::toStringValue; #include <SNR.hpp> using PulsarSearch::SNR; #include <Timer.hpp> using isa::utils::Timer; typedef float dataType; const string typeName("float"); int main(int argc, char * argv[]) { unsigned int nrIterations = 0; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; unsigned int minThreads = 0; unsigned int maxThreadsPerBlock = 0; unsigned int maxRows = 0; Observation< dataType > observation("SNRTuning", typeName); CLData< dataType > * foldedData = new CLData< dataType >("FoldedData", true); CLData< dataType > * SNRData = new CLData< dataType >("SNRData", true); try { ArgumentList args(argc, argv); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); nrIterations = args.getSwitchArgument< unsigned int >("-iterations"); observation.setPadding(args.getSwitchArgument< unsigned int >("-padding")); minThreads = args.getSwitchArgument< unsigned int >("-min_threads"); maxThreadsPerBlock = args.getSwitchArgument< unsigned int >("-max_threads"); maxRows = args.getSwitchArgument< unsigned int >("-max_rows"); observation.setNrDMs(args.getSwitchArgument< unsigned int >("-dms")); observation.setNrPeriods(args.getSwitchArgument< unsigned int >("-periods")); observation.setNrBins(args.getSwitchArgument< unsigned int >("-bins")); } catch ( EmptyCommandLine err ) { cerr << argv[0] << " -iterations ... -opencl_platform ... -opencl_device ... -padding ... -min_threads ... -max_threads ... -max_rows ... -dms ... -periods ... -bins ..." << endl; return 1; } catch ( exception & err ) { cerr << err.what() << endl; return 1; } cl::Context * clContext = new cl::Context(); vector< cl::Platform > * clPlatforms = new vector< cl::Platform >(); vector< cl::Device > * clDevices = new vector< cl::Device >(); vector< vector< cl::CommandQueue > > * clQueues = new vector< vector < cl::CommandQueue > >(); initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues); cout << fixed << endl; cout << "# nrDMs nrPeriods nrBins nrDMsPerBlock nrPeriodsPerBlock GFLOP/s err time err GB/s err " << endl << endl; // Allocate memory foldedData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods()); SNRData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrPeriods()); foldedData->setCLContext(clContext); foldedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); SNRData->setCLContext(clContext); SNRData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); try { foldedData->allocateDeviceData(); foldedData->copyHostToDevice(); SNRData->allocateDeviceData(); } catch ( OpenCLError err ) { cerr << err.what() << endl; } // Find the parameters vector< unsigned int > DMsPerBlock; for ( unsigned int DMs = minThreads; DMs <= maxThreadsPerBlock; DMs += minThreads ) { if ( (observation.getNrPaddedDMs() % DMs) == 0 ) { DMsPerBlock.push_back(DMs); } } vector< unsigned int > periodsPerBlock; for ( unsigned int periods = 1; periods <= maxThreadsPerBlock; periods++ ) { if ( (observation.getNrPeriods() % periods) == 0 ) { periodsPerBlock.push_back(periods); } } for ( vector< unsigned int >::iterator DMs = DMsPerBlock.begin(); DMs != DMsPerBlock.end(); DMs++ ) { for ( vector< unsigned int >::iterator periods = periodsPerBlock.begin(); periods != periodsPerBlock.end(); periods++ ) { if ( (*DMs * *periods) > maxThreadsPerBlock ) { break; } try { // Generate kernel SNR< dataType > clSNR("clSNR", typeName); clSNR.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0))); clSNR.setObservation(&observation); clSNR.setNrDMsPerBlock(*DMs); clSNR.setNrPeriodsPerBlock(*periods); clSNR.setPulsarPipeline(); clSNR.generateCode(); // Warming up clSNR(foldedData, SNRData); (clSNR.getTimer()).reset(); // Measurements for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) { clSNR(foldedData, SNRData); } cout << observation.getNrDMs() << " " << observation.getNrPeriods() << " " << observation.getNrBins() << " " << *DMs << " " << *periods << " " << setprecision(3) << clSNR.getGFLOPs() << " " << clSNR.getGFLOPsErr() << " " << setprecision(6) << clSNR.getTimer().getAverageTime() << " " << clSNR.getTimer().getStdDev() << " " << setprecision(3) << clSNR.getGBs() << " " << clSNR.getGBsErr() << endl; } catch ( OpenCLError err ) { cerr << err.what() << endl; continue; } } } cout << endl; return 0; } <|endoftext|>
<commit_before>#include "tests/ffi/tests.h" #include "tests/ffi/lib.rs.h" #include <cstring> #include <numeric> #include <stdexcept> extern "C" void cxx_test_suite_set_correct() noexcept; extern "C" tests::R *cxx_test_suite_get_box() noexcept; extern "C" bool cxx_test_suite_r_is_correct(const tests::R *) noexcept; namespace tests { const char *SLICE_DATA = "2020"; C::C(size_t n) : n(n) {} size_t C::get() const { return this->n; } size_t C::get2() const { return this->n; } size_t C::set(size_t n) { this->n = n; return this->n; } size_t C::set2(size_t n) { this->n = n; return this->n; } const std::vector<uint8_t> &C::get_v() const { return this->v; } size_t c_return_primitive() { return 2020; } Shared c_return_shared() { return Shared{2020}; } rust::Box<R> c_return_box() { return rust::Box<R>::from_raw(cxx_test_suite_get_box()); } std::unique_ptr<C> c_return_unique_ptr() { return std::unique_ptr<C>(new C{2020}); } const size_t &c_return_ref(const Shared &shared) { return shared.z; } rust::Str c_return_str(const Shared &shared) { (void)shared; return "2020"; } rust::Slice<uint8_t> c_return_sliceu8(const Shared &shared) { (void)shared; return rust::Slice<uint8_t>(reinterpret_cast<const uint8_t *>(SLICE_DATA), 5); } rust::String c_return_rust_string() { return "2020"; } std::unique_ptr<std::string> c_return_unique_ptr_string() { return std::unique_ptr<std::string>(new std::string("2020")); } std::unique_ptr<std::vector<uint8_t>> c_return_unique_ptr_vector_u8() { auto vec = std::unique_ptr<std::vector<uint8_t>>(new std::vector<uint8_t>()); vec->push_back(86); vec->push_back(75); vec->push_back(30); vec->push_back(9); return vec; } std::unique_ptr<std::vector<double>> c_return_unique_ptr_vector_f64() { auto vec = std::unique_ptr<std::vector<double>>(new std::vector<double>()); vec->push_back(86.0); vec->push_back(75.0); vec->push_back(30.0); vec->push_back(9.5); return vec; } std::unique_ptr<std::vector<Shared>> c_return_unique_ptr_vector_shared() { auto vec = std::unique_ptr<std::vector<Shared>>(new std::vector<Shared>()); vec->push_back(Shared{1010}); vec->push_back(Shared{1011}); return vec; } std::unique_ptr<std::vector<C>> c_return_unique_ptr_vector_opaque() { return std::unique_ptr<std::vector<C>>(new std::vector<C>()); } const std::vector<uint8_t> &c_return_ref_vector(const C &c) { return c.get_v(); } rust::Vec<uint8_t> c_return_rust_vec() { throw std::runtime_error("unimplemented"); } const rust::Vec<uint8_t> &c_return_ref_rust_vec(const C &c) { (void)c; throw std::runtime_error("unimplemented"); } size_t c_return_identity(size_t n) { return n; } size_t c_return_sum(size_t n1, size_t n2) { return n1 + n2; } Enum c_return_enum(uint32_t n) { if (n <= static_cast<uint32_t>(Enum::AVal)) { return Enum::AVal; } else if (n <= static_cast<uint32_t>(Enum::BVal)) { return Enum::BVal; } else { return Enum::CVal; } } void c_take_primitive(size_t n) { if (n == 2020) { cxx_test_suite_set_correct(); } } void c_take_shared(Shared shared) { if (shared.z == 2020) { cxx_test_suite_set_correct(); } } void c_take_box(rust::Box<R> r) { if (cxx_test_suite_r_is_correct(&*r)) { cxx_test_suite_set_correct(); } } void c_take_unique_ptr(std::unique_ptr<C> c) { if (c->get() == 2020) { cxx_test_suite_set_correct(); } } void c_take_ref_r(const R &r) { if (cxx_test_suite_r_is_correct(&r)) { cxx_test_suite_set_correct(); } } void c_take_ref_c(const C &c) { if (c.get() == 2020) { cxx_test_suite_set_correct(); } } void c_take_str(rust::Str s) { if (std::string(s) == "2020") { cxx_test_suite_set_correct(); } } void c_take_sliceu8(rust::Slice<uint8_t> s) { if (std::string(reinterpret_cast<const char *>(s.data()), s.size()) == "2020") { cxx_test_suite_set_correct(); } } void c_take_rust_string(rust::String s) { if (std::string(s) == "2020") { cxx_test_suite_set_correct(); } } void c_take_unique_ptr_string(std::unique_ptr<std::string> s) { if (*s == "2020") { cxx_test_suite_set_correct(); } } void c_take_unique_ptr_vector_u8(std::unique_ptr<std::vector<uint8_t>> v) { if (v->size() == 4) { cxx_test_suite_set_correct(); } } void c_take_unique_ptr_vector_f64(std::unique_ptr<std::vector<double>> v) { if (v->size() == 4) { cxx_test_suite_set_correct(); } } void c_take_unique_ptr_vector_shared(std::unique_ptr<std::vector<Shared>> v) { if (v->size() == 2) { cxx_test_suite_set_correct(); } } void c_take_ref_vector(const std::vector<uint8_t> &v) { if (v.size() == 4) { cxx_test_suite_set_correct(); } } void c_take_rust_vec(rust::Vec<uint8_t> v) { c_take_ref_rust_vec(v); } void c_take_rust_vec_shared(rust::Vec<Shared> v) { uint32_t sum = 0; for (auto i : v) { sum += i.z; } if (sum == 2021) { cxx_test_suite_set_correct(); } } void c_take_rust_vec_shared_forward_iterator(rust::Vec<Shared> v) { // Exercise requirements of ForwardIterator // https://en.cppreference.com/w/cpp/named_req/ForwardIterator uint32_t sum = 0; for (auto it = v.begin(), it_end = v.end(); it != it_end; it++) { sum += it->z; } if (sum == 2021) { cxx_test_suite_set_correct(); } } void c_take_ref_rust_vec(const rust::Vec<uint8_t> &v) { uint8_t sum = std::accumulate(v.begin(), v.end(), 0); if (sum == 200) { cxx_test_suite_set_correct(); } } void c_take_ref_rust_vec_copy(const rust::Vec<uint8_t> &v) { // The std::copy() will make sure rust::Vec<>::const_iterator satisfies the // requirements for std::iterator_traits. // https://en.cppreference.com/w/cpp/iterator/iterator_traits std::vector<uint8_t> cxx_v; std::copy(v.begin(), v.end(), back_inserter(cxx_v)); uint8_t sum = std::accumulate(cxx_v.begin(), cxx_v.end(), 0); if (sum == 200) { cxx_test_suite_set_correct(); } } void c_take_callback(rust::Fn<size_t(rust::String)> callback) { callback("2020"); } void c_take_enum(Enum e) { if (e == Enum::AVal) { cxx_test_suite_set_correct(); } } void c_try_return_void() {} size_t c_try_return_primitive() { return 2020; } size_t c_fail_return_primitive() { throw std::logic_error("logic error"); } rust::Box<R> c_try_return_box() { return c_return_box(); } const rust::String &c_try_return_ref(const rust::String &s) { return s; } rust::Str c_try_return_str(rust::Str s) { return s; } rust::Slice<uint8_t> c_try_return_sliceu8(rust::Slice<uint8_t> s) { return s; } rust::String c_try_return_rust_string() { return c_return_rust_string(); } std::unique_ptr<std::string> c_try_return_unique_ptr_string() { return c_return_unique_ptr_string(); } rust::Vec<uint8_t> c_try_return_rust_vec() { throw std::runtime_error("unimplemented"); } const rust::Vec<uint8_t> &c_try_return_ref_rust_vec(const C &c) { (void)c; throw std::runtime_error("unimplemented"); } extern "C" C *cxx_test_suite_get_unique_ptr() noexcept { return std::unique_ptr<C>(new C{2020}).release(); } extern "C" std::string *cxx_test_suite_get_unique_ptr_string() noexcept { return std::unique_ptr<std::string>(new std::string("2020")).release(); } extern "C" const char *cxx_run_test() noexcept { #define STRINGIFY(x) #x #define TOSTRING(x) STRINGIFY(x) #define ASSERT(x) \ do { \ if (!(x)) { \ return "Assertion failed: `" #x "`, " __FILE__ ":" TOSTRING(__LINE__); \ } \ } while (false) ASSERT(r_return_primitive() == 2020); ASSERT(r_return_shared().z == 2020); ASSERT(cxx_test_suite_r_is_correct(&*r_return_box())); ASSERT(r_return_unique_ptr()->get() == 2020); ASSERT(r_return_ref(Shared{2020}) == 2020); ASSERT(std::string(r_return_str(Shared{2020})) == "2020"); ASSERT(std::string(r_return_rust_string()) == "2020"); ASSERT(*r_return_unique_ptr_string() == "2020"); ASSERT(r_return_identity(2020) == 2020); ASSERT(r_return_sum(2020, 1) == 2021); ASSERT(r_return_enum(0) == Enum::AVal); ASSERT(r_return_enum(1) == Enum::BVal); ASSERT(r_return_enum(2021) == Enum::CVal); r_take_primitive(2020); r_take_shared(Shared{2020}); r_take_unique_ptr(std::unique_ptr<C>(new C{2020})); r_take_ref_c(C{2020}); r_take_str(rust::Str("2020")); r_take_sliceu8( rust::Slice<uint8_t>(reinterpret_cast<const uint8_t *>(SLICE_DATA), 5)); r_take_rust_string(rust::String("2020")); r_take_unique_ptr_string( std::unique_ptr<std::string>(new std::string("2020"))); r_take_enum(Enum::AVal); ASSERT(r_try_return_primitive() == 2020); try { r_fail_return_primitive(); ASSERT(false); } catch (const rust::Error &e) { ASSERT(std::strcmp(e.what(), "rust error") == 0); } auto r2 = r_return_r2(2020); ASSERT(r2->get() == 2020); ASSERT(r2->set(2021) == 2021); ASSERT(r2->get() == 2021); ASSERT(r2->set(2020) == 2020); ASSERT(r2->get() == 2020); cxx_test_suite_set_correct(); return nullptr; } } // namespace tests <commit_msg>Avoid relying on ADL for std::back_inserter<commit_after>#include "tests/ffi/tests.h" #include "tests/ffi/lib.rs.h" #include <cstring> #include <numeric> #include <stdexcept> extern "C" void cxx_test_suite_set_correct() noexcept; extern "C" tests::R *cxx_test_suite_get_box() noexcept; extern "C" bool cxx_test_suite_r_is_correct(const tests::R *) noexcept; namespace tests { const char *SLICE_DATA = "2020"; C::C(size_t n) : n(n) {} size_t C::get() const { return this->n; } size_t C::get2() const { return this->n; } size_t C::set(size_t n) { this->n = n; return this->n; } size_t C::set2(size_t n) { this->n = n; return this->n; } const std::vector<uint8_t> &C::get_v() const { return this->v; } size_t c_return_primitive() { return 2020; } Shared c_return_shared() { return Shared{2020}; } rust::Box<R> c_return_box() { return rust::Box<R>::from_raw(cxx_test_suite_get_box()); } std::unique_ptr<C> c_return_unique_ptr() { return std::unique_ptr<C>(new C{2020}); } const size_t &c_return_ref(const Shared &shared) { return shared.z; } rust::Str c_return_str(const Shared &shared) { (void)shared; return "2020"; } rust::Slice<uint8_t> c_return_sliceu8(const Shared &shared) { (void)shared; return rust::Slice<uint8_t>(reinterpret_cast<const uint8_t *>(SLICE_DATA), 5); } rust::String c_return_rust_string() { return "2020"; } std::unique_ptr<std::string> c_return_unique_ptr_string() { return std::unique_ptr<std::string>(new std::string("2020")); } std::unique_ptr<std::vector<uint8_t>> c_return_unique_ptr_vector_u8() { auto vec = std::unique_ptr<std::vector<uint8_t>>(new std::vector<uint8_t>()); vec->push_back(86); vec->push_back(75); vec->push_back(30); vec->push_back(9); return vec; } std::unique_ptr<std::vector<double>> c_return_unique_ptr_vector_f64() { auto vec = std::unique_ptr<std::vector<double>>(new std::vector<double>()); vec->push_back(86.0); vec->push_back(75.0); vec->push_back(30.0); vec->push_back(9.5); return vec; } std::unique_ptr<std::vector<Shared>> c_return_unique_ptr_vector_shared() { auto vec = std::unique_ptr<std::vector<Shared>>(new std::vector<Shared>()); vec->push_back(Shared{1010}); vec->push_back(Shared{1011}); return vec; } std::unique_ptr<std::vector<C>> c_return_unique_ptr_vector_opaque() { return std::unique_ptr<std::vector<C>>(new std::vector<C>()); } const std::vector<uint8_t> &c_return_ref_vector(const C &c) { return c.get_v(); } rust::Vec<uint8_t> c_return_rust_vec() { throw std::runtime_error("unimplemented"); } const rust::Vec<uint8_t> &c_return_ref_rust_vec(const C &c) { (void)c; throw std::runtime_error("unimplemented"); } size_t c_return_identity(size_t n) { return n; } size_t c_return_sum(size_t n1, size_t n2) { return n1 + n2; } Enum c_return_enum(uint32_t n) { if (n <= static_cast<uint32_t>(Enum::AVal)) { return Enum::AVal; } else if (n <= static_cast<uint32_t>(Enum::BVal)) { return Enum::BVal; } else { return Enum::CVal; } } void c_take_primitive(size_t n) { if (n == 2020) { cxx_test_suite_set_correct(); } } void c_take_shared(Shared shared) { if (shared.z == 2020) { cxx_test_suite_set_correct(); } } void c_take_box(rust::Box<R> r) { if (cxx_test_suite_r_is_correct(&*r)) { cxx_test_suite_set_correct(); } } void c_take_unique_ptr(std::unique_ptr<C> c) { if (c->get() == 2020) { cxx_test_suite_set_correct(); } } void c_take_ref_r(const R &r) { if (cxx_test_suite_r_is_correct(&r)) { cxx_test_suite_set_correct(); } } void c_take_ref_c(const C &c) { if (c.get() == 2020) { cxx_test_suite_set_correct(); } } void c_take_str(rust::Str s) { if (std::string(s) == "2020") { cxx_test_suite_set_correct(); } } void c_take_sliceu8(rust::Slice<uint8_t> s) { if (std::string(reinterpret_cast<const char *>(s.data()), s.size()) == "2020") { cxx_test_suite_set_correct(); } } void c_take_rust_string(rust::String s) { if (std::string(s) == "2020") { cxx_test_suite_set_correct(); } } void c_take_unique_ptr_string(std::unique_ptr<std::string> s) { if (*s == "2020") { cxx_test_suite_set_correct(); } } void c_take_unique_ptr_vector_u8(std::unique_ptr<std::vector<uint8_t>> v) { if (v->size() == 4) { cxx_test_suite_set_correct(); } } void c_take_unique_ptr_vector_f64(std::unique_ptr<std::vector<double>> v) { if (v->size() == 4) { cxx_test_suite_set_correct(); } } void c_take_unique_ptr_vector_shared(std::unique_ptr<std::vector<Shared>> v) { if (v->size() == 2) { cxx_test_suite_set_correct(); } } void c_take_ref_vector(const std::vector<uint8_t> &v) { if (v.size() == 4) { cxx_test_suite_set_correct(); } } void c_take_rust_vec(rust::Vec<uint8_t> v) { c_take_ref_rust_vec(v); } void c_take_rust_vec_shared(rust::Vec<Shared> v) { uint32_t sum = 0; for (auto i : v) { sum += i.z; } if (sum == 2021) { cxx_test_suite_set_correct(); } } void c_take_rust_vec_shared_forward_iterator(rust::Vec<Shared> v) { // Exercise requirements of ForwardIterator // https://en.cppreference.com/w/cpp/named_req/ForwardIterator uint32_t sum = 0; for (auto it = v.begin(), it_end = v.end(); it != it_end; it++) { sum += it->z; } if (sum == 2021) { cxx_test_suite_set_correct(); } } void c_take_ref_rust_vec(const rust::Vec<uint8_t> &v) { uint8_t sum = std::accumulate(v.begin(), v.end(), 0); if (sum == 200) { cxx_test_suite_set_correct(); } } void c_take_ref_rust_vec_copy(const rust::Vec<uint8_t> &v) { // The std::copy() will make sure rust::Vec<>::const_iterator satisfies the // requirements for std::iterator_traits. // https://en.cppreference.com/w/cpp/iterator/iterator_traits std::vector<uint8_t> cxx_v; std::copy(v.begin(), v.end(), std::back_inserter(cxx_v)); uint8_t sum = std::accumulate(cxx_v.begin(), cxx_v.end(), 0); if (sum == 200) { cxx_test_suite_set_correct(); } } void c_take_callback(rust::Fn<size_t(rust::String)> callback) { callback("2020"); } void c_take_enum(Enum e) { if (e == Enum::AVal) { cxx_test_suite_set_correct(); } } void c_try_return_void() {} size_t c_try_return_primitive() { return 2020; } size_t c_fail_return_primitive() { throw std::logic_error("logic error"); } rust::Box<R> c_try_return_box() { return c_return_box(); } const rust::String &c_try_return_ref(const rust::String &s) { return s; } rust::Str c_try_return_str(rust::Str s) { return s; } rust::Slice<uint8_t> c_try_return_sliceu8(rust::Slice<uint8_t> s) { return s; } rust::String c_try_return_rust_string() { return c_return_rust_string(); } std::unique_ptr<std::string> c_try_return_unique_ptr_string() { return c_return_unique_ptr_string(); } rust::Vec<uint8_t> c_try_return_rust_vec() { throw std::runtime_error("unimplemented"); } const rust::Vec<uint8_t> &c_try_return_ref_rust_vec(const C &c) { (void)c; throw std::runtime_error("unimplemented"); } extern "C" C *cxx_test_suite_get_unique_ptr() noexcept { return std::unique_ptr<C>(new C{2020}).release(); } extern "C" std::string *cxx_test_suite_get_unique_ptr_string() noexcept { return std::unique_ptr<std::string>(new std::string("2020")).release(); } extern "C" const char *cxx_run_test() noexcept { #define STRINGIFY(x) #x #define TOSTRING(x) STRINGIFY(x) #define ASSERT(x) \ do { \ if (!(x)) { \ return "Assertion failed: `" #x "`, " __FILE__ ":" TOSTRING(__LINE__); \ } \ } while (false) ASSERT(r_return_primitive() == 2020); ASSERT(r_return_shared().z == 2020); ASSERT(cxx_test_suite_r_is_correct(&*r_return_box())); ASSERT(r_return_unique_ptr()->get() == 2020); ASSERT(r_return_ref(Shared{2020}) == 2020); ASSERT(std::string(r_return_str(Shared{2020})) == "2020"); ASSERT(std::string(r_return_rust_string()) == "2020"); ASSERT(*r_return_unique_ptr_string() == "2020"); ASSERT(r_return_identity(2020) == 2020); ASSERT(r_return_sum(2020, 1) == 2021); ASSERT(r_return_enum(0) == Enum::AVal); ASSERT(r_return_enum(1) == Enum::BVal); ASSERT(r_return_enum(2021) == Enum::CVal); r_take_primitive(2020); r_take_shared(Shared{2020}); r_take_unique_ptr(std::unique_ptr<C>(new C{2020})); r_take_ref_c(C{2020}); r_take_str(rust::Str("2020")); r_take_sliceu8( rust::Slice<uint8_t>(reinterpret_cast<const uint8_t *>(SLICE_DATA), 5)); r_take_rust_string(rust::String("2020")); r_take_unique_ptr_string( std::unique_ptr<std::string>(new std::string("2020"))); r_take_enum(Enum::AVal); ASSERT(r_try_return_primitive() == 2020); try { r_fail_return_primitive(); ASSERT(false); } catch (const rust::Error &e) { ASSERT(std::strcmp(e.what(), "rust error") == 0); } auto r2 = r_return_r2(2020); ASSERT(r2->get() == 2020); ASSERT(r2->set(2021) == 2021); ASSERT(r2->get() == 2021); ASSERT(r2->set(2020) == 2020); ASSERT(r2->get() == 2020); cxx_test_suite_set_correct(); return nullptr; } } // namespace tests <|endoftext|>
<commit_before>#include "tests/ffi/tests.h" #include "tests/ffi/lib.rs.h" #include <cstring> #include <stdexcept> extern "C" void cxx_test_suite_set_correct() noexcept; extern "C" tests::R *cxx_test_suite_get_box() noexcept; extern "C" bool cxx_test_suite_r_is_correct(const tests::R *) noexcept; namespace tests { const char *SLICE_DATA = "2020"; C::C(size_t n) : n(n) {} size_t C::get() const { return this->n; } size_t c_return_primitive() { return 2020; } Shared c_return_shared() { return Shared{2020}; } rust::Box<R> c_return_box() { return rust::Box<R>::from_raw(cxx_test_suite_get_box()); } std::unique_ptr<C> c_return_unique_ptr() { return std::unique_ptr<C>(new C{2020}); } const size_t &c_return_ref(const Shared &shared) { return shared.z; } rust::Str c_return_str(const Shared &shared) { (void)shared; return "2020"; } rust::Slice<uint8_t> c_return_sliceu8(const Shared &shared) { (void)shared; return rust::Slice<uint8_t>((const unsigned char *)SLICE_DATA, 5); } rust::String c_return_rust_string() { return "2020"; } std::unique_ptr<std::string> c_return_unique_ptr_string() { return std::unique_ptr<std::string>(new std::string("2020")); } void c_take_primitive(size_t n) { if (n == 2020) { cxx_test_suite_set_correct(); } } void c_take_shared(Shared shared) { if (shared.z == 2020) { cxx_test_suite_set_correct(); } } void c_take_box(rust::Box<R> r) { if (cxx_test_suite_r_is_correct(&*r)) { cxx_test_suite_set_correct(); } } void c_take_unique_ptr(std::unique_ptr<C> c) { if (c->get() == 2020) { cxx_test_suite_set_correct(); } } void c_take_ref_r(const R &r) { if (cxx_test_suite_r_is_correct(&r)) { cxx_test_suite_set_correct(); } } void c_take_ref_c(const C &c) { if (c.get() == 2020) { cxx_test_suite_set_correct(); } } void c_take_str(rust::Str s) { if (std::string(s) == "2020") { cxx_test_suite_set_correct(); } } void c_take_sliceu8(rust::Slice<uint8_t> s) { if (std::string((const char *)s.data(), s.size()) == "2020") { cxx_test_suite_set_correct(); } } void c_take_rust_string(rust::String s) { if (std::string(s) == "2020") { cxx_test_suite_set_correct(); } } void c_take_unique_ptr_string(std::unique_ptr<std::string> s) { if (*s == "2020") { cxx_test_suite_set_correct(); } } void c_take_callback(rust::Fn<size_t(rust::String)> callback) { callback("2020"); } void c_try_return_void() {} size_t c_try_return_primitive() { return 2020; } size_t c_fail_return_primitive() { throw std::logic_error("logic error"); } rust::Box<R> c_try_return_box() { return c_return_box(); } const rust::String &c_try_return_ref(const rust::String &s) { return s; } rust::Str c_try_return_str(rust::Str s) { return s; } rust::Slice<uint8_t> c_try_return_sliceu8(rust::Slice<uint8_t> s) { return s; } rust::String c_try_return_rust_string() { return c_return_rust_string(); } std::unique_ptr<std::string> c_try_return_unique_ptr_string() { return c_return_unique_ptr_string(); } extern "C" C *cxx_test_suite_get_unique_ptr() noexcept { return std::unique_ptr<C>(new C{2020}).release(); } extern "C" std::string *cxx_test_suite_get_unique_ptr_string() noexcept { return std::unique_ptr<std::string>(new std::string("2020")).release(); } extern "C" const char *cxx_run_test() noexcept { #define STRINGIFY(x) #x #define TOSTRING(x) STRINGIFY(x) #define ASSERT(x) \ do { \ if (!(x)) { \ return "Assertion failed: `" #x "`, " __FILE__ ":" TOSTRING(__LINE__); \ } \ } while (false) ASSERT(r_return_primitive() == 2020); ASSERT(r_return_shared().z == 2020); ASSERT(cxx_test_suite_r_is_correct(&*r_return_box())); ASSERT(r_return_unique_ptr()->get() == 2020); ASSERT(r_return_ref(Shared{2020}) == 2020); ASSERT(std::string(r_return_str(Shared{2020})) == "2020"); ASSERT(std::string(r_return_rust_string()) == "2020"); ASSERT(*r_return_unique_ptr_string() == "2020"); r_take_primitive(2020); r_take_shared(Shared{2020}); r_take_unique_ptr(std::unique_ptr<C>(new C{2020})); r_take_ref_c(C{2020}); r_take_str(rust::Str("2020")); r_take_sliceu8(rust::Slice<uint8_t>((const unsigned char *)SLICE_DATA, 5)); r_take_rust_string(rust::String("2020")); r_take_unique_ptr_string( std::unique_ptr<std::string>(new std::string("2020"))); ASSERT(r_try_return_primitive() == 2020); try { r_fail_return_primitive(); ASSERT(false); } catch (const rust::Error &e) { ASSERT(std::strcmp(e.what(), "rust error") == 0); } cxx_test_suite_set_correct(); return nullptr; } } // namespace tests <commit_msg>Switch C-style casting to reinterpret_casts<commit_after>#include "tests/ffi/tests.h" #include "tests/ffi/lib.rs.h" #include <cstring> #include <stdexcept> extern "C" void cxx_test_suite_set_correct() noexcept; extern "C" tests::R *cxx_test_suite_get_box() noexcept; extern "C" bool cxx_test_suite_r_is_correct(const tests::R *) noexcept; namespace tests { const char *SLICE_DATA = "2020"; C::C(size_t n) : n(n) {} size_t C::get() const { return this->n; } size_t c_return_primitive() { return 2020; } Shared c_return_shared() { return Shared{2020}; } rust::Box<R> c_return_box() { return rust::Box<R>::from_raw(cxx_test_suite_get_box()); } std::unique_ptr<C> c_return_unique_ptr() { return std::unique_ptr<C>(new C{2020}); } const size_t &c_return_ref(const Shared &shared) { return shared.z; } rust::Str c_return_str(const Shared &shared) { (void)shared; return "2020"; } rust::Slice<uint8_t> c_return_sliceu8(const Shared &shared) { (void)shared; return rust::Slice<uint8_t>(reinterpret_cast<const uint8_t *>(SLICE_DATA), 5); } rust::String c_return_rust_string() { return "2020"; } std::unique_ptr<std::string> c_return_unique_ptr_string() { return std::unique_ptr<std::string>(new std::string("2020")); } void c_take_primitive(size_t n) { if (n == 2020) { cxx_test_suite_set_correct(); } } void c_take_shared(Shared shared) { if (shared.z == 2020) { cxx_test_suite_set_correct(); } } void c_take_box(rust::Box<R> r) { if (cxx_test_suite_r_is_correct(&*r)) { cxx_test_suite_set_correct(); } } void c_take_unique_ptr(std::unique_ptr<C> c) { if (c->get() == 2020) { cxx_test_suite_set_correct(); } } void c_take_ref_r(const R &r) { if (cxx_test_suite_r_is_correct(&r)) { cxx_test_suite_set_correct(); } } void c_take_ref_c(const C &c) { if (c.get() == 2020) { cxx_test_suite_set_correct(); } } void c_take_str(rust::Str s) { if (std::string(s) == "2020") { cxx_test_suite_set_correct(); } } void c_take_sliceu8(rust::Slice<uint8_t> s) { if (std::string(reinterpret_cast<const char *>(s.data()), s.size()) == "2020") { cxx_test_suite_set_correct(); } } void c_take_rust_string(rust::String s) { if (std::string(s) == "2020") { cxx_test_suite_set_correct(); } } void c_take_unique_ptr_string(std::unique_ptr<std::string> s) { if (*s == "2020") { cxx_test_suite_set_correct(); } } void c_take_callback(rust::Fn<size_t(rust::String)> callback) { callback("2020"); } void c_try_return_void() {} size_t c_try_return_primitive() { return 2020; } size_t c_fail_return_primitive() { throw std::logic_error("logic error"); } rust::Box<R> c_try_return_box() { return c_return_box(); } const rust::String &c_try_return_ref(const rust::String &s) { return s; } rust::Str c_try_return_str(rust::Str s) { return s; } rust::Slice<uint8_t> c_try_return_sliceu8(rust::Slice<uint8_t> s) { return s; } rust::String c_try_return_rust_string() { return c_return_rust_string(); } std::unique_ptr<std::string> c_try_return_unique_ptr_string() { return c_return_unique_ptr_string(); } extern "C" C *cxx_test_suite_get_unique_ptr() noexcept { return std::unique_ptr<C>(new C{2020}).release(); } extern "C" std::string *cxx_test_suite_get_unique_ptr_string() noexcept { return std::unique_ptr<std::string>(new std::string("2020")).release(); } extern "C" const char *cxx_run_test() noexcept { #define STRINGIFY(x) #x #define TOSTRING(x) STRINGIFY(x) #define ASSERT(x) \ do { \ if (!(x)) { \ return "Assertion failed: `" #x "`, " __FILE__ ":" TOSTRING(__LINE__); \ } \ } while (false) ASSERT(r_return_primitive() == 2020); ASSERT(r_return_shared().z == 2020); ASSERT(cxx_test_suite_r_is_correct(&*r_return_box())); ASSERT(r_return_unique_ptr()->get() == 2020); ASSERT(r_return_ref(Shared{2020}) == 2020); ASSERT(std::string(r_return_str(Shared{2020})) == "2020"); ASSERT(std::string(r_return_rust_string()) == "2020"); ASSERT(*r_return_unique_ptr_string() == "2020"); r_take_primitive(2020); r_take_shared(Shared{2020}); r_take_unique_ptr(std::unique_ptr<C>(new C{2020})); r_take_ref_c(C{2020}); r_take_str(rust::Str("2020")); r_take_sliceu8( rust::Slice<uint8_t>(reinterpret_cast<const uint8_t *>(SLICE_DATA), 5)); r_take_rust_string(rust::String("2020")); r_take_unique_ptr_string( std::unique_ptr<std::string>(new std::string("2020"))); ASSERT(r_try_return_primitive() == 2020); try { r_fail_return_primitive(); ASSERT(false); } catch (const rust::Error &e) { ASSERT(std::strcmp(e.what(), "rust error") == 0); } cxx_test_suite_set_correct(); return nullptr; } } // namespace tests <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include "compiler.h" #include <QStandardItem> #include "blocktypelistmodel.h" #include <QFileDialog> #include <QFile> #include <QTextStream> #include "applicationdata.h" #include "blocktype.h" #include <QJsonDocument> #include <QJsonValue> #include <QJsonObject> #include <QJsonArray> #include <QProcess> #include <QString> #include <QList> #include <QMessageBox> #include <QJsonParseError> MainWindow::MainWindow(ApplicationData _appData, QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->listView_io->setAcceptDrops(false); flow = FlowChart(QHash<int, Block>(), &_appData.blockTypes); ui->graphicsView->setFlowChart(&flow); scene = new QGraphicsScene(); ui->graphicsView->setScene(scene); ui->graphicsView->scale(xScale, yScale); ui->graphicsView->setSceneRect(-10000, -10000, 20000, 20000); ui->graphicsView->centerOn(0,0); appData = _appData; blocks = new BlockTypeListModel(appData.blockTypes.values()); ui->listView_io->setModel(blocks); connect(ui->listView_io->selectionModel(), &QItemSelectionModel::currentChanged, this, &MainWindow::handleCurrentItemChanged); ui->graphicsView->setBlockTypes(&(appData.blockTypes)); connect(ui->actionZoom_In, &QAction::triggered, this, &MainWindow::handleZoomIn); connect(ui->actionZoom_Out, &QAction::triggered, this, &MainWindow::handleZoomOut); connect(ui->actionSave_As, &QAction::triggered, this, &MainWindow::handleSaveAs); connect(ui->actionLoad, &QAction::triggered, this, &MainWindow::handleLoad); connect(ui->pushButton_compile, &QPushButton::pressed, this, &MainWindow::handleCompile); connect(ui->pushButton_program, &QPushButton::pressed, this, &MainWindow::handleProgram); } MainWindow::~MainWindow() { delete ui; } void MainWindow::handleCurrentItemChanged(const QModelIndex& current, const QModelIndex&) { ui->graphicsView->setCurrentBlockType(blocks->blockTypeAt(current)); } void MainWindow::handleZoomIn() { ui->graphicsView->scale(1.1, 1.1); } void MainWindow::handleZoomOut() { ui->graphicsView->scale(1/1.1, 1/1.1); } void MainWindow::handleSaveAs() { QString filePath = QFileDialog::getSaveFileName(this, "Save Flowchart As", "", "Flowchart files (*.flow)"); QFile file(filePath); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) return; QJsonDocument doc(FlowChart_toJson(flow).toObject()); QByteArray bytes = doc.toJson(); file.write(bytes); } void MainWindow::handleLoad() { QString filePath = QFileDialog::getOpenFileName(this, "Open Flowchart", "", "Flowchart files (*.flow)"); QFile file(filePath); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { QMessageBox::warning(this, "SignalCraft failed to open the flowchart", "The flowchart file could not be opened. Ensure that it exists."); return; } QByteArray bytes = file.readAll(); QJsonParseError parseErr; auto doc = QJsonDocument::fromJson(bytes, &parseErr); if (parseErr.error != QJsonParseError::NoError) { QMessageBox::warning(this, "SignalCraft failed to parse the flowchart", "The flowchart file could not be parsed as valid JSON. The parser reported: \"" + parseErr.errorString() + "\" at offset " + QString::number(parseErr.offset) + "."); return; } bool success; flow = FlowChart_fromJsonWithBlockTypes(doc.array(), &appData.blockTypes, &success); if (!success) { QMessageBox::warning(this, "SignalCraft failed to interpret the flowchart", "The flowchart file did not fit the required structure."); } ui->graphicsView->setFlowChart(&flow); ui->graphicsView->syncGraphicsItems(); } void MainWindow::handleCompile(){ QString picCode = generatePicCode(flow); //QString filePath = QFileDialog::getSaveFileName(this, "Save PicCode", "", "*.c"); QString filePath = "GccApplication1.c"; QFile file(filePath); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) return; QTextStream out(&file); out << picCode; file.close(); QString exefile = "\"C:\\Program Files (x86)\\Atmel\\Studio\\7.0\\shellUtils\\make.exe\""; QList<QString> args; args.append("-C"); args.append("build-firmware"); args.append("all"); QProcess::execute(exefile, args); } void MainWindow::handleProgram() { QString exefile = "\"C:\\Program Files (x86)\\Atmel\\Studio\\7.0\\atbackend\\atprogram.exe\""; QList<QString> args; args.append("-t"); args.append("edbg"); args.append("-i"); args.append("SWD"); args.append("-d"); args.append("atsamg55j19"); args.append("program"); args.append("-f"); args.append("build-firmware\\GccApplication1.elf"); QProcess::execute(exefile, args); } <commit_msg>Handle canceled file dialog<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include "compiler.h" #include <QStandardItem> #include "blocktypelistmodel.h" #include <QFileDialog> #include <QFile> #include <QTextStream> #include "applicationdata.h" #include "blocktype.h" #include <QJsonDocument> #include <QJsonValue> #include <QJsonObject> #include <QJsonArray> #include <QProcess> #include <QString> #include <QList> #include <QMessageBox> #include <QJsonParseError> MainWindow::MainWindow(ApplicationData _appData, QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->listView_io->setAcceptDrops(false); flow = FlowChart(QHash<int, Block>(), &_appData.blockTypes); ui->graphicsView->setFlowChart(&flow); scene = new QGraphicsScene(); ui->graphicsView->setScene(scene); ui->graphicsView->scale(xScale, yScale); ui->graphicsView->setSceneRect(-10000, -10000, 20000, 20000); ui->graphicsView->centerOn(0,0); appData = _appData; blocks = new BlockTypeListModel(appData.blockTypes.values()); ui->listView_io->setModel(blocks); connect(ui->listView_io->selectionModel(), &QItemSelectionModel::currentChanged, this, &MainWindow::handleCurrentItemChanged); ui->graphicsView->setBlockTypes(&(appData.blockTypes)); connect(ui->actionZoom_In, &QAction::triggered, this, &MainWindow::handleZoomIn); connect(ui->actionZoom_Out, &QAction::triggered, this, &MainWindow::handleZoomOut); connect(ui->actionSave_As, &QAction::triggered, this, &MainWindow::handleSaveAs); connect(ui->actionLoad, &QAction::triggered, this, &MainWindow::handleLoad); connect(ui->pushButton_compile, &QPushButton::pressed, this, &MainWindow::handleCompile); connect(ui->pushButton_program, &QPushButton::pressed, this, &MainWindow::handleProgram); } MainWindow::~MainWindow() { delete ui; } void MainWindow::handleCurrentItemChanged(const QModelIndex& current, const QModelIndex&) { ui->graphicsView->setCurrentBlockType(blocks->blockTypeAt(current)); } void MainWindow::handleZoomIn() { ui->graphicsView->scale(1.1, 1.1); } void MainWindow::handleZoomOut() { ui->graphicsView->scale(1/1.1, 1/1.1); } void MainWindow::handleSaveAs() { QString filePath = QFileDialog::getSaveFileName(this, "Save Flowchart As", "", "Flowchart files (*.flow)"); if (filePath.isEmpty()) { return; } QFile file(filePath); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) return; QJsonDocument doc(FlowChart_toJson(flow).toObject()); QByteArray bytes = doc.toJson(); file.write(bytes); } void MainWindow::handleLoad() { QString filePath = QFileDialog::getOpenFileName(this, "Open Flowchart", "", "Flowchart files (*.flow)"); if (filePath.isEmpty()) { return; } QFile file(filePath); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { QMessageBox::warning(this, "SignalCraft failed to open the flowchart", "The flowchart file could not be opened. Ensure that it exists."); return; } QByteArray bytes = file.readAll(); QJsonParseError parseErr; auto doc = QJsonDocument::fromJson(bytes, &parseErr); if (parseErr.error != QJsonParseError::NoError) { QMessageBox::warning(this, "SignalCraft failed to parse the flowchart", "The flowchart file could not be parsed as valid JSON. The parser reported: \"" + parseErr.errorString() + "\" at offset " + QString::number(parseErr.offset) + "."); return; } bool success; flow = FlowChart_fromJsonWithBlockTypes(doc.array(), &appData.blockTypes, &success); if (!success) { QMessageBox::warning(this, "SignalCraft failed to interpret the flowchart", "The flowchart file did not fit the required structure."); } ui->graphicsView->setFlowChart(&flow); ui->graphicsView->syncGraphicsItems(); } void MainWindow::handleCompile(){ QString picCode = generatePicCode(flow); //QString filePath = QFileDialog::getSaveFileName(this, "Save PicCode", "", "*.c"); QString filePath = "GccApplication1.c"; QFile file(filePath); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) return; QTextStream out(&file); out << picCode; file.close(); QString exefile = "\"C:\\Program Files (x86)\\Atmel\\Studio\\7.0\\shellUtils\\make.exe\""; QList<QString> args; args.append("-C"); args.append("build-firmware"); args.append("all"); QProcess::execute(exefile, args); } void MainWindow::handleProgram() { QString exefile = "\"C:\\Program Files (x86)\\Atmel\\Studio\\7.0\\atbackend\\atprogram.exe\""; QList<QString> args; args.append("-t"); args.append("edbg"); args.append("-i"); args.append("SWD"); args.append("-d"); args.append("atsamg55j19"); args.append("program"); args.append("-f"); args.append("build-firmware\\GccApplication1.elf"); QProcess::execute(exefile, args); } <|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 "wrapper.hxx" #define WIN32_LEAN_AND_MEAN #include <windows.h> #define BUFLEN 2048 string getexe(string exename) { char* cmdbuf; size_t cmdlen; _dupenv_s(&cmdbuf,&cmdlen,exename.c_str()); if(!cmdbuf) { cout << "Error " << exename << " not defined. Did you forget to source the enviroment?" << endl; exit(1); } string command(cmdbuf); free(cmdbuf); return command; } void setupccenv() { // Set-up library path string libpath="LIB="; char* libbuf; size_t liblen; _dupenv_s(&libbuf,&liblen,"ILIB"); libpath.append(libbuf); free(libbuf); if(_putenv(libpath.c_str())<0) { cerr << "Error: could not export LIB" << endl; exit(1); } // Set-up include path string includepath="INCLUDE=.;"; char* incbuf; size_t inclen; _dupenv_s(&incbuf,&inclen,"SOLARINC"); string inctmp(incbuf); free(incbuf); // 3 = strlen(" -I") for(size_t pos=0; pos != string::npos;) { size_t endpos=inctmp.find(" -I",pos+3); size_t len=endpos-pos-3; if(endpos==string::npos) includepath.append(inctmp,pos+3,endpos); else if(len>0) { includepath.append(inctmp,pos+3,len); includepath.append(";"); } pos=inctmp.find(" -I",pos+len); } if(_putenv(includepath.c_str())<0) { cerr << "Error: could not export INCLUDE" << endl; exit(1); } } string processccargs(vector<string> rawargs) { // suppress the msvc banner string args=" -nologo"; // TODO: should these options be enabled globally? args.append(" -EHsc"); const char *const pDebugRuntime(getenv("MSVC_USE_DEBUG_RUNTIME")); if (pDebugRuntime && !strcmp(pDebugRuntime, "TRUE")) args.append(" -MDd"); else args.append(" -MD"); args.append(" -Gy"); args.append(" -Zc:wchar_t-"); args.append(" -Ob1 -Oxs -Oy-"); // apparently these must be at the end // otherwise configure tests may fail string linkargs(" -link"); for(vector<string>::iterator i = rawargs.begin(); i != rawargs.end(); ++i) { args.append(" "); if(*i == "-o") { // TODO: handle more than just exe output ++i; size_t dot=(*i).find_last_of("."); if(!(*i).compare(dot+1,3,"obj") || !(*i).compare(dot+1,1,"o")) { args.append("-Fo"); args.append(*i); } else if(!(*i).compare(dot+1,3,"exe")) { args.append("-Fe"); args.append(*i); } else if(!(*i).compare(dot+1,3,"dll")) { // apparently cl.exe has no flag for dll? linkargs.append(" -dll -out:"); linkargs.append(*i); } else { cerr << "unknonwn -o argument - please adapt gcc-wrapper for \"" << (*i) << "\""; exit(1); } } else if(*i == "-g") args.append("-Zi"); else if(!(*i).compare(0,2,"-D")) { // need to re-escape strings for preprocessor for(size_t pos=(*i).find("\"",0); pos!=string::npos; pos=(*i).find("\"",pos)) { (*i).replace(pos,0,"\\"); pos+=2; } args.append(*i); } else if(!(*i).compare(0,2,"-L")) { linkargs.append(" -LIBPATH:"+(*i).substr(2)); } else if(!(*i).compare(0,2,"-l")) { linkargs.append(" "+(*i).substr(2)+".lib"); } else if(!(*i).compare(0,5,"-def:") || !(*i).compare(0,5,"/def:")) { // why are we invoked with /def:? cl.exe should handle plain // "foo.def" by itself linkargs.append(" " + *i); } else if(!(*i).compare(0,12,"-fvisibility")) { //TODO: drop other gcc-specific options } else if(!(*i).compare(0,4,"-Wl,")) { //TODO: drop other gcc-specific options } else if(*i == "-Werror") args.append("-WX"); else args.append(*i); } args.append(linkargs); return args; } int startprocess(string command, string args) { STARTUPINFO si; PROCESS_INFORMATION pi; SECURITY_ATTRIBUTES sa; HANDLE childout_read; HANDLE childout_write; memset(&sa,0,sizeof(sa)); memset(&si,0,sizeof(si)); memset(&pi,0,sizeof(pi)); sa.nLength=sizeof(sa); sa.bInheritHandle=TRUE; if(!CreatePipe(&childout_read,&childout_write,&sa,0)) { cerr << "Error: could not create stdout pipe" << endl; exit(1); } si.cb=sizeof(si); si.dwFlags |= STARTF_USESTDHANDLES; si.hStdOutput=childout_write; si.hStdError=childout_write; // support ccache size_t pos=command.find("ccache "); if(pos != string::npos) { args.insert(0,"cl.exe"); command=command.substr(0,pos+strlen("ccache"))+".exe"; } //cerr << "CMD= " << command << " " << args << endl; // Commandline may be modified by CreateProcess char* cmdline=_strdup(args.c_str()); if(!CreateProcess(command.c_str(), // Process Name cmdline, // Command Line NULL, // Process Handle not Inheritable NULL, // Thread Handle not Inheritable TRUE, // Handles are Inherited 0, // No creation flags NULL, // Enviroment for process NULL, // Use same starting directory &si, // Startup Info &pi) // Process Information ) { cerr << "Error: could not create process" << endl; exit(1); } // if you don't close this the process will hang CloseHandle(childout_write); // Get Process output char buffer[BUFLEN]; DWORD readlen, writelen, ret; HANDLE stdout_handle=GetStdHandle(STD_OUTPUT_HANDLE); while(true) { int success=ReadFile(childout_read,buffer,BUFLEN,&readlen,NULL); // check if the child process has exited if(GetLastError()==ERROR_BROKEN_PIPE) break; if(!success) { cerr << "Error: could not read from subprocess stdout" << endl; exit(1); } if(readlen!=0) { WriteFile(stdout_handle,buffer,readlen,&writelen,NULL); } } WaitForSingleObject(pi.hProcess, INFINITE); GetExitCodeProcess(pi.hProcess, &ret); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); return int(ret); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>gcc-wrapper: warn on invalid path names.<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 "wrapper.hxx" #define WIN32_LEAN_AND_MEAN #include <windows.h> #define BUFLEN 2048 string getexe(string exename) { char* cmdbuf; size_t cmdlen; _dupenv_s(&cmdbuf,&cmdlen,exename.c_str()); if(!cmdbuf) { cout << "Error " << exename << " not defined. Did you forget to source the enviroment?" << endl; exit(1); } string command(cmdbuf); free(cmdbuf); return command; } void setupccenv() { // Set-up library path string libpath="LIB="; char* libbuf; size_t liblen; _dupenv_s(&libbuf,&liblen,"ILIB"); libpath.append(libbuf); free(libbuf); if(_putenv(libpath.c_str())<0) { cerr << "Error: could not export LIB" << endl; exit(1); } // Set-up include path string includepath="INCLUDE=.;"; char* incbuf; size_t inclen; _dupenv_s(&incbuf,&inclen,"SOLARINC"); string inctmp(incbuf); free(incbuf); // 3 = strlen(" -I") for(size_t pos=0; pos != string::npos;) { size_t endpos=inctmp.find(" -I",pos+3); size_t len=endpos-pos-3; if(endpos==string::npos) includepath.append(inctmp,pos+3,endpos); else if(len>0) { includepath.append(inctmp,pos+3,len); includepath.append(";"); } pos=inctmp.find(" -I",pos+len); } if(_putenv(includepath.c_str())<0) { cerr << "Error: could not export INCLUDE" << endl; exit(1); } } string processccargs(vector<string> rawargs) { // suppress the msvc banner string args=" -nologo"; // TODO: should these options be enabled globally? args.append(" -EHsc"); const char *const pDebugRuntime(getenv("MSVC_USE_DEBUG_RUNTIME")); if (pDebugRuntime && !strcmp(pDebugRuntime, "TRUE")) args.append(" -MDd"); else args.append(" -MD"); args.append(" -Gy"); args.append(" -Zc:wchar_t-"); args.append(" -Ob1 -Oxs -Oy-"); // apparently these must be at the end // otherwise configure tests may fail string linkargs(" -link"); for(vector<string>::iterator i = rawargs.begin(); i != rawargs.end(); ++i) { args.append(" "); if(i->find("/") == 0) { cerr << "Error: absolute unix path passed that looks like an option: '" << *i << "'"; args.append(*i); } else if(*i == "-o") { // TODO: handle more than just exe output ++i; size_t dot=(*i).find_last_of("."); if(!(*i).compare(dot+1,3,"obj") || !(*i).compare(dot+1,1,"o")) { args.append("-Fo"); args.append(*i); } else if(!(*i).compare(dot+1,3,"exe")) { args.append("-Fe"); args.append(*i); } else if(!(*i).compare(dot+1,3,"dll")) { // apparently cl.exe has no flag for dll? linkargs.append(" -dll -out:"); linkargs.append(*i); } else { cerr << "unknonwn -o argument - please adapt gcc-wrapper for \"" << (*i) << "\""; exit(1); } } else if(*i == "-g") args.append("-Zi"); else if(!(*i).compare(0,2,"-D")) { // need to re-escape strings for preprocessor for(size_t pos=(*i).find("\"",0); pos!=string::npos; pos=(*i).find("\"",pos)) { (*i).replace(pos,0,"\\"); pos+=2; } args.append(*i); } else if(!(*i).compare(0,2,"-L")) { linkargs.append(" -LIBPATH:"+(*i).substr(2)); } else if(!(*i).compare(0,2,"-l")) { linkargs.append(" "+(*i).substr(2)+".lib"); } else if(!(*i).compare(0,5,"-def:") || !(*i).compare(0,5,"/def:")) { // why are we invoked with /def:? cl.exe should handle plain // "foo.def" by itself linkargs.append(" " + *i); } else if(!(*i).compare(0,12,"-fvisibility")) { //TODO: drop other gcc-specific options } else if(!(*i).compare(0,4,"-Wl,")) { //TODO: drop other gcc-specific options } else if(*i == "-Werror") args.append("-WX"); else args.append(*i); } args.append(linkargs); return args; } int startprocess(string command, string args) { STARTUPINFO si; PROCESS_INFORMATION pi; SECURITY_ATTRIBUTES sa; HANDLE childout_read; HANDLE childout_write; memset(&sa,0,sizeof(sa)); memset(&si,0,sizeof(si)); memset(&pi,0,sizeof(pi)); sa.nLength=sizeof(sa); sa.bInheritHandle=TRUE; if(!CreatePipe(&childout_read,&childout_write,&sa,0)) { cerr << "Error: could not create stdout pipe" << endl; exit(1); } si.cb=sizeof(si); si.dwFlags |= STARTF_USESTDHANDLES; si.hStdOutput=childout_write; si.hStdError=childout_write; // support ccache size_t pos=command.find("ccache "); if(pos != string::npos) { args.insert(0,"cl.exe"); command=command.substr(0,pos+strlen("ccache"))+".exe"; } //cerr << "CMD= " << command << " " << args << endl; // Commandline may be modified by CreateProcess char* cmdline=_strdup(args.c_str()); if(!CreateProcess(command.c_str(), // Process Name cmdline, // Command Line NULL, // Process Handle not Inheritable NULL, // Thread Handle not Inheritable TRUE, // Handles are Inherited 0, // No creation flags NULL, // Enviroment for process NULL, // Use same starting directory &si, // Startup Info &pi) // Process Information ) { cerr << "Error: could not create process" << endl; exit(1); } // if you don't close this the process will hang CloseHandle(childout_write); // Get Process output char buffer[BUFLEN]; DWORD readlen, writelen, ret; HANDLE stdout_handle=GetStdHandle(STD_OUTPUT_HANDLE); while(true) { int success=ReadFile(childout_read,buffer,BUFLEN,&readlen,NULL); // check if the child process has exited if(GetLastError()==ERROR_BROKEN_PIPE) break; if(!success) { cerr << "Error: could not read from subprocess stdout" << endl; exit(1); } if(readlen!=0) { WriteFile(stdout_handle,buffer,readlen,&writelen,NULL); } } WaitForSingleObject(pi.hProcess, INFINITE); GetExitCodeProcess(pi.hProcess, &ret); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); return int(ret); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>//===--- IndexerMain.cpp -----------------------------------------*- C++-*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // GlobalSymbolBuilder is a tool to extract symbols from a whole project. // This tool is **experimental** only. Don't use it in production code. // //===----------------------------------------------------------------------===// #include "index/Index.h" #include "index/IndexAction.h" #include "index/Merge.h" #include "index/Serialization.h" #include "index/SymbolCollector.h" #include "clang/Tooling/CommonOptionsParser.h" #include "clang/Tooling/Execution.h" #include "clang/Tooling/Tooling.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Path.h" #include "llvm/Support/Signals.h" using namespace llvm; using namespace clang::tooling; using clang::clangd::SymbolSlab; namespace clang { namespace clangd { namespace { static llvm::cl::opt<std::string> AssumedHeaderDir( "assume-header-dir", llvm::cl::desc("The index includes header that a symbol is defined in. " "If the absolute path cannot be determined (e.g. an " "in-memory VFS) then the relative path is resolved against " "this directory, which must be absolute. If this flag is " "not given, such headers will have relative paths."), llvm::cl::init("")); static llvm::cl::opt<IndexFileFormat> Format("format", llvm::cl::desc("Format of the index to be written"), llvm::cl::values(clEnumValN(IndexFileFormat::YAML, "yaml", "human-readable YAML format"), clEnumValN(IndexFileFormat::RIFF, "binary", "binary RIFF format")), llvm::cl::init(IndexFileFormat::RIFF)); class IndexActionFactory : public tooling::FrontendActionFactory { public: IndexActionFactory(IndexFileIn &Result) : Result(Result) {} clang::FrontendAction *create() override { SymbolCollector::Options Opts; Opts.FallbackDir = AssumedHeaderDir; return createStaticIndexingAction( Opts, [&](SymbolSlab S) { // Merge as we go. std::lock_guard<std::mutex> Lock(SymbolsMu); for (const auto &Sym : S) { if (const auto *Existing = Symbols.find(Sym.ID)) Symbols.insert(mergeSymbol(*Existing, Sym)); else Symbols.insert(Sym); } }) .release(); } // Awkward: we write the result in the destructor, because the executor // takes ownership so it's the easiest way to get our data back out. ~IndexActionFactory() { Result.Symbols = std::move(Symbols).build(); } private: IndexFileIn &Result; std::mutex SymbolsMu; SymbolSlab::Builder Symbols; }; } // namespace } // namespace clangd } // namespace clang int main(int argc, const char **argv) { llvm::sys::PrintStackTraceOnErrorSignal(argv[0]); const char *Overview = R"( Creates an index of symbol information etc in a whole project. This is **experimental** and not production-ready! Example usage for a project using CMake compile commands: $ clangd-indexer --executor=all-TUs compile_commands.json > index.yaml Example usage for file sequence index without flags: $ clangd-indexer File1.cpp File2.cpp ... FileN.cpp > index.yaml Note: only symbols from header files will be indexed. )"; auto Executor = clang::tooling::createExecutorFromCommandLineArgs( argc, argv, cl::GeneralCategory, Overview); if (!Executor) { llvm::errs() << llvm::toString(Executor.takeError()) << "\n"; return 1; } if (!clang::clangd::AssumedHeaderDir.empty() && !llvm::sys::path::is_absolute(clang::clangd::AssumedHeaderDir)) { llvm::errs() << "--assume-header-dir must be an absolute path.\n"; return 1; } // Collect symbols found in each translation unit, merging as we go. clang::clangd::IndexFileIn Data; auto Err = Executor->get()->execute( llvm::make_unique<clang::clangd::IndexActionFactory>(Data)); if (Err) { llvm::errs() << llvm::toString(std::move(Err)) << "\n"; } // Emit collected data. clang::clangd::IndexFileOut Out(Data); Out.Format = clang::clangd::Format; llvm::outs() << Out; return 0; } <commit_msg>[clangd] Revert accidental flag change<commit_after>//===--- IndexerMain.cpp -----------------------------------------*- C++-*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // GlobalSymbolBuilder is a tool to extract symbols from a whole project. // This tool is **experimental** only. Don't use it in production code. // //===----------------------------------------------------------------------===// #include "index/Index.h" #include "index/IndexAction.h" #include "index/Merge.h" #include "index/Serialization.h" #include "index/SymbolCollector.h" #include "clang/Tooling/CommonOptionsParser.h" #include "clang/Tooling/Execution.h" #include "clang/Tooling/Tooling.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Path.h" #include "llvm/Support/Signals.h" using namespace llvm; using namespace clang::tooling; using clang::clangd::SymbolSlab; namespace clang { namespace clangd { namespace { static llvm::cl::opt<std::string> AssumedHeaderDir( "assume-header-dir", llvm::cl::desc("The index includes header that a symbol is defined in. " "If the absolute path cannot be determined (e.g. an " "in-memory VFS) then the relative path is resolved against " "this directory, which must be absolute. If this flag is " "not given, such headers will have relative paths."), llvm::cl::init("")); static llvm::cl::opt<IndexFileFormat> Format("format", llvm::cl::desc("Format of the index to be written"), llvm::cl::values(clEnumValN(IndexFileFormat::YAML, "yaml", "human-readable YAML format"), clEnumValN(IndexFileFormat::RIFF, "binary", "binary RIFF format")), llvm::cl::init(IndexFileFormat::YAML)); class IndexActionFactory : public tooling::FrontendActionFactory { public: IndexActionFactory(IndexFileIn &Result) : Result(Result) {} clang::FrontendAction *create() override { SymbolCollector::Options Opts; Opts.FallbackDir = AssumedHeaderDir; return createStaticIndexingAction( Opts, [&](SymbolSlab S) { // Merge as we go. std::lock_guard<std::mutex> Lock(SymbolsMu); for (const auto &Sym : S) { if (const auto *Existing = Symbols.find(Sym.ID)) Symbols.insert(mergeSymbol(*Existing, Sym)); else Symbols.insert(Sym); } }) .release(); } // Awkward: we write the result in the destructor, because the executor // takes ownership so it's the easiest way to get our data back out. ~IndexActionFactory() { Result.Symbols = std::move(Symbols).build(); } private: IndexFileIn &Result; std::mutex SymbolsMu; SymbolSlab::Builder Symbols; }; } // namespace } // namespace clangd } // namespace clang int main(int argc, const char **argv) { llvm::sys::PrintStackTraceOnErrorSignal(argv[0]); const char *Overview = R"( Creates an index of symbol information etc in a whole project. This is **experimental** and not production-ready! Example usage for a project using CMake compile commands: $ clangd-indexer --executor=all-TUs compile_commands.json > index.yaml Example usage for file sequence index without flags: $ clangd-indexer File1.cpp File2.cpp ... FileN.cpp > index.yaml Note: only symbols from header files will be indexed. )"; auto Executor = clang::tooling::createExecutorFromCommandLineArgs( argc, argv, cl::GeneralCategory, Overview); if (!Executor) { llvm::errs() << llvm::toString(Executor.takeError()) << "\n"; return 1; } if (!clang::clangd::AssumedHeaderDir.empty() && !llvm::sys::path::is_absolute(clang::clangd::AssumedHeaderDir)) { llvm::errs() << "--assume-header-dir must be an absolute path.\n"; return 1; } // Collect symbols found in each translation unit, merging as we go. clang::clangd::IndexFileIn Data; auto Err = Executor->get()->execute( llvm::make_unique<clang::clangd::IndexActionFactory>(Data)); if (Err) { llvm::errs() << llvm::toString(std::move(Err)) << "\n"; } // Emit collected data. clang::clangd::IndexFileOut Out(Data); Out.Format = clang::clangd::Format; llvm::outs() << Out; return 0; } <|endoftext|>
<commit_before>/* Rapicorn * Copyright (C) 2008 Tim Janik * * 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. * * A copy of the GNU Lesser General Public License should ship along * with this library; if not, see http://www.gnu.org/copyleft/. */ #include <rapicorn-core/testutils.hh> #include <rapicorn-core/rapicorn-core.hh> namespace { using namespace Rapicorn; template<typename CharArray> static String string_from_chars (CharArray &ca) { return String (ca, sizeof (ca)); } static void test_type_info () { String err, ts; Typ2 *t0 = Typ2::from_type_info ("Invalid-Type-Definition", err); assert (t0 == NULL && err != ""); ts = string_from_chars ("GType001\200\200\200\201X\200\200\200\210___i\200\200\200\200"); Typ2 t1 = Typ2::from_type_info (ts.data(), ts.size()); assert (t1.name() == "X"); ts = string_from_chars ("GType001\200\200\200\201Y\200\200\200\217___f\200\200\200\201\200\200\200\203a=b"); Typ2 *t2 = Typ2::from_type_info (ts, err); assert (t2 != NULL && err == ""); assert (t2->name() == "Y"); } static void test_types () { Type t1 ("RcTi;0003Foo;n;0008zonk=bar000eSHREK=Schreck!0009SomeNum=7;"); assert (t1.storage() == Type::NUM); assert (t1.ident() == "Foo"); assert (t1.label() == "Foo"); assert (t1.aux_string ("SHREK") == "Schreck!"); assert (t1.aux_num ("SomeNum") == 7); assert (t1.aux_float ("SomeNum") == 7.0); assert (t1.hints() == ":"); Type t2 ("RcTi;0003Bar;n;0009label=BAR0008hints=rw000Dblurb=nothing;"); assert (t2.storage() == Type::NUM); assert (t2.ident() == "Bar"); assert (t2.label() == "BAR"); assert (t2.blurb() == "nothing"); assert (t2.hints() == ":rw:"); } static void test_value_num () { AnyValue v1 (Type::NUM); assert (v1.num() == false); v1 = true; assert (v1.num() == true); AnyValue v2 (v1); assert ((bool) v2 == true); v1.set ((int64) false); assert ((bool) v1 == false); v2 = v1; assert (v2.num() == false); v1 = 0; assert (v1.num() == 0); v1 = 1; assert (v1.num() == 1); v1.set ("-2"); assert (v1.num() == -2.0); v1.set (9223372036854775807LL); assert (v1.num() == 9223372036854775807LL); v1 = false; assert (v1.num() == 0.0); } static void test_value_float () { AnyValue v1 (Type::FLOAT); assert (v1.vfloat() == 0.0); v1 = 1.; assert (v1.vfloat() == 1.0); v1.set ("-1"); assert (v1.vfloat() == -1.0); v1.set ((long double) 16.5e+6); assert (v1.vfloat() > 16000000.0); assert (v1.vfloat() < 17000000.0); v1 = 7; assert (v1.vfloat() == 7.0); v1 = false; assert (v1.vfloat() == 0.0); } static void test_value_string () { AnyValue v1 (Type::STRING); assert (v1.string() == ""); v1.set ("foo"); assert (v1.string() == "foo"); v1.set ((int64) 1); assert (v1.string() == "1"); v1 = 0; assert (v1.string() == "0"); v1 = "x"; assert (v1.string() == "x"); } struct TestObject : public virtual ReferenceCountImpl {}; static void test_array_auto_value () { Array a1, a2; TestObject *to = new TestObject(); ref_sink (to); a1.push_head (AutoValue ("first")); // demand create AutoValue a1.push_head (String ("second")); // implicit AutoValue creation a1.push_head ("third"); // implicit AutoValue creation from C string // implicit AutoValue creations a1.push_head (0.1); a1.push_head (a2); a1.push_head (*to); unref (to); } static void test_array () { Array a; // [0] == head a.push_head (AnyValue (Type::NUM, 0)); assert (a[0].num() == 0); // [-1] == tail assert (a[-1].num() == 0); a.push_head (AnyValue (Type::NUM, 1)); assert (a[0].num() == 1); assert (a[-1].num() == 0); assert (a.count() == 2); // out-of-range-int => string-key conversion: a[99] = 5; assert (a.key (2) == "99"); // count() was 2 before inserting assert (a[2].num() == 5); assert (a[-1].num() == 5); assert (5 == (int) a[-1]); assert (a.count() == 3); a.push_tail (AnyValue (Type::NUM, 2)); assert (a[-1].num() == 2); assert (a.count() == 4); a.clear(); a["ape"] = AnyValue (Type::STRING, "affe"); a["beard"] = "bart"; assert (a[-1].string() == "bart"); a["anum"] = 5; assert (a.key (-3) == "ape"); assert (a.pop_head().string() == "affe"); assert (a.pop_head().string() == "bart"); assert (a.key (-1) == "anum"); assert (a.pop_head().num() == 5); assert (a.count() == 0); const char *board[][8] = { { "R","N","B","Q","K","B","N","R" }, { "P","P","P","P","P","P","P","P" }, { " "," "," "," "," "," "," "," " }, { " "," "," "," "," "," "," "," " }, { " "," "," "," "," "," "," "," " }, { " "," "," "," "," "," "," "," " }, { "p","p","p","p","p","p","p","p" }, { "r","n","b","q","k","b","n","r" } }; for (int64 i = 0; i < RAPICORN_ARRAY_SIZE (board); i++) a.push_tail (Array::FromCArray<String> (board[i])); if (Test::verbose()) printout ("chess0:\n%s\n", a.to_string ("\n").c_str()); a[3].array()[4] = a[1].array()[4]; a[1].array()[4] = " "; if (Test::verbose()) printout ("\nchess1:\n%s\n", a.to_string ("\n").c_str()); } static void variable_changed (Variable *self) { if (Test::verbose()) printout ("Variable::changed: %s\n", self->type().ident().c_str()); } static void test_variable () { Type somestring ("RcTi;000aSomeString;s;;"); Variable &v1 = *new Variable (somestring); ref_sink (v1); v1.sig_changed += slot (variable_changed, &v1); v1 = "foohoo"; String as_string = v1; assert (as_string == "foohoo"); v1 = 5; assert (v1.get<String>() == "5"); v1.set (6.0); assert (v1.get<String>() == "6"); bool b = v1; int i = v1; uint ui = v1; double d = v1; (void) (b + i + ui + d); // silence compiler unref (v1); } } // Anon int main (int argc, char *argv[]) { rapicorn_init_test (&argc, &argv); Test::add ("/Type/type info", test_type_info); Test::add ("/Type/basics", test_types); Test::add ("/Value/num", test_value_num); Test::add ("/Value/float", test_value_float); Test::add ("/Value/string", test_value_string); Test::add ("/Array/AutoValue", test_array_auto_value); Test::add ("/Array/chess", test_array); Test::add ("/Variable/notification", test_variable); return Test::run(); } <commit_msg>modval.cc: fixed passing dynamic instead of static memory into from_type_info()<commit_after>/* Rapicorn * Copyright (C) 2008 Tim Janik * * 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. * * A copy of the GNU Lesser General Public License should ship along * with this library; if not, see http://www.gnu.org/copyleft/. */ #include <rapicorn-core/testutils.hh> #include <rapicorn-core/rapicorn-core.hh> namespace { using namespace Rapicorn; template<typename CharArray> static String string_from_chars (CharArray &ca) { return String (ca, sizeof (ca)); } static void test_type_info () { String err, ts; Typ2 *t0 = Typ2::from_type_info ("Invalid-Type-Definition", err); assert (t0 == NULL && err != ""); const char tchars[] = "GType001\200\200\200\201X\200\200\200\210___i\200\200\200\200 "; Typ2 t1 = Typ2::from_type_info (tchars, sizeof (tchars)); assert (t1.name() == "X"); ts = string_from_chars ("GType001\200\200\200\201Y\200\200\200\217___f\200\200\200\201\200\200\200\203a=b"); Typ2 *t2 = Typ2::from_type_info (ts, err); assert (t2 != NULL && err == ""); assert (t2->name() == "Y"); // check that type memory used above is still valid assert (t1.name() + "postfix" == String ("Xpostfix")); assert (t2->name() == String ("Y")); } static void test_types () { Type t1 ("RcTi;0003Foo;n;0008zonk=bar000eSHREK=Schreck!0009SomeNum=7;"); assert (t1.storage() == Type::NUM); assert (t1.ident() == "Foo"); assert (t1.label() == "Foo"); assert (t1.aux_string ("SHREK") == "Schreck!"); assert (t1.aux_num ("SomeNum") == 7); assert (t1.aux_float ("SomeNum") == 7.0); assert (t1.hints() == ":"); Type t2 ("RcTi;0003Bar;n;0009label=BAR0008hints=rw000Dblurb=nothing;"); assert (t2.storage() == Type::NUM); assert (t2.ident() == "Bar"); assert (t2.label() == "BAR"); assert (t2.blurb() == "nothing"); assert (t2.hints() == ":rw:"); } static void test_value_num () { AnyValue v1 (Type::NUM); assert (v1.num() == false); v1 = true; assert (v1.num() == true); AnyValue v2 (v1); assert ((bool) v2 == true); v1.set ((int64) false); assert ((bool) v1 == false); v2 = v1; assert (v2.num() == false); v1 = 0; assert (v1.num() == 0); v1 = 1; assert (v1.num() == 1); v1.set ("-2"); assert (v1.num() == -2.0); v1.set (9223372036854775807LL); assert (v1.num() == 9223372036854775807LL); v1 = false; assert (v1.num() == 0.0); } static void test_value_float () { AnyValue v1 (Type::FLOAT); assert (v1.vfloat() == 0.0); v1 = 1.; assert (v1.vfloat() == 1.0); v1.set ("-1"); assert (v1.vfloat() == -1.0); v1.set ((long double) 16.5e+6); assert (v1.vfloat() > 16000000.0); assert (v1.vfloat() < 17000000.0); v1 = 7; assert (v1.vfloat() == 7.0); v1 = false; assert (v1.vfloat() == 0.0); } static void test_value_string () { AnyValue v1 (Type::STRING); assert (v1.string() == ""); v1.set ("foo"); assert (v1.string() == "foo"); v1.set ((int64) 1); assert (v1.string() == "1"); v1 = 0; assert (v1.string() == "0"); v1 = "x"; assert (v1.string() == "x"); } struct TestObject : public virtual ReferenceCountImpl {}; static void test_array_auto_value () { Array a1, a2; TestObject *to = new TestObject(); ref_sink (to); a1.push_head (AutoValue ("first")); // demand create AutoValue a1.push_head (String ("second")); // implicit AutoValue creation a1.push_head ("third"); // implicit AutoValue creation from C string // implicit AutoValue creations a1.push_head (0.1); a1.push_head (a2); a1.push_head (*to); unref (to); } static void test_array () { Array a; // [0] == head a.push_head (AnyValue (Type::NUM, 0)); assert (a[0].num() == 0); // [-1] == tail assert (a[-1].num() == 0); a.push_head (AnyValue (Type::NUM, 1)); assert (a[0].num() == 1); assert (a[-1].num() == 0); assert (a.count() == 2); // out-of-range-int => string-key conversion: a[99] = 5; assert (a.key (2) == "99"); // count() was 2 before inserting assert (a[2].num() == 5); assert (a[-1].num() == 5); assert (5 == (int) a[-1]); assert (a.count() == 3); a.push_tail (AnyValue (Type::NUM, 2)); assert (a[-1].num() == 2); assert (a.count() == 4); a.clear(); a["ape"] = AnyValue (Type::STRING, "affe"); a["beard"] = "bart"; assert (a[-1].string() == "bart"); a["anum"] = 5; assert (a.key (-3) == "ape"); assert (a.pop_head().string() == "affe"); assert (a.pop_head().string() == "bart"); assert (a.key (-1) == "anum"); assert (a.pop_head().num() == 5); assert (a.count() == 0); const char *board[][8] = { { "R","N","B","Q","K","B","N","R" }, { "P","P","P","P","P","P","P","P" }, { " "," "," "," "," "," "," "," " }, { " "," "," "," "," "," "," "," " }, { " "," "," "," "," "," "," "," " }, { " "," "," "," "," "," "," "," " }, { "p","p","p","p","p","p","p","p" }, { "r","n","b","q","k","b","n","r" } }; for (int64 i = 0; i < RAPICORN_ARRAY_SIZE (board); i++) a.push_tail (Array::FromCArray<String> (board[i])); if (Test::verbose()) printout ("chess0:\n%s\n", a.to_string ("\n").c_str()); a[3].array()[4] = a[1].array()[4]; a[1].array()[4] = " "; if (Test::verbose()) printout ("\nchess1:\n%s\n", a.to_string ("\n").c_str()); } static void variable_changed (Variable *self) { if (Test::verbose()) printout ("Variable::changed: %s\n", self->type().ident().c_str()); } static void test_variable () { Type somestring ("RcTi;000aSomeString;s;;"); Variable &v1 = *new Variable (somestring); ref_sink (v1); v1.sig_changed += slot (variable_changed, &v1); v1 = "foohoo"; String as_string = v1; assert (as_string == "foohoo"); v1 = 5; assert (v1.get<String>() == "5"); v1.set (6.0); assert (v1.get<String>() == "6"); bool b = v1; int i = v1; uint ui = v1; double d = v1; (void) (b + i + ui + d); // silence compiler unref (v1); } } // Anon int main (int argc, char *argv[]) { rapicorn_init_test (&argc, &argv); Test::add ("/Type/type info", test_type_info); Test::add ("/Type/basics", test_types); Test::add ("/Value/num", test_value_num); Test::add ("/Value/float", test_value_float); Test::add ("/Value/string", test_value_string); Test::add ("/Array/AutoValue", test_array_auto_value); Test::add ("/Array/chess", test_array); Test::add ("/Variable/notification", test_variable); return Test::run(); } <|endoftext|>
<commit_before>#include <stout/gtest.hpp> #include <gtest/gtest.h> #include "pwave/scenario.hpp" namespace pwave { TEST(PwaveTest, ScenarioStableSignal) { const double_t THRESHOLD = 0.01; const int32_t LOAD_ITERATIONS = 100; SignalScenario signalGen = SignalScenario(LOAD_ITERATIONS) .use(math::const10Function) .after(12).add(-24.05) .after(2).use(new SymetricNoiseGenerator(3)) .after(23).use(math::linearFunction); ITERATE_SIGNAL(signalGen) { double_t result = (*signalGen)(); // See result as CSV: (*signalGen).printCSVLine(result); } } } // namespace pwave <commit_msg>Renamed test.<commit_after>#include <stout/gtest.hpp> #include <gtest/gtest.h> #include "pwave/scenario.hpp" namespace pwave { TEST(PwaveTest, ScenarioExample) { const int32_t LOAD_ITERATIONS = 100; SignalScenario signalGen = SignalScenario(LOAD_ITERATIONS) .use(math::const10Function) .after(12).add(-24.05) .after(2).use(new SymetricNoiseGenerator(3)) .after(23).use(math::linearFunction); ITERATE_SIGNAL(signalGen) { double_t result = (*signalGen)(); // See result as CSV: (*signalGen).printCSVLine(result); } } } // namespace pwave <|endoftext|>
<commit_before>/* JAPY is a new JSON parser in C++. This file contains examples of JAPY in action. The MIT License (MIT) Copyright (c) 2014 Artur Brugeman, brugeman.artur@gmail.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 "japy.hpp" struct hello_t { std::string str; }; static const japy::node_t & operator>> (const japy::node_t & node, hello_t & hello) { hello.str = "hello "; hello.str += node.body (); return node; } static void test1 () { // this is the simplest thing you can do: // get a single value out of json document int i = 0; // JAPY uses 'paths' to address parts of json documents // '/a' path refers to 'child members named a' japy::parse ("{\"a\":1}", "/a") >> i; assert (i == 1); // how about a more complex document? // '//b' refers to 'descendant members named b' japy::parse ("{\"a\":{\"b\":\"2\"}}", "//b") >> i; // note how string "2" was converted to int assert (i == 2); // what if required field does not exist? try { // exception is thrown if we don't find a match japy::parse ("{\"a\":3}", "/b") >> i; assert (0); } catch (...) {} // what if we want a default value to be used instead of exception? i = -1; // default // ? in path means 'optional', if no match - i is not written japy::parse ("{\"a\":4}", "/?b") >> i; assert (i == -1); // what if matched value is out of range of our numeric variable? try { // out_of_range exception is thrown (if your ints are 32 bit, of course) japy::parse ("{\"a\":5555555555}", "/a") >> i; assert (0); // what if we don't want an out_of_range exception thrown here? // 1. I believe that is most probably a design error - // fix it, i.e. by using a wider type. // 2. Use try-catch if only you really must - 'i' is not // modified in case of exception. } catch (...) {} // how about an even more complex document? // '#/$/a' refers to "root array's child objects' members named a" japy::parse ("[{\"a\":6}]", "#/$/a") >> i; assert (i == 6); // what if we want to make sure the selected value is of integral type? // 'i:' in path means 'node type - integral' japy::parse ("{\"a\":7}", "/i:a") >> i; assert (i == 7); japy::parse ("{\"a\":\"77\"}", "/?i:a") >> i; assert (i == 7); // ok, one more thing // '/#a/*' refers to 'elements of child array named a' japy::parse ("{\"a\":[8, 88]}", "/#a/*") >> i; // note that both 8 and 88 are a match, but >> extracts only the first one assert (i == 8); // now, escaped sequences decoding std::string s; japy::parse ("{\"a\":\"\\n\\u20AC\\uD834\\uDD1E\\ud834ab\\c\"}", "/a") >> s; assert (s == "\n\xE2\x82\xAC\xF0\x9D\x84\x9E\xED\xA0\xB4""abc"); // now, do not decode the value, get the raw bytes std::string raw; japy::parse ("{\"a\":\"\\n\\u20AC\"}", "/a") >> japy::raw (raw); assert (raw == "\\n\\u20AC"); // now, get the full body of an object as a string std::string body; const char * json = "{\"a\":\"\\n\\u20AC\"}"; japy::parse (json, "$") >> japy::body (body); assert (body == json); // now, our custom object and overloaded >> (see above) hello_t hello; japy::parse ("[\"world\"]", "/*") >> hello; assert (hello.str == "hello world"); // that's pretty it printf ("test1 done\n"); } static void test2 () { // now, how about iterating over a collection? // easy! int sum = 0; // #/$ means 'object elements of array root' for (auto object: japy::parse ("[{\"a\":1}, {\"a\":2}]", "#/$")) { int v = 0; // see the sub-query - '/a' works on the pre-selected object object["/a"] >> v; sum += v; } assert (sum == 3); // or one by one extraction of nodes sum = 0; auto node_set = japy::parse ("[{\"a\":1}, {\"a\":2}]", "#/$/a"); int v1 = 0; int v2 = 0; node_set >> v1 >> v2; sum += v1 + v2; assert (sum == 3); // a bit more complex document sum = 0; // '//$/a' means "all descendant objects' children named a" for (auto a_member: japy::parse ("[{\"a\":1}, [{\"a\":2}]]", "//$/a")) { int v = 0; // note that we don't need a sub-query here a_member >> v; sum += v; } assert (sum == 3); // and what if some parts of document do not match? sum = 0; // same path as in previous example try { const char * json = "[{\"a\":1}, [{\"b\":2}], {\"a\":3}]"; for (auto a_member: japy::parse (json, "//$/a")) { int v = 0; a_member >> v; sum += v; } assert (0); } catch (...) { // Path matching is done in 'all or nothing' manner, // that is - if first selector matches - than all path must match. // {\"b\":2} matches path head '//$', but does not match the tail 'a', // so exception is thrown as soon as japy finishes parsing it. } assert (sum == 1); // to avoid exceptions on partially matching branches, // use ? on selector that may observe mismatch sum = 0; for (auto a_member: japy::parse ("[{\"a\":1}, [{\"b\":2}]]", "//$/?a")) { int v = 0; a_member >> v; sum += v; } assert (sum == 1); // how about sub-iterating? sum = 0; for (auto arr: japy::parse ("[{\"a\":1}, [2, 3]]", "/#")) { for (auto element: arr["/*"]) { int v = 0; element >> v; sum += v; } } assert (sum == 5); // that's it on iterating printf ("test2 done\n"); } static void test3 () { // now how about parsing a json stream? { // a bit more to do, but still easy! const char * part1 = "[1, 2"; const char * part2 = ", 3]"; // will be 6 when we're done int sum = 0; // create a parser, specify a 'scope-path' // objects referred by scope-path are buffered internally // (if seen on the parts' borders) japy::parser_t parser ("/*"); // feed a part of your json into parser parser.put (part1); // iterate over elements found in first part for (auto element: parser) { int v = 0; element >> v; sum += v; } // only the first element was returned, as japy didn't yet see // the end of second element assert (sum == 1); // feed the second part of your json parser.put (part2); // iterate over elements found in second part for (auto element: parser) { int v = 0; element >> v; sum += v; } // now we're done! assert (sum == 6); } { // So, the structure of your stream parser will most // probably be like this: // 0. A container to store results of json processing. int sum = 0; // 1. Some input stream that produces parts of json. // Here, we'll use a plain string that will produce single chars. // I recommend you to choose the size of your parts (your read buffer) // such that it could allocate >10 of the typical node size // that is addressed by the scope-path - this will make // japy internal buffering costs insignificant. std::string stream ("[11, 22, 33]"); // 2. Parser with a proper scope japy::parser_t parser ("/*"); for (auto part: stream) { // 3. Feed part to the parser parser.put (part); // 4. Iterate over nodes addressed by scope-path for (auto node: parser) { int v = 0; node >> v; sum += v; } } // that's it assert (sum == 66); } { // normally a json document must have a single root, // and an exception is thrown in presence of 'trailing garbage'. // however, sometimes you have streams of json documents, // each having a root. use 'allow_many_roots' option for that case: int sum = 0; japy::parser_t parser ("/a"); parser.allow_many_roots (true); parser.put ("{\"a\":1} {\"a\":2}"); // two json docs in one stream for (auto node: parser) { int v = 0; node >> v; sum += v; } assert (sum == 3); } // I guess I'll add more stuff here when questions arise. printf ("test3 done\n"); } int main () { try { test1 (); test2 (); test3 (); } catch (std::exception & e) { printf ("ERROR: %s\n", e.what ()); } } <commit_msg>Minor enh in examples<commit_after>/* JAPY is a new JSON parser in C++. This file contains examples of JAPY in action. The MIT License (MIT) Copyright (c) 2014 Artur Brugeman, brugeman.artur@gmail.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 "japy.hpp" struct hello_t { std::string str; }; static const japy::node_t & operator>> (const japy::node_t & node, hello_t & hello) { hello.str = "hello "; hello.str += node.body (); return node; } static void test1 () { // this is the simplest thing you can do: // get a single value out of json document int i = 0; // JAPY uses 'paths' to address parts of json documents // '/a' path refers to 'child members named a' japy::parse ("{\"a\":1}", "/a") >> i; assert (i == 1); // how about a more complex document? // '//b' refers to 'descendant members named b' japy::parse ("{\"a\":{\"b\":\"2\"}}", "//b") >> i; // note how string "2" was converted to int assert (i == 2); // what if required field does not exist? try { // exception is thrown if we don't find a match japy::parse ("{\"a\":3}", "/b") >> i; assert (0); } catch (...) {} // what if we want a default value to be used instead of exception? i = -1; // default // ? in path means 'optional', if no match - i is not written japy::parse ("{\"a\":4}", "/?b") >> i; assert (i == -1); // what if matched value is out of range of our numeric variable? try { // out_of_range exception is thrown (if your ints are 32 bit, of course) japy::parse ("{\"a\":5555555555}", "/a") >> i; assert (0); // what if we don't want an out_of_range exception thrown here? // 1. I believe that is most probably a design error - // fix it, i.e. by using a wider type. // 2. Use try-catch if only you really must - 'i' is not // modified in case of exception. } catch (...) {} // how about an even more complex document? // '#/$/a' refers to "root array's child objects' members named a" japy::parse ("[{\"a\":6}]", "#/$/a") >> i; assert (i == 6); // what if we want to make sure the selected value is of integral type? // 'i:' in path means 'node type - integral' japy::parse ("{\"a\":7}", "/i:a") >> i; assert (i == 7); japy::parse ("{\"a\":\"77\"}", "/?i:a") >> i; assert (i == 7); // ok, one more thing // '/#a/*' refers to 'elements of child array named a' japy::parse ("{\"a\":[8, 88]}", "/#a/*") >> i; // note that both 8 and 88 are a match, but >> extracts only the first one assert (i == 8); // now, escaped sequences decoding std::string s; japy::parse ("{\"a\":\"\\n\\u20AC\\uD834\\uDD1E\\ud834ab\\c\"}", "/a") >> s; assert (s == "\n\xE2\x82\xAC\xF0\x9D\x84\x9E\xED\xA0\xB4""abc"); // now, do not decode the value, get the raw bytes std::string raw; japy::parse ("{\"a\":\"\\n\\u20AC\"}", "/a") >> japy::raw (raw); assert (raw == "\\n\\u20AC"); // now, get the full body of an object as a string std::string body; const char * json = "{\"a\":\"\\n\\u20AC\"}"; japy::parse (json, "$") >> japy::body (body); assert (body == json); // now, our custom object and overloaded >> (see above) hello_t hello; japy::parse ("[\"world\"]", "/*") >> hello; assert (hello.str == "hello world"); // that's pretty it printf ("test1 done\n"); } static void test2 () { // now, how about iterating over a collection? // easy! int sum = 0; // #/$ means 'object elements of array root' for (auto object: japy::parse ("[{\"a\":1}, {\"a\":2}]", "#/$")) { int v = 0; // see the sub-query - '/a' works on the pre-selected object object["/a"] >> v; sum += v; } assert (sum == 3); // or one by one extraction of nodes sum = 0; auto node_set (japy::parse ("[{\"a\":1}, {\"a\":2}]", "#/$/a")); int v1 = 0; int v2 = 0; node_set >> v1 >> v2; sum += v1 + v2; assert (sum == 3); // a bit more complex document sum = 0; // '//$/a' means "all descendant objects' children named a" for (auto a_member: japy::parse ("[{\"a\":1}, [{\"a\":2}]]", "//$/a")) { int v = 0; // note that we don't need a sub-query here a_member >> v; sum += v; } assert (sum == 3); // and what if some parts of document do not match? sum = 0; // same path as in previous example try { const char * json = "[{\"a\":1}, [{\"b\":2}], {\"a\":3}]"; for (auto a_member: japy::parse (json, "//$/a")) { int v = 0; a_member >> v; sum += v; } assert (0); } catch (...) { // Path matching is done in 'all or nothing' manner, // that is - if first selector matches - than all path must match. // {\"b\":2} matches path head '//$', but does not match the tail 'a', // so exception is thrown as soon as japy finishes parsing it. } assert (sum == 1); // to avoid exceptions on partially matching branches, // use ? on selector that may observe mismatch sum = 0; for (auto a_member: japy::parse ("[{\"a\":1}, [{\"b\":2}]]", "//$/?a")) { int v = 0; a_member >> v; sum += v; } assert (sum == 1); // how about sub-iterating? sum = 0; for (auto arr: japy::parse ("[{\"a\":1}, [2, 3]]", "/#")) { for (auto element: arr["/*"]) { int v = 0; element >> v; sum += v; } } assert (sum == 5); // that's it on iterating printf ("test2 done\n"); } static void test3 () { // now how about parsing a json stream? { // a bit more to do, but still easy! const char * part1 = "[1, 2"; const char * part2 = ", 3]"; // will be 6 when we're done int sum = 0; // create a parser, specify a 'scope-path' // objects referred by scope-path are buffered internally // (if seen on the parts' borders) japy::parser_t parser ("/*"); // feed a part of your json into parser parser.put (part1); // iterate over elements found in first part for (auto element: parser) { int v = 0; element >> v; sum += v; } // only the first element was returned, as japy didn't yet see // the end of second element assert (sum == 1); // feed the second part of your json parser.put (part2); // iterate over elements found in second part for (auto element: parser) { int v = 0; element >> v; sum += v; } // now we're done! assert (sum == 6); } { // So, the structure of your stream parser will most // probably be like this: // 0. A container to store results of json processing. int sum = 0; // 1. Some input stream that produces parts of json. // Here, we'll use a plain string that will produce single chars. // I recommend you to choose the size of your parts (your read buffer) // such that it could allocate >10 of the typical node size // that is addressed by the scope-path - this will make // japy internal buffering costs insignificant. std::string stream ("[11, 22, 33]"); // 2. Parser with a proper scope japy::parser_t parser ("/*"); for (auto part: stream) { // 3. Feed part to the parser parser.put (part); // 4. Iterate over nodes addressed by scope-path for (auto node: parser) { int v = 0; node >> v; sum += v; } } // that's it assert (sum == 66); } { // normally a json document must have a single root, // and an exception is thrown in presence of 'trailing garbage'. // however, sometimes you have streams of json documents, // each having a root. use 'allow_many_roots' option for that case: int sum = 0; japy::parser_t parser ("/a"); parser.allow_many_roots (true); parser.put ("{\"a\":1} {\"a\":2}"); // two json docs in one stream for (auto node: parser) { int v = 0; node >> v; sum += v; } assert (sum == 3); } // I guess I'll add more stuff here when questions arise. printf ("test3 done\n"); } int main () { try { test1 (); test2 (); test3 (); } catch (std::exception & e) { printf ("ERROR: %s\n", e.what ()); } } <|endoftext|>
<commit_before>#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE Main #include <atomic> #include <boost/asio/steady_timer.hpp> #include <boost/test/unit_test.hpp> #include <chrono> #include <interfaces/imeasstorage.h> #include <iostream> #include <meas.h> #include <net/client.h> #include <net/server.h> #include <thread> #include <utils/logger.h> class Mock_MeasStorage : public virtual dariadb::storage::IMeasStorage { public: Mock_MeasStorage() { writed_count.store(0); } dariadb::Time minTime() override { return dariadb::Time(0); } dariadb::Time maxTime() override { return dariadb::Time(0); } bool minMaxTime(dariadb::Id id, dariadb::Time *minResult, dariadb::Time *maxResult) { return false; } void foreach(const dariadb::storage::QueryInterval &qi, dariadb::storage::IReaderClb *clbk) override { for (auto&v : writed) { if (v.inQuery(qi.ids, qi.flag, qi.source, qi.from, qi.to)) { clbk->call(v); } } } dariadb::Meas::Id2Meas readInTimePoint(const dariadb::storage::QueryTimePoint &q) override { return dariadb::Meas::Id2Meas{}; } dariadb::Meas::Id2Meas currentValue(const dariadb::IdArray &ids, const dariadb::Flag &flag) override { return dariadb::Meas::Id2Meas{}; } dariadb::append_result append(const dariadb::Meas &value) override { writed_count++; writed.push_back(value); return dariadb::append_result(1, 0); } void flush() override { } std::atomic_int writed_count; dariadb::Meas::MeasList writed; }; const dariadb::net::Server::Param server_param(2001); const dariadb::net::Client::Param client_param("127.0.0.1", 2001); std::atomic_bool server_runned; std::atomic_bool server_stop_flag; dariadb::net::Server *server_instance = nullptr; void server_thread_func() { dariadb::net::Server s(server_param); while (!s.is_runned()) { } server_instance = &s; server_runned.store(true); while (!server_stop_flag.load()) { } server_instance = nullptr; } BOOST_AUTO_TEST_CASE(QueryToStrTest) { const size_t MEASES_SIZE = 101; dariadb::IdArray ids; ids.resize(MEASES_SIZE); for (size_t i = 0; i < MEASES_SIZE; ++i) { ids[i] = i; } { dariadb::storage::QueryParam qp{ ids, 1, 3 }; auto dumped = qp.to_string(); BOOST_CHECK_GT(dumped.size(), size_t(2)); dariadb::storage::QueryParam qp_res{ {}, 0, 0 }; qp_res.from_string(dumped); BOOST_CHECK_EQUAL(qp.flag, qp_res.flag); BOOST_CHECK_EQUAL(qp.source, qp_res.source); BOOST_CHECK(qp.ids == qp_res.ids); } { dariadb::storage::QueryInterval qi{ ids, 1, 3, 11,123 }; auto dumped = qi.to_string(); BOOST_CHECK_GT(dumped.size(), size_t(2)); dariadb::storage::QueryInterval qi_res{ {}, 0, 0,0,0 }; qi_res.from_string(dumped); BOOST_CHECK_EQUAL(qi.flag, qi_res.flag); BOOST_CHECK_EQUAL(qi.source, qi_res.source); BOOST_CHECK(qi.ids == qi_res.ids); BOOST_CHECK_EQUAL(qi.from, qi_res.from); BOOST_CHECK_EQUAL(qi.to, qi_res.to); } { dariadb::storage::QueryTimePoint qi{ ids, 1, 11 }; auto dumped = qi.to_string(); BOOST_CHECK_GT(dumped.size(), size_t(2)); dariadb::storage::QueryTimePoint qi_res{ {}, 0, 0 }; qi_res.from_string(dumped); BOOST_CHECK_EQUAL(qi.flag, qi_res.flag); BOOST_CHECK_EQUAL(qi.source, qi_res.source); BOOST_CHECK(qi.ids == qi_res.ids); BOOST_CHECK_EQUAL(qi.time_point, qi_res.time_point); } } BOOST_AUTO_TEST_CASE(Connect) { dariadb::logger("********** Connect **********"); server_runned.store(false); std::thread server_thread{server_thread_func}; while (!server_runned.load()) { std::this_thread::sleep_for(std::chrono::milliseconds(300)); } dariadb::net::Client c(client_param); c.connect(); // 1 client while (true) { auto res = server_instance->connections_accepted(); auto st = c.state(); dariadb::logger("test>> ", "0 count: ", res, " state: ", st); if (res == size_t(1) && st == dariadb::net::ClientState::WORK) { break; } std::this_thread::sleep_for(std::chrono::milliseconds(300)); } { // this check disconnect on client::dtor. dariadb::net::Client c2(client_param); c2.connect(); // 2 client: c and c2 while (true) { auto res = server_instance->connections_accepted(); auto st = c2.state(); dariadb::logger("test>> ", "1 count: ", res, " state: ", st); if (res == size_t(2) && st == dariadb::net::ClientState::WORK) { break; } std::this_thread::sleep_for(std::chrono::milliseconds(300)); } } // 1 client: c while (true) { auto res = server_instance->connections_accepted(); std::cout << "one expect: " << res << std::endl; if (res == size_t(1)) { break; } std::this_thread::sleep_for(std::chrono::milliseconds(300)); } dariadb::net::Client c3(client_param); c3.connect(); // 2 client: c and c3 while (true) { auto res = server_instance->connections_accepted(); auto st = c3.state(); dariadb::logger("test>> ", "2 count: ", res, " state: ", st); if (res == size_t(2) && st == dariadb::net::ClientState::WORK) { break; } std::this_thread::sleep_for(std::chrono::milliseconds(300)); } c.disconnect(); // 1 client: c3 while (true) { auto res = server_instance->connections_accepted(); auto st = c.state(); dariadb::logger("test>> ", "3 count: ", res, " state: ", st); if (res == size_t(1) && c.state() == dariadb::net::ClientState::DISCONNECTED) { break; } std::this_thread::sleep_for(std::chrono::milliseconds(300)); } server_stop_flag = true; server_thread.join(); while (true) { auto state = c3.state(); dariadb::logger("test>> ", "4 state: ", state); if (state == dariadb::net::ClientState::DISCONNECTED) { break; } std::this_thread::sleep_for(std::chrono::milliseconds(300)); } } BOOST_AUTO_TEST_CASE(PingTest) { dariadb::logger("********** PingTest **********"); const size_t MAX_PONGS = 2; server_runned.store(false); server_stop_flag = false; std::thread server_thread{server_thread_func}; while (!server_runned.load()) { std::this_thread::sleep_for(std::chrono::milliseconds(300)); } dariadb::net::Client c1(client_param); c1.connect(); dariadb::net::Client c2(client_param); c2.connect(); // 2 clients while (true) { auto st1 = c1.state(); auto st2 = c2.state(); dariadb::logger("test>> ", "0 state1: ", st1, " state2: ", st2); if (st1 == dariadb::net::ClientState::WORK && st2 == dariadb::net::ClientState::WORK) { break; } std::this_thread::sleep_for(std::chrono::milliseconds(300)); } while (true) { auto p1 = c1.pings_answers(); auto p2 = c2.pings_answers(); dariadb::logger("test>> p1:", p1, " p2:", p2); std::this_thread::sleep_for(std::chrono::milliseconds(500)); if (p1 > MAX_PONGS && p2 > MAX_PONGS) { break; } } c1.disconnect(); c2.disconnect(); server_stop_flag = true; server_thread.join(); } BOOST_AUTO_TEST_CASE(ReadWriteTest) { const size_t MEASES_SIZE = 101; dariadb::logger("********** ReadWriteTest **********"); std::shared_ptr<Mock_MeasStorage> stor{ new Mock_MeasStorage() }; server_runned.store(false); server_stop_flag = false; std::thread server_thread{server_thread_func}; while (!server_runned.load()) { std::this_thread::sleep_for(std::chrono::milliseconds(300)); } server_instance->set_storage(stor.get()); dariadb::net::Client c1(client_param); c1.connect(); // 1 client while (true) { auto st1 = c1.state(); dariadb::logger("test>> ", "0 state1: ", st1); if (st1 == dariadb::net::ClientState::WORK) { break; } std::this_thread::sleep_for(std::chrono::milliseconds(300)); } dariadb::Meas::MeasArray ma; ma.resize(MEASES_SIZE); dariadb::IdArray ids; size_t max_id_size = 10; for (size_t i = 0; i < MEASES_SIZE; ++i) { ma[i].id = dariadb::Id(i); ma[i].value = dariadb::Value(i); ma[i].time = i; if (ids.size() < max_id_size) { ids.push_back(ma[i].id); } } c1.write(ma); while (stor->writed_count.load() != MEASES_SIZE) { std::this_thread::sleep_for(std::chrono::milliseconds(300)); } dariadb::storage::QueryInterval qi{ ids,0,dariadb::Time(0),dariadb::Time(MEASES_SIZE) }; auto result = c1.read(qi); BOOST_CHECK_EQUAL(result.size(), max_id_size); //BOOST_CHECK_EQUAL(result.size(), ma.size()); c1.disconnect(); server_stop_flag = true; server_thread.join(); } <commit_msg>test params.<commit_after>#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE Main #include <atomic> #include <boost/asio/steady_timer.hpp> #include <boost/test/unit_test.hpp> #include <chrono> #include <interfaces/imeasstorage.h> #include <iostream> #include <meas.h> #include <net/client.h> #include <net/server.h> #include <thread> #include <utils/logger.h> class Mock_MeasStorage : public virtual dariadb::storage::IMeasStorage { public: Mock_MeasStorage() { writed_count.store(0); } dariadb::Time minTime() override { return dariadb::Time(0); } dariadb::Time maxTime() override { return dariadb::Time(0); } bool minMaxTime(dariadb::Id id, dariadb::Time *minResult, dariadb::Time *maxResult) { return false; } void foreach(const dariadb::storage::QueryInterval &qi, dariadb::storage::IReaderClb *clbk) override { for (auto&v : writed) { if (v.inQuery(qi.ids, qi.flag, qi.source, qi.from, qi.to)) { clbk->call(v); } } } dariadb::Meas::Id2Meas readInTimePoint(const dariadb::storage::QueryTimePoint &q) override { return dariadb::Meas::Id2Meas{}; } dariadb::Meas::Id2Meas currentValue(const dariadb::IdArray &ids, const dariadb::Flag &flag) override { return dariadb::Meas::Id2Meas{}; } dariadb::append_result append(const dariadb::Meas &value) override { writed_count++; writed.push_back(value); return dariadb::append_result(1, 0); } void flush() override { } std::atomic_int writed_count; dariadb::Meas::MeasList writed; }; const dariadb::net::Server::Param server_param(2001); const dariadb::net::Client::Param client_param("127.0.0.1", 2001); std::atomic_bool server_runned; std::atomic_bool server_stop_flag; dariadb::net::Server *server_instance = nullptr; void server_thread_func() { dariadb::net::Server s(server_param); while (!s.is_runned()) { } server_instance = &s; server_runned.store(true); while (!server_stop_flag.load()) { } server_instance = nullptr; } BOOST_AUTO_TEST_CASE(QueryToStrTest) { const size_t MEASES_SIZE = 101; dariadb::IdArray ids; ids.resize(MEASES_SIZE); for (size_t i = 0; i < MEASES_SIZE; ++i) { ids[i] = i; } { dariadb::storage::QueryParam qp{ ids, 1, 3 }; auto dumped = qp.to_string(); BOOST_CHECK_GT(dumped.size(), size_t(2)); dariadb::storage::QueryParam qp_res{ {}, 0, 0 }; qp_res.from_string(dumped); BOOST_CHECK_EQUAL(qp.flag, qp_res.flag); BOOST_CHECK_EQUAL(qp.source, qp_res.source); BOOST_CHECK(qp.ids == qp_res.ids); } { dariadb::storage::QueryInterval qi{ ids, 1, 3, 11,123 }; auto dumped = qi.to_string(); BOOST_CHECK_GT(dumped.size(), size_t(2)); dariadb::storage::QueryInterval qi_res{ {}, 0, 0,0,0 }; qi_res.from_string(dumped); BOOST_CHECK_EQUAL(qi.flag, qi_res.flag); BOOST_CHECK_EQUAL(qi.source, qi_res.source); BOOST_CHECK(qi.ids == qi_res.ids); BOOST_CHECK_EQUAL(qi.from, qi_res.from); BOOST_CHECK_EQUAL(qi.to, qi_res.to); } { dariadb::storage::QueryTimePoint qi{ ids, 1, 11 }; auto dumped = qi.to_string(); BOOST_CHECK_GT(dumped.size(), size_t(2)); dariadb::storage::QueryTimePoint qi_res{ {}, 0, 0 }; qi_res.from_string(dumped); BOOST_CHECK_EQUAL(qi.flag, qi_res.flag); BOOST_CHECK_EQUAL(qi.source, qi_res.source); BOOST_CHECK(qi.ids == qi_res.ids); BOOST_CHECK_EQUAL(qi.time_point, qi_res.time_point); } } BOOST_AUTO_TEST_CASE(Connect) { dariadb::logger("********** Connect **********"); server_runned.store(false); std::thread server_thread{server_thread_func}; while (!server_runned.load()) { std::this_thread::sleep_for(std::chrono::milliseconds(300)); } dariadb::net::Client c(client_param); c.connect(); // 1 client while (true) { auto res = server_instance->connections_accepted(); auto st = c.state(); dariadb::logger("test>> ", "0 count: ", res, " state: ", st); if (res == size_t(1) && st == dariadb::net::ClientState::WORK) { break; } std::this_thread::sleep_for(std::chrono::milliseconds(300)); } { // this check disconnect on client::dtor. dariadb::net::Client c2(client_param); c2.connect(); // 2 client: c and c2 while (true) { auto res = server_instance->connections_accepted(); auto st = c2.state(); dariadb::logger("test>> ", "1 count: ", res, " state: ", st); if (res == size_t(2) && st == dariadb::net::ClientState::WORK) { break; } std::this_thread::sleep_for(std::chrono::milliseconds(300)); } } // 1 client: c while (true) { auto res = server_instance->connections_accepted(); std::cout << "one expect: " << res << std::endl; if (res == size_t(1)) { break; } std::this_thread::sleep_for(std::chrono::milliseconds(300)); } dariadb::net::Client c3(client_param); c3.connect(); // 2 client: c and c3 while (true) { auto res = server_instance->connections_accepted(); auto st = c3.state(); dariadb::logger("test>> ", "2 count: ", res, " state: ", st); if (res == size_t(2) && st == dariadb::net::ClientState::WORK) { break; } std::this_thread::sleep_for(std::chrono::milliseconds(300)); } c.disconnect(); // 1 client: c3 while (true) { auto res = server_instance->connections_accepted(); auto st = c.state(); dariadb::logger("test>> ", "3 count: ", res, " state: ", st); if (res == size_t(1) && c.state() == dariadb::net::ClientState::DISCONNECTED) { break; } std::this_thread::sleep_for(std::chrono::milliseconds(300)); } server_stop_flag = true; server_thread.join(); while (true) { auto state = c3.state(); dariadb::logger("test>> ", "4 state: ", state); if (state == dariadb::net::ClientState::DISCONNECTED) { break; } std::this_thread::sleep_for(std::chrono::milliseconds(300)); } } BOOST_AUTO_TEST_CASE(PingTest) { dariadb::logger("********** PingTest **********"); const size_t MAX_PONGS = 2; server_runned.store(false); server_stop_flag = false; std::thread server_thread{server_thread_func}; while (!server_runned.load()) { std::this_thread::sleep_for(std::chrono::milliseconds(300)); } dariadb::net::Client c1(client_param); c1.connect(); dariadb::net::Client c2(client_param); c2.connect(); // 2 clients while (true) { auto st1 = c1.state(); auto st2 = c2.state(); dariadb::logger("test>> ", "0 state1: ", st1, " state2: ", st2); if (st1 == dariadb::net::ClientState::WORK && st2 == dariadb::net::ClientState::WORK) { break; } std::this_thread::sleep_for(std::chrono::milliseconds(300)); } while (true) { auto p1 = c1.pings_answers(); auto p2 = c2.pings_answers(); dariadb::logger("test>> p1:", p1, " p2:", p2); std::this_thread::sleep_for(std::chrono::milliseconds(500)); if (p1 > MAX_PONGS && p2 > MAX_PONGS) { break; } } c1.disconnect(); c2.disconnect(); while (true) { auto st1 = c1.state(); auto st2 = c2.state(); dariadb::logger("test>> ", "0 state1: ", st1, " state2: ", st2); if (st1 == dariadb::net::ClientState::DISCONNECTED && st2 == dariadb::net::ClientState::DISCONNECTED) { break; } std::this_thread::sleep_for(std::chrono::milliseconds(300)); } server_stop_flag = true; server_thread.join(); } BOOST_AUTO_TEST_CASE(ReadWriteTest) { const size_t MEASES_SIZE = 101; dariadb::logger("********** ReadWriteTest **********"); std::shared_ptr<Mock_MeasStorage> stor{ new Mock_MeasStorage() }; server_runned.store(false); server_stop_flag = false; std::thread server_thread{server_thread_func}; while (!server_runned.load()) { std::this_thread::sleep_for(std::chrono::milliseconds(300)); } server_instance->set_storage(stor.get()); dariadb::net::Client c1(client_param); c1.connect(); // 1 client while (true) { auto st1 = c1.state(); dariadb::logger("test>> ", "0 state1: ", st1); if (st1 == dariadb::net::ClientState::WORK) { break; } std::this_thread::sleep_for(std::chrono::milliseconds(300)); } dariadb::Meas::MeasArray ma; ma.resize(MEASES_SIZE); dariadb::IdArray ids; ids.resize(MEASES_SIZE); size_t max_id_size = 101; for (size_t i = 0; i < MEASES_SIZE; ++i) { ma[i].id = dariadb::Id(i); ma[i].value = dariadb::Value(i); ma[i].time = i; ids[i]=ma[i].id; } c1.write(ma); while (stor->writed_count.load() != MEASES_SIZE) { std::this_thread::sleep_for(std::chrono::milliseconds(300)); } dariadb::storage::QueryInterval qi{ ids,0,dariadb::Time(0),dariadb::Time(MEASES_SIZE) }; auto result = c1.read(qi); //BOOST_CHECK_EQUAL(result.size(), max_id_size); BOOST_CHECK_EQUAL(result.size(), ma.size()); c1.disconnect(); while (true) { auto st1 = c1.state(); dariadb::logger("test>> ", "0 state1: ", st1); if (st1 == dariadb::net::ClientState::DISCONNECTED) { break; } std::this_thread::sleep_for(std::chrono::milliseconds(300)); } server_stop_flag = true; server_thread.join(); } <|endoftext|>
<commit_before>// Macro to compare masses in root data base to the values from pdg // http://pdg.lbl.gov/2009/mcdata/mass_width_2008.mc // // the ROOT values are read in by TDatabasePDG from $ROOTSYS/etc/pdg_table.C // // Author: Christian.Klein-Boesing@cern.ch #include <fstream> #include <iostream> #include "TDatabasePDG.h" #include "TParticlePDG.h" using namespace std; void CompareMasses(){ TString massWidthFile = gSystem->UnixPathName(gInterpreter->GetCurrentMacroName()); massWidthFile.ReplaceAll("tasks.C","mass_width_2008.mc.txt"); FILE* file = fopen(massWidthFile.Data(),"r"); ifstream in1; in1.open(massWidthFile); if (!in1.good()){ Printf("Could not open PDG particle file %s",massWidthFile.Data()); fclose(file); return; } char c[200]; char cempty; Int_t pdg[4]; Float_t mass, err1,err2,err; Int_t ndiff = 0; while (fgets(&c[0],200,file)) { if (c[0] != '*' && c[0] !='W') { // printf("%s",c); sscanf(&c[1],"%8d",&pdg[0]); // check emptyness pdg[1] = 0; for(int i = 0;i<8;i++){ sscanf(&c[9+i],"%c",&cempty); if(cempty != ' ')sscanf(&c[9],"%8d",&pdg[1]); } pdg[2] = 0; for(int i = 0;i<8;i++){ sscanf(&c[17+i],"%c",&cempty); if(cempty != ' ')sscanf(&c[17],"%8d",&pdg[2]); } pdg[3] = 0; for(int i = 0;i<8;i++){ sscanf(&c[25+i],"%c",&cempty); if(cempty != ' ')sscanf(&c[25],"%8d",&pdg[3]); } sscanf(&c[35],"%14f",&mass); sscanf(&c[50],"%8f",&err1); sscanf(&c[50],"%8f",&err2); err = TMath::Max((Double_t)err1,(Double_t)-1.*err2); for(int ipdg = 0;ipdg < 4;ipdg++){ if(pdg[ipdg]==0)continue; TParticlePDG *partRoot = TDatabasePDG::Instance()->GetParticle(pdg[ipdg]); if(partRoot){ Float_t massRoot = partRoot->Mass(); Float_t deltaM = TMath::Abs(massRoot - mass); // if(deltaM > err){ if(deltaM/mass>1E-05){ ndiff++; Printf("%10s %8d pdg mass %E pdg err %E root Mass %E >> deltaM %E = %3.3f%%",partRoot->GetName(),pdg[ipdg],mass,err,massRoot,deltaM,100.*deltaM/mass); } } } } }// while fclose(file); if (ndiff == 0) Printf("Crongratulations !! All particles in ROOT and PDG have identical masses"); } <commit_msg>Fix totally bogus code in this macro. Fixes ROOT-5890.<commit_after>// Macro to compare masses in ROOT data base to the values from pdg // http://pdg.lbl.gov/2009/mcdata/mass_width_2008.mc // // The ROOT values are read in by TDatabasePDG from $ROOTSYS/etc/pdg_table.txt // // Author: Christian.Klein-Boesing@cern.ch #include "TDatabasePDG.h" #include "TParticlePDG.h" void CompareMasses() { TString massWidthFile = gSystem->UnixPathName(gInterpreter->GetCurrentMacroName()); massWidthFile.ReplaceAll("CompareMasses.C","mass_width_2008.mc.txt"); FILE* file = fopen(massWidthFile.Data(),"r"); if (!file){ Printf("Could not open PDG particle file %s", massWidthFile.Data()); return; } char c[200]; char cempty; Int_t pdg[4]; Float_t mass, err1, err2, err; Int_t ndiff = 0; while (fgets(c, 200, file)) { if (c[0] != '*' && c[0] !='W') { //printf("%s",c); sscanf(&c[1], "%8d", &pdg[0]); // check emptyness pdg[1] = 0; for(int i = 0;i<8;i++){ sscanf(&c[9+i],"%c",&cempty); if(cempty != ' ')sscanf(&c[9],"%8d",&pdg[1]); } pdg[2] = 0; for(int i = 0;i<8;i++){ sscanf(&c[17+i],"%c",&cempty); if(cempty != ' ')sscanf(&c[17],"%8d",&pdg[2]); } pdg[3] = 0; for(int i = 0;i<8;i++){ sscanf(&c[25+i],"%c",&cempty); if(cempty != ' ')sscanf(&c[25],"%8d",&pdg[3]); } sscanf(&c[35],"%14f",&mass); sscanf(&c[50],"%8f",&err1); sscanf(&c[50],"%8f",&err2); err = TMath::Max((Double_t)err1,(Double_t)-1.*err2); for(int ipdg = 0;ipdg < 4;ipdg++){ if(pdg[ipdg]==0)continue; TParticlePDG *partRoot = TDatabasePDG::Instance()->GetParticle(pdg[ipdg]); if(partRoot){ Float_t massRoot = partRoot->Mass(); Float_t deltaM = TMath::Abs(massRoot - mass); // if(deltaM > err){ if (mass != 0.0 && deltaM/mass>1E-05){ ndiff++; Printf("%10s %8d pdg mass %E pdg err %E root Mass %E >> deltaM %E = %3.3f%%",partRoot->GetName(),pdg[ipdg],mass,err,massRoot,deltaM,100.*deltaM/mass); } } } } }// while fclose(file); if (ndiff == 0) Printf("Crongratulations !! All particles in ROOT and PDG have identical masses"); } <|endoftext|>
<commit_before>//===-- MainLoop.cpp --------------------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "llvm/Config/llvm-config.h" #include "lldb/Host/MainLoop.h" #include "lldb/Host/PosixApi.h" #include "lldb/Utility/Status.h" #include <algorithm> #include <cassert> #include <cerrno> #include <csignal> #include <time.h> #include <vector> // Multiplexing is implemented using kqueue on systems that support it (BSD // variants including OSX). On linux we use ppoll, while android uses pselect // (ppoll is present but not implemented properly). On windows we use WSApoll // (which does not support signals). #if HAVE_SYS_EVENT_H #include <sys/event.h> #elif defined(_WIN32) #include <winsock2.h> #elif defined(__ANDROID__) #include <sys/syscall.h> #else #include <poll.h> #endif #ifdef _WIN32 #define POLL WSAPoll #else #define POLL poll #endif #if SIGNAL_POLLING_UNSUPPORTED #ifdef _WIN32 typedef int sigset_t; typedef int siginfo_t; #endif int ppoll(struct pollfd *fds, size_t nfds, const struct timespec *timeout_ts, const sigset_t *) { int timeout = (timeout_ts == nullptr) ? -1 : (timeout_ts->tv_sec * 1000 + timeout_ts->tv_nsec / 1000000); return POLL(fds, nfds, timeout); } #endif using namespace lldb; using namespace lldb_private; static sig_atomic_t g_signal_flags[NSIG]; static void SignalHandler(int signo, siginfo_t *info, void *) { assert(signo < NSIG); g_signal_flags[signo] = 1; } class MainLoop::RunImpl { public: RunImpl(MainLoop &loop); ~RunImpl() = default; Status Poll(); void ProcessEvents(); private: MainLoop &loop; #if HAVE_SYS_EVENT_H std::vector<struct kevent> in_events; struct kevent out_events[4]; int num_events = -1; #else #ifdef __ANDROID__ fd_set read_fd_set; #else std::vector<struct pollfd> read_fds; #endif sigset_t get_sigmask(); #endif }; #if HAVE_SYS_EVENT_H MainLoop::RunImpl::RunImpl(MainLoop &loop) : loop(loop) { in_events.reserve(loop.m_read_fds.size()); } Status MainLoop::RunImpl::Poll() { in_events.resize(loop.m_read_fds.size()); unsigned i = 0; for (auto &fd : loop.m_read_fds) EV_SET(&in_events[i++], fd.first, EVFILT_READ, EV_ADD, 0, 0, 0); num_events = kevent(loop.m_kqueue, in_events.data(), in_events.size(), out_events, llvm::array_lengthof(out_events), nullptr); if (num_events < 0) return Status("kevent() failed with error %d\n", num_events); return Status(); } void MainLoop::RunImpl::ProcessEvents() { assert(num_events >= 0); for (int i = 0; i < num_events; ++i) { if (loop.m_terminate_request) return; switch (out_events[i].filter) { case EVFILT_READ: loop.ProcessReadObject(out_events[i].ident); break; case EVFILT_SIGNAL: loop.ProcessSignal(out_events[i].ident); break; default: llvm_unreachable("Unknown event"); } } } #else MainLoop::RunImpl::RunImpl(MainLoop &loop) : loop(loop) { #ifndef __ANDROID__ read_fds.reserve(loop.m_read_fds.size()); #endif } sigset_t MainLoop::RunImpl::get_sigmask() { sigset_t sigmask; #if defined(_WIN32) sigmask = 0; #elif SIGNAL_POLLING_UNSUPPORTED sigemptyset(&sigmask); #else int ret = pthread_sigmask(SIG_SETMASK, nullptr, &sigmask); assert(ret == 0); (void) ret; for (const auto &sig : loop.m_signals) sigdelset(&sigmask, sig.first); #endif return sigmask; } #ifdef __ANDROID__ Status MainLoop::RunImpl::Poll() { // ppoll(2) is not supported on older all android versions. Also, older // versions android (API <= 19) implemented pselect in a non-atomic way, as a // combination of pthread_sigmask and select. This is not sufficient for us, // as we rely on the atomicity to correctly implement signal polling, so we // call the underlying syscall ourselves. FD_ZERO(&read_fd_set); int nfds = 0; for (const auto &fd : loop.m_read_fds) { FD_SET(fd.first, &read_fd_set); nfds = std::max(nfds, fd.first + 1); } union { sigset_t set; uint64_t pad; } kernel_sigset; memset(&kernel_sigset, 0, sizeof(kernel_sigset)); kernel_sigset.set = get_sigmask(); struct { void *sigset_ptr; size_t sigset_len; } extra_data = {&kernel_sigset, sizeof(kernel_sigset)}; if (syscall(__NR_pselect6, nfds, &read_fd_set, nullptr, nullptr, nullptr, &extra_data) == -1 && errno != EINTR) return Status(errno, eErrorTypePOSIX); return Status(); } #else Status MainLoop::RunImpl::Poll() { read_fds.clear(); sigset_t sigmask = get_sigmask(); for (const auto &fd : loop.m_read_fds) { struct pollfd pfd; pfd.fd = fd.first; pfd.events = POLLIN; pfd.revents = 0; read_fds.push_back(pfd); } if (ppoll(read_fds.data(), read_fds.size(), nullptr, &sigmask) == -1 && errno != EINTR) return Status(errno, eErrorTypePOSIX); return Status(); } #endif void MainLoop::RunImpl::ProcessEvents() { #ifdef __ANDROID__ // Collect first all readable file descriptors into a separate vector and // then iterate over it to invoke callbacks. Iterating directly over // loop.m_read_fds is not possible because the callbacks can modify the // container which could invalidate the iterator. std::vector<IOObject::WaitableHandle> fds; for (const auto &fd : loop.m_read_fds) if (FD_ISSET(fd.first, &read_fd_set)) fds.push_back(fd.first); for (const auto &handle : fds) { #else for (const auto &fd : read_fds) { if ((fd.revents & (POLLIN | POLLHUP)) == 0) continue; IOObject::WaitableHandle handle = fd.fd; #endif if (loop.m_terminate_request) return; loop.ProcessReadObject(handle); } std::vector<int> signals; for (const auto &entry : loop.m_signals) if (g_signal_flags[entry.first] != 0) signals.push_back(entry.first); for (const auto &signal : signals) { if (loop.m_terminate_request) return; g_signal_flags[signal] = 0; loop.ProcessSignal(signal); } } #endif MainLoop::MainLoop() { #if HAVE_SYS_EVENT_H m_kqueue = kqueue(); assert(m_kqueue >= 0); #endif } MainLoop::~MainLoop() { #if HAVE_SYS_EVENT_H close(m_kqueue); #endif assert(m_read_fds.size() == 0); assert(m_signals.size() == 0); } MainLoop::ReadHandleUP MainLoop::RegisterReadObject(const IOObjectSP &object_sp, const Callback &callback, Status &error) { #ifdef _WIN32 if (object_sp->GetFdType() != IOObject:: eFDTypeSocket) { error.SetErrorString("MainLoop: non-socket types unsupported on Windows"); return nullptr; } #endif if (!object_sp || !object_sp->IsValid()) { error.SetErrorString("IO object is not valid."); return nullptr; } const bool inserted = m_read_fds.insert({object_sp->GetWaitableHandle(), callback}).second; if (!inserted) { error.SetErrorStringWithFormat("File descriptor %d already monitored.", object_sp->GetWaitableHandle()); return nullptr; } return CreateReadHandle(object_sp); } // We shall block the signal, then install the signal handler. The signal will // be unblocked in the Run() function to check for signal delivery. MainLoop::SignalHandleUP MainLoop::RegisterSignal(int signo, const Callback &callback, Status &error) { #ifdef SIGNAL_POLLING_UNSUPPORTED error.SetErrorString("Signal polling is not supported on this platform."); return nullptr; #else if (m_signals.find(signo) != m_signals.end()) { error.SetErrorStringWithFormat("Signal %d already monitored.", signo); return nullptr; } SignalInfo info; info.callback = callback; struct sigaction new_action; new_action.sa_sigaction = &SignalHandler; new_action.sa_flags = SA_SIGINFO; sigemptyset(&new_action.sa_mask); sigaddset(&new_action.sa_mask, signo); sigset_t old_set; g_signal_flags[signo] = 0; // Even if using kqueue, the signal handler will still be invoked, so it's // important to replace it with our "benign" handler. int ret = sigaction(signo, &new_action, &info.old_action); assert(ret == 0 && "sigaction failed"); #if HAVE_SYS_EVENT_H struct kevent ev; EV_SET(&ev, signo, EVFILT_SIGNAL, EV_ADD, 0, 0, 0); ret = kevent(m_kqueue, &ev, 1, nullptr, 0, nullptr); assert(ret == 0); #endif // If we're using kqueue, the signal needs to be unblocked in order to // receive it. If using pselect/ppoll, we need to block it, and later unblock // it as a part of the system call. ret = pthread_sigmask(HAVE_SYS_EVENT_H ? SIG_UNBLOCK : SIG_BLOCK, &new_action.sa_mask, &old_set); assert(ret == 0 && "pthread_sigmask failed"); info.was_blocked = sigismember(&old_set, signo); m_signals.insert({signo, info}); return SignalHandleUP(new SignalHandle(*this, signo)); #endif } void MainLoop::UnregisterReadObject(IOObject::WaitableHandle handle) { bool erased = m_read_fds.erase(handle); UNUSED_IF_ASSERT_DISABLED(erased); assert(erased); } void MainLoop::UnregisterSignal(int signo) { #if SIGNAL_POLLING_UNSUPPORTED Status("Signal polling is not supported on this platform."); #else auto it = m_signals.find(signo); assert(it != m_signals.end()); sigaction(signo, &it->second.old_action, nullptr); sigset_t set; sigemptyset(&set); sigaddset(&set, signo); int ret = pthread_sigmask(it->second.was_blocked ? SIG_BLOCK : SIG_UNBLOCK, &set, nullptr); assert(ret == 0); (void)ret; #if HAVE_SYS_EVENT_H struct kevent ev; EV_SET(&ev, signo, EVFILT_SIGNAL, EV_DELETE, 0, 0, 0); ret = kevent(m_kqueue, &ev, 1, nullptr, 0, nullptr); assert(ret == 0); #endif m_signals.erase(it); #endif } Status MainLoop::Run() { m_terminate_request = false; Status error; RunImpl impl(*this); // run until termination or until we run out of things to listen to while (!m_terminate_request && (!m_read_fds.empty() || !m_signals.empty())) { error = impl.Poll(); if (error.Fail()) return error; impl.ProcessEvents(); if (m_terminate_request) return Status(); } return Status(); } void MainLoop::ProcessSignal(int signo) { auto it = m_signals.find(signo); if (it != m_signals.end()) it->second.callback(*this); // Do the work } void MainLoop::ProcessReadObject(IOObject::WaitableHandle handle) { auto it = m_read_fds.find(handle); if (it != m_read_fds.end()) it->second(*this); // Do the work } <commit_msg>[lldb] [MainLoop] Report errno for failed kevent()<commit_after>//===-- MainLoop.cpp --------------------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "llvm/Config/llvm-config.h" #include "lldb/Host/MainLoop.h" #include "lldb/Host/PosixApi.h" #include "lldb/Utility/Status.h" #include <algorithm> #include <cassert> #include <cerrno> #include <csignal> #include <time.h> #include <vector> // Multiplexing is implemented using kqueue on systems that support it (BSD // variants including OSX). On linux we use ppoll, while android uses pselect // (ppoll is present but not implemented properly). On windows we use WSApoll // (which does not support signals). #if HAVE_SYS_EVENT_H #include <sys/event.h> #elif defined(_WIN32) #include <winsock2.h> #elif defined(__ANDROID__) #include <sys/syscall.h> #else #include <poll.h> #endif #ifdef _WIN32 #define POLL WSAPoll #else #define POLL poll #endif #if SIGNAL_POLLING_UNSUPPORTED #ifdef _WIN32 typedef int sigset_t; typedef int siginfo_t; #endif int ppoll(struct pollfd *fds, size_t nfds, const struct timespec *timeout_ts, const sigset_t *) { int timeout = (timeout_ts == nullptr) ? -1 : (timeout_ts->tv_sec * 1000 + timeout_ts->tv_nsec / 1000000); return POLL(fds, nfds, timeout); } #endif using namespace lldb; using namespace lldb_private; static sig_atomic_t g_signal_flags[NSIG]; static void SignalHandler(int signo, siginfo_t *info, void *) { assert(signo < NSIG); g_signal_flags[signo] = 1; } class MainLoop::RunImpl { public: RunImpl(MainLoop &loop); ~RunImpl() = default; Status Poll(); void ProcessEvents(); private: MainLoop &loop; #if HAVE_SYS_EVENT_H std::vector<struct kevent> in_events; struct kevent out_events[4]; int num_events = -1; #else #ifdef __ANDROID__ fd_set read_fd_set; #else std::vector<struct pollfd> read_fds; #endif sigset_t get_sigmask(); #endif }; #if HAVE_SYS_EVENT_H MainLoop::RunImpl::RunImpl(MainLoop &loop) : loop(loop) { in_events.reserve(loop.m_read_fds.size()); } Status MainLoop::RunImpl::Poll() { in_events.resize(loop.m_read_fds.size()); unsigned i = 0; for (auto &fd : loop.m_read_fds) EV_SET(&in_events[i++], fd.first, EVFILT_READ, EV_ADD, 0, 0, 0); num_events = kevent(loop.m_kqueue, in_events.data(), in_events.size(), out_events, llvm::array_lengthof(out_events), nullptr); if (num_events < 0) return Status(errno, eErrorTypePOSIX); return Status(); } void MainLoop::RunImpl::ProcessEvents() { assert(num_events >= 0); for (int i = 0; i < num_events; ++i) { if (loop.m_terminate_request) return; switch (out_events[i].filter) { case EVFILT_READ: loop.ProcessReadObject(out_events[i].ident); break; case EVFILT_SIGNAL: loop.ProcessSignal(out_events[i].ident); break; default: llvm_unreachable("Unknown event"); } } } #else MainLoop::RunImpl::RunImpl(MainLoop &loop) : loop(loop) { #ifndef __ANDROID__ read_fds.reserve(loop.m_read_fds.size()); #endif } sigset_t MainLoop::RunImpl::get_sigmask() { sigset_t sigmask; #if defined(_WIN32) sigmask = 0; #elif SIGNAL_POLLING_UNSUPPORTED sigemptyset(&sigmask); #else int ret = pthread_sigmask(SIG_SETMASK, nullptr, &sigmask); assert(ret == 0); (void) ret; for (const auto &sig : loop.m_signals) sigdelset(&sigmask, sig.first); #endif return sigmask; } #ifdef __ANDROID__ Status MainLoop::RunImpl::Poll() { // ppoll(2) is not supported on older all android versions. Also, older // versions android (API <= 19) implemented pselect in a non-atomic way, as a // combination of pthread_sigmask and select. This is not sufficient for us, // as we rely on the atomicity to correctly implement signal polling, so we // call the underlying syscall ourselves. FD_ZERO(&read_fd_set); int nfds = 0; for (const auto &fd : loop.m_read_fds) { FD_SET(fd.first, &read_fd_set); nfds = std::max(nfds, fd.first + 1); } union { sigset_t set; uint64_t pad; } kernel_sigset; memset(&kernel_sigset, 0, sizeof(kernel_sigset)); kernel_sigset.set = get_sigmask(); struct { void *sigset_ptr; size_t sigset_len; } extra_data = {&kernel_sigset, sizeof(kernel_sigset)}; if (syscall(__NR_pselect6, nfds, &read_fd_set, nullptr, nullptr, nullptr, &extra_data) == -1 && errno != EINTR) return Status(errno, eErrorTypePOSIX); return Status(); } #else Status MainLoop::RunImpl::Poll() { read_fds.clear(); sigset_t sigmask = get_sigmask(); for (const auto &fd : loop.m_read_fds) { struct pollfd pfd; pfd.fd = fd.first; pfd.events = POLLIN; pfd.revents = 0; read_fds.push_back(pfd); } if (ppoll(read_fds.data(), read_fds.size(), nullptr, &sigmask) == -1 && errno != EINTR) return Status(errno, eErrorTypePOSIX); return Status(); } #endif void MainLoop::RunImpl::ProcessEvents() { #ifdef __ANDROID__ // Collect first all readable file descriptors into a separate vector and // then iterate over it to invoke callbacks. Iterating directly over // loop.m_read_fds is not possible because the callbacks can modify the // container which could invalidate the iterator. std::vector<IOObject::WaitableHandle> fds; for (const auto &fd : loop.m_read_fds) if (FD_ISSET(fd.first, &read_fd_set)) fds.push_back(fd.first); for (const auto &handle : fds) { #else for (const auto &fd : read_fds) { if ((fd.revents & (POLLIN | POLLHUP)) == 0) continue; IOObject::WaitableHandle handle = fd.fd; #endif if (loop.m_terminate_request) return; loop.ProcessReadObject(handle); } std::vector<int> signals; for (const auto &entry : loop.m_signals) if (g_signal_flags[entry.first] != 0) signals.push_back(entry.first); for (const auto &signal : signals) { if (loop.m_terminate_request) return; g_signal_flags[signal] = 0; loop.ProcessSignal(signal); } } #endif MainLoop::MainLoop() { #if HAVE_SYS_EVENT_H m_kqueue = kqueue(); assert(m_kqueue >= 0); #endif } MainLoop::~MainLoop() { #if HAVE_SYS_EVENT_H close(m_kqueue); #endif assert(m_read_fds.size() == 0); assert(m_signals.size() == 0); } MainLoop::ReadHandleUP MainLoop::RegisterReadObject(const IOObjectSP &object_sp, const Callback &callback, Status &error) { #ifdef _WIN32 if (object_sp->GetFdType() != IOObject:: eFDTypeSocket) { error.SetErrorString("MainLoop: non-socket types unsupported on Windows"); return nullptr; } #endif if (!object_sp || !object_sp->IsValid()) { error.SetErrorString("IO object is not valid."); return nullptr; } const bool inserted = m_read_fds.insert({object_sp->GetWaitableHandle(), callback}).second; if (!inserted) { error.SetErrorStringWithFormat("File descriptor %d already monitored.", object_sp->GetWaitableHandle()); return nullptr; } return CreateReadHandle(object_sp); } // We shall block the signal, then install the signal handler. The signal will // be unblocked in the Run() function to check for signal delivery. MainLoop::SignalHandleUP MainLoop::RegisterSignal(int signo, const Callback &callback, Status &error) { #ifdef SIGNAL_POLLING_UNSUPPORTED error.SetErrorString("Signal polling is not supported on this platform."); return nullptr; #else if (m_signals.find(signo) != m_signals.end()) { error.SetErrorStringWithFormat("Signal %d already monitored.", signo); return nullptr; } SignalInfo info; info.callback = callback; struct sigaction new_action; new_action.sa_sigaction = &SignalHandler; new_action.sa_flags = SA_SIGINFO; sigemptyset(&new_action.sa_mask); sigaddset(&new_action.sa_mask, signo); sigset_t old_set; g_signal_flags[signo] = 0; // Even if using kqueue, the signal handler will still be invoked, so it's // important to replace it with our "benign" handler. int ret = sigaction(signo, &new_action, &info.old_action); assert(ret == 0 && "sigaction failed"); #if HAVE_SYS_EVENT_H struct kevent ev; EV_SET(&ev, signo, EVFILT_SIGNAL, EV_ADD, 0, 0, 0); ret = kevent(m_kqueue, &ev, 1, nullptr, 0, nullptr); assert(ret == 0); #endif // If we're using kqueue, the signal needs to be unblocked in order to // receive it. If using pselect/ppoll, we need to block it, and later unblock // it as a part of the system call. ret = pthread_sigmask(HAVE_SYS_EVENT_H ? SIG_UNBLOCK : SIG_BLOCK, &new_action.sa_mask, &old_set); assert(ret == 0 && "pthread_sigmask failed"); info.was_blocked = sigismember(&old_set, signo); m_signals.insert({signo, info}); return SignalHandleUP(new SignalHandle(*this, signo)); #endif } void MainLoop::UnregisterReadObject(IOObject::WaitableHandle handle) { bool erased = m_read_fds.erase(handle); UNUSED_IF_ASSERT_DISABLED(erased); assert(erased); } void MainLoop::UnregisterSignal(int signo) { #if SIGNAL_POLLING_UNSUPPORTED Status("Signal polling is not supported on this platform."); #else auto it = m_signals.find(signo); assert(it != m_signals.end()); sigaction(signo, &it->second.old_action, nullptr); sigset_t set; sigemptyset(&set); sigaddset(&set, signo); int ret = pthread_sigmask(it->second.was_blocked ? SIG_BLOCK : SIG_UNBLOCK, &set, nullptr); assert(ret == 0); (void)ret; #if HAVE_SYS_EVENT_H struct kevent ev; EV_SET(&ev, signo, EVFILT_SIGNAL, EV_DELETE, 0, 0, 0); ret = kevent(m_kqueue, &ev, 1, nullptr, 0, nullptr); assert(ret == 0); #endif m_signals.erase(it); #endif } Status MainLoop::Run() { m_terminate_request = false; Status error; RunImpl impl(*this); // run until termination or until we run out of things to listen to while (!m_terminate_request && (!m_read_fds.empty() || !m_signals.empty())) { error = impl.Poll(); if (error.Fail()) return error; impl.ProcessEvents(); if (m_terminate_request) return Status(); } return Status(); } void MainLoop::ProcessSignal(int signo) { auto it = m_signals.find(signo); if (it != m_signals.end()) it->second.callback(*this); // Do the work } void MainLoop::ProcessReadObject(IOObject::WaitableHandle handle) { auto it = m_read_fds.find(handle); if (it != m_read_fds.end()) it->second(*this); // Do the work } <|endoftext|>
<commit_before>#pragma once //=========================================================================// /*! @file @brief SD カード・マネージャー @n @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=========================================================================// #include <cstring> #include "common/format.hpp" #include "common/string_utils.hpp" #include "ff12b/mmc_io.hpp" namespace utils { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief SD カード・マネージャー・クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// class sdc_man { FATFS fatfs_; ///< FatFS コンテキスト char current_[_MAX_LFN + 1]; bool mount_; public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// sdc_man() : current_{ 0 }, mount_(false) { } //-----------------------------------------------------------------// /*! @brief 開始(初期化) */ //-----------------------------------------------------------------// void start() { mount_ = false; strcpy(current_, "/"); select_wait_ = 0; mount_delay_ = 0; memset(&fatfs_, 0, sizeof(FATFS)); } }; } <commit_msg>new file<commit_after>#pragma once //=========================================================================// /*! @file @brief SD カード・マネージャー @n @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=========================================================================// #include <cstring> #include "common/format.hpp" #include "common/string_utils.hpp" #include "ff12b/mmc_io.hpp" namespace utils { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief SD カード・マネージャー・クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// class sdc_man { public: //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief DIR リスト関数型 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// typedef void (*dir_loop_func)(const char* name, const FILINFO* fi, bool dir, void* option); private: //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief SD カード・ディレクトリー・リスト・クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// class dir_list { DIR dir_; uint32_t total_; uint32_t limit_; char* ptr_; bool init_; char full_[_MAX_LFN + 1]; public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// dir_list() : total_(0), limit_(10), ptr_(nullptr), init_(false) { } //-----------------------------------------------------------------// /*! @brief プローブ(状態) @return 取得中なら「true」 */ //-----------------------------------------------------------------// bool probe() const { return init_; } //-----------------------------------------------------------------// /*! @brief ファイル数を取得 @return ファイル数 */ //-----------------------------------------------------------------// uint32_t get_total() const { return total_; } //-----------------------------------------------------------------// /*! @brief ディレクトリーリスト開始 @n ※「probe()」関数が「false」になるまで「service()」を呼ぶ @param[in] root ルート・パス @return エラー無ければ「true」 */ //-----------------------------------------------------------------// bool start(const char* root) { total_ = 0; std::strcpy(full_, root); auto st = f_opendir(&dir_, full_); if(st != FR_OK) { return false; } std::strcat(full_, "/"); ptr_ = &full_[std::strlen(full_)]; init_ = true; return true; } //-----------------------------------------------------------------// /*! @brief ディレクトリーリスト、ループ @param[in] num ループ回数 @param[in] func 実行関数 @param[in] todir 「true」の場合、ディレクトリーも関数を呼ぶ @param[in] option オプション・ポインター @return エラー無ければ「true」 */ //-----------------------------------------------------------------// bool service(uint32_t num, dir_loop_func func = nullptr, bool todir = false, void* option = nullptr) { if(!init_) return false; for(uint32_t i = 0; i < num; ++i) { FILINFO fi; // Read a directory item if(f_readdir(&dir_, &fi) != FR_OK) { init_ = false; return false; } if(!fi.fname[0]) { f_closedir(&dir_); init_ = false; break; } if(func != nullptr) { #if _USE_LFN != 0 str::sjis_to_utf8(fi.fname, ptr_); #else std::strcpy(ptr_, fi.fname); #endif if(fi.fattrib & AM_DIR) { if(todir) { func(ptr_, &fi, true, option); } } else { func(ptr_, &fi, false, option); } } ++total_; } return true; } }; FATFS fatfs_; ///< FatFS コンテキスト char current_[_MAX_LFN + 1]; bool cdet_; bool mount_; uint16_t mount_delay_; dir_list dir_list_; uint32_t dir_list_limit_; dir_loop_func dir_func_; bool dir_todir_; void* dir_option_; struct match_t { const char* key_; char* dst_; uint8_t cnt_; uint8_t no_; }; struct copy_t { uint16_t idx_; uint16_t match_; char* path_; }; static void dir_list_func_(const char* name, const FILINFO* fi, bool dir, void* option) { if(fi == nullptr) return; time_t t = str::fatfs_time_to(fi->fdate, fi->ftime); struct tm *m = localtime(&t); if(dir) { format(" "); } else { format("%10d ") % fi->fsize; } format("%s %2d %4d %02d:%02d ") % get_mon(m->tm_mon) % static_cast<int>(m->tm_mday) % static_cast<int>(m->tm_year + 1900) % static_cast<int>(m->tm_hour) % static_cast<int>(m->tm_min); if(dir) { format("/"); } else { format(" "); } format("%s\n") % name; } static void match_func_(const char* name, const FILINFO* fi, bool dir, void* option) noexcept { match_t* t = reinterpret_cast<match_t*>(option); if(std::strncmp(name, t->key_, std::strlen(t->key_)) == 0) { if(t->dst_ != nullptr && t->cnt_ == t->no_) { std::strcpy(t->dst_, name); } ++t->cnt_; } } static void path_copy_func_(const char* name, const FILINFO* fi, bool dir, void* option) noexcept { copy_t* t = reinterpret_cast<copy_t*>(option); if(t->idx_ == t->match_) { if(t->path_ != nullptr) { char* p = t->path_; if(dir) *p++ = '/'; std::strcpy(p, name); } } ++t->idx_; } void create_full_path_(const char* path, char* full) const noexcept { std::strcpy(full, current_); if(path == nullptr || path[0] == 0) { if(full[0] == 0) { std::strcpy(full, "/"); } } else if(std::strcmp(path, "..") == 0) { char* p = std::strrchr(full, '/'); if(p != nullptr) { if(&full[0] == p) { p[1] = 0; } else { *p = 0; } } } else if(path[0] == '/') { std::strcpy(full, path); } else { uint32_t len = strlen(full); if(len > 0 && full[len - 1] != '/') { std::strcat(full, "/"); } std::strcat(full, path); } } // FATFS で認識できるパス(文字コード)へ変換 void create_fatfs_path_(const char* path, char* full) const noexcept { #if _USE_LFN != 0 char tmp[_MAX_LFN + 1]; create_full_path_(path, tmp); str::utf8_to_sjis(tmp, full); #else create_full_path_(path, full); #endif } // パス中のディレクトリーが無かったら生成 bool build_dir_path_(const char* path) const noexcept { char tmp[_MAX_LFN + 1]; std::strcpy(tmp, path); char* p = tmp; if(p[0] == '/') ++p; while(p[0] != 0) { p = std::strchr(p, '/'); if(p == nullptr) break; p[0] = 0; #if _USE_LFN != 0 char sjis[_MAX_LFN + 1]; str::utf8_to_sjis(tmp, sjis); auto ret = f_mkdir(sjis); #else auto ret = f_mkdir(tmp); #endif if(ret == FR_OK) ; else if(ret == FR_EXIST) ; else { return false; } p[0] = '/'; ++p; } return true; } public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// sdc_man() noexcept : current_{ 0 }, cdet_(false), mount_(false), mount_delay_(0), dir_list_(), dir_list_limit_(10), dir_func_(nullptr), dir_todir_(false), dir_option_(nullptr) { } //-----------------------------------------------------------------// /*! @brief 開始(初期化) */ //-----------------------------------------------------------------// void start() noexcept { mount_ = false; strcpy(current_, "/"); memset(&fatfs_, 0, sizeof(FATFS)); } //-----------------------------------------------------------------// /*! @brief ファイルの存在を検査 @param[in] path ファイル名 @return ファイルがある場合「true」 */ //-----------------------------------------------------------------// bool probe(const char* path) const { if(!mount_) return false; FIL fp; bool ret = open(&fp, path, FA_READ | FA_OPEN_EXISTING); if(ret) { if(f_close(&fp) != FR_OK) { return false; } } return ret; } //-----------------------------------------------------------------// /*! @brief パス中のディレクトリーを生成 @param[in] path ファイル名 @return 成功なら「true」 */ //-----------------------------------------------------------------// bool build_dir_path(const char* path) noexcept { if(!mount_) return false; if(path == nullptr) return false; char full[_MAX_LFN + 1]; create_full_path_(path, full); if(!build_dir_path_(full)) { return false; } return true; } //-----------------------------------------------------------------// /*! @brief カレント・ファイルのオープン @param[in] fp ファイル構造体ポインター @param[in] path ファイル名 @param[in] mode オープン・モード @return 成功なら「true」 */ //-----------------------------------------------------------------// bool open(FIL* fp, const char* path, BYTE mode) const noexcept { if(!mount_) return false; if(fp == nullptr || path == nullptr) return false; char full[_MAX_LFN + 1]; create_fatfs_path_(path, full); if(f_open(fp, full, mode) != FR_OK) { return false; } return true; } //-----------------------------------------------------------------// /*! @brief クローズ @param[in] fp ファイル構造体ポインター @return 成功なら「true」 */ //-----------------------------------------------------------------// bool close(FIL* fp) const { if(!mount_) return false; if(fp == nullptr) return false; return f_close(fp) == FR_OK; } //-----------------------------------------------------------------// /*! @brief ファイル・サイズを返す @n ※アクセス出来ない場合も「0」を返すので、存在確認に使えない @param[in] path ファイル名 @return ファイル・サイズ */ //-----------------------------------------------------------------// uint32_t size(const char* path) const { if(!mount_) return false; if(path == nullptr) return false; char full[_MAX_LFN + 1]; create_fatfs_path_(path, full); FILINFO fno; if(f_stat(full, &fno) != FR_OK) { return 0; } return fno.fsize; } //-----------------------------------------------------------------// /*! @brief ファイルの更新時間を取得 @param[in] path ファイル名 @return ファイルの更新時間(0の場合エラー) */ //-----------------------------------------------------------------// time_t get_time(const char* path) const { if(!mount_) return 0; if(path == nullptr) return 0; char full[_MAX_LFN + 1]; create_fatfs_path_(path, full); FILINFO fno; if(f_stat(full, &fno) != FR_OK) { return 0; } return str::fatfs_time_to(fno.fdate, fno.ftime); } //-----------------------------------------------------------------// /*! @brief ファイルの削除 @param[in] path 相対パス、又は、絶対パス @return 削除成功なら「true」 */ //-----------------------------------------------------------------// bool remove(const char* path) { if(!mount_) return false; if(path == nullptr) return false; char full[_MAX_LFN + 1]; create_fatfs_path_(path, full); return f_unlink(full) == FR_OK; } //-----------------------------------------------------------------// /*! @brief ファイル名の変更 @param[in] org_path 元名 @param[in] new_path 新名 @return 成功なら「true」 */ //-----------------------------------------------------------------// bool rename(const char* org_path, const char* new_path) { if(!mount_) return false; if(org_path == nullptr || new_path == nullptr) return false; char org_full[_MAX_LFN + 1]; create_fatfs_path_(org_path, org_full); char new_full[_MAX_LFN + 1]; create_fatfs_path_(new_path, new_full); return f_rename(org_full, new_full) == FR_OK; } //-----------------------------------------------------------------// /*! @brief ディレクトリーの作成 @param[in] path 相対パス、又は、絶対パス @return 成功なら「true」 */ //-----------------------------------------------------------------// bool mkdir(const char* path) { if(!mount_) return false; if(path == nullptr) return false; char full[_MAX_LFN + 1]; create_fatfs_path_(path, full); return f_mkdir(full) == FR_OK; } //-----------------------------------------------------------------// /*! @brief ディスク空き容量の取得 @param[in] fspc フリー・スペース(単位Kバイト) @param[in] capa 最大容量(単位Kバイト) @return 成功なら「true」 */ //-----------------------------------------------------------------// bool get_disk_space(uint32_t& fspc, uint32_t& capa) const { if(!get_mount()) return false; FATFS* fs; DWORD nclst = 0; if(f_getfree("", &nclst, &fs) == FR_OK) { // 全セクタ数と空きセクタ数を計算(512バイトセクタ) capa = (fs->n_fatent - 2) * fs->csize / 2; fspc = nclst * fs->csize / 2; return true; } else { return false; } } //-----------------------------------------------------------------// /*! @brief カレント・パスの移動 @param[in] path 相対パス、又は、絶対パス @return 移動成功なら「true」 */ //-----------------------------------------------------------------// bool cd(const char* path) { if(!mount_) return false; if(path == nullptr) return false; char full[_MAX_LFN + 1]; create_full_path_(path, full); #if _USE_LFN != 0 char oem[_MAX_LFN + 1]; str::utf8_to_sjis(full, oem); DIR dir; auto st = f_opendir(&dir, oem); #else DIR dir; auto st = f_opendir(&dir, full); #endif if(st != FR_OK) { format("Can't open dir(%d): '%s'\n") % static_cast<uint32_t>(st) % full; return false; } std::strcpy(current_, full); f_closedir(&dir); return true; } //-----------------------------------------------------------------// /*! @brief ディレクトリー・リストのフレーム単位での最大数を設定 @param[in] limit フレーム毎の最大数 */ //-----------------------------------------------------------------// void set_dir_list_limit(uint32_t limit) { dir_list_limit_ = limit; } //-----------------------------------------------------------------// /*! @brief ディレクトリー・リストの状態を取得 @param[in] num リスト数 @return ディレクトリー・リスト処理中なら「true」 */ //-----------------------------------------------------------------// bool probe_dir_list(uint32_t& num) const { num = dir_list_.get_total(); return dir_list_.probe(); } //-----------------------------------------------------------------// /*! @brief SD カードのディレクトリーリストでタスクを実行する @param[in] root ルート・パス @param[in] func 実行関数 @param[in] todir 「true」の場合、ディレクトリーも関数を呼ぶ @param[in] option オプション・ポインター @return 成功なら「true」 */ //-----------------------------------------------------------------// bool start_dir_list(const char* root, dir_loop_func func = nullptr, bool todir = false, void* option = nullptr) { dir_func_ = func; dir_todir_ = todir; dir_option_ = option; char full[256]; create_full_path_(root, full); #if _USE_LFN != 0 str::utf8_to_sjis(full, full); #endif return dir_list_.start(full); } //-----------------------------------------------------------------// /*! @brief SD カードのディレクトリから、ファイル名の取得 @param[in] root ルート・パス @param[in] match 所得パスのインデックス @param[out] path パスのコピー先 @return 成功なら「true」 */ //-----------------------------------------------------------------// bool get_dir_path(const char* root, uint16_t match, char* path) { #if 0 copy_t t; t.idx_ = 0; t.match_ = match; t.path_ = path; dir_loop(root, path_copy_func_, true, &t); #endif return true; } //-----------------------------------------------------------------// /*! @brief SD カードのディレクトリーをリストする @param[in] root ルート・パス @return ファイル数 */ //-----------------------------------------------------------------// uint32_t dir(const char* root) noexcept { dir_list dl; char full[256]; create_full_path_(root, full); #if _USE_LFN != 0 str::utf8_to_sjis(full, full); #endif if(!dl.start(full)) return 0; do { dl.service(10, dir_list_func_, true); } while(dl.probe()) ; auto n = dl.get_total(); utils::format("Total %d file%s\n") % n % (n > 1 ? "s" : ""); return n; } //-----------------------------------------------------------------// /*! @brief ファイル名候補の取得 @param[in] name 候補のキー @param[in] no 候補の順番 @param[out] dst 候補の格納先 @return 候補の数 */ //-----------------------------------------------------------------// uint8_t match(const char* key, uint8_t no, char* dst) noexcept { match_t t; t.key_ = key; t.dst_ = dst; t.cnt_ = 0; t.no_ = no; /// dir_loop(current_, match_func_, false, &t); return t.cnt_; } //-----------------------------------------------------------------// /*! @brief SD カードアクセス・サービス(毎フレーム呼ぶ) @param[in] cdet SD カード検出時「true」 @return マウントしている場合「true」 */ //-----------------------------------------------------------------// bool service(bool cdet) noexcept { if(cdet_ != cdet) { if(!cdet_ && cdet) { // Detect CARD // POWER::P = 0; mount_delay_ = 30; // マウント初期化を呼ぶ遅延 } cdet_ = cdet; } if(mount_delay_) { --mount_delay_; if(mount_delay_ == 0) { auto st = f_mount(&fatfs_, "", 1); if(st != FR_OK) { format("f_mount NG: %d\n") % static_cast<uint32_t>(st); // spi_.destroy(); // POWER::P = 1; // SELECT::P = 0; mount_ = false; } else { strcpy(current_, "/"); mount_ = true; } } } if(mount_) { dir_list_.service(dir_list_limit_, dir_func_, dir_todir_, dir_option_); } return mount_; } //-----------------------------------------------------------------// /*! @brief フル・パスを生成 @param[in] name ファイル名 @param[out] dst 生成先(オーバーランに注意) */ //-----------------------------------------------------------------// void make_full_path(const char* name, char* dst) const noexcept { if(name == nullptr || dst == nullptr) return; if(name[0] == '/') { std::strcpy(dst, name); return; } std::strcpy(dst, current_); auto len = std::strlen(dst); if(len > 0 && dst[len - 1] != '/') { std::strcat(dst, "/"); } std::strcat(dst, name); } //-----------------------------------------------------------------// /*! @brief カレント・パスを取得 @return カレント。パス */ //-----------------------------------------------------------------// const char* get_current() const noexcept { return current_; } //-----------------------------------------------------------------// /*! @brief カードのマウント状態を取得 @return 「true」ならマウント状態 */ //-----------------------------------------------------------------// bool get_mount() const noexcept { return mount_; } }; } <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief RL78/G13 グループ SAU/UART 制御 @n Copyright 2016 Kunihito Hiramatsu @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include "G13/system.hpp" #include "G13/sau.hpp" #include "G13/intr.hpp" #include "common/fifo.hpp" /// F_CLK はボーレートパラメーター計算で必要、設定が無いとエラーにします。 #ifndef F_CLK # error "uart_io.hpp requires F_CLK to be defined" #endif namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief UART 制御クラス・テンプレート @param[in] SAUtx シリアル・アレイ・ユニット送信・クラス(偶数チャネル) @param[in] SAUrx シリアル・アレイ・ユニット受信・クラス(奇数チャネル) @param[in] send_size 送信バッファサイズ @param[in] recv_size 受信バッファサイズ */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class SAUtx, class SAUrx, uint16_t send_size, uint16_t recv_size> class uart_io { static SAUtx tx_; ///< 送信リソース static SAUrx rx_; ///< 受信リソース static utils::fifo<send_size> send_; static utils::fifo<recv_size> recv_; static volatile bool send_stall_; uint8_t intr_level_ = 0; bool crlf_ = true; // ※必要なら、実装する void sleep_() { asm("nop"); } void send_restart_() { if(send_stall_ && send_.length() > 0) { while(tx_.SSR.TSF() != 0) sleep_(); char ch = send_.get(); send_stall_ = false; tx_.SDR_L = ch; send_intrrupt_mask_(false); } } void putch_(char ch) { if(intr_level_) { /// 7/8 を超えてた場合は、バッファが空になるまで待つ。 if(send_.length() >= (send_.size() * 7 / 8)) { send_restart_(); while(send_.length() != 0) sleep_(); } send_.put(ch); send_restart_(); } else { while(tx_.SSR.TSF() != 0) sleep_(); tx_.SDR_L = ch; } } public: // 送信完了割り込み設定 static inline void send_intrrupt_mask_(bool f) { if(tx_.get_unit_no() == 0) { if(tx_.get_chanel_no() == 0) { // UART0 intr::MK0H.STMK0 = f; } else { // UART1 intr::MK1L.STMK1 = f; } } else { if(tx_.get_chanel_no() == 0) { // UART2 intr::MK0H.STMK2 = f; } else { // UART3 intr::MK1H.STMK3 = f; } } } // 受信割り込みマスク設定 static inline void recv_interrupt_mask_(bool f) { if(rx_.get_unit_no() == 0) { if(rx_.get_chanel_no() == 1) { // UART0 intr::MK0H.SRMK0 = f; } else { // UART1 intr::MK1L.SRMK1 = f; } } else { if(rx_.get_chanel_no() == 1) { // UART2 intr::MK0H.SRMK2 = f; } else { //UART3 intr::MK1H.SRMK3 = f; } } } static __attribute__ ((interrupt)) void send_task() { if(send_.length()) { tx_.SDR_L = send_.get(); } else { send_intrrupt_mask_(true); send_stall_ = true; } } static __attribute__ ((interrupt)) void recv_task() { recv_.put(rx_.SDR_L()); } static __attribute__ ((interrupt)) void error_task() { } //-----------------------------------------------------------------// /*! @brief ボーレートを設定して、UART を有効にする @param[in] baud ボーレート @param[in] level 割り込みレベル(1~2)、0の場合はポーリング @return エラーなら「false」 */ //-----------------------------------------------------------------// bool start(uint32_t baud, bool level = 0) { intr_level_ = level; // ボーレートから分周比の算出 auto div = static_cast<uint32_t>(F_CLK) / baud; uint8_t master = 0; while(div > 256) { div /= 2; ++master; if(master >= 16) { /// ボーレート設定範囲外 return false; } } --div; div &= 0xfe; if(div <= 2) { /// ボーレート設定範囲外 return false; } // 対応するユニットを有効にする if(tx_.get_unit_no() == 0) { PER0.SAU0EN = 1; } else { PER0.SAU1EN = 1; } // チャネル0、1で共有の為、どちらか片方のみの設定 bool cks = false; if(tx_.get_chanel_no() == 0) { tx_.SPS = SAUtx::SPS.PRS0.b(master); } else { tx_.SPS = SAUtx::SPS.PRS1.b(master); cks = true; } tx_.SMR = 0x0020 | SAUtx::SMR.CKS.b(cks) | SAUtx::SMR.MD.b(1) | SAUtx::SMR.MD0.b(1); rx_.SMR = 0x0020 | SAUtx::SMR.CKS.b(cks) | SAUrx::SMR.STS.b(1) | SAUrx::SMR.MD.b(1); // 8 date, 1 stop, no-parity LSB-first // 送信設定 tx_.SCR = 0x0004 | SAUtx::SCR.TXE.b(1) | SAUtx::SCR.SLC.b(1) | SAUtx::SCR.DLS.b(3) | SAUtx::SCR.DIR.b(1); // 受信設定 rx_.SCR = 0x0004 | SAUrx::SCR.RXE.b(1) | SAUrx::SCR.SLC.b(1) | SAUrx::SCR.DLS.b(3) | SAUrx::SCR.DIR.b(1); // ボーレート・ジェネレーター設定 tx_.SDR = div << 8; rx_.SDR = div << 8; tx_.SOL = 0; // TxD tx_.SO = 1; // シリアル出力設定 tx_.SOE = 1; // シリアル出力許可(Txd) // 対応するポートの設定 if(tx_.get_unit_no() == 0) { if(tx_.get_chanel_no() == 0) { // UART0 PM1.B1 = 1; // P1-1 input (RxD0) PM1.B2 = 0; // P1-2 output (TxD0) P1.B2 = 1; // ポートレジスター TxD 切り替え } else { // UART1 PM1.B4 = 1; // P1-1 input (RxD0) PM1.B3 = 0; // P1-2 output (TxD0) P1.B3 = 1; // ポートレジスター TxD 切り替え } } else { if(tx_.get_chanel_no() == 0) { // UART2 PM0.B3 = 1; // P1-3 input (RxD2) PM0.B2 = 0; // P1-2 output (TxD2) PMC0.B2 = 0; // ポートモードコントロール P0.B2 = 1; // ポートレジスター TxD 切り替え } else { // UART3(128ピンデバイスでサポート) PM14.B3 = 1; // P14-3 input (RxD3) PM14.B4 = 0; // P14-4 output (TxD3) P14.B4 = 1; // ポートレジスター TxD 切り替え } } send_stall_ = true; tx_.SS = 1; /// TxD enable rx_.SS = 1; /// RxD enable // マスクをクリアして、割り込み許可 if(intr_level_ > 0) { recv_interrupt_mask_(0); } return true; } //-----------------------------------------------------------------// /*! @brief CRLF 自動送出 @param[in] f 「false」なら無効 */ //-----------------------------------------------------------------// void auto_crlf(bool f = true) { crlf_ = f; } //-----------------------------------------------------------------// /*! @brief 送信バッファのサイズを返す @return バッファのサイズ */ //-----------------------------------------------------------------// uint16_t send_length() const { if(intr_level_) { return send_.length(); } else { return tx_.SSR.TSF(); } } //-----------------------------------------------------------------// /*! @brief 受信バッファのサイズを返す @n ※ポーリング時、データが無い:0、データがある:1 @return バッファのサイズ */ //-----------------------------------------------------------------// uint16_t recv_length() const { if(intr_level_) { return recv_.length(); } else { return rx_.SSR.BFF(); } } //-----------------------------------------------------------------// /*! @brief 文字出力 @param[in] ch 文字コード */ //-----------------------------------------------------------------// void putch(char ch) { if(crlf_ && ch == '\n') { putch_('\r'); } putch_(ch); } //-----------------------------------------------------------------// /*! @brief 文字入力 @return 文字コード */ //-----------------------------------------------------------------// char getch() { if(intr_level_) { while(recv_.length() == 0) sleep_(); return recv_.get(); } else { while(rx_.SSR.BFF() == 0) sleep_(); return rx_.SDR_L(); } } //-----------------------------------------------------------------// /*! @brief 文字列出力 @param[in] s 出力ストリング */ //-----------------------------------------------------------------// void puts(const char* s) { char ch; while((ch = *s) != 0) { putch(ch); ++s; } } }; // send_、recv_, send_stall_ の実体を定義 template<class SAUtx, class SAUrx, uint16_t send_size, uint16_t recv_size> utils::fifo<send_size> uart_io<SAUtx, SAUrx, send_size, recv_size>::send_; template<class SAUtx, class SAUrx, uint16_t send_size, uint16_t recv_size> utils::fifo<recv_size> uart_io<SAUtx, SAUrx, send_size, recv_size>::recv_; template<class SAUtx, class SAUrx, uint16_t send_size, uint16_t recv_size> volatile bool uart_io<SAUtx, SAUrx, send_size, recv_size>::send_stall_ = true; } <commit_msg>change section for interrupt function<commit_after>#pragma once //=====================================================================// /*! @file @brief RL78/G13 グループ SAU/UART 制御 @n Copyright 2016 Kunihito Hiramatsu @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include "G13/system.hpp" #include "G13/sau.hpp" #include "G13/intr.hpp" #include "common/fifo.hpp" /// F_CLK はボーレートパラメーター計算で必要、設定が無いとエラーにします。 #ifndef F_CLK # error "uart_io.hpp requires F_CLK to be defined" #endif namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief UART 制御クラス・テンプレート @param[in] SAUtx シリアル・アレイ・ユニット送信・クラス(偶数チャネル) @param[in] SAUrx シリアル・アレイ・ユニット受信・クラス(奇数チャネル) @param[in] send_size 送信バッファサイズ @param[in] recv_size 受信バッファサイズ */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class SAUtx, class SAUrx, uint16_t send_size, uint16_t recv_size> class uart_io { static SAUtx tx_; ///< 送信リソース static SAUrx rx_; ///< 受信リソース static utils::fifo<send_size> send_; static utils::fifo<recv_size> recv_; static volatile bool send_stall_; uint8_t intr_level_ = 0; bool crlf_ = true; // ※必要なら、実装する void sleep_() { asm("nop"); } void send_restart_() { if(send_stall_ && send_.length() > 0) { while(tx_.SSR.TSF() != 0) sleep_(); char ch = send_.get(); send_stall_ = false; tx_.SDR_L = ch; send_intrrupt_mask_(false); } } void putch_(char ch) { if(intr_level_) { /// 7/8 を超えてた場合は、バッファが空になるまで待つ。 if(send_.length() >= (send_.size() * 7 / 8)) { send_restart_(); while(send_.length() != 0) sleep_(); } send_.put(ch); send_restart_(); } else { while(tx_.SSR.TSF() != 0) sleep_(); tx_.SDR_L = ch; } } public: // 送信完了割り込み設定 static inline void send_intrrupt_mask_(bool f) { if(tx_.get_unit_no() == 0) { if(tx_.get_chanel_no() == 0) { // UART0 intr::MK0H.STMK0 = f; } else { // UART1 intr::MK1L.STMK1 = f; } } else { if(tx_.get_chanel_no() == 0) { // UART2 intr::MK0H.STMK2 = f; } else { // UART3 intr::MK1H.STMK3 = f; } } } // 受信割り込みマスク設定 static inline void recv_interrupt_mask_(bool f) { if(rx_.get_unit_no() == 0) { if(rx_.get_chanel_no() == 1) { // UART0 intr::MK0H.SRMK0 = f; } else { // UART1 intr::MK1L.SRMK1 = f; } } else { if(rx_.get_chanel_no() == 1) { // UART2 intr::MK0H.SRMK2 = f; } else { //UART3 intr::MK1H.SRMK3 = f; } } } static __attribute__ ((interrupt)) void send_task() __attribute__ ((section (".lowtext"))) { if(send_.length()) { tx_.SDR_L = send_.get(); } else { send_intrrupt_mask_(true); send_stall_ = true; } } static __attribute__ ((interrupt)) void recv_task() __attribute__ ((section (".lowtext"))) { recv_.put(rx_.SDR_L()); } static __attribute__ ((interrupt)) void error_task() { } //-----------------------------------------------------------------// /*! @brief ボーレートを設定して、UART を有効にする @param[in] baud ボーレート @param[in] level 割り込みレベル(1~2)、0の場合はポーリング @return エラーなら「false」 */ //-----------------------------------------------------------------// bool start(uint32_t baud, bool level = 0) { intr_level_ = level; // ボーレートから分周比の算出 auto div = static_cast<uint32_t>(F_CLK) / baud; uint8_t master = 0; while(div > 256) { div /= 2; ++master; if(master >= 16) { /// ボーレート設定範囲外 return false; } } --div; div &= 0xfe; if(div <= 2) { /// ボーレート設定範囲外 return false; } // 対応するユニットを有効にする if(tx_.get_unit_no() == 0) { PER0.SAU0EN = 1; } else { PER0.SAU1EN = 1; } // チャネル0、1で共有の為、どちらか片方のみの設定 bool cks = false; if(tx_.get_chanel_no() == 0) { tx_.SPS = SAUtx::SPS.PRS0.b(master); } else { tx_.SPS = SAUtx::SPS.PRS1.b(master); cks = true; } tx_.SMR = 0x0020 | SAUtx::SMR.CKS.b(cks) | SAUtx::SMR.MD.b(1) | SAUtx::SMR.MD0.b(1); rx_.SMR = 0x0020 | SAUtx::SMR.CKS.b(cks) | SAUrx::SMR.STS.b(1) | SAUrx::SMR.MD.b(1); // 8 date, 1 stop, no-parity LSB-first // 送信設定 tx_.SCR = 0x0004 | SAUtx::SCR.TXE.b(1) | SAUtx::SCR.SLC.b(1) | SAUtx::SCR.DLS.b(3) | SAUtx::SCR.DIR.b(1); // 受信設定 rx_.SCR = 0x0004 | SAUrx::SCR.RXE.b(1) | SAUrx::SCR.SLC.b(1) | SAUrx::SCR.DLS.b(3) | SAUrx::SCR.DIR.b(1); // ボーレート・ジェネレーター設定 tx_.SDR = div << 8; rx_.SDR = div << 8; tx_.SOL = 0; // TxD tx_.SO = 1; // シリアル出力設定 tx_.SOE = 1; // シリアル出力許可(Txd) // 対応するポートの設定 if(tx_.get_unit_no() == 0) { if(tx_.get_chanel_no() == 0) { // UART0 PM1.B1 = 1; // P1-1 input (RxD0) PM1.B2 = 0; // P1-2 output (TxD0) P1.B2 = 1; // ポートレジスター TxD 切り替え } else { // UART1 PM1.B4 = 1; // P1-1 input (RxD0) PM1.B3 = 0; // P1-2 output (TxD0) P1.B3 = 1; // ポートレジスター TxD 切り替え } } else { if(tx_.get_chanel_no() == 0) { // UART2 PM0.B3 = 1; // P1-3 input (RxD2) PM0.B2 = 0; // P1-2 output (TxD2) PMC0.B2 = 0; // ポートモードコントロール P0.B2 = 1; // ポートレジスター TxD 切り替え } else { // UART3(128ピンデバイスでサポート) PM14.B3 = 1; // P14-3 input (RxD3) PM14.B4 = 0; // P14-4 output (TxD3) P14.B4 = 1; // ポートレジスター TxD 切り替え } } send_stall_ = true; tx_.SS = 1; /// TxD enable rx_.SS = 1; /// RxD enable // マスクをクリアして、割り込み許可 if(intr_level_ > 0) { recv_interrupt_mask_(0); } return true; } //-----------------------------------------------------------------// /*! @brief CRLF 自動送出 @param[in] f 「false」なら無効 */ //-----------------------------------------------------------------// void auto_crlf(bool f = true) { crlf_ = f; } //-----------------------------------------------------------------// /*! @brief 送信バッファのサイズを返す @return バッファのサイズ */ //-----------------------------------------------------------------// uint16_t send_length() const { if(intr_level_) { return send_.length(); } else { return tx_.SSR.TSF(); } } //-----------------------------------------------------------------// /*! @brief 受信バッファのサイズを返す @n ※ポーリング時、データが無い:0、データがある:1 @return バッファのサイズ */ //-----------------------------------------------------------------// uint16_t recv_length() const { if(intr_level_) { return recv_.length(); } else { return rx_.SSR.BFF(); } } //-----------------------------------------------------------------// /*! @brief 文字出力 @param[in] ch 文字コード */ //-----------------------------------------------------------------// void putch(char ch) { if(crlf_ && ch == '\n') { putch_('\r'); } putch_(ch); } //-----------------------------------------------------------------// /*! @brief 文字入力 @return 文字コード */ //-----------------------------------------------------------------// char getch() { if(intr_level_) { while(recv_.length() == 0) sleep_(); return recv_.get(); } else { while(rx_.SSR.BFF() == 0) sleep_(); return rx_.SDR_L(); } } //-----------------------------------------------------------------// /*! @brief 文字列出力 @param[in] s 出力ストリング */ //-----------------------------------------------------------------// void puts(const char* s) { char ch; while((ch = *s) != 0) { putch(ch); ++s; } } }; // send_、recv_, send_stall_ の実体を定義 template<class SAUtx, class SAUrx, uint16_t send_size, uint16_t recv_size> utils::fifo<send_size> uart_io<SAUtx, SAUrx, send_size, recv_size>::send_; template<class SAUtx, class SAUrx, uint16_t send_size, uint16_t recv_size> utils::fifo<recv_size> uart_io<SAUtx, SAUrx, send_size, recv_size>::recv_; template<class SAUtx, class SAUrx, uint16_t send_size, uint16_t recv_size> volatile bool uart_io<SAUtx, SAUrx, send_size, recv_size>::send_stall_ = true; } <|endoftext|>
<commit_before>#include <v8.h> #include <node.h> #include <tcl.h> using namespace node; using namespace v8; class NodeTcl : ObjectWrap { private: Tcl_Interp *m_interp; public: static Persistent<FunctionTemplate> s_ct; static void Init(Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); s_ct = Persistent<FunctionTemplate>::New(t); s_ct->InstanceTemplate()->SetInternalFieldCount(1); s_ct->SetClassName(String::NewSymbol("NodeTcl")); NODE_SET_PROTOTYPE_METHOD(s_ct, "eval", Eval); NODE_SET_PROTOTYPE_METHOD(s_ct, "proc", Proc); NODE_SET_PROTOTYPE_METHOD(s_ct, "process_events", Event); target->Set(String::NewSymbol("NodeTcl"), s_ct->GetFunction()); } NodeTcl() { m_interp = Tcl_CreateInterp(); } ~NodeTcl() { Tcl_DeleteInterp(m_interp); m_interp = NULL; } /* * new NodeTcl() -- allocate and return a new interpreter. */ static Handle<Value> New(const Arguments& args) { HandleScope scope; NodeTcl* hw = new NodeTcl(); if (Tcl_Init(hw->m_interp) == TCL_ERROR) { Local<String> err = String::New(Tcl_GetStringResult(hw->m_interp)); delete hw; return ThrowException(Exception::Error(err)); } hw->Wrap(args.This()); return args.This(); } /* * eval(String) -- execute some Tcl code and return the result. */ static Handle<Value> Eval(const Arguments& args) { HandleScope scope; if (args.Length() != 1 || !args[0]->IsString()) { return ThrowException(Exception::TypeError(String::New("Argument must be a string"))); } Local<String> script = Local<String>::Cast(args[0]); NodeTcl* hw = ObjectWrap::Unwrap<NodeTcl>(args.This()); int cc = Tcl_Eval(hw->m_interp, (const char*)*String::Utf8Value(script)); if (cc != TCL_OK) { Tcl_Obj *obj = Tcl_GetObjResult(hw->m_interp); return ThrowException(Exception::Error(String::New(Tcl_GetString(obj)))); } Tcl_Obj *obj = Tcl_GetObjResult(hw->m_interp); Local<String> result = String::New(Tcl_GetString(obj)); return scope.Close(result); } /* * Data about a JavaScript function that can be executed. */ struct callback_data_t { NodeTcl *hw; Tcl_Command cmd; Persistent<Function> jsfunc; }; /* * Called by Tcl when it wants to invoke a JavaScript function. */ static int CallbackTrampoline (ClientData clientData, Tcl_Interp *interp, int tclArgc, const char *tclArgv[]) { callback_data_t *cbdata = static_cast<callback_data_t*>(clientData); // Convert all of the arguments, but skip the 0th element (the procname). Local<Value> jsArgv[tclArgc - 1]; for (int i = 1; i < tclArgc; i++) { jsArgv[i - 1] = String::New(tclArgv[i]); } // Execute the JavaScript method. TryCatch try_catch; Local<Value> result = cbdata->jsfunc->Call(Context::GetCurrent()->Global(), tclArgc - 1, jsArgv); // If a JavaScript exception occurred, send back a Tcl error. if (try_catch.HasCaught()) { Local<Message> msg = try_catch.Message(); Tcl_SetObjResult(interp, Tcl_NewStringObj((const char*)*String::Utf8Value(msg->Get()), -1)); return TCL_ERROR; } // Pass back to Tcl the returned value as a string. Tcl_SetObjResult(interp, Tcl_NewStringObj((const char*)*String::Utf8Value(result->ToString()), -1)); return TCL_OK; } /* * proc(String, Function) -- define a proc within the Tcl namespace that executes a JavaScript function callback. */ static Handle<Value> Proc(const Arguments& args) { HandleScope scope; if (args.Length() != 2) { return ThrowException(Exception::TypeError(String::New("Expecting 2 arguments (String, Function)"))); } if (!args[0]->IsString()) { return ThrowException(Exception::TypeError(String::New("Argument 1 must be a string"))); } Local<String> cmdName = Local<String>::Cast(args[0]); if (!args[1]->IsFunction()) { return ThrowException(Exception::TypeError(String::New("Argument 2 must be a function"))); } Local<Function> jsfunc = Local<Function>::Cast(args[1]); NodeTcl* hw = ObjectWrap::Unwrap<NodeTcl>(args.This()); callback_data_t *cbdata = new callback_data_t(); cbdata->hw = hw; cbdata->jsfunc = Persistent<Function>::New(jsfunc); cbdata->cmd = Tcl_CreateCommand(hw->m_interp, (const char*)*String::Utf8Value(cmdName), CallbackTrampoline, (ClientData) cbdata, NULL); hw->Ref(); return Undefined(); } /* * event(Boolean) -- handle one or all pending Tcl events if boolean is present and true */ static Handle<Value> Event(const Arguments& args) { HandleScope scope; int eventStatus; int doMultiple; if (args.Length() > 1 || (args.Length() == 1 && !args[0]->IsBoolean())) { return ThrowException(Exception::TypeError(String::New("Optional argument, if present, must be a boolean"))); } if (args.Length() == 0) { doMultiple = 1; } else { doMultiple = args[0]->ToBoolean()->Value(); } do { eventStatus = Tcl_DoOneEvent (TCL_ALL_EVENTS | TCL_DONT_WAIT); } while (doMultiple && eventStatus); Local<Integer> result = Integer::New(eventStatus); return scope.Close(result); } }; Persistent<FunctionTemplate> NodeTcl::s_ct; extern "C" { static void init (Handle<Object> target) { NodeTcl::Init(target); } NODE_MODULE(nodetcl, init); } <commit_msg>install a command deletion handler to avoid leaking memory when the interp is freed.<commit_after>#include <v8.h> #include <node.h> #include <tcl.h> using namespace node; using namespace v8; class NodeTcl : ObjectWrap { private: Tcl_Interp *m_interp; public: static Persistent<FunctionTemplate> s_ct; static void Init(Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); s_ct = Persistent<FunctionTemplate>::New(t); s_ct->InstanceTemplate()->SetInternalFieldCount(1); s_ct->SetClassName(String::NewSymbol("NodeTcl")); NODE_SET_PROTOTYPE_METHOD(s_ct, "eval", Eval); NODE_SET_PROTOTYPE_METHOD(s_ct, "proc", Proc); NODE_SET_PROTOTYPE_METHOD(s_ct, "process_events", Event); target->Set(String::NewSymbol("NodeTcl"), s_ct->GetFunction()); } NodeTcl() { m_interp = Tcl_CreateInterp(); } ~NodeTcl() { Tcl_DeleteInterp(m_interp); m_interp = NULL; } // ---------------------------------------------------- /* * new NodeTcl() -- allocate and return a new interpreter. */ static Handle<Value> New(const Arguments& args) { HandleScope scope; NodeTcl* hw = new NodeTcl(); if (Tcl_Init(hw->m_interp) == TCL_ERROR) { Local<String> err = String::New(Tcl_GetStringResult(hw->m_interp)); delete hw; return ThrowException(Exception::Error(err)); } hw->Wrap(args.This()); return args.This(); } // ---------------------------------------------------- /* * eval(String) -- execute some Tcl code and return the result. */ static Handle<Value> Eval(const Arguments& args) { HandleScope scope; if (args.Length() != 1 || !args[0]->IsString()) { return ThrowException(Exception::TypeError(String::New("Argument must be a string"))); } Local<String> script = Local<String>::Cast(args[0]); NodeTcl* hw = ObjectWrap::Unwrap<NodeTcl>(args.This()); int cc = Tcl_Eval(hw->m_interp, (const char*)*String::Utf8Value(script)); if (cc != TCL_OK) { Tcl_Obj *obj = Tcl_GetObjResult(hw->m_interp); return ThrowException(Exception::Error(String::New(Tcl_GetString(obj)))); } Tcl_Obj *obj = Tcl_GetObjResult(hw->m_interp); Local<String> result = String::New(Tcl_GetString(obj)); return scope.Close(result); } // ---------------------------------------------------- /* * Data about a JavaScript function that can be executed. */ struct callback_data_t { NodeTcl *hw; Tcl_Command cmd; Persistent<Function> jsfunc; }; /* * Called by Tcl when it wants to invoke a JavaScript function. */ static int CallbackTrampoline (ClientData clientData, Tcl_Interp *interp, int tclArgc, const char *tclArgv[]) { callback_data_t *cbdata = static_cast<callback_data_t*>(clientData); // Convert all of the arguments, but skip the 0th element (the procname). Local<Value> jsArgv[tclArgc - 1]; for (int i = 1; i < tclArgc; i++) { jsArgv[i - 1] = String::New(tclArgv[i]); } // Execute the JavaScript method. TryCatch try_catch; Local<Value> result = cbdata->jsfunc->Call(Context::GetCurrent()->Global(), tclArgc - 1, jsArgv); // If a JavaScript exception occurred, send back a Tcl error. if (try_catch.HasCaught()) { Local<Message> msg = try_catch.Message(); Tcl_SetObjResult(interp, Tcl_NewStringObj((const char*)*String::Utf8Value(msg->Get()), -1)); return TCL_ERROR; } // Pass back to Tcl the returned value as a string. Tcl_SetObjResult(interp, Tcl_NewStringObj((const char*)*String::Utf8Value(result->ToString()), -1)); return TCL_OK; } /* * Called by Tcl when it wants to delete the proc. */ static void CallbackDelete (ClientData clientData) { callback_data_t *cbdata = static_cast<callback_data_t*>(clientData); cbdata->jsfunc.Dispose(); cbdata->hw->Unref(); delete cbdata; } /* * proc(String, Function) -- define a proc within the Tcl namespace that executes a JavaScript function callback. */ static Handle<Value> Proc(const Arguments& args) { HandleScope scope; if (args.Length() != 2) { return ThrowException(Exception::TypeError(String::New("Expecting 2 arguments (String, Function)"))); } if (!args[0]->IsString()) { return ThrowException(Exception::TypeError(String::New("Argument 1 must be a string"))); } Local<String> cmdName = Local<String>::Cast(args[0]); if (!args[1]->IsFunction()) { return ThrowException(Exception::TypeError(String::New("Argument 2 must be a function"))); } Local<Function> jsfunc = Local<Function>::Cast(args[1]); NodeTcl* hw = ObjectWrap::Unwrap<NodeTcl>(args.This()); callback_data_t *cbdata = new callback_data_t(); cbdata->hw = hw; cbdata->jsfunc = Persistent<Function>::New(jsfunc); cbdata->cmd = Tcl_CreateCommand(hw->m_interp, (const char*)*String::Utf8Value(cmdName), CallbackTrampoline, (ClientData) cbdata, CallbackDelete); hw->Ref(); return Undefined(); } // ---------------------------------------------------- /* * event(Boolean) -- handle one or all pending Tcl events if boolean is present and true */ static Handle<Value> Event(const Arguments& args) { HandleScope scope; int eventStatus; int doMultiple; if (args.Length() > 1 || (args.Length() == 1 && !args[0]->IsBoolean())) { return ThrowException(Exception::TypeError(String::New("Optional argument, if present, must be a boolean"))); } if (args.Length() == 0) { doMultiple = 1; } else { doMultiple = args[0]->ToBoolean()->Value(); } do { eventStatus = Tcl_DoOneEvent (TCL_ALL_EVENTS | TCL_DONT_WAIT); } while (doMultiple && eventStatus); Local<Integer> result = Integer::New(eventStatus); return scope.Close(result); } // ---------------------------------------------------- }; Persistent<FunctionTemplate> NodeTcl::s_ct; extern "C" { static void init (Handle<Object> target) { NodeTcl::Init(target); } NODE_MODULE(nodetcl, init); } <|endoftext|>
<commit_before>/* ** Copyright 2014 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker 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 Centreon Broker. If not, see ** <http:/www.gnu.org/licenses/>. */ #include "com/centreon/broker/bam/configuration/applier/ba.hh" #include "com/centreon/broker/bam/configuration/applier/bool_expression.hh" #include "com/centreon/broker/bam/configuration/applier/kpi.hh" #include "com/centreon/broker/bam/configuration/applier/meta_service.hh" #include "com/centreon/broker/bam/bool_expression.hh" #include "com/centreon/broker/bam/kpi_ba.hh" #include "com/centreon/broker/bam/kpi_boolexp.hh" #include "com/centreon/broker/bam/kpi_meta.hh" #include "com/centreon/broker/bam/kpi_service.hh" #include "com/centreon/broker/bam/meta_service.hh" #include "com/centreon/broker/bam/service_book.hh" #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/logging/logging.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::bam::configuration; /** * Default constructor. */ applier::kpi::kpi() {} /** * Copy constructor. * * @param[in] right Object to copy. */ applier::kpi::kpi(applier::kpi const& right) { _internal_copy(right); } /** * Destructor. */ applier::kpi::~kpi() {} /** * Assignment operator. * * @param[in] right Object to copy. * * @return This object. */ applier::kpi& applier::kpi::operator=(applier::kpi const& right) { if (this != &right) _internal_copy(right); return (*this); } /** * Apply configuration. * * @param[in] my_kpis Object to copy. * @param[in,out] my_bas Already applied BAs. * @param[in,out] my_metas Already applied meta-services. * @param[in,out] my_boolexps Already applied boolean expressions. * @param[out] book Service book. * * @return This object. */ void applier::kpi::apply( bam::configuration::state::kpis const& my_kpis, applier::ba& my_bas, applier::meta_service& my_metas, applier::bool_expression& my_boolexps, bam::service_book& book) { // // DIFF // // Objects to delete are items remaining in the // set at the end of the iteration. std::map<unsigned int, applied> to_delete(_applied); // Objects to create are items remaining in the // set at the end of the iteration. bam::configuration::state::kpis to_create(my_kpis); // Iterate through configuration. for (bam::configuration::state::kpis::iterator it(to_create.begin()), end(to_create.end()); it != end;) { std::map<unsigned int, applied>::iterator cfg_it(to_delete.find(it->first)); // Found = modify (or not). if (cfg_it != to_delete.end()) { // Configuration mismatch, modify object // (indeed deletion + recreation). if (cfg_it->second.cfg != it->second) ++it; else { to_delete.erase(cfg_it); bam::configuration::state::kpis::iterator tmp = it; ++it; to_create.erase(tmp); } } // Not found = create. else ++it; } // // OBJECT CREATION/DELETION // // Delete objects. for (std::map<unsigned int, applied>::iterator it(to_delete.begin()), end(to_delete.end()); it != end; ++it) { logging::config(logging::medium) << "BAM: removing KPI " << it->second.cfg.get_id(); if (it->second.cfg.is_service()) book.unlisten( it->second.cfg.get_host_id(), it->second.cfg.get_service_id(), static_cast<kpi_service*>(it->second.obj.data())); _applied.erase(it->first); } to_delete.clear(); // Create new objects. for (bam::configuration::state::kpis::iterator it(to_create.begin()), end(to_create.end()); it != end; ++it) { misc::shared_ptr<bam::kpi> new_kpi(_new_kpi( it->second, my_bas, my_metas, my_boolexps, book)); applied& content(_applied[it->first]); content.cfg = it->second; content.obj = new_kpi; } return ; } /** * Visit KPIs. * * @param[out] visitor Object that will receive status. */ void applier::kpi::visit(io::stream* visitor) { for (std::map<unsigned int, applied>::iterator it(_applied.begin()), end(_applied.end()); it != end; ++it) it->second.obj->visit(visitor); return ; } /** * Copy internal data members. * * @param[in] right Object to copy. */ void applier::kpi::_internal_copy(applier::kpi const& right) { _applied = right._applied; return ; } /** * Create new KPI object. * * @param[in] cfg KPI configuration. * @param[in,out] my_bas Already applied BAs. * @param[in,out] my_metas Already applied meta-services. * @param[in,out] my_boolexps Already applied boolean expressions. * @param[out] book Service book, used to notify kpi_service * of service change. * * @return New KPI object. */ misc::shared_ptr<bam::kpi> applier::kpi::_new_kpi( configuration::kpi const& cfg, applier::ba& my_bas, applier::meta_service& my_metas, applier::bool_expression& my_boolexps, service_book& book) { misc::shared_ptr<bam::kpi> my_kpi; if (cfg.is_service()) { logging::config(logging::medium) << "BAM: creating new KPI " << cfg.get_id() << " of service (" << cfg.get_host_id() << ", " << cfg.get_service_id() << ") impacting BA " << cfg.get_ba_id(); misc::shared_ptr<bam::kpi_service> obj(new bam::kpi_service); obj->set_acknowledged(cfg.is_acknowledged()); obj->set_downtimed(cfg.is_downtimed()); obj->set_host_id(cfg.get_host_id()); obj->set_impact_critical(cfg.get_impact_critical()); obj->set_impact_unknown(cfg.get_impact_unknown()); obj->set_impact_warning(cfg.get_impact_warning()); obj->set_service_id(cfg.get_service_id()); obj->set_state_hard(cfg.get_status()); obj->set_state_type(cfg.get_state_type()); my_kpi = obj.staticCast<bam::kpi>(); book.listen(cfg.get_host_id(), cfg.get_service_id(), obj.data()); } else if (cfg.is_ba()) { logging::config(logging::medium) << "BAM: creating new KPI " << cfg.get_id() << " of BA " << cfg.get_indicator_ba_id() << " impacting BA " << cfg.get_ba_id(); misc::shared_ptr<bam::kpi_ba> obj(new bam::kpi_ba); obj->set_impact_critical(cfg.get_impact_critical()); obj->set_impact_warning(cfg.get_impact_warning()); misc::shared_ptr<bam::ba> target(my_bas.find_ba(cfg.get_indicator_ba_id())); if (target.isNull()) throw (exceptions::msg() << "BAM: could not create KPI " << cfg.get_id() << ": could not find BA " << cfg.get_indicator_ba_id()); obj->link_ba(target); target->add_parent(obj.staticCast<bam::computable>()); my_kpi = obj.staticCast<bam::kpi>(); } else if (cfg.is_meta()) { logging::config(logging::medium) << "BAM: creating new KPI " << cfg.get_id() << " of meta-service " << cfg.get_meta_id() << " impacting BA " << cfg.get_ba_id(); misc::shared_ptr<bam::kpi_meta> obj(new bam::kpi_meta); obj->set_impact_critical(cfg.get_impact_critical()); obj->set_impact_warning(cfg.get_impact_warning()); misc::shared_ptr<bam::meta_service> target(my_metas.find_meta(cfg.get_meta_id())); if (target.isNull()) throw (exceptions::msg() << "BAM: could not create KPI " << cfg.get_id() << ": could not find meta-service " << cfg.get_meta_id()); obj->link_meta(target); target->add_parent(obj.staticCast<bam::computable>()); my_kpi = obj.staticCast<bam::kpi>(); } else if (cfg.is_boolexp()) { logging::config(logging::medium) << "BAM: creating new KPI " << cfg.get_id() << " of boolean expression " << cfg.get_boolexp_id() << " impacting BA " << cfg.get_ba_id(); misc::shared_ptr<bam::kpi_boolexp> obj(new bam::kpi_boolexp); obj->set_impact(cfg.get_impact_critical()); misc::shared_ptr<bam::bool_expression> target(my_boolexps.find_boolexp(cfg.get_boolexp_id())); if (target.isNull()) throw (exceptions::msg() << "BAM: could not create KPI " << cfg.get_id() << ": could not find boolean expression " << cfg.get_boolexp_id()); obj->link_boolexp(target); target->add_parent(obj.staticCast<bam::computable>()); my_kpi = obj.staticCast<bam::kpi>(); } else throw (exceptions::msg() << "BAM: could not create KPI " << cfg.get_id() << " which is neither related to a service, nor a BA," << " nor a meta-service"); misc::shared_ptr<bam::ba> my_ba(my_bas.find_ba(cfg.get_ba_id())); if (my_ba.isNull()) throw (exceptions::msg() << "BAM: could not create KPI " << cfg.get_id() << ": BA " << cfg.get_ba_id() << " does not exist"); my_kpi->set_id(cfg.get_id()); if (cfg.get_opened_event().kpi_id != 0) my_kpi->set_initial_event(cfg.get_opened_event()); my_ba->add_impact(my_kpi.staticCast<bam::kpi>()); my_kpi->add_parent(my_ba.staticCast<bam::computable>()); return (my_kpi); } <commit_msg>Bam: Fix a double impact in kpi loading.<commit_after>/* ** Copyright 2014 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker 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 Centreon Broker. If not, see ** <http:/www.gnu.org/licenses/>. */ #include "com/centreon/broker/bam/configuration/applier/ba.hh" #include "com/centreon/broker/bam/configuration/applier/bool_expression.hh" #include "com/centreon/broker/bam/configuration/applier/kpi.hh" #include "com/centreon/broker/bam/configuration/applier/meta_service.hh" #include "com/centreon/broker/bam/bool_expression.hh" #include "com/centreon/broker/bam/kpi_ba.hh" #include "com/centreon/broker/bam/kpi_boolexp.hh" #include "com/centreon/broker/bam/kpi_meta.hh" #include "com/centreon/broker/bam/kpi_service.hh" #include "com/centreon/broker/bam/meta_service.hh" #include "com/centreon/broker/bam/service_book.hh" #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/logging/logging.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::bam::configuration; /** * Default constructor. */ applier::kpi::kpi() {} /** * Copy constructor. * * @param[in] right Object to copy. */ applier::kpi::kpi(applier::kpi const& right) { _internal_copy(right); } /** * Destructor. */ applier::kpi::~kpi() {} /** * Assignment operator. * * @param[in] right Object to copy. * * @return This object. */ applier::kpi& applier::kpi::operator=(applier::kpi const& right) { if (this != &right) _internal_copy(right); return (*this); } /** * Apply configuration. * * @param[in] my_kpis Object to copy. * @param[in,out] my_bas Already applied BAs. * @param[in,out] my_metas Already applied meta-services. * @param[in,out] my_boolexps Already applied boolean expressions. * @param[out] book Service book. * * @return This object. */ void applier::kpi::apply( bam::configuration::state::kpis const& my_kpis, applier::ba& my_bas, applier::meta_service& my_metas, applier::bool_expression& my_boolexps, bam::service_book& book) { // // DIFF // // Objects to delete are items remaining in the // set at the end of the iteration. std::map<unsigned int, applied> to_delete(_applied); // Objects to create are items remaining in the // set at the end of the iteration. bam::configuration::state::kpis to_create(my_kpis); // Iterate through configuration. for (bam::configuration::state::kpis::iterator it(to_create.begin()), end(to_create.end()); it != end;) { std::map<unsigned int, applied>::iterator cfg_it(to_delete.find(it->first)); // Found = modify (or not). if (cfg_it != to_delete.end()) { // Configuration mismatch, modify object // (indeed deletion + recreation). if (cfg_it->second.cfg != it->second) ++it; else { to_delete.erase(cfg_it); bam::configuration::state::kpis::iterator tmp = it; ++it; to_create.erase(tmp); } } // Not found = create. else ++it; } // // OBJECT CREATION/DELETION // // Delete objects. for (std::map<unsigned int, applied>::iterator it(to_delete.begin()), end(to_delete.end()); it != end; ++it) { logging::config(logging::medium) << "BAM: removing KPI " << it->second.cfg.get_id(); if (it->second.cfg.is_service()) book.unlisten( it->second.cfg.get_host_id(), it->second.cfg.get_service_id(), static_cast<kpi_service*>(it->second.obj.data())); misc::shared_ptr<bam::ba> my_ba(my_bas.find_ba(it->second.cfg.get_ba_id())); if (!my_ba.isNull()) my_ba->remove_impact(it->second.obj); _applied.erase(it->first); } to_delete.clear(); // Create new objects. for (bam::configuration::state::kpis::iterator it(to_create.begin()), end(to_create.end()); it != end; ++it) { misc::shared_ptr<bam::kpi> new_kpi(_new_kpi( it->second, my_bas, my_metas, my_boolexps, book)); applied& content(_applied[it->first]); content.cfg = it->second; content.obj = new_kpi; } return ; } /** * Visit KPIs. * * @param[out] visitor Object that will receive status. */ void applier::kpi::visit(io::stream* visitor) { for (std::map<unsigned int, applied>::iterator it(_applied.begin()), end(_applied.end()); it != end; ++it) it->second.obj->visit(visitor); return ; } /** * Copy internal data members. * * @param[in] right Object to copy. */ void applier::kpi::_internal_copy(applier::kpi const& right) { _applied = right._applied; return ; } /** * Create new KPI object. * * @param[in] cfg KPI configuration. * @param[in,out] my_bas Already applied BAs. * @param[in,out] my_metas Already applied meta-services. * @param[in,out] my_boolexps Already applied boolean expressions. * @param[out] book Service book, used to notify kpi_service * of service change. * * @return New KPI object. */ misc::shared_ptr<bam::kpi> applier::kpi::_new_kpi( configuration::kpi const& cfg, applier::ba& my_bas, applier::meta_service& my_metas, applier::bool_expression& my_boolexps, service_book& book) { misc::shared_ptr<bam::kpi> my_kpi; if (cfg.is_service()) { logging::config(logging::medium) << "BAM: creating new KPI " << cfg.get_id() << " of service (" << cfg.get_host_id() << ", " << cfg.get_service_id() << ") impacting BA " << cfg.get_ba_id(); misc::shared_ptr<bam::kpi_service> obj(new bam::kpi_service); obj->set_acknowledged(cfg.is_acknowledged()); obj->set_downtimed(cfg.is_downtimed()); obj->set_host_id(cfg.get_host_id()); obj->set_impact_critical(cfg.get_impact_critical()); obj->set_impact_unknown(cfg.get_impact_unknown()); obj->set_impact_warning(cfg.get_impact_warning()); obj->set_service_id(cfg.get_service_id()); obj->set_state_hard(cfg.get_status()); obj->set_state_type(cfg.get_state_type()); my_kpi = obj.staticCast<bam::kpi>(); book.listen(cfg.get_host_id(), cfg.get_service_id(), obj.data()); } else if (cfg.is_ba()) { logging::config(logging::medium) << "BAM: creating new KPI " << cfg.get_id() << " of BA " << cfg.get_indicator_ba_id() << " impacting BA " << cfg.get_ba_id(); misc::shared_ptr<bam::kpi_ba> obj(new bam::kpi_ba); obj->set_impact_critical(cfg.get_impact_critical()); obj->set_impact_warning(cfg.get_impact_warning()); misc::shared_ptr<bam::ba> target(my_bas.find_ba(cfg.get_indicator_ba_id())); if (target.isNull()) throw (exceptions::msg() << "BAM: could not create KPI " << cfg.get_id() << ": could not find BA " << cfg.get_indicator_ba_id()); obj->link_ba(target); target->add_parent(obj.staticCast<bam::computable>()); my_kpi = obj.staticCast<bam::kpi>(); } else if (cfg.is_meta()) { logging::config(logging::medium) << "BAM: creating new KPI " << cfg.get_id() << " of meta-service " << cfg.get_meta_id() << " impacting BA " << cfg.get_ba_id(); misc::shared_ptr<bam::kpi_meta> obj(new bam::kpi_meta); obj->set_impact_critical(cfg.get_impact_critical()); obj->set_impact_warning(cfg.get_impact_warning()); misc::shared_ptr<bam::meta_service> target(my_metas.find_meta(cfg.get_meta_id())); if (target.isNull()) throw (exceptions::msg() << "BAM: could not create KPI " << cfg.get_id() << ": could not find meta-service " << cfg.get_meta_id()); obj->link_meta(target); target->add_parent(obj.staticCast<bam::computable>()); my_kpi = obj.staticCast<bam::kpi>(); } else if (cfg.is_boolexp()) { logging::config(logging::medium) << "BAM: creating new KPI " << cfg.get_id() << " of boolean expression " << cfg.get_boolexp_id() << " impacting BA " << cfg.get_ba_id(); misc::shared_ptr<bam::kpi_boolexp> obj(new bam::kpi_boolexp); obj->set_impact(cfg.get_impact_critical()); misc::shared_ptr<bam::bool_expression> target(my_boolexps.find_boolexp(cfg.get_boolexp_id())); if (target.isNull()) throw (exceptions::msg() << "BAM: could not create KPI " << cfg.get_id() << ": could not find boolean expression " << cfg.get_boolexp_id()); obj->link_boolexp(target); target->add_parent(obj.staticCast<bam::computable>()); my_kpi = obj.staticCast<bam::kpi>(); } else throw (exceptions::msg() << "BAM: could not create KPI " << cfg.get_id() << " which is neither related to a service, nor a BA," << " nor a meta-service"); misc::shared_ptr<bam::ba> my_ba(my_bas.find_ba(cfg.get_ba_id())); if (my_ba.isNull()) throw (exceptions::msg() << "BAM: could not create KPI " << cfg.get_id() << ": BA " << cfg.get_ba_id() << " does not exist"); my_kpi->set_id(cfg.get_id()); if (cfg.get_opened_event().kpi_id != 0) my_kpi->set_initial_event(cfg.get_opened_event()); my_ba->add_impact(my_kpi.staticCast<bam::kpi>()); my_kpi->add_parent(my_ba.staticCast<bam::computable>()); return (my_kpi); } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <vector> #include <cstdio> #include <assert.h> #include <algorithm> #include <boost/lambda/lambda.hpp> #include "EventCluster.h" #include "Subclone.h" #include "SubcloneExplore.h" sqlite3 *res_database; using namespace SubcloneExplorer; void TreeEnumeration(Subclone * root, std::vector<EventCluster> vecClusters, size_t symIdx); void TreeAssessment(Subclone * root, std::vector<EventCluster> vecClusters); void SubcloneExplorerMain(int argc, char* argv[]) { if(argc < 2) { std::cerr<<"Usage: "<<argv[0]<<" <cluster-archive-sqlite-db> [output-db]"<<std::endl; return; } res_database=NULL; sqlite3 *database; int rc; rc = sqlite3_open_v2(argv[1], &database, SQLITE_OPEN_READONLY, NULL); if(rc != SQLITE_OK) { std::cerr<<"Unable to open database "<<argv[1]<<std::endl; return; } // load mutation clusters EventCluster dummyCluster; std::vector<sqlite3_int64> clusterIDs = dummyCluster.vecAllObjectsID(database); if(clusterIDs.size() == 0) { std::cerr<<"Event cluster list is empty!"<<std::endl; return; } std::vector<EventCluster> vecClusters; for(size_t i=0; i<clusterIDs.size(); i++) { EventCluster newCluster; newCluster.unarchiveObjectFromDB(database, clusterIDs[i]); vecClusters.push_back(newCluster); } sqlite3_close(database); std::sort(vecClusters.begin(), vecClusters.end()); std::reverse(vecClusters.begin(), vecClusters.end()); // Mutation list read. Start to enumerate trees // 1. Create a node contains no mutation (symId = 0). // this node will act as the root of the trees Subclone *root = new Subclone(); root->setFraction(-1); root->setTreeFraction(-1); if(argc >= 2) { int rc = sqlite3_open(argv[2], &res_database); if(rc != SQLITE_OK ) { std::cerr<<"Unable to open result database for writting."<<std::endl; return; } } TreeEnumeration(root, vecClusters, 0); if(res_database != NULL) sqlite3_close(res_database); } // First of all, a tree traverser that will print out the tree. // This will be used when the program decides to output a tree // Tree Print Traverser. This one will just print the symbol id // of the node that is given to it. class TreePrintTraverser: public TreeTraverseDelegate { public: virtual void preprocessNode(TreeNode *node) { if(!node->isLeaf()) std::cerr<<"("; } virtual void processNode(TreeNode * node) { std::cerr<<((Subclone *)node)->fraction()<<","; } virtual void postprocessNode(TreeNode *node) { if(!node->isLeaf()) std::cerr<<")"; } }; // This function will recursively construct all possible tree structures // using the given mutation list, starting with the mutation identified by symIdx // // The idea behind this is quite simple. If a node is not the last symbol on the // mutation list, it will try to add this particular node to every other existing // node's children list. After one addition, the traverser calls the TreeEnumeration // again but with a incremented symIdx, so that the next symbol can be treated in the // same way. When the last symbol has been reached, the tree is printed out, in both // Pre-Order and Post-Order, by the TreePrintTraverser class, so that each tree can be // uniquely identified. void TreeEnumeration(Subclone * root, std::vector<EventCluster> vecClusters, size_t symIdx) { // Tree Enum Traverser. It will check if the last symbol has been // treated or not. If yes, the tree is complete and it will call // TreeAssessment to assess the viability of the tree; If no, it // will add the current untreated symbol as a children to the node // that is given to it, and call TreeEnumeration again to go into // one more level of the recursion. class TreeEnumTraverser : public TreeTraverseDelegate { protected: // Some state variables that the TreeEnumeration // function needs to expose to the traverser std::vector<EventCluster>& _vecClusters; size_t _symIdx; Subclone *_floatNode; Subclone *_root; public: TreeEnumTraverser(std::vector<EventCluster>& vecClusters, size_t symIdx, Subclone *floatNode, Subclone *root): _vecClusters(vecClusters), _symIdx(symIdx), _floatNode(floatNode), _root(root) {;} virtual void processNode(TreeNode * node) { Subclone *clone = dynamic_cast<Subclone *>(node); // Add the floating node as the chilren of the current node clone->addChild(_floatNode); // Move on to the next symbol TreeEnumeration(_root, _vecClusters, _symIdx); // Remove the child node->removeChild(_floatNode); } }; if(symIdx == vecClusters.size()) { TreeAssessment(root, vecClusters); return; } // Create the new tree node Subclone *newClone = new Subclone(); newClone->setFraction(-1); newClone->setTreeFraction(-1); newClone->addEventCluster(&vecClusters[symIdx]); // Configure the tree traverser TreeEnumTraverser TreeEnumTraverserObj(vecClusters, ++symIdx, newClone, root); // Traverse the tree TreeNode::PreOrderTraverse(root, TreeEnumTraverserObj); delete newClone; } void TreeAssessment(Subclone * root, std::vector<EventCluster> vecClusters) { class FracAsnTraverser : public TreeTraverseDelegate { protected: std::vector<EventCluster>& _vecClusters; public: FracAsnTraverser(std::vector<EventCluster>& vecClusters): _vecClusters(vecClusters) {;} virtual void processNode(TreeNode * node) { if(node->isLeaf()) { // direct assign ((Subclone *)node)->setFraction(((Subclone *)node)->vecEventCluster()[0]->cellFraction()); ((Subclone *)node)->setTreeFraction(((Subclone *)node)->vecEventCluster()[0]->cellFraction()); } else { // intermediate node. assign it's mutation fraction - subtree_fraction // actually, if it's root, assign 1 if(node->isRoot()) ((Subclone *)node)->setTreeFraction(1); else ((Subclone *)node)->setTreeFraction(((Subclone *)node)->vecEventCluster()[0]->cellFraction()); assert(((Subclone *)node)->treeFraction() >= 0 && ((Subclone *)node)->treeFraction() <= 1); double childrenFraction = 0; for(size_t i=0; i<node->getVecChildren().size(); i++) childrenFraction += ((Subclone *)node->getVecChildren()[i])->treeFraction(); double nodeFraction = ((Subclone *)node)->treeFraction() - childrenFraction; if(nodeFraction < 1e-3 && nodeFraction > -1e-3) nodeFraction = 0; // check tree viability if(nodeFraction < 0) { terminate(); } else { ((Subclone *)node)->setFraction(nodeFraction); assert(((Subclone *)node)->fraction() >= 0 && ((Subclone *)node)->fraction() <= 1); } } } }; // Fraction Reset Traverser. This will go through the nodes and // reset the fraction to uninitialized state so that the same nodes // can be used for another structure's evaluation class NodeResetTraverser : public TreeTraverseDelegate { public: virtual void processNode(TreeNode * node) { ((Subclone *)node)->setFraction(-1); ((Subclone *)node)->setTreeFraction(-1); ((Subclone *)node)->setParentId(0); ((Subclone *)node)->setId(0); } }; // check if the root is sane if(root == NULL) return; // reset node and tree fractions NodeResetTraverser nrTraverser; TreeNode::PreOrderTraverse(root, nrTraverser); // calcuate tree fractions FracAsnTraverser fracTraverser(vecClusters); TreeNode::PostOrderTraverse(root, fracTraverser); // if the tree is viable, output it if(root->fraction() >= 0) { TreePrintTraverser printTraverser; std::cerr<<"Viable Tree! Pre-Orer: "; TreeNode::PreOrderTraverse(root, printTraverser); std::cerr<<std::endl; // save tree to database if(res_database != NULL) { SubcloneSaveTreeTraverser stt(res_database); TreeNode::PreOrderTraverse(root, stt); } } else { TreePrintTraverser printTraverser; std::cerr<<"Unviable Tree! Pre-Orer: "; TreeNode::PreOrderTraverse(root, printTraverser); std::cerr<<std::endl; } } <commit_msg>Now status of each solution is printed to stdout<commit_after>#include <iostream> #include <fstream> #include <vector> #include <cstdio> #include <assert.h> #include <algorithm> #include <numeric> #include <boost/lambda/lambda.hpp> #include "EventCluster.h" #include "Subclone.h" #include "SubcloneExplore.h" sqlite3 *res_database; static int _num_solutions; static std::vector<int> _tree_depth; using namespace SubcloneExplorer; int treeDepth(TreeNode *root) { if(root->isLeaf()) return 1; int max_subtree_depth = 0; for(size_t i=0; i<root->getVecChildren().size(); i++) { int subtree_depth = treeDepth(root->getVecChildren()[i]); if(subtree_depth > max_subtree_depth) max_subtree_depth = subtree_depth; } return 1+max_subtree_depth; } void TreeEnumeration(Subclone * root, std::vector<EventCluster> vecClusters, size_t symIdx); void TreeAssessment(Subclone * root, std::vector<EventCluster> vecClusters); void SubcloneExplorerMain(int argc, char* argv[]) { if(argc < 2) { std::cerr<<"Usage: "<<argv[0]<<" <cluster-archive-sqlite-db> [output-db]"<<std::endl; return; } res_database=NULL; sqlite3 *database; int rc; rc = sqlite3_open_v2(argv[1], &database, SQLITE_OPEN_READONLY, NULL); if(rc != SQLITE_OK) { std::cerr<<"Unable to open database "<<argv[1]<<std::endl; return; } // load mutation clusters EventCluster dummyCluster; std::vector<sqlite3_int64> clusterIDs = dummyCluster.vecAllObjectsID(database); if(clusterIDs.size() == 0) { std::cerr<<"Event cluster list is empty!"<<std::endl; return; } std::vector<EventCluster> vecClusters; for(size_t i=0; i<clusterIDs.size(); i++) { EventCluster newCluster; newCluster.unarchiveObjectFromDB(database, clusterIDs[i]); vecClusters.push_back(newCluster); } sqlite3_close(database); std::sort(vecClusters.begin(), vecClusters.end()); std::reverse(vecClusters.begin(), vecClusters.end()); // Mutation list read. Start to enumerate trees // 1. Create a node contains no mutation (symId = 0). // this node will act as the root of the trees Subclone *root = new Subclone(); root->setFraction(-1); root->setTreeFraction(-1); if(argc >= 2) { int rc = sqlite3_open(argv[2], &res_database); if(rc != SQLITE_OK ) { std::cerr<<"Unable to open result database for writting."<<std::endl; return; } } TreeEnumeration(root, vecClusters, 0); if(res_database != NULL) sqlite3_close(res_database); if(_tree_depth.size()> 0) std::cout<<_num_solutions<<"\t"<<std::accumulate(_tree_depth.begin(), _tree_depth.end(), 0)/float(_tree_depth.size())<<std::endl; } // First of all, a tree traverser that will print out the tree. // This will be used when the program decides to output a tree // Tree Print Traverser. This one will just print the symbol id // of the node that is given to it. class TreePrintTraverser: public TreeTraverseDelegate { public: virtual void preprocessNode(TreeNode *node) { if(!node->isLeaf()) std::cerr<<"("; } virtual void processNode(TreeNode * node) { std::cerr<<((Subclone *)node)->fraction()<<","; } virtual void postprocessNode(TreeNode *node) { if(!node->isLeaf()) std::cerr<<")"; } }; // This function will recursively construct all possible tree structures // using the given mutation list, starting with the mutation identified by symIdx // // The idea behind this is quite simple. If a node is not the last symbol on the // mutation list, it will try to add this particular node to every other existing // node's children list. After one addition, the traverser calls the TreeEnumeration // again but with a incremented symIdx, so that the next symbol can be treated in the // same way. When the last symbol has been reached, the tree is printed out, in both // Pre-Order and Post-Order, by the TreePrintTraverser class, so that each tree can be // uniquely identified. void TreeEnumeration(Subclone * root, std::vector<EventCluster> vecClusters, size_t symIdx) { // Tree Enum Traverser. It will check if the last symbol has been // treated or not. If yes, the tree is complete and it will call // TreeAssessment to assess the viability of the tree; If no, it // will add the current untreated symbol as a children to the node // that is given to it, and call TreeEnumeration again to go into // one more level of the recursion. class TreeEnumTraverser : public TreeTraverseDelegate { protected: // Some state variables that the TreeEnumeration // function needs to expose to the traverser std::vector<EventCluster>& _vecClusters; size_t _symIdx; Subclone *_floatNode; Subclone *_root; public: TreeEnumTraverser(std::vector<EventCluster>& vecClusters, size_t symIdx, Subclone *floatNode, Subclone *root): _vecClusters(vecClusters), _symIdx(symIdx), _floatNode(floatNode), _root(root) {;} virtual void processNode(TreeNode * node) { Subclone *clone = dynamic_cast<Subclone *>(node); // Add the floating node as the chilren of the current node clone->addChild(_floatNode); // Move on to the next symbol TreeEnumeration(_root, _vecClusters, _symIdx); // Remove the child node->removeChild(_floatNode); } }; if(symIdx == vecClusters.size()) { TreeAssessment(root, vecClusters); return; } // Create the new tree node Subclone *newClone = new Subclone(); newClone->setFraction(-1); newClone->setTreeFraction(-1); newClone->addEventCluster(&vecClusters[symIdx]); // Configure the tree traverser TreeEnumTraverser TreeEnumTraverserObj(vecClusters, ++symIdx, newClone, root); // Traverse the tree TreeNode::PreOrderTraverse(root, TreeEnumTraverserObj); delete newClone; } void TreeAssessment(Subclone * root, std::vector<EventCluster> vecClusters) { class FracAsnTraverser : public TreeTraverseDelegate { protected: std::vector<EventCluster>& _vecClusters; public: FracAsnTraverser(std::vector<EventCluster>& vecClusters): _vecClusters(vecClusters) {;} virtual void processNode(TreeNode * node) { if(node->isLeaf()) { // direct assign ((Subclone *)node)->setFraction(((Subclone *)node)->vecEventCluster()[0]->cellFraction()); ((Subclone *)node)->setTreeFraction(((Subclone *)node)->vecEventCluster()[0]->cellFraction()); } else { // intermediate node. assign it's mutation fraction - subtree_fraction // actually, if it's root, assign 1 if(node->isRoot()) ((Subclone *)node)->setTreeFraction(1); else ((Subclone *)node)->setTreeFraction(((Subclone *)node)->vecEventCluster()[0]->cellFraction()); assert(((Subclone *)node)->treeFraction() >= 0 && ((Subclone *)node)->treeFraction() <= 1); double childrenFraction = 0; for(size_t i=0; i<node->getVecChildren().size(); i++) childrenFraction += ((Subclone *)node->getVecChildren()[i])->treeFraction(); double nodeFraction = ((Subclone *)node)->treeFraction() - childrenFraction; if(nodeFraction < 1e-3 && nodeFraction > -1e-3) nodeFraction = 0; // check tree viability if(nodeFraction < 0) { terminate(); } else { ((Subclone *)node)->setFraction(nodeFraction); assert(((Subclone *)node)->fraction() >= 0 && ((Subclone *)node)->fraction() <= 1); } } } }; // Fraction Reset Traverser. This will go through the nodes and // reset the fraction to uninitialized state so that the same nodes // can be used for another structure's evaluation class NodeResetTraverser : public TreeTraverseDelegate { public: virtual void processNode(TreeNode * node) { ((Subclone *)node)->setFraction(-1); ((Subclone *)node)->setTreeFraction(-1); ((Subclone *)node)->setParentId(0); ((Subclone *)node)->setId(0); } }; // check if the root is sane if(root == NULL) return; // reset node and tree fractions NodeResetTraverser nrTraverser; TreeNode::PreOrderTraverse(root, nrTraverser); // calcuate tree fractions FracAsnTraverser fracTraverser(vecClusters); TreeNode::PostOrderTraverse(root, fracTraverser); // if the tree is viable, output it if(root->fraction() >= 0) { TreePrintTraverser printTraverser; std::cerr<<"Viable Tree! Pre-Orer: "; TreeNode::PreOrderTraverse(root, printTraverser); std::cerr<<std::endl; // save tree to database if(res_database != NULL) { SubcloneSaveTreeTraverser stt(res_database); TreeNode::PreOrderTraverse(root, stt); } _num_solutions++; _tree_depth.push_back(treeDepth(root)); } else { TreePrintTraverser printTraverser; std::cerr<<"Unviable Tree! Pre-Orer: "; TreeNode::PreOrderTraverse(root, printTraverser); std::cerr<<std::endl; } } <|endoftext|>
<commit_before>// // posix_main.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Modifed by Geoff Lawler, SPARTA, inc. 2008. // #include <iostream> #include <string> #include <boost/asio.hpp> #include <boost/thread.hpp> #include <boost/shared_ptr.hpp> #include "server.h" #if !defined(_WIN32) #include <pthread.h> #include <signal.h> #include "logger.h" #include "libconfig.h++" #include "initConfig.h" #include "singletonConfig.h" #include "watcherd.h" using namespace std; using namespace watcher; using namespace libconfig; int main(int argc, char* argv[]) { TRACE_ENTER(); string configFilename; Config &config=SingletonConfig::instance(); SingletonConfig::lock(); if (false==initConfig(config, argc, argv, configFilename)) { cerr << "Error reading configuration file, unable to continue." << endl; cerr << "Usage: " << basename(argv[0]) << " [-c|--configFile] configfile" << endl; return 1; } SingletonConfig::unlock(); string logConf("log.properties"); if (!config.lookupValue("logPropertiesFile", logConf)) { cout << "Unable to find logPropertiesFile setting in the configuration file, using default: " << logConf << " and adding it to the configuration file." << endl; config.getRoot().add("logPropertiesFile", libconfig::Setting::TypeString)=logConf; } LOAD_LOG_PROPS(logConf); LOG_INFO("Logger initialized from file \"" << logConf << "\""); string address("glory"); string port("8095"); size_t numThreads; if (!config.lookupValue("server", address)) { LOG_INFO("'server' not found in the configuration file, using default: " << address << " and adding this to the configuration file."); config.getRoot().add("server", libconfig::Setting::TypeString) = address; } if (!config.lookupValue("port", port)) { LOG_INFO("'port' not found in the configuration file, using default: " << port << " and adding this to the configuration file."); config.getRoot().add("port", libconfig::Setting::TypeString)=port; } if (!config.lookupValue("serverThreadNum", numThreads)) { LOG_INFO("'serverThreadNum' not found in the configuration file, using default: " << numThreads << " and adding this to the configuration file.") config.getRoot().add("serverThreadNum", libconfig::Setting::TypeInt)=static_cast<int>(numThreads); } WatcherdPtr theWatcherDaemon(new Watcherd); try { theWatcherDaemon->run(address, port, (int)numThreads); } catch (std::exception &e) { LOG_FATAL("Caught exception in main(): " << e.what()); std::cerr << "exception: " << e.what() << "\n"; } // Save any configuration changes made during the run. LOG_INFO("Saving last known configuration to " << configFilename); SingletonConfig::lock(); config.writeFile(configFilename.c_str()); return 0; } #endif // !defined(_WIN32) <commit_msg>add config for sqlite database file<commit_after>// // posix_main.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Modifed by Geoff Lawler, SPARTA, inc. 2008. // #include <iostream> #include <string> #include <boost/asio.hpp> #include <boost/thread.hpp> #include <boost/shared_ptr.hpp> #include "server.h" #if !defined(_WIN32) #include <pthread.h> #include <signal.h> #include "logger.h" #include "libconfig.h++" #include "initConfig.h" #include "singletonConfig.h" #include "watcherd.h" using namespace std; using namespace watcher; using namespace libconfig; int main(int argc, char* argv[]) { TRACE_ENTER(); string configFilename; Config &config=SingletonConfig::instance(); SingletonConfig::lock(); if (false==initConfig(config, argc, argv, configFilename)) { cerr << "Error reading configuration file, unable to continue." << endl; cerr << "Usage: " << basename(argv[0]) << " [-c|--configFile] configfile" << endl; return 1; } SingletonConfig::unlock(); string logConf("log.properties"); if (!config.lookupValue("logPropertiesFile", logConf)) { cout << "Unable to find logPropertiesFile setting in the configuration file, using default: " << logConf << " and adding it to the configuration file." << endl; config.getRoot().add("logPropertiesFile", libconfig::Setting::TypeString)=logConf; } LOAD_LOG_PROPS(logConf); LOG_INFO("Logger initialized from file \"" << logConf << "\""); string address("glory"); string port("8095"); size_t numThreads; std::string dbPath("event.db"); if (!config.lookupValue("server", address)) { LOG_INFO("'server' not found in the configuration file, using default: " << address << " and adding this to the configuration file."); config.getRoot().add("server", libconfig::Setting::TypeString) = address; } if (!config.lookupValue("port", port)) { LOG_INFO("'port' not found in the configuration file, using default: " << port << " and adding this to the configuration file."); config.getRoot().add("port", libconfig::Setting::TypeString)=port; } if (!config.lookupValue("serverThreadNum", numThreads)) { LOG_INFO("'serverThreadNum' not found in the configuration file, using default: " << numThreads << " and adding this to the configuration file.") config.getRoot().add("serverThreadNum", libconfig::Setting::TypeInt)=static_cast<int>(numThreads); } if (!config.lookupValue("databasePath", dbPath)) { LOG_INFO("'databasePath' not found in the configuration file, using default: " << dbPath << " and adding this to the configuration file.") config.getRoot().add("databasePath", libconfig::Setting::TypeString)=dbPath; } WatcherdPtr theWatcherDaemon(new Watcherd); try { theWatcherDaemon->run(address, port, (int)numThreads); } catch (std::exception &e) { LOG_FATAL("Caught exception in main(): " << e.what()); std::cerr << "exception: " << e.what() << "\n"; } // Save any configuration changes made during the run. LOG_INFO("Saving last known configuration to " << configFilename); SingletonConfig::lock(); config.writeFile(configFilename.c_str()); return 0; } #endif // !defined(_WIN32) <|endoftext|>
<commit_before>#include "customuploader.hpp" #include <QApplication> #include <QBuffer> #include <QClipboard> #include <QFile> #include <QHttpMultiPart> #include <QJsonArray> #include <QJsonDocument> #include <QNetworkReply> #include <formats.hpp> #include <io/ioutils.hpp> #include <notifications.hpp> using formats::normalFormatFromName; using formats::normalFormatMIME; using formats::recordingFormatFromName; using formats::recordingFormatMIME; using std::runtime_error; void error(QString absFilePath, QString err) { throw runtime_error((QString("Invalid file: ").append(absFilePath) + ": " + err).toStdString()); } CustomUploader::CustomUploader(QString absFilePath) { // Let's go QFile file(absFilePath); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) error(absFilePath, file.errorString()); QJsonDocument doc = QJsonDocument::fromJson(file.readAll()); if (!doc.isObject()) { error(absFilePath, "Root not an object"); } QJsonObject obj = doc.object(); if (!obj["name"].isString()) error(absFilePath, "name is not a string"); else uName = obj["name"].toString(); if (!obj.contains("desc")) { if (!obj["desc"].isString()) /*t*/ error(absFilePath, "desc not a string"); else desc = obj["desc"].toString(); } else desc = absFilePath; QJsonValue m = obj["method"]; if (!m.isUndefined() && !m.isNull()) { if (!m.isString()) error(absFilePath, "method not a string"); QString toCheck = m.toString().toLower(); if (toCheck == "post") method = HttpMethod::POST; else error(absFilePath, "method invalid"); } QJsonValue url = obj["target"]; if (!url.isString()) { error(absFilePath, "target missing"); } QUrl target(url.toString()); if (!target.isValid()) error(absFilePath, "target not URL"); this->target = target; QJsonValue formatValue = obj["format"]; if (!formatValue.isUndefined() && !formatValue.isNull()) { if (formatValue.isString()) { QString formatString = formatValue.toString().toLower(); if (formatString == "x-www-form-urlencoded") rFormat = RequestFormat::X_WWW_FORM_URLENCODED; else if (formatString == "json") rFormat = RequestFormat::JSON; else if (formatString == "plain") rFormat = RequestFormat::PLAIN; else if (formatString == "multipart-form-data") rFormat = RequestFormat::MULTIPART_FORM_DATA; else error(absFilePath, "format invalid"); } } else error(absFilePath, "format provided but not string"); QJsonValue bodyValue = obj["body"]; if (rFormat != RequestFormat::PLAIN) { if (bodyValue.isUndefined()) error(absFilePath, "body not set"); if (rFormat == RequestFormat::MULTIPART_FORM_DATA) { if (bodyValue.isArray()) { for (QJsonValue val : bodyValue.toArray()) { if (!val.isObject()) error(absFilePath, "all elements of body must be objects"); if (!val.toObject()["body"].isObject() && !val.toObject().value("body").isString()) error(absFilePath, "all parts must have a body which is object or string!"); QJsonObject vo = val.toObject(); for (auto v : vo["body"].toObject()) if (!v.isObject() && !v.isString()) error(absFilePath, "all parts of body must be string or object"); for (auto v : vo.keys()) if (v.startsWith("__") && !vo[v].isString()) error(absFilePath, "all __headers must be strings"); } body = bodyValue; } else error(absFilePath, "body not array (needed for multipart)"); } else { if (bodyValue.isObject()) body = bodyValue; else error(absFilePath, "body not object"); } } else { if (bodyValue.isString()) { body = bodyValue; } else error(absFilePath, "body not string (reason: format: PLAIN)"); } QJsonValue headerVal = obj["headers"]; if (!(headerVal.isUndefined() || headerVal.isNull())) { if (!headerVal.isObject()) error(absFilePath, "headers must be object"); headers = headerVal.toObject(); } else headers = QJsonObject(); QJsonValue returnPsVal = obj["return"]; if (returnPsVal.isString()) { returnPathspec = returnPsVal.toString(); } else error(absFilePath, "return invalid"); QJsonValue fileLimit = obj["fileLimit"]; if (!fileLimit.isNull() && !fileLimit.isUndefined()) { if (!fileLimit.isDouble()) error(absFilePath, "fileLimit not double"); limit = fileLimit.toDouble(); } QJsonValue bool64 = obj["base64"]; if (!bool64.isNull() && !bool64.isUndefined()) { if (!bool64.isBool()) error(absFilePath, "base64 must be boolean"); base64 = bool64.toBool(); if (rFormat == RequestFormat::JSON && !base64) error(absFilePath, "base64 required with json"); } } QString CustomUploader::name() { return uName; } QString CustomUploader::description() { return desc; } QString getCType(RequestFormat format, QString plainType) { switch (format) { case RequestFormat::X_WWW_FORM_URLENCODED: return "application/x-www-form-urlencoded"; case RequestFormat::JSON: return "application/json"; case RequestFormat::MULTIPART_FORM_DATA: return "multipart/form-data"; case RequestFormat::PLAIN: return plainType; } return plainType; } QList<QPair<QString, QString>> getHeaders(QJsonObject h, QString imageFormat, RequestFormat format) { QList<QPair<QString, QString>> headers; for (QString s : h.keys()) { if (s.toLower() == "content-type") continue; QJsonValue v = h[s]; if (!v.isString()) headers << QPair<QString, QString>(s, QJsonDocument::fromVariant(v.toVariant()).toJson()); else headers << QPair<QString, QString>(s, v.toString()); } headers << QPair<QString, QString>("Content-Type", getCType(format, normalFormatMIME(normalFormatFromName(imageFormat)))); return headers; } QJsonObject recurseAndReplace(QJsonObject &body, QByteArray &data, QString contentType) { QJsonObject o; for (QString s : body.keys()) { QJsonValue v = body[s]; if (v.isObject()) { QJsonObject vo = v.toObject(); o.insert(s, recurseAndReplace(vo, data, contentType)); } else if (v.isString()) { QString str = v.toString(); if (str.startsWith("/") && str.endsWith("/")) { o.insert(s, str.mid(1, str.length() - 2).replace("%imagedata", data).replace("%contenttype", contentType)); } else o.insert(s, v); } else o.insert(s, v); } return o; } QString parsePathspec(QJsonDocument &response, QString &pathspec) { if (!pathspec.startsWith(".")) { // Does not point to anything return ""; } else { if (!response.isObject()) return ""; QStringList fields = pathspec.right(pathspec.length() - 1).split('.', QString::SkipEmptyParts); QJsonObject o = response.object(); if (pathspec == ".") { return QString::fromUtf8(response.toJson()); } QJsonValue val = o[fields.at(0)]; if (val.isUndefined() || val.isNull()) return ""; else if (val.isString()) return val.toString(); else if (!val.isObject()) return QString::fromUtf8(QJsonDocument::fromVariant(val.toVariant()).toJson()); for (int i = 1; i < fields.size(); i++) { if (val.isUndefined() || val.isNull()) return ""; else if (val.isString()) return val.toString(); else if (!val.isObject()) return QString::fromUtf8(QJsonDocument::fromVariant(val.toVariant()).toJson()); else val = val.toObject()[fields.at(i)]; } if (val.isUndefined() || val.isNull()) return ""; else if (val.isString()) return val.toString(); else if (!val.isObject()) return QString::fromUtf8(QJsonDocument::fromVariant(val.toVariant()).toJson()); } return ""; } void parseResult(QJsonDocument result, QByteArray data, QString returnPathspec, QString name) { if (result.isObject()) { qDebug() << result.object()[".url"]; QString url = parsePathspec(result, returnPathspec); if (!url.isEmpty()) { QApplication::clipboard()->setText(url); notifications::notify("KShare Custom Uploader " + name, "Copied upload link to clipboard!"); } else { notifications::notify("KShare Custom Uploader " + name, "Upload done, but result empty!"); QApplication::clipboard()->setText(data); } } else { notifications::notify("KShare Custom Uploader " + name, "Upload done, but result is not JSON Object! Result in clipboard."); QApplication::clipboard()->setText(data); } } void CustomUploader::doUpload(QByteArray imgData, QString format) { auto h = getHeaders(headers, format, this->rFormat); QByteArray data; if (base64) imgData = imgData.toBase64(); QString mime = normalFormatMIME(normalFormatFromName(format)); if (mime.isEmpty()) mime = recordingFormatMIME(recordingFormatFromName(format)); switch (this->rFormat) { case RequestFormat::PLAIN: { data = imgData; } break; case RequestFormat::JSON: { if (body.isString()) { QStringList split = body.toString().replace("%contenttype", mime).split("%imagedata"); for (int i = 0; i < split.size(); i++) { data.append(split[i]); if (i < split.size() - 1) data.append(imgData); } } else { QJsonObject vo = body.toObject(); data = QJsonDocument::fromVariant(recurseAndReplace(vo, imgData, mime).toVariantMap()).toJson(); } } break; case RequestFormat::X_WWW_FORM_URLENCODED: { QJsonObject body = this->body.toObject(); for (QString key : body.keys()) { QJsonValue val = body[key]; if (val.isString()) { QString str = val.toString(); QByteArray strB; if (str.startsWith("/") && str.endsWith("/")) { str = str.mid(1, str.length() - 2); QStringList split = str.replace("%contenttype", mime).split("%imagedata"); for (int i = 0; i < split.size(); i++) { strB.append(split[i]); if (i < split.size() - 1) strB.append(imgData); } } data.append(QUrl::toPercentEncoding(key)).append('=').append(strB); } else { if (!data.isEmpty()) data.append('&'); data.append(QUrl::toPercentEncoding(key)) .append('=') .append(QUrl::toPercentEncoding(QJsonDocument::fromVariant(body[key].toVariant()).toJson())); } } } break; case RequestFormat::MULTIPART_FORM_DATA: { QHttpMultiPart *multipart = new QHttpMultiPart(QHttpMultiPart::FormDataType); auto arr = body.toArray(); for (QJsonValue val : arr) { auto valo = val.toObject(); QHttpPart part; QJsonValue bd = valo["body"]; if (bd.isString()) { QString s = bd.toString(); QByteArray body; if (s.startsWith("/") && s.endsWith("/")) { s = s.mid(1, s.length() - 1); QStringList split = s.replace("%contenttype", mime).split("%imagedata"); for (int i = 0; i < split.size(); i++) { body.append(split[i]); if (i < split.size() - 1) body.append(imgData); } } QBuffer *buffer = new QBuffer(&imgData); buffer->open(QIODevice::ReadOnly); part.setBodyDevice(buffer); multipart->append(part); } else { auto bdo = bd.toObject(); QJsonObject result = recurseAndReplace(bdo, imgData, mime); part.setBody(QJsonDocument::fromVariant(result.toVariantMap()).toJson()); multipart->append(part); } for (QString headerVal : valo.keys()) { QString str = valo[headerVal].toString(); if (str.startsWith("/") && str.endsWith("/")) str = str.mid(1, str.length() - 1).replace("%contenttype", mime); part.setRawHeader(headerVal.toLatin1(), str.toLatin1()); } } switch (method) { case HttpMethod::POST: if (returnPathspec == "|") { ioutils::postMultipartData(target, h, multipart, [&](QByteArray result, QNetworkReply *) { QApplication::clipboard()->setText(QString::fromUtf8(result)); notifications::notify("KShare Custom Uploader " + name(), "Copied upload result to clipboard!"); }); } else { ioutils::postMultipart(target, h, multipart, [&](QJsonDocument result, QByteArray data, QNetworkReply *) { parseResult(result, data, returnPathspec, name()); }); } break; } return; } break; } if (limit > 0 && data.size() > limit) { notifications::notify("KShare Custom Uploader " + name(), "File limit exceeded!"); return; } switch (method) { case HttpMethod::POST: if (returnPathspec == "|") { ioutils::postData(target, h, data, [&](QByteArray result, QNetworkReply *) { QApplication::clipboard()->setText(QString::fromUtf8(result)); notifications::notify("KShare Custom Uploader " + name(), "Copied upload result to clipboard!"); }); } else { ioutils::postJson(target, h, data, [&](QJsonDocument result, QByteArray data, QNetworkReply *) { parseResult(result, data, returnPathspec, name()); }); } break; } } <commit_msg>Oops fix header processing for multipart<commit_after>#include "customuploader.hpp" #include <QApplication> #include <QBuffer> #include <QClipboard> #include <QFile> #include <QHttpMultiPart> #include <QJsonArray> #include <QJsonDocument> #include <QNetworkReply> #include <formats.hpp> #include <io/ioutils.hpp> #include <notifications.hpp> using formats::normalFormatFromName; using formats::normalFormatMIME; using formats::recordingFormatFromName; using formats::recordingFormatMIME; using std::runtime_error; void error(QString absFilePath, QString err) { throw runtime_error((QString("Invalid file: ").append(absFilePath) + ": " + err).toStdString()); } CustomUploader::CustomUploader(QString absFilePath) { // Let's go QFile file(absFilePath); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) error(absFilePath, file.errorString()); QJsonDocument doc = QJsonDocument::fromJson(file.readAll()); if (!doc.isObject()) { error(absFilePath, "Root not an object"); } QJsonObject obj = doc.object(); if (!obj["name"].isString()) error(absFilePath, "name is not a string"); else uName = obj["name"].toString(); if (!obj.contains("desc")) { if (!obj["desc"].isString()) /*t*/ error(absFilePath, "desc not a string"); else desc = obj["desc"].toString(); } else desc = absFilePath; QJsonValue m = obj["method"]; if (!m.isUndefined() && !m.isNull()) { if (!m.isString()) error(absFilePath, "method not a string"); QString toCheck = m.toString().toLower(); if (toCheck == "post") method = HttpMethod::POST; else error(absFilePath, "method invalid"); } QJsonValue url = obj["target"]; if (!url.isString()) { error(absFilePath, "target missing"); } QUrl target(url.toString()); if (!target.isValid()) error(absFilePath, "target not URL"); this->target = target; QJsonValue formatValue = obj["format"]; if (!formatValue.isUndefined() && !formatValue.isNull()) { if (formatValue.isString()) { QString formatString = formatValue.toString().toLower(); if (formatString == "x-www-form-urlencoded") rFormat = RequestFormat::X_WWW_FORM_URLENCODED; else if (formatString == "json") rFormat = RequestFormat::JSON; else if (formatString == "plain") rFormat = RequestFormat::PLAIN; else if (formatString == "multipart-form-data") rFormat = RequestFormat::MULTIPART_FORM_DATA; else error(absFilePath, "format invalid"); } } else error(absFilePath, "format provided but not string"); QJsonValue bodyValue = obj["body"]; if (rFormat != RequestFormat::PLAIN) { if (bodyValue.isUndefined()) error(absFilePath, "body not set"); if (rFormat == RequestFormat::MULTIPART_FORM_DATA) { if (bodyValue.isArray()) { for (QJsonValue val : bodyValue.toArray()) { if (!val.isObject()) error(absFilePath, "all elements of body must be objects"); if (!val.toObject()["body"].isObject() && !val.toObject().value("body").isString()) error(absFilePath, "all parts must have a body which is object or string!"); QJsonObject vo = val.toObject(); for (auto v : vo["body"].toObject()) if (!v.isObject() && !v.isString()) error(absFilePath, "all parts of body must be string or object"); for (auto v : vo.keys()) if (v.startsWith("__") && !vo[v].isString()) error(absFilePath, "all __headers must be strings"); } body = bodyValue; } else error(absFilePath, "body not array (needed for multipart)"); } else { if (bodyValue.isObject()) body = bodyValue; else error(absFilePath, "body not object"); } } else { if (bodyValue.isString()) { body = bodyValue; } else error(absFilePath, "body not string (reason: format: PLAIN)"); } QJsonValue headerVal = obj["headers"]; if (!(headerVal.isUndefined() || headerVal.isNull())) { if (!headerVal.isObject()) error(absFilePath, "headers must be object"); headers = headerVal.toObject(); } else headers = QJsonObject(); QJsonValue returnPsVal = obj["return"]; if (returnPsVal.isString()) { returnPathspec = returnPsVal.toString(); } else error(absFilePath, "return invalid"); QJsonValue fileLimit = obj["fileLimit"]; if (!fileLimit.isNull() && !fileLimit.isUndefined()) { if (!fileLimit.isDouble()) error(absFilePath, "fileLimit not double"); limit = fileLimit.toDouble(); } QJsonValue bool64 = obj["base64"]; if (!bool64.isNull() && !bool64.isUndefined()) { if (!bool64.isBool()) error(absFilePath, "base64 must be boolean"); base64 = bool64.toBool(); if (rFormat == RequestFormat::JSON && !base64) error(absFilePath, "base64 required with json"); } } QString CustomUploader::name() { return uName; } QString CustomUploader::description() { return desc; } QString getCType(RequestFormat format, QString plainType) { switch (format) { case RequestFormat::X_WWW_FORM_URLENCODED: return "application/x-www-form-urlencoded"; case RequestFormat::JSON: return "application/json"; case RequestFormat::MULTIPART_FORM_DATA: return "multipart/form-data"; case RequestFormat::PLAIN: return plainType; } return plainType; } QList<QPair<QString, QString>> getHeaders(QJsonObject h, QString imageFormat, RequestFormat format) { QList<QPair<QString, QString>> headers; for (QString s : h.keys()) { if (s.toLower() == "content-type") continue; QJsonValue v = h[s]; if (!v.isString()) headers << QPair<QString, QString>(s, QJsonDocument::fromVariant(v.toVariant()).toJson()); else headers << QPair<QString, QString>(s, v.toString()); } headers << QPair<QString, QString>("Content-Type", getCType(format, normalFormatMIME(normalFormatFromName(imageFormat)))); return headers; } QJsonObject recurseAndReplace(QJsonObject &body, QByteArray &data, QString contentType) { QJsonObject o; for (QString s : body.keys()) { QJsonValue v = body[s]; if (v.isObject()) { QJsonObject vo = v.toObject(); o.insert(s, recurseAndReplace(vo, data, contentType)); } else if (v.isString()) { QString str = v.toString(); if (str.startsWith("/") && str.endsWith("/")) { o.insert(s, str.mid(1, str.length() - 2).replace("%imagedata", data).replace("%contenttype", contentType)); } else o.insert(s, v); } else o.insert(s, v); } return o; } QString parsePathspec(QJsonDocument &response, QString &pathspec) { if (!pathspec.startsWith(".")) { // Does not point to anything return ""; } else { if (!response.isObject()) return ""; QStringList fields = pathspec.right(pathspec.length() - 1).split('.', QString::SkipEmptyParts); QJsonObject o = response.object(); if (pathspec == ".") { return QString::fromUtf8(response.toJson()); } QJsonValue val = o[fields.at(0)]; if (val.isUndefined() || val.isNull()) return ""; else if (val.isString()) return val.toString(); else if (!val.isObject()) return QString::fromUtf8(QJsonDocument::fromVariant(val.toVariant()).toJson()); for (int i = 1; i < fields.size(); i++) { if (val.isUndefined() || val.isNull()) return ""; else if (val.isString()) return val.toString(); else if (!val.isObject()) return QString::fromUtf8(QJsonDocument::fromVariant(val.toVariant()).toJson()); else val = val.toObject()[fields.at(i)]; } if (val.isUndefined() || val.isNull()) return ""; else if (val.isString()) return val.toString(); else if (!val.isObject()) return QString::fromUtf8(QJsonDocument::fromVariant(val.toVariant()).toJson()); } return ""; } void parseResult(QJsonDocument result, QByteArray data, QString returnPathspec, QString name) { if (result.isObject()) { qDebug() << result.object()[".url"]; QString url = parsePathspec(result, returnPathspec); if (!url.isEmpty()) { QApplication::clipboard()->setText(url); notifications::notify("KShare Custom Uploader " + name, "Copied upload link to clipboard!"); } else { notifications::notify("KShare Custom Uploader " + name, "Upload done, but result empty!"); QApplication::clipboard()->setText(data); } } else { notifications::notify("KShare Custom Uploader " + name, "Upload done, but result is not JSON Object! Result in clipboard."); QApplication::clipboard()->setText(data); } } void CustomUploader::doUpload(QByteArray imgData, QString format) { auto h = getHeaders(headers, format, this->rFormat); QByteArray data; if (base64) imgData = imgData.toBase64(); QString mime = normalFormatMIME(normalFormatFromName(format)); if (mime.isEmpty()) mime = recordingFormatMIME(recordingFormatFromName(format)); switch (this->rFormat) { case RequestFormat::PLAIN: { data = imgData; } break; case RequestFormat::JSON: { if (body.isString()) { QStringList split = body.toString().replace("%contenttype", mime).split("%imagedata"); for (int i = 0; i < split.size(); i++) { data.append(split[i]); if (i < split.size() - 1) data.append(imgData); } } else { QJsonObject vo = body.toObject(); data = QJsonDocument::fromVariant(recurseAndReplace(vo, imgData, mime).toVariantMap()).toJson(); } } break; case RequestFormat::X_WWW_FORM_URLENCODED: { QJsonObject body = this->body.toObject(); for (QString key : body.keys()) { QJsonValue val = body[key]; if (val.isString()) { QString str = val.toString(); QByteArray strB; if (str.startsWith("/") && str.endsWith("/")) { str = str.mid(1, str.length() - 2); QStringList split = str.replace("%contenttype", mime).split("%imagedata"); for (int i = 0; i < split.size(); i++) { strB.append(split[i]); if (i < split.size() - 1) strB.append(imgData); } } data.append(QUrl::toPercentEncoding(key)).append('=').append(strB); } else { if (!data.isEmpty()) data.append('&'); data.append(QUrl::toPercentEncoding(key)) .append('=') .append(QUrl::toPercentEncoding(QJsonDocument::fromVariant(body[key].toVariant()).toJson())); } } } break; case RequestFormat::MULTIPART_FORM_DATA: { QHttpMultiPart *multipart = new QHttpMultiPart(QHttpMultiPart::FormDataType); auto arr = body.toArray(); for (QJsonValue val : arr) { auto valo = val.toObject(); QHttpPart part; QJsonValue bd = valo["body"]; if (bd.isString()) { QString s = bd.toString(); QByteArray body; if (s.startsWith("/") && s.endsWith("/")) { s = s.mid(1, s.length() - 1); QStringList split = s.replace("%contenttype", mime).split("%imagedata"); for (int i = 0; i < split.size(); i++) { body.append(split[i]); if (i < split.size() - 1) body.append(imgData); } } QBuffer *buffer = new QBuffer(&imgData); buffer->open(QIODevice::ReadOnly); part.setBodyDevice(buffer); multipart->append(part); } else { auto bdo = bd.toObject(); QJsonObject result = recurseAndReplace(bdo, imgData, mime); part.setBody(QJsonDocument::fromVariant(result.toVariantMap()).toJson()); multipart->append(part); } for (QString headerVal : valo.keys()) { if (headerVal.startsWith("__")) { headerVal = headerVal.mid(2); QString str = valo[headerVal].toString(); if (str.startsWith("/") && str.endsWith("/")) str = str.mid(1, str.length() - 1).replace("%contenttype", mime); part.setRawHeader(headerVal.toLatin1(), str.toLatin1()); } } } switch (method) { case HttpMethod::POST: if (returnPathspec == "|") { ioutils::postMultipartData(target, h, multipart, [&](QByteArray result, QNetworkReply *) { QApplication::clipboard()->setText(QString::fromUtf8(result)); notifications::notify("KShare Custom Uploader " + name(), "Copied upload result to clipboard!"); }); } else { ioutils::postMultipart(target, h, multipart, [&](QJsonDocument result, QByteArray data, QNetworkReply *) { parseResult(result, data, returnPathspec, name()); }); } break; } return; } break; } if (limit > 0 && data.size() > limit) { notifications::notify("KShare Custom Uploader " + name(), "File limit exceeded!"); return; } switch (method) { case HttpMethod::POST: if (returnPathspec == "|") { ioutils::postData(target, h, data, [&](QByteArray result, QNetworkReply *) { QApplication::clipboard()->setText(QString::fromUtf8(result)); notifications::notify("KShare Custom Uploader " + name(), "Copied upload result to clipboard!"); }); } else { ioutils::postJson(target, h, data, [&](QJsonDocument result, QByteArray data, QNetworkReply *) { parseResult(result, data, returnPathspec, name()); }); } break; } } <|endoftext|>
<commit_before>/* * AscEmu Framework based on ArcEmu MMORPG Server * Copyright (C) 2014-2016 AscEmu Team <http://www.ascemu.org/> * Copyright (C) 2008-2012 ArcEmu Team <http://www.ArcEmu.org/> * Copyright (C) 2005-2007 Ascent Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "StdAfx.h" #include <Common.h> #include <Network/Network.h> #include <Config/ConfigEnv.h> #include <git_version.h> #include "BaseConsole.h" #include "ConsoleCommands.h" #define LOCAL_BUFFER_SIZE 2048 #define ENABLE_REMOTE_CONSOLE 1 enum STATES { STATE_USER = 1, STATE_PASSWORD = 2, STATE_LOGGED = 3, STATE_WAITING = 4 }; class ConsoleSocket : public Socket { RemoteConsole* m_pConsole; char* m_pBuffer; uint32 m_pBufferLen; uint32 m_pBufferPos; uint32 m_state; std::string m_username; std::string m_password; uint32 m_requestNo; uint8 m_failedLogins; public: ConsoleSocket(SOCKET iFd); ~ConsoleSocket(); void OnRead(); void OnDisconnect(); void OnConnect(); void TryAuthenticate(); void AuthCallback(bool result); }; class ConsoleAuthMgr : public Singleton < ConsoleAuthMgr > { Mutex authmgrlock; uint32 highrequestid; std::map<uint32, ConsoleSocket*> requestmap; public: ConsoleAuthMgr() { highrequestid = 1; } uint32 GenerateRequestId() { uint32 n; authmgrlock.Acquire(); n = highrequestid++; authmgrlock.Release(); return n; } void SetRequest(uint32 id, ConsoleSocket* sock) { authmgrlock.Acquire(); if (sock == NULL) requestmap.erase(id); else requestmap.insert(std::make_pair(id, sock)); authmgrlock.Release(); } ConsoleSocket* GetRequest(uint32 id) { ConsoleSocket* rtn; authmgrlock.Acquire(); std::map<uint32, ConsoleSocket*>::iterator itr = requestmap.find(id); if (itr == requestmap.end()) rtn = NULL; else rtn = itr->second; authmgrlock.Release(); return rtn; } }; ListenSocket<ConsoleSocket> * g_pListenSocket = NULL; initialiseSingleton(ConsoleAuthMgr); void ConsoleAuthCallback(uint32 request, uint32 result) { ConsoleSocket* pSocket = ConsoleAuthMgr::getSingleton().GetRequest(request); if (pSocket == NULL || !pSocket->IsConnected()) return; if (result) pSocket->AuthCallback(true); else pSocket->AuthCallback(false); } void CloseConsoleListener() { if (g_pListenSocket != NULL) g_pListenSocket->Close(); } bool StartConsoleListener() { #ifndef ENABLE_REMOTE_CONSOLE return false; #else std::string lhost = Config.MainConfig.GetStringDefault("RemoteConsole", "Host", "0.0.0.0"); uint32 lport = Config.MainConfig.GetIntDefault("RemoteConsole", "Port", 8092); bool enabled = Config.MainConfig.GetBoolDefault("RemoteConsole", "Enabled", false); if (!enabled) return false; g_pListenSocket = new ListenSocket<ConsoleSocket>(lhost.c_str(), lport); if (g_pListenSocket == NULL) return false; if (!g_pListenSocket->IsOpen()) { g_pListenSocket->Close(); delete g_pListenSocket; g_pListenSocket = NULL; return false; } new ConsoleAuthMgr; return true; #endif } ThreadBase* GetConsoleListener() { return (ThreadBase*)g_pListenSocket; } ConsoleSocket::ConsoleSocket(SOCKET iFd) : Socket(iFd, 10000, 1000) { m_pBufferLen = LOCAL_BUFFER_SIZE; m_pBufferPos = 0; m_pBuffer = new char[LOCAL_BUFFER_SIZE]; m_pConsole = new RemoteConsole(this); m_state = STATE_USER; m_failedLogins = 0; m_requestNo = 0; } ConsoleSocket::~ConsoleSocket() { if (m_pBuffer != NULL) delete[] m_pBuffer; if (m_pConsole != NULL) delete m_pConsole; if (m_requestNo) { ConsoleAuthMgr::getSingleton().SetRequest(m_requestNo, NULL); m_requestNo = 0; } } void TestConsoleLogin(std::string & username, std::string & password, uint32 requestid); void ConsoleSocket::OnRead() { uint32 readlen = (uint32)readBuffer.GetSize(); uint32 len; char* p; if ((readlen + m_pBufferPos) >= m_pBufferLen) { Disconnect(); return; } readBuffer.Read((uint8*)&m_pBuffer[m_pBufferPos], readlen); m_pBufferPos += readlen; // let's look for any newline bytes. p = strchr(m_pBuffer, '\n'); while (p != NULL) { // windows is stupid. :P len = (uint32)((p + 1) - m_pBuffer); if (*(p - 1) == '\r') *(p - 1) = '\0'; *p = '\0'; // handle the command if (*m_pBuffer != '\0') { switch (m_state) { case STATE_USER: m_username = std::string(m_pBuffer); m_pConsole->Write("password: "); m_state = STATE_PASSWORD; break; case STATE_PASSWORD: m_password = std::string(m_pBuffer); m_pConsole->Write("\r\nAttempting to authenticate. Please wait.\r\n"); m_state = STATE_WAITING; m_requestNo = ConsoleAuthMgr::getSingleton().GenerateRequestId(); ConsoleAuthMgr::getSingleton().SetRequest(m_requestNo, this); TestConsoleLogin(m_username, m_password, m_requestNo); break; case STATE_LOGGED: if (!strnicmp(m_pBuffer, "quit", 4)) { Disconnect(); break; } HandleConsoleInput(m_pConsole, m_pBuffer); break; } } // move the bytes back if (len == m_pBufferPos) { m_pBuffer[0] = '\0'; m_pBufferPos = 0; } else { memcpy(m_pBuffer, &m_pBuffer[len], m_pBufferPos - len); m_pBufferPos -= len; } p = strchr(m_pBuffer, '\n'); } } void ConsoleSocket::OnConnect() { m_pConsole->Write("Welcome to AscEmu's Remote Administration Console.\r\n"); m_pConsole->Write("Please authenticate to continue. \r\n\r\n"); m_pConsole->Write("login: "); } void ConsoleSocket::OnDisconnect() { if (m_requestNo) { ConsoleAuthMgr::getSingleton().SetRequest(m_requestNo, NULL); m_requestNo = 0; } if (m_state == STATE_LOGGED) { Log.Notice("RemoteConsole", "User `%s` disconnected.", m_username.c_str()); } } void ConsoleSocket::AuthCallback(bool result) { ConsoleAuthMgr::getSingleton().SetRequest(m_requestNo, NULL); m_requestNo = 0; if (!result) { m_pConsole->Write("Authentication failed.\r\n\r\n"); m_failedLogins++; if (m_failedLogins < 3) { m_pConsole->Write("login: "); m_state = STATE_USER; } else { Disconnect(); } } else { m_pConsole->Write("User `%s` authenticated.\r\n\r\n", m_username.c_str()); Log.Notice("RemoteConsole", "User `%s` authenticated.", m_username.c_str()); const char* argv[1]; HandleInfoCommand(m_pConsole, 1, argv); m_pConsole->Write("Type ? to see commands, quit to end session.\r\n"); m_state = STATE_LOGGED; } } RemoteConsole::RemoteConsole(ConsoleSocket* pSocket) { m_pSocket = pSocket; } void RemoteConsole::Write(const char* Format, ...) { char obuf[65536]; va_list ap; va_start(ap, Format); vsnprintf(obuf, 65536, Format, ap); va_end(ap); if (*obuf == '\0') return; m_pSocket->Send((const uint8*)obuf, (uint32)strlen(obuf)); } struct ConsoleCommand { bool(*CommandPointer)(BaseConsole*, int, const char*[]); const char* Name; // 10 chars const char* ArgumentFormat; // 30 chars const char* Description; // 40 chars // = 70 chars }; void HandleConsoleInput(BaseConsole* pConsole, const char* szInput) { static ConsoleCommand Commands[] = { { &HandleAnnounceCommand, "a", "<announce string>", "Shows the message in all client chat boxes." }, { &HandleAnnounceCommand, "announce", "<announce string>", "Shows the message in all client chat boxes." }, { &HandleBanAccountCommand, "ban", "<account> <timeperiod> [reason]", "Bans account x for time y." }, { &HandleBanAccountCommand, "banaccount", "<account> <timeperiod> [reason]", "Bans account x for time y." }, { &HandleCancelCommand, "cancel", "None", "Cancels a pending shutdown." }, { &HandleInfoCommand, "info", "None", "Gives server runtime information." }, { &HandleNetworkStatusCommand, "netstatus", "none", "Shows network status." }, { &HandleGMsCommand, "gms", "None", "Shows online GMs." }, { &HandleKickCommand, "kick", "<Player Name> <reason>", "Kicks player x for reason y." }, { &HandleMOTDCommand, "getmotd", "None", "View the current MOTD" }, { &HandleMOTDCommand, "setmotd", "<new motd>", "Sets a new MOTD" }, { &HandleOnlinePlayersCommand, "online", "None", "Shows online players." }, { &HandlePlayerInfoCommand, "playerinfo", "<Player Name>", "Shows information about a player." }, { &HandleShutDownCommand, "exit", "[delay]", "Shuts down server with optional delay in seconds." }, { &HandleShutDownCommand, "shutdown", "[delay]", "Shuts down server with optional delay in seconds." }, { &HandleRehashCommand, "rehash", "None", "Reloads the config file" }, { &HandleUnbanAccountCommand, "unban", "<account>", "Unbans account x." }, { &HandleUnbanAccountCommand, "unbanaccount", "<account>", "Unbans account x." }, { &HandleWAnnounceCommand, "w", "<wannounce string>", "Shows the message in all client title areas." }, { &HandleWAnnounceCommand, "wannounce", "<wannounce string>", "Shows the message in all client title areas." }, { &HandleWhisperCommand, "whisper", "<player> <message>", "Whispers a message to someone from the console." }, { &HandleNameHashCommand, "getnamehash", "<text>", "Returns the crc32 hash of <text>" }, { &HandleRevivePlayer, "reviveplr", "<name>", "Revives a Player" }, { &HandleClearConsoleCommand, "clear", "None", "Clears the console screen." }, { &HandleReloadConsoleCommand, "reload", "<Table>", "Reloads a table from the world database." }, { &HandleScriptEngineReloadCommand, "reloadscripts", "<NULL>", "Reloads all scripting engines currently loaded." }, { &HandleTimeDateCommand, "datetime", "<NULL>", "Shows time and date according to localtime()" }, { NULL, NULL, NULL, NULL }, }; uint32 i; char* p, *q = nullptr; // let's tokenize into arguments. std::vector<const char*> tokens; q = (char*)szInput; p = strchr(q, ' '); while (p != nullptr) { *p = 0; tokens.push_back(q); q = p + 1; p = strchr(q, ' '); } if (q != NULL && *q != '\0') tokens.push_back(q); if (tokens.empty()) return; if (!stricmp(tokens[0], "help") || tokens[0][0] == '?') { if (tokens.size() > 1) { for (i = 0; Commands[i].Name != NULL; ++i) { if (!stricmp(Commands[i].Name, tokens[1])) { pConsole->Write("Command: %s\r\n" "Arguments: %s\r\n" "Description: %s\r\n", Commands[i].Name, Commands[i].ArgumentFormat, Commands[i].Description); return; } } } pConsole->Write("===============================================================================\r\n"); pConsole->Write("| %15s | %57s |\r\n", "Name", "Arguments"); pConsole->Write("===============================================================================\r\n"); for (i = 0; Commands[i].Name != NULL; ++i) { pConsole->Write("| %15s | %57s |\r\n", Commands[i].Name, Commands[i].ArgumentFormat); } pConsole->Write("===============================================================================\r\n"); pConsole->Write("| type 'quit' to terminate a Remote Console Session |\r\n"); pConsole->Write("===============================================================================\r\n"); } else { for (i = 0; Commands[i].Name != NULL; ++i) { if (!stricmp(Commands[i].Name, tokens[0])) { if (!Commands[i].CommandPointer(pConsole, (int)tokens.size(), &tokens[0])) { pConsole->Write("[!]Error, '%s' used an incorrect syntax, the correct syntax is: '%s'.\r\n\r\n", Commands[i].Name, Commands[i].ArgumentFormat); return; } else return; } } pConsole->Write("[!]Error, Command '%s' doesn't exist. Type '?' or 'help' to get a command overview.\r\n\r\n", tokens[0]); } } void LocalConsole::Write(const char* Format, ...) { va_list ap; va_start(ap, Format); vprintf(Format, ap); va_end(ap); } <commit_msg>Resolve CID 53042 (Dereference before null check) Null-checking q suggests that it might be null....<commit_after>/* * AscEmu Framework based on ArcEmu MMORPG Server * Copyright (C) 2014-2016 AscEmu Team <http://www.ascemu.org/> * Copyright (C) 2008-2012 ArcEmu Team <http://www.ArcEmu.org/> * Copyright (C) 2005-2007 Ascent Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "StdAfx.h" #include <Common.h> #include <Network/Network.h> #include <Config/ConfigEnv.h> #include <git_version.h> #include "BaseConsole.h" #include "ConsoleCommands.h" #define LOCAL_BUFFER_SIZE 2048 #define ENABLE_REMOTE_CONSOLE 1 enum STATES { STATE_USER = 1, STATE_PASSWORD = 2, STATE_LOGGED = 3, STATE_WAITING = 4 }; class ConsoleSocket : public Socket { RemoteConsole* m_pConsole; char* m_pBuffer; uint32 m_pBufferLen; uint32 m_pBufferPos; uint32 m_state; std::string m_username; std::string m_password; uint32 m_requestNo; uint8 m_failedLogins; public: ConsoleSocket(SOCKET iFd); ~ConsoleSocket(); void OnRead(); void OnDisconnect(); void OnConnect(); void TryAuthenticate(); void AuthCallback(bool result); }; class ConsoleAuthMgr : public Singleton < ConsoleAuthMgr > { Mutex authmgrlock; uint32 highrequestid; std::map<uint32, ConsoleSocket*> requestmap; public: ConsoleAuthMgr() { highrequestid = 1; } uint32 GenerateRequestId() { uint32 n; authmgrlock.Acquire(); n = highrequestid++; authmgrlock.Release(); return n; } void SetRequest(uint32 id, ConsoleSocket* sock) { authmgrlock.Acquire(); if (sock == NULL) requestmap.erase(id); else requestmap.insert(std::make_pair(id, sock)); authmgrlock.Release(); } ConsoleSocket* GetRequest(uint32 id) { ConsoleSocket* rtn; authmgrlock.Acquire(); std::map<uint32, ConsoleSocket*>::iterator itr = requestmap.find(id); if (itr == requestmap.end()) rtn = NULL; else rtn = itr->second; authmgrlock.Release(); return rtn; } }; ListenSocket<ConsoleSocket> * g_pListenSocket = NULL; initialiseSingleton(ConsoleAuthMgr); void ConsoleAuthCallback(uint32 request, uint32 result) { ConsoleSocket* pSocket = ConsoleAuthMgr::getSingleton().GetRequest(request); if (pSocket == NULL || !pSocket->IsConnected()) return; if (result) pSocket->AuthCallback(true); else pSocket->AuthCallback(false); } void CloseConsoleListener() { if (g_pListenSocket != NULL) g_pListenSocket->Close(); } bool StartConsoleListener() { #ifndef ENABLE_REMOTE_CONSOLE return false; #else std::string lhost = Config.MainConfig.GetStringDefault("RemoteConsole", "Host", "0.0.0.0"); uint32 lport = Config.MainConfig.GetIntDefault("RemoteConsole", "Port", 8092); bool enabled = Config.MainConfig.GetBoolDefault("RemoteConsole", "Enabled", false); if (!enabled) return false; g_pListenSocket = new ListenSocket<ConsoleSocket>(lhost.c_str(), lport); if (g_pListenSocket == NULL) return false; if (!g_pListenSocket->IsOpen()) { g_pListenSocket->Close(); delete g_pListenSocket; g_pListenSocket = NULL; return false; } new ConsoleAuthMgr; return true; #endif } ThreadBase* GetConsoleListener() { return (ThreadBase*)g_pListenSocket; } ConsoleSocket::ConsoleSocket(SOCKET iFd) : Socket(iFd, 10000, 1000) { m_pBufferLen = LOCAL_BUFFER_SIZE; m_pBufferPos = 0; m_pBuffer = new char[LOCAL_BUFFER_SIZE]; m_pConsole = new RemoteConsole(this); m_state = STATE_USER; m_failedLogins = 0; m_requestNo = 0; } ConsoleSocket::~ConsoleSocket() { if (m_pBuffer != NULL) delete[] m_pBuffer; if (m_pConsole != NULL) delete m_pConsole; if (m_requestNo) { ConsoleAuthMgr::getSingleton().SetRequest(m_requestNo, NULL); m_requestNo = 0; } } void TestConsoleLogin(std::string & username, std::string & password, uint32 requestid); void ConsoleSocket::OnRead() { uint32 readlen = (uint32)readBuffer.GetSize(); uint32 len; char* p; if ((readlen + m_pBufferPos) >= m_pBufferLen) { Disconnect(); return; } readBuffer.Read((uint8*)&m_pBuffer[m_pBufferPos], readlen); m_pBufferPos += readlen; // let's look for any newline bytes. p = strchr(m_pBuffer, '\n'); while (p != NULL) { // windows is stupid. :P len = (uint32)((p + 1) - m_pBuffer); if (*(p - 1) == '\r') *(p - 1) = '\0'; *p = '\0'; // handle the command if (*m_pBuffer != '\0') { switch (m_state) { case STATE_USER: m_username = std::string(m_pBuffer); m_pConsole->Write("password: "); m_state = STATE_PASSWORD; break; case STATE_PASSWORD: m_password = std::string(m_pBuffer); m_pConsole->Write("\r\nAttempting to authenticate. Please wait.\r\n"); m_state = STATE_WAITING; m_requestNo = ConsoleAuthMgr::getSingleton().GenerateRequestId(); ConsoleAuthMgr::getSingleton().SetRequest(m_requestNo, this); TestConsoleLogin(m_username, m_password, m_requestNo); break; case STATE_LOGGED: if (!strnicmp(m_pBuffer, "quit", 4)) { Disconnect(); break; } HandleConsoleInput(m_pConsole, m_pBuffer); break; } } // move the bytes back if (len == m_pBufferPos) { m_pBuffer[0] = '\0'; m_pBufferPos = 0; } else { memcpy(m_pBuffer, &m_pBuffer[len], m_pBufferPos - len); m_pBufferPos -= len; } p = strchr(m_pBuffer, '\n'); } } void ConsoleSocket::OnConnect() { m_pConsole->Write("Welcome to AscEmu's Remote Administration Console.\r\n"); m_pConsole->Write("Please authenticate to continue. \r\n\r\n"); m_pConsole->Write("login: "); } void ConsoleSocket::OnDisconnect() { if (m_requestNo) { ConsoleAuthMgr::getSingleton().SetRequest(m_requestNo, NULL); m_requestNo = 0; } if (m_state == STATE_LOGGED) { Log.Notice("RemoteConsole", "User `%s` disconnected.", m_username.c_str()); } } void ConsoleSocket::AuthCallback(bool result) { ConsoleAuthMgr::getSingleton().SetRequest(m_requestNo, NULL); m_requestNo = 0; if (!result) { m_pConsole->Write("Authentication failed.\r\n\r\n"); m_failedLogins++; if (m_failedLogins < 3) { m_pConsole->Write("login: "); m_state = STATE_USER; } else { Disconnect(); } } else { m_pConsole->Write("User `%s` authenticated.\r\n\r\n", m_username.c_str()); Log.Notice("RemoteConsole", "User `%s` authenticated.", m_username.c_str()); const char* argv[1]; HandleInfoCommand(m_pConsole, 1, argv); m_pConsole->Write("Type ? to see commands, quit to end session.\r\n"); m_state = STATE_LOGGED; } } RemoteConsole::RemoteConsole(ConsoleSocket* pSocket) { m_pSocket = pSocket; } void RemoteConsole::Write(const char* Format, ...) { char obuf[65536]; va_list ap; va_start(ap, Format); vsnprintf(obuf, 65536, Format, ap); va_end(ap); if (*obuf == '\0') return; m_pSocket->Send((const uint8*)obuf, (uint32)strlen(obuf)); } struct ConsoleCommand { bool(*CommandPointer)(BaseConsole*, int, const char*[]); const char* Name; // 10 chars const char* ArgumentFormat; // 30 chars const char* Description; // 40 chars // = 70 chars }; void HandleConsoleInput(BaseConsole* pConsole, const char* szInput) { static ConsoleCommand Commands[] = { { &HandleAnnounceCommand, "a", "<announce string>", "Shows the message in all client chat boxes." }, { &HandleAnnounceCommand, "announce", "<announce string>", "Shows the message in all client chat boxes." }, { &HandleBanAccountCommand, "ban", "<account> <timeperiod> [reason]", "Bans account x for time y." }, { &HandleBanAccountCommand, "banaccount", "<account> <timeperiod> [reason]", "Bans account x for time y." }, { &HandleCancelCommand, "cancel", "None", "Cancels a pending shutdown." }, { &HandleInfoCommand, "info", "None", "Gives server runtime information." }, { &HandleNetworkStatusCommand, "netstatus", "none", "Shows network status." }, { &HandleGMsCommand, "gms", "None", "Shows online GMs." }, { &HandleKickCommand, "kick", "<Player Name> <reason>", "Kicks player x for reason y." }, { &HandleMOTDCommand, "getmotd", "None", "View the current MOTD" }, { &HandleMOTDCommand, "setmotd", "<new motd>", "Sets a new MOTD" }, { &HandleOnlinePlayersCommand, "online", "None", "Shows online players." }, { &HandlePlayerInfoCommand, "playerinfo", "<Player Name>", "Shows information about a player." }, { &HandleShutDownCommand, "exit", "[delay]", "Shuts down server with optional delay in seconds." }, { &HandleShutDownCommand, "shutdown", "[delay]", "Shuts down server with optional delay in seconds." }, { &HandleRehashCommand, "rehash", "None", "Reloads the config file" }, { &HandleUnbanAccountCommand, "unban", "<account>", "Unbans account x." }, { &HandleUnbanAccountCommand, "unbanaccount", "<account>", "Unbans account x." }, { &HandleWAnnounceCommand, "w", "<wannounce string>", "Shows the message in all client title areas." }, { &HandleWAnnounceCommand, "wannounce", "<wannounce string>", "Shows the message in all client title areas." }, { &HandleWhisperCommand, "whisper", "<player> <message>", "Whispers a message to someone from the console." }, { &HandleNameHashCommand, "getnamehash", "<text>", "Returns the crc32 hash of <text>" }, { &HandleRevivePlayer, "reviveplr", "<name>", "Revives a Player" }, { &HandleClearConsoleCommand, "clear", "None", "Clears the console screen." }, { &HandleReloadConsoleCommand, "reload", "<Table>", "Reloads a table from the world database." }, { &HandleScriptEngineReloadCommand, "reloadscripts", "<NULL>", "Reloads all scripting engines currently loaded." }, { &HandleTimeDateCommand, "datetime", "<NULL>", "Shows time and date according to localtime()" }, { NULL, NULL, NULL, NULL }, }; uint32 i; char* p, *q = nullptr; // let's tokenize into arguments. std::vector<const char*> tokens; q = (char*)szInput; p = strchr(q, ' '); while (p != nullptr) { *p = 0; tokens.push_back(q); q = p + 1; p = strchr(q, ' '); } if (*q != '\0') tokens.push_back(q); if (tokens.empty()) return; if (!stricmp(tokens[0], "help") || tokens[0][0] == '?') { if (tokens.size() > 1) { for (i = 0; Commands[i].Name != NULL; ++i) { if (!stricmp(Commands[i].Name, tokens[1])) { pConsole->Write("Command: %s\r\n" "Arguments: %s\r\n" "Description: %s\r\n", Commands[i].Name, Commands[i].ArgumentFormat, Commands[i].Description); return; } } } pConsole->Write("===============================================================================\r\n"); pConsole->Write("| %15s | %57s |\r\n", "Name", "Arguments"); pConsole->Write("===============================================================================\r\n"); for (i = 0; Commands[i].Name != NULL; ++i) { pConsole->Write("| %15s | %57s |\r\n", Commands[i].Name, Commands[i].ArgumentFormat); } pConsole->Write("===============================================================================\r\n"); pConsole->Write("| type 'quit' to terminate a Remote Console Session |\r\n"); pConsole->Write("===============================================================================\r\n"); } else { for (i = 0; Commands[i].Name != NULL; ++i) { if (!stricmp(Commands[i].Name, tokens[0])) { if (!Commands[i].CommandPointer(pConsole, (int)tokens.size(), &tokens[0])) { pConsole->Write("[!]Error, '%s' used an incorrect syntax, the correct syntax is: '%s'.\r\n\r\n", Commands[i].Name, Commands[i].ArgumentFormat); return; } else return; } } pConsole->Write("[!]Error, Command '%s' doesn't exist. Type '?' or 'help' to get a command overview.\r\n\r\n", tokens[0]); } } void LocalConsole::Write(const char* Format, ...) { va_list ap; va_start(ap, Format); vprintf(Format, ap); va_end(ap); } <|endoftext|>
<commit_before>//Open Producer - Copyright (C) 2002 Don Burns //Distributed under the terms of the GNU LIBRARY GENERAL PUBLIC LICENSE (LGPL) //as published by the Free Software Foundation. #include <osgProducer/CameraGroup> #include <osgDB/FileUtils> using namespace osgProducer; std::string findCameraConfigFile(const std::string& configFile) { std::string foundFile = osgDB::findDataFile(configFile); if (foundFile.empty()) return ""; else return foundFile; } CameraGroup::CameraGroup() : Producer::CameraGroup() { _init(); } CameraGroup::CameraGroup(Producer::CameraConfig *cfg): Producer::CameraGroup(cfg) { _init(); } CameraGroup::CameraGroup(const std::string& configFile) : Producer::CameraGroup(findCameraConfigFile(configFile)) { _init(); } void CameraGroup::_init() { _scene_data = NULL; _global_stateset = NULL; _background_color.set( 0.2f, 0.2f, 0.4f, 1.0f ); _LODScale = 1.0f; _fusionDistanceMode = osgUtil::SceneView::USE_CAMERA_FUSION_DISTANCE; _fusionDistanceValue = 1.0f; _initialized = false; if (!_frameStamp) _frameStamp = new osg::FrameStamp; // set up the maximum number of graphics contexts, before loading the scene graph // to ensure that texture objects and display buffers are configured to the correct size. osg::DisplaySettings::instance()->setMaxNumberOfGraphicsContexts( getNumberOfCameras() ); } void CameraGroup::setSceneData( osg::Node *scene ) { if (_scene_data==scene) return; if (_scene_decorator.valid() && _scene_data.valid()) { _scene_decorator->removeChild(_scene_data.get()); } _scene_data = scene; if (_scene_decorator.valid() && _scene_data.valid()) { _scene_decorator->addChild(scene); } setUpSceneViewsWithData(); } void CameraGroup::setSceneDecorator( osg::Group* decorator) { if (_scene_decorator==decorator) return; _scene_decorator = decorator; if (_scene_data.valid() && decorator) { decorator->addChild(_scene_data.get()); } setUpSceneViewsWithData(); } void CameraGroup::setUpSceneViewsWithData() { for(SceneHandlerList::iterator p = _shvec.begin(); p != _shvec.end(); p++ ) { if (_scene_decorator.valid()) { (*p)->setSceneData( _scene_decorator.get() ); } else if (_scene_data.valid()) { (*p)->setSceneData( _scene_data.get() ); } (*p)->setFrameStamp( _frameStamp.get() ); (*p)->setGlobalStateSet( _global_stateset.get() ); (*p)->setBackgroundColor( _background_color ); (*p)->setLODScale( _LODScale ); (*p)->setFusionDistance( _fusionDistanceMode, _fusionDistanceValue ); } } void CameraGroup::setFrameStamp( osg::FrameStamp* fs ) { _frameStamp = fs; setUpSceneViewsWithData(); } void CameraGroup::setGlobalStateSet( osg::StateSet *sset ) { _global_stateset = sset; setUpSceneViewsWithData(); } void CameraGroup::setBackgroundColor( const osg::Vec4& backgroundColor ) { _background_color = backgroundColor; setUpSceneViewsWithData(); } void CameraGroup::setLODScale( float scale ) { // need to set a local variable? _LODScale = scale; setUpSceneViewsWithData(); } void CameraGroup::setFusionDistance( osgUtil::SceneView::FusionDistanceMode mode,float value) { // need to set a local variable? _fusionDistanceMode = mode; _fusionDistanceValue = value; setUpSceneViewsWithData(); } void CameraGroup::advance() { if( !_initialized ) return; CameraGroup::advance(); } void CameraGroup::realize( ThreadingModel thread_model) { if( _initialized ) return; if (!_ds) _ds = osg::DisplaySettings::instance(); _ds->setMaxNumberOfGraphicsContexts( _cfg->getNumberOfCameras() ); for( unsigned int i = 0; i < _cfg->getNumberOfCameras(); i++ ) { Producer::Camera *cam = _cfg->getCamera(i); osgProducer::SceneHandler *sh = new osgProducer::SceneHandler(_ds.get()); sh->setDefaults(); if( _global_stateset != NULL ) sh->setGlobalStateSet( _global_stateset.get() ); if( _scene_data != NULL ) sh->setSceneData( _scene_data.get() ); sh->setBackgroundColor( _background_color); sh->getState()->setContextID(i); sh->setFrameStamp( _frameStamp.get() ); _shvec.push_back( sh ); cam->setSceneHandler( sh ); } setUpSceneViewsWithData(); /// Make all statesets the same as the first. if( _global_stateset == NULL && _shvec.size() > 0 ) { SceneHandlerList::iterator p; p = _shvec.begin(); _global_stateset = (*p)->getGlobalStateSet(); p++; for( ; p != _shvec.end(); p++ ) (*p)->setGlobalStateSet( _global_stateset.get() ); } Producer::CameraGroup::realize( thread_model ); _initialized = true; } osg::Node* CameraGroup::getTopMostSceneData() { if (_scene_decorator.valid()) return _scene_decorator.get(); else return _scene_data.get(); } const osg::Node* CameraGroup::getTopMostSceneData() const { if (_scene_decorator.valid()) return _scene_decorator.get(); else return _scene_data.get(); } void CameraGroup::frame() { osg::Node* node = getTopMostSceneData(); if (node) node->getBound(); Producer::CameraGroup::frame(); _frameStamp->setFrameNumber( _frameStamp->getFrameNumber() + 1 ); } <commit_msg>Fixed infinite loop in osgProducer::CameraGroup::advance().<commit_after>//Open Producer - Copyright (C) 2002 Don Burns //Distributed under the terms of the GNU LIBRARY GENERAL PUBLIC LICENSE (LGPL) //as published by the Free Software Foundation. #include <osgProducer/CameraGroup> #include <osgDB/FileUtils> using namespace osgProducer; std::string findCameraConfigFile(const std::string& configFile) { std::string foundFile = osgDB::findDataFile(configFile); if (foundFile.empty()) return ""; else return foundFile; } CameraGroup::CameraGroup() : Producer::CameraGroup() { _init(); } CameraGroup::CameraGroup(Producer::CameraConfig *cfg): Producer::CameraGroup(cfg) { _init(); } CameraGroup::CameraGroup(const std::string& configFile) : Producer::CameraGroup(findCameraConfigFile(configFile)) { _init(); } void CameraGroup::_init() { _scene_data = NULL; _global_stateset = NULL; _background_color.set( 0.2f, 0.2f, 0.4f, 1.0f ); _LODScale = 1.0f; _fusionDistanceMode = osgUtil::SceneView::USE_CAMERA_FUSION_DISTANCE; _fusionDistanceValue = 1.0f; _initialized = false; if (!_frameStamp) _frameStamp = new osg::FrameStamp; // set up the maximum number of graphics contexts, before loading the scene graph // to ensure that texture objects and display buffers are configured to the correct size. osg::DisplaySettings::instance()->setMaxNumberOfGraphicsContexts( getNumberOfCameras() ); } void CameraGroup::setSceneData( osg::Node *scene ) { if (_scene_data==scene) return; if (_scene_decorator.valid() && _scene_data.valid()) { _scene_decorator->removeChild(_scene_data.get()); } _scene_data = scene; if (_scene_decorator.valid() && _scene_data.valid()) { _scene_decorator->addChild(scene); } setUpSceneViewsWithData(); } void CameraGroup::setSceneDecorator( osg::Group* decorator) { if (_scene_decorator==decorator) return; _scene_decorator = decorator; if (_scene_data.valid() && decorator) { decorator->addChild(_scene_data.get()); } setUpSceneViewsWithData(); } void CameraGroup::setUpSceneViewsWithData() { for(SceneHandlerList::iterator p = _shvec.begin(); p != _shvec.end(); p++ ) { if (_scene_decorator.valid()) { (*p)->setSceneData( _scene_decorator.get() ); } else if (_scene_data.valid()) { (*p)->setSceneData( _scene_data.get() ); } (*p)->setFrameStamp( _frameStamp.get() ); (*p)->setGlobalStateSet( _global_stateset.get() ); (*p)->setBackgroundColor( _background_color ); (*p)->setLODScale( _LODScale ); (*p)->setFusionDistance( _fusionDistanceMode, _fusionDistanceValue ); } } void CameraGroup::setFrameStamp( osg::FrameStamp* fs ) { _frameStamp = fs; setUpSceneViewsWithData(); } void CameraGroup::setGlobalStateSet( osg::StateSet *sset ) { _global_stateset = sset; setUpSceneViewsWithData(); } void CameraGroup::setBackgroundColor( const osg::Vec4& backgroundColor ) { _background_color = backgroundColor; setUpSceneViewsWithData(); } void CameraGroup::setLODScale( float scale ) { // need to set a local variable? _LODScale = scale; setUpSceneViewsWithData(); } void CameraGroup::setFusionDistance( osgUtil::SceneView::FusionDistanceMode mode,float value) { // need to set a local variable? _fusionDistanceMode = mode; _fusionDistanceValue = value; setUpSceneViewsWithData(); } void CameraGroup::advance() { if( !_initialized ) return; Producer::CameraGroup::advance(); } void CameraGroup::realize( ThreadingModel thread_model) { if( _initialized ) return; if (!_ds) _ds = osg::DisplaySettings::instance(); _ds->setMaxNumberOfGraphicsContexts( _cfg->getNumberOfCameras() ); for( unsigned int i = 0; i < _cfg->getNumberOfCameras(); i++ ) { Producer::Camera *cam = _cfg->getCamera(i); osgProducer::SceneHandler *sh = new osgProducer::SceneHandler(_ds.get()); sh->setDefaults(); if( _global_stateset != NULL ) sh->setGlobalStateSet( _global_stateset.get() ); if( _scene_data != NULL ) sh->setSceneData( _scene_data.get() ); sh->setBackgroundColor( _background_color); sh->getState()->setContextID(i); sh->setFrameStamp( _frameStamp.get() ); _shvec.push_back( sh ); cam->setSceneHandler( sh ); } setUpSceneViewsWithData(); /// Make all statesets the same as the first. if( _global_stateset == NULL && _shvec.size() > 0 ) { SceneHandlerList::iterator p; p = _shvec.begin(); _global_stateset = (*p)->getGlobalStateSet(); p++; for( ; p != _shvec.end(); p++ ) (*p)->setGlobalStateSet( _global_stateset.get() ); } Producer::CameraGroup::realize( thread_model ); _initialized = true; } osg::Node* CameraGroup::getTopMostSceneData() { if (_scene_decorator.valid()) return _scene_decorator.get(); else return _scene_data.get(); } const osg::Node* CameraGroup::getTopMostSceneData() const { if (_scene_decorator.valid()) return _scene_decorator.get(); else return _scene_data.get(); } void CameraGroup::frame() { osg::Node* node = getTopMostSceneData(); if (node) node->getBound(); Producer::CameraGroup::frame(); _frameStamp->setFrameNumber( _frameStamp->getFrameNumber() + 1 ); } <|endoftext|>
<commit_before>/** @file @brief Implementation @date 2014 @author Ryan Pavlik <ryan@sensics.com> <http://sensics.com> */ // Copyright 2014 Sensics, Inc. // // All rights reserved. // // (Final version intended to be licensed under // the Apache License, Version 2.0) // Internal Includes #include "VRPNContext.h" #include "display_json.h" #include "RouterPredicates.h" #include "RouterTransforms.h" #include "VRPNAnalogRouter.h" #include "VRPNButtonRouter.h" #include "VRPNTrackerRouter.h" #include <osvr/Util/ClientCallbackTypesC.h> #include <osvr/Client/ClientContext.h> #include <osvr/Client/ClientInterface.h> #include <osvr/Util/Verbosity.h> // Library/third-party includes // - none // Standard includes #include <cstring> namespace osvr { namespace client { RouterEntry::~RouterEntry() {} VRPNContext::VRPNContext(const char appId[], const char host[]) : ::OSVR_ClientContextObject(appId), m_host(host) { std::string contextDevice = "OSVR@" + m_host; m_conn = vrpn_get_connection_by_name(contextDevice.c_str()); /// @todo this is hardcoded routing, and not well done - just a stop-gap /// measure. m_addTrackerRouter("org_opengoggles_bundled_Multiserver/RazerHydra0", "/me/hands/left", SensorPredicate(0), HydraTrackerTransform()); m_addTrackerRouter("org_opengoggles_bundled_Multiserver/RazerHydra0", "/me/hands/right", SensorPredicate(1), HydraTrackerTransform()); m_addTrackerRouter("org_opengoggles_bundled_Multiserver/RazerHydra0", "/me/hands", AlwaysTruePredicate(), HydraTrackerTransform()); m_addTrackerRouter( "org_opengoggles_bundled_Multiserver/YEI_3Space_Sensor0", "/me/head", SensorPredicate(1)); #define OSVR_HYDRA_BUTTON(SENSOR, NAME) \ m_addButtonRouter("org_opengoggles_bundled_Multiserver/RazerHydra0", \ "/controller/left/" NAME, SensorPredicate(SENSOR)); \ m_addButtonRouter("org_opengoggles_bundled_Multiserver/RazerHydra0", \ "/controller/right/" NAME, SensorPredicate(SENSOR + 8)) OSVR_HYDRA_BUTTON(0, "middle"); OSVR_HYDRA_BUTTON(1, "1"); OSVR_HYDRA_BUTTON(2, "2"); OSVR_HYDRA_BUTTON(3, "3"); OSVR_HYDRA_BUTTON(4, "4"); OSVR_HYDRA_BUTTON(5, "bumper"); OSVR_HYDRA_BUTTON(6, "joystick/button"); #undef OSVR_HYDRA_BUTTON #define OSVR_HYDRA_ANALOG(SENSOR, NAME) \ m_addAnalogRouter("org_opengoggles_bundled_Multiserver/RazerHydra0", \ "/controller/left/" NAME, SENSOR); \ m_addAnalogRouter("org_opengoggles_bundled_Multiserver/RazerHydra0", \ "/controller/right/" NAME, SENSOR + 3) OSVR_HYDRA_ANALOG(0, "joystick/x"); OSVR_HYDRA_ANALOG(1, "joystick/y"); OSVR_HYDRA_ANALOG(2, "trigger"); #undef OSVR_HYDRA_ANALOG setParameter("/display", std::string(reinterpret_cast<char *>(display_json), display_json_len)); } VRPNContext::~VRPNContext() {} void VRPNContext::m_update() { // mainloop the VRPN connection. m_conn->mainloop(); // Process each of the routers. for (auto const &p : m_routers) { (*p)(); } } void VRPNContext::m_addAnalogRouter(const char *src, const char *dest, int channel) { OSVR_DEV_VERBOSE("Adding analog route for " << dest); m_routers.emplace_back( new VRPNAnalogRouter<SensorPredicate, NullTransform>( this, m_conn.get(), src, dest, SensorPredicate(channel), NullTransform(), channel)); } template <typename Predicate> void VRPNContext::m_addButtonRouter(const char *src, const char *dest, Predicate pred) { OSVR_DEV_VERBOSE("Adding button route for " << dest); m_routers.emplace_back(new VRPNButtonRouter<Predicate>( this, m_conn.get(), src, dest, pred)); } template <typename Predicate> void VRPNContext::m_addTrackerRouter(const char *src, const char *dest, Predicate pred) { m_addTrackerRouter(src, dest, pred, NullTransform()); } template <typename Predicate, typename Transform> void VRPNContext::m_addTrackerRouter(const char *src, const char *dest, Predicate pred, Transform xform) { OSVR_DEV_VERBOSE("Adding tracker route for " << dest); m_routers.emplace_back(new VRPNTrackerRouter<Predicate, Transform>( this, m_conn.get(), src, dest, pred, xform)); } } // namespace client } // namespace osvr<commit_msg>Change routing to point to the one-euro filter.<commit_after>/** @file @brief Implementation @date 2014 @author Ryan Pavlik <ryan@sensics.com> <http://sensics.com> */ // Copyright 2014 Sensics, Inc. // // All rights reserved. // // (Final version intended to be licensed under // the Apache License, Version 2.0) // Internal Includes #include "VRPNContext.h" #include "display_json.h" #include "RouterPredicates.h" #include "RouterTransforms.h" #include "VRPNAnalogRouter.h" #include "VRPNButtonRouter.h" #include "VRPNTrackerRouter.h" #include <osvr/Util/ClientCallbackTypesC.h> #include <osvr/Client/ClientContext.h> #include <osvr/Client/ClientInterface.h> #include <osvr/Util/Verbosity.h> // Library/third-party includes // - none // Standard includes #include <cstring> namespace osvr { namespace client { RouterEntry::~RouterEntry() {} VRPNContext::VRPNContext(const char appId[], const char host[]) : ::OSVR_ClientContextObject(appId), m_host(host) { std::string contextDevice = "OSVR@" + m_host; m_conn = vrpn_get_connection_by_name(contextDevice.c_str()); /// @todo this is hardcoded routing, and not well done - just a stop-gap /// measure. This one-euro filter connects to the hydra. m_addTrackerRouter("org_opengoggles_bundled_Multiserver/OneEuroFilter0", "/me/hands/left", SensorPredicate(0), HydraTrackerTransform()); m_addTrackerRouter("org_opengoggles_bundled_Multiserver/OneEuroFilter0", "/me/hands/right", SensorPredicate(1), HydraTrackerTransform()); m_addTrackerRouter("org_opengoggles_bundled_Multiserver/OneEuroFilter0", "/me/hands", AlwaysTruePredicate(), HydraTrackerTransform()); m_addTrackerRouter( "org_opengoggles_bundled_Multiserver/YEI_3Space_Sensor0", "/me/head", SensorPredicate(1)); #define OSVR_HYDRA_BUTTON(SENSOR, NAME) \ m_addButtonRouter("org_opengoggles_bundled_Multiserver/RazerHydra0", \ "/controller/left/" NAME, SensorPredicate(SENSOR)); \ m_addButtonRouter("org_opengoggles_bundled_Multiserver/RazerHydra0", \ "/controller/right/" NAME, SensorPredicate(SENSOR + 8)) OSVR_HYDRA_BUTTON(0, "middle"); OSVR_HYDRA_BUTTON(1, "1"); OSVR_HYDRA_BUTTON(2, "2"); OSVR_HYDRA_BUTTON(3, "3"); OSVR_HYDRA_BUTTON(4, "4"); OSVR_HYDRA_BUTTON(5, "bumper"); OSVR_HYDRA_BUTTON(6, "joystick/button"); #undef OSVR_HYDRA_BUTTON #define OSVR_HYDRA_ANALOG(SENSOR, NAME) \ m_addAnalogRouter("org_opengoggles_bundled_Multiserver/RazerHydra0", \ "/controller/left/" NAME, SENSOR); \ m_addAnalogRouter("org_opengoggles_bundled_Multiserver/RazerHydra0", \ "/controller/right/" NAME, SENSOR + 3) OSVR_HYDRA_ANALOG(0, "joystick/x"); OSVR_HYDRA_ANALOG(1, "joystick/y"); OSVR_HYDRA_ANALOG(2, "trigger"); #undef OSVR_HYDRA_ANALOG setParameter("/display", std::string(reinterpret_cast<char *>(display_json), display_json_len)); } VRPNContext::~VRPNContext() {} void VRPNContext::m_update() { // mainloop the VRPN connection. m_conn->mainloop(); // Process each of the routers. for (auto const &p : m_routers) { (*p)(); } } void VRPNContext::m_addAnalogRouter(const char *src, const char *dest, int channel) { OSVR_DEV_VERBOSE("Adding analog route for " << dest); m_routers.emplace_back( new VRPNAnalogRouter<SensorPredicate, NullTransform>( this, m_conn.get(), src, dest, SensorPredicate(channel), NullTransform(), channel)); } template <typename Predicate> void VRPNContext::m_addButtonRouter(const char *src, const char *dest, Predicate pred) { OSVR_DEV_VERBOSE("Adding button route for " << dest); m_routers.emplace_back(new VRPNButtonRouter<Predicate>( this, m_conn.get(), src, dest, pred)); } template <typename Predicate> void VRPNContext::m_addTrackerRouter(const char *src, const char *dest, Predicate pred) { m_addTrackerRouter(src, dest, pred, NullTransform()); } template <typename Predicate, typename Transform> void VRPNContext::m_addTrackerRouter(const char *src, const char *dest, Predicate pred, Transform xform) { OSVR_DEV_VERBOSE("Adding tracker route for " << dest); m_routers.emplace_back(new VRPNTrackerRouter<Predicate, Transform>( this, m_conn.get(), src, dest, pred, xform)); } } // namespace client } // namespace osvr<|endoftext|>
<commit_before>// tag::C++11check[] #define STRING2(x) #x #define STRING(x) STRING2(x) #if __cplusplus < 201103L #pragma message("WARNING: the compiler may not be C++11 compliant. __cplusplus version is : " STRING(__cplusplus)) #endif // end::C++11check[] // tag::includes[] #include <iostream> #include <vector> #include <algorithm> #include <string> #include <GL/glew.h> #include <SDL.h> // end::includes[] // tag::namespace[] using namespace std; // end::namespace[] // tag::globalVariables[] std::string exeName; SDL_Window *win; //pointer to the SDL_Window SDL_GLContext context; //the SDL_GLContext int frameCount = 0; std::string frameLine = ""; // end::globalVariables[] // tag::vertexShader[] //string holding the **source** of our vertex shader, to save loading from a file const std::string strVertexShader = R"( #version 330 in vec2 position; uniform vec2 offset; void main() { vec2 tmpPosition = position + offset; gl_Position = vec4(tmpPosition, 0.0, 1.0); } )"; // end::vertexShader[] // tag::fragmentShader[] //string holding the **source** of our fragment shader, to save loading from a file const std::string strFragmentShader = R"( #version 330 out vec4 outputColor; void main() { outputColor = vec4(1.0f, 1.0f, 1.0f, 1.0f); } )"; // end::fragmentShader[] //our variables bool done = false; //the data about our geometry const GLfloat vertexData[] = { 0.000f, 0.500f, -0.433f, -0.250f, 0.433f, -0.250f, }; //the offset we'll pass to the GLSL GLfloat offset[] = { -0.5, -0.5 }; //using different values from CPU and static GLSL examples, to make it clear this is working GLfloat offsetVelocity[] = { 0.2, 0.2 }; //rate of change of offset in units per second //our GL and GLSL variables GLuint theProgram; //GLuint that we'll fill in to refer to the GLSL program (only have 1 at this point) GLint positionLocation; //GLuint that we'll fill in with the location of the `offset` variable in the GLSL GLint offsetLocation; //GLuint that we'll fill in with the location of the `offset` variable in the GLSL GLuint vertexDataBufferObject; GLuint vertexArrayObject; // end Global Variables ///////////////////////// void initialise() { if (SDL_Init(SDL_INIT_EVERYTHING) != 0){ cout << "SDL_Init Error: " << SDL_GetError() << std::endl; exit(1); } cout << "SDL initialised OK!\n"; } void createWindow() { //get executable name, and use as window title int beginIdxWindows = exeName.rfind("\\"); //find last occurrence of a backslash int beginIdxLinux = exeName.rfind("/"); //find last occurrence of a forward slash int beginIdx = max(beginIdxWindows, beginIdxLinux); std::string exeNameEnd = exeName.substr(beginIdx + 1); const char *exeNameCStr = exeNameEnd.c_str(); //create window win = SDL_CreateWindow(exeNameCStr, 100, 100, 600, 600, SDL_WINDOW_OPENGL); //same height and width makes the window square ... //error handling if (win == nullptr) { std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl; SDL_Quit(); exit(1); } cout << "SDL CreatedWindow OK!\n"; } void setGLAttributes() { int major = 3; int minor = 3; cout << "Built for OpenGL Version " << major << "." << minor << endl; //ahttps://en.wikipedia.org/wiki/OpenGL_Shading_Language#Versions // set the opengl context version SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, major); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, minor); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); //core profile cout << "Set OpenGL context to versicreate remote branchon " << major << "." << minor << " OK!\n"; } void createContext() { setGLAttributes(); context = SDL_GL_CreateContext(win); if (context == nullptr){ SDL_DestroyWindow(win); std::cout << "SDL_GL_CreateContext Error: " << SDL_GetError() << std::endl; SDL_Quit(); exit(1); } cout << "Created OpenGL context OK!\n"; } void initGlew() { GLenum rev; glewExperimental = GL_TRUE; //GLEW isn't perfect - see https://www.opengl.org/wiki/OpenGL_Loading_Library#GLEW rev = glewInit(); if (GLEW_OK != rev){ std::cout << "GLEW Error: " << glewGetErrorString(rev) << std::endl; SDL_Quit(); exit(1); } else { cout << "GLEW Init OK!\n"; } } GLuint createShader(GLenum eShaderType, const std::string &strShaderFile) { GLuint shader = glCreateShader(eShaderType); //error check const char *strFileData = strShaderFile.c_str(); glShaderSource(shader, 1, &strFileData, NULL); glCompileShader(shader); GLint status; glGetShaderiv(shader, GL_COMPILE_STATUS, &status); if (status == GL_FALSE) { GLint infoLogLength; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength); GLchar *strInfoLog = new GLchar[infoLogLength + 1]; glGetShaderInfoLog(shader, infoLogLength, NULL, strInfoLog); const char *strShaderType = NULL; switch (eShaderType) { case GL_VERTEX_SHADER: strShaderType = "vertex"; break; case GL_GEOMETRY_SHADER: strShaderType = "geometry"; break; case GL_FRAGMENT_SHADER: strShaderType = "fragment"; break; } fprintf(stderr, "Compile failure in %s shader:\n%s\n", strShaderType, strInfoLog); delete[] strInfoLog; } return shader; } GLuint createProgram(const std::vector<GLuint> &shaderList) { GLuint program = glCreateProgram(); for (size_t iLoop = 0; iLoop < shaderList.size(); iLoop++) glAttachShader(program, shaderList[iLoop]); glLinkProgram(program); GLint status; glGetProgramiv(program, GL_LINK_STATUS, &status); if (status == GL_FALSE) { GLint infoLogLength; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLogLength); GLchar *strInfoLog = new GLchar[infoLogLength + 1]; glGetProgramInfoLog(program, infoLogLength, NULL, strInfoLog); fprintf(stderr, "Linker failure: %s\n", strInfoLog); delete[] strInfoLog; } for (size_t iLoop = 0; iLoop < shaderList.size(); iLoop++) glDetachShader(program, shaderList[iLoop]); return program; } void initializeProgram() { std::vector<GLuint> shaderList; shaderList.push_back(createShader(GL_VERTEX_SHADER, strVertexShader)); shaderList.push_back(createShader(GL_FRAGMENT_SHADER, strFragmentShader)); theProgram = createProgram(shaderList); if (theProgram == 0) { cout << "GLSL program creation error." << std::endl; SDL_Quit(); exit(1); } else { cout << "GLSL program creation OK! GLUint is: " << theProgram << std::endl; } positionLocation = glGetAttribLocation(theProgram, "position"); offsetLocation = glGetUniformLocation(theProgram, "offset"); //clean up shaders (we don't need them anymore as they are no in theProgram for_each(shaderList.begin(), shaderList.end(), glDeleteShader); } void initializeVertexBuffer() { glGenBuffers(1, &vertexDataBufferObject); glBindBuffer(GL_ARRAY_BUFFER, vertexDataBufferObject); glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); cout << "vertexDataBufferObject created OK! GLUint is: " << vertexDataBufferObject << std::endl; } void loadAssets() { initializeProgram(); //create GLSL Shaders, link into a GLSL program, and get IDs of attributes and variables initializeVertexBuffer(); //load data into a vertex buffer cout << "Loaded Assets OK!\n"; } void setupvertexArrayObject() { glGenVertexArrays(1, &vertexArrayObject); //create a Vertex Array Object cout << "Vertex Array Object created OK! GLUint is: " << vertexArrayObject << std::endl; glBindVertexArray(vertexArrayObject); //make the just created vertexArrayObject the active one glBindBuffer(GL_ARRAY_BUFFER, vertexDataBufferObject); //bind vertexDataBufferObject glEnableVertexAttribArray(positionLocation); //enable attribute at index positionLocation glVertexAttribPointer(positionLocation, 2, GL_FLOAT, GL_FALSE, 0, 0); //specify that position data contains four floats per vertex, and goes into attribute index positionLocation glBindVertexArray(0); //unbind the vertexArrayObject so we can't change it //cleanup glDisableVertexAttribArray(positionLocation); //disable vertex attribute at index positionLocation glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind array buffer } void handleInput() { //Event-based input handling //The underlying OS is event-based, so **each** key-up or key-down (for example) //generates an event. // - https://wiki.libsdl.org/SDL_PollEvent //In some scenarios we want to catch **ALL** the events, not just to present state // - for instance, if taking keyboard input the user might key-down two keys during a frame // - we want to catch based, and know the order // - or the user might key-down and key-up the same within a frame, and we still want something to happen (e.g. jump) // - the alternative is to Poll the current state with SDL_GetKeyboardState SDL_Event event; //somewhere to store an event //NOTE: there may be multiple events per frame while (SDL_PollEvent(&event)) //loop until SDL_PollEvent returns 0 (meaning no more events) { switch (event.type) { case SDL_QUIT: done = true; //set donecreate remote branch flag if SDL wants to quit (i.e. if the OS has triggered a close event, // - such as window close, or SIGINT break; //keydown handling - we should to the opposite on key-up for direction controls (generally) case SDL_KEYDOWN: //Keydown can fire repeatable if key-repeat is on. // - the repeat flag is set on the keyboard event, if this is a repeat event // - in our case, we're going to ignore repeat events // - https://wiki.libsdl.org/SDL_KeyboardEvent if (!event.key.repeat) switch (event.key.keysym.sym) { //hit escape to exit case SDLK_ESCAPE: done = true; } break; } } } void updateSimulation(double simLength) //update simulation with an amount of time to simulate for (in seconds) { //CHANGE ME } void preRender() { glViewport(0, 0, 600, 600); //set viewpoint glClearColor(1.0f, 0.0f, 0.0f, 1.0f); //set clear colour glClear(GL_COLOR_BUFFER_BIT); //clear the window (technical the scissor box bounds) } void render() { glUseProgram(theProgram); //installs the program object specified by program as part of current rendering state //load data to GLSL that **may** have changed glUniform2f(offsetLocation, offset[0], offset[1]); //alternatively, use glUnivform2fv //glUniform2fv(offsetLocation, 1, offset); //Note: the count is 1, because we are setting a single uniform vec2 - https://www.opengl.org/wiki/GLSL_:_common_mistakes#How_to_use_glUniform glBindVertexArray(vertexArrayObject); glDrawArrays(GL_TRIANGLES, 0, 3); //Draw something, using Triangles, and 3 vertices - i.e. one lonely triangle glBindVertexArray(0); glUseProgram(0); //clean up } void postRender() { SDL_GL_SwapWindow(win);; //present the frame buffer to the display (swapBuffers) frameLine += "Frame: " + std::to_string(frameCount++); cout << "\r" << frameLine << std::flush; frameLine = ""; } void cleanUp() { SDL_GL_DeleteContext(context); SDL_DestroyWindow(win); cout << "Cleaning up OK!\n"; } int main( int argc, char* args[] ) { exeName = args[0]; //setup //- do just once initialise(); createWindow(); createContext(); initGlew(); glViewport(0,0,600,600); //should check what the actual window res is? SDL_GL_SwapWindow(win); //force a swap, to make the trace clearer //do stuff that only needs to happen once //- create shaders //- load vertex data loadAssets(); //setup a GL object (a VertexArrayObject) that stores how to access data and from where setupvertexArrayObject(); while (!done) //loop until done flag is set) { handleInput(); updateSimulation(0.02); //call update simulation with an amount of time to simulate for (in seconds) //WARNING - we are always updating by a constant amount of time. This should be tied to how long has elapsed // see, for example, http://headerphile.blogspot.co.uk/2014/07/part-9-no-more-delays.html preRender(); render(); //RENDER HERE - PLACEHOLDER postRender(); } //cleanup and exit cleanUp(); SDL_Quit(); return 0; } <commit_msg>set colour with a uniform. pass no offset information<commit_after>// tag::C++11check[] #define STRING2(x) #x #define STRING(x) STRING2(x) #if __cplusplus < 201103L #pragma message("WARNING: the compiler may not be C++11 compliant. __cplusplus version is : " STRING(__cplusplus)) #endif // end::C++11check[] // tag::includes[] #include <iostream> #include <vector> #include <algorithm> #include <string> #include <GL/glew.h> #include <SDL.h> // end::includes[] // tag::namespace[] using namespace std; // end::namespace[] // tag::globalVariables[] std::string exeName; SDL_Window *win; //pointer to the SDL_Window SDL_GLContext context; //the SDL_GLContext int frameCount = 0; std::string frameLine = ""; // end::globalVariables[] // tag::vertexShader[] //string holding the **source** of our vertex shader, to save loading from a file const std::string strVertexShader = R"( #version 330 in vec2 position; void main() { gl_Position = vec4(position, 0.0, 1.0); } )"; // end::vertexShader[] // tag::fragmentShader[] //string holding the **source** of our fragment shader, to save loading from a file const std::string strFragmentShader = R"( #version 330 out vec4 outputColor; uniform vec3 color; void main() { outputColor = vec4(color, 1.0f); } )"; // end::fragmentShader[] //our variables bool done = false; //the data about our geometry const GLfloat vertexData[] = { 0.000f, 0.500f, -0.433f, -0.250f, 0.433f, -0.250f, }; //the color we'll pass to the GLSL GLfloat color[] = { 1.0f, 1.0f, 1.0f }; //using different values from CPU and static GLSL examples, to make it clear this is working //our GL and GLSL variables GLuint theProgram; //GLuint that we'll fill in to refer to the GLSL program (only have 1 at this point) GLint positionLocation; //GLuint that we'll fill in with the location of the `position` attribute in the GLSL GLint colorLocation; //GLuint that we'll fill in with the location of the `color` variable in the GLSL GLuint vertexDataBufferObject; GLuint vertexArrayObject; // end Global Variables ///////////////////////// void initialise() { if (SDL_Init(SDL_INIT_EVERYTHING) != 0){ cout << "SDL_Init Error: " << SDL_GetError() << std::endl; exit(1); } cout << "SDL initialised OK!\n"; } void createWindow() { //get executable name, and use as window title int beginIdxWindows = exeName.rfind("\\"); //find last occurrence of a backslash int beginIdxLinux = exeName.rfind("/"); //find last occurrence of a forward slash int beginIdx = max(beginIdxWindows, beginIdxLinux); std::string exeNameEnd = exeName.substr(beginIdx + 1); const char *exeNameCStr = exeNameEnd.c_str(); //create window win = SDL_CreateWindow(exeNameCStr, 100, 100, 600, 600, SDL_WINDOW_OPENGL); //same height and width makes the window square ... //error handling if (win == nullptr) { std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl; SDL_Quit(); exit(1); } cout << "SDL CreatedWindow OK!\n"; } void setGLAttributes() { int major = 3; int minor = 3; cout << "Built for OpenGL Version " << major << "." << minor << endl; //ahttps://en.wikipedia.org/wiki/OpenGL_Shading_Language#Versions // set the opengl context version SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, major); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, minor); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); //core profile cout << "Set OpenGL context to versicreate remote branchon " << major << "." << minor << " OK!\n"; } void createContext() { setGLAttributes(); context = SDL_GL_CreateContext(win); if (context == nullptr){ SDL_DestroyWindow(win); std::cout << "SDL_GL_CreateContext Error: " << SDL_GetError() << std::endl; SDL_Quit(); exit(1); } cout << "Created OpenGL context OK!\n"; } void initGlew() { GLenum rev; glewExperimental = GL_TRUE; //GLEW isn't perfect - see https://www.opengl.org/wiki/OpenGL_Loading_Library#GLEW rev = glewInit(); if (GLEW_OK != rev){ std::cout << "GLEW Error: " << glewGetErrorString(rev) << std::endl; SDL_Quit(); exit(1); } else { cout << "GLEW Init OK!\n"; } } GLuint createShader(GLenum eShaderType, const std::string &strShaderFile) { GLuint shader = glCreateShader(eShaderType); //error check const char *strFileData = strShaderFile.c_str(); glShaderSource(shader, 1, &strFileData, NULL); glCompileShader(shader); GLint status; glGetShaderiv(shader, GL_COMPILE_STATUS, &status); if (status == GL_FALSE) { GLint infoLogLength; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength); GLchar *strInfoLog = new GLchar[infoLogLength + 1]; glGetShaderInfoLog(shader, infoLogLength, NULL, strInfoLog); const char *strShaderType = NULL; switch (eShaderType) { case GL_VERTEX_SHADER: strShaderType = "vertex"; break; case GL_GEOMETRY_SHADER: strShaderType = "geometry"; break; case GL_FRAGMENT_SHADER: strShaderType = "fragment"; break; } fprintf(stderr, "Compile failure in %s shader:\n%s\n", strShaderType, strInfoLog); delete[] strInfoLog; } return shader; } GLuint createProgram(const std::vector<GLuint> &shaderList) { GLuint program = glCreateProgram(); for (size_t iLoop = 0; iLoop < shaderList.size(); iLoop++) glAttachShader(program, shaderList[iLoop]); glLinkProgram(program); GLint status; glGetProgramiv(program, GL_LINK_STATUS, &status); if (status == GL_FALSE) { GLint infoLogLength; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLogLength); GLchar *strInfoLog = new GLchar[infoLogLength + 1]; glGetProgramInfoLog(program, infoLogLength, NULL, strInfoLog); fprintf(stderr, "Linker failure: %s\n", strInfoLog); delete[] strInfoLog; } for (size_t iLoop = 0; iLoop < shaderList.size(); iLoop++) glDetachShader(program, shaderList[iLoop]); return program; } void initializeProgram() { std::vector<GLuint> shaderList; shaderList.push_back(createShader(GL_VERTEX_SHADER, strVertexShader)); shaderList.push_back(createShader(GL_FRAGMENT_SHADER, strFragmentShader)); theProgram = createProgram(shaderList); if (theProgram == 0) { cout << "GLSL program creation error." << std::endl; SDL_Quit(); exit(1); } else { cout << "GLSL program creation OK! GLUint is: " << theProgram << std::endl; } positionLocation = glGetAttribLocation(theProgram, "position"); colorLocation = glGetUniformLocation(theProgram, "color"); //clean up shaders (we don't need them anymore as they are no in theProgram for_each(shaderList.begin(), shaderList.end(), glDeleteShader); } void initializeVertexBuffer() { glGenBuffers(1, &vertexDataBufferObject); glBindBuffer(GL_ARRAY_BUFFER, vertexDataBufferObject); glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); cout << "vertexDataBufferObject created OK! GLUint is: " << vertexDataBufferObject << std::endl; } void loadAssets() { initializeProgram(); //create GLSL Shaders, link into a GLSL program, and get IDs of attributes and variables initializeVertexBuffer(); //load data into a vertex buffer cout << "Loaded Assets OK!\n"; } void setupvertexArrayObject() { glGenVertexArrays(1, &vertexArrayObject); //create a Vertex Array Object cout << "Vertex Array Object created OK! GLUint is: " << vertexArrayObject << std::endl; glBindVertexArray(vertexArrayObject); //make the just created vertexArrayObject the active one glBindBuffer(GL_ARRAY_BUFFER, vertexDataBufferObject); //bind vertexDataBufferObject glEnableVertexAttribArray(positionLocation); //enable attribute at index positionLocation glVertexAttribPointer(positionLocation, 2, GL_FLOAT, GL_FALSE, 0, 0); //specify that position data contains four floats per vertex, and goes into attribute index positionLocation glBindVertexArray(0); //unbind the vertexArrayObject so we can't change it //cleanup glDisableVertexAttribArray(positionLocation); //disable vertex attribute at index positionLocation glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind array buffer } void handleInput() { //Event-based input handling //The underlying OS is event-based, so **each** key-up or key-down (for example) //generates an event. // - https://wiki.libsdl.org/SDL_PollEvent //In some scenarios we want to catch **ALL** the events, not just to present state // - for instance, if taking keyboard input the user might key-down two keys during a frame // - we want to catch based, and know the order // - or the user might key-down and key-up the same within a frame, and we still want something to happen (e.g. jump) // - the alternative is to Poll the current state with SDL_GetKeyboardState SDL_Event event; //somewhere to store an event //NOTE: there may be multiple events per frame while (SDL_PollEvent(&event)) //loop until SDL_PollEvent returns 0 (meaning no more events) { switch (event.type) { case SDL_QUIT: done = true; //set donecreate remote branch flag if SDL wants to quit (i.e. if the OS has triggered a close event, // - such as window close, or SIGINT break; //keydown handling - we should to the opposite on key-up for direction controls (generally) case SDL_KEYDOWN: //Keydown can fire repeatable if key-repeat is on. // - the repeat flag is set on the keyboard event, if this is a repeat event // - in our case, we're going to ignore repeat events // - https://wiki.libsdl.org/SDL_KeyboardEvent if (!event.key.repeat) switch (event.key.keysym.sym) { //hit escape to exit case SDLK_ESCAPE: done = true; } break; } } } void updateSimulation(double simLength) //update simulation with an amount of time to simulate for (in seconds) { //CHANGE ME } void preRender() { glViewport(0, 0, 600, 600); //set viewpoint glClearColor(1.0f, 0.0f, 0.0f, 1.0f); //set clear colour glClear(GL_COLOR_BUFFER_BIT); //clear the window (technical the scissor box bounds) } void render() { glUseProgram(theProgram); //installs the program object specified by program as part of current rendering state //load data to GLSL that **may** have changed glUniform3f(colorLocation, color[0], color[1], color[2]); //alternatively, use glUnivform2fv //glUniform2fv(colorLocation, 1, color); //Note: the count is 1, because we are setting a single uniform vec2 - https://www.opengl.org/wiki/GLSL_:_common_mistakes#How_to_use_glUniform glBindVertexArray(vertexArrayObject); glDrawArrays(GL_TRIANGLES, 0, 3); //Draw something, using Triangles, and 3 vertices - i.e. one lonely triangle glBindVertexArray(0); glUseProgram(0); //clean up } void postRender() { SDL_GL_SwapWindow(win);; //present the frame buffer to the display (swapBuffers) frameLine += "Frame: " + std::to_string(frameCount++); cout << "\r" << frameLine << std::flush; frameLine = ""; } void cleanUp() { SDL_GL_DeleteContext(context); SDL_DestroyWindow(win); cout << "Cleaning up OK!\n"; } int main( int argc, char* args[] ) { exeName = args[0]; //setup //- do just once initialise(); createWindow(); createContext(); initGlew(); glViewport(0,0,600,600); //should check what the actual window res is? SDL_GL_SwapWindow(win); //force a swap, to make the trace clearer //do stuff that only needs to happen once //- create shaders //- load vertex data loadAssets(); //setup a GL object (a VertexArrayObject) that stores how to access data and from where setupvertexArrayObject(); while (!done) //loop until done flag is set) { handleInput(); updateSimulation(0.02); //call update simulation with an amount of time to simulate for (in seconds) //WARNING - we are always updating by a constant amount of time. This should be tied to how long has elapsed // see, for example, http://headerphile.blogspot.co.uk/2014/07/part-9-no-more-delays.html preRender(); render(); //RENDER HERE - PLACEHOLDER postRender(); } //cleanup and exit cleanUp(); SDL_Quit(); return 0; } <|endoftext|>
<commit_before>#include "FEINDLib.h" #include <math.h> FEINDLib::FEINDLib(char* arg0, char* arg1, char* arg2, int setType) : DataLib(setType) { FEIND::LibDefine lib; lib.Args.push_back(" "); int libCase = -9; if (arg0 == "EAF") libCase = 1; else if (arg0 == "CINDER") libCase = 2; switch (libCase) { case 1: //Load decay library lib.format = FEIND::DECAY_ENDF_6; lib.Args[0] = arg1; //*** LOAD THE LIBRARY ***// try{ FEIND::LoadLibrary(lib); } catch(FEIND::Exception& ex) { ex.Abort(); } //Load activation library lib.format = FEIND::EAF_4_1; nGroups = 175; lib.Args[0] = arg2; //*** LOAD THE LIBRARY ***// try{ FEIND::LoadLibrary(lib); } catch(FEIND::Exception& ex) { ex.Abort(); } break; case 2: lib.format = FEIND::CINDER; nGroups = 63; lib.Args[0] = arg1; lib.Args.push_back(arg2); //*** LOAD THE LIBRARY ***// try{ FEIND::LoadLibrary(lib); } catch(FEIND::Exception& ex) { ex.Abort(); } break; default: cerr << "*** ERROR LOADING NUCLEAR LIBRARY...\n" << "Unknown nuclear data format \"" << format_str << "\" encountered." << "\n\nABORTING\n\n"; assert(0); } nParents = (FEIND::Library.Parents()).size(); } void FEINDLib::readData(int parent, NuclearData* data) { int checkKza, nRxns=0; float thalf = 0, E[3] = {0,0,0}; int *daugKza = NULL; char **emitted = NULL; float **xSection = NULL, *totalXSect=NULL; int rxnNum, emittedLen, numNZGrps, gNum; float bRatio; float decayConst = FEIND::GetDecayConstant(parent); thalf = log(2)/decayConst; vector<int> daughterVec = FEIND::Daughters(parent); nRxns = daughterVec.size(); daughKza = new int[nRxns]; xSection = new float*[nRxns]; emitted = new char*[nRxns]; for (rxnNum = 0; rxnNum < nRxns; rxnNum++) { *daughKza = daughterVec[rxnNum]; daughKza++; //Create emitted[rxnNum]. Currently, FEIND cannot handle types of reaction. emitted[rxnNum] = new char[3+1]; emitted[rxnNum][0] = 'x'; emitted[rxnNum][1] = 'x'; emitted[rxnNum][2] = 'x'; emitted[rxnNum][3] = '\0'; //Create xSection[rxnNum] with a size of nGroups+1 xSection[rxnNum] = new float[nGroups+1]; FEIND::XSec csc = FEIND::GetDCs(parent, daughterVec[rxnNum], FEIND::TOTAL_CS); for (gNum = 0; gNum < nGroups; gNum++) xSection[gNum] = csc[gNum]; bRatio = FEIND::GetBratio(parent, daughterVec[rxnNum]; xSection[nGroups] = bRatio*decayConst; //HAVE TO WORK ON totalXSect totalXSect = new float[nGroups+1]; FEIND::XSec tCsc = FEIND::GetPCs(parent, FEIND::TOTAL_CS); for (gNum = 0; gNum < nGroups; gNum++) totalXSect[gNum] = tCsc[gNum]; totalXSec[nGroups] = decayConst; } E[0] = FEIND::GetDecayEnergy(parent, LIGHT_PARTICLES); E[1] = FEIND::GetDecayEnergy(parent, EM_RADIATION); E[2] = FEIND::GetDecayEnergy(parent, HEAVY_PARTICLES); data->setData(nRxns,E,daugKza,emitted,xSection,thalf,totalXSect); for (rxnNum=0;rxnNum<nRxns;rxnNum++) { delete xSection[rxnNum]; delete emitted[rxnNum]; } delete xSection; delete emitted; delete daugKza; delete totalXSect; xSection = NULL; emitted = NULL; daugKza = NULL; totalXSect = NULL; } void FEINDLib::readGammaData(int parent, GammSrc* gsrc) { } <commit_msg>Fixed bugs<commit_after>#include "FEINDLib.h" #include <math.h> FEINDLib::FEINDLib(char* arg0, char* arg1, char* arg2, int setType) : DataLib(setType) { FEIND::LibDefine lib; lib.Args.push_back(" "); int libCase = -9; if (arg0 == "EAF") libCase = 1; else if (arg0 == "CINDER") libCase = 2; switch (libCase) { case 1: //Load decay library lib.Format = FEIND::DECAY_ENDF_6; lib.Args[0] = arg1; //*** LOAD THE LIBRARY ***// try{ FEIND::LoadLibrary(lib); } catch(FEIND::Exception& ex) { ex.Abort(); } //Load activation library lib.Format = FEIND::EAF_4_1; nGroups = 175; lib.Args[0] = arg2; //*** LOAD THE LIBRARY ***// try{ FEIND::LoadLibrary(lib); } catch(FEIND::Exception& ex) { ex.Abort(); } break; case 2: lib.Format = FEIND::CINDER; nGroups = 63; lib.Args[0] = arg1; lib.Args.push_back(arg2); //*** LOAD THE LIBRARY ***// try{ FEIND::LoadLibrary(lib); } catch(FEIND::Exception& ex) { ex.Abort(); } break; default: cerr << "*** ERROR LOADING NUCLEAR LIBRARY...\n" << "Unknown nuclear data format \"" << arg0 << "\" encountered." << "\n\nABORTING\n\n"; exit(0); } nParents = (FEIND::Library.Parents()).size(); } void FEINDLib::readData(int parent, NuclearData* data) { int checkKza, nRxns=0; float thalf = 0, E[3] = {0,0,0}; int *daughKza = NULL; char **emitted = NULL; float **xSection = NULL, *totalXSect=NULL; int rxnNum, emittedLen, numNZGrps, gNum; float bRatio; float decayConst = FEIND::Library.GetDecayConstant(parent); thalf = log(2.0)/decayConst; vector<int> daughterVec = FEIND::Library.Daughters(parent); nRxns = daughterVec.size(); daughKza = new int[nRxns]; xSection = new float*[nRxns]; emitted = new char*[nRxns]; for (rxnNum = 0; rxnNum < nRxns; rxnNum++) { *daughKza = daughterVec[rxnNum]; daughKza++; //Create emitted[rxnNum]. Currently, FEIND cannot handle types of reaction. emitted[rxnNum] = new char[3+1]; emitted[rxnNum][0] = 'x'; emitted[rxnNum][1] = 'x'; emitted[rxnNum][2] = 'x'; emitted[rxnNum][3] = '\0'; //Create xSection[rxnNum] with a size of nGroups+1 xSection[rxnNum] = new float[nGroups+1]; FEIND::XSec csc = FEIND::Library.GetDCs(parent, daughterVec[rxnNum], FEIND::TOTAL_CS); for (gNum = 0; gNum < nGroups; gNum++) *xSection[gNum] = csc[gNum]; bRatio = FEIND::Library.GetBratio(parent, daughterVec[rxnNum]); *xSection[nGroups] = bRatio*decayConst; totalXSect = new float[nGroups+1]; FEIND::XSec tCsc = FEIND::Library.GetPCs(parent, FEIND::TOTAL_CS); for (gNum = 0; gNum < nGroups; gNum++) totalXSect[gNum] = tCsc[gNum]; totalXSect[nGroups] = decayConst; } E[0] = FEIND::Library.GetDecayEnergy(parent, FEIND::LIGHT_PARTICLES); E[1] = FEIND::Library.GetDecayEnergy(parent, FEIND::EM_RADIATION); E[2] = FEIND::Library.GetDecayEnergy(parent, FEIND::HEAVY_PARTICLES); data->setData(nRxns,E,daughKza,emitted,xSection,thalf,totalXSect); for (rxnNum=0;rxnNum<nRxns;rxnNum++) { delete xSection[rxnNum]; delete emitted[rxnNum]; } delete xSection; delete emitted; delete daughKza; delete totalXSect; xSection = NULL; emitted = NULL; daughKza = NULL; totalXSect = NULL; } void FEINDLib::readGammaData(int parent, GammaSrc* gsrc) { } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2019, Image Engine Design 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 John Haddon nor the names of // any other contributors to this software 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 "GafferOSL/OSLObject.h" #include "GafferOSL/ClosurePlug.h" #include "GafferUI/Nodule.h" #include "GafferUI/NoduleLayout.h" #include "GafferUI/PlugAdder.h" #include "Gaffer/Metadata.h" #include "Gaffer/MetadataAlgo.h" #include "Gaffer/ScriptNode.h" #include "Gaffer/UndoScope.h" #include "Gaffer/NameValuePlug.h" #include "Gaffer/PlugAlgo.h" #include "IECore/CompoundData.h" #include "boost/bind.hpp" using namespace std; using namespace Gaffer; using namespace GafferUI; namespace { class OSLObjectPlugAdder : public PlugAdder { public : OSLObjectPlugAdder( GraphComponentPtr plugsParent ) : m_plugsParent( IECore::runTimeCast<Plug>( plugsParent ) ) { if( ! m_plugsParent ) { throw IECore::Exception( "OSLObjectUI::PlugAdder constructor must be passed plug" ); } buttonReleaseSignal().connect( boost::bind( &OSLObjectPlugAdder::buttonRelease, this, ::_2 ) ); } protected : bool canCreateConnection( const Plug *endpoint ) const override { IECore::ConstCompoundDataPtr plugAdderOptions = Metadata::value<IECore::CompoundData>( m_plugsParent->node(), "plugAdderOptions" ); return !availablePrimVars( plugAdderOptions.get(), endpoint ).empty(); } void createConnection( Plug *endpoint ) override { IECore::ConstCompoundDataPtr plugAdderOptions = Metadata::value<IECore::CompoundData>( m_plugsParent->node(), "plugAdderOptions" ); vector<std::string> names = availablePrimVars( plugAdderOptions.get(), endpoint ); std::string picked = menuSignal()( "Connect To", names ); if( !picked.size() ) { return; } NameValuePlug *newPlug = addPlug( picked, plugAdderOptions->member<IECore::Data>( picked ) ); newPlug->valuePlug()->setInput( endpoint ); } private : std::set<std::string> usedNames() const { std::set<std::string> used; for( NameValuePlugIterator it( m_plugsParent.get() ); !it.done(); ++it ) { // TODO - this method for checking if a plug variesWithContext should probably live in PlugAlgo // ( it's based on Switch::variesWithContext ) PlugPtr sourcePlug = (*it)->namePlug()->source<Gaffer::Plug>(); bool variesWithContext = sourcePlug->direction() == Plug::Out && IECore::runTimeCast<const ComputeNode>( sourcePlug->node() ); if( !variesWithContext ) { used.insert( (*it)->namePlug()->getValue() ); } } return used; } NameValuePlug* addPlug( std::string primVarName, const IECore::Data *defaultData ) { std::set<std::string> used = usedNames(); std::string plugName = "primitiveVariable"; PlugPtr valuePlug; if( defaultData ) { if( used.find( primVarName ) != used.end() ) { std::string newName; for( int i = 2; ; i++ ) { newName = primVarName + std::to_string( i ); if( used.find( newName ) == used.end() ) { break; } } primVarName = newName; } valuePlug = PlugAlgo::createPlugFromData( "value", Plug::In, Plug::Flags::Default | Plug::Flags::Dynamic, defaultData ); } else { valuePlug = new GafferOSL::ClosurePlug( "value", Plug::In, Plug::Flags::Default | Plug::Flags::Dynamic ); plugName = "closure"; primVarName = ""; } UndoScope undoScope( m_plugsParent->ancestor<ScriptNode>() ); NameValuePlugPtr created = new Gaffer::NameValuePlug( primVarName, valuePlug, true, plugName ); m_plugsParent->addChild( created ); return created.get(); } bool buttonRelease( const ButtonEvent &event ) { IECore::ConstCompoundDataPtr plugAdderOptions = Metadata::value<IECore::CompoundData>( m_plugsParent->node(), "plugAdderOptions" ); vector<std::string> origNames = availablePrimVars( plugAdderOptions.get() ); map<std::string, std::string> nameMapping; vector<std::string> standardMenuNames; vector<std::string> customMenuNames; vector<std::string> advancedMenuNames; for( auto &n : origNames ) { std::string menuName; if( n.substr( 0, 6 ) == "custom" ) { menuName = "Custom/" + n.substr( 6 ); customMenuNames.push_back( menuName ); } else if( n == "closure" ) { menuName = "Advanced/Closure"; advancedMenuNames.push_back( menuName ); } else { menuName = "Standard/" + n; standardMenuNames.push_back( menuName ); } nameMapping[ menuName ] = n; } vector<std::string> menuNames; menuNames.insert( menuNames.end(), standardMenuNames.begin(), standardMenuNames.end() ); menuNames.insert( menuNames.end(), customMenuNames.begin(), customMenuNames.end() ); menuNames.insert( menuNames.end(), advancedMenuNames.begin(), advancedMenuNames.end() ); std::string picked = menuSignal()( "Add Input", menuNames ); if( !picked.size() ) { return false; } std::string origName = nameMapping[picked]; addPlug( origName, plugAdderOptions->member<IECore::Data>(origName) ); return true; } // Which prim vars are available that haven't already been used, and that match the input plug if provided vector<std::string> availablePrimVars( const IECore::CompoundData* plugAdderOptions, const Plug *input = nullptr ) const { if( !plugAdderOptions ) { throw IECore::Exception( "OSLObjectUI::PlugAdder requires plugAdderOptions metadata" ); } IECore::DataPtr matchingDataType; const ValuePlug *valueInput = IECore::runTimeCast< const ValuePlug >( input ); if( valueInput ) { matchingDataType = PlugAlgo::extractDataFromPlug( valueInput ); } vector<std::string> result; std::set<std::string> used = usedNames(); for( auto it=plugAdderOptions->readable().begin(); it!=plugAdderOptions->readable().end(); it++ ) { std::string name = it->first; // For plugs that aren't closures or custom, we need to check if we've already // used the primitive variable name if( it->second && name.substr( 0, 6 ) != "custom" && used.find( name ) != used.end() ) { // Already added continue; } if( input ) { if( input->typeId() == GafferOSL::ClosurePlug::staticTypeId() ) { if( it->second ) { continue; } } else { if( !matchingDataType || !it->second || matchingDataType->typeId() != it->second->typeId() ) { continue; } } } result.push_back( name ); } std::sort( result.begin(), result.end() ); return result; } PlugPtr m_plugsParent; }; struct Registration { Registration() { NoduleLayout::registerCustomGadget( "GafferOSLUI.OSLObjectUI.PlugAdder", boost::bind( &create, ::_1 ) ); } private : static GadgetPtr create( GraphComponentPtr parent ) { return new OSLObjectPlugAdder( parent ); } }; Registration g_registration; } // namespace <commit_msg>OSLObjectUI.PlugAdder : Fix exception with unsupported plug types<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2019, Image Engine Design 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 John Haddon nor the names of // any other contributors to this software 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 "GafferOSL/OSLObject.h" #include "GafferOSL/ClosurePlug.h" #include "GafferUI/Nodule.h" #include "GafferUI/NoduleLayout.h" #include "GafferUI/PlugAdder.h" #include "Gaffer/Metadata.h" #include "Gaffer/MetadataAlgo.h" #include "Gaffer/ScriptNode.h" #include "Gaffer/UndoScope.h" #include "Gaffer/NameValuePlug.h" #include "Gaffer/PlugAlgo.h" #include "IECore/CompoundData.h" #include "boost/bind.hpp" using namespace std; using namespace Gaffer; using namespace GafferUI; namespace { class OSLObjectPlugAdder : public PlugAdder { public : OSLObjectPlugAdder( GraphComponentPtr plugsParent ) : m_plugsParent( IECore::runTimeCast<Plug>( plugsParent ) ) { if( ! m_plugsParent ) { throw IECore::Exception( "OSLObjectUI::PlugAdder constructor must be passed plug" ); } buttonReleaseSignal().connect( boost::bind( &OSLObjectPlugAdder::buttonRelease, this, ::_2 ) ); } protected : bool canCreateConnection( const Plug *endpoint ) const override { IECore::ConstCompoundDataPtr plugAdderOptions = Metadata::value<IECore::CompoundData>( m_plugsParent->node(), "plugAdderOptions" ); return !availablePrimVars( plugAdderOptions.get(), endpoint ).empty(); } void createConnection( Plug *endpoint ) override { IECore::ConstCompoundDataPtr plugAdderOptions = Metadata::value<IECore::CompoundData>( m_plugsParent->node(), "plugAdderOptions" ); vector<std::string> names = availablePrimVars( plugAdderOptions.get(), endpoint ); std::string picked = menuSignal()( "Connect To", names ); if( !picked.size() ) { return; } NameValuePlug *newPlug = addPlug( picked, plugAdderOptions->member<IECore::Data>( picked ) ); newPlug->valuePlug()->setInput( endpoint ); } private : std::set<std::string> usedNames() const { std::set<std::string> used; for( NameValuePlugIterator it( m_plugsParent.get() ); !it.done(); ++it ) { // TODO - this method for checking if a plug variesWithContext should probably live in PlugAlgo // ( it's based on Switch::variesWithContext ) PlugPtr sourcePlug = (*it)->namePlug()->source<Gaffer::Plug>(); bool variesWithContext = sourcePlug->direction() == Plug::Out && IECore::runTimeCast<const ComputeNode>( sourcePlug->node() ); if( !variesWithContext ) { used.insert( (*it)->namePlug()->getValue() ); } } return used; } NameValuePlug* addPlug( std::string primVarName, const IECore::Data *defaultData ) { std::set<std::string> used = usedNames(); std::string plugName = "primitiveVariable"; PlugPtr valuePlug; if( defaultData ) { if( used.find( primVarName ) != used.end() ) { std::string newName; for( int i = 2; ; i++ ) { newName = primVarName + std::to_string( i ); if( used.find( newName ) == used.end() ) { break; } } primVarName = newName; } valuePlug = PlugAlgo::createPlugFromData( "value", Plug::In, Plug::Flags::Default | Plug::Flags::Dynamic, defaultData ); } else { valuePlug = new GafferOSL::ClosurePlug( "value", Plug::In, Plug::Flags::Default | Plug::Flags::Dynamic ); plugName = "closure"; primVarName = ""; } UndoScope undoScope( m_plugsParent->ancestor<ScriptNode>() ); NameValuePlugPtr created = new Gaffer::NameValuePlug( primVarName, valuePlug, true, plugName ); m_plugsParent->addChild( created ); return created.get(); } bool buttonRelease( const ButtonEvent &event ) { IECore::ConstCompoundDataPtr plugAdderOptions = Metadata::value<IECore::CompoundData>( m_plugsParent->node(), "plugAdderOptions" ); vector<std::string> origNames = availablePrimVars( plugAdderOptions.get() ); map<std::string, std::string> nameMapping; vector<std::string> standardMenuNames; vector<std::string> customMenuNames; vector<std::string> advancedMenuNames; for( auto &n : origNames ) { std::string menuName; if( n.substr( 0, 6 ) == "custom" ) { menuName = "Custom/" + n.substr( 6 ); customMenuNames.push_back( menuName ); } else if( n == "closure" ) { menuName = "Advanced/Closure"; advancedMenuNames.push_back( menuName ); } else { menuName = "Standard/" + n; standardMenuNames.push_back( menuName ); } nameMapping[ menuName ] = n; } vector<std::string> menuNames; menuNames.insert( menuNames.end(), standardMenuNames.begin(), standardMenuNames.end() ); menuNames.insert( menuNames.end(), customMenuNames.begin(), customMenuNames.end() ); menuNames.insert( menuNames.end(), advancedMenuNames.begin(), advancedMenuNames.end() ); std::string picked = menuSignal()( "Add Input", menuNames ); if( !picked.size() ) { return false; } std::string origName = nameMapping[picked]; addPlug( origName, plugAdderOptions->member<IECore::Data>(origName) ); return true; } // Which prim vars are available that haven't already been used, and that match the input plug if provided vector<std::string> availablePrimVars( const IECore::CompoundData* plugAdderOptions, const Plug *input = nullptr ) const { if( !plugAdderOptions ) { throw IECore::Exception( "OSLObjectUI::PlugAdder requires plugAdderOptions metadata" ); } IECore::DataPtr matchingDataType; const ValuePlug *valueInput = IECore::runTimeCast< const ValuePlug >( input ); if( valueInput ) { try { matchingDataType = PlugAlgo::extractDataFromPlug( valueInput ); } catch( ... ) { // If we can't extract data, then it doesn't match any of our accepted plug types } } vector<std::string> result; std::set<std::string> used = usedNames(); for( auto it=plugAdderOptions->readable().begin(); it!=plugAdderOptions->readable().end(); it++ ) { std::string name = it->first; // For plugs that aren't closures or custom, we need to check if we've already // used the primitive variable name if( it->second && name.substr( 0, 6 ) != "custom" && used.find( name ) != used.end() ) { // Already added continue; } if( input ) { if( input->typeId() == GafferOSL::ClosurePlug::staticTypeId() ) { if( it->second ) { continue; } } else { if( !matchingDataType || !it->second || matchingDataType->typeId() != it->second->typeId() ) { continue; } } } result.push_back( name ); } std::sort( result.begin(), result.end() ); return result; } PlugPtr m_plugsParent; }; struct Registration { Registration() { NoduleLayout::registerCustomGadget( "GafferOSLUI.OSLObjectUI.PlugAdder", boost::bind( &create, ::_1 ) ); } private : static GadgetPtr create( GraphComponentPtr parent ) { return new OSLObjectPlugAdder( parent ); } }; Registration g_registration; } // namespace <|endoftext|>
<commit_before><commit_msg>when leaving dragger edit mode make sure to release the grabbed node<commit_after><|endoftext|>
<commit_before>/**************************************************************************** * * (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> * * QGroundControl is licensed according to the terms in the file * COPYING.md in the root of the source code directory. * ****************************************************************************/ #include "JoystickManager.h" #include "QGCApplication.h" #include <QQmlEngine> #ifndef __mobile__ #include "JoystickSDL.h" #define __sdljoystick__ #endif #ifdef __android__ #include "JoystickAndroid.h" #endif QGC_LOGGING_CATEGORY(JoystickManagerLog, "JoystickManagerLog") const char * JoystickManager::_settingsGroup = "JoystickManager"; const char * JoystickManager::_settingsKeyActiveJoystick = "ActiveJoystick"; JoystickManager::JoystickManager(QGCApplication* app, QGCToolbox* toolbox) : QGCTool(app, toolbox) , _activeJoystick(nullptr) , _multiVehicleManager(nullptr) { } JoystickManager::~JoystickManager() { QMap<QString, Joystick*>::iterator i; for (i = _name2JoystickMap.begin(); i != _name2JoystickMap.end(); ++i) { qCDebug(JoystickManagerLog) << "Releasing joystick:" << i.key(); delete i.value(); } qDebug() << "Done"; } void JoystickManager::setToolbox(QGCToolbox *toolbox) { QGCTool::setToolbox(toolbox); _multiVehicleManager = _toolbox->multiVehicleManager(); QQmlEngine::setObjectOwnership(this, QQmlEngine::CppOwnership); } void JoystickManager::init() { #ifdef __sdljoystick__ if (!JoystickSDL::init()) { return; } _setActiveJoystickFromSettings(); #elif defined(__android__) if (!JoystickAndroid::init(this)) { return; } connect(this, &JoystickManager::updateAvailableJoysticksSignal, this, &JoystickManager::restartJoystickCheckTimer); #endif connect(&_joystickCheckTimer, &QTimer::timeout, this, &JoystickManager::_updateAvailableJoysticks); _joystickCheckTimerCounter = 5; _joystickCheckTimer.start(1000); } void JoystickManager::_setActiveJoystickFromSettings(void) { QMap<QString,Joystick*> newMap; #ifdef __sdljoystick__ // Get the latest joystick mapping newMap = JoystickSDL::discover(_multiVehicleManager); #elif defined(__android__) newMap = JoystickAndroid::discover(_multiVehicleManager); #endif if (_activeJoystick && !newMap.contains(_activeJoystick->name())) { qCDebug(JoystickManagerLog) << "Active joystick removed"; setActiveJoystick(nullptr); } // Check to see if our current mapping contains any joysticks that are not in the new mapping // If so, those joysticks have been unplugged, and need to be cleaned up QMap<QString, Joystick*>::iterator i; for (i = _name2JoystickMap.begin(); i != _name2JoystickMap.end(); ++i) { if (!newMap.contains(i.key())) { qCDebug(JoystickManagerLog) << "Releasing joystick:" << i.key(); i.value()->stopPolling(); i.value()->wait(1000); i.value()->deleteLater(); } } _name2JoystickMap = newMap; emit availableJoysticksChanged(); if (!_name2JoystickMap.count()) { setActiveJoystick(nullptr); return; } QSettings settings; settings.beginGroup(_settingsGroup); QString name = settings.value(_settingsKeyActiveJoystick).toString(); if (name.isEmpty()) { name = _name2JoystickMap.first()->name(); } setActiveJoystick(_name2JoystickMap.value(name, _name2JoystickMap.first())); settings.setValue(_settingsKeyActiveJoystick, _activeJoystick->name()); } Joystick* JoystickManager::activeJoystick(void) { return _activeJoystick; } void JoystickManager::setActiveJoystick(Joystick* joystick) { QSettings settings; if (joystick != nullptr && !_name2JoystickMap.contains(joystick->name())) { qCWarning(JoystickManagerLog) << "Set active not in map" << joystick->name(); return; } if (_activeJoystick == joystick) { return; } if (_activeJoystick) { _activeJoystick->stopPolling(); } _activeJoystick = joystick; if (_activeJoystick != nullptr) { qCDebug(JoystickManagerLog) << "Set active:" << _activeJoystick->name(); settings.beginGroup(_settingsGroup); settings.setValue(_settingsKeyActiveJoystick, _activeJoystick->name()); } emit activeJoystickChanged(_activeJoystick); emit activeJoystickNameChanged(_activeJoystick?_activeJoystick->name():""); } QVariantList JoystickManager::joysticks(void) { QVariantList list; for (const QString &name: _name2JoystickMap.keys()) { list += QVariant::fromValue(_name2JoystickMap[name]); } return list; } QStringList JoystickManager::joystickNames(void) { return _name2JoystickMap.keys(); } QString JoystickManager::activeJoystickName(void) { return _activeJoystick ? _activeJoystick->name() : QString(); } void JoystickManager::setActiveJoystickName(const QString& name) { if (!_name2JoystickMap.contains(name)) { qCWarning(JoystickManagerLog) << "Set active not in map" << name; return; } setActiveJoystick(_name2JoystickMap[name]); } /* * TODO: move this to the right place: JoystickSDL.cc and JoystickAndroid.cc respectively and call through Joystick.cc */ void JoystickManager::_updateAvailableJoysticks() { #ifdef __sdljoystick__ SDL_Event event; while (SDL_PollEvent(&event)) { switch(event.type) { case SDL_QUIT: qCDebug(JoystickManagerLog) << "SDL ERROR:" << SDL_GetError(); break; case SDL_JOYDEVICEADDED: qCDebug(JoystickManagerLog) << "Joystick added:" << event.jdevice.which; _setActiveJoystickFromSettings(); break; case SDL_JOYDEVICEREMOVED: qCDebug(JoystickManagerLog) << "Joystick removed:" << event.jdevice.which; _setActiveJoystickFromSettings(); break; default: break; } } #elif defined(__android__) _joystickCheckTimerCounter--; _setActiveJoystickFromSettings(); if (_joystickCheckTimerCounter <= 0) { _joystickCheckTimer.stop(); } #endif } void JoystickManager::restartJoystickCheckTimer() { _joystickCheckTimerCounter = 5; _joystickCheckTimer.start(1000); } <commit_msg>remove trailing whitespaces in JoystickManager.cc<commit_after>/**************************************************************************** * * (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> * * QGroundControl is licensed according to the terms in the file * COPYING.md in the root of the source code directory. * ****************************************************************************/ #include "JoystickManager.h" #include "QGCApplication.h" #include <QQmlEngine> #ifndef __mobile__ #include "JoystickSDL.h" #define __sdljoystick__ #endif #ifdef __android__ #include "JoystickAndroid.h" #endif QGC_LOGGING_CATEGORY(JoystickManagerLog, "JoystickManagerLog") const char * JoystickManager::_settingsGroup = "JoystickManager"; const char * JoystickManager::_settingsKeyActiveJoystick = "ActiveJoystick"; JoystickManager::JoystickManager(QGCApplication* app, QGCToolbox* toolbox) : QGCTool(app, toolbox) , _activeJoystick(nullptr) , _multiVehicleManager(nullptr) { } JoystickManager::~JoystickManager() { QMap<QString, Joystick*>::iterator i; for (i = _name2JoystickMap.begin(); i != _name2JoystickMap.end(); ++i) { qCDebug(JoystickManagerLog) << "Releasing joystick:" << i.key(); delete i.value(); } qDebug() << "Done"; } void JoystickManager::setToolbox(QGCToolbox *toolbox) { QGCTool::setToolbox(toolbox); _multiVehicleManager = _toolbox->multiVehicleManager(); QQmlEngine::setObjectOwnership(this, QQmlEngine::CppOwnership); } void JoystickManager::init() { #ifdef __sdljoystick__ if (!JoystickSDL::init()) { return; } _setActiveJoystickFromSettings(); #elif defined(__android__) if (!JoystickAndroid::init(this)) { return; } connect(this, &JoystickManager::updateAvailableJoysticksSignal, this, &JoystickManager::restartJoystickCheckTimer); #endif connect(&_joystickCheckTimer, &QTimer::timeout, this, &JoystickManager::_updateAvailableJoysticks); _joystickCheckTimerCounter = 5; _joystickCheckTimer.start(1000); } void JoystickManager::_setActiveJoystickFromSettings(void) { QMap<QString,Joystick*> newMap; #ifdef __sdljoystick__ // Get the latest joystick mapping newMap = JoystickSDL::discover(_multiVehicleManager); #elif defined(__android__) newMap = JoystickAndroid::discover(_multiVehicleManager); #endif if (_activeJoystick && !newMap.contains(_activeJoystick->name())) { qCDebug(JoystickManagerLog) << "Active joystick removed"; setActiveJoystick(nullptr); } // Check to see if our current mapping contains any joysticks that are not in the new mapping // If so, those joysticks have been unplugged, and need to be cleaned up QMap<QString, Joystick*>::iterator i; for (i = _name2JoystickMap.begin(); i != _name2JoystickMap.end(); ++i) { if (!newMap.contains(i.key())) { qCDebug(JoystickManagerLog) << "Releasing joystick:" << i.key(); i.value()->stopPolling(); i.value()->wait(1000); i.value()->deleteLater(); } } _name2JoystickMap = newMap; emit availableJoysticksChanged(); if (!_name2JoystickMap.count()) { setActiveJoystick(nullptr); return; } QSettings settings; settings.beginGroup(_settingsGroup); QString name = settings.value(_settingsKeyActiveJoystick).toString(); if (name.isEmpty()) { name = _name2JoystickMap.first()->name(); } setActiveJoystick(_name2JoystickMap.value(name, _name2JoystickMap.first())); settings.setValue(_settingsKeyActiveJoystick, _activeJoystick->name()); } Joystick* JoystickManager::activeJoystick(void) { return _activeJoystick; } void JoystickManager::setActiveJoystick(Joystick* joystick) { QSettings settings; if (joystick != nullptr && !_name2JoystickMap.contains(joystick->name())) { qCWarning(JoystickManagerLog) << "Set active not in map" << joystick->name(); return; } if (_activeJoystick == joystick) { return; } if (_activeJoystick) { _activeJoystick->stopPolling(); } _activeJoystick = joystick; if (_activeJoystick != nullptr) { qCDebug(JoystickManagerLog) << "Set active:" << _activeJoystick->name(); settings.beginGroup(_settingsGroup); settings.setValue(_settingsKeyActiveJoystick, _activeJoystick->name()); } emit activeJoystickChanged(_activeJoystick); emit activeJoystickNameChanged(_activeJoystick?_activeJoystick->name():""); } QVariantList JoystickManager::joysticks(void) { QVariantList list; for (const QString &name: _name2JoystickMap.keys()) { list += QVariant::fromValue(_name2JoystickMap[name]); } return list; } QStringList JoystickManager::joystickNames(void) { return _name2JoystickMap.keys(); } QString JoystickManager::activeJoystickName(void) { return _activeJoystick ? _activeJoystick->name() : QString(); } void JoystickManager::setActiveJoystickName(const QString& name) { if (!_name2JoystickMap.contains(name)) { qCWarning(JoystickManagerLog) << "Set active not in map" << name; return; } setActiveJoystick(_name2JoystickMap[name]); } /* * TODO: move this to the right place: JoystickSDL.cc and JoystickAndroid.cc respectively and call through Joystick.cc */ void JoystickManager::_updateAvailableJoysticks() { #ifdef __sdljoystick__ SDL_Event event; while (SDL_PollEvent(&event)) { switch(event.type) { case SDL_QUIT: qCDebug(JoystickManagerLog) << "SDL ERROR:" << SDL_GetError(); break; case SDL_JOYDEVICEADDED: qCDebug(JoystickManagerLog) << "Joystick added:" << event.jdevice.which; _setActiveJoystickFromSettings(); break; case SDL_JOYDEVICEREMOVED: qCDebug(JoystickManagerLog) << "Joystick removed:" << event.jdevice.which; _setActiveJoystickFromSettings(); break; default: break; } } #elif defined(__android__) _joystickCheckTimerCounter--; _setActiveJoystickFromSettings(); if (_joystickCheckTimerCounter <= 0) { _joystickCheckTimer.stop(); } #endif } void JoystickManager::restartJoystickCheckTimer() { _joystickCheckTimerCounter = 5; _joystickCheckTimer.start(1000); } <|endoftext|>
<commit_before>#include "BLEHIDPeripheral.h" #include "BLEHID.h" unsigned char BLEHID::_numHids = 0; BLEHID::BLEHID(const unsigned char* descriptor, unsigned char descriptorLength, unsigned char reportIdOffset) : _reportId(0), _descriptor(descriptor), _descriptorLength(descriptorLength), _reportIdOffset(reportIdOffset) { _numHids++; } void BLEHID::setReportId(unsigned char reportId) { this->_reportId = reportId; } unsigned char BLEHID::getDescriptorLength() { return this->_descriptorLength; } unsigned char BLEHID::getDescriptorValueAtOffset(unsigned char offset) { if (offset == this->_reportIdOffset) { return this->_reportId; } else { return pgm_read_byte_near(&this->_descriptor[offset]); } } unsigned char BLEHID::numHids() { return _numHids; } void BLEHID::sendData(BLECharacteristic& characteristic, unsigned char data[], unsigned char length) { // wait until we can notify while(!characteristic.canNotify()) { BLEHIDPeripheral::instance()->poll(); } characteristic.setValue(data, length); } <commit_msg>Ignore report ID offset's that are 0<commit_after>#include "BLEHIDPeripheral.h" #include "BLEHID.h" unsigned char BLEHID::_numHids = 0; BLEHID::BLEHID(const unsigned char* descriptor, unsigned char descriptorLength, unsigned char reportIdOffset) : _reportId(0), _descriptor(descriptor), _descriptorLength(descriptorLength), _reportIdOffset(reportIdOffset) { _numHids++; } void BLEHID::setReportId(unsigned char reportId) { this->_reportId = reportId; } unsigned char BLEHID::getDescriptorLength() { return this->_descriptorLength; } unsigned char BLEHID::getDescriptorValueAtOffset(unsigned char offset) { if (offset == this->_reportIdOffset && this->_reportIdOffset) { return this->_reportId; } else { return pgm_read_byte_near(&this->_descriptor[offset]); } } unsigned char BLEHID::numHids() { return _numHids; } void BLEHID::sendData(BLECharacteristic& characteristic, unsigned char data[], unsigned char length) { // wait until we can notify while(!characteristic.canNotify()) { BLEHIDPeripheral::instance()->poll(); } characteristic.setValue(data, length); } <|endoftext|>
<commit_before>/* * Copyright 2012-2013 BrewPi/Elco Jacobs. * * This file is part of BrewPi. * * BrewPi is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BrewPi 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 BrewPi. If not, see <http://www.gnu.org/licenses/>. */ /* * This Atmel Studio 6 project automatically includes all needed Arduino source files, you just have to point it to the right directories. * To compile this project on your computer, you will have to set an environment variable to find your local Arduino installation. * Set the variable ARDUINO_HOME to point to your local Arduino path, without trailing slash, e.g. 'D:\arduino-1.01'. Instructions on the wiki here: * http://wiki.brewpi.com/index.php/Setting_up_the_brewpi-avr_Project * 'ArduinoFunctions.cpp' includes all the source files from Arduino that are used. You might have to edit it if you are not using a Leonardo. * That is all that is needed! No hassle with makefiles and compiling libraries. */ #include "Brewpi.h" #include "Ticks.h" #include "Display.h" #include "TempControl.h" #include "PiLink.h" #include "Menu.h" #include "Pins.h" #include "RotaryEncoder.h" #include "Buzzer.h" #include "TempSensor.h" #include "TempSensorMock.h" #include "OneWireTempSensor.h" #include "TempSensorExternal.h" #include "Ticks.h" #include "Sensor.h" #include "FastDigitalPin.h" #include "OneWireActuator.h" #include "SettingsManager.h" #if BREWPI_SIMULATE #include "Simulator.h" #endif // global class objects static and defined in class cpp and h files // instantiate and configure the sensors, actuators and controllers we want to use void setup(void); void loop (void); /* Configure the counter and delay timer. The actual type of these will vary depending upon the environment. * They are non-virtual to keep code size minimal, so typedefs and preprocessing are used to select the actual compile-time type used. */ TicksImpl ticks = TicksImpl(TICKS_IMPL_CONFIG); DelayImpl wait = DelayImpl(DELAY_IMPL_CONFIG); DisplayType realDisplay; DisplayType DISPLAY_REF display = realDisplay; void setup() { piLink.init(); logDebug("started"); tempControl.init(); settingsManager.loadSettings(); #if BREWPI_SIMULATE simulator.step(); // initialize the filters with the assigned initial temp value tempControl.beerSensor->init(); tempControl.fridgeSensor->init(); #endif display.init(); display.printStationaryText(); display.printState(); rotaryEncoder.init(); #if BREWPI_BUZZER buzzer.init(); buzzer.beep(2, 500); #endif logDebug("init complete"); } void brewpiLoop(void) { static unsigned long lastUpdate = 0; uint8_t oldState; if(ticks.millis() - lastUpdate >= (1000)) { //update settings every second lastUpdate = ticks.millis(); tempControl.updateTemperatures(); tempControl.detectPeaks(); tempControl.updatePID(); oldState = tempControl.getState(); tempControl.updateState(); if(oldState != tempControl.getState()){ piLink.printTemperatures(); // add a data point at every state transition } tempControl.updateOutputs(); #if BREWPI_MENU if(rotaryEncoder.pushed()){ rotaryEncoder.resetPushed(); menu.pickSettingToChange(); } #endif // update the lcd for the chamber being displayed display.printState(); display.printAllTemperatures(); display.printMode(); display.updateBacklight(); } //listen for incoming serial connections while waiting to update piLink.receive(); } void loop() { #if BREWPI_SIMULATE simulateLoop(); #else brewpiLoop(); #endif } <commit_msg>Make beep the first thing at boot. This is more useful for debugging: you know when the bootloader stops and brewpi starts.<commit_after>/* * Copyright 2012-2013 BrewPi/Elco Jacobs. * * This file is part of BrewPi. * * BrewPi is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BrewPi 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 BrewPi. If not, see <http://www.gnu.org/licenses/>. */ /* * This Atmel Studio 6 project automatically includes all needed Arduino source files, you just have to point it to the right directories. * To compile this project on your computer, you will have to set an environment variable to find your local Arduino installation. * Set the variable ARDUINO_HOME to point to your local Arduino path, without trailing slash, e.g. 'D:\arduino-1.01'. Instructions on the wiki here: * http://wiki.brewpi.com/index.php/Setting_up_the_brewpi-avr_Project * 'ArduinoFunctions.cpp' includes all the source files from Arduino that are used. You might have to edit it if you are not using a Leonardo. * That is all that is needed! No hassle with makefiles and compiling libraries. */ #include "Brewpi.h" #include "Ticks.h" #include "Display.h" #include "TempControl.h" #include "PiLink.h" #include "Menu.h" #include "Pins.h" #include "RotaryEncoder.h" #include "Buzzer.h" #include "TempSensor.h" #include "TempSensorMock.h" #include "OneWireTempSensor.h" #include "TempSensorExternal.h" #include "Ticks.h" #include "Sensor.h" #include "FastDigitalPin.h" #include "OneWireActuator.h" #include "SettingsManager.h" #if BREWPI_SIMULATE #include "Simulator.h" #endif // global class objects static and defined in class cpp and h files // instantiate and configure the sensors, actuators and controllers we want to use void setup(void); void loop (void); /* Configure the counter and delay timer. The actual type of these will vary depending upon the environment. * They are non-virtual to keep code size minimal, so typedefs and preprocessing are used to select the actual compile-time type used. */ TicksImpl ticks = TicksImpl(TICKS_IMPL_CONFIG); DelayImpl wait = DelayImpl(DELAY_IMPL_CONFIG); DisplayType realDisplay; DisplayType DISPLAY_REF display = realDisplay; void setup() { #if BREWPI_BUZZER buzzer.init(); buzzer.beep(2, 500); #endif piLink.init(); logDebug("started"); tempControl.init(); settingsManager.loadSettings(); #if BREWPI_SIMULATE simulator.step(); // initialize the filters with the assigned initial temp value tempControl.beerSensor->init(); tempControl.fridgeSensor->init(); #endif display.init(); display.printStationaryText(); display.printState(); rotaryEncoder.init(); logDebug("init complete"); } void brewpiLoop(void) { static unsigned long lastUpdate = 0; uint8_t oldState; if(ticks.millis() - lastUpdate >= (1000)) { //update settings every second lastUpdate = ticks.millis(); tempControl.updateTemperatures(); tempControl.detectPeaks(); tempControl.updatePID(); oldState = tempControl.getState(); tempControl.updateState(); if(oldState != tempControl.getState()){ piLink.printTemperatures(); // add a data point at every state transition } tempControl.updateOutputs(); #if BREWPI_MENU if(rotaryEncoder.pushed()){ rotaryEncoder.resetPushed(); menu.pickSettingToChange(); } #endif // update the lcd for the chamber being displayed display.printState(); display.printAllTemperatures(); display.printMode(); display.updateBacklight(); } //listen for incoming serial connections while waiting to update piLink.receive(); } void loop() { #if BREWPI_SIMULATE simulateLoop(); #else brewpiLoop(); #endif } <|endoftext|>
<commit_before>/** * @file * * @brief * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) */ #include "dump.hpp" using namespace ckdb; #include <fstream> #include <iostream> #include <sstream> #include <string> #include <vector> #include <unistd.h> #include <kdberrors.h> #include <kdblogger.h> namespace dump { int serialise (std::ostream & os, ckdb::Key *, ckdb::KeySet * ks) { ckdb::Key * cur; os << "kdbOpen 1" << std::endl; os << "ksNew " << ckdb::ksGetSize (ks) << std::endl; ckdb::KeySet * metacopies = ckdb::ksNew (0, KS_END); ksRewind (ks); while ((cur = ksNext (ks)) != nullptr) { size_t namesize = ckdb::keyGetNameSize (cur); size_t valuesize = ckdb::keyGetValueSize (cur); os << "keyNew " << namesize << " " << valuesize << std::endl; os.write (ckdb::keyName (cur), namesize); os.write (static_cast<const char *> (ckdb::keyValue (cur)), valuesize); os << std::endl; const ckdb::Key * meta; ckdb::keyRewindMeta (cur); while ((meta = ckdb::keyNextMeta (cur)) != nullptr) { std::stringstream ss; ss << "user/" << meta; // use the address of pointer as name ckdb::Key * search = ckdb::keyNew (ss.str ().c_str (), KEY_END); ckdb::Key * ret = ksLookup (metacopies, search, 0); if (!ret) { /* This metakey was not serialised up to now */ size_t metanamesize = ckdb::keyGetNameSize (meta); size_t metavaluesize = ckdb::keyGetValueSize (meta); os << "keyMeta " << metanamesize << " " << metavaluesize << std::endl; os.write (ckdb::keyName (meta), metanamesize); os.write (static_cast<const char *> (ckdb::keyValue (meta)), metavaluesize); os << std::endl; std::stringstream ssv; ssv << namesize << " " << metanamesize << std::endl; ssv.write (ckdb::keyName (cur), namesize); ssv.write (ckdb::keyName (meta), metanamesize); ckdb::keySetRaw (search, ssv.str ().c_str (), ssv.str ().size ()); ksAppendKey (metacopies, search); } else { /* Meta key already serialised, write out a reference to it */ keyDel (search); os << "keyCopyMeta "; os.write (static_cast<const char *> (ckdb::keyValue (ret)), ckdb::keyGetValueSize (ret)); os << std::endl; } } os << "keyEnd" << std::endl; } os << "ksEnd" << std::endl; ksDel (metacopies); return 1; } int unserialise (std::istream & is, ckdb::Key * errorKey, ckdb::KeySet * ks) { ckdb::Key * cur = nullptr; std::vector<char> namebuffer (4048); std::vector<char> valuebuffer (4048); std::string line; std::string command; size_t nrKeys; size_t namesize; size_t valuesize; while (std::getline (is, line)) { std::stringstream ss (line); ss >> command; if (command == "kdbOpen") { std::string version; ss >> version; if (version != "1") { ELEKTRA_SET_ERROR (50, errorKey, version.c_str ()); return -1; } } else if (command == "ksNew") { ss >> nrKeys; ksClear (ks); } else if (command == "keyNew") { cur = ckdb::keyNew (nullptr); ss >> namesize; ss >> valuesize; if (namesize > namebuffer.size ()) namebuffer.resize (namesize + 1); is.read (&namebuffer[0], namesize); namebuffer[namesize] = 0; ckdb::keySetName (cur, &namebuffer[0]); if (valuesize > valuebuffer.size ()) valuebuffer.resize (valuesize + 1); is.read (&valuebuffer[0], valuesize); valuebuffer[valuesize] = 0; ckdb::keySetRaw (cur, &valuebuffer[0], valuesize); std::getline (is, line); } else if (command == "keyMeta") { ss >> namesize; ss >> valuesize; if (namesize > namebuffer.size ()) namebuffer.resize (namesize + 1); is.read (&namebuffer[0], namesize); namebuffer[namesize] = 0; if (valuesize > valuebuffer.size ()) valuebuffer.resize (valuesize + 1); is.read (&valuebuffer[0], valuesize); valuebuffer[valuesize] = 0; keySetMeta (cur, &namebuffer[0], &valuebuffer[0]); std::getline (is, line); } else if (command == "keyCopyMeta") { ss >> namesize; ss >> valuesize; if (namesize > namebuffer.size ()) namebuffer.resize (namesize + 1); is.read (&namebuffer[0], namesize); namebuffer[namesize] = 0; if (valuesize > valuebuffer.size ()) valuebuffer.resize (valuesize + 1); is.read (&valuebuffer[0], valuesize); valuebuffer[valuesize] = 0; ckdb::Key * search = ckdb::ksLookupByName (ks, &namebuffer[0], 0); ckdb::keyCopyMeta (cur, search, &valuebuffer[0]); std::getline (is, line); } else if (command == "keyEnd") { ckdb::ksAppendKey (ks, cur); cur = nullptr; } else if (command == "ksEnd") { break; } else { ELEKTRA_SET_ERROR (49, errorKey, command.c_str ()); return -1; } } return 1; } class pipebuf : public std::streambuf { char * buffer_; int fd_; public: pipebuf (int fd) : buffer_ (new char[4096]), fd_ (fd) { } ~pipebuf () { delete[] this->buffer_; } int underflow () { if (this->gptr () == this->egptr ()) { // read from the pipe directly, using an ifstream on // /dev/fd/<fd> fails on macOS ssize_t r = read (fd_, buffer_, 4096); this->setg (this->buffer_, this->buffer_, this->buffer_ + r); } return this->gptr () == this->egptr () ? std::char_traits<char>::eof () : std::char_traits<char>::to_int_type (*this->gptr ()); } }; } // namespace dump extern "C" { int elektraDumpGet (ckdb::Plugin *, ckdb::KeySet * returned, ckdb::Key * parentKey) { Key * root = ckdb::keyNew ("system/elektra/modules/dump", KEY_END); if (keyRel (root, parentKey) >= 0) { keyDel (root); KeySet * n = ksNew (50, keyNew ("system/elektra/modules/dump", KEY_VALUE, "dump plugin waits for your orders", KEY_END), keyNew ("system/elektra/modules/dump/exports", KEY_END), keyNew ("system/elektra/modules/dump/exports/get", KEY_FUNC, elektraDumpGet, KEY_END), keyNew ("system/elektra/modules/dump/exports/set", KEY_FUNC, elektraDumpSet, KEY_END), keyNew ("system/elektra/modules/dump/exports/serialise", KEY_FUNC, dump::serialise, KEY_END), keyNew ("system/elektra/modules/dump/exports/unserialise", KEY_FUNC, dump::unserialise, KEY_END), keyNew ("system/elektra/modules/dump/config/needs/fcrypt/textmode", KEY_VALUE, "0", KEY_END), #include "readme_dump.c" keyNew ("system/elektra/modules/dump/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END); ksAppend (returned, n); ksDel (n); return 1; } keyDel (root); int errnosave = errno; // We use dump for the processplugin library. Unfortunately on macOS reading from /dev/fd/<fd> via // ifstream fails, thus we read directly from unnamed pipes using a custom buffer and read const char pipe[] = "/dev/fd/"; if (!strncmp (keyString (parentKey), pipe, strlen (pipe))) { int fd = std::stoi (std::string (keyString (parentKey) + strlen (pipe))); dump::pipebuf pipebuf (fd); std::istream is (&pipebuf); return dump::unserialise (is, parentKey, returned); } else { // ELEKTRA_LOG (ELEKTRA_LOG_MODULE_DUMP, "opening file %s", keyString (parentKey)); std::ifstream is (keyString (parentKey), std::ios::binary); if (!is.is_open ()) { ELEKTRA_SET_ERROR_GET (parentKey); errno = errnosave; return -1; } return dump::unserialise (is, parentKey, returned); } } int elektraDumpSet (ckdb::Plugin *, ckdb::KeySet * returned, ckdb::Key * parentKey) { int errnosave = errno; // ELEKTRA_LOG (ELEKTRA_LOG_MODULE_DUMP, "opening file %s", keyString (parentKey)); std::ofstream ofs (keyString (parentKey), std::ios::binary); if (!ofs.is_open ()) { ELEKTRA_SET_ERROR_SET (parentKey); errno = errnosave; return -1; } return dump::serialise (ofs, parentKey, returned); } ckdb::Plugin * ELEKTRA_PLUGIN_EXPORT (dump) { // clang-format off return elektraPluginExport("dump", ELEKTRA_PLUGIN_GET, &elektraDumpGet, ELEKTRA_PLUGIN_SET, &elektraDumpSet, ELEKTRA_PLUGIN_END); } } // extern C <commit_msg>pluginprocess: fix typo in comment<commit_after>/** * @file * * @brief * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) */ #include "dump.hpp" using namespace ckdb; #include <fstream> #include <iostream> #include <sstream> #include <string> #include <vector> #include <unistd.h> #include <kdberrors.h> #include <kdblogger.h> namespace dump { int serialise (std::ostream & os, ckdb::Key *, ckdb::KeySet * ks) { ckdb::Key * cur; os << "kdbOpen 1" << std::endl; os << "ksNew " << ckdb::ksGetSize (ks) << std::endl; ckdb::KeySet * metacopies = ckdb::ksNew (0, KS_END); ksRewind (ks); while ((cur = ksNext (ks)) != nullptr) { size_t namesize = ckdb::keyGetNameSize (cur); size_t valuesize = ckdb::keyGetValueSize (cur); os << "keyNew " << namesize << " " << valuesize << std::endl; os.write (ckdb::keyName (cur), namesize); os.write (static_cast<const char *> (ckdb::keyValue (cur)), valuesize); os << std::endl; const ckdb::Key * meta; ckdb::keyRewindMeta (cur); while ((meta = ckdb::keyNextMeta (cur)) != nullptr) { std::stringstream ss; ss << "user/" << meta; // use the address of pointer as name ckdb::Key * search = ckdb::keyNew (ss.str ().c_str (), KEY_END); ckdb::Key * ret = ksLookup (metacopies, search, 0); if (!ret) { /* This metakey was not serialised up to now */ size_t metanamesize = ckdb::keyGetNameSize (meta); size_t metavaluesize = ckdb::keyGetValueSize (meta); os << "keyMeta " << metanamesize << " " << metavaluesize << std::endl; os.write (ckdb::keyName (meta), metanamesize); os.write (static_cast<const char *> (ckdb::keyValue (meta)), metavaluesize); os << std::endl; std::stringstream ssv; ssv << namesize << " " << metanamesize << std::endl; ssv.write (ckdb::keyName (cur), namesize); ssv.write (ckdb::keyName (meta), metanamesize); ckdb::keySetRaw (search, ssv.str ().c_str (), ssv.str ().size ()); ksAppendKey (metacopies, search); } else { /* Meta key already serialised, write out a reference to it */ keyDel (search); os << "keyCopyMeta "; os.write (static_cast<const char *> (ckdb::keyValue (ret)), ckdb::keyGetValueSize (ret)); os << std::endl; } } os << "keyEnd" << std::endl; } os << "ksEnd" << std::endl; ksDel (metacopies); return 1; } int unserialise (std::istream & is, ckdb::Key * errorKey, ckdb::KeySet * ks) { ckdb::Key * cur = nullptr; std::vector<char> namebuffer (4048); std::vector<char> valuebuffer (4048); std::string line; std::string command; size_t nrKeys; size_t namesize; size_t valuesize; while (std::getline (is, line)) { std::stringstream ss (line); ss >> command; if (command == "kdbOpen") { std::string version; ss >> version; if (version != "1") { ELEKTRA_SET_ERROR (50, errorKey, version.c_str ()); return -1; } } else if (command == "ksNew") { ss >> nrKeys; ksClear (ks); } else if (command == "keyNew") { cur = ckdb::keyNew (nullptr); ss >> namesize; ss >> valuesize; if (namesize > namebuffer.size ()) namebuffer.resize (namesize + 1); is.read (&namebuffer[0], namesize); namebuffer[namesize] = 0; ckdb::keySetName (cur, &namebuffer[0]); if (valuesize > valuebuffer.size ()) valuebuffer.resize (valuesize + 1); is.read (&valuebuffer[0], valuesize); valuebuffer[valuesize] = 0; ckdb::keySetRaw (cur, &valuebuffer[0], valuesize); std::getline (is, line); } else if (command == "keyMeta") { ss >> namesize; ss >> valuesize; if (namesize > namebuffer.size ()) namebuffer.resize (namesize + 1); is.read (&namebuffer[0], namesize); namebuffer[namesize] = 0; if (valuesize > valuebuffer.size ()) valuebuffer.resize (valuesize + 1); is.read (&valuebuffer[0], valuesize); valuebuffer[valuesize] = 0; keySetMeta (cur, &namebuffer[0], &valuebuffer[0]); std::getline (is, line); } else if (command == "keyCopyMeta") { ss >> namesize; ss >> valuesize; if (namesize > namebuffer.size ()) namebuffer.resize (namesize + 1); is.read (&namebuffer[0], namesize); namebuffer[namesize] = 0; if (valuesize > valuebuffer.size ()) valuebuffer.resize (valuesize + 1); is.read (&valuebuffer[0], valuesize); valuebuffer[valuesize] = 0; ckdb::Key * search = ckdb::ksLookupByName (ks, &namebuffer[0], 0); ckdb::keyCopyMeta (cur, search, &valuebuffer[0]); std::getline (is, line); } else if (command == "keyEnd") { ckdb::ksAppendKey (ks, cur); cur = nullptr; } else if (command == "ksEnd") { break; } else { ELEKTRA_SET_ERROR (49, errorKey, command.c_str ()); return -1; } } return 1; } class pipebuf : public std::streambuf { char * buffer_; int fd_; public: pipebuf (int fd) : buffer_ (new char[4096]), fd_ (fd) { } ~pipebuf () { delete[] this->buffer_; } int underflow () { if (this->gptr () == this->egptr ()) { // read from the pipe directly into the buffer ssize_t r = read (fd_, buffer_, 4096); this->setg (this->buffer_, this->buffer_, this->buffer_ + r); } return this->gptr () == this->egptr () ? std::char_traits<char>::eof () : std::char_traits<char>::to_int_type (*this->gptr ()); } }; } // namespace dump extern "C" { int elektraDumpGet (ckdb::Plugin *, ckdb::KeySet * returned, ckdb::Key * parentKey) { Key * root = ckdb::keyNew ("system/elektra/modules/dump", KEY_END); if (keyRel (root, parentKey) >= 0) { keyDel (root); KeySet * n = ksNew (50, keyNew ("system/elektra/modules/dump", KEY_VALUE, "dump plugin waits for your orders", KEY_END), keyNew ("system/elektra/modules/dump/exports", KEY_END), keyNew ("system/elektra/modules/dump/exports/get", KEY_FUNC, elektraDumpGet, KEY_END), keyNew ("system/elektra/modules/dump/exports/set", KEY_FUNC, elektraDumpSet, KEY_END), keyNew ("system/elektra/modules/dump/exports/serialise", KEY_FUNC, dump::serialise, KEY_END), keyNew ("system/elektra/modules/dump/exports/unserialise", KEY_FUNC, dump::unserialise, KEY_END), keyNew ("system/elektra/modules/dump/config/needs/fcrypt/textmode", KEY_VALUE, "0", KEY_END), #include "readme_dump.c" keyNew ("system/elektra/modules/dump/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END); ksAppend (returned, n); ksDel (n); return 1; } keyDel (root); int errnosave = errno; // We use dump for the pluginprocess library. Unfortunately on macOS reading from /dev/fd/<fd> via // ifstream fails, thus we read directly from unnamed pipes using a custom buffer and read const char pipe[] = "/dev/fd/"; if (!strncmp (keyString (parentKey), pipe, strlen (pipe))) { int fd = std::stoi (std::string (keyString (parentKey) + strlen (pipe))); dump::pipebuf pipebuf (fd); std::istream is (&pipebuf); return dump::unserialise (is, parentKey, returned); } else { // ELEKTRA_LOG (ELEKTRA_LOG_MODULE_DUMP, "opening file %s", keyString (parentKey)); std::ifstream is (keyString (parentKey), std::ios::binary); if (!is.is_open ()) { ELEKTRA_SET_ERROR_GET (parentKey); errno = errnosave; return -1; } return dump::unserialise (is, parentKey, returned); } } int elektraDumpSet (ckdb::Plugin *, ckdb::KeySet * returned, ckdb::Key * parentKey) { int errnosave = errno; // ELEKTRA_LOG (ELEKTRA_LOG_MODULE_DUMP, "opening file %s", keyString (parentKey)); std::ofstream ofs (keyString (parentKey), std::ios::binary); if (!ofs.is_open ()) { ELEKTRA_SET_ERROR_SET (parentKey); errno = errnosave; return -1; } return dump::serialise (ofs, parentKey, returned); } ckdb::Plugin * ELEKTRA_PLUGIN_EXPORT (dump) { // clang-format off return elektraPluginExport("dump", ELEKTRA_PLUGIN_GET, &elektraDumpGet, ELEKTRA_PLUGIN_SET, &elektraDumpSet, ELEKTRA_PLUGIN_END); } } // extern C <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkPropertyManager.h" #include "mitkProperties.h" #include <limits> mitk::PropertyManager::PropertyManager() { m_DefaultPropertyNameSet.insert(std::string("visible")); m_PropertyLimits.insert(std::make_pair("opacity",std::make_pair(0.0f,1.0f))); } mitk::PropertyManager* mitk::PropertyManager::GetInstance() { static mitk::PropertyManager propManager; return &propManager; } const mitk::PropertyManager::PropertyNameSet& mitk::PropertyManager::GetDefaultPropertyNames() { return m_DefaultPropertyNameSet; }; mitk::BaseProperty::Pointer mitk::PropertyManager::CreateDefaultProperty(std::string name) { mitk::BaseProperty::Pointer newProperty(NULL); if ( name == "visible" ) { newProperty = new mitk::BoolProperty(true); } else { std::cout << "Warning: non-existing default property requested: " << name << std::endl; } return newProperty; } bool mitk::PropertyManager::GetDefaultLimits(const std::string &name,std::pair<float,float> &minMax) { PropertyLimitsMap::iterator it = m_PropertyLimits.find(name.c_str()); if (it != m_PropertyLimits.end()) { minMax = it->second; return true; } else { minMax = std::make_pair(std::numeric_limits<float>::min(),std::numeric_limits<float>::max()); return false; } } <commit_msg>remove debug code<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkPropertyManager.h" #include "mitkProperties.h" #include <limits> mitk::PropertyManager::PropertyManager() { m_DefaultPropertyNameSet.insert(std::string("visible")); m_PropertyLimits.insert(std::make_pair("opacity",std::make_pair(0.0f,1.0f))); } mitk::PropertyManager* mitk::PropertyManager::GetInstance() { static mitk::PropertyManager propManager; return &propManager; } const mitk::PropertyManager::PropertyNameSet& mitk::PropertyManager::GetDefaultPropertyNames() { return m_DefaultPropertyNameSet; }; mitk::BaseProperty::Pointer mitk::PropertyManager::CreateDefaultProperty(std::string name) { mitk::BaseProperty::Pointer newProperty(NULL); if ( name == "visible" ) { newProperty = new mitk::BoolProperty(true); } else { //std::cout << "Warning: non-existing default property requested: " << name << std::endl; } return newProperty; } bool mitk::PropertyManager::GetDefaultLimits(const std::string &name,std::pair<float,float> &minMax) { PropertyLimitsMap::iterator it = m_PropertyLimits.find(name.c_str()); if (it != m_PropertyLimits.end()) { minMax = it->second; return true; } else { minMax = std::make_pair(std::numeric_limits<float>::min(),std::numeric_limits<float>::max()); return false; } } <|endoftext|>
<commit_before>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2010 Emmanuel Benazera, ebenazer@seeks-project.info * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "user_db_fix.h" #include "user_db.h" #include "plugin_manager.h" #include "plugin.h" #include "db_query_record.h" // XXX: for fixing issue 169. Will disappear afterwards. using seeks_plugins::db_query_record; #include "errlog.h" #include "db_obj.h" #include <stdlib.h> #include <stdbool.h> #include <stdint.h> #include <unistd.h> #include <stdio.h> #include <assert.h> #include <iostream> namespace sp { int user_db_fix::fix_issue_169() { /** * What we need to do: * - create a new db. * - iterate records of the existing user db. * - transfer non affected records (from uri-capture plugin) to new db with no change. * - fix and transfer affected records (from query-capture plugin) to new db. * - replace existing db with new db. */ user_db udb; // existing user db. int err = udb.open_db_readonly(); if (err != 0) { // handle error. errlog::log_error(LOG_LEVEL_ERROR,"Could not open the user db for fixing it"); return -1; } user_db cudb("seeks_user.db.tmp"); // new db to be filled up. err = cudb.open_db(); if (err != 0) { // handle error. errlog::log_error(LOG_LEVEL_ERROR,"Could not create the temporary db for fixing the user db"); udb.close_db(); } /* traverse records */ void *rkey = NULL; void *value = NULL; int rkey_size; udb._hdb->dbiterinit(); while ((rkey = udb._hdb->dbiternext(&rkey_size)) != NULL) { int value_size; value = udb._hdb->dbget(rkey, rkey_size, &value_size); if (value) { std::string str = std::string((char*)value,value_size); free(value); std::string key, plugin_name; if (user_db::extract_plugin_and_key(std::string((char*)rkey), plugin_name,key) != 0) { //errlog::log_error(LOG_LEVEL_ERROR,"Could not extract record plugin and key from internal user db key"); } else { // get a proper object based on plugin name, and call the virtual function for reading the record. plugin *pl = plugin_manager::get_plugin(plugin_name); if (!pl) { errlog::log_error(LOG_LEVEL_ERROR,"Could not find plugin %s for fixing user db record", plugin_name.c_str()); } else { // call to plugin record creation function. db_record *dbr = pl->create_db_record(); if (dbr->deserialize(str) != 0) // here we check deserialization even if the record needs not be fixed. { } else { // only records by 'query-capture' plugin are affected. if (dbr->_plugin_name != "query-capture") { cudb.add_dbr(key,*dbr); // add record to new db as is. } else { // fix query-capture record. db_query_record *dqr = static_cast<db_query_record*>(dbr); dqr->fix_issue_169(cudb); } delete dbr; } } } } free(rkey); } // check that we have at least the same number of records in both db. bool replace = false; if (udb.number_records() == cudb.number_records()) { replace = true; errlog::log_error(LOG_LEVEL_INFO,"user db appears to have been fixed correctly!"); } else errlog::log_error(LOG_LEVEL_ERROR,"Failed fixing the user db"); // replace current user db with the new (fixed) one. if (replace) { unlink(udb._hdb->get_name().c_str()); // erase current db. if (rename(cudb._hdb->get_name().c_str(),udb._hdb->get_name().c_str()) < 0) { errlog::log_error(LOG_LEVEL_ERROR,"failed renaming fixed user db"); } } else unlink(cudb._hdb->get_name().c_str()); // erase temporary db. return err; } int user_db_fix::fix_issue_263() { user_db udb; // existing user db. int err = udb.open_db(); if (err != 0) { // handle error. errlog::log_error(LOG_LEVEL_ERROR,"Could not open the user db for fixing it"); return -1; } // traverse records. size_t frec = 0; std::map<std::string,db_record*> to_add; void *rkey = NULL; int rkey_size; std::vector<std::string> to_remove; udb._hdb->dbiterinit(); while ((rkey = udb._hdb->dbiternext(&rkey_size)) != NULL) { int value_size; void *value = udb._hdb->dbget(rkey, rkey_size, &value_size); if (value) { std::string str = std::string((char*)value,value_size); free(value); std::string key, plugin_name; std::string rkey_str = std::string((char*)rkey); if (rkey_str != user_db::_db_version_key && user_db::extract_plugin_and_key(rkey_str, plugin_name,key) != 0) { errlog::log_error(LOG_LEVEL_ERROR,"Fix 263: could not extract record plugin and key from internal user db key"); } else if (plugin_name != "query-capture") { } else if (rkey_str != user_db::_db_version_key) { // get a proper object based on plugin name, and call the virtual function for reading the record. plugin *pl = plugin_manager::get_plugin(plugin_name); db_record *dbr = NULL; if (!pl) { // handle error. errlog::log_error(LOG_LEVEL_ERROR,"Fix 263: could not find plugin %s for pruning user db record", plugin_name.c_str()); dbr = new db_record(); } else { dbr = pl->create_db_record(); } if (dbr->deserialize(str) != 0) { // deserialization error. } else { int f = static_cast<db_query_record*>(dbr)->fix_issue_263(); if (f != 0) { frec++; udb.remove_dbr(rkey_str); udb.add_dbr(key,*dbr); } } delete dbr; } } free(rkey); } udb.close_db(); errlog::log_error(LOG_LEVEL_INFO,"Fix 263: fixed %u records in user db",frec); return err; } int user_db_fix::fix_issue_281() { user_db udb; // existing user db. int err = udb.open_db(); if (err != 0) { // handle error. errlog::log_error(LOG_LEVEL_ERROR,"Could not open the user db for fixing it"); return -1; } // traverse records. size_t frec = 0; size_t fque = 0; size_t furls = 0; std::map<std::string,db_record*> to_add; void *rkey = NULL; int rkey_size; std::vector<std::string> to_remove; udb._hdb->dbiterinit(); while ((rkey = udb._hdb->dbiternext(&rkey_size)) != NULL) { int value_size; void *value = udb._hdb->dbget(rkey, rkey_size, &value_size); if (value) { std::string str = std::string((char*)value,value_size); free(value); std::string key, plugin_name; std::string rkey_str = std::string((char*)rkey); if (rkey_str != user_db::_db_version_key && user_db::extract_plugin_and_key(rkey_str, plugin_name,key) != 0) { errlog::log_error(LOG_LEVEL_ERROR,"Fix 281: could not extract record plugin and key from internal user db key"); } else if (plugin_name != "query-capture") { } else if (rkey_str != user_db::_db_version_key) { // get a proper object based on plugin name, and call the virtual function for reading the record. plugin *pl = plugin_manager::get_plugin(plugin_name); db_record *dbr = NULL; if (!pl) { // handle error. errlog::log_error(LOG_LEVEL_ERROR,"Fix 281: could not find plugin %s for pruning user db record", plugin_name.c_str()); dbr = new db_record(); } else { dbr = pl->create_db_record(); } if (dbr->deserialize(str) != 0) { // deserialization error. } else { uint32_t fu = 0; int f = static_cast<db_query_record*>(dbr)->fix_issue_281(fu); if (f != 0) { furls += fu; fque += f; frec++; udb.remove_dbr(rkey_str); udb.add_dbr(key,*dbr); } } delete dbr; } } free(rkey); } udb.close_db(); errlog::log_error(LOG_LEVEL_INFO,"Fix 281: fixed %u records in user db, %u queries fixed, %u urls fixed", frec,fque,furls); return err; } } /* end of namespace. */ <commit_msg>fixed catching of tmp db creation error on fix 169<commit_after>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2010 Emmanuel Benazera, ebenazer@seeks-project.info * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "user_db_fix.h" #include "user_db.h" #include "plugin_manager.h" #include "plugin.h" #include "db_query_record.h" // XXX: for fixing issue 169. Will disappear afterwards. using seeks_plugins::db_query_record; #include "errlog.h" #include "db_obj.h" #include <stdlib.h> #include <stdbool.h> #include <stdint.h> #include <unistd.h> #include <stdio.h> #include <assert.h> #include <iostream> namespace sp { int user_db_fix::fix_issue_169() { /** * What we need to do: * - create a new db. * - iterate records of the existing user db. * - transfer non affected records (from uri-capture plugin) to new db with no change. * - fix and transfer affected records (from query-capture plugin) to new db. * - replace existing db with new db. */ user_db udb; // existing user db. int err = udb.open_db_readonly(); if (err != 0) { // handle error. errlog::log_error(LOG_LEVEL_ERROR,"Could not open the user db for fixing it"); return -1; } user_db cudb("seeks_user.db.tmp"); // new db to be filled up. err = cudb.open_db(); if (err != 0) { // handle error. errlog::log_error(LOG_LEVEL_ERROR,"Could not create the temporary db for fixing the user db"); udb.close_db(); return -1; } /* traverse records */ void *rkey = NULL; void *value = NULL; int rkey_size; udb._hdb->dbiterinit(); while ((rkey = udb._hdb->dbiternext(&rkey_size)) != NULL) { int value_size; value = udb._hdb->dbget(rkey, rkey_size, &value_size); if (value) { std::string str = std::string((char*)value,value_size); free(value); std::string key, plugin_name; if (user_db::extract_plugin_and_key(std::string((char*)rkey), plugin_name,key) != 0) { //errlog::log_error(LOG_LEVEL_ERROR,"Could not extract record plugin and key from internal user db key"); } else { // get a proper object based on plugin name, and call the virtual function for reading the record. plugin *pl = plugin_manager::get_plugin(plugin_name); if (!pl) { errlog::log_error(LOG_LEVEL_ERROR,"Could not find plugin %s for fixing user db record", plugin_name.c_str()); } else { // call to plugin record creation function. db_record *dbr = pl->create_db_record(); if (dbr->deserialize(str) != 0) // here we check deserialization even if the record needs not be fixed. { } else { // only records by 'query-capture' plugin are affected. if (dbr->_plugin_name != "query-capture") { cudb.add_dbr(key,*dbr); // add record to new db as is. } else { // fix query-capture record. db_query_record *dqr = static_cast<db_query_record*>(dbr); dqr->fix_issue_169(cudb); } delete dbr; } } } } free(rkey); } // check that we have at least the same number of records in both db. bool replace = false; if (udb.number_records() == cudb.number_records()) { replace = true; errlog::log_error(LOG_LEVEL_INFO,"user db appears to have been fixed correctly!"); } else errlog::log_error(LOG_LEVEL_ERROR,"Failed fixing the user db"); // replace current user db with the new (fixed) one. if (replace) { unlink(udb._hdb->get_name().c_str()); // erase current db. if (rename(cudb._hdb->get_name().c_str(),udb._hdb->get_name().c_str()) < 0) { errlog::log_error(LOG_LEVEL_ERROR,"failed renaming fixed user db"); } } else unlink(cudb._hdb->get_name().c_str()); // erase temporary db. return err; } int user_db_fix::fix_issue_263() { user_db udb; // existing user db. int err = udb.open_db(); if (err != 0) { // handle error. errlog::log_error(LOG_LEVEL_ERROR,"Could not open the user db for fixing it"); return -1; } // traverse records. size_t frec = 0; std::map<std::string,db_record*> to_add; void *rkey = NULL; int rkey_size; std::vector<std::string> to_remove; udb._hdb->dbiterinit(); while ((rkey = udb._hdb->dbiternext(&rkey_size)) != NULL) { int value_size; void *value = udb._hdb->dbget(rkey, rkey_size, &value_size); if (value) { std::string str = std::string((char*)value,value_size); free(value); std::string key, plugin_name; std::string rkey_str = std::string((char*)rkey); if (rkey_str != user_db::_db_version_key && user_db::extract_plugin_and_key(rkey_str, plugin_name,key) != 0) { errlog::log_error(LOG_LEVEL_ERROR,"Fix 263: could not extract record plugin and key from internal user db key"); } else if (plugin_name != "query-capture") { } else if (rkey_str != user_db::_db_version_key) { // get a proper object based on plugin name, and call the virtual function for reading the record. plugin *pl = plugin_manager::get_plugin(plugin_name); db_record *dbr = NULL; if (!pl) { // handle error. errlog::log_error(LOG_LEVEL_ERROR,"Fix 263: could not find plugin %s for pruning user db record", plugin_name.c_str()); dbr = new db_record(); } else { dbr = pl->create_db_record(); } if (dbr->deserialize(str) != 0) { // deserialization error. } else { int f = static_cast<db_query_record*>(dbr)->fix_issue_263(); if (f != 0) { frec++; udb.remove_dbr(rkey_str); udb.add_dbr(key,*dbr); } } delete dbr; } } free(rkey); } udb.close_db(); errlog::log_error(LOG_LEVEL_INFO,"Fix 263: fixed %u records in user db",frec); return err; } int user_db_fix::fix_issue_281() { user_db udb; // existing user db. int err = udb.open_db(); if (err != 0) { // handle error. errlog::log_error(LOG_LEVEL_ERROR,"Could not open the user db for fixing it"); return -1; } // traverse records. size_t frec = 0; size_t fque = 0; size_t furls = 0; std::map<std::string,db_record*> to_add; void *rkey = NULL; int rkey_size; std::vector<std::string> to_remove; udb._hdb->dbiterinit(); while ((rkey = udb._hdb->dbiternext(&rkey_size)) != NULL) { int value_size; void *value = udb._hdb->dbget(rkey, rkey_size, &value_size); if (value) { std::string str = std::string((char*)value,value_size); free(value); std::string key, plugin_name; std::string rkey_str = std::string((char*)rkey); if (rkey_str != user_db::_db_version_key && user_db::extract_plugin_and_key(rkey_str, plugin_name,key) != 0) { errlog::log_error(LOG_LEVEL_ERROR,"Fix 281: could not extract record plugin and key from internal user db key"); } else if (plugin_name != "query-capture") { } else if (rkey_str != user_db::_db_version_key) { // get a proper object based on plugin name, and call the virtual function for reading the record. plugin *pl = plugin_manager::get_plugin(plugin_name); db_record *dbr = NULL; if (!pl) { // handle error. errlog::log_error(LOG_LEVEL_ERROR,"Fix 281: could not find plugin %s for pruning user db record", plugin_name.c_str()); dbr = new db_record(); } else { dbr = pl->create_db_record(); } if (dbr->deserialize(str) != 0) { // deserialization error. } else { uint32_t fu = 0; int f = static_cast<db_query_record*>(dbr)->fix_issue_281(fu); if (f != 0) { furls += fu; fque += f; frec++; udb.remove_dbr(rkey_str); udb.add_dbr(key,*dbr); } } delete dbr; } } free(rkey); } udb.close_db(); errlog::log_error(LOG_LEVEL_INFO,"Fix 281: fixed %u records in user db, %u queries fixed, %u urls fixed", frec,fque,furls); return err; } } /* end of namespace. */ <|endoftext|>
<commit_before>#include "eoPruning.h" eoPruning::eoPruning() { file_path = "eoPruning.datat"; EdgeOrientation edgeOrientation; edgeOrientation.buildTransitionTable(); vector<vector<long long>> transition_table = edgeOrientation.getTransitionTable(); buildPruneTable(transition_table, edgeOrientation.get_state_count()); } int eoPruning::pruning_number(Cube &cube) { return prune_table[cube.getEoState()]; } <commit_msg>Fix wrong filename<commit_after>#include "eoPruning.h" eoPruning::eoPruning() { file_path = "eoPruning.data"; EdgeOrientation edgeOrientation; edgeOrientation.buildTransitionTable(); vector<vector<long long>> transition_table = edgeOrientation.getTransitionTable(); buildPruneTable(transition_table, edgeOrientation.get_state_count()); } int eoPruning::pruning_number(Cube &cube) { return prune_table[cube.getEoState()]; } <|endoftext|>